text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/assert.h"
#include "platform/utils.h"
#include "vm/unit_test.h"
namespace dart {
UNIT_TEST_CASE(Minimum) {
EXPECT_EQ(0, Utils::Minimum(0, 1));
EXPECT_EQ(0, Utils::Minimum(1, 0));
EXPECT_EQ(1, Utils::Minimum(1, 2));
EXPECT_EQ(1, Utils::Minimum(2, 1));
EXPECT_EQ(-1, Utils::Minimum(-1, 1));
EXPECT_EQ(-1, Utils::Minimum(1, -1));
EXPECT_EQ(-2, Utils::Minimum(-1, -2));
EXPECT_EQ(-2, Utils::Minimum(-2, -1));
}
UNIT_TEST_CASE(Maximum) {
EXPECT_EQ(1, Utils::Maximum(0, 1));
EXPECT_EQ(1, Utils::Maximum(1, 0));
EXPECT_EQ(2, Utils::Maximum(1, 2));
EXPECT_EQ(2, Utils::Maximum(2, 1));
EXPECT_EQ(1, Utils::Maximum(-1, 1));
EXPECT_EQ(1, Utils::Maximum(1, -1));
EXPECT_EQ(-1, Utils::Maximum(-1, -2));
EXPECT_EQ(-1, Utils::Maximum(-2, -1));
}
UNIT_TEST_CASE(IsPowerOfTwo) {
EXPECT(!Utils::IsPowerOfTwo(0));
EXPECT(Utils::IsPowerOfTwo(1));
EXPECT(Utils::IsPowerOfTwo(2));
EXPECT(!Utils::IsPowerOfTwo(3));
EXPECT(Utils::IsPowerOfTwo(4));
EXPECT(Utils::IsPowerOfTwo(256));
EXPECT(!Utils::IsPowerOfTwo(-1));
EXPECT(!Utils::IsPowerOfTwo(-2));
}
UNIT_TEST_CASE(ShiftForPowerOfTwo) {
EXPECT_EQ(1, Utils::ShiftForPowerOfTwo(2));
EXPECT_EQ(2, Utils::ShiftForPowerOfTwo(4));
EXPECT_EQ(8, Utils::ShiftForPowerOfTwo(256));
}
UNIT_TEST_CASE(IsAligned) {
EXPECT(Utils::IsAligned(0, 1));
EXPECT(Utils::IsAligned(1, 1));
EXPECT(Utils::IsAligned(0, 2));
EXPECT(!Utils::IsAligned(1, 2));
EXPECT(Utils::IsAligned(2, 2));
EXPECT(Utils::IsAligned(32, 8));
EXPECT(!Utils::IsAligned(33, 8));
EXPECT(Utils::IsAligned(40, 8));
}
UNIT_TEST_CASE(RoundDown) {
EXPECT_EQ(0, Utils::RoundDown(22, 32));
EXPECT_EQ(32, Utils::RoundDown(33, 32));
EXPECT_EQ(32, Utils::RoundDown(63, 32));
uword* address = reinterpret_cast<uword*>(63);
uword* rounddown_address = reinterpret_cast<uword*>(32);
EXPECT_EQ(rounddown_address, Utils::RoundDown(address, 32));
}
UNIT_TEST_CASE(RoundUp) {
EXPECT_EQ(32, Utils::RoundUp(22, 32));
EXPECT_EQ(64, Utils::RoundUp(33, 32));
EXPECT_EQ(64, Utils::RoundUp(63, 32));
uword* address = reinterpret_cast<uword*>(63);
uword* roundup_address = reinterpret_cast<uword*>(64);
EXPECT_EQ(roundup_address, Utils::RoundUp(address, 32));
}
UNIT_TEST_CASE(RoundUpToPowerOfTwo) {
EXPECT_EQ(0U, Utils::RoundUpToPowerOfTwo(0));
EXPECT_EQ(1U, Utils::RoundUpToPowerOfTwo(1));
EXPECT_EQ(2U, Utils::RoundUpToPowerOfTwo(2));
EXPECT_EQ(4U, Utils::RoundUpToPowerOfTwo(3));
EXPECT_EQ(4U, Utils::RoundUpToPowerOfTwo(4));
EXPECT_EQ(8U, Utils::RoundUpToPowerOfTwo(5));
EXPECT_EQ(8U, Utils::RoundUpToPowerOfTwo(7));
EXPECT_EQ(16U, Utils::RoundUpToPowerOfTwo(9));
EXPECT_EQ(16U, Utils::RoundUpToPowerOfTwo(16));
EXPECT_EQ(0x10000000U, Utils::RoundUpToPowerOfTwo(0x08765432));
}
UNIT_TEST_CASE(CountOneBits) {
EXPECT_EQ(0, Utils::CountOneBits(0));
EXPECT_EQ(1, Utils::CountOneBits(0x00000010));
EXPECT_EQ(1, Utils::CountOneBits(0x00010000));
EXPECT_EQ(1, Utils::CountOneBits(0x10000000));
EXPECT_EQ(4, Utils::CountOneBits(0x10101010));
EXPECT_EQ(8, Utils::CountOneBits(0x03030303));
EXPECT_EQ(32, Utils::CountOneBits(0xFFFFFFFF));
}
UNIT_TEST_CASE(CountZeros) {
EXPECT_EQ(0, Utils::CountTrailingZeros(0x1));
EXPECT_EQ(kBitsPerWord - 1, Utils::CountLeadingZeros(0x1));
EXPECT_EQ(1, Utils::CountTrailingZeros(0x2));
EXPECT_EQ(kBitsPerWord - 2, Utils::CountLeadingZeros(0x2));
EXPECT_EQ(0, Utils::CountTrailingZeros(0x3));
EXPECT_EQ(kBitsPerWord - 2, Utils::CountLeadingZeros(0x3));
EXPECT_EQ(2, Utils::CountTrailingZeros(0x4));
EXPECT_EQ(kBitsPerWord - 2, Utils::CountLeadingZeros(0x4));
EXPECT_EQ(0, Utils::CountTrailingZeros(kUwordMax));
EXPECT_EQ(0, Utils::CountLeadingZeros(kUwordMax));
static const uword kTopBit = static_cast<uword>(1) << (kBitsPerWord - 1);
EXPECT_EQ(kBitsPerWord - 1, Utils::CountTrailingZeros(kTopBit));
EXPECT_EQ(0, Utils::CountLeadingZeros(kTopBit));
}
UNIT_TEST_CASE(IsInt) {
EXPECT(Utils::IsInt(8, 16));
EXPECT(Utils::IsInt(8, 127));
EXPECT(Utils::IsInt(8, -128));
EXPECT(!Utils::IsInt(8, 255));
EXPECT(Utils::IsInt(16, 16));
EXPECT(!Utils::IsInt(16, 65535));
EXPECT(Utils::IsInt(16, 32767));
EXPECT(Utils::IsInt(16, -32768));
EXPECT(Utils::IsInt(32, 16LL));
EXPECT(Utils::IsInt(32, 2147483647LL));
EXPECT(Utils::IsInt(32, -2147483648LL));
EXPECT(!Utils::IsInt(32, 4294967295LL));
}
UNIT_TEST_CASE(IsUint) {
EXPECT(Utils::IsUint(8, 16));
EXPECT(Utils::IsUint(8, 0));
EXPECT(Utils::IsUint(8, 255));
EXPECT(!Utils::IsUint(8, 256));
EXPECT(Utils::IsUint(16, 16));
EXPECT(Utils::IsUint(16, 0));
EXPECT(Utils::IsUint(16, 65535));
EXPECT(!Utils::IsUint(16, 65536));
EXPECT(Utils::IsUint(32, 16LL));
EXPECT(Utils::IsUint(32, 0LL));
EXPECT(Utils::IsUint(32, 4294967295LL));
EXPECT(!Utils::IsUint(32, 4294967296LL));
}
UNIT_TEST_CASE(IsAbsoluteUint) {
EXPECT(Utils::IsAbsoluteUint(8, 16));
EXPECT(Utils::IsAbsoluteUint(8, 0));
EXPECT(Utils::IsAbsoluteUint(8, -128));
EXPECT(Utils::IsAbsoluteUint(8, 255));
EXPECT(!Utils::IsAbsoluteUint(8, 256));
EXPECT(Utils::IsAbsoluteUint(16, 16));
EXPECT(Utils::IsAbsoluteUint(16, 0));
EXPECT(Utils::IsAbsoluteUint(16, 65535));
EXPECT(Utils::IsAbsoluteUint(16, -32768));
EXPECT(!Utils::IsAbsoluteUint(16, 65536));
EXPECT(Utils::IsAbsoluteUint(32, 16LL));
EXPECT(Utils::IsAbsoluteUint(32, 0LL));
EXPECT(Utils::IsAbsoluteUint(32, -2147483648LL));
EXPECT(Utils::IsAbsoluteUint(32, 4294967295LL));
EXPECT(!Utils::IsAbsoluteUint(32, 4294967296LL));
}
UNIT_TEST_CASE(LowBits) {
EXPECT_EQ(0xff00, Utils::Low16Bits(0xffff00));
EXPECT_EQ(0xff, Utils::High16Bits(0xffff00));
EXPECT_EQ(0xff00, Utils::Low32Bits(0xff0000ff00LL));
EXPECT_EQ(0xff, Utils::High32Bits(0xff0000ff00LL));
EXPECT_EQ(0x00ff0000ff00LL, Utils::LowHighTo64Bits(0xff00, 0x00ff));
}
UNIT_TEST_CASE(Endianity) {
uint16_t value16be = Utils::HostToBigEndian16(0xf1);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value16be)[0]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value16be)[1]);
uint16_t value16le = Utils::HostToLittleEndian16(0xf1);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value16le)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value16le)[1]);
uint32_t value32be = Utils::HostToBigEndian32(0xf1f2);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32be)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32be)[1]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value32be)[2]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value32be)[3]);
uint32_t value32le = Utils::HostToLittleEndian32(0xf1f2);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value32le)[0]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value32le)[1]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32le)[2]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32le)[3]);
uint64_t value64be = Utils::HostToBigEndian64(0xf1f2f3f4);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[1]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[2]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[3]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value64be)[4]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value64be)[5]);
EXPECT_EQ(0xf3, reinterpret_cast<uint8_t*>(&value64be)[6]);
EXPECT_EQ(0xf4, reinterpret_cast<uint8_t*>(&value64be)[7]);
uint64_t value64le = Utils::HostToLittleEndian64(0xf1f2f3f4);
EXPECT_EQ(0xf4, reinterpret_cast<uint8_t*>(&value64le)[0]);
EXPECT_EQ(0xf3, reinterpret_cast<uint8_t*>(&value64le)[1]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value64le)[2]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value64le)[3]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[4]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[5]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[6]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[7]);
}
UNIT_TEST_CASE(DoublesBitEqual) {
EXPECT(Utils::DoublesBitEqual(1.0, 1.0));
EXPECT(!Utils::DoublesBitEqual(1.0, -1.0));
EXPECT(Utils::DoublesBitEqual(0.0, 0.0));
EXPECT(!Utils::DoublesBitEqual(0.0, -0.0));
EXPECT(Utils::DoublesBitEqual(NAN, NAN));
}
} // namespace dart
<commit_msg>Fix typo in unit test.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/assert.h"
#include "platform/utils.h"
#include "vm/unit_test.h"
namespace dart {
UNIT_TEST_CASE(Minimum) {
EXPECT_EQ(0, Utils::Minimum(0, 1));
EXPECT_EQ(0, Utils::Minimum(1, 0));
EXPECT_EQ(1, Utils::Minimum(1, 2));
EXPECT_EQ(1, Utils::Minimum(2, 1));
EXPECT_EQ(-1, Utils::Minimum(-1, 1));
EXPECT_EQ(-1, Utils::Minimum(1, -1));
EXPECT_EQ(-2, Utils::Minimum(-1, -2));
EXPECT_EQ(-2, Utils::Minimum(-2, -1));
}
UNIT_TEST_CASE(Maximum) {
EXPECT_EQ(1, Utils::Maximum(0, 1));
EXPECT_EQ(1, Utils::Maximum(1, 0));
EXPECT_EQ(2, Utils::Maximum(1, 2));
EXPECT_EQ(2, Utils::Maximum(2, 1));
EXPECT_EQ(1, Utils::Maximum(-1, 1));
EXPECT_EQ(1, Utils::Maximum(1, -1));
EXPECT_EQ(-1, Utils::Maximum(-1, -2));
EXPECT_EQ(-1, Utils::Maximum(-2, -1));
}
UNIT_TEST_CASE(IsPowerOfTwo) {
EXPECT(!Utils::IsPowerOfTwo(0));
EXPECT(Utils::IsPowerOfTwo(1));
EXPECT(Utils::IsPowerOfTwo(2));
EXPECT(!Utils::IsPowerOfTwo(3));
EXPECT(Utils::IsPowerOfTwo(4));
EXPECT(Utils::IsPowerOfTwo(256));
EXPECT(!Utils::IsPowerOfTwo(-1));
EXPECT(!Utils::IsPowerOfTwo(-2));
}
UNIT_TEST_CASE(ShiftForPowerOfTwo) {
EXPECT_EQ(1, Utils::ShiftForPowerOfTwo(2));
EXPECT_EQ(2, Utils::ShiftForPowerOfTwo(4));
EXPECT_EQ(8, Utils::ShiftForPowerOfTwo(256));
}
UNIT_TEST_CASE(IsAligned) {
EXPECT(Utils::IsAligned(0, 1));
EXPECT(Utils::IsAligned(1, 1));
EXPECT(Utils::IsAligned(0, 2));
EXPECT(!Utils::IsAligned(1, 2));
EXPECT(Utils::IsAligned(2, 2));
EXPECT(Utils::IsAligned(32, 8));
EXPECT(!Utils::IsAligned(33, 8));
EXPECT(Utils::IsAligned(40, 8));
}
UNIT_TEST_CASE(RoundDown) {
EXPECT_EQ(0, Utils::RoundDown(22, 32));
EXPECT_EQ(32, Utils::RoundDown(33, 32));
EXPECT_EQ(32, Utils::RoundDown(63, 32));
uword* address = reinterpret_cast<uword*>(63);
uword* rounddown_address = reinterpret_cast<uword*>(32);
EXPECT_EQ(rounddown_address, Utils::RoundDown(address, 32));
}
UNIT_TEST_CASE(RoundUp) {
EXPECT_EQ(32, Utils::RoundUp(22, 32));
EXPECT_EQ(64, Utils::RoundUp(33, 32));
EXPECT_EQ(64, Utils::RoundUp(63, 32));
uword* address = reinterpret_cast<uword*>(63);
uword* roundup_address = reinterpret_cast<uword*>(64);
EXPECT_EQ(roundup_address, Utils::RoundUp(address, 32));
}
UNIT_TEST_CASE(RoundUpToPowerOfTwo) {
EXPECT_EQ(0U, Utils::RoundUpToPowerOfTwo(0));
EXPECT_EQ(1U, Utils::RoundUpToPowerOfTwo(1));
EXPECT_EQ(2U, Utils::RoundUpToPowerOfTwo(2));
EXPECT_EQ(4U, Utils::RoundUpToPowerOfTwo(3));
EXPECT_EQ(4U, Utils::RoundUpToPowerOfTwo(4));
EXPECT_EQ(8U, Utils::RoundUpToPowerOfTwo(5));
EXPECT_EQ(8U, Utils::RoundUpToPowerOfTwo(7));
EXPECT_EQ(16U, Utils::RoundUpToPowerOfTwo(9));
EXPECT_EQ(16U, Utils::RoundUpToPowerOfTwo(16));
EXPECT_EQ(0x10000000U, Utils::RoundUpToPowerOfTwo(0x08765432));
}
UNIT_TEST_CASE(CountOneBits) {
EXPECT_EQ(0, Utils::CountOneBits(0));
EXPECT_EQ(1, Utils::CountOneBits(0x00000010));
EXPECT_EQ(1, Utils::CountOneBits(0x00010000));
EXPECT_EQ(1, Utils::CountOneBits(0x10000000));
EXPECT_EQ(4, Utils::CountOneBits(0x10101010));
EXPECT_EQ(8, Utils::CountOneBits(0x03030303));
EXPECT_EQ(32, Utils::CountOneBits(0xFFFFFFFF));
}
UNIT_TEST_CASE(CountZeros) {
EXPECT_EQ(0, Utils::CountTrailingZeros(0x1));
EXPECT_EQ(kBitsPerWord - 1, Utils::CountLeadingZeros(0x1));
EXPECT_EQ(1, Utils::CountTrailingZeros(0x2));
EXPECT_EQ(kBitsPerWord - 2, Utils::CountLeadingZeros(0x2));
EXPECT_EQ(0, Utils::CountTrailingZeros(0x3));
EXPECT_EQ(kBitsPerWord - 2, Utils::CountLeadingZeros(0x3));
EXPECT_EQ(2, Utils::CountTrailingZeros(0x4));
EXPECT_EQ(kBitsPerWord - 3, Utils::CountLeadingZeros(0x4));
EXPECT_EQ(0, Utils::CountTrailingZeros(kUwordMax));
EXPECT_EQ(0, Utils::CountLeadingZeros(kUwordMax));
static const uword kTopBit = static_cast<uword>(1) << (kBitsPerWord - 1);
EXPECT_EQ(kBitsPerWord - 1, Utils::CountTrailingZeros(kTopBit));
EXPECT_EQ(0, Utils::CountLeadingZeros(kTopBit));
}
UNIT_TEST_CASE(IsInt) {
EXPECT(Utils::IsInt(8, 16));
EXPECT(Utils::IsInt(8, 127));
EXPECT(Utils::IsInt(8, -128));
EXPECT(!Utils::IsInt(8, 255));
EXPECT(Utils::IsInt(16, 16));
EXPECT(!Utils::IsInt(16, 65535));
EXPECT(Utils::IsInt(16, 32767));
EXPECT(Utils::IsInt(16, -32768));
EXPECT(Utils::IsInt(32, 16LL));
EXPECT(Utils::IsInt(32, 2147483647LL));
EXPECT(Utils::IsInt(32, -2147483648LL));
EXPECT(!Utils::IsInt(32, 4294967295LL));
}
UNIT_TEST_CASE(IsUint) {
EXPECT(Utils::IsUint(8, 16));
EXPECT(Utils::IsUint(8, 0));
EXPECT(Utils::IsUint(8, 255));
EXPECT(!Utils::IsUint(8, 256));
EXPECT(Utils::IsUint(16, 16));
EXPECT(Utils::IsUint(16, 0));
EXPECT(Utils::IsUint(16, 65535));
EXPECT(!Utils::IsUint(16, 65536));
EXPECT(Utils::IsUint(32, 16LL));
EXPECT(Utils::IsUint(32, 0LL));
EXPECT(Utils::IsUint(32, 4294967295LL));
EXPECT(!Utils::IsUint(32, 4294967296LL));
}
UNIT_TEST_CASE(IsAbsoluteUint) {
EXPECT(Utils::IsAbsoluteUint(8, 16));
EXPECT(Utils::IsAbsoluteUint(8, 0));
EXPECT(Utils::IsAbsoluteUint(8, -128));
EXPECT(Utils::IsAbsoluteUint(8, 255));
EXPECT(!Utils::IsAbsoluteUint(8, 256));
EXPECT(Utils::IsAbsoluteUint(16, 16));
EXPECT(Utils::IsAbsoluteUint(16, 0));
EXPECT(Utils::IsAbsoluteUint(16, 65535));
EXPECT(Utils::IsAbsoluteUint(16, -32768));
EXPECT(!Utils::IsAbsoluteUint(16, 65536));
EXPECT(Utils::IsAbsoluteUint(32, 16LL));
EXPECT(Utils::IsAbsoluteUint(32, 0LL));
EXPECT(Utils::IsAbsoluteUint(32, -2147483648LL));
EXPECT(Utils::IsAbsoluteUint(32, 4294967295LL));
EXPECT(!Utils::IsAbsoluteUint(32, 4294967296LL));
}
UNIT_TEST_CASE(LowBits) {
EXPECT_EQ(0xff00, Utils::Low16Bits(0xffff00));
EXPECT_EQ(0xff, Utils::High16Bits(0xffff00));
EXPECT_EQ(0xff00, Utils::Low32Bits(0xff0000ff00LL));
EXPECT_EQ(0xff, Utils::High32Bits(0xff0000ff00LL));
EXPECT_EQ(0x00ff0000ff00LL, Utils::LowHighTo64Bits(0xff00, 0x00ff));
}
UNIT_TEST_CASE(Endianity) {
uint16_t value16be = Utils::HostToBigEndian16(0xf1);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value16be)[0]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value16be)[1]);
uint16_t value16le = Utils::HostToLittleEndian16(0xf1);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value16le)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value16le)[1]);
uint32_t value32be = Utils::HostToBigEndian32(0xf1f2);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32be)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32be)[1]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value32be)[2]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value32be)[3]);
uint32_t value32le = Utils::HostToLittleEndian32(0xf1f2);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value32le)[0]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value32le)[1]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32le)[2]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value32le)[3]);
uint64_t value64be = Utils::HostToBigEndian64(0xf1f2f3f4);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[0]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[1]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[2]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64be)[3]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value64be)[4]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value64be)[5]);
EXPECT_EQ(0xf3, reinterpret_cast<uint8_t*>(&value64be)[6]);
EXPECT_EQ(0xf4, reinterpret_cast<uint8_t*>(&value64be)[7]);
uint64_t value64le = Utils::HostToLittleEndian64(0xf1f2f3f4);
EXPECT_EQ(0xf4, reinterpret_cast<uint8_t*>(&value64le)[0]);
EXPECT_EQ(0xf3, reinterpret_cast<uint8_t*>(&value64le)[1]);
EXPECT_EQ(0xf2, reinterpret_cast<uint8_t*>(&value64le)[2]);
EXPECT_EQ(0xf1, reinterpret_cast<uint8_t*>(&value64le)[3]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[4]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[5]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[6]);
EXPECT_EQ(0x0, reinterpret_cast<uint8_t*>(&value64le)[7]);
}
UNIT_TEST_CASE(DoublesBitEqual) {
EXPECT(Utils::DoublesBitEqual(1.0, 1.0));
EXPECT(!Utils::DoublesBitEqual(1.0, -1.0));
EXPECT(Utils::DoublesBitEqual(0.0, 0.0));
EXPECT(!Utils::DoublesBitEqual(0.0, -0.0));
EXPECT(Utils::DoublesBitEqual(NAN, NAN));
}
} // namespace dart
<|endoftext|> |
<commit_before>#ifndef RADIUMENGINE_TRIANGLEMESH_HPP
#define RADIUMENGINE_TRIANGLEMESH_HPP
#include <Core/RaCore.hpp>
#include <Core/Math/LinearAlgebra.hpp>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Mesh/MeshTypes.hpp>
namespace Ra
{
namespace Core
{
/// A very basic structure representing a triangle mesh which stores the bare minimum :
/// vertices, faces and normals. See MeshUtils for geometric functions operating on a mesh.
struct TriangleMesh
{
/// Create an empty mesh.
inline TriangleMesh() {}
/// Copy constructor and assignment operator
TriangleMesh( const TriangleMesh& ) = default;
TriangleMesh& operator= ( const TriangleMesh& ) = default;
/// Erases all data, making the mesh empty.
inline void clear();
/// Appends another mesh to this one.
inline void append( const TriangleMesh& other );
VectorArray<Vector3> m_vertices;
VectorArray<Vector3> m_normals;
VectorArray<Triangle> m_triangles;
};
}
}
#include <Core/Mesh/TriangleMesh.inl>
#endif //RADIUMENGINE_TRIANGLEMESH_HPP
<commit_msg>Add aligned operator<commit_after>#ifndef RADIUMENGINE_TRIANGLEMESH_HPP
#define RADIUMENGINE_TRIANGLEMESH_HPP
#include <Core/RaCore.hpp>
#include <Core/Math/LinearAlgebra.hpp>
#include <Core/Containers/VectorArray.hpp>
#include <Core/Mesh/MeshTypes.hpp>
namespace Ra
{
namespace Core
{
/// A very basic structure representing a triangle mesh which stores the bare minimum :
/// vertices, faces and normals. See MeshUtils for geometric functions operating on a mesh.
struct TriangleMesh
{
/// Create an empty mesh.
inline TriangleMesh() {}
/// Copy constructor and assignment operator
TriangleMesh( const TriangleMesh& ) = default;
TriangleMesh& operator= ( const TriangleMesh& ) = default;
/// Erases all data, making the mesh empty.
inline void clear();
/// Appends another mesh to this one.
inline void append( const TriangleMesh& other );
VectorArray<Vector3> m_vertices;
VectorArray<Vector3> m_normals;
VectorArray<Triangle> m_triangles;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
}
}
#include <Core/Mesh/TriangleMesh.inl>
#endif //RADIUMENGINE_TRIANGLEMESH_HPP
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macro.hxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _RTL_MACRO_HXX
#define _RTL_MACRO_HXX
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <osl/endian.h>
#if defined WIN32
#define THIS_OS "Windows"
#elif defined OS2
#define THIS_OS "OS/2"
#elif defined SOLARIS
#define THIS_OS "Solaris"
#elif defined LINUX
#define THIS_OS "Linux"
#elif defined MACOSX
#define THIS_OS "MacOSX"
#elif defined NETBSD
#define THIS_OS "NetBSD"
#elif defined FREEBSD
#define THIS_OS "FreeBSD"
#elif defined IRIX
#define THIS_OS "Irix"
#endif
#if ! defined THIS_OS
#error "unknown OS -- insert your OS identifier above"
this is inserted for the case that the preprocessor ignores error
#endif
#if defined INTEL
# define THIS_ARCH "x86"
#elif defined POWERPC64
# define THIS_ARCH "PowerPC_64"
#elif defined POWERPC
# define THIS_ARCH "PowerPC"
#elif defined S390X
# define THIS_ARCH "S390x"
#elif defined S390
# define THIS_ARCH "S390"
#elif defined SPARC
# define THIS_ARCH "SPARC"
#elif defined SPARC64
# define THIS_ARCH "SPARC64"
#elif defined IRIX
# define THIS_ARCH "MIPS"
#elif defined X86_64
# define THIS_ARCH "X86_64"
#elif defined MIPS
# ifdef OSL_BIGENDIAN
# define THIS_ARCH "MIPS_EB"
# else
# define THIS_ARCH "MIPS_EL"
# endif
#elif defined ARM
# ifdef __ARM_EABI__
# define THIS_ARCH "ARM_EABI"
# else
# define THIS_ARCH "ARM_OABI"
# endif
#elif defined IA64
# define THIS_ARCH "IA64"
#elif defined M68K
# define THIS_ARCH "M68K"
#endif
#if ! defined THIS_ARCH
#error "unknown ARCH -- insert your ARCH identifier above"
this is inserted for the case that the preprocessor ignores error
#endif
#endif
<commit_msg>INTEGRATION: CWS os2port03 (1.7.6); FILE MERGED 2008/07/16 12:26:23 obr 1.7.6.3: RESYNC: (1.8-1.14); FILE MERGED 2008/01/15 13:57:41 obr 1.7.6.2: RESYNC: (1.7-1.8); FILE MERGED 2008/01/14 17:01:01 ydario 1.7.6.1: remove slash from macro.hxx, it is used as path separator. Issue number:i85203 Submitted by:ydario<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: macro.hxx,v $
* $Revision: 1.15 $
*
* 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 _RTL_MACRO_HXX
#define _RTL_MACRO_HXX
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <osl/endian.h>
#if defined WIN32
#define THIS_OS "Windows"
#elif defined OS2
#define THIS_OS "OS2"
#elif defined SOLARIS
#define THIS_OS "Solaris"
#elif defined LINUX
#define THIS_OS "Linux"
#elif defined MACOSX
#define THIS_OS "MacOSX"
#elif defined NETBSD
#define THIS_OS "NetBSD"
#elif defined FREEBSD
#define THIS_OS "FreeBSD"
#elif defined IRIX
#define THIS_OS "Irix"
#endif
#if ! defined THIS_OS
#error "unknown OS -- insert your OS identifier above"
this is inserted for the case that the preprocessor ignores error
#endif
#if defined INTEL
# define THIS_ARCH "x86"
#elif defined POWERPC64
# define THIS_ARCH "PowerPC_64"
#elif defined POWERPC
# define THIS_ARCH "PowerPC"
#elif defined S390X
# define THIS_ARCH "S390x"
#elif defined S390
# define THIS_ARCH "S390"
#elif defined SPARC
# define THIS_ARCH "SPARC"
#elif defined SPARC64
# define THIS_ARCH "SPARC64"
#elif defined IRIX
# define THIS_ARCH "MIPS"
#elif defined X86_64
# define THIS_ARCH "X86_64"
#elif defined MIPS
# ifdef OSL_BIGENDIAN
# define THIS_ARCH "MIPS_EB"
# else
# define THIS_ARCH "MIPS_EL"
# endif
#elif defined ARM
# ifdef __ARM_EABI__
# define THIS_ARCH "ARM_EABI"
# else
# define THIS_ARCH "ARM_OABI"
# endif
#elif defined IA64
# define THIS_ARCH "IA64"
#elif defined M68K
# define THIS_ARCH "M68K"
#endif
#if ! defined THIS_ARCH
#error "unknown ARCH -- insert your ARCH identifier above"
this is inserted for the case that the preprocessor ignores error
#endif
#endif
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "MatrixMFD.hh"
#include "MatrixMFD_Factory.hh"
#include "Function.hh"
#include "FunctionFactory.hh"
#include "implicit_snow_distribution_evaluator.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist),
assembled_(false) {
my_key_ = plist_.get<std::string>("precipitation snow field", "precipitation_snow");
// depenedencies
mesh_name_ = plist_.get<std::string>("domain name", "surface");
if (mesh_name_ == "domain") {
cell_vol_key_ = "cell_volume";
} else {
cell_vol_key_ = mesh_name_+std::string("_cell_volume");
}
dependencies_.insert(cell_vol_key_);
elev_key_ = plist_.get<std::string>("elevation key", "elevation");
dependencies_.insert(elev_key_);
slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude");
dependencies_.insert(slope_key_);
pd_key_ = plist_.get<std::string>("ponded depth key", "ponded_depth");
dependencies_.insert(pd_key_);
snow_height_key_ = plist_.get<std::string>("snow height key", "snow_depth");
dependencies_.insert(snow_height_key_);
// constant parameters
kL_ = plist_.get<double>("snow distribution length");
kdx_ = plist_.get<double>("characteristic horizontal grid size", 0.25);
ktmax_ = plist_.get<double>("faux integration time", 86400.);
kS_ = plist_.get<double>("characteristic slope", 1.);
kCFL_ = plist_.get<double>("Courant number", 1.);
kSWE_conv_ = plist_.get<double>("SWE-to-snow conversion ratio", 10.);
tol_ = plist_.get<double>("solver tolerance", 1.e-2);
max_it_ = plist_.get<int>("max iterations", 10);
FunctionFactory fac;
precip_func_ = Teuchos::rcp(fac.Create(plist_.sublist("precipitation function")));
}
ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(const ImplicitSnowDistributionEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
elev_key_(other.elev_key_),
slope_key_(other.slope_key_),
pd_key_(other.pd_key_),
snow_height_key_(other.snow_height_key_),
cell_vol_key_(other.cell_vol_key_),
precip_func_(other.precip_func_),
kL_(other.kL_),
kdx_(other.kdx_),
ktmax_(other.ktmax_),
kS_(other.kS_),
kCFL_(other.kCFL_),
kSWE_conv_(other.kSWE_conv_),
tol_(other.tol_),
max_it_(other.max_it_),
assembled_(other.assembled_),
mesh_name_(other.mesh_name_),
matrix_(other.matrix_) {}
void ImplicitSnowDistributionEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::OSTab tab = vo_->getOSTab();
if (!assembled_) AssembleOperator_(S);
double time = S->time();
double Qe = (*precip_func_)(&time);
double dt_sim = *S->GetScalarData("dt");
// NOTE: snow precip comes in SWE, must convert it to snow depth!
if (Qe * dt_sim * kSWE_conv_ > 0.) {
// determine scaling of flow
const double kV = kL_/ktmax_;
double dt = kCFL_ * kdx_ / kV;
const double kh0 = Qe * ktmax_ * kSWE_conv_;
const double nm = std::pow(kh0, 1./3) * std::sqrt(kS_) / kV;
int nsteps = std::ceil(ktmax_ / dt);
dt = ktmax_ / nsteps;
// scale report
if (vo_->os_OK(Teuchos::VERB_HIGH)) {
*vo_->os() << "Snow Distribution: taking " << nsteps << " steps of size " << dt
<< " s for travel length " << kL_ << " m." << std::endl
<< " L = " << kL_ << std::endl
<< " t_max = " << ktmax_ << std::endl
<< " V = " << kV << std::endl
<< " Q = " << kV*kh0 << std::endl
<< " -------" << std::endl
<< " h0 = " << kh0 << std::endl
<< " nm = " << nm << std::endl
<< " V(man)= " << std::pow(kh0,1./3) * std::sqrt(kS_) / nm << std::endl
<< " -------" << std::endl;
}
// Gather mesh entities
Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_);
int nfaces = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::OWNED);
int ncells = mesh->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
int nfaces_g = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::USED);
// Gather null boundary conditions (no flux of snow into or out of domain)
std::vector<Operators::MatrixBC> bc_markers(nfaces_g, Operators::MATRIX_BC_NULL);
std::vector<double> bc_values(nfaces_g, 0.0);
// Create temporary work space
// -- not necessarily ghosted workspace
Teuchos::RCP<CompositeVector> residual = Teuchos::rcp(new CompositeVector(*result));
Teuchos::RCP<CompositeVector> result_prev = Teuchos::rcp(new CompositeVector(*result));
Teuchos::RCP<CompositeVector> dresult = Teuchos::rcp(new CompositeVector(*result));
// -- necessarily ghosted workspace
CompositeVectorSpace ghosted_space(result->Map());
ghosted_space.SetGhosted();
Teuchos::RCP<CompositeVector> hz = Teuchos::rcp(new CompositeVector(ghosted_space));
Teuchos::RCP<CompositeVector> Krel_c = Teuchos::rcp(new CompositeVector(ghosted_space));
CompositeVectorSpace Krel_f_space;
Krel_f_space.SetMesh(mesh)->SetGhosted()->SetComponent("face",AmanziMesh::FACE,1);
Teuchos::RCP<CompositeVector> Krel_uw = Teuchos::rcp(new CompositeVector(Krel_f_space));
// Gather dependencies
// NOTE: this is incorrect approximation... should be | sqrt( grad( z+h_pd ) ) |
const Epetra_MultiVector& slope = *S->GetFieldData(slope_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& cv = *S->GetFieldData(cell_vol_key_)->ViewComponent("cell",false);
Teuchos::RCP<const CompositeVector> elev = S->GetFieldData(elev_key_);
Teuchos::RCP<const CompositeVector> pd = S->GetFieldData(pd_key_);
Teuchos::RCP<const CompositeVector> snow_height = S->GetFieldData(snow_height_key_);
// initialize and begin timestep loop
result->PutScalar(Qe * ktmax_ * kSWE_conv_);
for (int istep=0; istep!=nsteps; ++istep) {
if (vo_->os_OK(Teuchos::VERB_HIGH))
*vo_->os() << "Snow distribution inner timestep " << istep << " with size " << dt << std::endl
<< " Qe*t_total =" << std::endl;
*result_prev = *result;
double norm0 = 0.;
bool done = false;
int ncycle = 0;
while(!done) {
// update snow potential, z + h_pd + h_s + Qe*dt
*hz = *result;
hz->Update(1., *elev, 1., *pd, 1.);
hz->Update(1., *snow_height, 1.);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " z + h_pd + h_s potential = " << std::endl;
hz->Print(*vo_->os());
}
// update Krel
{
Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",false);
const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false);
for (int c=0; c!=ncells; ++c) {
Krel_c_vec[0][c] = std::pow(std::max(result_c[0][c],0.), 4./3)
/ (std::sqrt(std::max(slope[0][c], 1.e-6)) * nm);
}
}
// communicate and upwind
Krel_c->ScatterMasterToGhosted();
hz->ScatterMasterToGhosted();
{
Epetra_MultiVector& Krel_uw_vec = *Krel_uw->ViewComponent("face",false);
const Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",true);
const Epetra_MultiVector& hz_c = *hz->ViewComponent("cell",true);
for (int f=0; f!=nfaces; ++f) {
AmanziMesh::Entity_ID_List cells;
mesh->face_get_cells(f,AmanziMesh::USED,&cells);
if (cells.size() == 1) {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]];
} else {
if (hz_c[0][cells[0]] > hz_c[0][cells[1]]) {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]];
} else {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[1]];
}
}
}
}
// Re-assemble
Krel_uw->ScatterMasterToGhosted();
matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr());
matrix_->CreateMFDrhsVectors();
matrix_->ApplyBoundaryConditions(bc_markers, bc_values);
matrix_->AssembleGlobalMatrices();
// Apply the operator to get div flux
matrix_->ComputeNegativeResidual(*hz, residual.ptr());
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " DIFFUSION RESIDUAL = " << std::endl;
residual->Print(*vo_->os());
}
// Accumulation
{
Epetra_MultiVector& residual_c = *residual->ViewComponent("cell",false);
const Epetra_MultiVector& result_prev_c = *result_prev->ViewComponent("cell",false);
const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false);
unsigned int ncells = residual_c.MyLength();
for (unsigned int c=0; c!=ncells; ++c) {
residual_c[0][c] += (result_c[0][c] - result_prev_c[0][c]) * cv[0][c] / dt;
}
}
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " ACCUMULATION RESIDUAL = " << std::endl;
residual->Print(*vo_->os());
}
double norm = 0.;
residual->NormInf(&norm);
if (ncycle == 0) norm0 = norm;
ncycle++;
if (vo_->os_OK(Teuchos::VERB_HIGH)) {
*vo_->os() << " inner iterate " << ncycle << " has error norm " << norm << std::endl;
}
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
residual->Print(*vo_->os());
}
if ((norm0 == 0.) || (norm / norm0 < tol_) || (ncycle > max_it_)) {
done = true;
continue;
}
// Apply the preconditioner
matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr());
matrix_->CreateMFDrhsVectors();
matrix_->ApplyBoundaryConditions(bc_markers, bc_values);
{
std::vector<double>& Acc_cells = matrix_->Acc_cells();
unsigned int ncells = Acc_cells.size();
for (unsigned int c=0; c!=ncells; ++c) {
Acc_cells[c] += cv[0][c] / dt;
}
}
matrix_->AssembleGlobalMatrices();
matrix_->ComputeSchurComplement(bc_markers, bc_values);
matrix_->UpdatePreconditioner();
dresult->PutScalar(0.);
matrix_linsolve_->ApplyInverse(*residual, *dresult);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " precon'd update = " << std::endl;
dresult->Print(*vo_->os());
}
// Update
result->Update(-1., *dresult, 1.);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " new snow depth = " << std::endl;
result->Print(*vo_->os());
}
}
}
// get Q back
result->Scale(1./(ktmax_ * kSWE_conv_));
} else {
result->PutScalar(0.);
}
}
// This is hopefully never called?
void ImplicitSnowDistributionEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& results) {
ASSERT(0);
}
void
ImplicitSnowDistributionEvaluator::AssembleOperator_(const Teuchos::Ptr<State>& S) {
Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_);
matrix_ = Operators::CreateMatrixMFD(plist_.sublist("Diffusion"), mesh);
matrix_->set_symmetric(true);
matrix_->SymbolicAssembleGlobalMatrices();
matrix_->CreateMFDmassMatrices(Teuchos::null);
matrix_->InitPreconditioner();
AmanziSolvers::LinearOperatorFactory<CompositeMatrix,CompositeVector,CompositeVectorSpace> fac;
matrix_linsolve_ = fac.Create(plist_.sublist("Diffusion Solver"), matrix_);
}
} //namespace
} //namespace
} //namespace
<commit_msg>tweaks to debugging of snow distribution<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "MatrixMFD.hh"
#include "MatrixMFD_Factory.hh"
#include "Function.hh"
#include "FunctionFactory.hh"
#include "implicit_snow_distribution_evaluator.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist),
assembled_(false) {
my_key_ = plist_.get<std::string>("precipitation snow field", "precipitation_snow");
// depenedencies
mesh_name_ = plist_.get<std::string>("domain name", "surface");
if (mesh_name_ == "domain") {
cell_vol_key_ = "cell_volume";
} else {
cell_vol_key_ = mesh_name_+std::string("_cell_volume");
}
dependencies_.insert(cell_vol_key_);
elev_key_ = plist_.get<std::string>("elevation key", "elevation");
dependencies_.insert(elev_key_);
slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude");
dependencies_.insert(slope_key_);
pd_key_ = plist_.get<std::string>("ponded depth key", "ponded_depth");
dependencies_.insert(pd_key_);
snow_height_key_ = plist_.get<std::string>("snow height key", "snow_depth");
dependencies_.insert(snow_height_key_);
// constant parameters
kL_ = plist_.get<double>("snow distribution length");
kdx_ = plist_.get<double>("characteristic horizontal grid size", 0.25);
ktmax_ = plist_.get<double>("faux integration time", 86400.);
kS_ = plist_.get<double>("characteristic slope", 1.);
kCFL_ = plist_.get<double>("Courant number", 1.);
kSWE_conv_ = plist_.get<double>("SWE-to-snow conversion ratio", 10.);
tol_ = plist_.get<double>("solver tolerance", 1.e-2);
max_it_ = plist_.get<int>("max iterations", 10);
FunctionFactory fac;
precip_func_ = Teuchos::rcp(fac.Create(plist_.sublist("precipitation function")));
}
ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(const ImplicitSnowDistributionEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
elev_key_(other.elev_key_),
slope_key_(other.slope_key_),
pd_key_(other.pd_key_),
snow_height_key_(other.snow_height_key_),
cell_vol_key_(other.cell_vol_key_),
precip_func_(other.precip_func_),
kL_(other.kL_),
kdx_(other.kdx_),
ktmax_(other.ktmax_),
kS_(other.kS_),
kCFL_(other.kCFL_),
kSWE_conv_(other.kSWE_conv_),
tol_(other.tol_),
max_it_(other.max_it_),
assembled_(other.assembled_),
mesh_name_(other.mesh_name_),
matrix_(other.matrix_) {}
void ImplicitSnowDistributionEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::OSTab tab = vo_->getOSTab();
if (!assembled_) AssembleOperator_(S);
double time = S->time();
double Qe = (*precip_func_)(&time);
double dt_sim = *S->GetScalarData("dt");
// NOTE: snow precip comes in SWE, must convert it to snow depth!
if (Qe * dt_sim * kSWE_conv_ > 0.) {
// determine scaling of flow
const double kV = kL_/ktmax_;
double dt = kCFL_ * kdx_ / kV;
const double kh0 = Qe * ktmax_ * kSWE_conv_;
const double nm = std::pow(kh0, 1./3) * std::sqrt(kS_) / kV;
int nsteps = std::ceil(ktmax_ / dt);
dt = ktmax_ / nsteps;
// scale report
if (vo_->os_OK(Teuchos::VERB_MEDIUM)) {
*vo_->os() << "Snow Distribution: taking " << nsteps << " steps of size " << dt
<< " s for travel length " << kL_ << " m." << std::endl
<< " L = " << kL_ << std::endl
<< " t_max = " << ktmax_ << std::endl
<< " V = " << kV << std::endl
<< " Q = " << kV*kh0 << std::endl
<< " -------" << std::endl
<< " h0 = " << kh0 << std::endl
<< " nm = " << nm << std::endl
<< " V(man)= " << std::pow(kh0,1./3) * std::sqrt(kS_) / nm << std::endl
<< " -------" << std::endl;
}
// Gather mesh entities
Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_);
int nfaces = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::OWNED);
int ncells = mesh->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED);
int nfaces_g = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::USED);
// Gather null boundary conditions (no flux of snow into or out of domain)
std::vector<Operators::MatrixBC> bc_markers(nfaces_g, Operators::MATRIX_BC_NULL);
std::vector<double> bc_values(nfaces_g, 0.0);
// Create temporary work space
// -- not necessarily ghosted workspace
Teuchos::RCP<CompositeVector> residual = Teuchos::rcp(new CompositeVector(*result));
Teuchos::RCP<CompositeVector> result_prev = Teuchos::rcp(new CompositeVector(*result));
Teuchos::RCP<CompositeVector> dresult = Teuchos::rcp(new CompositeVector(*result));
// -- necessarily ghosted workspace
CompositeVectorSpace ghosted_space(result->Map());
ghosted_space.SetGhosted();
Teuchos::RCP<CompositeVector> hz = Teuchos::rcp(new CompositeVector(ghosted_space));
Teuchos::RCP<CompositeVector> Krel_c = Teuchos::rcp(new CompositeVector(ghosted_space));
CompositeVectorSpace Krel_f_space;
Krel_f_space.SetMesh(mesh)->SetGhosted()->SetComponent("face",AmanziMesh::FACE,1);
Teuchos::RCP<CompositeVector> Krel_uw = Teuchos::rcp(new CompositeVector(Krel_f_space));
// Gather dependencies
// NOTE: this is incorrect approximation... should be | sqrt( grad( z+h_pd ) ) |
const Epetra_MultiVector& slope = *S->GetFieldData(slope_key_)->ViewComponent("cell",false);
const Epetra_MultiVector& cv = *S->GetFieldData(cell_vol_key_)->ViewComponent("cell",false);
Teuchos::RCP<const CompositeVector> elev = S->GetFieldData(elev_key_);
Teuchos::RCP<const CompositeVector> pd = S->GetFieldData(pd_key_);
Teuchos::RCP<const CompositeVector> snow_height = S->GetFieldData(snow_height_key_);
// initialize and begin timestep loop
result->PutScalar(Qe * ktmax_ * kSWE_conv_);
for (int istep=0; istep!=nsteps; ++istep) {
if (vo_->os_OK(Teuchos::VERB_HIGH))
*vo_->os() << "Snow distribution inner timestep " << istep << " with size " << dt << std::endl
<< " Qe*t_total =" << std::endl;
*result_prev = *result;
double norm0 = 0.;
bool done = false;
int ncycle = 0;
while(!done) {
// update snow potential, z + h_pd + h_s + Qe*dt
*hz = *result;
hz->Update(1., *elev, 1., *pd, 1.);
hz->Update(1., *snow_height, 1.);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " z + h_pd + h_s potential = " << std::endl;
hz->Print(*vo_->os());
}
// update Krel
{
Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",false);
const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false);
for (int c=0; c!=ncells; ++c) {
Krel_c_vec[0][c] = std::pow(std::max(result_c[0][c],0.), 4./3)
/ (std::sqrt(std::max(slope[0][c], 1.e-6)) * nm);
}
}
// communicate and upwind
Krel_c->ScatterMasterToGhosted();
hz->ScatterMasterToGhosted();
{
Epetra_MultiVector& Krel_uw_vec = *Krel_uw->ViewComponent("face",false);
const Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",true);
const Epetra_MultiVector& hz_c = *hz->ViewComponent("cell",true);
for (int f=0; f!=nfaces; ++f) {
AmanziMesh::Entity_ID_List cells;
mesh->face_get_cells(f,AmanziMesh::USED,&cells);
if (cells.size() == 1) {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]];
} else {
if (hz_c[0][cells[0]] > hz_c[0][cells[1]]) {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]];
} else {
Krel_uw_vec[0][f] = Krel_c_vec[0][cells[1]];
}
}
}
}
// Re-assemble
Krel_uw->ScatterMasterToGhosted();
matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr());
matrix_->CreateMFDrhsVectors();
matrix_->ApplyBoundaryConditions(bc_markers, bc_values);
matrix_->AssembleGlobalMatrices();
// Apply the operator to get div flux
matrix_->ComputeNegativeResidual(*hz, residual.ptr());
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " DIFFUSION RESIDUAL = " << std::endl;
residual->Print(*vo_->os());
}
// Accumulation
{
Epetra_MultiVector& residual_c = *residual->ViewComponent("cell",false);
const Epetra_MultiVector& result_prev_c = *result_prev->ViewComponent("cell",false);
const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false);
unsigned int ncells = residual_c.MyLength();
for (unsigned int c=0; c!=ncells; ++c) {
residual_c[0][c] += (result_c[0][c] - result_prev_c[0][c]) * cv[0][c] / dt;
}
}
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " ACCUMULATION RESIDUAL = " << std::endl;
residual->Print(*vo_->os());
}
double norm = 0.;
residual->NormInf(&norm);
if (ncycle == 0) norm0 = norm;
ncycle++;
if (vo_->os_OK(Teuchos::VERB_HIGH)) {
*vo_->os() << " inner iterate " << ncycle << " has error norm " << norm << std::endl;
}
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
residual->Print(*vo_->os());
}
if ((norm0 == 0.) || (norm / norm0 < tol_) || (ncycle > max_it_)) {
done = true;
continue;
}
// Apply the preconditioner
matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr());
matrix_->CreateMFDrhsVectors();
matrix_->ApplyBoundaryConditions(bc_markers, bc_values);
{
std::vector<double>& Acc_cells = matrix_->Acc_cells();
unsigned int ncells = Acc_cells.size();
for (unsigned int c=0; c!=ncells; ++c) {
Acc_cells[c] += cv[0][c] / dt;
}
}
matrix_->AssembleGlobalMatrices();
matrix_->ComputeSchurComplement(bc_markers, bc_values);
matrix_->UpdatePreconditioner();
dresult->PutScalar(0.);
matrix_linsolve_->ApplyInverse(*residual, *dresult);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " precon'd update = " << std::endl;
dresult->Print(*vo_->os());
}
// Update
result->Update(-1., *dresult, 1.);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << " new snow depth = " << std::endl;
result->Print(*vo_->os());
}
}
}
// get Q back
result->Scale(1./(ktmax_ * kSWE_conv_));
} else {
result->PutScalar(0.);
}
}
// This is hopefully never called?
void ImplicitSnowDistributionEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& results) {
ASSERT(0);
}
void
ImplicitSnowDistributionEvaluator::AssembleOperator_(const Teuchos::Ptr<State>& S) {
Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_);
matrix_ = Operators::CreateMatrixMFD(plist_.sublist("Diffusion"), mesh);
matrix_->set_symmetric(true);
matrix_->SymbolicAssembleGlobalMatrices();
matrix_->CreateMFDmassMatrices(Teuchos::null);
matrix_->InitPreconditioner();
AmanziSolvers::LinearOperatorFactory<CompositeMatrix,CompositeVector,CompositeVectorSpace> fac;
matrix_linsolve_ = fac.Create(plist_.sublist("Diffusion Solver"), matrix_);
}
} //namespace
} //namespace
} //namespace
<|endoftext|> |
<commit_before>#include <cstdio> // sscanf
#include <cstdint>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <sstream>
#include <vector>
extern "C" {
#include "../../src/ASSInspector.h"
}
struct DialogLine {
int time;
std::string line;
};
class ScriptWrapper {
std::string headerBuffer;
std::vector<DialogLine> lineBuffers;
public:
ScriptWrapper( void );
void appendHeader( std::string line );
std::string getHeader( void );
std::vector<DialogLine> getLines( void );
void appendDialogue( std::string line, int time );
};
ScriptWrapper::ScriptWrapper( void ) :
headerBuffer( "[Script Info]\n" ) {
}
void ScriptWrapper::appendHeader( std::string line ) {
headerBuffer += line + "\n";
}
std::string ScriptWrapper::getHeader( void ) {
return headerBuffer;
}
void ScriptWrapper::appendDialogue( std::string line, int time ) {
lineBuffers.push_back( {time, line + '\n'} );
}
std::vector<DialogLine> ScriptWrapper::getLines( void ) {
return lineBuffers;
}
// this should definitely all be one function it is so good
int main( int argc, char **argv ) {
int width = 0, height = 0;
if ( 2 > argc ) {
std::cout << "Usage: " << argv[0] << " infile.ass" << std::endl;
return 1;
}
std::fstream inAss( argv[1], std::ifstream::in );
if ( inAss.fail( ) ) {
std::cout << "Failed to open " << argv[1] << std::endl;
}
std::string line;
std::getline( inAss, line );
if ( "[Script Info]" != line ) {
// BOM?
if ( "[Script Info]" != line.substr( 3 ) ) {
std::cout << "The input file, " << argv[1] << ", does not appear to be valid ASS." << std::endl;
inAss.close( );
return 1;
}
}
ScriptWrapper wrapper;
// This is pretty terrible.
while ( true ) {
std::getline( inAss, line );
if ( '[' == line[0] ) {
break;
}
switch ( line[0] ) {
case 'S':
if ( 0 == line.compare( 0, 22, "ScaledBorderAndShadow:" ) ) {
wrapper.appendHeader( line );
} else if ( 0 == line.compare( 0, 11, "ScriptType:" ) ) {
wrapper.appendHeader( line );
}
break;
case 'P':
if ( 0 == line.compare( 0, 9, "PlayResX:" ) ) {
std::stringstream converter( line.substr( 9 ) );
converter >> width;
wrapper.appendHeader( line );
} else if ( 0 == line.compare( 0, 9, "PlayResY:" ) ) {
std::stringstream converter( line.substr( 9 ) );
converter >> height;
wrapper.appendHeader( line );
}
break;
case 'W':
if ( 0 == line.compare( 0, 10, "WrapStyle:" ) ) {
wrapper.appendHeader( line );
}
break;
}
if ( !inAss.good( ) ) {
break;
}
}
wrapper.appendHeader( "[V4+ Styles]" );
while ( true ) {
std::getline( inAss, line );
switch ( line[0] ) {
case 'S':
if ( 0 == line.compare( 0, 6, "Style:" ) ) {
wrapper.appendHeader( line );
}
break;
case 'D':
if ( 0 == line.compare( 0, 9, "Dialogue:" ) ) {
int hours = 0, minutes = 0, seconds = 0, centiseconds = 0;
sscanf( line.substr( 9 ).c_str( ), "%*d,%u:%u:%u.%u", &hours, &minutes, &seconds, ¢iseconds );
int milliseconds = 3600000*hours + 60000*minutes + 1000*seconds + 10*centiseconds;
wrapper.appendDialogue( line, milliseconds );
}
break;
}
if ( !inAss.good( ) ) {
break;
}
}
inAss.close( );
wrapper.appendHeader( "[Events]" );
ASSI_State *state = assi_init( width, height, NULL, NULL );
std::string header = wrapper.getHeader( );
assi_setHeader( state, header.c_str( ), header.length( ) );
std::map<uint32_t,int> hashes;
std::map<uint32_t,int>::iterator match;
int deleted = 0, kept = 0;
int processed = 0;
for ( const auto &pair : wrapper.getLines( ) ) {
assi_setScript( state, pair.line.c_str( ), pair.line.length( ) );
ASSI_Rect rect{ 0, 0, 0, 0, 0 };
assi_calculateBounds( state, &rect, &pair.time, 1 );
++processed;
match = hashes.find( rect.hash );
if ( hashes.end( ) != match ) {
std::cout << "Line " << processed << ": duplicate hash found (line " << match->second << ")" << std::endl;
} else {
hashes[rect.hash] = processed;
}
if ( rect.w == 0 || rect.h == 0 ) {
++deleted;
} else {
++kept;
}
}
std::cout << "Deleted " << deleted << " lines out of " << processed << std::endl;
assi_cleanup( state );
return 0;
}
<commit_msg>C++ example: don't segfault if input file doesn't exist.<commit_after>#include <cstdio> // sscanf
#include <cstdint>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <sstream>
#include <vector>
extern "C" {
#include "../../src/ASSInspector.h"
}
struct DialogLine {
int time;
std::string line;
};
class ScriptWrapper {
std::string headerBuffer;
std::vector<DialogLine> lineBuffers;
public:
ScriptWrapper( void );
void appendHeader( std::string line );
std::string getHeader( void );
std::vector<DialogLine> getLines( void );
void appendDialogue( std::string line, int time );
};
ScriptWrapper::ScriptWrapper( void ) :
headerBuffer( "[Script Info]\n" ) {
}
void ScriptWrapper::appendHeader( std::string line ) {
headerBuffer += line + "\n";
}
std::string ScriptWrapper::getHeader( void ) {
return headerBuffer;
}
void ScriptWrapper::appendDialogue( std::string line, int time ) {
lineBuffers.push_back( {time, line + '\n'} );
}
std::vector<DialogLine> ScriptWrapper::getLines( void ) {
return lineBuffers;
}
// this should definitely all be one function it is so good
int main( int argc, char **argv ) {
int width = 0, height = 0;
if ( 2 > argc ) {
std::cout << "Usage: " << argv[0] << " infile.ass" << std::endl;
return 1;
}
std::fstream inAss( argv[1], std::ifstream::in );
if ( inAss.fail( ) ) {
std::cout << "Failed to open " << argv[1] << std::endl;
return 1;
}
std::string line;
std::getline( inAss, line );
if ( "[Script Info]" != line ) {
// BOM?
if ( "[Script Info]" != line.substr( 3 ) ) {
std::cout << "The input file, " << argv[1] << ", does not appear to be valid ASS." << std::endl;
inAss.close( );
return 1;
}
}
ScriptWrapper wrapper;
// This is pretty terrible.
while ( true ) {
std::getline( inAss, line );
if ( '[' == line[0] ) {
break;
}
switch ( line[0] ) {
case 'S':
if ( 0 == line.compare( 0, 22, "ScaledBorderAndShadow:" ) ) {
wrapper.appendHeader( line );
} else if ( 0 == line.compare( 0, 11, "ScriptType:" ) ) {
wrapper.appendHeader( line );
}
break;
case 'P':
if ( 0 == line.compare( 0, 9, "PlayResX:" ) ) {
std::stringstream converter( line.substr( 9 ) );
converter >> width;
wrapper.appendHeader( line );
} else if ( 0 == line.compare( 0, 9, "PlayResY:" ) ) {
std::stringstream converter( line.substr( 9 ) );
converter >> height;
wrapper.appendHeader( line );
}
break;
case 'W':
if ( 0 == line.compare( 0, 10, "WrapStyle:" ) ) {
wrapper.appendHeader( line );
}
break;
}
if ( !inAss.good( ) ) {
break;
}
}
wrapper.appendHeader( "[V4+ Styles]" );
while ( true ) {
std::getline( inAss, line );
switch ( line[0] ) {
case 'S':
if ( 0 == line.compare( 0, 6, "Style:" ) ) {
wrapper.appendHeader( line );
}
break;
case 'D':
if ( 0 == line.compare( 0, 9, "Dialogue:" ) ) {
int hours = 0, minutes = 0, seconds = 0, centiseconds = 0;
sscanf( line.substr( 9 ).c_str( ), "%*d,%u:%u:%u.%u", &hours, &minutes, &seconds, ¢iseconds );
int milliseconds = 3600000*hours + 60000*minutes + 1000*seconds + 10*centiseconds;
wrapper.appendDialogue( line, milliseconds );
}
break;
}
if ( !inAss.good( ) ) {
break;
}
}
inAss.close( );
wrapper.appendHeader( "[Events]" );
ASSI_State *state = assi_init( width, height, NULL, NULL );
std::string header = wrapper.getHeader( );
assi_setHeader( state, header.c_str( ), header.length( ) );
std::map<uint32_t,int> hashes;
std::map<uint32_t,int>::iterator match;
int deleted = 0, kept = 0;
int processed = 0;
for ( const auto &pair : wrapper.getLines( ) ) {
assi_setScript( state, pair.line.c_str( ), pair.line.length( ) );
ASSI_Rect rect{ 0, 0, 0, 0, 0 };
assi_calculateBounds( state, &rect, &pair.time, 1 );
++processed;
match = hashes.find( rect.hash );
if ( hashes.end( ) != match ) {
std::cout << "Line " << processed << ": duplicate hash found (line " << match->second << ")" << std::endl;
} else {
hashes[rect.hash] = processed;
}
if ( rect.w == 0 || rect.h == 0 ) {
++deleted;
} else {
++kept;
}
}
std::cout << "Deleted " << deleted << " lines out of " << processed << std::endl;
assi_cleanup( state );
return 0;
}
<|endoftext|> |
<commit_before>#include "ModuleAssimp.h"
#include "Globals.h"
#include "Application.h"
#include "ModuleGui.h"
#include "Module.h"
#include"Imgui/imgui_impl_sdl.h"
#include"Imgui\imgui_impl_sdl_gl3.h"
#include"Imgui/imgui.h"
#include"ModuleSceneIntro.h"
ModuleAssimp::ModuleAssimp(bool start_enabled) : Module(start_enabled)
{
}
// Destructor
ModuleAssimp::~ModuleAssimp()
{
}
// Called before render is available
bool ModuleAssimp::Start()
{
ilutRenderer(ILUT_OPENGL);
ilInit();
iluInit();
ilutInit();
ilutRenderer(ILUT_OPENGL);
ilClearColour(255, 255, 255, 000);
//Check for error
ILenum ilError = ilGetError();
if (ilError != IL_NO_ERROR)
{
LOG("IlInit error!!");
}
struct aiLogStream stream;
stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, NULL);
aiAttachLogStream(&stream);
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Initialize();
}
return true;
}
update_status ModuleAssimp::PreUpdate(float dt)
{
return update_status::UPDATE_CONTINUE;
}
update_status ModuleAssimp::Update(float dt)
{
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Draw();
}
if (App->input->flie_dropped) {
if (IsTexture(App->input->dropped_filedir) == false) {
for (int p = 0; p < meshes_vec.size(); p++) {
delete meshes_vec[p];
}
meshes_vec.clear();
}
bool loaded = ImportGeometry(App->input->dropped_filedir);
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Initialize();
}
<<<<<<< HEAD
if (loaded == true)
{
App->camera->CameraCenter(&meshes_vec.back()->mesh.BoundBox);
}
App->input->flie_dropped = false;
=======
App->input->flie_dropped = false;
>>>>>>> origin/Assigment_1
}
return UPDATE_CONTINUE;
}
update_status ModuleAssimp::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
bool ModuleAssimp::Gui_Engine_Modules(float dt)
{
return false;
}
// Called before quitting
bool ModuleAssimp::CleanUp()
{
return true;
}
bool ModuleAssimp::ImportGeometry(char* fbx)
{
//----------------ASSIMP
std::string full_path;
full_path = fbx;
const aiScene* scene = aiImportFile(full_path.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (scene != nullptr && scene->HasMeshes())
{
// Use scene->mNumMeshes to iterate on scene->mMeshes array
for (int i = 0; i < scene->mNumMeshes; i++) {
m = new Geometry_Manager(PrimitiveTypes::Primitive_Mesh);
m->mesh.num_vertices = scene->mMeshes[i]->mNumVertices;
m->mesh.vertices = new float[m->mesh.num_vertices * 3];
memcpy(m->mesh.vertices, scene->mMeshes[i]->mVertices, sizeof(float) * m->mesh.num_vertices * 3);
LOG("New mesh with %d vertices", m->mesh.num_vertices);
//Generate bounding bax
m->mesh.BoundBox.SetNegativeInfinity();
m->mesh.BoundBox.Enclose((float3*)m->mesh.vertices, m->mesh.num_vertices);
//
// copy faces
if (scene->mMeshes[i]->HasFaces())
{
m->mesh.num_tris = scene->mMeshes[i]->mNumFaces;
m->mesh.num_indices = scene->mMeshes[i]->mNumFaces * 3;
m->mesh.indices = new uint[m->mesh.num_indices]; // assume each face is a triangle
for (uint k = 0; k < scene->mMeshes[i]->mNumFaces; ++k)
{
if (scene->mMeshes[i]->mFaces[k].mNumIndices != 3) {
LOG("WARNING, geometry face with != 3 indices!");
}
else {
memcpy(&m->mesh.indices[k * 3], scene->mMeshes[i]->mFaces[k].mIndices, 3 * sizeof(uint));
}
}
}
if (scene->mMeshes[i]->HasNormals()) {
m->mesh.normals = new float[m->mesh.num_vertices * 3];
memcpy(m->mesh.normals, scene->mMeshes[i]->mNormals, sizeof(float) * m->mesh.num_vertices * 3);
}
aiVector3D translation;
aiVector3D scaling;
aiQuaternion rotation;
/*for (int i = 0; i < scene->mRootNode->mNumChildren; i++) {
scene->mRootNode->mChildren[i]->mTransformation.Decompose(scaling, rotation, translation);
m->mesh.translation.Set(translation.x,translation.y, translation.z);
m->mesh.scaling.Set(scaling.x, scaling.y, scaling.z);
m->mesh.rotation.Set(rotation.x, rotation.y, rotation.z, rotation.w);
}*/
aiNode* nod =Calc_AllGeometry_Childs(scene->mRootNode, i);
aiMatrix4x4 temp_trans;
while (nod->mParent!=nullptr) {
temp_trans*=nod->mTransformation;
nod = nod->mParent;
}
temp_trans.Decompose(scaling, rotation, translation);
m->mesh.translation.Set(translation.x, translation.y, translation.z);
m->mesh.scaling.Set(scaling.x, scaling.y, scaling.z);
m->mesh.rotation.Set(rotation.x, rotation.y, rotation.z, rotation.w);
// texture coords (only one texture for now)
if (scene->mMeshes[i]->HasTextureCoords(0))
{
m->mesh.textures_coord = new float[m->mesh.num_vertices * 2];
for (int z = 0; z < scene->mMeshes[i]->mNumVertices; ++z) {
m->mesh.textures_coord[z*2] = scene->mMeshes[i]->mTextureCoords[0][z].x;
m->mesh.textures_coord[z * 2+1] = scene->mMeshes[i]->mTextureCoords[0][z].y;
}
}
aiMaterial* material = scene->mMaterials[scene->mMeshes[i]->mMaterialIndex];
uint numTextures = material->GetTextureCount(aiTextureType_DIFFUSE);
aiString path;
material->GetTexture(aiTextureType_DIFFUSE, 0, &path);
m->mesh.texture_str = path.C_Str();
meshes_vec.push_back(m);
}
return true;
aiReleaseImport(scene);
}
else {
bool textureLoaded = false;
//Generate and set current image ID
if (IsTexture(fbx))
{
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->mesh.texture_str = fbx;
}
}
LOG("Error loading scene %s", full_path);
return false;
}
//aiMesh
}
GLuint ModuleAssimp::LoadImage_devil(const char * theFileName, GLuint *buff)
{
//Texture loading success
bool textureLoaded = false;
//Generate and set current image ID
uint imgID = 0;
ilGenImages(1, &imgID);
ilBindImage(imgID);
//Load image
ILboolean success = ilLoadImage(theFileName);
//Image loaded successfully
if (success == IL_TRUE)
{
ILinfo ImageInfo;
iluGetImageInfo(&ImageInfo);
if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
{
iluFlipImage();
}
//Convert image to RGBA
success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
if (success == IL_TRUE)
{
textureLoaded = loadTextureFromPixels32((GLuint*)ilGetData(), (GLuint)ilGetInteger(IL_IMAGE_WIDTH), (GLuint)ilGetInteger(IL_IMAGE_HEIGHT), buff);
//Create texture from file pixels
textureLoaded = true;
}
//Delete file from memory
ilDeleteImages(1, &imgID);
}
//Report error
if (!textureLoaded)
{
}
return textureLoaded;
}
bool ModuleAssimp::loadTextureFromPixels32(GLuint * id_pixels, GLuint width_img, GLuint height_img, GLuint *buff)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, buff);
glBindTexture(GL_TEXTURE_2D, *buff);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_img, height_img,
0, GL_RGBA, GL_UNSIGNED_BYTE, id_pixels);
glBindTexture(GL_TEXTURE_2D, NULL);
//Check for error
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
printf("Error loading texture from %p pixels! %s\n", id_pixels, gluErrorString(error));
return false;
}
return true;
}
bool ModuleAssimp::IsTexture(char * path)
{
bool ret = false;
uint imgID = 0;
ilGenImages(1, &imgID);
ilBindImage(imgID);
//Load image
ILboolean success = ilLoadImage(path);
if (success) {
ret = true;
}
ilDeleteImages(1, &imgID);
return ret;
}
aiNode* ModuleAssimp::Calc_AllGeometry_Childs(aiNode* Parent_node, uint search_mesh) {
aiNode* temp;
if (Parent_node != nullptr) {
int i;
for (i = 0; i < Parent_node->mNumChildren; i++) {
for (int j = 0; j < Parent_node->mChildren[i]->mNumMeshes; j++) {
if (Parent_node->mChildren[i]->mMeshes[j] == search_mesh) {
return Parent_node->mChildren[i];
}
}
if (Parent_node->mNumChildren > 0) {
temp = Calc_AllGeometry_Childs(Parent_node->mChildren[i], search_mesh);
if (temp != nullptr)
return temp;
}
}
}
return nullptr;
}<commit_msg>Fixed merge<commit_after>#include "ModuleAssimp.h"
#include "Globals.h"
#include "Application.h"
#include "ModuleGui.h"
#include "Module.h"
#include"Imgui/imgui_impl_sdl.h"
#include"Imgui\imgui_impl_sdl_gl3.h"
#include"Imgui/imgui.h"
#include"ModuleSceneIntro.h"
ModuleAssimp::ModuleAssimp(bool start_enabled) : Module(start_enabled)
{
}
// Destructor
ModuleAssimp::~ModuleAssimp()
{
}
// Called before render is available
bool ModuleAssimp::Start()
{
ilutRenderer(ILUT_OPENGL);
ilInit();
iluInit();
ilutInit();
ilutRenderer(ILUT_OPENGL);
ilClearColour(255, 255, 255, 000);
//Check for error
ILenum ilError = ilGetError();
if (ilError != IL_NO_ERROR)
{
LOG("IlInit error!!");
}
struct aiLogStream stream;
stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, NULL);
aiAttachLogStream(&stream);
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Initialize();
}
return true;
}
update_status ModuleAssimp::PreUpdate(float dt)
{
return update_status::UPDATE_CONTINUE;
}
update_status ModuleAssimp::Update(float dt)
{
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Draw();
}
if (App->input->flie_dropped) {
if (IsTexture(App->input->dropped_filedir) == false) {
for (int p = 0; p < meshes_vec.size(); p++) {
delete meshes_vec[p];
}
meshes_vec.clear();
}
bool loaded = ImportGeometry(App->input->dropped_filedir);
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->Initialize();
}
if (loaded == true)
{
App->camera->CameraCenter(&meshes_vec.back()->mesh.BoundBox);
}
App->input->flie_dropped = false;
App->input->flie_dropped = false;
}
return UPDATE_CONTINUE;
}
update_status ModuleAssimp::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
bool ModuleAssimp::Gui_Engine_Modules(float dt)
{
return false;
}
// Called before quitting
bool ModuleAssimp::CleanUp()
{
return true;
}
bool ModuleAssimp::ImportGeometry(char* fbx)
{
//----------------ASSIMP
std::string full_path;
full_path = fbx;
const aiScene* scene = aiImportFile(full_path.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (scene != nullptr && scene->HasMeshes())
{
// Use scene->mNumMeshes to iterate on scene->mMeshes array
for (int i = 0; i < scene->mNumMeshes; i++) {
m = new Geometry_Manager(PrimitiveTypes::Primitive_Mesh);
m->mesh.num_vertices = scene->mMeshes[i]->mNumVertices;
m->mesh.vertices = new float[m->mesh.num_vertices * 3];
memcpy(m->mesh.vertices, scene->mMeshes[i]->mVertices, sizeof(float) * m->mesh.num_vertices * 3);
LOG("New mesh with %d vertices", m->mesh.num_vertices);
//Generate bounding bax
m->mesh.BoundBox.SetNegativeInfinity();
m->mesh.BoundBox.Enclose((float3*)m->mesh.vertices, m->mesh.num_vertices);
//
// copy faces
if (scene->mMeshes[i]->HasFaces())
{
m->mesh.num_tris = scene->mMeshes[i]->mNumFaces;
m->mesh.num_indices = scene->mMeshes[i]->mNumFaces * 3;
m->mesh.indices = new uint[m->mesh.num_indices]; // assume each face is a triangle
for (uint k = 0; k < scene->mMeshes[i]->mNumFaces; ++k)
{
if (scene->mMeshes[i]->mFaces[k].mNumIndices != 3) {
LOG("WARNING, geometry face with != 3 indices!");
}
else {
memcpy(&m->mesh.indices[k * 3], scene->mMeshes[i]->mFaces[k].mIndices, 3 * sizeof(uint));
}
}
}
if (scene->mMeshes[i]->HasNormals()) {
m->mesh.normals = new float[m->mesh.num_vertices * 3];
memcpy(m->mesh.normals, scene->mMeshes[i]->mNormals, sizeof(float) * m->mesh.num_vertices * 3);
}
aiVector3D translation;
aiVector3D scaling;
aiQuaternion rotation;
/*for (int i = 0; i < scene->mRootNode->mNumChildren; i++) {
scene->mRootNode->mChildren[i]->mTransformation.Decompose(scaling, rotation, translation);
m->mesh.translation.Set(translation.x,translation.y, translation.z);
m->mesh.scaling.Set(scaling.x, scaling.y, scaling.z);
m->mesh.rotation.Set(rotation.x, rotation.y, rotation.z, rotation.w);
}*/
aiNode* nod =Calc_AllGeometry_Childs(scene->mRootNode, i);
aiMatrix4x4 temp_trans;
while (nod->mParent!=nullptr) {
temp_trans*=nod->mTransformation;
nod = nod->mParent;
}
temp_trans.Decompose(scaling, rotation, translation);
m->mesh.translation.Set(translation.x, translation.y, translation.z);
m->mesh.scaling.Set(scaling.x, scaling.y, scaling.z);
m->mesh.rotation.Set(rotation.x, rotation.y, rotation.z, rotation.w);
// texture coords (only one texture for now)
if (scene->mMeshes[i]->HasTextureCoords(0))
{
m->mesh.textures_coord = new float[m->mesh.num_vertices * 2];
for (int z = 0; z < scene->mMeshes[i]->mNumVertices; ++z) {
m->mesh.textures_coord[z*2] = scene->mMeshes[i]->mTextureCoords[0][z].x;
m->mesh.textures_coord[z * 2+1] = scene->mMeshes[i]->mTextureCoords[0][z].y;
}
}
aiMaterial* material = scene->mMaterials[scene->mMeshes[i]->mMaterialIndex];
uint numTextures = material->GetTextureCount(aiTextureType_DIFFUSE);
aiString path;
material->GetTexture(aiTextureType_DIFFUSE, 0, &path);
m->mesh.texture_str = path.C_Str();
meshes_vec.push_back(m);
}
return true;
aiReleaseImport(scene);
}
else {
bool textureLoaded = false;
//Generate and set current image ID
if (IsTexture(fbx))
{
for (int p = 0; p < meshes_vec.size(); p++) {
meshes_vec[p]->mesh.texture_str = fbx;
}
}
LOG("Error loading scene %s", full_path);
return false;
}
//aiMesh
}
GLuint ModuleAssimp::LoadImage_devil(const char * theFileName, GLuint *buff)
{
//Texture loading success
bool textureLoaded = false;
//Generate and set current image ID
uint imgID = 0;
ilGenImages(1, &imgID);
ilBindImage(imgID);
//Load image
ILboolean success = ilLoadImage(theFileName);
//Image loaded successfully
if (success == IL_TRUE)
{
ILinfo ImageInfo;
iluGetImageInfo(&ImageInfo);
if (ImageInfo.Origin == IL_ORIGIN_UPPER_LEFT)
{
iluFlipImage();
}
//Convert image to RGBA
success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
if (success == IL_TRUE)
{
textureLoaded = loadTextureFromPixels32((GLuint*)ilGetData(), (GLuint)ilGetInteger(IL_IMAGE_WIDTH), (GLuint)ilGetInteger(IL_IMAGE_HEIGHT), buff);
//Create texture from file pixels
textureLoaded = true;
}
//Delete file from memory
ilDeleteImages(1, &imgID);
}
//Report error
if (!textureLoaded)
{
}
return textureLoaded;
}
bool ModuleAssimp::loadTextureFromPixels32(GLuint * id_pixels, GLuint width_img, GLuint height_img, GLuint *buff)
{
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, buff);
glBindTexture(GL_TEXTURE_2D, *buff);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_img, height_img,
0, GL_RGBA, GL_UNSIGNED_BYTE, id_pixels);
glBindTexture(GL_TEXTURE_2D, NULL);
//Check for error
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
printf("Error loading texture from %p pixels! %s\n", id_pixels, gluErrorString(error));
return false;
}
return true;
}
bool ModuleAssimp::IsTexture(char * path)
{
bool ret = false;
uint imgID = 0;
ilGenImages(1, &imgID);
ilBindImage(imgID);
//Load image
ILboolean success = ilLoadImage(path);
if (success) {
ret = true;
}
ilDeleteImages(1, &imgID);
return ret;
}
aiNode* ModuleAssimp::Calc_AllGeometry_Childs(aiNode* Parent_node, uint search_mesh) {
aiNode* temp;
if (Parent_node != nullptr) {
int i;
for (i = 0; i < Parent_node->mNumChildren; i++) {
for (int j = 0; j < Parent_node->mChildren[i]->mNumMeshes; j++) {
if (Parent_node->mChildren[i]->mMeshes[j] == search_mesh) {
return Parent_node->mChildren[i];
}
}
if (Parent_node->mNumChildren > 0) {
temp = Calc_AllGeometry_Childs(Parent_node->mChildren[i], search_mesh);
if (temp != nullptr)
return temp;
}
}
}
return nullptr;
}<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* Copyright 2010 VMware, 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.
*
**************************************************************************/
#include <string.h>
#include <limits.h> // for CHAR_MAX
#include <getopt.h>
#include "cli.hpp"
#include "cli_pager.hpp"
#include "trace_parser.hpp"
#include "trace_dump.hpp"
#include "trace_callset.hpp"
enum ColorOption {
COLOR_OPTION_NEVER = 0,
COLOR_OPTION_ALWAYS = 1,
COLOR_OPTION_AUTO = -1
};
static ColorOption color = COLOR_OPTION_AUTO;
static bool verbose = false;
static trace::CallSet calls(trace::FREQUENCY_ALL);
static const char *synopsis = "Dump given trace(s) to standard output.";
static void
usage(void)
{
std::cout
<< "usage: apitrace dump [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help show this help message and exit\n"
" -v, --verbose verbose output\n"
" --calls=CALLSET only dump specified calls\n"
" --color[=WHEN]\n"
" --colour[=WHEN] colored syntax highlighting\n"
" WHEN is 'auto', 'always', or 'never'\n"
" --thread-ids=[=BOOL] dump thread ids [default: no]\n"
" --call-nos[=BOOL] dump call numbers[default: yes]\n"
" --arg-names[=BOOL] dump argument names [default: yes]\n"
"\n"
;
}
enum {
CALLS_OPT = CHAR_MAX + 1,
COLOR_OPT,
THREAD_IDS_OPT,
CALL_NOS_OPT,
ARG_NAMES_OPT,
};
const static char *
shortOptions = "hv";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"calls", required_argument, 0, CALLS_OPT},
{"colour", optional_argument, 0, COLOR_OPT},
{"color", optional_argument, 0, COLOR_OPT},
{"thread-ids", optional_argument, 0, THREAD_IDS_OPT},
{"call-nos", optional_argument, 0, CALL_NOS_OPT},
{"arg-names", optional_argument, 0, ARG_NAMES_OPT},
{0, 0, 0, 0}
};
static bool
boolOption(const char *option, bool default_ = true) {
if (!option) {
return default_;
}
if (strcmp(option, "0") == 0 ||
strcmp(option, "no") == 0 ||
strcmp(option, "false") == 0) {
return false;
}
if (strcmp(option, "0") == 0 ||
strcmp(option, "yes") == 0 ||
strcmp(option, "true") == 0) {
return true;
}
std::cerr << "error: unexpected bool " << option << "\n";
return default_;
}
static int
command(int argc, char *argv[])
{
trace::DumpFlags dumpFlags = 0;
bool dumpThreadIds = false;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 'v':
verbose = true;
break;
case CALLS_OPT:
calls = trace::CallSet(optarg);
break;
case COLOR_OPT:
if (!optarg ||
!strcmp(optarg, "always")) {
color = COLOR_OPTION_ALWAYS;
} else if (!strcmp(optarg, "auto")) {
color = COLOR_OPTION_AUTO;
} else if (!strcmp(optarg, "never")) {
color = COLOR_OPTION_NEVER;
} else {
std::cerr << "error: unknown color argument " << optarg << "\n";
return 1;
}
break;
case THREAD_IDS_OPT:
dumpThreadIds = boolOption(optarg);
break;
case CALL_NOS_OPT:
if (boolOption(optarg)) {
dumpFlags &= ~trace::DUMP_FLAG_NO_CALL_NO;
} else {
dumpFlags |= trace::DUMP_FLAG_NO_CALL_NO;
}
break;
case ARG_NAMES_OPT:
if (boolOption(optarg)) {
dumpFlags &= ~trace::DUMP_FLAG_NO_ARG_NAMES;
} else {
dumpFlags |= trace::DUMP_FLAG_NO_ARG_NAMES;
}
break;
default:
std::cerr << "error: unexpected option `" << opt << "`\n";
usage();
return 1;
}
}
if (color == COLOR_OPTION_AUTO) {
#ifdef _WIN32
color = COLOR_OPTION_ALWAYS;
#else
color = isatty(1) ? COLOR_OPTION_ALWAYS : COLOR_OPTION_NEVER;
pipepager();
#endif
}
if (color == COLOR_OPTION_NEVER) {
dumpFlags |= trace::DUMP_FLAG_NO_COLOR;
}
for (int i = optind; i < argc; ++i) {
trace::Parser p;
if (!p.open(argv[i])) {
std::cerr << "error: failed to open " << argv[i] << "\n";
return 1;
}
trace::Call *call;
while ((call = p.parse_call())) {
if (calls.contains(*call)) {
if (verbose ||
!(call->flags & trace::CALL_FLAG_VERBOSE)) {
if (dumpThreadIds) {
std::cout << std::hex << call->thread_id << std::dec << " ";
}
trace::dump(*call, std::cout, dumpFlags);
}
}
delete call;
}
}
return 0;
}
const Command dump_command = {
"dump",
synopsis,
usage,
command
};
<commit_msg>Fix compile error "isatty was not declared"; missing unistd.h include<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* Copyright 2010 VMware, 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.
*
**************************************************************************/
#include <string.h>
#include <limits.h> // for CHAR_MAX
#include <getopt.h>
#ifndef _WIN32
#include <unistd.h> // for isatty()
#endif
#include "cli.hpp"
#include "cli_pager.hpp"
#include "trace_parser.hpp"
#include "trace_dump.hpp"
#include "trace_callset.hpp"
enum ColorOption {
COLOR_OPTION_NEVER = 0,
COLOR_OPTION_ALWAYS = 1,
COLOR_OPTION_AUTO = -1
};
static ColorOption color = COLOR_OPTION_AUTO;
static bool verbose = false;
static trace::CallSet calls(trace::FREQUENCY_ALL);
static const char *synopsis = "Dump given trace(s) to standard output.";
static void
usage(void)
{
std::cout
<< "usage: apitrace dump [OPTIONS] TRACE_FILE...\n"
<< synopsis << "\n"
"\n"
" -h, --help show this help message and exit\n"
" -v, --verbose verbose output\n"
" --calls=CALLSET only dump specified calls\n"
" --color[=WHEN]\n"
" --colour[=WHEN] colored syntax highlighting\n"
" WHEN is 'auto', 'always', or 'never'\n"
" --thread-ids=[=BOOL] dump thread ids [default: no]\n"
" --call-nos[=BOOL] dump call numbers[default: yes]\n"
" --arg-names[=BOOL] dump argument names [default: yes]\n"
"\n"
;
}
enum {
CALLS_OPT = CHAR_MAX + 1,
COLOR_OPT,
THREAD_IDS_OPT,
CALL_NOS_OPT,
ARG_NAMES_OPT,
};
const static char *
shortOptions = "hv";
const static struct option
longOptions[] = {
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'v'},
{"calls", required_argument, 0, CALLS_OPT},
{"colour", optional_argument, 0, COLOR_OPT},
{"color", optional_argument, 0, COLOR_OPT},
{"thread-ids", optional_argument, 0, THREAD_IDS_OPT},
{"call-nos", optional_argument, 0, CALL_NOS_OPT},
{"arg-names", optional_argument, 0, ARG_NAMES_OPT},
{0, 0, 0, 0}
};
static bool
boolOption(const char *option, bool default_ = true) {
if (!option) {
return default_;
}
if (strcmp(option, "0") == 0 ||
strcmp(option, "no") == 0 ||
strcmp(option, "false") == 0) {
return false;
}
if (strcmp(option, "0") == 0 ||
strcmp(option, "yes") == 0 ||
strcmp(option, "true") == 0) {
return true;
}
std::cerr << "error: unexpected bool " << option << "\n";
return default_;
}
static int
command(int argc, char *argv[])
{
trace::DumpFlags dumpFlags = 0;
bool dumpThreadIds = false;
int opt;
while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
switch (opt) {
case 'h':
usage();
return 0;
case 'v':
verbose = true;
break;
case CALLS_OPT:
calls = trace::CallSet(optarg);
break;
case COLOR_OPT:
if (!optarg ||
!strcmp(optarg, "always")) {
color = COLOR_OPTION_ALWAYS;
} else if (!strcmp(optarg, "auto")) {
color = COLOR_OPTION_AUTO;
} else if (!strcmp(optarg, "never")) {
color = COLOR_OPTION_NEVER;
} else {
std::cerr << "error: unknown color argument " << optarg << "\n";
return 1;
}
break;
case THREAD_IDS_OPT:
dumpThreadIds = boolOption(optarg);
break;
case CALL_NOS_OPT:
if (boolOption(optarg)) {
dumpFlags &= ~trace::DUMP_FLAG_NO_CALL_NO;
} else {
dumpFlags |= trace::DUMP_FLAG_NO_CALL_NO;
}
break;
case ARG_NAMES_OPT:
if (boolOption(optarg)) {
dumpFlags &= ~trace::DUMP_FLAG_NO_ARG_NAMES;
} else {
dumpFlags |= trace::DUMP_FLAG_NO_ARG_NAMES;
}
break;
default:
std::cerr << "error: unexpected option `" << opt << "`\n";
usage();
return 1;
}
}
if (color == COLOR_OPTION_AUTO) {
#ifdef _WIN32
color = COLOR_OPTION_ALWAYS;
#else
color = isatty(1) ? COLOR_OPTION_ALWAYS : COLOR_OPTION_NEVER;
pipepager();
#endif
}
if (color == COLOR_OPTION_NEVER) {
dumpFlags |= trace::DUMP_FLAG_NO_COLOR;
}
for (int i = optind; i < argc; ++i) {
trace::Parser p;
if (!p.open(argv[i])) {
std::cerr << "error: failed to open " << argv[i] << "\n";
return 1;
}
trace::Call *call;
while ((call = p.parse_call())) {
if (calls.contains(*call)) {
if (verbose ||
!(call->flags & trace::CALL_FLAG_VERBOSE)) {
if (dumpThreadIds) {
std::cout << std::hex << call->thread_id << std::dec << " ";
}
trace::dump(*call, std::cout, dumpFlags);
}
}
delete call;
}
}
return 0;
}
const Command dump_command = {
"dump",
synopsis,
usage,
command
};
<|endoftext|> |
<commit_before>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(4, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-4);
SANITY_CHECK(tvec, 1e-4);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(4), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_DLS)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-4);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(4, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<commit_msg>Updating sanity check<commit_after>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(4, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(4), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_DLS, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-4);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(4, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<|endoftext|> |
<commit_before>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(5, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP, (int)SOLVEPNP_UPNP, (int)SOLVEPNP_DLS)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(5),
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_EPNP, (int)SOLVEPNP_DLS, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
if( algo == SOLVEPNP_P3P )
pointsNum = 4;
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0f;
intrinsics.at<float> (1, 1) = 400.0f;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, -0.001, 0.001);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-1);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(5, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<commit_msg>calib3d: normalize Rodrigues vector in perf test<commit_after>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(5, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP, (int)SOLVEPNP_UPNP, (int)SOLVEPNP_DLS)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(5),
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_EPNP, (int)SOLVEPNP_DLS, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
if( algo == SOLVEPNP_P3P )
pointsNum = 4;
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0f;
intrinsics.at<float> (1, 1) = 400.0f;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
// normalize Rodrigues vector
Mat rvec_tmp = Mat::eye(3, 3, CV_32F);
Rodrigues(rvec, rvec_tmp);
Rodrigues(rvec_tmp, rvec);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, -0.001, 0.001);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-1);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(5, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merrunconfigurationfactory.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "merrunconfiguration.h"
#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <qmakeprojectmanager/qmakeproject.h>
#include <utils/qtcassert.h>
using namespace Mer::Constants;
namespace Mer {
namespace Internal {
namespace {
QString stringFromId(Core::Id id)
{
const QString idStr = id.toString();
if (idStr.startsWith(QLatin1String(MER_RUNCONFIGURATION_PREFIX)))
return idStr.mid(QString::fromLatin1(MER_RUNCONFIGURATION_PREFIX).size());
return QString();
}
} // Anonymous
MerRunConfigurationFactory::MerRunConfigurationFactory(QObject *parent)
: ProjectExplorer::IRunConfigurationFactory(parent)
{
}
QList<Core::Id> MerRunConfigurationFactory::availableCreationIds(
ProjectExplorer::Target *parent, CreationMode mode) const
{
Q_UNUSED(mode);
QList<Core::Id>result;
if (!canHandle(parent))
return result;
QmakeProjectManager::QmakeProject *qmakeProject =
qobject_cast<QmakeProjectManager::QmakeProject *>(parent->project());
if (!qmakeProject)
return result;
const Core::Id base = Core::Id(MER_RUNCONFIGURATION_PREFIX);
foreach (const ProjectExplorer::BuildTargetInfo &bti, parent->applicationTargets().list)
result << base.withSuffix(bti.targetName);
return result;
}
QString MerRunConfigurationFactory::displayNameForId(Core::Id id) const
{
if (id.toString().startsWith(QLatin1String(MER_RUNCONFIGURATION_PREFIX)))
return tr("%1 (on Mer Device)").arg(stringFromId(id));
return QString();
}
bool MerRunConfigurationFactory::canCreate(ProjectExplorer::Target *parent, Core::Id id) const
{
if (!canHandle(parent))
return false;
return parent->applicationTargets().hasTarget(stringFromId(id));
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::doCreate(
ProjectExplorer::Target *parent, Core::Id id)
{
if (!canCreate(parent, id))
return 0;
if (id.toString().startsWith(QLatin1String(MER_RUNCONFIGURATION_PREFIX))) {
MerRunConfiguration *config = new MerRunConfiguration(parent, id, stringFromId(id));
config->setDefaultDisplayName(displayNameForId(id));
return config;
}
return 0;
}
bool MerRunConfigurationFactory::canRestore(ProjectExplorer::Target *parent,
const QVariantMap &map) const
{
if (!canHandle(parent))
return false;
return ProjectExplorer::idFromMap(map).toString().startsWith(
QLatin1String(MER_RUNCONFIGURATION_PREFIX));
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::doRestore(
ProjectExplorer::Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
Core::Id id = ProjectExplorer::idFromMap(map);
ProjectExplorer::RunConfiguration *rc = new MerRunConfiguration(parent, id, stringFromId(id));
QTC_ASSERT(rc, return 0);
if (rc->fromMap(map))
return rc;
delete rc;
return 0;
}
bool MerRunConfigurationFactory::canClone(ProjectExplorer::Target *parent,
ProjectExplorer::RunConfiguration *source) const
{
return canCreate(parent, source->id());
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::clone(
ProjectExplorer::Target *parent, ProjectExplorer::RunConfiguration *source)
{
if (!canClone(parent, source))
return 0;
MerRunConfiguration *old = qobject_cast<MerRunConfiguration *>(source);
if (!old)
return 0;
return new MerRunConfiguration(parent, old);
}
bool MerRunConfigurationFactory::canHandle(ProjectExplorer::Target *t) const
{
return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(t->kit()));
}
} // Internal
} // Mer
<commit_msg>Mer: Simplify stringFromId by using Core::Id::suffixAfter<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merrunconfigurationfactory.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "merrunconfiguration.h"
#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <qmakeprojectmanager/qmakeproject.h>
#include <utils/qtcassert.h>
using namespace Mer::Constants;
namespace Mer {
namespace Internal {
namespace {
QString stringFromId(Core::Id id)
{
return id.suffixAfter(MER_RUNCONFIGURATION_PREFIX);
}
} // Anonymous
MerRunConfigurationFactory::MerRunConfigurationFactory(QObject *parent)
: ProjectExplorer::IRunConfigurationFactory(parent)
{
}
QList<Core::Id> MerRunConfigurationFactory::availableCreationIds(
ProjectExplorer::Target *parent, CreationMode mode) const
{
Q_UNUSED(mode);
QList<Core::Id>result;
if (!canHandle(parent))
return result;
QmakeProjectManager::QmakeProject *qmakeProject =
qobject_cast<QmakeProjectManager::QmakeProject *>(parent->project());
if (!qmakeProject)
return result;
const Core::Id base = Core::Id(MER_RUNCONFIGURATION_PREFIX);
foreach (const ProjectExplorer::BuildTargetInfo &bti, parent->applicationTargets().list)
result << base.withSuffix(bti.targetName);
return result;
}
QString MerRunConfigurationFactory::displayNameForId(Core::Id id) const
{
if (id.toString().startsWith(QLatin1String(MER_RUNCONFIGURATION_PREFIX)))
return tr("%1 (on Mer Device)").arg(stringFromId(id));
return QString();
}
bool MerRunConfigurationFactory::canCreate(ProjectExplorer::Target *parent, Core::Id id) const
{
if (!canHandle(parent))
return false;
return parent->applicationTargets().hasTarget(stringFromId(id));
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::doCreate(
ProjectExplorer::Target *parent, Core::Id id)
{
if (!canCreate(parent, id))
return 0;
if (id.toString().startsWith(QLatin1String(MER_RUNCONFIGURATION_PREFIX))) {
MerRunConfiguration *config = new MerRunConfiguration(parent, id, stringFromId(id));
config->setDefaultDisplayName(displayNameForId(id));
return config;
}
return 0;
}
bool MerRunConfigurationFactory::canRestore(ProjectExplorer::Target *parent,
const QVariantMap &map) const
{
if (!canHandle(parent))
return false;
return ProjectExplorer::idFromMap(map).toString().startsWith(
QLatin1String(MER_RUNCONFIGURATION_PREFIX));
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::doRestore(
ProjectExplorer::Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
Core::Id id = ProjectExplorer::idFromMap(map);
ProjectExplorer::RunConfiguration *rc = new MerRunConfiguration(parent, id, stringFromId(id));
QTC_ASSERT(rc, return 0);
if (rc->fromMap(map))
return rc;
delete rc;
return 0;
}
bool MerRunConfigurationFactory::canClone(ProjectExplorer::Target *parent,
ProjectExplorer::RunConfiguration *source) const
{
return canCreate(parent, source->id());
}
ProjectExplorer::RunConfiguration *MerRunConfigurationFactory::clone(
ProjectExplorer::Target *parent, ProjectExplorer::RunConfiguration *source)
{
if (!canClone(parent, source))
return 0;
MerRunConfiguration *old = qobject_cast<MerRunConfiguration *>(source);
if (!old)
return 0;
return new MerRunConfiguration(parent, old);
}
bool MerRunConfigurationFactory::canHandle(ProjectExplorer::Target *t) const
{
return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(t->kit()));
}
} // Internal
} // Mer
<|endoftext|> |
<commit_before>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(4, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(4), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_DLS, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-1);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(4, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<commit_msg>this is trivial change; the main change is in opencv_extra - added regression data for perf tests<commit_after>#include "perf_precomp.hpp"
#ifdef HAVE_TBB
#include "tbb/task_scheduler_init.h"
#endif
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(pnpAlgo, SOLVEPNP_ITERATIVE, SOLVEPNP_EPNP, SOLVEPNP_P3P, SOLVEPNP_DLS, SOLVEPNP_UPNP)
typedef std::tr1::tuple<int, pnpAlgo> PointsNum_Algo_t;
typedef perf::TestBaseWithParam<PointsNum_Algo_t> PointsNum_Algo;
typedef perf::TestBaseWithParam<int> PointsNum;
PERF_TEST_P(PointsNum_Algo, solvePnP,
testing::Combine(
testing::Values(4, 3*9, 7*13), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_ITERATIVE, (int)SOLVEPNP_EPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0;
intrinsics.at<float> (1, 1) = 400.0;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
PERF_TEST_P(PointsNum_Algo, solvePnPSmallPoints,
testing::Combine(
testing::Values(4), //TODO: find why results on 4 points are too unstable
testing::Values((int)SOLVEPNP_P3P, (int)SOLVEPNP_DLS, (int)SOLVEPNP_UPNP)
)
)
{
int pointsNum = get<0>(GetParam());
pnpAlgo algo = get<1>(GetParam());
vector<Point2f> points2d(pointsNum);
vector<Point3f> points3d(pointsNum);
Mat rvec = Mat::zeros(3, 1, CV_32FC1);
Mat tvec = Mat::zeros(3, 1, CV_32FC1);
Mat distortion = Mat::zeros(5, 1, CV_32FC1);
Mat intrinsics = Mat::eye(3, 3, CV_32FC1);
intrinsics.at<float> (0, 0) = 400.0f;
intrinsics.at<float> (1, 1) = 400.0f;
intrinsics.at<float> (0, 2) = 640 / 2;
intrinsics.at<float> (1, 2) = 480 / 2;
warmup(points3d, WARMUP_RNG);
warmup(rvec, WARMUP_RNG);
warmup(tvec, WARMUP_RNG);
projectPoints(points3d, rvec, tvec, intrinsics, distortion, points2d);
//add noise
Mat noise(1, (int)points2d.size(), CV_32FC2);
randu(noise, 0, 0.01);
add(points2d, noise, points2d);
declare.in(points3d, points2d);
declare.time(100);
TEST_CYCLE_N(1000)
{
solvePnP(points3d, points2d, intrinsics, distortion, rvec, tvec, false, algo);
}
SANITY_CHECK(rvec, 1e-1);
SANITY_CHECK(tvec, 1e-2);
}
PERF_TEST_P(PointsNum, DISABLED_SolvePnPRansac, testing::Values(4, 3*9, 7*13))
{
int count = GetParam();
Mat object(1, count, CV_32FC3);
randu(object, -100, 100);
Mat camera_mat(3, 3, CV_32FC1);
randu(camera_mat, 0.5, 1);
camera_mat.at<float>(0, 1) = 0.f;
camera_mat.at<float>(1, 0) = 0.f;
camera_mat.at<float>(2, 0) = 0.f;
camera_mat.at<float>(2, 1) = 0.f;
Mat dist_coef(1, 8, CV_32F, cv::Scalar::all(0));
vector<cv::Point2f> image_vec;
Mat rvec_gold(1, 3, CV_32FC1);
randu(rvec_gold, 0, 1);
Mat tvec_gold(1, 3, CV_32FC1);
randu(tvec_gold, 0, 1);
projectPoints(object, rvec_gold, tvec_gold, camera_mat, dist_coef, image_vec);
Mat image(1, count, CV_32FC2, &image_vec[0]);
Mat rvec;
Mat tvec;
#ifdef HAVE_TBB
// limit concurrency to get deterministic result
tbb::task_scheduler_init one_thread(1);
#endif
TEST_CYCLE()
{
solvePnPRansac(object, image, camera_mat, dist_coef, rvec, tvec);
}
SANITY_CHECK(rvec, 1e-6);
SANITY_CHECK(tvec, 1e-6);
}
<|endoftext|> |
<commit_before>#include "FloatEditor.hpp"
#include <exception>
using namespace GUI;
FloatEditor::FloatEditor(Widget* parent, Font* font) : TextField(parent, font) {
variable = nullptr;
}
void FloatEditor::SetFloat(float* variable) {
this->variable = variable;
SetText(std::to_string(*variable));
}
void FloatEditor::TextUpdated() {
float oldValue = *variable;
try {
*variable = std::stof(GetText());
} catch (std::exception& e) {
*variable = oldValue;
}
}
<commit_msg>Removed unnecessary code.<commit_after>#include "FloatEditor.hpp"
#include <exception>
using namespace GUI;
FloatEditor::FloatEditor(Widget* parent, Font* font) : TextField(parent, font) {
variable = nullptr;
}
void FloatEditor::SetFloat(float* variable) {
this->variable = variable;
SetText(std::to_string(*variable));
}
void FloatEditor::TextUpdated() {
try {
*variable = std::stof(GetText());
} catch (std::exception& e) { }
}
<|endoftext|> |
<commit_before>#pragma once
#include "KEngine/Interface/IEventManagerImpl.hpp"
#include <deque>
#include <unordered_map>
#include <vector>
namespace ke::priv
{
class EventManagerImpl : public ke::priv::IEventManagerImpl
{
public:
virtual ~EventManagerImpl();
virtual bool registerListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate) final;
virtual bool deregisterAllListeners(const ke::EventType p_EventType) final;
virtual bool deregisterListener(const ke::EventType p_EventType, const ke::EventDelegate & p_EventDelegate) final;
virtual void queue(ke::EventSptr p_spNewEvent) final;
virtual bool dispatchNow(ke::EventSptr p_Event) final;
virtual bool removeEvent(const ke::EventType p_EventType, const bool p_RemoveAllSame = false) final;
virtual ke::EventProcessResult update(const ke::Time p_DurationLimit = ke::Time::Zero) final;
public:
using DelegateType = ke::EventDelegate;
using ListenerList = std::vector<DelegateType>;
using EventListenersMap = std::unordered_map<ke::EventType, ListenerList>;
using EventQueue = std::deque<ke::EventSptr>;
private:
ke::EventQueue m_ThreadSafeEventQueue;
EventQueue m_EventQueue;
EventListenersMap m_Listeners;
};
}
<commit_msg>change argument name<commit_after>#pragma once
#include "KEngine/Interface/IEventManagerImpl.hpp"
#include <deque>
#include <unordered_map>
#include <vector>
namespace ke::priv
{
class EventManagerImpl : public ke::priv::IEventManagerImpl
{
public:
virtual ~EventManagerImpl();
virtual bool registerListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate) final;
virtual bool deregisterAllListeners(const ke::EventType p_EventType) final;
virtual bool deregisterListener(const ke::EventType p_EventType, const ke::EventDelegate & p_Delegate) final;
virtual void queue(ke::EventSptr p_spNewEvent) final;
virtual bool dispatchNow(ke::EventSptr p_Event) final;
virtual bool removeEvent(const ke::EventType p_EventType, const bool p_RemoveAllSame = false) final;
virtual ke::EventProcessResult update(const ke::Time p_DurationLimit = ke::Time::Zero) final;
public:
using DelegateType = ke::EventDelegate;
using ListenerList = std::vector<DelegateType>;
using EventListenersMap = std::unordered_map<ke::EventType, ListenerList>;
using EventQueue = std::deque<ke::EventSptr>;
private:
ke::EventQueue m_ThreadSafeEventQueue;
EventQueue m_EventQueue;
EventListenersMap m_Listeners;
};
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 David Wicks, sansumbrella.com
* 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.
*
* 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 "TreentSample.h"
#include "TreentNode.h"
#include "cinder/gl/gl.h"
#include "treent/LayeredShapeRenderSystem.h"
#include "treent/TextRenderSystem.h"
#include "treent/ShapeComponent.h"
#include "cinder/Rand.h"
#include <memory>
#define USE_SMOOTHED_ROTATION 1
using namespace pockets;
using namespace cinder;
using namespace cinder::app;
using namespace std;
namespace
{
struct RotationComponent : treent::Component<RotationComponent>
{
RotationComponent() = default;
RotationComponent( float rate ):
rate( rate )
{}
float rate = 1.0f;
};
class RotationSystem : public treent::System<RotationSystem>
{
public:
void update( treent::EntityManagerRef entities, treent::EventManagerRef events, double dt ) override
{
for( auto entity : entities->entities_with_components<RotationComponent, treent::LocationComponent>() )
{
treent::LocationComponentRef location;
shared_ptr<RotationComponent> rotation;
entity.unpack( location, rotation );
#if USE_SMOOTHED_ROTATION
// lerp(curr, target, 1.0-pow(1.0-rate, targetFPS*dt)
// smoothed step
float target = location->rotation + rotation->rate / 60.0;
location->rotation = lerp<float>( location->rotation, target, 1.0 - pow(0.01, 60.0 * dt) );
#else
location->rotation += rotation->rate * dt;
#endif
}
}
};
treent::TreentNodeRef addOrbiter( treent::TreentNodeRef center, bool warm, float max_distance, int depth ) {
float size = center->getSize().length() / 5.0f;
auto moon = center->createChild<treent::TreentNode>();
moon->setSize( vec2( 1.0f ) * size );
vec2 position = randVec2f() * randFloat( max_distance / 4, max_distance );
moon->setPosition( position );
moon->setRegistrationPoint( -position );
auto shape = moon->assign<treent::ShapeComponent>();
auto color = warm ? ColorA( CM_HSV, randFloat( 0.02f, 0.18f ), 1.0f, 1.0f, 1.0f ) : ColorA( CM_HSV, randFloat( 0.45f, 0.62f ), 1.0f, 0.7f, 1.0f );
shape->setAsBox( Rectf( -size, -size, size, size ) );
shape->setColor( color );
moon->assign<treent::LayeredShapeRenderData>( shape, moon->getTransform(), depth );
moon->assign<RotationComponent>( lmap<float>( length( position ), 0.0f, length( vec2(getWindowSize()) ), 1.0f, 0.1f ) );
if( size > 10.0f && randFloat() < 0.5f ) {
addOrbiter( moon, !warm, max_distance / 8, depth + 1 );
}
return moon;
}
} // anon::
void TreentTest::setup()
{
_treent.systems->add<treent::LayeredShapeRenderSystem>();
_treent.systems->add<treent::TextRenderSystem>();
_treent.systems->add<RotationSystem>();
_treent.systems->configure();
_treent_root = _treent.createRoot2D();
_treent_root->setPosition( getWindowCenter() );
_treent_root->setSize( getWindowSize() / 4 );
auto shape = _treent_root->assign<treent::ShapeComponent>();
shape->setAsCircle( vec2( 1.0f ) * (getWindowWidth() / 6.0f), 0, M_PI * 2, 6 ); // hexagon
_treent_root->assign<treent::LayeredShapeRenderData>( shape, _treent_root->getTransform(), 0 );
Font arial( "Arial Bold", 24.0f );
gl::TextureFontRef font = gl::TextureFont::create( arial, gl::TextureFont::Format().premultiply() );
for( int i = 0; i < 1000; ++i )
{
auto moon = addOrbiter( _treent_root, true, getWindowSize().length(), 0 );
if( randFloat() < 0.05f ) {
moon->assign<treent::TextComponent>( font, "I am planet " + to_string( i ) );
}
}
}
void TreentTest::connect( app::WindowRef window )
{
storeConnection( window->getSignalMouseDown().connect( [this]( const MouseEvent &e )
{ mouseDown( e ); } ) );
storeConnection( window->getSignalMouseDrag().connect( [this]( const MouseEvent &e )
{ mouseDrag( e ); } ) );
storeConnection( window->getSignalMouseUp().connect( [this]( const MouseEvent &e )
{ mouseUp( e ); } ) );
}
void TreentTest::mouseDown( MouseEvent event )
{
_mouse_down = true;
_mouse_position = event.getPos();
_mouse_start = event.getPos();
_node_start = _treent_root->getPosition();
}
void TreentTest::mouseDrag( MouseEvent event )
{
_mouse_position = event.getPos();
}
void TreentTest::mouseUp( MouseEvent event )
{
_mouse_down = false;
_mouse_position = event.getPos();
}
void TreentTest::update( double dt )
{
auto delta = _mouse_position - _mouse_start;
_treent_root->setPosition( _node_start + delta );
_treent.systems->update<RotationSystem>( dt );
_treent_root->updateTree( mat4() );
_treent.systems->update<treent::LayeredShapeRenderSystem>( dt );
_treent.systems->update<treent::TextRenderSystem>( dt );
}
void TreentTest::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
_treent.systems->system<treent::LayeredShapeRenderSystem>()->draw();
gl::ScopedAlphaBlend premult( true );
_treent.systems->system<treent::TextRenderSystem>()->draw();
}
<commit_msg>.length -> length( prop )<commit_after>/*
* Copyright (c) 2014 David Wicks, sansumbrella.com
* 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.
*
* 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 "TreentSample.h"
#include "TreentNode.h"
#include "cinder/gl/gl.h"
#include "treent/LayeredShapeRenderSystem.h"
#include "treent/TextRenderSystem.h"
#include "treent/ShapeComponent.h"
#include "cinder/Rand.h"
#include <memory>
#define USE_SMOOTHED_ROTATION 1
using namespace pockets;
using namespace cinder;
using namespace cinder::app;
using namespace std;
namespace
{
struct RotationComponent : treent::Component<RotationComponent>
{
RotationComponent() = default;
RotationComponent( float rate ):
rate( rate )
{}
float rate = 1.0f;
};
class RotationSystem : public treent::System<RotationSystem>
{
public:
void update( treent::EntityManagerRef entities, treent::EventManagerRef events, double dt ) override
{
for( auto entity : entities->entities_with_components<RotationComponent, treent::LocationComponent>() )
{
treent::LocationComponentRef location;
shared_ptr<RotationComponent> rotation;
entity.unpack( location, rotation );
#if USE_SMOOTHED_ROTATION
// lerp(curr, target, 1.0-pow(1.0-rate, targetFPS*dt)
// smoothed step
float target = location->rotation + rotation->rate / 60.0;
location->rotation = lerp<float>( location->rotation, target, 1.0 - pow(0.01, 60.0 * dt) );
#else
location->rotation += rotation->rate * dt;
#endif
}
}
};
treent::TreentNodeRef addOrbiter( treent::TreentNodeRef center, bool warm, float max_distance, int depth ) {
float size = length( center->getSize() ) / 5.0f;
auto moon = center->createChild<treent::TreentNode>();
moon->setSize( vec2( 1.0f ) * size );
vec2 position = randVec2f() * randFloat( max_distance / 4, max_distance );
moon->setPosition( position );
moon->setRegistrationPoint( -position );
auto shape = moon->assign<treent::ShapeComponent>();
auto color = warm ? ColorA( CM_HSV, randFloat( 0.02f, 0.18f ), 1.0f, 1.0f, 1.0f ) : ColorA( CM_HSV, randFloat( 0.45f, 0.62f ), 1.0f, 0.7f, 1.0f );
shape->setAsBox( Rectf( -size, -size, size, size ) );
shape->setColor( color );
moon->assign<treent::LayeredShapeRenderData>( shape, moon->getTransform(), depth );
moon->assign<RotationComponent>( lmap<float>( length( position ), 0.0f, length( vec2(getWindowSize()) ), 1.0f, 0.1f ) );
if( size > 10.0f && randFloat() < 0.5f ) {
addOrbiter( moon, !warm, max_distance / 8, depth + 1 );
}
return moon;
}
} // anon::
void TreentTest::setup()
{
_treent.systems->add<treent::LayeredShapeRenderSystem>();
_treent.systems->add<treent::TextRenderSystem>();
_treent.systems->add<RotationSystem>();
_treent.systems->configure();
_treent_root = _treent.createRoot2D();
_treent_root->setPosition( getWindowCenter() );
_treent_root->setSize( getWindowSize() / 4 );
auto shape = _treent_root->assign<treent::ShapeComponent>();
shape->setAsCircle( vec2( 1.0f ) * (getWindowWidth() / 6.0f), 0, M_PI * 2, 6 ); // hexagon
_treent_root->assign<treent::LayeredShapeRenderData>( shape, _treent_root->getTransform(), 0 );
Font arial( "Arial Bold", 24.0f );
gl::TextureFontRef font = gl::TextureFont::create( arial, gl::TextureFont::Format().premultiply() );
for( int i = 0; i < 1000; ++i )
{
auto moon = addOrbiter( _treent_root, true, length( vec2( getWindowSize() ) ), 0 );
if( randFloat() < 0.05f ) {
moon->assign<treent::TextComponent>( font, "I am planet " + to_string( i ) );
}
}
}
void TreentTest::connect( app::WindowRef window )
{
storeConnection( window->getSignalMouseDown().connect( [this]( const MouseEvent &e )
{ mouseDown( e ); } ) );
storeConnection( window->getSignalMouseDrag().connect( [this]( const MouseEvent &e )
{ mouseDrag( e ); } ) );
storeConnection( window->getSignalMouseUp().connect( [this]( const MouseEvent &e )
{ mouseUp( e ); } ) );
}
void TreentTest::mouseDown( MouseEvent event )
{
_mouse_down = true;
_mouse_position = event.getPos();
_mouse_start = event.getPos();
_node_start = _treent_root->getPosition();
}
void TreentTest::mouseDrag( MouseEvent event )
{
_mouse_position = event.getPos();
}
void TreentTest::mouseUp( MouseEvent event )
{
_mouse_down = false;
_mouse_position = event.getPos();
}
void TreentTest::update( double dt )
{
auto delta = _mouse_position - _mouse_start;
_treent_root->setPosition( _node_start + delta );
_treent.systems->update<RotationSystem>( dt );
_treent_root->updateTree( mat4() );
_treent.systems->update<treent::LayeredShapeRenderSystem>( dt );
_treent.systems->update<treent::TextRenderSystem>( dt );
}
void TreentTest::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
_treent.systems->system<treent::LayeredShapeRenderSystem>()->draw();
gl::ScopedAlphaBlend premult( true );
_treent.systems->system<treent::TextRenderSystem>()->draw();
}
<|endoftext|> |
<commit_before>#include "PendingOperation.hpp"
#include <QLoggingCategory>
namespace Telegram {
PendingOperation::PendingOperation(QObject *parent) :
QObject(parent),
m_finished(false),
m_succeeded(true)
{
}
bool PendingOperation::isFinished() const
{
return m_finished;
}
bool PendingOperation::isSucceeded() const
{
return m_finished && m_succeeded;
}
QString PendingOperation::c_text()
{
return QStringLiteral("text");
}
QVariantHash PendingOperation::errorDetails() const
{
return m_errorDetails;
}
void PendingOperation::startLater()
{
QMetaObject::invokeMethod(this, "start", Qt::QueuedConnection);
}
void PendingOperation::runAfter(PendingOperation *operation)
{
connect(operation, &PendingOperation::succeeded, this, &PendingOperation::start);
connect(operation, &PendingOperation::failed, this, &PendingOperation::onPreviousFailed);
if (operation->isFinished()) {
if (operation->isSucceeded()) {
startLater();
} else {
setDelayedFinishedWithError(operation->errorDetails());
}
}
}
void PendingOperation::setFinished()
{
qDebug() << "finished" << this;
if (m_finished) {
qWarning() << "Operation is already finished" << this;
return;
}
m_finished = true;
if (m_succeeded) {
emit succeeded(this);
}
emit finished(this);
}
void PendingOperation::setFinishedWithError(const QVariantHash &details)
{
qDebug() << "finished with error" << this << details;
m_succeeded = false;
m_errorDetails = details;
emit failed(this, details);
setFinished();
}
void PendingOperation::setDelayedFinishedWithError(const QVariantHash &details)
{
QMetaObject::invokeMethod(this, "setFinishedWithError", Qt::QueuedConnection, Q_ARG(QVariantHash, details)); // Invoke after return
}
void PendingOperation::clearResult()
{
m_finished = false;
m_succeeded = true;
m_errorDetails.clear();
}
void PendingOperation::onPreviousFailed(PendingOperation *operation, const QVariantHash &details)
{
Q_UNUSED(operation)
setFinishedWithError(details);
}
} // Telegram namespace
<commit_msg>PendingOperation: Emit failed() only after operation is marked as finished<commit_after>#include "PendingOperation.hpp"
#include <QLoggingCategory>
namespace Telegram {
PendingOperation::PendingOperation(QObject *parent) :
QObject(parent),
m_finished(false),
m_succeeded(true)
{
}
bool PendingOperation::isFinished() const
{
return m_finished;
}
bool PendingOperation::isSucceeded() const
{
return m_finished && m_succeeded;
}
QString PendingOperation::c_text()
{
return QStringLiteral("text");
}
QVariantHash PendingOperation::errorDetails() const
{
return m_errorDetails;
}
void PendingOperation::startLater()
{
QMetaObject::invokeMethod(this, "start", Qt::QueuedConnection);
}
void PendingOperation::runAfter(PendingOperation *operation)
{
connect(operation, &PendingOperation::succeeded, this, &PendingOperation::start);
connect(operation, &PendingOperation::failed, this, &PendingOperation::onPreviousFailed);
if (operation->isFinished()) {
if (operation->isSucceeded()) {
startLater();
} else {
setDelayedFinishedWithError(operation->errorDetails());
}
}
}
void PendingOperation::setFinished()
{
qDebug() << "finished" << this;
if (m_finished) {
qWarning() << "Operation is already finished" << this;
return;
}
m_finished = true;
if (m_succeeded) {
emit succeeded(this);
} else {
emit failed(this, m_errorDetails);
}
emit finished(this);
}
void PendingOperation::setFinishedWithError(const QVariantHash &details)
{
qDebug() << "finished with error" << this << details;
m_succeeded = false;
m_errorDetails = details;
setFinished();
}
void PendingOperation::setDelayedFinishedWithError(const QVariantHash &details)
{
QMetaObject::invokeMethod(this, "setFinishedWithError", Qt::QueuedConnection, Q_ARG(QVariantHash, details)); // Invoke after return
}
void PendingOperation::clearResult()
{
m_finished = false;
m_succeeded = true;
m_errorDetails.clear();
}
void PendingOperation::onPreviousFailed(PendingOperation *operation, const QVariantHash &details)
{
Q_UNUSED(operation)
setFinishedWithError(details);
}
} // Telegram namespace
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <MD5Builder.h>
uint8_t hex_char_to_byte(uint8_t c){
return (c >= 'a' && c <= 'f') ? (c - ((uint8_t)'a' - 0xa)) :
(c >= 'A' && c <= 'F') ? (c - ((uint8_t)'A' - 0xA)) :
(c >= '0' && c<= '9') ? (c - (uint8_t)'0') : 0;
}
void MD5Builder::begin(void){
memset(_buf, 0x00, 16);
MD5Init(&_ctx);
}
void MD5Builder::add(const uint8_t * data, const uint16_t len){
MD5Update(&_ctx, data, len);
}
void MD5Builder::addHexString(const char * data){
uint16_t i, len = strlen(data);
uint8_t * tmp = (uint8_t*)malloc(len/2);
if(tmp == NULL) {
return;
}
for(i=0; i<len; i+=2) {
uint8_t high = hex_char_to_byte(data[i]);
uint8_t low = hex_char_to_byte(data[i+1]);
tmp[i/2] = (high & 0x0F) << 4 | (low & 0x0F);
}
add(tmp, len/2);
free(tmp);
}
bool MD5Builder::addStream(Stream & stream, const size_t maxLen){
const int buf_size = 512;
int maxLengthLeft = maxLen;
uint8_t * buf = (uint8_t*) malloc(buf_size);
if(!buf) {
return false;
}
int bytesAvailable = stream.available();
while((bytesAvailable > 0) && (maxLengthLeft > 0)) {
// determine number of bytes to read
int readBytes = bytesAvailable;
if(readBytes > maxLengthLeft) {
readBytes = maxLengthLeft ; // read only until max_len
}
if(readBytes > buf_size) {
readBytes = buf_size; // not read more the buffer can handle
}
// read data and check if we got something
int numBytesRead = stream.readBytes(buf, readBytes);
if(numBytesRead< 1) {
return false;
}
// Update MD5 with buffer payload
MD5Update(&_ctx, buf, numBytesRead);
yield(); // time for network streams
// update available number of bytes
maxLengthLeft -= numBytesRead;
bytesAvailable = stream.available();
}
free(buf);
return true;
}
void MD5Builder::calculate(void){
MD5Final(_buf, &_ctx);
}
void MD5Builder::getBytes(uint8_t * output){
memcpy(output, _buf, 16);
}
void MD5Builder::getChars(char * output){
for(uint8_t i = 0; i < 16; i++) {
sprintf(output + (i * 2), "%02x", _buf[i]);
}
}
String MD5Builder::toString(void){
char out[33];
getChars(out);
return String(out);
}
<commit_msg>Fix for MD5 leak bug, issue #7195 (#7197)<commit_after>#include <Arduino.h>
#include <MD5Builder.h>
uint8_t hex_char_to_byte(uint8_t c){
return (c >= 'a' && c <= 'f') ? (c - ((uint8_t)'a' - 0xa)) :
(c >= 'A' && c <= 'F') ? (c - ((uint8_t)'A' - 0xA)) :
(c >= '0' && c<= '9') ? (c - (uint8_t)'0') : 0;
}
void MD5Builder::begin(void){
memset(_buf, 0x00, 16);
MD5Init(&_ctx);
}
void MD5Builder::add(const uint8_t * data, const uint16_t len){
MD5Update(&_ctx, data, len);
}
void MD5Builder::addHexString(const char * data){
uint16_t i, len = strlen(data);
uint8_t * tmp = (uint8_t*)malloc(len/2);
if(tmp == NULL) {
return;
}
for(i=0; i<len; i+=2) {
uint8_t high = hex_char_to_byte(data[i]);
uint8_t low = hex_char_to_byte(data[i+1]);
tmp[i/2] = (high & 0x0F) << 4 | (low & 0x0F);
}
add(tmp, len/2);
free(tmp);
}
bool MD5Builder::addStream(Stream & stream, const size_t maxLen){
const int buf_size = 512;
int maxLengthLeft = maxLen;
uint8_t * buf = (uint8_t*) malloc(buf_size);
if(!buf) {
return false;
}
int bytesAvailable = stream.available();
while((bytesAvailable > 0) && (maxLengthLeft > 0)) {
// determine number of bytes to read
int readBytes = bytesAvailable;
if(readBytes > maxLengthLeft) {
readBytes = maxLengthLeft ; // read only until max_len
}
if(readBytes > buf_size) {
readBytes = buf_size; // not read more the buffer can handle
}
// read data and check if we got something
int numBytesRead = stream.readBytes(buf, readBytes);
if(numBytesRead< 1) {
free(buf); // release the buffer
return false;
}
// Update MD5 with buffer payload
MD5Update(&_ctx, buf, numBytesRead);
yield(); // time for network streams
// update available number of bytes
maxLengthLeft -= numBytesRead;
bytesAvailable = stream.available();
}
free(buf);
return true;
}
void MD5Builder::calculate(void){
MD5Final(_buf, &_ctx);
}
void MD5Builder::getBytes(uint8_t * output){
memcpy(output, _buf, 16);
}
void MD5Builder::getChars(char * output){
for(uint8_t i = 0; i < 16; i++) {
sprintf(output + (i * 2), "%02x", _buf[i]);
}
}
String MD5Builder::toString(void){
char out[33];
getChars(out);
return String(out);
}
<|endoftext|> |
<commit_before>#include <ecl/map.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
#include <ostream>
enum class E
{
e1
, e2
, e3
, e4
, e5
, e6
, e7
, e8
, e9
, e10
};
std::ostream& operator<<(std::ostream& s, E e)
{
switch(e)
{
case E::e1 : s << "e1" ; break;
case E::e2 : s << "e2" ; break;
case E::e3 : s << "e3" ; break;
case E::e4 : s << "e4" ; break;
case E::e5 : s << "e5" ; break;
case E::e6 : s << "e6" ; break;
case E::e7 : s << "e7" ; break;
case E::e8 : s << "e8" ; break;
case E::e9 : s << "e9" ; break;
case E::e10: s << "e10"; break;
default : break;
}
return s;
}
using key_type = E;
using value_type = std::uint32_t;
using map_t = ecl::map<key_type, value_type, 8>;
auto m0 = ecl::create_map<key_type, value_type>
(
std::make_pair(E::e1, 1u)
, std::make_pair(E::e2, 2u)
, std::make_pair(E::e3, 4u)
, std::make_pair(E::e3, 3u) // overwrite E::e3 element
);
template<typename T>
void fill_map_ilist(std::string prefix, T& m)
{
std::cout << ">>> Insert to map" << std::endl;
m.insert(
{
{ E::e1 , 1 }
, { E::e2 , 3 }
, { E::e3 , 5 }
, { E::e4 , 7 }
, { E::e5 , 9 }
, { E::e6 , 11 }
, { E::e7 , 13 }
, { E::e8 , 15 }
, { E::e9 , 17 }
, { E::e10 , 19 }
});
dump_map(prefix, m);
}
template<typename T>
void fill_map_operator(std::string prefix, T& m)
{
std::cout << ">>> Assign via operator[]" << std::endl;
m[E::e1] = 5;
m[E::e2] = 10;
m[E::e3] = 15;
m[E::e4] = 20;
m[E::e5] = 25;
m[E::e6] = 30;
m[E::e7] = 35;
m[E::e8] = 40;
m[E::e9] = 45;
m[E::e10] = 50;
dump_map(prefix, m);
// m.print();
}
template<typename T>
void dump_map(std::string prefix, T& m)
{
std::cout << ">>> Dump map" << std::endl;
std::cout << prefix << " map elements count: " << m.size() << std::endl;
std::cout << prefix << " range-for interation over map: ";
for(auto& p : m)
{
std::cout << "(" << p.first << ":" << p.second << ") ";
}
std::cout << std::endl;
std::cout << prefix << ".at(E::e1): " << m.at(E::e1) << std::endl;
std::cout << prefix << ".at(E::e2): " << m.at(E::e2) << std::endl;
std::cout << prefix << ".at(E::e3): " << m.at(E::e3) << std::endl;
std::cout << prefix << ".at(E::e4): " << m.at(E::e4) << std::endl;
std::cout << prefix << ".at(E::e5): " << m.at(E::e5) << std::endl;
std::cout << prefix << ".at(E::e6): " << m.at(E::e6) << std::endl;
std::cout << prefix << ".at(E::e7): " << m.at(E::e7) << std::endl;
std::cout << prefix << ".at(E::e8): " << m.at(E::e8) << std::endl;
std::cout << prefix << ".at(E::e9): " << m.at(E::e9) << std::endl;
std::cout << prefix << ".at(E::e10): " << m.at(E::e10) << std::endl;
}
template<typename T>
void erase_map_by_key(std::string prefix, T& m)
{
std::cout << ">>> Erase map by keys" << std::endl;
std::cout << prefix << ".erase(E::e1) : " << m.erase(E::e1) << std::endl;
std::cout << prefix << ".erase(E::e2) : " << m.erase(E::e2) << std::endl;
std::cout << prefix << ".erase(E::e3) : " << m.erase(E::e3) << std::endl;
std::cout << prefix << ".erase(E::e4) : " << m.erase(E::e4) << std::endl;
std::cout << prefix << ".erase(E::e5) : " << m.erase(E::e5) << std::endl;
std::cout << prefix << ".erase(E::e6) : " << m.erase(E::e6) << std::endl;
std::cout << prefix << ".erase(E::e7) : " << m.erase(E::e7) << std::endl;
std::cout << prefix << ".erase(E::e8) : " << m.erase(E::e8) << std::endl;
std::cout << prefix << ".erase(E::e9) : " << m.erase(E::e9) << std::endl;
std::cout << prefix << ".erase(E::e10): " << m.erase(E::e10) << std::endl;
dump_map(prefix, m);
}
template<typename T>
void erase_map_by_irange(std::string prefix, T& m)
{
std::cout << ">>> Erase map by iterator range" << std::endl;
m.erase(m.begin(), m.end());
dump_map(prefix, m);
}
template<typename T>
void erase_map_by_iterator(std::string prefix, T& m)
{
std::cout << ">>> Erase map by iterator" << std::endl;
typename T::const_iterator it = m.begin();
std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
// it = m.begin();
// std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
dump_map(prefix, m);
}
int main(int, char**, char**)
{
map_t m1
{
{ E::e1 , 2 }
, { E::e2 , 4 }
, { E::e3 , 6 }
, { E::e4 , 8 }
, { E::e5 , 10 }
, { E::e6 , 12 }
, { E::e7 , 14 }
, { E::e8 , 16 }
, { E::e9 , 18 }
, { E::e10 , 20 }
};
dump_map("m1", m1);
erase_map_by_key("m1", m1);
fill_map_ilist("m1", m1);
erase_map_by_irange("m1", m1);
// map_t m1;
fill_map_operator("m1", m1);
erase_map_by_iterator("m1", m1);
return 0;
}
<commit_msg>Map example: erase via iterator assignment and iterator increment.<commit_after>#include <ecl/map.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
#include <ostream>
enum class E
{
e1
, e2
, e3
, e4
, e5
, e6
, e7
, e8
, e9
, e10
};
std::ostream& operator<<(std::ostream& s, E e)
{
switch(e)
{
case E::e1 : s << "e1" ; break;
case E::e2 : s << "e2" ; break;
case E::e3 : s << "e3" ; break;
case E::e4 : s << "e4" ; break;
case E::e5 : s << "e5" ; break;
case E::e6 : s << "e6" ; break;
case E::e7 : s << "e7" ; break;
case E::e8 : s << "e8" ; break;
case E::e9 : s << "e9" ; break;
case E::e10: s << "e10"; break;
default : break;
}
return s;
}
using key_type = E;
using value_type = std::uint32_t;
using map_t = ecl::map<key_type, value_type, 8>;
auto m0 = ecl::create_map<key_type, value_type>
(
std::make_pair(E::e1, 1u)
, std::make_pair(E::e2, 2u)
, std::make_pair(E::e3, 4u)
, std::make_pair(E::e3, 3u) // overwrite E::e3 element
);
template<typename T>
void fill_map_ilist(std::string prefix, T& m)
{
std::cout << ">>> Insert to map" << std::endl;
m.insert(
{
{ E::e1 , 1 }
, { E::e2 , 3 }
, { E::e3 , 5 }
, { E::e4 , 7 }
, { E::e5 , 9 }
, { E::e6 , 11 }
, { E::e7 , 13 }
, { E::e8 , 15 }
, { E::e9 , 17 }
, { E::e10 , 19 }
});
dump_map(prefix, m);
}
template<typename T>
void fill_map_operator(std::string prefix, T& m)
{
std::cout << ">>> Assign via operator[]" << std::endl;
m[E::e1] = 5;
m[E::e2] = 10;
m[E::e3] = 15;
m[E::e4] = 20;
m[E::e5] = 25;
m[E::e6] = 30;
m[E::e7] = 35;
m[E::e8] = 40;
m[E::e9] = 45;
m[E::e10] = 50;
dump_map(prefix, m);
// m.print();
}
template<typename T>
void dump_map(std::string prefix, T& m)
{
std::cout << ">>> Dump map" << std::endl;
std::cout << prefix << " map elements count: " << m.size() << std::endl;
std::cout << prefix << " range-for interation over map: ";
for(auto& p : m)
{
std::cout << "(" << p.first << ":" << p.second << ") ";
}
std::cout << std::endl;
std::cout << prefix << ".at(E::e1): " << m.at(E::e1) << std::endl;
std::cout << prefix << ".at(E::e2): " << m.at(E::e2) << std::endl;
std::cout << prefix << ".at(E::e3): " << m.at(E::e3) << std::endl;
std::cout << prefix << ".at(E::e4): " << m.at(E::e4) << std::endl;
std::cout << prefix << ".at(E::e5): " << m.at(E::e5) << std::endl;
std::cout << prefix << ".at(E::e6): " << m.at(E::e6) << std::endl;
std::cout << prefix << ".at(E::e7): " << m.at(E::e7) << std::endl;
std::cout << prefix << ".at(E::e8): " << m.at(E::e8) << std::endl;
std::cout << prefix << ".at(E::e9): " << m.at(E::e9) << std::endl;
std::cout << prefix << ".at(E::e10): " << m.at(E::e10) << std::endl;
}
template<typename T>
void erase_map_by_key(std::string prefix, T& m)
{
std::cout << ">>> Erase map by keys" << std::endl;
std::cout << prefix << ".erase(E::e1) : " << m.erase(E::e1) << std::endl;
std::cout << prefix << ".erase(E::e2) : " << m.erase(E::e2) << std::endl;
std::cout << prefix << ".erase(E::e3) : " << m.erase(E::e3) << std::endl;
std::cout << prefix << ".erase(E::e4) : " << m.erase(E::e4) << std::endl;
std::cout << prefix << ".erase(E::e5) : " << m.erase(E::e5) << std::endl;
std::cout << prefix << ".erase(E::e6) : " << m.erase(E::e6) << std::endl;
std::cout << prefix << ".erase(E::e7) : " << m.erase(E::e7) << std::endl;
std::cout << prefix << ".erase(E::e8) : " << m.erase(E::e8) << std::endl;
std::cout << prefix << ".erase(E::e9) : " << m.erase(E::e9) << std::endl;
std::cout << prefix << ".erase(E::e10): " << m.erase(E::e10) << std::endl;
dump_map(prefix, m);
}
template<typename T>
void erase_map_by_irange(std::string prefix, T& m)
{
std::cout << ">>> Erase map by iterator range" << std::endl;
m.erase(m.begin(), m.end());
dump_map(prefix, m);
}
template<typename T>
void erase_map_by_iterator_increment(std::string prefix, T& m)
{
std::cout << ">>> Erase map by iterator (increment)" << std::endl;
typename T::const_iterator it = m.begin();
std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
m.erase(it++); std::cout << it->first << ":" << it->second << std::endl;
// it = m.begin();
// std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
// it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
dump_map(prefix, m);
}
template<typename T>
void erase_map_by_iterator_assign_return(std::string prefix, T& m)
{
std::cout << ">>> Erase map by iterator (assign return)" << std::endl;
typename T::const_iterator it = m.begin();
std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
it = m.erase(it); std::cout << it->first << ":" << it->second << std::endl;
dump_map(prefix, m);
}
int main(int, char**, char**)
{
map_t m1
{
{ E::e1 , 2 }
, { E::e2 , 4 }
, { E::e3 , 6 }
, { E::e4 , 8 }
, { E::e5 , 10 }
, { E::e6 , 12 }
, { E::e7 , 14 }
, { E::e8 , 16 }
, { E::e9 , 18 }
, { E::e10 , 20 }
};
dump_map("m1", m1);
erase_map_by_key("m1", m1);
fill_map_ilist("m1", m1);
erase_map_by_irange("m1", m1);
// map_t m1;
fill_map_operator("m1", m1);
erase_map_by_iterator_increment("m1", m1);
fill_map_operator("m1", m1);
erase_map_by_iterator_assign_return("m1", m1);
return 0;
}
<|endoftext|> |
<commit_before>#include <cstddef>
#include <cstdlib>
#include <hls_video.h>
#include "Accel.h"
#include "AccelSchedule.h"
#include "AccelTest.h"
#include "Dense.h"
#include "ZipIO.h"
#include "ParamIO.h"
#include "DataIO.h"
#include "Timer.h"
int main(int argc, char** argv) {
if (argc < 2) {
printf ("Give number of character to produce as 1st arg\n");
printf ("Give the initial srting as 2nd arg optional\n");
return 0;
}
const unsigned n_char = std::stoi(argv[1]);
bool Init = false;
char* str_init = NULL;
if (argc == 3) {
Init = true;
str_init = argv[2]; // *ML: cant loas text with ' '
printf("* Initial string is %s\n", str_init);
}
// print some config numbers
printf ("* WT_WORDS = %u\n", WT_WORDS);
printf ("* BIAS_WORDS = %u\n", BIAS_WORDS);
// Load input data
//printf ("## Loading input data ##\n");
// ML: hidden state can be initialized by a given string
// Load parameters
printf ("## Loading parameters ##\n");
Params params(get_root_dir() + "/params/rnn_parameters.zip");
// ---------------------------------------------------------------------
// allocate and binarize all weights
// ---------------------------------------------------------------------
Word* wt[N_LAYERS];
Word* b[N_LAYERS];
for (unsigned l = 0; l < N_LAYERS; ++l) {
const unsigned M = M_tab[l];
const unsigned N = N_tab[l];
if (layer_is_rnn(l+1)) {
wt[l] = new Word[(M+N)*4*N / WORD_SIZE];
b[l] = new Word[4*N / WORD_SIZE];
}
else {
wt[l] = new Word[M*N / WORD_SIZE]; // ML: RNN layers
b[l] = new Word[N / WORD_SIZE];
}
if (layer_is_rnn(l+1)) {
for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) {
// ML: set in_to weight and hid_to weight
const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]);
const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]);
set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l);
// ML: set bias
const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]);
set_rnn_bias_array(b[l], bias, l+1, w_l);
}
} else {
const float* weights = params.float_data(widx_tab[16]);
set_dense_weight_array(wt[l], weights, l+1);
const float* bias = params.float_data(bidx_tab[8]);
set_dense_bias_array(b[l], bias, l+1);
}
}
// ---------------------------------------------------------------------
// // compute accelerator schedule (divides up weights)
// ---------------------------------------------------------------------
AccelSchedule layer_sched[N_LAYERS];
for (unsigned l = 0; l < N_LAYERS; ++l) {
compute_accel_schedule(
wt[l], b[l],
M_tab[l], N_tab[l], T_tab[l],
layer_sched[l], l
);
}
// allocate memories for data i/o for the accelerator
Word* data_i = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) ); // ML: need to be modified!
Word* data_o = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) );
if (!data_i || !data_o) {
fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__);
return (-2);
}
unsigned n_errors = 0;
printf("## Initialing the RNN\n");
if (Init) {
unsigned i = 0;
while (str_init[i] != '\0') {
set_char_to_word(data_i, str_init[i]);
for (unsigned l = 1; l <= 3; ++l) {
const unsigned M = M_tab[l-1];
const unsigned N = N_tab[l-1];
dense_layer(
data_i, data_o,
l-1,
(l==1) ? 1 : 0, // input_words
layer_sched[l][0].n_inputs,
layer_sched[l][0].n_outputs,
layer_sched[l][0].wt,
layer_sched[l][0].b
);
}
i++;
}
}
printf ("## Running RNN for %d characters\n", n_char);
//--------------------------------------------------------------
// Run RNN
//--------------------------------------------------------------
// ML: load an arbitrary input character [1, 0. 0, ..., 0]
for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) {
if (i == 0) {
data_i[i] = 0;
DATA start_seed = 1;
data_i[i](15,0) = start_seed(15,0);
} else {
data_i[i] = 0;
}
}
for (unsigned n = 0; n < n_char; ++n) {
//------------------------------------------------------------
// Execute RNN layers
//------------------------------------------------------------
for (unsigned l = 1; l <= 3; ++l) {
const unsigned M = M_tab[l-1];
const unsigned N = N_tab[l-1];
dense_layer(
data_i, data_o,
l-1,
(n==0 && l==1 && (~Init)) ? 1 : 0, // input_words
layer_sched[l][0].n_inputs,
layer_sched[l][0].n_outputs,
layer_sched[l][0].wt,
layer_sched[l][0].b
);
}
//------------------------------------------------------------
// Execute the prediciton
//------------------------------------------------------------
int prediction = 0;
int max = -512; // ML: may shoulb be less
for (unsigned i = 0; i < VOCAB_SIZE; i++) {
DATA temp;
int add = i / DATA_PER_WORD;
int off = i % DATA_PER_WORD;
temp(15,0) = data_o[add]((off+1)*16-1,off*16);
if (temp.to_int() > max) {
max = temp;
prediction = i;
}
}
assert(prediction >= 0 && prediction <= 63);
std::cout<<vocab[prediction];
}
printf("\n");
/*printf ("\n");
printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs);
printf ("\n");
printf ("Total accel runtime = %10.4f seconds\n", total_time());
printf ("\n");*/
MEM_FREE( data_o );
MEM_FREE( data_i );
for (unsigned n = 0; n < N_LAYERS; ++n) {
delete[] wt[n];
delete[] b[n];
}
return 0;
}
<commit_msg>fixed a bug<commit_after>#include <cstddef>
#include <cstdlib>
#include <hls_video.h>
#include "Accel.h"
#include "AccelSchedule.h"
#include "AccelTest.h"
#include "Dense.h"
#include "ZipIO.h"
#include "ParamIO.h"
#include "DataIO.h"
#include "Timer.h"
int main(int argc, char** argv) {
if (argc < 2) {
printf ("Give number of character to produce as 1st arg\n");
printf ("Give the initial srting as 2nd arg optional\n");
return 0;
}
const unsigned n_char = std::stoi(argv[1]);
bool Init = false;
char* str_init = NULL;
if (argc == 3) {
Init = true;
str_init = argv[2]; // *ML: cant loas text with ' '
printf("* Initial string is %s\n", str_init);
}
// print some config numbers
printf ("* WT_WORDS = %u\n", WT_WORDS);
printf ("* BIAS_WORDS = %u\n", BIAS_WORDS);
// Load input data
//printf ("## Loading input data ##\n");
// ML: hidden state can be initialized by a given string
// Load parameters
printf ("## Loading parameters ##\n");
Params params(get_root_dir() + "/params/rnn_parameters.zip");
// ---------------------------------------------------------------------
// allocate and binarize all weights
// ---------------------------------------------------------------------
Word* wt[N_LAYERS];
Word* b[N_LAYERS];
for (unsigned l = 0; l < N_LAYERS; ++l) {
const unsigned M = M_tab[l];
const unsigned N = N_tab[l];
if (layer_is_rnn(l+1)) {
wt[l] = new Word[(M+N)*4*N / WORD_SIZE];
b[l] = new Word[4*N / WORD_SIZE];
}
else {
wt[l] = new Word[M*N / WORD_SIZE]; // ML: RNN layers
b[l] = new Word[N / WORD_SIZE];
}
if (layer_is_rnn(l+1)) {
for (unsigned w_l = 0; w_l < N_W_LAYERS; ++w_l) {
// ML: set in_to weight and hid_to weight
const float* weights_in = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l]);
const float* weights_hid = params.float_data(widx_tab[l*N_W_LAYERS*2 + 2*w_l +1]);
set_rnn_weight_array(wt[l], weights_in, weights_hid, l+1, w_l);
// ML: set bias
const float* bias = params.float_data(bidx_tab[l*N_W_LAYERS + w_l]);
set_rnn_bias_array(b[l], bias, l+1, w_l);
}
} else {
const float* weights = params.float_data(widx_tab[16]);
set_dense_weight_array(wt[l], weights, l+1);
const float* bias = params.float_data(bidx_tab[8]);
set_dense_bias_array(b[l], bias, l+1);
}
}
// ---------------------------------------------------------------------
// // compute accelerator schedule (divides up weights)
// ---------------------------------------------------------------------
AccelSchedule layer_sched[N_LAYERS];
for (unsigned l = 0; l < N_LAYERS; ++l) {
compute_accel_schedule(
wt[l], b[l],
M_tab[l], N_tab[l], T_tab[l],
layer_sched[l], l
);
}
// allocate memories for data i/o for the accelerator
Word* data_i = (Word*) MEM_ALLOC( DMEM_WORDS * sizeof(Word) ); // ML: need to be modified!
Word* data_o = (Word*) MEM_ALLOC( DMEM_O_WORDS * sizeof(Word) );
if (!data_i || !data_o) {
fprintf (stderr, "**** ERROR: Alloc failed in %s\n", __FILE__);
return (-2);
}
unsigned n_errors = 0;
printf("## Initialing the RNN\n");
if (Init) {
unsigned i = 0;
while (str_init[i] != '\0') {
set_char_to_word(data_i, str_init[i]);
for (unsigned l = 1; l <= 3; ++l) {
const unsigned M = M_tab[l-1];
const unsigned N = N_tab[l-1];
dense_layer(
data_i, data_o,
l-1,
(l==1) ? 1 : 0, // input_words
layer_sched[l-1][0].n_inputs,
layer_sched[l-1][0].n_outputs,
layer_sched[l-1][0].wt,
layer_sched[l-1][0].b
);
}
i++;
}
}
printf ("## Running RNN for %d characters\n", n_char);
//--------------------------------------------------------------
// Run RNN
//--------------------------------------------------------------
// ML: load an arbitrary input character [1, 0. 0, ..., 0]
for (unsigned i = 0; i < VOCAB_SIZE/DATA_PER_WORD; ++i) {
if (i == 0) {
data_i[i] = 0;
DATA start_seed = 1;
data_i[i](15,0) = start_seed(15,0);
} else {
data_i[i] = 0;
}
}
for (unsigned n = 0; n < n_char; ++n) {
//------------------------------------------------------------
// Execute RNN layers
//------------------------------------------------------------
for (unsigned l = 1; l <= 3; ++l) {
const unsigned M = M_tab[l-1];
const unsigned N = N_tab[l-1];
dense_layer(
data_i, data_o,
l-1,
(n==0 && l==1 && (~Init)) ? 1 : 0, // input_words
layer_sched[l-1][0].n_inputs,
layer_sched[l-1][0].n_outputs,
layer_sched[l-1][0].wt,
layer_sched[l-1][0].b
);
}
//------------------------------------------------------------
// Execute the prediciton
//------------------------------------------------------------
int prediction = 0;
int max = -512; // ML: may shoulb be less
for (unsigned i = 0; i < VOCAB_SIZE; i++) {
DATA temp;
int add = i / DATA_PER_WORD;
int off = i % DATA_PER_WORD;
temp(15,0) = data_o[add]((off+1)*16-1,off*16);
if (temp.to_int() > max) {
max = temp;
prediction = i;
}
}
assert(prediction >= 0 && prediction <= 63);
std::cout<<vocab[prediction];
}
printf("\n");
/*printf ("\n");
printf ("Errors: %u (%4.2f%%)\n", n_errors, float(n_errors)*100/n_imgs);
printf ("\n");
printf ("Total accel runtime = %10.4f seconds\n", total_time());
printf ("\n");*/
MEM_FREE( data_o );
MEM_FREE( data_i );
for (unsigned n = 0; n < N_LAYERS; ++n) {
delete[] wt[n];
delete[] b[n];
}
return 0;
}
<|endoftext|> |
<commit_before>/** \file restart_zts
* \brief Restart the docker container with the Zotero Translation Server
* \author Johannes Riedl
*/
/*
Copyright (C) 2020, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sstream>
#include "ExecUtil.h"
#include "StringUtil.h"
#include "WebUtil.h"
#include "util.h"
namespace {
void SendHeaders() {
std::cout << "Content-Type: text/html; charset=utf-8\r\n\r\n"
<< "<html>\n";
}
void SendTrailer() {
std::cout << "</html>\n";
}
void DisplayRestartButton() {
SendHeaders();
std::cout << "<h2>Restart Zotero Translation Server Service</h2>\n"
<< "<form action=\"\" method=\"post\">\n"
<< "\t<input type=\"submit\" name=\"action\" value=\"Restart\">\n"
<< "</form>\n";
SendTrailer();
}
bool IsRestartActionPresent(std::multimap<std::string, std::string> *cgi_args) {
WebUtil::GetAllCgiArgs(cgi_args);
const auto key_and_value(cgi_args->find("action"));
return key_and_value != cgi_args->cend() and key_and_value->second == "Restart";
}
void OutputZTSStatus() {
const std::string tmp_output(FileUtil::AutoTempFile().getFilePath());
ExecUtil::ExecOrDie("/usr/bin/sudo", { "systemctl", "status", "zts" }, "" /*stdin*/,
tmp_output, tmp_output);
std::ifstream zts_output_file(tmp_output);
if (not zts_output_file)
LOG_ERROR("Could not open " + tmp_output + " for reading\n");
std::stringstream zts_output_istream;
zts_output_istream << zts_output_file.rdbuf();
std::cout << StringUtil::ReplaceString("\n", "<br/>", zts_output_istream.str());
}
void RestartZTS() {
SendHeaders();
std::cout << "<h2>Attempting restart of ZTS...</h2>\n" << std::endl;
bool log_no_decorations_old(logger->getLogNoDecorations());
bool log_strip_call_site_old(logger->getLogStripCallSite());
logger->setLogNoDecorations(true);
logger->setLogStripCallSite(true);
logger->redirectOutput(STDOUT_FILENO);
try {
ExecUtil::ExecOrDie("/usr/bin/sudo", { "systemctl", "restart", "zts" });
OutputZTSStatus();
} catch (const std::runtime_error &error) {
std::cerr << error.what();
}
std::cout << "<h2>Done...</h>\n";
SendTrailer();
logger->redirectOutput(STDERR_FILENO);
logger->setLogNoDecorations(log_no_decorations_old);
logger->setLogStripCallSite(log_strip_call_site_old);
}
} // end unnamed namespace
int Main(int /*argc*/, char */*argv*/[]) {
std::multimap<std::string, std::string> cgi_args;
if (not IsRestartActionPresent(&cgi_args)) {
DisplayRestartButton();
return EXIT_SUCCESS;
}
RestartZTS();
return EXIT_SUCCESS;
}
<commit_msg>Add configureable possibility to switch a different translator branch<commit_after>/** \file restart_zts
* \brief Restart the docker container with the Zotero Translation Server
* \author Johannes Riedl
*/
/*
Copyright (C) 2020,2021, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iostream>
#include <sstream>
#include "ExecUtil.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "WebUtil.h"
#include "util.h"
namespace {
const std::string ZTS_RESTART_CONFIG("/usr/local/var/lib/tuelib/zts_restart.conf");
const std::string ZTS_TRANSLATORS_DIR("/tmp/translators");
void SendHeaders() {
std::cout << "Content-Type: text/html; charset=utf-8\r\n\r\n"
<< "<html>\n";
}
void SendTrailer() {
std::cout << "</html>\n";
}
struct TranslatorsLocationConfig {
std::string name_;
std::string url_;
std::string local_path_;
std::string branch_;
TranslatorsLocationConfig(std::string name = "", std::string url = "",
std::string local_path = "", std::string branch = "") :
name_(name), url_(url), local_path_(local_path), branch_(branch)
{}
};
void GetTranslatorLocationConfigs(const IniFile &ini_file,
std::vector<TranslatorsLocationConfig> * translators_location_configs) {
translators_location_configs->clear();
const std::string location_prefix("Repo_");
for (const auto §ion : ini_file) {
if (StringUtil::StartsWith(section.getSectionName(), location_prefix)) {
TranslatorsLocationConfig translators_location_config;
translators_location_config.name_ = section.getSectionName().substr(location_prefix.length());
translators_location_config.url_ = section.getString("url");
translators_location_config.local_path_ = section.getString("local_path");
translators_location_config.branch_ = section.getString("branch");
translators_location_configs->emplace_back(translators_location_config);
}
}
}
void DisplayRestartAndSelectButtons(const std::vector<TranslatorsLocationConfig> &translators_location_configs) {
SendHeaders();
std::cout << "<h2>Restart Zotero Translation Server Service</h2>\n"
<< "<form action=\"\" method=\"post\">\n";
for (const auto &translators_location_config : translators_location_configs)
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"" + translators_location_config.name_ +"\">\n";
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"Restart\">\n"
<< "</form>\n";
SendTrailer();
}
bool IsRestartActionPresent(const std::multimap<std::string, std::string> &cgi_args) {
const auto key_and_value(cgi_args.find("action"));
return key_and_value != cgi_args.cend() and key_and_value->second == "Restart";
}
void ExecuteAndDumpMessages(const std::string &command, const std::vector<std::string> &args) {
auto auto_temp_file((FileUtil::AutoTempFile()));
const std::string tmp_output(auto_temp_file.getFilePath());
ExecUtil::ExecOrDie(command, args, "" /*stdin*/,
tmp_output, tmp_output);
std::ifstream output_file(tmp_output);
if (not output_file)
LOG_ERROR("Could not open " + tmp_output + " for reading\n");
std::stringstream output_istream;
output_istream << output_file.rdbuf();
std::cout << StringUtil::ReplaceString("\n", "<br/>", output_istream.str());
}
template<typename Function>
void ExecuteAndSendStatus(const std::string &message, Function function) {
SendHeaders();
std::cout << message << std::endl;
bool log_no_decorations_old(logger->getLogNoDecorations());
bool log_strip_call_site_old(logger->getLogStripCallSite());
logger->setLogNoDecorations(true);
logger->setLogStripCallSite(true);
logger->redirectOutput(STDOUT_FILENO);
try {
function();
} catch (const std::runtime_error &error) {
std::cerr << error.what();
}
std::cout << "<h2>Done...</h2>\n";
SendTrailer();
logger->redirectOutput(STDERR_FILENO);
logger->setLogNoDecorations(log_no_decorations_old);
logger->setLogStripCallSite(log_strip_call_site_old);
}
void RestartZTS() {
auto closure = []{
ExecUtil::ExecOrDie("/usr/bin/sudo", { "systemctl", "restart", "zts" });
ExecuteAndDumpMessages("/usr/bin/sudo", { "systemctl", "status", "zts" });
};
ExecuteAndSendStatus("<h2>Trying to restart ZTS Server</h2>", closure);
}
void RelinkTranslatorDirectory(const TranslatorsLocationConfig &translators_location_config) {
auto closure = [&]{ExecuteAndDumpMessages("/usr/bin/sudo",
{ "ln" , "--symbolic", "--force", "--no-dereference",
translators_location_config.local_path_, ZTS_TRANSLATORS_DIR});};
ExecuteAndSendStatus("<h2>Switching to branch " + translators_location_config.name_ + "</h2>",
closure);
}
bool GetSwitchBranch(const std::multimap<std::string, std::string> &cgi_args,
std::vector<TranslatorsLocationConfig> translators_location_configs,
TranslatorsLocationConfig * const translator_location_config) {
const auto key_and_value(cgi_args.find("action"));
if (key_and_value == cgi_args.end())
return false;
const std::string target(key_and_value->second);
auto match(std::find_if(translators_location_configs.begin(),
translators_location_configs.end(),
[&target](const TranslatorsLocationConfig &target_obj)
{return target_obj.name_ == target;}));
if (match == translators_location_configs.end()) {
std::cout << "NO MATCH";
return false;
}
*translator_location_config = *match;
return true;
}
} // end unnamed namespace
int Main(int /*argc*/, char */*argv*/[]) {
std::multimap<std::string, std::string> cgi_args;
WebUtil::GetAllCgiArgs(&cgi_args);
IniFile ini_file(ZTS_RESTART_CONFIG);
std::vector<TranslatorsLocationConfig> translators_location_configs;
GetTranslatorLocationConfigs(ini_file, &translators_location_configs);
if (IsRestartActionPresent(cgi_args)) {
RestartZTS();
return EXIT_SUCCESS;
}
TranslatorsLocationConfig translators_location_config;
if (GetSwitchBranch(cgi_args, translators_location_configs, &translators_location_config)) {
RelinkTranslatorDirectory(translators_location_config);
return EXIT_SUCCESS;
}
DisplayRestartAndSelectButtons(translators_location_configs);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "InternalVolume.h"
template <>
InputParameters validParams<InternalVolume>()
{
InputParameters params = validParams<SideIntegral>();
params.set<bool>("use_displaced_mesh") = true;
return params;
}
InternalVolume::InternalVolume(const std::string & name,
InputParameters parameters)
: SideIntegral( name, parameters )
{}
Real
InternalVolume::computeQpIntegral()
{
return -_q_point[_qp](0)*_normals[_qp](0);
}
<commit_msg>Minor changes<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "InternalVolume.h"
template <>
InputParameters validParams<InternalVolume>()
{
InputParameters params = validParams<SideIntegral>();
params.set<bool>("use_displaced_mesh") = true;
return params;
}
InternalVolume::InternalVolume(const std::string & name,
InputParameters parameters)
: SideIntegral( name, parameters )
{}
// / /
// | |
// | div(F) dV = | F dot n dS
// | |
// / V / dS
//
// with
// F = a field
// n = the normal at the surface
// V = the volume of the domain
// S = the surface of the domain
//
// If we choose F as [x 0 0]^T, then
// div(F) = 1.
// So,
//
// / /
// | |
// | dV = | x * n[0] dS
// | |
// / V / dS
//
// That is, the volume of the domain is the integral over the surface of the domain
// of the x position of the surface times the x-component of the normal of the
// surface.
//
Real
InternalVolume::computeQpIntegral()
{
return -_q_point[_qp](0)*_normals[_qp](0);
}
<|endoftext|> |
<commit_before>/** \brief Utility for deleting partial or entire MARC records based on an input list.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2015-2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <vector>
#include <cstdlib>
#include "BSZUtil.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--input-format=(marc-21|marc-xml)] [--output-format=(marc-21|marc-xml)]"
" deletion_list input_marc21 output_marc21 entire_record_deletion_log\n"
"Record ID's of records that were deleted and not merely modified will be written to \"entire_record_deletion_log\".");
}
/** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids"
* \return True if at least one local section has been deleted, else false.
*/
bool DeleteLocalSections(const std::unordered_set <std::string> &local_deletion_ids, MARC::Record * const record) {
bool modified(false);
std::vector<MARC::Record::iterator> local_block_starts_for_deletion;
for (const auto &local_block_start : record->findStartOfAllLocalDataBlocks()) {
const auto _001_range(record->getLocalTagRange("001", local_block_start));
if (_001_range.size() != 1)
LOG_ERROR("Every local data block has to have exactly one 001 field. (Record: "
+ record->getControlNumber() + ", First field in local block was: "
+ local_block_start->toString() + " - Found "
+ std::to_string(_001_range.size()) + ".)");
const MARC::Subfields subfields(_001_range.front().getSubfields());
const std::string subfield_contents(subfields.getFirstSubfieldWithCode('0'));
if (not StringUtil::StartsWith(subfield_contents, "001 ")
or local_deletion_ids.find(subfield_contents.substr(4)) == local_deletion_ids.end())
continue;
local_block_starts_for_deletion.emplace_back(local_block_start);
modified = true;
}
record->deleteLocalBlocks(local_block_starts_for_deletion);
return modified;
}
void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
const std::unordered_set <std::string> &local_deletion_ids, MARC::Reader * const marc_reader,
MARC::Writer * const marc_writer, File * const entire_record_deletion_log)
{
unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
while (MARC::Record record = marc_reader->read()) {
++total_record_count;
if (title_deletion_ids.find(record.getControlNumber()) != title_deletion_ids.end()) {
++deleted_record_count;
(*entire_record_deletion_log) << record.getControlNumber() << '\n';
} else { // Look for local (LOK) data sets that may need to be deleted.
if (DeleteLocalSections(local_deletion_ids, &record))
++modified_record_count;
marc_writer->write(record);
}
}
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Deleted " << deleted_record_count << " records.\n";
std::cerr << "Modified " << modified_record_count << " records.\n";
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 5)
Usage();
const auto reader_type(MARC::GetOptionalReaderType(&argc, &argv, 1));
const auto writer_type(MARC::GetOptionalWriterType(&argc, &argv, 1));
if (argc != 5)
Usage();
const auto deletion_list(FileUtil::OpenInputFileOrDie(argv[1]));
std::unordered_set<std::string> title_deletion_ids, local_deletion_ids;
BSZUtil::ExtractDeletionIds(deletion_list.get(), &title_deletion_ids, &local_deletion_ids);
const auto marc_reader(MARC::Reader::Factory(argv[2], reader_type));
const auto marc_writer(MARC::Writer::Factory(argv[3], writer_type));
const auto entire_record_deletion_log(FileUtil::OpenForAppendingOrDie(argv[4]));
ProcessRecords(title_deletion_ids, local_deletion_ids, marc_reader.get(), marc_writer.get(), entire_record_deletion_log.get());
return EXIT_SUCCESS;
}
<commit_msg>Added a documentation link.<commit_after>/** \brief Utility for deleting partial or entire MARC records based on an input list.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
* \documentation https://wiki.bsz-bw.de/doku.php?id=v-team:daten:datendienste:sekkor under "Löschungen".
*
* \copyright 2015-2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <memory>
#include <vector>
#include <cstdlib>
#include "BSZUtil.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--input-format=(marc-21|marc-xml)] [--output-format=(marc-21|marc-xml)]"
" deletion_list input_marc21 output_marc21 entire_record_deletion_log\n"
"Record ID's of records that were deleted and not merely modified will be written to \"entire_record_deletion_log\".");
}
/** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids"
* \return True if at least one local section has been deleted, else false.
*/
bool DeleteLocalSections(const std::unordered_set <std::string> &local_deletion_ids, MARC::Record * const record) {
bool modified(false);
std::vector<MARC::Record::iterator> local_block_starts_for_deletion;
for (const auto &local_block_start : record->findStartOfAllLocalDataBlocks()) {
const auto _001_range(record->getLocalTagRange("001", local_block_start));
if (_001_range.size() != 1)
LOG_ERROR("Every local data block has to have exactly one 001 field. (Record: "
+ record->getControlNumber() + ", First field in local block was: "
+ local_block_start->toString() + " - Found "
+ std::to_string(_001_range.size()) + ".)");
const MARC::Subfields subfields(_001_range.front().getSubfields());
const std::string subfield_contents(subfields.getFirstSubfieldWithCode('0'));
if (not StringUtil::StartsWith(subfield_contents, "001 ")
or local_deletion_ids.find(subfield_contents.substr(4)) == local_deletion_ids.end())
continue;
local_block_starts_for_deletion.emplace_back(local_block_start);
modified = true;
}
record->deleteLocalBlocks(local_block_starts_for_deletion);
return modified;
}
void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids,
const std::unordered_set <std::string> &local_deletion_ids, MARC::Reader * const marc_reader,
MARC::Writer * const marc_writer, File * const entire_record_deletion_log)
{
unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0);
while (MARC::Record record = marc_reader->read()) {
++total_record_count;
if (title_deletion_ids.find(record.getControlNumber()) != title_deletion_ids.end()) {
++deleted_record_count;
(*entire_record_deletion_log) << record.getControlNumber() << '\n';
} else { // Look for local (LOK) data sets that may need to be deleted.
if (DeleteLocalSections(local_deletion_ids, &record))
++modified_record_count;
marc_writer->write(record);
}
}
std::cerr << "Read " << total_record_count << " records.\n";
std::cerr << "Deleted " << deleted_record_count << " records.\n";
std::cerr << "Modified " << modified_record_count << " records.\n";
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 5)
Usage();
const auto reader_type(MARC::GetOptionalReaderType(&argc, &argv, 1));
const auto writer_type(MARC::GetOptionalWriterType(&argc, &argv, 1));
if (argc != 5)
Usage();
const auto deletion_list(FileUtil::OpenInputFileOrDie(argv[1]));
std::unordered_set<std::string> title_deletion_ids, local_deletion_ids;
BSZUtil::ExtractDeletionIds(deletion_list.get(), &title_deletion_ids, &local_deletion_ids);
const auto marc_reader(MARC::Reader::Factory(argv[2], reader_type));
const auto marc_writer(MARC::Writer::Factory(argv[3], writer_type));
const auto entire_record_deletion_log(FileUtil::OpenForAppendingOrDie(argv[4]));
ProcessRecords(title_deletion_ids, local_deletion_ids, marc_reader.get(), marc_writer.get(), entire_record_deletion_log.get());
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl.h> // for conversions between c++ and python collections
#include <pybind11/numpy.h> // support for numpy arrays
#include "trajectory.h"
#include "raster.h"
#include "planning.h"
namespace py = pybind11;
/** Converts a numpy array to a vector */
template<class T>
std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) {
std::vector<T> data(array.size());
for(ssize_t x=0; x<array.shape(0); x++) {
for(ssize_t y=0; y<array.shape(1); y++) {
data[x + y*array.shape(0)] = *(array.data(x, y));
}
}
return data;
}
/** Converts a vector to a 2D numpy array. */
template<class T>
py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) {
ASSERT(vec.size() == x_width * y_height)
py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height});
auto s_x_width = static_cast<ssize_t>(x_width);
auto s_y_height = static_cast<ssize_t>(y_height);
for(ssize_t x=0; x<s_x_width; x++) {
for (ssize_t y = 0; y < s_y_height; y++) {
*(array.mutable_data(x, y)) = vec[x + y*x_width];
}
}
return array;
}
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
PYBIND11_MODULE(uav_planning, m) {
m.doc() = "Python module for UAV trajectory planning";
srand(0);
py::class_<DRaster>(m, "DRaster")
.def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr,
double x_offset, double y_offset, double cell_width) {
return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);
}))
.def("as_numpy", [](DRaster& self) {
return as_nparray<double>(self.data, self.x_width, self.y_height);
})
.def_readonly("x_offset", &DRaster::x_offset)
.def_readonly("y_offset", &DRaster::y_offset)
.def_readonly("cell_width", &DRaster::cell_width);
py::class_<LRaster>(m, "LRaster")
.def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr,
double x_offset, double y_offset, double cell_width) {
return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);
}))
.def("as_numpy", [](LRaster& self) {
return as_nparray<long>(self.data, self.x_width, self.y_height);
})
.def_readonly("x_offset", &LRaster::x_offset)
.def_readonly("y_offset", &LRaster::y_offset)
.def_readonly("cell_width", &LRaster::cell_width);
py::class_<TimeWindow>(m, "TimeWindow")
.def(py::init<const double, const double>(),
py::arg("start"), py::arg("end"))
.def_readonly("start", &TimeWindow::start)
.def_readonly("end", &TimeWindow::end)
.def("__repr__",
[](const TimeWindow &tw) {
std::stringstream repr;
repr << "TimeWindow(" << tw.start << ", " << tw.end << ")";
return repr.str();
}
)
.def("as_tuple", [](TimeWindow &self) {
return py::make_tuple(self.start, self.end);
} );
py::class_<Cell>(m, "Cell")
.def(py::init<const size_t, const size_t>(),
py::arg("x"), py::arg("y"))
.def_readonly("x", &Cell::x)
.def_readonly("y", &Cell::y)
.def("__repr__",
[](const Cell &c) {
std::stringstream repr;
repr << "Cell(" << c.x << ", " << c.y << ")";
return repr.str();
}
)
.def("as_tuple", [](Cell &self) {
return py::make_tuple(self.x, self.y);
} );
py::class_<Position>(m, "Position2d")
.def(py::init<double, double>(),
py::arg("x"), py::arg("y"))
.def_readonly("x", &Position::x)
.def_readonly("y", &Position::y)
.def("__repr__",
[](const Position &p) {
std::stringstream repr;
repr << "Position2d(" << p.x << ", " << p.y << ")";
return repr.str();
}
)
.def("as_tuple", [](Position &self) {
return py::make_tuple(self.x, self.y);
} );
py::class_<Position3d>(m, "Position")
.def(py::init<double, double, double>(),
py::arg("x"), py::arg("y"), py::arg("z"))
.def_readonly("x", &Position3d::x)
.def_readonly("y", &Position3d::y)
.def_readonly("z", &Position3d::z)
.def("__repr__",
[](const Position3d &p) {
std::stringstream repr;
repr << "Position(" << p.x << ", " << p.y << ", " << p.z << ")";
return repr.str();
}
)
.def("as_tuple", [](Position3d &self) {
return py::make_tuple(self.x, self.y, self.z);
} );
py::class_<PositionTime>(m, "Position2dTime")
.def(py::init<Position, double>(),
py::arg("point"), py::arg("time"))
.def_readonly("pt", &PositionTime::pt)
.def_readonly("y", &PositionTime::time)
.def("__repr__",
[](const PositionTime &p) {
std::stringstream repr;
repr << "Position2dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")";
return repr.str();
}
)
.def("as_tuple", [](PositionTime &self) {
return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time);
} );
py::class_<Position3dTime>(m, "PositionTime")
.def(py::init<Position3d, double>(),
py::arg("point"), py::arg("time"))
.def_readonly("pt", &Position3dTime::pt)
.def_readonly("y", &Position3dTime::time)
.def("__repr__",
[](const Position3dTime &p) {
std::stringstream repr;
repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")";
return repr.str();
}
)
.def("as_tuple", [](Position3dTime &self) {
return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time);
} );
py::class_<IsochroneCluster, shared_ptr<IsochroneCluster>>(m, "IsochroneCluster")
.def(py::init<const TimeWindow&, vector<Cell>>(), py::arg("tw") , py::arg("cell_vector"))
.def_readonly("time_window", &IsochroneCluster::time_window)
.def_readonly("cells", &IsochroneCluster::cells);
py::class_<FireData>(m, "FireData")
.def(py::init<DRaster&, DDiscreteRaster&>(), py::arg("ignitions"), py::arg("elevation"))
.def_readonly("ignitions", &FireData::ignitions)
.def_readonly("traversal_end", &FireData::traversal_end)
.def_readonly("propagation_directions", &FireData::propagation_directions)
.def_readonly("elevation", &FireData::elevation);
// .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan)
// .def_readonly("isochrones", &FireData::isochrones);
py::class_<Waypoint3d>(m, "Waypoint")
.def(py::init<const double, const double, const double, const double>(),
py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction"))
.def_readonly("x", &Waypoint3d::x)
.def_readonly("y", &Waypoint3d::y)
.def_readonly("z", &Waypoint3d::z)
.def_readonly("dir", &Waypoint3d::dir)
.def("__repr__", &Waypoint3d::to_string);
py::class_<Segment3d>(m, "Segment")
.def(py::init<const Waypoint3d, const double>())
.def(py::init<const Waypoint3d, const Waypoint3d>())
.def_readonly("start", &Segment3d::start)
.def_readonly("end", &Segment3d::end)
.def_readonly("length", &Segment3d::length)
.def("__repr__", &Segment3d::to_string);
py::class_<UAV>(m, "UAV")
.def(py::init<const double, const double, const double>())
.def_readonly("min_turn_radius", &UAV::min_turn_radius)
.def_readonly("max_air_speed", &UAV::max_air_speed)
.def_readonly("max_pitch_angle", &UAV::max_pitch_angle)
.def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination"))
.def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination"))
.def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination"))
.def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination"));
py::class_<Trajectory>(m, "Trajectory")
.def(py::init<const TrajectoryConfig&>())
.def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time)
.def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time)
.def_readonly("segments", &Trajectory::traj)
.def("length", &Trajectory::length)
.def("duration", &Trajectory::duration)
.def("as_waypoints", &Trajectory::as_waypoints)
.def("sampled", &Trajectory::sampled, py::arg("step_size") = 1)
.def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end)
.def("__repr__", &Trajectory::to_string);
py::class_<TrajectoryConfig>(m, "TrajectoryConfig")
.def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>())
.def_readonly("uav", &TrajectoryConfig::uav)
.def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time)
.def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig {
return TrajectoryConfig(uav, start_time, max_flight_time);
}, "Constructor", py::arg("uav"), py::arg("start_time") = 0,
py::arg("max_flight_time") = std::numeric_limits<double>::max());
py::class_<Plan>(m, "Plan")
.def_readonly("trajectories", &Plan::trajectories)
.def("utility", &Plan::utility)
.def("duration", &Plan::duration)
.def_readonly("firedata", &Plan::firedata)
.def("observations", &Plan::observations);
py::class_<SearchResult>(m, "SearchResult")
.def("initial_plan", &SearchResult::initial)
.def("final_plan", &SearchResult::final)
.def_readonly("intermediate_plans", &SearchResult::intermediate_plans)
.def_readonly("planning_time", &SearchResult::planning_time)
.def_readonly("preprocessing_time", &SearchResult::preprocessing_time);
m.def("make_plan_vns", [](UAV uav, DRaster ignitions, DRaster elevation, double min_time, double max_time,
double max_flight_time, size_t save_every, bool save_improvements,
size_t discrete_elevation_interval=1) -> SearchResult {
auto fire_data = make_shared<FireData>(ignitions, DDiscreteRaster(std::move(elevation),
discrete_elevation_interval));
TrajectoryConfig conf(uav, min_time, max_flight_time);
Plan p(vector<TrajectoryConfig> { conf }, fire_data, TimeWindow{min_time, max_time});
DefaultVnsSearch vns;
auto res = vns.search(p, 0, save_every, save_improvements);
return res;
}, py::arg("uav"), py::arg("ignitions"), py::arg("elevation"), py::arg("min_time"), py::arg("max_time"),
py::arg("max_flight_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false,
py::arg("discrete_elevation_interval") = 1);
m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, double min_time,
double max_time, size_t save_every, bool save_improvements=false,
size_t discrete_elevation_interval=1) -> SearchResult {
auto time = []() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.);
};
printf("Processing firedata data\n");
double preprocessing_start = time();
auto fire_data = make_shared<FireData>(ignitions, DDiscreteRaster(std::move(elevation),
discrete_elevation_interval));
double preprocessing_end = time();
printf("Building initial plan\n");
Plan p(configs, fire_data, TimeWindow{min_time, max_time});
printf("Planning\n");
DefaultVnsSearch vns;
const double planning_start = time();
auto res = vns.search(p, 0, save_every, save_improvements);
const double planning_end = time();
printf("Plan found\n");
res.planning_time = planning_end - planning_start;
res.preprocessing_time = preprocessing_end - preprocessing_start;
return res;
}, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("elevation"), py::arg("min_time"),
py::arg("max_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false,
py::arg("discrete_elevation_interval") = 1, py::call_guard<py::gil_scoped_release>());
}
<commit_msg>Make trajectory configuration available from python.<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl.h> // for conversions between c++ and python collections
#include <pybind11/numpy.h> // support for numpy arrays
#include "trajectory.h"
#include "raster.h"
#include "planning.h"
namespace py = pybind11;
/** Converts a numpy array to a vector */
template<class T>
std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) {
std::vector<T> data(array.size());
for(ssize_t x=0; x<array.shape(0); x++) {
for(ssize_t y=0; y<array.shape(1); y++) {
data[x + y*array.shape(0)] = *(array.data(x, y));
}
}
return data;
}
/** Converts a vector to a 2D numpy array. */
template<class T>
py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) {
ASSERT(vec.size() == x_width * y_height)
py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height});
auto s_x_width = static_cast<ssize_t>(x_width);
auto s_y_height = static_cast<ssize_t>(y_height);
for(ssize_t x=0; x<s_x_width; x++) {
for (ssize_t y = 0; y < s_y_height; y++) {
*(array.mutable_data(x, y)) = vec[x + y*x_width];
}
}
return array;
}
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
PYBIND11_MODULE(uav_planning, m) {
m.doc() = "Python module for UAV trajectory planning";
srand(0);
py::class_<DRaster>(m, "DRaster")
.def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr,
double x_offset, double y_offset, double cell_width) {
return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);
}))
.def("as_numpy", [](DRaster& self) {
return as_nparray<double>(self.data, self.x_width, self.y_height);
})
.def_readonly("x_offset", &DRaster::x_offset)
.def_readonly("y_offset", &DRaster::y_offset)
.def_readonly("cell_width", &DRaster::cell_width);
py::class_<LRaster>(m, "LRaster")
.def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr,
double x_offset, double y_offset, double cell_width) {
return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);
}))
.def("as_numpy", [](LRaster& self) {
return as_nparray<long>(self.data, self.x_width, self.y_height);
})
.def_readonly("x_offset", &LRaster::x_offset)
.def_readonly("y_offset", &LRaster::y_offset)
.def_readonly("cell_width", &LRaster::cell_width);
py::class_<TimeWindow>(m, "TimeWindow")
.def(py::init<const double, const double>(),
py::arg("start"), py::arg("end"))
.def_readonly("start", &TimeWindow::start)
.def_readonly("end", &TimeWindow::end)
.def("__repr__",
[](const TimeWindow &tw) {
std::stringstream repr;
repr << "TimeWindow(" << tw.start << ", " << tw.end << ")";
return repr.str();
}
)
.def("as_tuple", [](TimeWindow &self) {
return py::make_tuple(self.start, self.end);
} );
py::class_<Cell>(m, "Cell")
.def(py::init<const size_t, const size_t>(),
py::arg("x"), py::arg("y"))
.def_readonly("x", &Cell::x)
.def_readonly("y", &Cell::y)
.def("__repr__",
[](const Cell &c) {
std::stringstream repr;
repr << "Cell(" << c.x << ", " << c.y << ")";
return repr.str();
}
)
.def("as_tuple", [](Cell &self) {
return py::make_tuple(self.x, self.y);
} );
py::class_<Position>(m, "Position2d")
.def(py::init<double, double>(),
py::arg("x"), py::arg("y"))
.def_readonly("x", &Position::x)
.def_readonly("y", &Position::y)
.def("__repr__",
[](const Position &p) {
std::stringstream repr;
repr << "Position2d(" << p.x << ", " << p.y << ")";
return repr.str();
}
)
.def("as_tuple", [](Position &self) {
return py::make_tuple(self.x, self.y);
} );
py::class_<Position3d>(m, "Position")
.def(py::init<double, double, double>(),
py::arg("x"), py::arg("y"), py::arg("z"))
.def_readonly("x", &Position3d::x)
.def_readonly("y", &Position3d::y)
.def_readonly("z", &Position3d::z)
.def("__repr__",
[](const Position3d &p) {
std::stringstream repr;
repr << "Position(" << p.x << ", " << p.y << ", " << p.z << ")";
return repr.str();
}
)
.def("as_tuple", [](Position3d &self) {
return py::make_tuple(self.x, self.y, self.z);
} );
py::class_<PositionTime>(m, "Position2dTime")
.def(py::init<Position, double>(),
py::arg("point"), py::arg("time"))
.def_readonly("pt", &PositionTime::pt)
.def_readonly("y", &PositionTime::time)
.def("__repr__",
[](const PositionTime &p) {
std::stringstream repr;
repr << "Position2dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")";
return repr.str();
}
)
.def("as_tuple", [](PositionTime &self) {
return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time);
} );
py::class_<Position3dTime>(m, "PositionTime")
.def(py::init<Position3d, double>(),
py::arg("point"), py::arg("time"))
.def_readonly("pt", &Position3dTime::pt)
.def_readonly("y", &Position3dTime::time)
.def("__repr__",
[](const Position3dTime &p) {
std::stringstream repr;
repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")";
return repr.str();
}
)
.def("as_tuple", [](Position3dTime &self) {
return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time);
} );
py::class_<IsochroneCluster, shared_ptr<IsochroneCluster>>(m, "IsochroneCluster")
.def(py::init<const TimeWindow&, vector<Cell>>(), py::arg("tw") , py::arg("cell_vector"))
.def_readonly("time_window", &IsochroneCluster::time_window)
.def_readonly("cells", &IsochroneCluster::cells);
py::class_<FireData>(m, "FireData")
.def(py::init<DRaster&, DDiscreteRaster&>(), py::arg("ignitions"), py::arg("elevation"))
.def_readonly("ignitions", &FireData::ignitions)
.def_readonly("traversal_end", &FireData::traversal_end)
.def_readonly("propagation_directions", &FireData::propagation_directions)
.def_readonly("elevation", &FireData::elevation);
// .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan)
// .def_readonly("isochrones", &FireData::isochrones);
py::class_<Waypoint3d>(m, "Waypoint")
.def(py::init<const double, const double, const double, const double>(),
py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction"))
.def_readonly("x", &Waypoint3d::x)
.def_readonly("y", &Waypoint3d::y)
.def_readonly("z", &Waypoint3d::z)
.def_readonly("dir", &Waypoint3d::dir)
.def("__repr__", &Waypoint3d::to_string);
py::class_<Segment3d>(m, "Segment")
.def(py::init<const Waypoint3d, const double>())
.def(py::init<const Waypoint3d, const Waypoint3d>())
.def_readonly("start", &Segment3d::start)
.def_readonly("end", &Segment3d::end)
.def_readonly("length", &Segment3d::length)
.def("__repr__", &Segment3d::to_string);
py::class_<UAV>(m, "UAV")
.def(py::init<const double, const double, const double>())
.def_readonly("min_turn_radius", &UAV::min_turn_radius)
.def_readonly("max_air_speed", &UAV::max_air_speed)
.def_readonly("max_pitch_angle", &UAV::max_pitch_angle)
.def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination"))
.def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination"))
.def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination"))
.def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination"));
py::class_<Trajectory>(m, "Trajectory")
.def(py::init<const TrajectoryConfig&>())
.def_readonly("conf", &Trajectory::conf)
.def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time)
.def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time)
.def_readonly("segments", &Trajectory::traj)
.def("length", &Trajectory::length)
.def("duration", &Trajectory::duration)
.def("as_waypoints", &Trajectory::as_waypoints)
.def("sampled", &Trajectory::sampled, py::arg("step_size") = 1)
.def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end)
.def("__repr__", &Trajectory::to_string);
py::class_<TrajectoryConfig>(m, "TrajectoryConfig")
.def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>())
.def_readonly("uav", &TrajectoryConfig::uav)
.def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time)
.def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig {
return TrajectoryConfig(uav, start_time, max_flight_time);
}, "Constructor", py::arg("uav"), py::arg("start_time") = 0,
py::arg("max_flight_time") = std::numeric_limits<double>::max());
py::class_<Plan>(m, "Plan")
.def_readonly("trajectories", &Plan::trajectories)
.def("utility", &Plan::utility)
.def("duration", &Plan::duration)
.def_readonly("firedata", &Plan::firedata)
.def("observations", &Plan::observations);
py::class_<SearchResult>(m, "SearchResult")
.def("initial_plan", &SearchResult::initial)
.def("final_plan", &SearchResult::final)
.def_readonly("intermediate_plans", &SearchResult::intermediate_plans)
.def_readonly("planning_time", &SearchResult::planning_time)
.def_readonly("preprocessing_time", &SearchResult::preprocessing_time);
m.def("make_plan_vns", [](UAV uav, DRaster ignitions, DRaster elevation, double min_time, double max_time,
double max_flight_time, size_t save_every, bool save_improvements,
size_t discrete_elevation_interval=1) -> SearchResult {
auto fire_data = make_shared<FireData>(ignitions, DDiscreteRaster(std::move(elevation),
discrete_elevation_interval));
TrajectoryConfig conf(uav, min_time, max_flight_time);
Plan p(vector<TrajectoryConfig> { conf }, fire_data, TimeWindow{min_time, max_time});
DefaultVnsSearch vns;
auto res = vns.search(p, 0, save_every, save_improvements);
return res;
}, py::arg("uav"), py::arg("ignitions"), py::arg("elevation"), py::arg("min_time"), py::arg("max_time"),
py::arg("max_flight_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false,
py::arg("discrete_elevation_interval") = 1);
m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, double min_time,
double max_time, size_t save_every, bool save_improvements=false,
size_t discrete_elevation_interval=1) -> SearchResult {
auto time = []() {
struct timeval tp;
gettimeofday(&tp, NULL);
return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.);
};
printf("Processing firedata data\n");
double preprocessing_start = time();
auto fire_data = make_shared<FireData>(ignitions, DDiscreteRaster(std::move(elevation),
discrete_elevation_interval));
double preprocessing_end = time();
printf("Building initial plan\n");
Plan p(configs, fire_data, TimeWindow{min_time, max_time});
printf("Planning\n");
DefaultVnsSearch vns;
const double planning_start = time();
auto res = vns.search(p, 0, save_every, save_improvements);
const double planning_end = time();
printf("Plan found\n");
res.planning_time = planning_end - planning_start;
res.preprocessing_time = preprocessing_end - preprocessing_start;
return res;
}, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("elevation"), py::arg("min_time"),
py::arg("max_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false,
py::arg("discrete_elevation_interval") = 1, py::call_guard<py::gil_scoped_release>());
}
<|endoftext|> |
<commit_before>/** \brief Utility for replacing generating up-to-date authority MARC collections.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2017 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <unordered_map>
#include <cstdio>
#include <cstdlib>
#include <dirent.h>
#include "Compiler.h"
#include "BSZUtil.h"
#include "ExecUtil.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcUtil.h"
#include "MarcWriter.h"
#include "RegexMatcher.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname << " deletion_list reference_records source_records target_records\n"
<< " Replaces all records in \"source_records\" that have an identical control number\n"
<< " as a record in \"reference_records\" with the corresponding record in\n"
<< " \"reference_records\". The file with the replacements as well as any records\n"
<< " that could not be replaced is the output file \"target_records\".\n"
<< " \"deletion_list\", \"reference_records\", and \"source_records\" must all be regular\n"
<< " expressions containing \\d\\d\\d\\d\\d\\d stading in for YYMMDD. Additionally\n"
<< " \"target_records\" must also contain the YYMMDD patternNo (No other metacharacters\n"
<< " than \\d should probably be used.)\n\n";
std::exit(EXIT_FAILURE);
}
/** \param path_regex A PCRE regex that must contain a \d\d\d\d\d\d subexpression standing in for YYYYMMDD.
* \return Either the most recent file or the empty string if no files matched the regex.
*/
std::string GetMostRecentFile(const std::string &path_regex) {
if (unlikely(path_regex.find("\\d\\d\\d\\d\\d\\d") == std::string::npos))
Error("in GetMostRecentFile: regex \"" + path_regex + "\" does not contain \\d\\d\\d\\d\\d\\d!");
std::string filename, directory;
FileUtil::DirnameAndBasename(path_regex, &filename, &directory);
std::string err_msg;
RegexMatcher *matcher(RegexMatcher::RegexMatcherFactory(filename, &err_msg));
if (unlikely(matcher == nullptr))
Error("in GetMostRecentFile: failed to compile regex \"" + filename + "\"! (" + err_msg + ")");
DIR * const directory_stream(::opendir(directory.c_str()));
if (unlikely(directory_stream == nullptr))
Error("in GetMostRecentFile: opendir(" + directory + ") failed(" + std::string(::strerror(errno)) + ")");
std::string most_recent_file;
struct dirent *entry;
while ((entry = ::readdir(directory_stream)) != nullptr) {
if ((entry->d_type == DT_REG or entry->d_type == DT_UNKNOWN) and matcher->matched(entry->d_name)) {
std::string dir_entry(entry->d_name);
if (dir_entry > most_recent_file)
most_recent_file.swap(dir_entry);
}
}
::closedir(directory_stream);
delete matcher;
return most_recent_file;
}
// Copies records from "marc_reader" to "marc_writer", skipping those whose ID's are found in
// "delete_full_record_ids".
void EraseRecords(MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::unordered_set <std::string> &delete_full_record_ids)
{
std::cout << "Eliminating records listed in a deletion list...\n";
unsigned total_record_count(0), deletion_count(0);
while (const MarcRecord record = marc_reader->read()) {
++total_record_count;
if (delete_full_record_ids.find(record.getControlNumber()) == delete_full_record_ids.cend())
++deletion_count;
else
marc_writer->write(record);
}
std::cout << "Read " << total_record_count << " records and dropped " << deletion_count << " records.\n";
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 5)
Usage();
try {
const std::string MARC_TEMP_FILENAME("/tmp/update_authority_data.temp.mrc");
const std::string MARC_TARGET_FILENAME(argv[4]);
const std::string MARC_TARGET_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_TARGET_FILENAME));
const std::string MARC_SOURCE_FILENAME(GetMostRecentFile(argv[3]));
const std::string MARC_SOURCE_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_SOURCE_FILENAME));
const std::string DELETION_LIST_FILENAME(GetMostRecentFile(argv[1]));
const std::string DELETION_LIST_DATE(BSZUtil::ExtractDateFromFilenameOrDie(DELETION_LIST_FILENAME));
if (DELETION_LIST_DATE >= MARC_SOURCE_DATE) {
std::unique_ptr<File> deletion_list_file(FileUtil::OpenInputFileOrDie(DELETION_LIST_FILENAME));
std::unordered_set <std::string> delete_full_record_ids, local_deletion_ids;
BSZUtil::ExtractDeletionIds(deletion_list_file.get(), &delete_full_record_ids, &local_deletion_ids);
std::unique_ptr<MarcReader> marc_source_reader(MarcReader::Factory(MARC_SOURCE_FILENAME));
std::unique_ptr<MarcWriter> marc_temp_writer(MarcWriter::Factory(MARC_TEMP_FILENAME));
EraseRecords(marc_source_reader.get(), marc_temp_writer.get(), delete_full_record_ids);
} else
FileUtil::CopyOrDie(MARC_SOURCE_FILENAME, MARC_TEMP_FILENAME);
const std::string MARC_REFERENCE_FILENAME(GetMostRecentFile(argv[2]));
const std::string MARC_REFERENCE_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_REFERENCE_FILENAME));
if (MARC_REFERENCE_DATE >= MARC_SOURCE_DATE) {
const std::string REPLACE_MARC_RECORDS_PATH("/usr/local/bin/replace_marc_records");
if (ExecUtil::Exec(REPLACE_MARC_RECORDS_PATH,
{ MARC_REFERENCE_FILENAME, MARC_TEMP_FILENAME, MARC_TARGET_FILENAME }) != 0)
Error("failed to execute \"" + REPLACE_MARC_RECORDS_PATH + "\"!");
} else
FileUtil::CopyOrDie(MARC_TEMP_FILENAME, MARC_TARGET_FILENAME);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<commit_msg>Added a sanity check.<commit_after>/** \brief Utility for replacing generating up-to-date authority MARC collections.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2017 Universitätsbiblothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <unordered_map>
#include <cstdio>
#include <cstdlib>
#include <dirent.h>
#include "Compiler.h"
#include "BSZUtil.h"
#include "ExecUtil.h"
#include "FileUtil.h"
#include "MarcReader.h"
#include "MarcRecord.h"
#include "MarcUtil.h"
#include "MarcWriter.h"
#include "RegexMatcher.h"
#include "util.h"
static void Usage() __attribute__((noreturn));
static void Usage() {
std::cerr << "Usage: " << ::progname << " deletion_list reference_records source_records target_records\n"
<< " Replaces all records in \"source_records\" that have an identical control number\n"
<< " as a record in \"reference_records\" with the corresponding record in\n"
<< " \"reference_records\". The file with the replacements as well as any records\n"
<< " that could not be replaced is the output file \"target_records\".\n"
<< " \"deletion_list\", \"reference_records\", and \"source_records\" must all be regular\n"
<< " expressions containing \\d\\d\\d\\d\\d\\d stading in for YYMMDD. Additionally\n"
<< " \"target_records\" must also contain the YYMMDD patternNo (No other metacharacters\n"
<< " than \\d should probably be used.)\n\n";
std::exit(EXIT_FAILURE);
}
/** \param path_regex A PCRE regex that must contain a \d\d\d\d\d\d subexpression standing in for YYYYMMDD.
* \return Either the most recent file or the empty string if no files matched the regex.
*/
std::string GetMostRecentFile(const std::string &path_regex) {
if (unlikely(path_regex.find("\\d\\d\\d\\d\\d\\d") == std::string::npos))
Error("in GetMostRecentFile: regex \"" + path_regex + "\" does not contain \\d\\d\\d\\d\\d\\d!");
std::string filename, directory;
FileUtil::DirnameAndBasename(path_regex, &filename, &directory);
std::string err_msg;
RegexMatcher *matcher(RegexMatcher::RegexMatcherFactory(filename, &err_msg));
if (unlikely(matcher == nullptr))
Error("in GetMostRecentFile: failed to compile regex \"" + filename + "\"! (" + err_msg + ")");
DIR * const directory_stream(::opendir(directory.c_str()));
if (unlikely(directory_stream == nullptr))
Error("in GetMostRecentFile: opendir(" + directory + ") failed(" + std::string(::strerror(errno)) + ")");
std::string most_recent_file;
struct dirent *entry;
while ((entry = ::readdir(directory_stream)) != nullptr) {
if ((entry->d_type == DT_REG or entry->d_type == DT_UNKNOWN) and matcher->matched(entry->d_name)) {
std::string dir_entry(entry->d_name);
if (dir_entry > most_recent_file)
most_recent_file.swap(dir_entry);
}
}
::closedir(directory_stream);
delete matcher;
return most_recent_file;
}
// Copies records from "marc_reader" to "marc_writer", skipping those whose ID's are found in
// "delete_full_record_ids".
void EraseRecords(MarcReader * const marc_reader, MarcWriter * const marc_writer,
const std::unordered_set <std::string> &delete_full_record_ids)
{
std::cout << "Eliminating records listed in a deletion list...\n";
unsigned total_record_count(0), deletion_count(0);
while (const MarcRecord record = marc_reader->read()) {
++total_record_count;
if (delete_full_record_ids.find(record.getControlNumber()) == delete_full_record_ids.cend())
++deletion_count;
else
marc_writer->write(record);
}
std::cout << "Read " << total_record_count << " records and dropped " << deletion_count << " records.\n";
}
int main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 5)
Usage();
try {
const std::string MARC_TEMP_FILENAME("/tmp/update_authority_data.temp.mrc");
const std::string MARC_TARGET_FILENAME(argv[4]);
const std::string MARC_TARGET_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_TARGET_FILENAME));
const std::string MARC_SOURCE_FILENAME(GetMostRecentFile(argv[3]));
const std::string MARC_SOURCE_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_SOURCE_FILENAME));
if (MARC_TARGET_DATE >= MARC_SOURCE_DATE) {
std::cout << "Nothing to be done!\n";
return EXIT_SUCCESS;
}
const std::string DELETION_LIST_FILENAME(GetMostRecentFile(argv[1]));
const std::string DELETION_LIST_DATE(BSZUtil::ExtractDateFromFilenameOrDie(DELETION_LIST_FILENAME));
if (DELETION_LIST_DATE >= MARC_SOURCE_DATE) {
std::unique_ptr<File> deletion_list_file(FileUtil::OpenInputFileOrDie(DELETION_LIST_FILENAME));
std::unordered_set <std::string> delete_full_record_ids, local_deletion_ids;
BSZUtil::ExtractDeletionIds(deletion_list_file.get(), &delete_full_record_ids, &local_deletion_ids);
std::unique_ptr<MarcReader> marc_source_reader(MarcReader::Factory(MARC_SOURCE_FILENAME));
std::unique_ptr<MarcWriter> marc_temp_writer(MarcWriter::Factory(MARC_TEMP_FILENAME));
EraseRecords(marc_source_reader.get(), marc_temp_writer.get(), delete_full_record_ids);
} else
FileUtil::CopyOrDie(MARC_SOURCE_FILENAME, MARC_TEMP_FILENAME);
const std::string MARC_REFERENCE_FILENAME(GetMostRecentFile(argv[2]));
const std::string MARC_REFERENCE_DATE(BSZUtil::ExtractDateFromFilenameOrDie(MARC_REFERENCE_FILENAME));
if (MARC_REFERENCE_DATE >= MARC_SOURCE_DATE) {
const std::string REPLACE_MARC_RECORDS_PATH("/usr/local/bin/replace_marc_records");
if (ExecUtil::Exec(REPLACE_MARC_RECORDS_PATH,
{ MARC_REFERENCE_FILENAME, MARC_TEMP_FILENAME, MARC_TARGET_FILENAME }) != 0)
Error("failed to execute \"" + REPLACE_MARC_RECORDS_PATH + "\"!");
} else
FileUtil::CopyOrDie(MARC_TEMP_FILENAME, MARC_TARGET_FILENAME);
} catch (const std::exception &e) {
Error("Caught exception: " + std::string(e.what()));
}
}
<|endoftext|> |
<commit_before>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "LanguageModelFactory.h"
#include "UserMessage.h"
#include "TypeDef.h"
#include "FactorCollection.h"
// include appropriate header
#ifdef LM_SRI
# include "LanguageModelSRI.h"
#endif
#ifdef LM_IRST
# include "LanguageModelIRST.h"
#endif
#include "LanguageModelInternal.h"
#include "LanguageModelSkip.h"
#include "LanguageModelJoint.h"
namespace LanguageModelFactory
{
LanguageModel* CreateLanguageModel(LMImplementation lmImplementation, const std::vector<FactorType> &factorTypes
, size_t nGramOrder, const std::string &languageModelFile, float weight, FactorCollection &factorCollection)
{
LanguageModel *lm = NULL;
switch (lmImplementation)
{
case SRI:
#ifdef LM_SRI
lm = new LanguageModelSRI(true);
#elif LM_IRST
lm = new LanguageModelIRST(true);
#else
lm = new LanguageModelInternal(true);
#endif
break;
case IRST:
#ifdef LM_IRST
lm = new LanguageModelIRST(true);
#elif LM_IRST
lm = new LanguageModelSRI(true);
#else
lm = new LanguageModelInternal(true);
#endif
break;
case Skip:
#ifdef LM_SRI
lm = new LanguageModelSkip(new LanguageModelSRI(false), true);
#elif LM_SRI
lm = new LanguageModelSkip(new LanguageModelIRST(false), true);
#else
lm = new LanguageModelSkip(new LanguageModelInternal(false), true);
#endif
break;
case Joint:
#ifdef LM_SRI
lm = new LanguageModelJoint(new LanguageModelSRI(false), true);
#elif LM_IRST
lm = new LanguageModelJoint(new LanguageModelIRST(false), true);
#else
lm = new LanguageModelJoint(new LanguageModelInternal(false), true);
#endif
break;
}
if (lm == NULL)
{
UserMessage::Add("Language model type unknown. Probably not compiled into library");
}
else
{
switch (lm->GetLMType())
{
case SingleFactor:
static_cast<LanguageModelSingleFactor*>(lm)->Load(languageModelFile, factorCollection, factorTypes[0], weight, nGramOrder);
break;
case MultiFactor:
static_cast<LanguageModelMultiFactor*>(lm)->Load(languageModelFile, factorCollection, factorTypes, weight, nGramOrder);
break;
}
}
return lm;
}
}
<commit_msg>added internal, x-platform LM which exactly mimics SRILM<commit_after>// $Id$
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "LanguageModelFactory.h"
#include "UserMessage.h"
#include "TypeDef.h"
#include "FactorCollection.h"
// include appropriate header
#ifdef LM_SRI
# include "LanguageModelSRI.h"
#endif
#ifdef LM_IRST
# include "LanguageModelIRST.h"
#endif
#include "LanguageModelInternal.h"
#include "LanguageModelSkip.h"
#include "LanguageModelJoint.h"
namespace LanguageModelFactory
{
LanguageModel* CreateLanguageModel(LMImplementation lmImplementation, const std::vector<FactorType> &factorTypes
, size_t nGramOrder, const std::string &languageModelFile, float weight, FactorCollection &factorCollection)
{
LanguageModel *lm = NULL;
switch (lmImplementation)
{
case SRI:
#ifdef LM_SRI
lm = new LanguageModelSRI(true);
#elif LM_INTERNAL
lm = new LanguageModelInternal(true);
#endif
break;
case IRST:
#ifdef LM_IRST
lm = new LanguageModelIRST(true);
#elif LM_SRI
lm = new LanguageModelSRI(true);
#elif LM_INTERNAL
lm = new LanguageModelInternal(true);
#endif
break;
case Skip:
#ifdef LM_SRI
lm = new LanguageModelSkip(new LanguageModelSRI(false), true);
#elif LM_INTERNAL
lm = new LanguageModelSkip(new LanguageModelInternal(false), true);
#endif
break;
case Joint:
#ifdef LM_SRI
lm = new LanguageModelJoint(new LanguageModelSRI(false), true);
#elif LM_INTERNAL
lm = new LanguageModelJoint(new LanguageModelInternal(false), true);
#endif
break;
}
if (lm == NULL)
{
UserMessage::Add("Language model type unknown. Probably not compiled into library");
}
else
{
switch (lm->GetLMType())
{
case SingleFactor:
static_cast<LanguageModelSingleFactor*>(lm)->Load(languageModelFile, factorCollection, factorTypes[0], weight, nGramOrder);
break;
case MultiFactor:
static_cast<LanguageModelMultiFactor*>(lm)->Load(languageModelFile, factorCollection, factorTypes, weight, nGramOrder);
break;
}
}
return lm;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "native_client/src/shared/ppapi_proxy/browser_ppp_input_event.h"
#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/ppapi_proxy/browser_globals.h"
#include "native_client/src/shared/ppapi_proxy/input_event_data.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/browser_ppp.h"
#include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppp_rpc.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/ppp_input_event.h"
namespace ppapi_proxy {
namespace {
PP_Bool HandleInputEvent(PP_Instance instance, PP_Resource input_event) {
DebugPrintf("PPP_InputEvent::HandleInputEvent: instance=%"NACL_PRIu32", "
"input_event = %"NACL_PRIu32"\n",
instance, input_event);
PP_Var character_text = PP_MakeUndefined();
InputEventData data;
data.event_type = PPBInputEventInterface()->GetType(input_event);
data.event_time_stamp = PPBInputEventInterface()->GetTimeStamp(input_event);
data.event_modifiers = PPBInputEventInterface()->GetModifiers(input_event);
switch (data.event_type) {
// These events all use the PPB_MouseInputEvent interface.
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
case PP_INPUTEVENT_TYPE_MOUSEUP:
case PP_INPUTEVENT_TYPE_MOUSEENTER:
case PP_INPUTEVENT_TYPE_MOUSELEAVE:
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
case PP_INPUTEVENT_TYPE_CONTEXTMENU:
data.mouse_button =
PPBMouseInputEventInterface()->GetButton(input_event);
data.mouse_position =
PPBMouseInputEventInterface()->GetPosition(input_event);
data.mouse_click_count =
PPBMouseInputEventInterface()->GetClickCount(input_event);
data.mouse_movement =
PPBMouseInputEventInterface()->GetMovement(input_event);
break;
// This event uses the PPB_WheelInputEvent interface.
case PP_INPUTEVENT_TYPE_WHEEL:
data.wheel_delta =
PPBWheelInputEventInterface()->GetDelta(input_event);
data.wheel_ticks =
PPBWheelInputEventInterface()->GetTicks(input_event);
data.wheel_scroll_by_page =
PPBWheelInputEventInterface()->GetScrollByPage(input_event);
break;
// These events all use the PPB_KeyInputEvent interface.
case PP_INPUTEVENT_TYPE_RAWKEYDOWN:
case PP_INPUTEVENT_TYPE_KEYDOWN:
case PP_INPUTEVENT_TYPE_KEYUP:
case PP_INPUTEVENT_TYPE_CHAR:
data.key_code =
PPBKeyboardInputEventInterface()->GetKeyCode(input_event);
character_text =
PPBKeyboardInputEventInterface()->GetCharacterText(input_event);
break;
case PP_INPUTEVENT_TYPE_UNDEFINED:
return PP_FALSE;
// No default case; if any new types are added we should get a compile
// warning.
}
// Now data and character_text have all the data we want to send to the
// untrusted side.
// character_text should either be undefined or a string type.
DCHECK((character_text.type == PP_VARTYPE_UNDEFINED) ||
(character_text.type == PP_VARTYPE_STRING));
// Serialize the character_text Var.
uint32_t text_size = kMaxVarSize;
nacl::scoped_array<char> text_bytes(Serialize(&character_text, 1,
&text_size));
int32_t handled;
NaClSrpcError srpc_result =
PppInputEventRpcClient::PPP_InputEvent_HandleInputEvent(
GetMainSrpcChannel(instance),
instance,
input_event,
sizeof(data),
reinterpret_cast<char*>(&data),
text_size,
text_bytes.get(),
&handled);
DebugPrintf("PPP_Instance::HandleInputEvent: %s\n",
NaClSrpcErrorString(srpc_result));
if (srpc_result != NACL_SRPC_RESULT_OK) {
return PP_FALSE;
}
// The 'handled' int should only ever have a value matching one of PP_FALSE
// or PP_TRUE. Otherwise, there's an error in the proxy.
DCHECK((handled == static_cast<int32_t>(PP_FALSE) ||
(handled == static_cast<int32_t>(PP_TRUE))));
PP_Bool handled_bool = static_cast<PP_Bool>(handled);
return handled_bool;
}
} // namespace
const PPP_InputEvent* BrowserInputEvent::GetInterface() {
static const PPP_InputEvent input_event_interface = {
HandleInputEvent
};
return &input_event_interface;
}
} // namespace ppapi_proxy
<commit_msg>Add new input event enums for deps roll BUG= none TEST= existing test suites Review URL: http://codereview.chromium.org/7925019<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "native_client/src/shared/ppapi_proxy/browser_ppp_input_event.h"
#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/ppapi_proxy/browser_globals.h"
#include "native_client/src/shared/ppapi_proxy/input_event_data.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/browser_ppp.h"
#include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppp_rpc.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/ppp_input_event.h"
namespace ppapi_proxy {
namespace {
PP_Bool HandleInputEvent(PP_Instance instance, PP_Resource input_event) {
DebugPrintf("PPP_InputEvent::HandleInputEvent: instance=%"NACL_PRIu32", "
"input_event = %"NACL_PRIu32"\n",
instance, input_event);
PP_Var character_text = PP_MakeUndefined();
InputEventData data;
data.event_type = PPBInputEventInterface()->GetType(input_event);
data.event_time_stamp = PPBInputEventInterface()->GetTimeStamp(input_event);
data.event_modifiers = PPBInputEventInterface()->GetModifiers(input_event);
switch (data.event_type) {
// These events all use the PPB_MouseInputEvent interface.
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
case PP_INPUTEVENT_TYPE_MOUSEUP:
case PP_INPUTEVENT_TYPE_MOUSEENTER:
case PP_INPUTEVENT_TYPE_MOUSELEAVE:
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
case PP_INPUTEVENT_TYPE_CONTEXTMENU:
data.mouse_button =
PPBMouseInputEventInterface()->GetButton(input_event);
data.mouse_position =
PPBMouseInputEventInterface()->GetPosition(input_event);
data.mouse_click_count =
PPBMouseInputEventInterface()->GetClickCount(input_event);
data.mouse_movement =
PPBMouseInputEventInterface()->GetMovement(input_event);
break;
// This event uses the PPB_WheelInputEvent interface.
case PP_INPUTEVENT_TYPE_WHEEL:
data.wheel_delta =
PPBWheelInputEventInterface()->GetDelta(input_event);
data.wheel_ticks =
PPBWheelInputEventInterface()->GetTicks(input_event);
data.wheel_scroll_by_page =
PPBWheelInputEventInterface()->GetScrollByPage(input_event);
break;
// These events all use the PPB_KeyInputEvent interface.
case PP_INPUTEVENT_TYPE_RAWKEYDOWN:
case PP_INPUTEVENT_TYPE_KEYDOWN:
case PP_INPUTEVENT_TYPE_KEYUP:
case PP_INPUTEVENT_TYPE_CHAR:
data.key_code =
PPBKeyboardInputEventInterface()->GetKeyCode(input_event);
character_text =
PPBKeyboardInputEventInterface()->GetCharacterText(input_event);
break;
case PP_INPUTEVENT_TYPE_UNDEFINED:
return PP_FALSE;
// TODO(nfullagar): Implement support for event types below.
case PP_INPUTEVENT_TYPE_COMPOSITION_START:
case PP_INPUTEVENT_TYPE_COMPOSITION_UPDATE:
case PP_INPUTEVENT_TYPE_COMPOSITION_END:
case PP_INPUTEVENT_TYPE_IME_TEXT:
DebugPrintf(" No implementation for event type %d\n",
data.event_type);
return PP_FALSE;
// No default case; if any new types are added we should get a compile
// warning.
}
// Now data and character_text have all the data we want to send to the
// untrusted side.
// character_text should either be undefined or a string type.
DCHECK((character_text.type == PP_VARTYPE_UNDEFINED) ||
(character_text.type == PP_VARTYPE_STRING));
// Serialize the character_text Var.
uint32_t text_size = kMaxVarSize;
nacl::scoped_array<char> text_bytes(Serialize(&character_text, 1,
&text_size));
int32_t handled;
NaClSrpcError srpc_result =
PppInputEventRpcClient::PPP_InputEvent_HandleInputEvent(
GetMainSrpcChannel(instance),
instance,
input_event,
sizeof(data),
reinterpret_cast<char*>(&data),
text_size,
text_bytes.get(),
&handled);
DebugPrintf("PPP_Instance::HandleInputEvent: %s\n",
NaClSrpcErrorString(srpc_result));
if (srpc_result != NACL_SRPC_RESULT_OK) {
return PP_FALSE;
}
// The 'handled' int should only ever have a value matching one of PP_FALSE
// or PP_TRUE. Otherwise, there's an error in the proxy.
DCHECK((handled == static_cast<int32_t>(PP_FALSE) ||
(handled == static_cast<int32_t>(PP_TRUE))));
PP_Bool handled_bool = static_cast<PP_Bool>(handled);
return handled_bool;
}
} // namespace
const PPP_InputEvent* BrowserInputEvent::GetInterface() {
static const PPP_InputEvent input_event_interface = {
HandleInputEvent
};
return &input_event_interface;
}
} // namespace ppapi_proxy
<|endoftext|> |
<commit_before>/*
* Copyright 2014 National ICT Australia Limited (NICTA)
*
* 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 <madopt/ipopt_model.hpp>
//#include <madopt/bonmin_model.hpp>
#include <vector>
using namespace std;
int main(){
int N = pow(10, 4);
//create IpoptModel
MadOpt::IpoptModel m;
//create BonminModel
//MadOpt::BonminModel m;
// Options
//
//
//m.setIntegerOption("print_level", 5);
//m.setStringOption("print_timing_statistics", "yes");
//m.setStringOption("hessian_approximation", "limited-memory");
// shortcut flags
// set flag if solver output should be printed
m.show_solver = true;
// timelimit, a negative value disables the time limit
m.timelimit = 12;
// Variables
//
//
// create continuous variable x
// lower bound = -1.5
// upper bound = 0
// initial value = -0.5
// MadOpt::Var x = m.addVar(-1.5, 0, -0.5, "x");
// to set a bound to infinity use MadOpt::INF
// MadOpt::Var v = m.addVar(MadOpt::INF, 0, -0.5, "v");
// create integer variable y
// lower bound = 1
// upper bound = 10
// initial value = 4
// MadOpt::Var y = m.addIVar(1, 10, 4, "y");
// create binary variable z
// initial value = 1
// MadOpt::Var z = m.addBVar(1, "z");
vector<MadOpt::Var> x(N);
for (int i=0; i<N; i++){
x[i] = m.addVar(-1.5, 0, -0.5, "x" + to_string(i));
}
// Parameters
//
//
// create Parameter
// value = 1
// name = p
// MadOpt::Param p = m.addParam(1, "p");
vector<MadOpt::Param> p(N-2);
for (int i=0; i<N-2; i++){
double a = double(i+2)/(double)N;
p[i] = m.addParam(a, "p"+to_string(i));
}
// Constraints
//
//
// expr = expression build from constants, variables MadOpt::Var, parameters MadOpt::Param
// lb = lower bound, double
// ub = upper bound, double
//
// add constraint of type:
//
// lb <= expr <= ub
// m.addConstr(lb, expr, ub);
//
// lb <= expr <= INF
// m.addConstr(lb, expr);
//
// INF <= expr <= ub
// m.addConstr(expr, ub);
//
// expr == eq
// m.addEqConstr(expr, eq);
vector<MadOpt::Constraint> c(N-2);
for (int i=0; i<N-2; i++){
c[i] = m.addEqConstr((MadOpt::pow(x[i+1], 2) + 1.5*x[i+1] - p[i])*MadOpt::cos(x[i+2]) - x[i], 0);
}
// Objective
//
//
MadOpt::Expr obj(0);
for (int i=0; i<N; i++)
obj += MadOpt::pow(x[i] - 1, 2);
// set objective
m.setObj(obj);
// calling the solver
//
//
m.solve();
// check if a solution exists, or in other words if the solver succeeded
//
//
if (m.hasSolution()){
// access objective value
cout<<"Objective:"<<m.objValue()<<endl;
// access solver status == Ipopt status values
cout<<"Solver status:"<<m.status()<<endl;
//print solution value of first variable
cout<<"Solution value for x0:"<<x[0].x()<<endl;
//print lambda value of constraint, only available for IpoptModel
cout<<"Lambda value of constraint 0:"<<c[0].lam()<<endl;
}
//changing the model
//
//
// Variables
//change variable bounds and initial value
x[1].lb(-12);
x[1].ub(1);
x[1].init(0);
//access bounds and initial values
cout<<"Variable values: lb="<<x[1].lb()<<" ub="<<x[1].ub()<<" init="<<x[1].init()<<endl;
//Constraints
//change constraint bounds
c[0].lb(-1);
c[0].ub(2);
//access bounds
cout<<"Constraint bounds: lb="<<c[0].lb()<<" ub="<<c[0].ub()<<endl;
//Parameter
// change value
p[0].value(12);
// access value
cout<<"Parameter value:"<<p[0].value()<<endl;
// resolve
//
//
// set solution as initial values
m.solAsInit();
m.show_solver = false;
m.solve();
if (not m.hasSolution())
cout<<"no solution"<<endl;
// test for specific solver status
if (m.status()==MadOpt::Solution::LOCAL_INFEASIBILITY)
cout<<"Infeasible"<<endl;
return 0;
}
<commit_msg>fixed bug in example<commit_after>/*
* Copyright 2014 National ICT Australia Limited (NICTA)
*
* 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 <madopt/ipopt_model.hpp>
//#include <madopt/bonmin_model.hpp>
#include <vector>
#include <math.h>
using namespace std;
int main(){
int N = pow(10, 4);
//create IpoptModel
MadOpt::IpoptModel m;
//create BonminModel
//MadOpt::BonminModel m;
// Options
//
//
//m.setIntegerOption("print_level", 5);
//m.setStringOption("print_timing_statistics", "yes");
//m.setStringOption("hessian_approximation", "limited-memory");
// shortcut flags
// set flag if solver output should be printed
m.show_solver = true;
// timelimit, a negative value disables the time limit
m.timelimit = 12;
// Variables
//
//
// create continuous variable x
// lower bound = -1.5
// upper bound = 0
// initial value = -0.5
// MadOpt::Var x = m.addVar(-1.5, 0, -0.5, "x");
// to set a bound to infinity use MadOpt::INF
// MadOpt::Var v = m.addVar(MadOpt::INF, 0, -0.5, "v");
// create integer variable y
// lower bound = 1
// upper bound = 10
// initial value = 4
// MadOpt::Var y = m.addIVar(1, 10, 4, "y");
// create binary variable z
// initial value = 1
// MadOpt::Var z = m.addBVar(1, "z");
vector<MadOpt::Var> x(N);
for (int i=0; i<N; i++){
x[i] = m.addVar(-1.5, 0, -0.5, "x" + to_string(i));
}
// Parameters
//
//
// create Parameter
// value = 1
// name = p
// MadOpt::Param p = m.addParam(1, "p");
vector<MadOpt::Param> p(N-2);
for (int i=0; i<N-2; i++){
double a = double(i+2)/(double)N;
p[i] = m.addParam(a, "p"+to_string(i));
}
// Constraints
//
//
// expr = expression build from constants, variables MadOpt::Var, parameters MadOpt::Param
// lb = lower bound, double
// ub = upper bound, double
//
// add constraint of type:
//
// lb <= expr <= ub
// m.addConstr(lb, expr, ub);
//
// lb <= expr <= INF
// m.addConstr(lb, expr);
//
// INF <= expr <= ub
// m.addConstr(expr, ub);
//
// expr == eq
// m.addEqConstr(expr, eq);
vector<MadOpt::Constraint> c(N-2);
for (int i=0; i<N-2; i++){
c[i] = m.addEqConstr((MadOpt::pow(x[i+1], 2) + 1.5*x[i+1] - p[i])*MadOpt::cos(x[i+2]) - x[i], 0);
}
// Objective
//
//
MadOpt::Expr obj(0);
for (int i=0; i<N; i++)
obj += MadOpt::pow(x[i] - 1, 2);
// set objective
m.setObj(obj);
// calling the solver
//
//
m.solve();
// check if a solution exists, or in other words if the solver succeeded
//
//
if (m.hasSolution()){
// access objective value
cout<<"Objective:"<<m.objValue()<<endl;
// access solver status == Ipopt status values
cout<<"Solver status:"<<m.status()<<endl;
//print solution value of first variable
cout<<"Solution value for x0:"<<x[0].x()<<endl;
//print lambda value of constraint, only available for IpoptModel
cout<<"Lambda value of constraint 0:"<<c[0].lam()<<endl;
}
//changing the model
//
//
// Variables
//change variable bounds and initial value
x[1].lb(-12);
x[1].ub(1);
x[1].init(0);
//access bounds and initial values
cout<<"Variable values: lb="<<x[1].lb()<<" ub="<<x[1].ub()<<" init="<<x[1].init()<<endl;
//Constraints
//change constraint bounds
c[0].lb(-1);
c[0].ub(2);
//access bounds
cout<<"Constraint bounds: lb="<<c[0].lb()<<" ub="<<c[0].ub()<<endl;
//Parameter
// change value
p[0].value(12);
// access value
cout<<"Parameter value:"<<p[0].value()<<endl;
// resolve
//
//
// set solution as initial values
m.solAsInit();
m.show_solver = false;
m.solve();
if (not m.hasSolution())
cout<<"no solution"<<endl;
// test for specific solver status
if (m.status()==MadOpt::Solution::LOCAL_INFEASIBILITY)
cout<<"Infeasible"<<endl;
return 0;
}
<|endoftext|> |
<commit_before>//
// Name: canvas.cpp
// Purpose: Implements the canvas class for a wxWindows application.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// Header for the vtlib library
#include "vtlib/vtlib.h"
#include "canvas.h"
#include "frame.h"
#include "app.h"
DECLARE_APP(vtApp);
/*
* vtGLCanvas implementation
*/
BEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)
EVT_SIZE(vtGLCanvas::OnSize)
EVT_PAINT(vtGLCanvas::OnPaint)
EVT_CHAR(vtGLCanvas::OnChar)
EVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)
EVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)
END_EVENT_TABLE()
vtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):
wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
parent->Show(TRUE);
SetCurrent();
m_bPainting = false;
m_bRunning = true;
QueueRefresh(FALSE);
}
vtGLCanvas::~vtGLCanvas(void)
{
}
void vtGLCanvas::QueueRefresh(bool eraseBackground)
// A Refresh routine we can call from inside OnPaint.
// (queues the events rather than dispatching them immediately).
{
#if !WIN32
// With wxGTK, you can't do a Refresh() in OnPaint because it doesn't
// queue (post) a Refresh event for later. Rather it dispatches
// (processes) the underlying events immediately via ProcessEvent
// (read, recursive call). See the wxPostEvent docs and Refresh code
// for more details.
if ( eraseBackground )
{
wxEraseEvent eevent( GetId() );
eevent.SetEventObject( this );
wxPostEvent( GetEventHandler(), eevent );
}
wxPaintEvent event( GetId() );
event.SetEventObject( this );
wxPostEvent( GetEventHandler(), event );
#endif
}
void vtGLCanvas::OnPaint( wxPaintEvent& event )
{
// Prevent this function from ever being called nested, it is not re-entrant
static bool bInside = false;
if (bInside)
return;
bInside = true;
vtScene *pScene = vtGetScene();
if (!pScene->HasWinInfo())
{
#ifdef WIN32
HWND handle = (HWND) GetHandle();
pScene->SetWinInfo(handle, m_glContext);
#else
pScene->SetWinInfo(NULL, NULL);
#endif
}
// place the dc inside a scope, to delete it before the end of function
if (1)
{
// This is a dummy, to avoid an endless succession of paint messages.
// OnPaint handlers must always create a wxPaintDC.
wxPaintDC dc(this);
#ifdef __WXMSW__
if (!GetContext()) return;
#endif
if (m_bPainting || !m_bRunning) return;
#if !VTLIB_PSM
m_bPainting = true;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render the SSG scene
vtGetScene()->DoUpdate();
SwapBuffers();
#ifdef WIN32
// Call Refresh again for continuous rendering,
if (m_bRunning)
Refresh(FALSE);
#else
// Queue another refresh for continuous rendering.
// (Yield first so we don't starve out keyboard & mouse events.)
//
// FIXME: We may want to use a frame timer instead of immediate-
// redraw so we don't eat so much CPU on machines that can
// easily handle the frame rate.
wxYield();
QueueRefresh(FALSE);
#endif
m_bPainting = false;
#endif // VTLIB_PSM
}
// Must allow some idle processing to occur - or the toolbars will not
// update, and the close box will not respond!
wxGetApp().ProcessIdle();
bInside = false;
}
static void Reshape(int width, int height)
{
printf("Reshape: %d, %d\n", width, height);
glViewport(0, 0, (GLint)width, (GLint)height);
}
void vtGLCanvas::OnSize(wxSizeEvent& event)
{
// Presumably this is a wxMSWism.
// For wxGTK & wxMotif, all canvas resize events occur before the context
// is set. So ignore this context check and grab the window width/height
// when we get it so it (and derived values such as aspect ratio and
// viewport parms) are computed correctly.
#ifdef __WXMSW__
if (!GetContext()) return;
#endif
SetCurrent();
int width, height;
GetClientSize(& width, & height);
Reshape(width, height);
vtGetScene()->SetWindowSize(width, height);
}
void vtGLCanvas::OnChar(wxKeyEvent& event)
{
long key = event.KeyCode();
if ( key == WXK_ESCAPE || key == 'q' || key == 'Q' )
wxGetApp().GetTopWindow()->Close();
// pass the char to the vtlib Scene
vtGetScene()->OnKey(key, 0);
}
void vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)
{
// turn WX mouse event into a VT mouse event
vtMouseEvent event;
wxEventType type = event1.GetEventType();
if ( type == wxEVT_LEFT_DOWN )
{
event.type = VT_DOWN;
event.button = VT_LEFT;
}
else if ( type == wxEVT_LEFT_UP )
{
event.type = VT_UP;
event.button = VT_LEFT;
}
else if ( type == wxEVT_MIDDLE_DOWN )
{
event.type = VT_DOWN;
event.button = VT_MIDDLE;
}
else if ( type == wxEVT_MIDDLE_UP )
{
event.type = VT_UP;
event.button = VT_MIDDLE;
}
else if ( type == wxEVT_RIGHT_DOWN )
{
event.type = VT_DOWN;
event.button = VT_RIGHT;
}
else if ( type == wxEVT_RIGHT_UP )
{
event.type = VT_UP;
event.button = VT_RIGHT;
}
else if ( type == wxEVT_MOTION )
{
event.type = VT_MOVE;
event.button = VT_NONE;
}
else
{
// ignore other mouse events, such as wxEVT_LEAVE_WINDOW
return;
}
event.flags = 0;
wxCoord xpos, ypos;
event1.GetPosition(&xpos, &ypos);
event.pos.Set(xpos, ypos);
if (event1.ControlDown())
event.flags |= VT_CONTROL;
if (event1.ShiftDown())
event.flags |= VT_SHIFT;
vtGetScene()->OnMouse(event);
}
void vtGLCanvas::OnEraseBackground(wxEraseEvent& event)
{
// Do nothing, to avoid flashing.
}
<commit_msg>added vtlib/core/Event.h<commit_after>//
// Name: canvas.cpp
// Purpose: Implements the canvas class for a wxWindows application.
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// Header for the vtlib library
#include "vtlib/vtlib.h"
#include "vtlib/core/Event.h"
#include "canvas.h"
#include "frame.h"
#include "app.h"
DECLARE_APP(vtApp);
/*
* vtGLCanvas implementation
*/
BEGIN_EVENT_TABLE(vtGLCanvas, wxGLCanvas)
EVT_SIZE(vtGLCanvas::OnSize)
EVT_PAINT(vtGLCanvas::OnPaint)
EVT_CHAR(vtGLCanvas::OnChar)
EVT_MOUSE_EVENTS(vtGLCanvas::OnMouseEvent)
EVT_ERASE_BACKGROUND(vtGLCanvas::OnEraseBackground)
END_EVENT_TABLE()
vtGLCanvas::vtGLCanvas(wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size, long style, const wxString& name, int* gl_attrib):
wxGLCanvas(parent, id, pos, size, style, name, gl_attrib)
{
parent->Show(TRUE);
SetCurrent();
m_bPainting = false;
m_bRunning = true;
QueueRefresh(FALSE);
}
vtGLCanvas::~vtGLCanvas(void)
{
}
void vtGLCanvas::QueueRefresh(bool eraseBackground)
// A Refresh routine we can call from inside OnPaint.
// (queues the events rather than dispatching them immediately).
{
#if !WIN32
// With wxGTK, you can't do a Refresh() in OnPaint because it doesn't
// queue (post) a Refresh event for later. Rather it dispatches
// (processes) the underlying events immediately via ProcessEvent
// (read, recursive call). See the wxPostEvent docs and Refresh code
// for more details.
if ( eraseBackground )
{
wxEraseEvent eevent( GetId() );
eevent.SetEventObject( this );
wxPostEvent( GetEventHandler(), eevent );
}
wxPaintEvent event( GetId() );
event.SetEventObject( this );
wxPostEvent( GetEventHandler(), event );
#endif
}
void vtGLCanvas::OnPaint( wxPaintEvent& event )
{
// Prevent this function from ever being called nested, it is not re-entrant
static bool bInside = false;
if (bInside)
return;
bInside = true;
vtScene *pScene = vtGetScene();
if (!pScene->HasWinInfo())
{
#ifdef WIN32
HWND handle = (HWND) GetHandle();
pScene->SetWinInfo(handle, m_glContext);
#else
pScene->SetWinInfo(NULL, NULL);
#endif
}
// place the dc inside a scope, to delete it before the end of function
if (1)
{
// This is a dummy, to avoid an endless succession of paint messages.
// OnPaint handlers must always create a wxPaintDC.
wxPaintDC dc(this);
#ifdef __WXMSW__
if (!GetContext()) return;
#endif
if (m_bPainting || !m_bRunning) return;
#if !VTLIB_PSM
m_bPainting = true;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render the SSG scene
vtGetScene()->DoUpdate();
SwapBuffers();
#ifdef WIN32
// Call Refresh again for continuous rendering,
if (m_bRunning)
Refresh(FALSE);
#else
// Queue another refresh for continuous rendering.
// (Yield first so we don't starve out keyboard & mouse events.)
//
// FIXME: We may want to use a frame timer instead of immediate-
// redraw so we don't eat so much CPU on machines that can
// easily handle the frame rate.
wxYield();
QueueRefresh(FALSE);
#endif
m_bPainting = false;
#endif // VTLIB_PSM
}
// Must allow some idle processing to occur - or the toolbars will not
// update, and the close box will not respond!
wxGetApp().ProcessIdle();
bInside = false;
}
static void Reshape(int width, int height)
{
printf("Reshape: %d, %d\n", width, height);
glViewport(0, 0, (GLint)width, (GLint)height);
}
void vtGLCanvas::OnSize(wxSizeEvent& event)
{
// Presumably this is a wxMSWism.
// For wxGTK & wxMotif, all canvas resize events occur before the context
// is set. So ignore this context check and grab the window width/height
// when we get it so it (and derived values such as aspect ratio and
// viewport parms) are computed correctly.
#ifdef __WXMSW__
if (!GetContext()) return;
#endif
SetCurrent();
int width, height;
GetClientSize(& width, & height);
Reshape(width, height);
vtGetScene()->SetWindowSize(width, height);
}
void vtGLCanvas::OnChar(wxKeyEvent& event)
{
long key = event.KeyCode();
if ( key == WXK_ESCAPE || key == 'q' || key == 'Q' )
wxGetApp().GetTopWindow()->Close();
// pass the char to the vtlib Scene
vtGetScene()->OnKey(key, 0);
}
void vtGLCanvas::OnMouseEvent(wxMouseEvent& event1)
{
// turn WX mouse event into a VT mouse event
vtMouseEvent event;
wxEventType type = event1.GetEventType();
if ( type == wxEVT_LEFT_DOWN )
{
event.type = VT_DOWN;
event.button = VT_LEFT;
}
else if ( type == wxEVT_LEFT_UP )
{
event.type = VT_UP;
event.button = VT_LEFT;
}
else if ( type == wxEVT_MIDDLE_DOWN )
{
event.type = VT_DOWN;
event.button = VT_MIDDLE;
}
else if ( type == wxEVT_MIDDLE_UP )
{
event.type = VT_UP;
event.button = VT_MIDDLE;
}
else if ( type == wxEVT_RIGHT_DOWN )
{
event.type = VT_DOWN;
event.button = VT_RIGHT;
}
else if ( type == wxEVT_RIGHT_UP )
{
event.type = VT_UP;
event.button = VT_RIGHT;
}
else if ( type == wxEVT_MOTION )
{
event.type = VT_MOVE;
event.button = VT_NONE;
}
else
{
// ignore other mouse events, such as wxEVT_LEAVE_WINDOW
return;
}
event.flags = 0;
wxCoord xpos, ypos;
event1.GetPosition(&xpos, &ypos);
event.pos.Set(xpos, ypos);
if (event1.ControlDown())
event.flags |= VT_CONTROL;
if (event1.ShiftDown())
event.flags |= VT_SHIFT;
vtGetScene()->OnMouse(event);
}
void vtGLCanvas::OnEraseBackground(wxEraseEvent& event)
{
// Do nothing, to avoid flashing.
}
<|endoftext|> |
<commit_before>#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;
}
<commit_msg>Refine Problem 152. Maximum Product Subarray<commit_after>#include "MaximumProductSubarray.hpp"
#include <algorithm>
using namespace std;
int MaximumProductSubarray::maxProduct(vector<int> &nums) {
if (nums.empty()) return 0;
vector<int> a(nums.begin(), nums.end());
vector<int> b(nums.begin(), nums.end());
int ret = a[0];
for (int i = 1; i < nums.size(); i++) {
int v1 = a[i - 1] * nums[i];
int v2 = b[i - 1] * nums[i];
a[i] = max(a[i], max(v1, v2));
b[i] = min(b[i], min(v1, v2));
ret = max(ret, a[i]);
}
return ret;
}
<|endoftext|> |
<commit_before>#include <Spirit_Defines.h>
#include <engine/Method_EMA.hpp>
#include <engine/Vectormath.hpp>
#include <data/Spin_System.hpp>
#include <io/IO.hpp>
#include <utility/Logging.hpp>
#include <fmt/format.h>
#include <Eigen/Dense>
#include <iostream>
#include <fstream>
#include <thread>
#include <chrono>
using namespace Utility;
namespace Engine
{
Method_EMA::Method_EMA(std::shared_ptr<Data::Spin_System> system, int idx_img, int idx_chain) :
Method(system->ema_parameters, idx_img, idx_chain)
{
// Currently we only support a single image being iterated at once:
this->systems = std::vector<std::shared_ptr<Data::Spin_System>>(1, system);
this->SenderName = Utility::Log_Sender::EMA;
this->noi = this->systems.size();
this->nos = this->systems[0]->nos;
this->parameters_ema = system->ema_parameters;
this->spins_initial = *this->systems[0]->spins;
this->axis = vectorfield(this->nos);
this->mode = vectorfield(this->nos, Vector3{1,0,0});
this->steps_per_period = 50;
this->timestep = 1./this->steps_per_period;
this->counter = 0;
this->amplitude = 0.2;
// Find the axes of rotation
for (int idx=0; idx<nos; idx++)
this->axis[idx] = spins_initial[idx].cross(this->mode[idx]).normalized();
}
void Method_EMA::Iteration()
{
int nos = this->systems[0]->spins->size();
auto& image = *this->systems[0]->spins;
// Calculate n for that iteration based on the initial n displacement vector
scalar angle = this->amplitude * std::cos(2*M_PI*this->counter*this->timestep);
// Rotate the spins
for (int idx=0; idx<nos; idx++)
Vectormath::rotate( this->spins_initial[idx], this->axis[idx], angle, image[idx] );
// normalize all spins
Vectormath::normalize_vectors( *this->systems[0]->spins );
}
bool Method_EMA::Converged()
{
//// TODO: Needs proper implementation
return false;
}
void Method_EMA::Save_Current(std::string starttime, int iteration, bool initial, bool final)
{
}
void Method_EMA::Hook_Pre_Iteration()
{
}
void Method_EMA::Hook_Post_Iteration()
{
++this->counter;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
void Method_EMA::Initialize()
{
}
void Method_EMA::Finalize()
{
}
void Method_EMA::Message_Start()
{
using namespace Utility;
//---- Log messages
Log.SendBlock(Log_Level::All, this->SenderName,
{
"------------ Started " + this->Name() + " Calculation ------------",
" Going to iterate " + fmt::format("{}", this->n_log) + " steps",
" with " + fmt::format("{}", this->n_iterations_log) + " iterations per step",
" Number of modes " + fmt::format("{}", this->parameters_ema->n_modes ),
"-----------------------------------------------------"
}, this->idx_image, this->idx_chain);
}
void Method_EMA::Message_Step()
{
}
void Method_EMA::Message_End()
{
}
// Method name as string
std::string Method_EMA::Name() { return "EMA"; }
}<commit_msg>Core: added eigenmode calculation to Method_EMA.<commit_after>#include <Spirit_Defines.h>
#include <engine/Method_EMA.hpp>
#include <engine/Vectormath.hpp>
#include <data/Spin_System.hpp>
#include <io/IO.hpp>
#include <utility/Logging.hpp>
#include <fmt/format.h>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <GenEigsSolver.h> // Also includes <MatOp/DenseGenMatProd.h>
#include <GenEigsRealShiftSolver.h>
#include <iostream>
#include <fstream>
#include <thread>
#include <chrono>
using namespace Utility;
namespace Engine
{
Method_EMA::Method_EMA(std::shared_ptr<Data::Spin_System> system, int idx_img, int idx_chain) :
Method(system->ema_parameters, idx_img, idx_chain)
{
// Currently we only support a single image being iterated at once:
this->systems = std::vector<std::shared_ptr<Data::Spin_System>>(1, system);
this->SenderName = Utility::Log_Sender::EMA;
this->noi = this->systems.size();
this->nos = this->systems[0]->nos;
this->parameters_ema = system->ema_parameters;
this->steps_per_period = 50;
this->timestep = 1./this->steps_per_period;
this->counter = 0;
this->amplitude = 0.2;
this->spins_initial = *this->systems[0]->spins;
this->axis = vectorfield(this->nos);
// Calculate the Eigenmodes
int n_modes = 10;
int selected_mode = 0;
vectorfield gradient(this->nos);
MatrixX hessian(3*this->nos, 3*this->nos);
// The gradient (unprojected)
system->hamiltonian->Gradient(spins_initial, gradient);
Vectormath::set_c_a(1, gradient, gradient, this->parameters->pinning->mask_unpinned);
// The Hessian (unprojected)
system->hamiltonian->Hessian(spins_initial, hessian);
// Calculate the final Hessian to use for the minimum mode
MatrixX hessian_final = MatrixX::Zero(2*this->nos, 2*this->nos);
Manifoldmath::hessian_bordered(spins_initial, gradient, hessian, hessian_final);
Spectra::DenseGenMatProd<scalar> op(hessian_final);
Spectra::GenEigsSolver< scalar, Spectra::SMALLEST_REAL, Spectra::DenseGenMatProd<scalar> > hessian_spectrum(&op, n_modes, 2*this->nos);
hessian_spectrum.init();
// Compute the specified spectrum
int nconv = hessian_spectrum.compute(1000, 1e-10, int(Spectra::SMALLEST_REAL));
this->mode = vectorfield(this->nos, Vector3{1, 0, 0});
if (hessian_spectrum.info() == Spectra::SUCCESSFUL)
{
// Retrieve the eigenvalues
// VectorX evalues = hessian_spectrum.eigenvalues().real();
// Retrieve the eigenmode
VectorX evec_2N = hessian_spectrum.eigenvectors().real().col(selected_mode);
// Extract the minimum mode (transform evec_lowest_2N back to 3N)
MatrixX basis_3Nx2N = MatrixX::Zero(3*nos, 2*nos);
Manifoldmath::tangent_basis_spherical(spins_initial, basis_3Nx2N); // Important to choose the right matrix here! It should especially be consistent with the matrix chosen in the Hessian calculation!
VectorX evec_3N = basis_3Nx2N * evec_2N;
// Set the mode
for (int n=0; n<this->nos; ++n)
this->mode[n] = {evec_3N[3*n], evec_3N[3*n+1], evec_3N[3*n+2]};
}
// Find the axes of rotation
for (int idx=0; idx<nos; idx++)
this->axis[idx] = spins_initial[idx].cross(this->mode[idx]).normalized();
}
void Method_EMA::Iteration()
{
int nos = this->systems[0]->spins->size();
auto& image = *this->systems[0]->spins;
// Calculate n for that iteration based on the initial n displacement vector
scalar angle = this->amplitude * std::cos(2*M_PI*this->counter*this->timestep);
// Rotate the spins
for (int idx=0; idx<nos; idx++)
Vectormath::rotate( this->spins_initial[idx], this->axis[idx], angle, image[idx] );
// normalize all spins
Vectormath::normalize_vectors( *this->systems[0]->spins );
}
bool Method_EMA::Converged()
{
//// TODO: Needs proper implementation
return false;
}
void Method_EMA::Save_Current(std::string starttime, int iteration, bool initial, bool final)
{
}
void Method_EMA::Hook_Pre_Iteration()
{
}
void Method_EMA::Hook_Post_Iteration()
{
++this->counter;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
void Method_EMA::Initialize()
{
}
void Method_EMA::Finalize()
{
}
void Method_EMA::Message_Start()
{
using namespace Utility;
//---- Log messages
Log.SendBlock(Log_Level::All, this->SenderName,
{
"------------ Started " + this->Name() + " Calculation ------------",
" Going to iterate " + fmt::format("{}", this->n_log) + " steps",
" with " + fmt::format("{}", this->n_iterations_log) + " iterations per step",
" Number of modes " + fmt::format("{}", this->parameters_ema->n_modes ),
"-----------------------------------------------------"
}, this->idx_image, this->idx_chain);
}
void Method_EMA::Message_Step()
{
}
void Method_EMA::Message_End()
{
}
// Method name as string
std::string Method_EMA::Name() { return "EMA"; }
}<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "core/clever.h"
#include "modules/std/core/function.h"
#include "modules/std/reflection/reflect.h"
#include "modules/std/core/array.h"
#include "modules/std/core/map.h"
namespace clever { namespace packages { namespace std { namespace reflection {
void* ReflectType::allocData(CLEVER_TYPE_CTOR_ARGS) const
{
ReflectObject* obj = new ReflectObject;
obj->setData(args->at(0));
return obj;
}
// Reflect::Reflect(object)
// Returns an instance of Reflect object
CLEVER_METHOD(ReflectType::ctor)
{
if (!clever_check_args(".")) {
return;
}
result->setObj(this, allocData(&args));
}
// Reflect::getType()
// Returns the type name of the object
CLEVER_METHOD(ReflectType::getType)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
if (intern->getData()->getType()) {
result->setStr(intern->getData()->getType()->getName());
}
}
// Reflect::isFunction()
// Check if the object is of function type
CLEVER_METHOD(ReflectType::isFunction)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isFunction());
}
// Reflect::isBool()
// Check if the object is of bool type
CLEVER_METHOD(ReflectType::isBool)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isBool());
}
// Reflect::isString()
// Check if the object is of string type
CLEVER_METHOD(ReflectType::isString)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isStr());
}
// Reflect::isInt()
// Check if the object is of int type
CLEVER_METHOD(ReflectType::isInt)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isInt());
}
// Reflect::isDouble()
// Check if the object is of double type
CLEVER_METHOD(ReflectType::isDouble)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isDouble());
}
// Reflect::isArray()
// Check if the object is of double type
CLEVER_METHOD(ReflectType::isArray)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isArray());
}
// Reflect::isMap()
// Check if the object is of map type
CLEVER_METHOD(ReflectType::isMap)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isMap());
}
// Reflect::isThread()
// Check if the object is of thread type
CLEVER_METHOD(ReflectType::isThread)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isThread());
}
// Reflect::getName()
// Returns the name of the type or function
CLEVER_METHOD(ReflectType::getName)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setStr(CSTRING(func->getName()));
}
// Reflect::isStatic()
// Check if the object is an static function
CLEVER_METHOD(ReflectType::isStatic)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isStatic());
}
// Reflect::isVariadic()
// Check if the object is a variadic function
CLEVER_METHOD(ReflectType::isVariadic)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isVariadic());
}
// Reflect::isUserDefined()
// Check if the object is an user-defined function
CLEVER_METHOD(ReflectType::isUserDefined)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isUserDefined());
}
// Reflect::isInternal()
// Check if the object is an internal function
CLEVER_METHOD(ReflectType::isInternal)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isInternal());
}
// Reflect::getNumArgs()
// Returns the number of arguments (variadic is not in the count)
CLEVER_METHOD(ReflectType::getNumArgs)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setInt(func->getNumArgs());
}
// Reflect::getNumRegArgs()
// Returns the number of required arguments (variadic is not in the count)
CLEVER_METHOD(ReflectType::getNumReqArgs)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setInt(func->getNumRequiredArgs());
}
// Reflect::getMethods()
// Returns an array with the type methods
CLEVER_METHOD(ReflectType::getMethods)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const MethodMap& methods = intern->getData()->getType()->getMethods();
MethodMap::const_iterator it(methods.begin()), end(methods.end());
ArrayObject* arr = new ArrayObject;
while (it != end) {
Value* val = new Value;
val->setStr(CSTRING(it->second->getName()));
arr->getData().push_back(val);
++it;
}
result->setObj(CLEVER_ARRAY_TYPE, arr);
}
// Reflect::getProperties()
// Returns the type properties
CLEVER_METHOD(ReflectType::getProperties)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const PropertyMap& props = intern->getData()->getType()->getProperties();
PropertyMap::const_iterator it(props.begin()), end(props.end());
MapObject* map = new MapObject;
while (it != end) {
map->getData().insert(MapObjectPair(*it->first, it->second));
it->second->addRef();
++it;
}
result->setObj(CLEVER_MAP_TYPE, map);
}
// Reflect type initialization
CLEVER_TYPE_INIT(ReflectType::init)
{
Function* ctor = new Function("Reflect", (MethodPtr) &ReflectType::ctor);
setConstructor(ctor);
addMethod(ctor);
addMethod(new Function("getType", (MethodPtr) &ReflectType::getType));
// Type checking
addMethod(new Function("isFunction", (MethodPtr) &ReflectType::isFunction));
addMethod(new Function("isBool", (MethodPtr) &ReflectType::isBool));
addMethod(new Function("isString", (MethodPtr) &ReflectType::isString));
addMethod(new Function("isInt", (MethodPtr) &ReflectType::isInt));
addMethod(new Function("isDouble", (MethodPtr) &ReflectType::isDouble));
addMethod(new Function("isArray", (MethodPtr) &ReflectType::isArray));
addMethod(new Function("isMap", (MethodPtr) &ReflectType::isMap));
addMethod(new Function("isThread", (MethodPtr) &ReflectType::isThread));
// Function specific methods
addMethod(new Function("getName", (MethodPtr) &ReflectType::getName));
addMethod(new Function("isStatic", (MethodPtr) &ReflectType::isStatic));
addMethod(new Function("isVariadic", (MethodPtr) &ReflectType::isVariadic));
addMethod(new Function("isUserDefined", (MethodPtr) &ReflectType::isUserDefined));
addMethod(new Function("isInternal", (MethodPtr) &ReflectType::isInternal));
addMethod(new Function("getNumArgs", (MethodPtr) &ReflectType::getNumArgs));
addMethod(new Function("getNumReqArgs", (MethodPtr) &ReflectType::getNumReqArgs));
// Type specific methods
addMethod(new Function("getMethods", (MethodPtr) &ReflectType::getMethods));
addMethod(new Function("getProperties", (MethodPtr) &ReflectType::getProperties));
}
}}}} // clever::packages::std::reflection
<commit_msg>- Fix comments<commit_after>/**
* Clever programming language
* Copyright (c) Clever Team
*
* This file is distributed under the MIT license. See LICENSE for details.
*/
#include "core/clever.h"
#include "modules/std/core/function.h"
#include "modules/std/reflection/reflect.h"
#include "modules/std/core/array.h"
#include "modules/std/core/map.h"
namespace clever { namespace packages { namespace std { namespace reflection {
void* ReflectType::allocData(CLEVER_TYPE_CTOR_ARGS) const
{
ReflectObject* obj = new ReflectObject;
obj->setData(args->at(0));
return obj;
}
// Reflect::Reflect(object)
// Returns an instance of Reflect object
CLEVER_METHOD(ReflectType::ctor)
{
if (!clever_check_args(".")) {
return;
}
result->setObj(this, allocData(&args));
}
// Reflect::getType()
// Returns the type name of the object
CLEVER_METHOD(ReflectType::getType)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
if (intern->getData()->getType()) {
result->setStr(intern->getData()->getType()->getName());
}
}
// Reflect::isFunction()
// Check if the object is of function type
CLEVER_METHOD(ReflectType::isFunction)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isFunction());
}
// Reflect::isBool()
// Check if the object is of bool type
CLEVER_METHOD(ReflectType::isBool)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isBool());
}
// Reflect::isString()
// Check if the object is of string type
CLEVER_METHOD(ReflectType::isString)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isStr());
}
// Reflect::isInt()
// Check if the object is of int type
CLEVER_METHOD(ReflectType::isInt)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isInt());
}
// Reflect::isDouble()
// Check if the object is of double type
CLEVER_METHOD(ReflectType::isDouble)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isDouble());
}
// Reflect::isArray()
// Check if the object is of double type
CLEVER_METHOD(ReflectType::isArray)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isArray());
}
// Reflect::isMap()
// Check if the object is of map type
CLEVER_METHOD(ReflectType::isMap)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isMap());
}
// Reflect::isThread()
// Check if the object is of thread type
CLEVER_METHOD(ReflectType::isThread)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
result->setBool(intern->getData()->isThread());
}
// Reflect::getName()
// Returns the name of the type or function
CLEVER_METHOD(ReflectType::getName)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setStr(CSTRING(func->getName()));
}
// Reflect::isStatic()
// Check if the object is an static function
CLEVER_METHOD(ReflectType::isStatic)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isStatic());
}
// Reflect::isVariadic()
// Check if the object is a variadic function
CLEVER_METHOD(ReflectType::isVariadic)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isVariadic());
}
// Reflect::isUserDefined()
// Check if the object is an user-defined function
CLEVER_METHOD(ReflectType::isUserDefined)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isUserDefined());
}
// Reflect::isInternal()
// Check if the object is an internal function
CLEVER_METHOD(ReflectType::isInternal)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setBool(func->isInternal());
}
// Reflect::getNumArgs()
// Returns the number of arguments (variadic is not in the count)
CLEVER_METHOD(ReflectType::getNumArgs)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setInt(func->getNumArgs());
}
// Reflect::getNumRegArgs()
// Returns the number of required arguments (variadic is not in the count)
CLEVER_METHOD(ReflectType::getNumReqArgs)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const Value* data = intern->getData();
if (!data->isFunction()) {
return;
}
const Function* func = static_cast<Function*>(data->getObj());
result->setInt(func->getNumRequiredArgs());
}
// Reflect::getMethods()
// Returns an array containing the type methods
CLEVER_METHOD(ReflectType::getMethods)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const MethodMap& methods = intern->getData()->getType()->getMethods();
MethodMap::const_iterator it(methods.begin()), end(methods.end());
ArrayObject* arr = new ArrayObject;
while (it != end) {
Value* val = new Value;
val->setStr(CSTRING(it->second->getName()));
arr->getData().push_back(val);
++it;
}
result->setObj(CLEVER_ARRAY_TYPE, arr);
}
// Reflect::getProperties()
// Returns a map containing the type properties
CLEVER_METHOD(ReflectType::getProperties)
{
if (!clever_check_no_args()) {
return;
}
const ReflectObject* intern = CLEVER_GET_OBJECT(ReflectObject*, CLEVER_THIS());
const PropertyMap& props = intern->getData()->getType()->getProperties();
PropertyMap::const_iterator it(props.begin()), end(props.end());
MapObject* map = new MapObject;
while (it != end) {
map->getData().insert(MapObjectPair(*it->first, it->second));
it->second->addRef();
++it;
}
result->setObj(CLEVER_MAP_TYPE, map);
}
// Reflect type initialization
CLEVER_TYPE_INIT(ReflectType::init)
{
Function* ctor = new Function("Reflect", (MethodPtr) &ReflectType::ctor);
setConstructor(ctor);
addMethod(ctor);
addMethod(new Function("getType", (MethodPtr) &ReflectType::getType));
// Type checking
addMethod(new Function("isFunction", (MethodPtr) &ReflectType::isFunction));
addMethod(new Function("isBool", (MethodPtr) &ReflectType::isBool));
addMethod(new Function("isString", (MethodPtr) &ReflectType::isString));
addMethod(new Function("isInt", (MethodPtr) &ReflectType::isInt));
addMethod(new Function("isDouble", (MethodPtr) &ReflectType::isDouble));
addMethod(new Function("isArray", (MethodPtr) &ReflectType::isArray));
addMethod(new Function("isMap", (MethodPtr) &ReflectType::isMap));
addMethod(new Function("isThread", (MethodPtr) &ReflectType::isThread));
// Function specific methods
addMethod(new Function("getName", (MethodPtr) &ReflectType::getName));
addMethod(new Function("isStatic", (MethodPtr) &ReflectType::isStatic));
addMethod(new Function("isVariadic", (MethodPtr) &ReflectType::isVariadic));
addMethod(new Function("isUserDefined", (MethodPtr) &ReflectType::isUserDefined));
addMethod(new Function("isInternal", (MethodPtr) &ReflectType::isInternal));
addMethod(new Function("getNumArgs", (MethodPtr) &ReflectType::getNumArgs));
addMethod(new Function("getNumReqArgs", (MethodPtr) &ReflectType::getNumReqArgs));
// Type specific methods
addMethod(new Function("getMethods", (MethodPtr) &ReflectType::getMethods));
addMethod(new Function("getProperties", (MethodPtr) &ReflectType::getProperties));
}
}}}} // clever::packages::std::reflection
<|endoftext|> |
<commit_before><commit_msg>[Part] AppPartPy.cpp Python 3.9 Unicode warning fixes.<commit_after><|endoftext|> |
<commit_before>/*
* superviseddescent: A C++11 implementation of the supervised descent
* optimisation method
* File: examples/rcr/helpers.hpp
*
* Copyright 2015 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef HELPERS_HPP_
#define HELPERS_HPP_
#include "eos_core_landmark.hpp"
#include <vector>
namespace rcr {
// for float-type landmarks
// returns a row in the form [x0, y0, ..., xn, yn]
// type of returned Mat is CV_32FC1
// we could write this more generic if needed
//template<class LandmarkType>
cv::Mat toRow(eos::core::LandmarkCollection<cv::Vec2f> landmarks)
{
auto numLandmarks = landmarks.size();
cv::Mat row(1, numLandmarks * 2, CV_32FC1);
for (std::size_t i = 0; i < numLandmarks; ++i) {
row.at<float>(i) = landmarks[i].coordinates[0];
row.at<float>(i + numLandmarks) = landmarks[i].coordinates[1];
}
return row;
}
// document how they're gonna be taken/expected from/int he Mat
eos::core::LandmarkCollection<cv::Vec2f> toLandmarkCollection(cv::Mat modelInstance, std::vector<std::string> modelLandmarksList)
{
eos::core::LandmarkCollection<cv::Vec2f> collection;
auto numLandmarks = modelInstance.cols / 2;
assert(numLandmarks == modelLandmarksList.size()); // shouldn't be an assert, not a programming/internal error.
for (int i = 0; i < numLandmarks; ++i) {
collection.emplace_back(eos::core::Landmark<cv::Vec2f>{ modelLandmarksList[i], cv::Vec2f{ modelInstance.at<float>(i), modelInstance.at<float>(i + numLandmarks) } });
}
return collection;
}
/**
* Draws the given landmarks into the image.
*
* @param[in] image An image to draw into.
* @param[in] landmarks The landmarks to draw.
* @param[in] color Color of the landmarks to be drawn.
*/
void drawLandmarks(cv::Mat image, cv::Mat landmarks, cv::Scalar color = cv::Scalar(0.0, 255.0, 0.0))
{
auto numLandmarks = std::max(landmarks.cols, landmarks.rows) / 2;
for (int i = 0; i < numLandmarks; ++i) {
cv::circle(image, cv::Point2f(landmarks.at<float>(i), landmarks.at<float>(i + numLandmarks)), 2, color);
}
}
// checks overlap...
// Possible better names: checkEqual, checkIsTruePositive, overlap...
bool checkFace(std::vector<cv::Rect> detectedFaces, eos::core::LandmarkCollection<cv::Vec2f> groundtruthLandmarks)
{
// If no face is detected, return immediately:
if (detectedFaces.empty()) {
return false;
}
bool isTruePositive = true;
// for now, if the ground-truth landmarks 37 (reye_oc), 46 (leye_oc) and 58 (mouth_ll_c) are inside the face-box
// (should add: _and_ the face-box is not bigger than IED*2 or something)
//assert(groundtruthLandmarks.size() == 68); // only works with ibug-68 so far...
// for now: user should make sure we have 37, 46, 58.
for (const auto& lm : groundtruthLandmarks) {
if (lm.name == "37" || lm.name == "46" || lm.name == "58") {
if (!detectedFaces[0].contains(cv::Point(lm.coordinates))) {
isTruePositive = false;
break; // if any LM is not inside, skip this training image
// Note: improvement: if the first face-box doesn't work, try the other ones
}
}
}
return isTruePositive;
}
// Calculate the IED from one or several identifiers.
// Several is necessary because sometimes (e.g. ibug) doesn't define the eye center.
// throws if any of given ids not present in lms. => Todo: Think about if we should throw or use optional<>.
double getIed(eos::core::LandmarkCollection<cv::Vec2f> lms, std::vector<std::string> rightEyeIdentifiers, std::vector<std::string> leftEyeIdentifiers)
{
// Calculate the inter-eye distance. Which landmarks to take for that is specified in the config, it
// might be one or two, and we calculate the average of them (per eye). For example, it might be the outer eye-corners.
cv::Vec2f rightEyeCenter(0.0f, 0.0f);
for (const auto& rightEyeIdentifyer : rightEyeIdentifiers) {
eos::core::LandmarkCollection<cv::Vec2f>::const_iterator element;
if ((element = std::find_if(begin(lms), end(lms), [&rightEyeIdentifyer](const eos::core::Landmark<cv::Vec2f>& landmark) { return landmark.name == rightEyeIdentifyer; })) == end(lms)) {
throw std::runtime_error("one of given rightEyeIdentifiers ids not present in lms");
}
rightEyeCenter += element->coordinates;
}
rightEyeCenter /= static_cast<float>(rightEyeIdentifiers.size());
cv::Vec2f leftEyeCenter(0.0f, 0.0f);
for (const auto& leftEyeIdentifyer : leftEyeIdentifiers) {
eos::core::LandmarkCollection<cv::Vec2f>::const_iterator element;
if ((element = std::find_if(begin(lms), end(lms), [&leftEyeIdentifyer](const eos::core::Landmark<cv::Vec2f>& landmark) { return landmark.name == leftEyeIdentifyer; })) == end(lms)) {
throw std::runtime_error("one of given leftEyeIdentifiers ids not present in lms");
}
leftEyeCenter += element->coordinates;
}
leftEyeCenter /= static_cast<float>(leftEyeIdentifiers.size());
cv::Scalar interEyeDistance = cv::norm(rightEyeCenter, leftEyeCenter, cv::NORM_L2);
return interEyeDistance[0];
};
} /* namespace rcr */
#endif /* HELPERS_HPP_ */
<commit_msg>Fixed type conversion warning in toRow<commit_after>/*
* superviseddescent: A C++11 implementation of the supervised descent
* optimisation method
* File: examples/rcr/helpers.hpp
*
* Copyright 2015 Patrik Huber
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifndef HELPERS_HPP_
#define HELPERS_HPP_
#include "eos_core_landmark.hpp"
#include "opencv2/core/core.hpp"
#include <vector>
namespace rcr {
// for float-type landmarks
// returns a row in the form [x0, y0, ..., xn, yn]
// type of returned Mat is CV_32FC1
// we could write this more generic if needed
//template<class LandmarkType>
cv::Mat toRow(eos::core::LandmarkCollection<cv::Vec2f> landmarks)
{
// landmarks.size() must be <= max_int
auto numLandmarks = static_cast<int>(landmarks.size());
cv::Mat row(1, numLandmarks * 2, CV_32FC1);
for (int i = 0; i < numLandmarks; ++i) {
row.at<float>(i) = landmarks[i].coordinates[0];
row.at<float>(i + numLandmarks) = landmarks[i].coordinates[1];
}
return row;
}
// document how they're gonna be taken/expected from/int he Mat
eos::core::LandmarkCollection<cv::Vec2f> toLandmarkCollection(cv::Mat modelInstance, std::vector<std::string> modelLandmarksList)
{
eos::core::LandmarkCollection<cv::Vec2f> collection;
auto numLandmarks = modelInstance.cols / 2;
assert(numLandmarks == modelLandmarksList.size()); // shouldn't be an assert, not a programming/internal error.
for (int i = 0; i < numLandmarks; ++i) {
collection.emplace_back(eos::core::Landmark<cv::Vec2f>{ modelLandmarksList[i], cv::Vec2f{ modelInstance.at<float>(i), modelInstance.at<float>(i + numLandmarks) } });
}
return collection;
}
/**
* Draws the given landmarks into the image.
*
* @param[in] image An image to draw into.
* @param[in] landmarks The landmarks to draw.
* @param[in] color Color of the landmarks to be drawn.
*/
void drawLandmarks(cv::Mat image, cv::Mat landmarks, cv::Scalar color = cv::Scalar(0.0, 255.0, 0.0))
{
auto numLandmarks = std::max(landmarks.cols, landmarks.rows) / 2;
for (int i = 0; i < numLandmarks; ++i) {
cv::circle(image, cv::Point2f(landmarks.at<float>(i), landmarks.at<float>(i + numLandmarks)), 2, color);
}
}
// checks overlap...
// Possible better names: checkEqual, checkIsTruePositive, overlap...
bool checkFace(std::vector<cv::Rect> detectedFaces, eos::core::LandmarkCollection<cv::Vec2f> groundtruthLandmarks)
{
// If no face is detected, return immediately:
if (detectedFaces.empty()) {
return false;
}
bool isTruePositive = true;
// for now, if the ground-truth landmarks 37 (reye_oc), 46 (leye_oc) and 58 (mouth_ll_c) are inside the face-box
// (should add: _and_ the face-box is not bigger than IED*2 or something)
//assert(groundtruthLandmarks.size() == 68); // only works with ibug-68 so far...
// for now: user should make sure we have 37, 46, 58.
for (const auto& lm : groundtruthLandmarks) {
if (lm.name == "37" || lm.name == "46" || lm.name == "58") {
if (!detectedFaces[0].contains(cv::Point(lm.coordinates))) {
isTruePositive = false;
break; // if any LM is not inside, skip this training image
// Note: improvement: if the first face-box doesn't work, try the other ones
}
}
}
return isTruePositive;
}
// Calculate the IED from one or several identifiers.
// Several is necessary because sometimes (e.g. ibug) doesn't define the eye center.
// throws if any of given ids not present in lms. => Todo: Think about if we should throw or use optional<>.
double getIed(eos::core::LandmarkCollection<cv::Vec2f> lms, std::vector<std::string> rightEyeIdentifiers, std::vector<std::string> leftEyeIdentifiers)
{
// Calculate the inter-eye distance. Which landmarks to take for that is specified in the config, it
// might be one or two, and we calculate the average of them (per eye). For example, it might be the outer eye-corners.
cv::Vec2f rightEyeCenter(0.0f, 0.0f);
for (const auto& rightEyeIdentifyer : rightEyeIdentifiers) {
eos::core::LandmarkCollection<cv::Vec2f>::const_iterator element;
if ((element = std::find_if(begin(lms), end(lms), [&rightEyeIdentifyer](const eos::core::Landmark<cv::Vec2f>& landmark) { return landmark.name == rightEyeIdentifyer; })) == end(lms)) {
throw std::runtime_error("one of given rightEyeIdentifiers ids not present in lms");
}
rightEyeCenter += element->coordinates;
}
rightEyeCenter /= static_cast<float>(rightEyeIdentifiers.size());
cv::Vec2f leftEyeCenter(0.0f, 0.0f);
for (const auto& leftEyeIdentifyer : leftEyeIdentifiers) {
eos::core::LandmarkCollection<cv::Vec2f>::const_iterator element;
if ((element = std::find_if(begin(lms), end(lms), [&leftEyeIdentifyer](const eos::core::Landmark<cv::Vec2f>& landmark) { return landmark.name == leftEyeIdentifyer; })) == end(lms)) {
throw std::runtime_error("one of given leftEyeIdentifiers ids not present in lms");
}
leftEyeCenter += element->coordinates;
}
leftEyeCenter /= static_cast<float>(leftEyeIdentifiers.size());
cv::Scalar interEyeDistance = cv::norm(rightEyeCenter, leftEyeCenter, cv::NORM_L2);
return interEyeDistance[0];
};
} /* namespace rcr */
#endif /* HELPERS_HPP_ */
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/stdtypes.h>
#include <stx/logging.h>
#include <stx/io/fileutil.h>
#include <stx/io/mmappedfile.h>
#include <stx/protobuf/msg.h>
#include <stx/wallclock.h>
#include <zbase/core/CSTableIndex.h>
#include <zbase/core/CSTableIndexBuildState.pb.h>
#include <zbase/core/RecordSet.h>
#include <zbase/core/LogPartitionReader.h>
#include <stx/protobuf/MessageDecoder.h>
#include <cstable/RecordShredder.h>
#include <cstable/CSTableWriter.h>
using namespace stx;
namespace zbase {
CSTableIndex::CSTableIndex(
PartitionMap* pmap,
size_t nthreads) :
nthreads_(nthreads),
queue_([] (
const Pair<uint64_t, RefPtr<Partition>>& a,
const Pair<uint64_t, RefPtr<Partition>>& b) {
return a.first < b.first;
}),
running_(false) {
pmap->subscribeToPartitionChanges([this] (
RefPtr<zbase::PartitionChangeNotification> change) {
enqueuePartition(change->partition);
});
start();
}
CSTableIndex::~CSTableIndex() {
stop();
}
bool CSTableIndex::needsUpdate(
RefPtr<PartitionSnapshot> snap) const {
String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size());
auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
if (FileUtil::exists(metapath)) {
auto metadata = msg::decode<CSTableIndexBuildState>(
FileUtil::read(metapath));
if (metadata.uuid() == tbl_uuid &&
metadata.offset() >= snap->nrecs) {
return false;
}
}
return true;
}
void CSTableIndex::buildCSTable(RefPtr<Partition> partition) {
auto table = partition->getTable();
if (table->storage() != zbase::TBL_STORAGE_LOG) {
return;
}
auto t0 = WallClock::unixMicros();
auto snap = partition->getSnapshot();
if (!needsUpdate(snap)) {
return;
}
logDebug(
"tsdb",
"Building CSTable index for partition $0/$1/$2",
snap->state.tsdb_namespace(),
table->name(),
snap->key.toString());
auto filepath = FileUtil::joinPaths(snap->base_path, "_cstable");
auto filepath_tmp = filepath + "." + Random::singleton()->hex128();
auto schema = table->schema();
{
auto cstable = cstable::CSTableWriter::createFile(
filepath_tmp,
cstable::BinaryFormatVersion::v0_1_0,
cstable::TableSchema::fromProtobuf(*schema));
cstable::RecordShredder shredder(cstable.get());
auto reader_ptr = partition->getReader();
auto& reader = dynamic_cast<LogPartitionReader&>(*reader_ptr);
reader.fetchRecords([&schema, &shredder] (const Buffer& record) {
msg::MessageObject obj;
msg::MessageDecoder::decode(record.data(), record.size(), *schema, &obj);
shredder.addRecordFromProtobuf(obj, *schema);
});
cstable->commit();
}
auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
auto metapath_tmp = metapath + "." + Random::singleton()->hex128();
{
auto metafile = File::openFile(
metapath_tmp,
File::O_CREATE | File::O_WRITE);
CSTableIndexBuildState metadata;
metadata.set_offset(snap->nrecs);
metadata.set_uuid(snap->uuid().data(), snap->uuid().size());
auto buf = msg::encode(metadata);
metafile.write(buf->data(), buf->size());
}
FileUtil::mv(filepath_tmp, filepath);
FileUtil::mv(metapath_tmp, metapath);
auto t1 = WallClock::unixMicros();
logDebug(
"tsdb",
"Commiting CSTable index for partition $0/$1/$2, building took $3s",
snap->state.tsdb_namespace(),
table->name(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
}
void CSTableIndex::enqueuePartition(RefPtr<Partition> partition) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void CSTableIndex::enqueuePartitionWithLock(RefPtr<Partition> partition) {
auto interval = partition->getTable()->cstableBuildInterval();
auto uuid = partition->uuid();
if (waitset_.count(uuid) > 0) {
return;
}
queue_.emplace(
WallClock::unixMicros() + interval.microseconds(),
partition);
waitset_.emplace(uuid);
cv_.notify_all();
}
void CSTableIndex::start() {
running_ = true;
for (int i = 0; i < nthreads_; ++i) {
threads_.emplace_back(std::bind(&CSTableIndex::work, this));
}
}
void CSTableIndex::stop() {
if (!running_) {
return;
}
running_ = false;
cv_.notify_all();
for (auto& t : threads_) {
t.join();
}
}
void CSTableIndex::work() {
std::unique_lock<std::mutex> lk(mutex_);
while (running_) {
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
continue;
}
auto now = WallClock::unixMicros();
if (now < queue_.begin()->first) {
cv_.wait_for(
lk,
std::chrono::microseconds(queue_.begin()->first - now));
continue;
}
auto partition = queue_.begin()->second;
queue_.erase(queue_.begin());
bool success = true;
{
lk.unlock();
try {
buildCSTable(partition);
} catch (const StandardException& e) {
logError("tsdb", e, "CSTableIndex error");
success = false;
}
lk.lock();
}
if (success) {
waitset_.erase(partition->uuid());
if (needsUpdate(partition->getSnapshot())) {
enqueuePartitionWithLock(partition);
}
} else {
auto delay = 30 * kMicrosPerSecond; // FIXPAUL increasing delay..
queue_.emplace(now + delay, partition);
}
}
}
} // namespace zbase
<commit_msg>abort if cstable is too large<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stx/stdtypes.h>
#include <stx/logging.h>
#include <stx/io/fileutil.h>
#include <stx/io/mmappedfile.h>
#include <stx/protobuf/msg.h>
#include <stx/wallclock.h>
#include <zbase/core/CSTableIndex.h>
#include <zbase/core/CSTableIndexBuildState.pb.h>
#include <zbase/core/RecordSet.h>
#include <zbase/core/LogPartitionReader.h>
#include <stx/protobuf/MessageDecoder.h>
#include <cstable/RecordShredder.h>
#include <cstable/CSTableWriter.h>
using namespace stx;
namespace zbase {
CSTableIndex::CSTableIndex(
PartitionMap* pmap,
size_t nthreads) :
nthreads_(nthreads),
queue_([] (
const Pair<uint64_t, RefPtr<Partition>>& a,
const Pair<uint64_t, RefPtr<Partition>>& b) {
return a.first < b.first;
}),
running_(false) {
pmap->subscribeToPartitionChanges([this] (
RefPtr<zbase::PartitionChangeNotification> change) {
enqueuePartition(change->partition);
});
start();
}
CSTableIndex::~CSTableIndex() {
stop();
}
bool CSTableIndex::needsUpdate(
RefPtr<PartitionSnapshot> snap) const {
String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size());
auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
if (FileUtil::exists(metapath)) {
auto metadata = msg::decode<CSTableIndexBuildState>(
FileUtil::read(metapath));
if (metadata.uuid() == tbl_uuid &&
metadata.offset() >= snap->nrecs) {
return false;
}
}
return true;
}
void CSTableIndex::buildCSTable(RefPtr<Partition> partition) {
auto table = partition->getTable();
if (table->storage() != zbase::TBL_STORAGE_LOG) {
return;
}
auto t0 = WallClock::unixMicros();
auto snap = partition->getSnapshot();
if (!needsUpdate(snap)) {
return;
}
logDebug(
"tsdb",
"Building CSTable index for partition $0/$1/$2",
snap->state.tsdb_namespace(),
table->name(),
snap->key.toString());
auto filepath = FileUtil::joinPaths(snap->base_path, "_cstable");
auto filepath_tmp = filepath + "." + Random::singleton()->hex128();
auto schema = table->schema();
{
auto cstable = cstable::CSTableWriter::createFile(
filepath_tmp,
cstable::BinaryFormatVersion::v0_1_0,
cstable::TableSchema::fromProtobuf(*schema));
cstable::RecordShredder shredder(cstable.get());
auto reader_ptr = partition->getReader();
auto& reader = dynamic_cast<LogPartitionReader&>(*reader_ptr);
size_t total_size = 0;
reader.fetchRecords([&schema, &shredder, &total_size, &snap, &table] (const Buffer& record) {
msg::MessageObject obj;
msg::MessageDecoder::decode(record.data(), record.size(), *schema, &obj);
shredder.addRecordFromProtobuf(obj, *schema);
total_size += record.size();
static const size_t kMaxTableSize = 1024 * 1024 * 1024 * 4;
if (total_size > kMaxTableSize) {
RAISEF(
kRuntimeError,
"CSTable is too large $0/$1/$2",
snap->state.tsdb_namespace(),
table->name(),
snap->key.toString());
}
});
cstable->commit();
}
auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state");
auto metapath_tmp = metapath + "." + Random::singleton()->hex128();
{
auto metafile = File::openFile(
metapath_tmp,
File::O_CREATE | File::O_WRITE);
CSTableIndexBuildState metadata;
metadata.set_offset(snap->nrecs);
metadata.set_uuid(snap->uuid().data(), snap->uuid().size());
auto buf = msg::encode(metadata);
metafile.write(buf->data(), buf->size());
}
FileUtil::mv(filepath_tmp, filepath);
FileUtil::mv(metapath_tmp, metapath);
auto t1 = WallClock::unixMicros();
logDebug(
"tsdb",
"Commiting CSTable index for partition $0/$1/$2, building took $3s",
snap->state.tsdb_namespace(),
table->name(),
snap->key.toString(),
(double) (t1 - t0) / 1000000.0f);
}
void CSTableIndex::enqueuePartition(RefPtr<Partition> partition) {
std::unique_lock<std::mutex> lk(mutex_);
enqueuePartitionWithLock(partition);
}
void CSTableIndex::enqueuePartitionWithLock(RefPtr<Partition> partition) {
auto interval = partition->getTable()->cstableBuildInterval();
auto uuid = partition->uuid();
if (waitset_.count(uuid) > 0) {
return;
}
queue_.emplace(
WallClock::unixMicros() + interval.microseconds(),
partition);
waitset_.emplace(uuid);
cv_.notify_all();
}
void CSTableIndex::start() {
running_ = true;
for (int i = 0; i < nthreads_; ++i) {
threads_.emplace_back(std::bind(&CSTableIndex::work, this));
}
}
void CSTableIndex::stop() {
if (!running_) {
return;
}
running_ = false;
cv_.notify_all();
for (auto& t : threads_) {
t.join();
}
}
void CSTableIndex::work() {
std::unique_lock<std::mutex> lk(mutex_);
while (running_) {
if (queue_.size() == 0) {
cv_.wait(lk);
}
if (queue_.size() == 0) {
continue;
}
auto now = WallClock::unixMicros();
if (now < queue_.begin()->first) {
cv_.wait_for(
lk,
std::chrono::microseconds(queue_.begin()->first - now));
continue;
}
auto partition = queue_.begin()->second;
queue_.erase(queue_.begin());
bool success = true;
{
lk.unlock();
try {
buildCSTable(partition);
} catch (const StandardException& e) {
logError("tsdb", e, "CSTableIndex error");
success = false;
}
lk.lock();
}
if (success) {
waitset_.erase(partition->uuid());
if (needsUpdate(partition->getSnapshot())) {
enqueuePartitionWithLock(partition);
}
} else {
auto delay = 30 * kMicrosPerSecond; // FIXPAUL increasing delay..
queue_.emplace(now + delay, partition);
}
}
}
} // namespace zbase
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Copyright 2022 The StableHLO Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "stablehlo/dialect/Register.h"
#include "stablehlo/dialect/ChloOps.h"
#include "stablehlo/dialect/StablehloOps.h"
namespace mlir {
namespace stablehlo {
void registerAllDialects(mlir::DialectRegistry ®istry) {
// clang-format off
registry.insert<mlir::chlo::ChloDialect,
mlir::stablehlo::StablehloDialect>();
// clang-format on
}
} // namespace stablehlo
} // namespace mlir
<commit_msg>Add SparseTensorDialect to registration (#483)<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Copyright 2022 The StableHLO Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "stablehlo/dialect/Register.h"
#include "mlir/Dialect/SparseTensor/IR/SparseTensor.h"
#include "stablehlo/dialect/ChloOps.h"
#include "stablehlo/dialect/StablehloOps.h"
namespace mlir {
namespace stablehlo {
void registerAllDialects(mlir::DialectRegistry ®istry) {
// clang-format off
registry.insert<mlir::sparse_tensor::SparseTensorDialect>();
registry.insert<mlir::chlo::ChloDialect,
mlir::stablehlo::StablehloDialect>();
// clang-format on
}
} // namespace stablehlo
} // namespace mlir
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPTYPES_HEADER__
#define __PION_HTTPTYPES_HEADER__
#include <string>
#include <cctype>
#include <pion/PionConfig.hpp>
#include <pion/PionHashMap.hpp>
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// HTTPTypes: common data types used by HTTP
///
struct PION_NET_API HTTPTypes
{
/// virtual destructor
virtual ~HTTPTypes() {}
// generic strings used by HTTP
static const std::string STRING_EMPTY;
static const std::string STRING_CRLF;
static const std::string STRING_HTTP_VERSION;
static const std::string HEADER_NAME_VALUE_DELIMITER;
// common HTTP header names
static const std::string HEADER_HOST;
static const std::string HEADER_COOKIE;
static const std::string HEADER_SET_COOKIE;
static const std::string HEADER_CONNECTION;
static const std::string HEADER_CONTENT_TYPE;
static const std::string HEADER_CONTENT_LENGTH;
static const std::string HEADER_CONTENT_LOCATION;
static const std::string HEADER_LAST_MODIFIED;
static const std::string HEADER_IF_MODIFIED_SINCE;
static const std::string HEADER_TRANSFER_ENCODING;
static const std::string HEADER_LOCATION;
// common HTTP content types
static const std::string CONTENT_TYPE_HTML;
static const std::string CONTENT_TYPE_TEXT;
static const std::string CONTENT_TYPE_XML;
static const std::string CONTENT_TYPE_URLENCODED;
// common HTTP request methods
static const std::string REQUEST_METHOD_HEAD;
static const std::string REQUEST_METHOD_GET;
static const std::string REQUEST_METHOD_PUT;
static const std::string REQUEST_METHOD_POST;
static const std::string REQUEST_METHOD_DELETE;
// common HTTP response messages
static const std::string RESPONSE_MESSAGE_OK;
static const std::string RESPONSE_MESSAGE_CREATED;
static const std::string RESPONSE_MESSAGE_NO_CONTENT;
static const std::string RESPONSE_MESSAGE_FORBIDDEN;
static const std::string RESPONSE_MESSAGE_NOT_FOUND;
static const std::string RESPONSE_MESSAGE_METHOD_NOT_ALLOWED;
static const std::string RESPONSE_MESSAGE_NOT_MODIFIED;
static const std::string RESPONSE_MESSAGE_BAD_REQUEST;
static const std::string RESPONSE_MESSAGE_SERVER_ERROR;
static const std::string RESPONSE_MESSAGE_NOT_IMPLEMENTED;
// common HTTP response codes
static const unsigned int RESPONSE_CODE_OK;
static const unsigned int RESPONSE_CODE_CREATED;
static const unsigned int RESPONSE_CODE_NO_CONTENT;
static const unsigned int RESPONSE_CODE_FORBIDDEN;
static const unsigned int RESPONSE_CODE_NOT_FOUND;
static const unsigned int RESPONSE_CODE_METHOD_NOT_ALLOWED;
static const unsigned int RESPONSE_CODE_NOT_MODIFIED;
static const unsigned int RESPONSE_CODE_BAD_REQUEST;
static const unsigned int RESPONSE_CODE_SERVER_ERROR;
static const unsigned int RESPONSE_CODE_NOT_IMPLEMENTED;
/// returns true if two strings are equal (ignoring case)
struct CaseInsensitiveEqual {
inline bool operator()(const std::string& str1, const std::string& str2) const {
if (str1.size() != str2.size())
return false;
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1!=str1.end()) && (it2!=str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return false;
++it1;
++it2;
}
return true;
}
};
/// case insensitive hash function for std::string
struct CaseInsensitiveHash {
inline unsigned long operator()(const std::string& str) const {
unsigned long value = 0;
for (std::string::const_iterator i = str.begin(); i!= str.end(); ++i)
value = static_cast<unsigned char>(tolower(*i)) + (value << 6) + (value << 16) - value;
return value;
}
};
/// returns true if str1 < str2 (ignoring case)
struct CaseInsensitiveLess {
inline bool operator()(const std::string& str1, const std::string& str2) const {
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1 != str1.end()) && (it2 != str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return (tolower(*it1) < tolower(*it2));
++it1;
++it2;
}
return (str1.size() < str2.size());
}
};
/// case insensitive extension of stdext::hash_compare for std::string
struct CaseInsensitiveHashCompare : public stdext::hash_compare<std::string, CaseInsensitiveLess> {
// makes operator() with two arguments visible, otherwise it would be hidden by the operator() defined here
using stdext::hash_compare<std::string, CaseInsensitiveLess>::operator();
inline size_t operator()(const std::string& str) const {
return CaseInsensitiveHash()(str);
}
};
/// use case-insensitive comparisons for HTTP header names
#ifdef _MSC_VER
typedef PION_HASH_MULTIMAP<std::string, std::string, CaseInsensitiveHashCompare> Headers;
#else
typedef PION_HASH_MULTIMAP<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual > Headers;
#endif
/// data type for a dictionary of strings (used for HTTP headers)
typedef PION_HASH_MULTIMAP<std::string, std::string, PION_HASH_STRING > StringDictionary;
/// data type for HTTP query parameters
typedef StringDictionary QueryParams;
/// data type for HTTP cookie parameters
typedef StringDictionary CookieParams;
/// escapes URL-encoded strings (a%20value+with%20spaces)
static std::string url_decode(const std::string& str);
/// encodes strings so that they are safe for URLs (with%20spaces)
static std::string url_encode(const std::string& str);
/// converts time_t format into an HTTP-date string
static std::string get_date_string(const time_t t);
/// builds an HTTP query string from a collection of query parameters
static std::string make_query_string(const QueryParams& query_params);
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
static std::string make_set_cookie_header(const std::string& name,
const std::string& value,
const std::string& path,
const bool has_max_age = false,
const unsigned long max_age = 0);
};
} // end namespace net
} // end namespace pion
#endif
<commit_msg>Made some MSVC specific code conditionally compiled.<commit_after>// ------------------------------------------------------------------
// pion-net: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//
#ifndef __PION_HTTPTYPES_HEADER__
#define __PION_HTTPTYPES_HEADER__
#include <string>
#include <cctype>
#include <pion/PionConfig.hpp>
#include <pion/PionHashMap.hpp>
namespace pion { // begin namespace pion
namespace net { // begin namespace net (Pion Network Library)
///
/// HTTPTypes: common data types used by HTTP
///
struct PION_NET_API HTTPTypes
{
/// virtual destructor
virtual ~HTTPTypes() {}
// generic strings used by HTTP
static const std::string STRING_EMPTY;
static const std::string STRING_CRLF;
static const std::string STRING_HTTP_VERSION;
static const std::string HEADER_NAME_VALUE_DELIMITER;
// common HTTP header names
static const std::string HEADER_HOST;
static const std::string HEADER_COOKIE;
static const std::string HEADER_SET_COOKIE;
static const std::string HEADER_CONNECTION;
static const std::string HEADER_CONTENT_TYPE;
static const std::string HEADER_CONTENT_LENGTH;
static const std::string HEADER_CONTENT_LOCATION;
static const std::string HEADER_LAST_MODIFIED;
static const std::string HEADER_IF_MODIFIED_SINCE;
static const std::string HEADER_TRANSFER_ENCODING;
static const std::string HEADER_LOCATION;
// common HTTP content types
static const std::string CONTENT_TYPE_HTML;
static const std::string CONTENT_TYPE_TEXT;
static const std::string CONTENT_TYPE_XML;
static const std::string CONTENT_TYPE_URLENCODED;
// common HTTP request methods
static const std::string REQUEST_METHOD_HEAD;
static const std::string REQUEST_METHOD_GET;
static const std::string REQUEST_METHOD_PUT;
static const std::string REQUEST_METHOD_POST;
static const std::string REQUEST_METHOD_DELETE;
// common HTTP response messages
static const std::string RESPONSE_MESSAGE_OK;
static const std::string RESPONSE_MESSAGE_CREATED;
static const std::string RESPONSE_MESSAGE_NO_CONTENT;
static const std::string RESPONSE_MESSAGE_FORBIDDEN;
static const std::string RESPONSE_MESSAGE_NOT_FOUND;
static const std::string RESPONSE_MESSAGE_METHOD_NOT_ALLOWED;
static const std::string RESPONSE_MESSAGE_NOT_MODIFIED;
static const std::string RESPONSE_MESSAGE_BAD_REQUEST;
static const std::string RESPONSE_MESSAGE_SERVER_ERROR;
static const std::string RESPONSE_MESSAGE_NOT_IMPLEMENTED;
// common HTTP response codes
static const unsigned int RESPONSE_CODE_OK;
static const unsigned int RESPONSE_CODE_CREATED;
static const unsigned int RESPONSE_CODE_NO_CONTENT;
static const unsigned int RESPONSE_CODE_FORBIDDEN;
static const unsigned int RESPONSE_CODE_NOT_FOUND;
static const unsigned int RESPONSE_CODE_METHOD_NOT_ALLOWED;
static const unsigned int RESPONSE_CODE_NOT_MODIFIED;
static const unsigned int RESPONSE_CODE_BAD_REQUEST;
static const unsigned int RESPONSE_CODE_SERVER_ERROR;
static const unsigned int RESPONSE_CODE_NOT_IMPLEMENTED;
/// returns true if two strings are equal (ignoring case)
struct CaseInsensitiveEqual {
inline bool operator()(const std::string& str1, const std::string& str2) const {
if (str1.size() != str2.size())
return false;
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1!=str1.end()) && (it2!=str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return false;
++it1;
++it2;
}
return true;
}
};
/// case insensitive hash function for std::string
struct CaseInsensitiveHash {
inline unsigned long operator()(const std::string& str) const {
unsigned long value = 0;
for (std::string::const_iterator i = str.begin(); i!= str.end(); ++i)
value = static_cast<unsigned char>(tolower(*i)) + (value << 6) + (value << 16) - value;
return value;
}
};
/// returns true if str1 < str2 (ignoring case)
struct CaseInsensitiveLess {
inline bool operator()(const std::string& str1, const std::string& str2) const {
std::string::const_iterator it1 = str1.begin();
std::string::const_iterator it2 = str2.begin();
while ( (it1 != str1.end()) && (it2 != str2.end()) ) {
if (tolower(*it1) != tolower(*it2))
return (tolower(*it1) < tolower(*it2));
++it1;
++it2;
}
return (str1.size() < str2.size());
}
};
#ifdef _MSC_VER
/// case insensitive extension of stdext::hash_compare for std::string
struct CaseInsensitiveHashCompare : public stdext::hash_compare<std::string, CaseInsensitiveLess> {
// makes operator() with two arguments visible, otherwise it would be hidden by the operator() defined here
using stdext::hash_compare<std::string, CaseInsensitiveLess>::operator();
inline size_t operator()(const std::string& str) const {
return CaseInsensitiveHash()(str);
}
};
#endif
/// use case-insensitive comparisons for HTTP header names
#ifdef _MSC_VER
typedef PION_HASH_MULTIMAP<std::string, std::string, CaseInsensitiveHashCompare> Headers;
#else
typedef PION_HASH_MULTIMAP<std::string, std::string, CaseInsensitiveHash, CaseInsensitiveEqual > Headers;
#endif
/// data type for a dictionary of strings (used for HTTP headers)
typedef PION_HASH_MULTIMAP<std::string, std::string, PION_HASH_STRING > StringDictionary;
/// data type for HTTP query parameters
typedef StringDictionary QueryParams;
/// data type for HTTP cookie parameters
typedef StringDictionary CookieParams;
/// escapes URL-encoded strings (a%20value+with%20spaces)
static std::string url_decode(const std::string& str);
/// encodes strings so that they are safe for URLs (with%20spaces)
static std::string url_encode(const std::string& str);
/// converts time_t format into an HTTP-date string
static std::string get_date_string(const time_t t);
/// builds an HTTP query string from a collection of query parameters
static std::string make_query_string(const QueryParams& query_params);
/**
* creates a "Set-Cookie" header
*
* @param name the name of the cookie
* @param value the value of the cookie
* @param path the path of the cookie
* @param has_max_age true if the max_age value should be set
* @param max_age the life of the cookie, in seconds (0 = discard)
*
* @return the new "Set-Cookie" header
*/
static std::string make_set_cookie_header(const std::string& name,
const std::string& value,
const std::string& path,
const bool has_max_age = false,
const unsigned long max_age = 0);
};
} // end namespace net
} // end namespace pion
#endif
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "../OSSupport/BlockingTCPLink.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
#include "inifile/iniFile.h"
#include "json/json.h"
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
#include "polarssl/certs.h"
#include <sstream>
#include <iomanip>
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, cClientHandle::GenerateOfflineUUID(a_UserName));
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
cAuthenticator::cUser & User = m_Queue.front();
int ClientID = User.m_ClientID;
AString UserName = User.m_Name;
AString ServerID = User.m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID))
{
LOGINFO("User %s authenticated with UUID '%s'", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
LOGD("Trying to auth user %s", a_UserName.c_str());
int ret, server_fd = -1;
unsigned char buf[1024];
const char *pers = "cAuthenticator";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_crt cacert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
x509_crt_init(&cacert);
entropy_init(&entropy);
if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
{
LOGWARNING("cAuthenticator: ctr_drbg_init returned %d", ret);
return false;
}
/* Initialize certificates */
// TODO: Grab the sessionserver's root CA and any intermediates and hard-code them here, instead of test_ca_list
ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
if (ret < 0)
{
LOGWARNING("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
return false;
}
/* Connect */
if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
{
LOGWARNING("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGWARNING("cAuthenticator: ssl_init returned %d", ret);
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if ((ret != POLARSSL_ERR_NET_WANT_READ) && (ret != POLARSSL_ERR_NET_WANT_WRITE))
{
LOGWARNING("cAuthenticator: ssl_handshake returned -0x%x", -ret);
return false;
}
}
/* Write the GET request */
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
AString Request;
Request += "GET " + ActualAddress + " HTTP/1.1\r\n";
Request += "Host: " + m_Server + "\r\n";
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "\r\n";
ret = ssl_write(&ssl, (const unsigned char *)Request.c_str(), Request.size());
if (ret <= 0)
{
LOGWARNING("cAuthenticator: ssl_write returned %d", ret);
return false;
}
/* Read the HTTP response */
std::string Response;
for (;;)
{
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, sizeof(buf));
if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
{
continue;
}
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
{
break;
}
if (ret < 0)
{
LOGWARNING("cAuthenticator: ssl_read returned %d", ret);
break;
}
if (ret == 0)
{
LOGWARNING("cAuthenticator: EOF");
break;
}
Response.append((const char *)buf, ret);
}
ssl_close_notify(&ssl);
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
// Check the HTTP status line:
AString prefix("HTTP/1.1 200 OK");
AString HexDump;
if (Response.compare(0, prefix.size(), prefix))
{
LOGINFO("User \"%s\" failed to auth, bad http status line received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
// Erase the HTTP headers from the response:
size_t idxHeadersEnd = Response.find("\r\n\r\n");
if (idxHeadersEnd == AString::npos)
{
LOGINFO("User \"%s\" failed to authenticate, bad http response header received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
Response.erase(0, idxHeadersEnd + 4);
// Parse the Json response:
if (Response.empty())
{
return false;
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(Response, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse Received Data to json!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = root.get("id", "").asString();
// If the UUID doesn't contain the hashes, insert them at the proper places:
if (a_UUID.size() == 32)
{
a_UUID.insert(8, "-");
a_UUID.insert(13, "-");
a_UUID.insert(18, "-");
a_UUID.insert(23, "-");
}
return true;
}
<commit_msg>Fixes resource leaks in the yggdrasil authenticator. (CID 43617)<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "../OSSupport/BlockingTCPLink.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
#include "inifile/iniFile.h"
#include "json/json.h"
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
#include "polarssl/certs.h"
#include <sstream>
#include <iomanip>
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, cClientHandle::GenerateOfflineUUID(a_UserName));
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
cAuthenticator::cUser & User = m_Queue.front();
int ClientID = User.m_ClientID;
AString UserName = User.m_Name;
AString ServerID = User.m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID))
{
LOGINFO("User %s authenticated with UUID '%s'", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
LOGD("Trying to auth user %s", a_UserName.c_str());
int ret, server_fd = -1;
unsigned char buf[1024];
const char *pers = "cAuthenticator";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_crt cacert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
x509_crt_init(&cacert);
entropy_init(&entropy);
if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
{
LOGWARNING("cAuthenticator: ctr_drbg_init returned %d", ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
entropy_free(&entropy);
return false;
}
/* Initialize certificates */
// TODO: Grab the sessionserver's root CA and any intermediates and hard-code them here, instead of test_ca_list
ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
if (ret < 0)
{
LOGWARNING("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
entropy_free(&entropy);
return false;
}
/* Connect */
if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
{
LOGWARNING("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
entropy_free(&entropy);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGWARNING("cAuthenticator: ssl_init returned %d", ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if ((ret != POLARSSL_ERR_NET_WANT_READ) && (ret != POLARSSL_ERR_NET_WANT_WRITE))
{
LOGWARNING("cAuthenticator: ssl_handshake returned -0x%x", -ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
return false;
}
}
/* Write the GET request */
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
AString Request;
Request += "GET " + ActualAddress + " HTTP/1.1\r\n";
Request += "Host: " + m_Server + "\r\n";
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "\r\n";
ret = ssl_write(&ssl, (const unsigned char *)Request.c_str(), Request.size());
if (ret <= 0)
{
LOGWARNING("cAuthenticator: ssl_write returned %d", ret);
// Free all resources which have been initialized up to this line
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
return false;
}
/* Read the HTTP response */
std::string Response;
for (;;)
{
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, sizeof(buf));
if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
{
continue;
}
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
{
break;
}
if (ret < 0)
{
LOGWARNING("cAuthenticator: ssl_read returned %d", ret);
break;
}
if (ret == 0)
{
LOGWARNING("cAuthenticator: EOF");
break;
}
Response.append((const char *)buf, ret);
}
ssl_close_notify(&ssl);
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
// Check the HTTP status line:
AString prefix("HTTP/1.1 200 OK");
AString HexDump;
if (Response.compare(0, prefix.size(), prefix))
{
LOGINFO("User \"%s\" failed to auth, bad http status line received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
// Erase the HTTP headers from the response:
size_t idxHeadersEnd = Response.find("\r\n\r\n");
if (idxHeadersEnd == AString::npos)
{
LOGINFO("User \"%s\" failed to authenticate, bad http response header received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
Response.erase(0, idxHeadersEnd + 4);
// Parse the Json response:
if (Response.empty())
{
return false;
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(Response, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse Received Data to json!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = root.get("id", "").asString();
// If the UUID doesn't contain the hashes, insert them at the proper places:
if (a_UUID.size() == 32)
{
a_UUID.insert(8, "-");
a_UUID.insert(13, "-");
a_UUID.insert(18, "-");
a_UUID.insert(23, "-");
}
return true;
}
<|endoftext|> |
<commit_before>#include "fdsb/test.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"
#include "fdsb/fabric.hpp"
using namespace fdsb;
void test_fabric_addget()
{
Harc h1(1_n,2_n);
add(h1);
get(1_n,2_n) = 47_n;
add(3_n,4_n);
get(3_n,4_n) = 56_n;
CHECK(get(1_n,2_n) == 47_n);
CHECK(get(3_n,4_n) == 56_n);
DONE;
}
void test_fabric_symetric()
{
add(10_n,11_n);
get(10_n,11_n) = 55_n;
CHECK(get(10_n,11_n) == 55_n);
CHECK(get(11_n,10_n) == 55_n);
get(11_n,10_n) = 66_n;
CHECK(get(10_n,11_n) == 66_n);
CHECK(get(11_n,10_n) == 66_n);
DONE;
}
void test_fabric_autocreate()
{
get(15_n,16_n) = 67_n;
CHECK(get(15_n,16_n) == 67_n);
DONE;
}
void test_fabric_subscript()
{
19_n[20_n] = 21_n;
CHECK(19_n[20_n] == 21_n);
CHECK(20_n[19_nid] == 21_n);
DONE;
}
int main(int argc, char *argv[])
{
test(test_fabric_addget);
test(test_fabric_symetric);
test(test_fabric_autocreate);
test(test_fabric_subscript);
return 0;
}
<commit_msg>Missing _nid changes<commit_after>#include "fdsb/test.hpp"
#include "fdsb/nid.hpp"
#include "fdsb/harc.hpp"
#include "fdsb/fabric.hpp"
using namespace fdsb;
void test_fabric_addget()
{
Harc h1(1_n,2_n);
add(h1);
get(1_n,2_n) = 47_n;
add(3_n,4_n);
get(3_n,4_n) = 56_n;
CHECK(get(1_n,2_n) == 47_n);
CHECK(get(3_n,4_n) == 56_n);
DONE;
}
void test_fabric_symetric()
{
add(10_n,11_n);
get(10_n,11_n) = 55_n;
CHECK(get(10_n,11_n) == 55_n);
CHECK(get(11_n,10_n) == 55_n);
get(11_n,10_n) = 66_n;
CHECK(get(10_n,11_n) == 66_n);
CHECK(get(11_n,10_n) == 66_n);
DONE;
}
void test_fabric_autocreate()
{
get(15_n,16_n) = 67_n;
CHECK(get(15_n,16_n) == 67_n);
DONE;
}
void test_fabric_subscript()
{
19_n[20_n] = 21_n;
CHECK(19_n[20_n] == 21_n);
CHECK(20_n[19_n] == 21_n);
DONE;
}
int main(int argc, char *argv[])
{
test(test_fabric_addget);
test(test_fabric_symetric);
test(test_fabric_autocreate);
test(test_fabric_subscript);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Ensures that writes are at least one byte, matching the libevent version. As discussed in http://codereview.chromium.org/55014 .<commit_after><|endoftext|> |
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Bioturbation via diffusion
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "Epetra_SerialDenseVector.h"
#include "bioturbation_evaluator.hh"
namespace Amanzi {
namespace BGC {
namespace BGCRelations {
BioturbationEvaluator::BioturbationEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
carbon_key_ = plist_.get<std::string>("SOM key", "soil_organic_matter");
dependencies_.insert(carbon_key_);
diffusivity_key_ = plist_.get<std::string>("cryoturbation diffusivity key", "cryoturbation_diffusivity");
dependencies_.insert(diffusivity_key_);
if (my_key_ == std::string("")) {
my_key_ = plist_.get<std::string>("divergence of bioturbation fluxes",
"div_bioturbation");
}
}
BioturbationEvaluator::BioturbationEvaluator(const BioturbationEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
carbon_key_(other.carbon_key_),
diffusivity_key_(other.diffusivity_key_) {}
Teuchos::RCP<FieldEvaluator>
BioturbationEvaluator::Clone() const {
return Teuchos::rcp(new BioturbationEvaluator(*this));
}
// Required methods from SecondaryVariableFieldEvaluator
void BioturbationEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> carbon_cv = S->GetFieldData(carbon_key_);
const AmanziMesh::Mesh& mesh = *carbon_cv->Mesh();
const Epetra_MultiVector& carbon = *carbon_cv->ViewComponent("cell",false);
const Epetra_MultiVector& diff = *S->GetFieldData(diffusivity_key_)
->ViewComponent("cell",false);
Epetra_MultiVector& res_c = *result->ViewComponent("cell",false);
// iterate over columns of the mesh
const AmanziMesh::Entity_ID_List& columns = mesh.cell_column_indices();
for (AmanziMesh::Entity_ID_List::const_iterator i=columns.begin(); i!=columns.end(); ++i) {
// grab the column
const AmanziMesh::Entity_ID_List& col = mesh.cell_column(*i);
Epetra_SerialDenseVector dC_up(carbon.NumVectors());
Epetra_SerialDenseVector dC_dn(carbon.NumVectors());
// loop over column, getting cell index ci and cell c
int ci=0;
for (AmanziMesh::Entity_ID_List::const_iterator c=col.begin(); c!=col.end(); ++c, ++ci) {
double my_z = mesh.cell_centroid(*c)[2];
double dz_up = 0.;
double dz_dn = 0.;
if (ci != 0) {
double my_z = mesh.cell_centroid(*c)[2];
int c_up = col[ci-1];
dz_up = mesh.cell_centroid(c_up)[2] - my_z;
for (int p=0; p!=carbon.NumVectors(); ++p) {
dC_up[p] = (diff[p][*c]+diff[p][c_up]) / 2. * (carbon[p][*c] - carbon[p][c_up]) / dz_up;
}
}
if (ci != col.size()-1) {
int c_dn = col[ci+1];
dz_dn = mesh.cell_centroid(c_dn)[2] - my_z;
for (int p=0; p!=carbon.NumVectors(); ++p) {
dC_dn[p] = (diff[p][*c]+diff[p][c_dn]) / 2. * (carbon[p][c_dn] - carbon[p][*c]) / dz_up;
}
}
double dz = dz_dn == 0. ? dz_up :
dz_up == 0. ? dz_dn : (dz_up + dz_dn) / 2.;
for (int p=0; p!=carbon.NumVectors(); ++p) {
res_c[p][*c] = (dC_dn[p] - dC_up[p]) / dz;
}
}
}
}
void BioturbationEvaluator::EvaluateFieldPartialDerivative_(
const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
ASSERT(0);
}
} //namespace
} //namespace
} //namespace
<commit_msg>changed calls to get column info in accordance with changes in Amanzi<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Bioturbation via diffusion
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "Epetra_SerialDenseVector.h"
#include "bioturbation_evaluator.hh"
namespace Amanzi {
namespace BGC {
namespace BGCRelations {
BioturbationEvaluator::BioturbationEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
carbon_key_ = plist_.get<std::string>("SOM key", "soil_organic_matter");
dependencies_.insert(carbon_key_);
diffusivity_key_ = plist_.get<std::string>("cryoturbation diffusivity key", "cryoturbation_diffusivity");
dependencies_.insert(diffusivity_key_);
if (my_key_ == std::string("")) {
my_key_ = plist_.get<std::string>("divergence of bioturbation fluxes",
"div_bioturbation");
}
}
BioturbationEvaluator::BioturbationEvaluator(const BioturbationEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
carbon_key_(other.carbon_key_),
diffusivity_key_(other.diffusivity_key_) {}
Teuchos::RCP<FieldEvaluator>
BioturbationEvaluator::Clone() const {
return Teuchos::rcp(new BioturbationEvaluator(*this));
}
// Required methods from SecondaryVariableFieldEvaluator
void BioturbationEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> carbon_cv = S->GetFieldData(carbon_key_);
const AmanziMesh::Mesh& mesh = *carbon_cv->Mesh();
const Epetra_MultiVector& carbon = *carbon_cv->ViewComponent("cell",false);
const Epetra_MultiVector& diff = *S->GetFieldData(diffusivity_key_)
->ViewComponent("cell",false);
Epetra_MultiVector& res_c = *result->ViewComponent("cell",false);
// iterate over columns of the mesh
int ncolumns = mesh.num_columns();
for (int i=0; i<ncolumns; ++i) {
// grab the column
const AmanziMesh::Entity_ID_List& col = mesh.cells_of_column(i);
Epetra_SerialDenseVector dC_up(carbon.NumVectors());
Epetra_SerialDenseVector dC_dn(carbon.NumVectors());
// loop over column, getting cell index ci and cell c
int ci=0;
for (AmanziMesh::Entity_ID_List::const_iterator c=col.begin(); c!=col.end(); ++c, ++ci) {
double my_z = mesh.cell_centroid(*c)[2];
double dz_up = 0.;
double dz_dn = 0.;
if (ci != 0) {
double my_z = mesh.cell_centroid(*c)[2];
int c_up = col[ci-1];
dz_up = mesh.cell_centroid(c_up)[2] - my_z;
for (int p=0; p!=carbon.NumVectors(); ++p) {
dC_up[p] = (diff[p][*c]+diff[p][c_up]) / 2. * (carbon[p][*c] - carbon[p][c_up]) / dz_up;
}
}
if (ci != col.size()-1) {
int c_dn = col[ci+1];
dz_dn = mesh.cell_centroid(c_dn)[2] - my_z;
for (int p=0; p!=carbon.NumVectors(); ++p) {
dC_dn[p] = (diff[p][*c]+diff[p][c_dn]) / 2. * (carbon[p][c_dn] - carbon[p][*c]) / dz_up;
}
}
double dz = dz_dn == 0. ? dz_up :
dz_up == 0. ? dz_dn : (dz_up + dz_dn) / 2.;
for (int p=0; p!=carbon.NumVectors(); ++p) {
res_c[p][*c] = (dC_dn[p] - dC_up[p]) / dz;
}
}
}
}
void BioturbationEvaluator::EvaluateFieldPartialDerivative_(
const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
ASSERT(0);
}
} //namespace
} //namespace
} //namespace
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <tracker-sparql.h>
#include "qsparql_tracker_direct_update_result_p.h"
#include "qsparql_tracker_direct_driver_p.h"
#include "qsparql_tracker_direct_result_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qdebug.h>
QT_BEGIN_NAMESPACE
////////////////////////////////////////////////////////////////////////////
class QTrackerDirectUpdateResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerDirectUpdateResultPrivate(QTrackerDirectUpdateResult* result, QTrackerDirectDriverPrivate *dpp);
~QTrackerDirectUpdateResultPrivate();
void terminate();
void setLastError(const QSparqlError& e);
QAtomicInt isFinished;
bool resultAlive; // whether the corresponding Result object is still alive
QEventLoop *loop;
QTrackerDirectUpdateResult* q;
QTrackerDirectDriverPrivate *driverPrivate;
};
static void
async_update_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectUpdateResultPrivate *data = static_cast<QTrackerDirectUpdateResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);
if (error) {
QSparqlError e(QString::fromUtf8(error->message));
e.setType(errorCodeToType(error->code));
e.setNumber(error->code);
data->setLastError(e);
g_error_free(error);
}
// A workaround for http://bugreports.qt.nokia.com/browse/QTBUG-18434
// We cannot emit the QSparqlResult::finished() signal directly here; so
// delay it and emit it the next time the main loop spins.
QMetaObject::invokeMethod(data->q, "terminate", Qt::QueuedConnection);
}
QTrackerDirectUpdateResultPrivate::QTrackerDirectUpdateResultPrivate(QTrackerDirectUpdateResult* result,
QTrackerDirectDriverPrivate *dpp)
: resultAlive(true), loop(0),
q(result), driverPrivate(dpp)
{
}
QTrackerDirectUpdateResultPrivate::~QTrackerDirectUpdateResultPrivate()
{
}
void QTrackerDirectUpdateResultPrivate::terminate()
{
isFinished = 1;
q->Q_EMIT finished();
if (loop)
loop->exit();
}
void QTrackerDirectUpdateResultPrivate::setLastError(const QSparqlError& e)
{
q->setLastError(e);
}
////////////////////////////////////////////////////////////////////////////
QTrackerDirectUpdateResult::QTrackerDirectUpdateResult(QTrackerDirectDriverPrivate* p,
const QString& query,
QSparqlQuery::StatementType type)
{
setQuery(query);
setStatementType(type);
d = new QTrackerDirectUpdateResultPrivate(this, p);
}
QTrackerDirectUpdateResult::~QTrackerDirectUpdateResult()
{
if (d->isFinished == 0) {
// We're deleting the Result before the async update has
// finished. There is a pending async callback that will be called at
// some point, and that will have our ResultPrivate as user_data. Don't
// delete the ResultPrivate here, but just mark that we're no longer
// alive. The callback will then delete the ResultPrivate.
d->resultAlive = false;
return;
}
delete d;
}
void QTrackerDirectUpdateResult::exec()
{
if (!d->driverPrivate->driver->isOpen()) {
setLastError(QSparqlError(d->driverPrivate->error,
QSparqlError::ConnectionError));
d->terminate();
return;
}
tracker_sparql_connection_update_async( d->driverPrivate->connection,
query().toUtf8().constData(),
0,
0,
async_update_callback,
d);
}
QSparqlBinding QTrackerDirectUpdateResult::binding(int /*field*/) const
{
return QSparqlBinding();
}
QVariant QTrackerDirectUpdateResult::value(int /*field*/) const
{
return QVariant();
}
void QTrackerDirectUpdateResult::waitForFinished()
{
if (d->isFinished == 1)
return;
// We first need the connection to be ready before doing anything
if (!d->driverPrivate->asyncOpenCalled) {
QEventLoop loop;
connect(d->driverPrivate->driver, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
if (!d->driverPrivate->driver->isOpen()) {
setLastError(QSparqlError(d->driverPrivate->error,
QSparqlError::ConnectionError));
d->terminate();
return;
}
QEventLoop loop;
d->loop = &loop;
loop.exec();
d->loop = 0;
}
bool QTrackerDirectUpdateResult::isFinished() const
{
return d->isFinished == 1;
}
void QTrackerDirectUpdateResult::terminate()
{
d->terminate();
}
int QTrackerDirectUpdateResult::size() const
{
return 0;
}
QSparqlResultRow QTrackerDirectUpdateResult::current() const
{
return QSparqlResultRow();
}
QT_END_NAMESPACE
#include "qsparql_tracker_direct_update_result_p.moc"
<commit_msg>Remove redundant resultAlive member of QTrackerDirectUpdateResultPrivate<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <tracker-sparql.h>
#include "qsparql_tracker_direct_update_result_p.h"
#include "qsparql_tracker_direct_driver_p.h"
#include "qsparql_tracker_direct_result_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qeventloop.h>
#include <QtCore/qdebug.h>
QT_BEGIN_NAMESPACE
////////////////////////////////////////////////////////////////////////////
class QTrackerDirectUpdateResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerDirectUpdateResultPrivate(QTrackerDirectUpdateResult* result, QTrackerDirectDriverPrivate *dpp);
~QTrackerDirectUpdateResultPrivate();
void terminate();
void setLastError(const QSparqlError& e);
QAtomicInt isFinished;
QEventLoop *loop;
QTrackerDirectUpdateResult* q;
QTrackerDirectDriverPrivate *driverPrivate;
};
static void
async_update_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectUpdateResultPrivate *data = static_cast<QTrackerDirectUpdateResultPrivate*>(user_data);
if (!data->q) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);
if (error) {
QSparqlError e(QString::fromUtf8(error->message));
e.setType(errorCodeToType(error->code));
e.setNumber(error->code);
data->setLastError(e);
g_error_free(error);
}
// A workaround for http://bugreports.qt.nokia.com/browse/QTBUG-18434
// We cannot emit the QSparqlResult::finished() signal directly here; so
// delay it and emit it the next time the main loop spins.
QMetaObject::invokeMethod(data->q, "terminate", Qt::QueuedConnection);
}
QTrackerDirectUpdateResultPrivate::QTrackerDirectUpdateResultPrivate(QTrackerDirectUpdateResult* result,
QTrackerDirectDriverPrivate *dpp)
: loop(0),
q(result), driverPrivate(dpp)
{
}
QTrackerDirectUpdateResultPrivate::~QTrackerDirectUpdateResultPrivate()
{
}
void QTrackerDirectUpdateResultPrivate::terminate()
{
isFinished = 1;
q->Q_EMIT finished();
if (loop)
loop->exit();
}
void QTrackerDirectUpdateResultPrivate::setLastError(const QSparqlError& e)
{
q->setLastError(e);
}
////////////////////////////////////////////////////////////////////////////
QTrackerDirectUpdateResult::QTrackerDirectUpdateResult(QTrackerDirectDriverPrivate* p,
const QString& query,
QSparqlQuery::StatementType type)
{
setQuery(query);
setStatementType(type);
d = new QTrackerDirectUpdateResultPrivate(this, p);
}
QTrackerDirectUpdateResult::~QTrackerDirectUpdateResult()
{
if (d->isFinished == 0) {
// We're deleting the Result before the async update has
// finished. There is a pending async callback that will be called at
// some point, and that will have our ResultPrivate as user_data. Don't
// delete the ResultPrivate here, but just mark that we're no longer
// alive. The callback will then delete the ResultPrivate.
d->q = 0;
return;
}
delete d;
}
void QTrackerDirectUpdateResult::exec()
{
if (!d->driverPrivate->driver->isOpen()) {
setLastError(QSparqlError(d->driverPrivate->error,
QSparqlError::ConnectionError));
d->terminate();
return;
}
tracker_sparql_connection_update_async( d->driverPrivate->connection,
query().toUtf8().constData(),
0,
0,
async_update_callback,
d);
}
QSparqlBinding QTrackerDirectUpdateResult::binding(int /*field*/) const
{
return QSparqlBinding();
}
QVariant QTrackerDirectUpdateResult::value(int /*field*/) const
{
return QVariant();
}
void QTrackerDirectUpdateResult::waitForFinished()
{
if (d->isFinished == 1)
return;
// We first need the connection to be ready before doing anything
if (!d->driverPrivate->asyncOpenCalled) {
QEventLoop loop;
connect(d->driverPrivate->driver, SIGNAL(opened()), &loop, SLOT(quit()));
loop.exec();
}
if (!d->driverPrivate->driver->isOpen()) {
setLastError(QSparqlError(d->driverPrivate->error,
QSparqlError::ConnectionError));
d->terminate();
return;
}
QEventLoop loop;
d->loop = &loop;
loop.exec();
d->loop = 0;
}
bool QTrackerDirectUpdateResult::isFinished() const
{
return d->isFinished == 1;
}
void QTrackerDirectUpdateResult::terminate()
{
d->terminate();
}
int QTrackerDirectUpdateResult::size() const
{
return 0;
}
QSparqlResultRow QTrackerDirectUpdateResult::current() const
{
return QSparqlResultRow();
}
QT_END_NAMESPACE
#include "qsparql_tracker_direct_update_result_p.moc"
<|endoftext|> |
<commit_before>// =============================================================================
//
// Copyright (c) 2013 Christopher Baker <http://christopherbaker.net>
// 2014 Brannon Dorsey <http://brannondorsey.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 "ProjectManager.h"
using namespace ofx;
namespace of {
namespace Sketch {
ProjectManager::ProjectManager(const std::string& path):
_path(path),
_templateProject(ofToDataPath("Resources/Templates/NewProject", true))
{
_projectWatcher.addPath(_path);
std::vector<std::string> files;
ofx::IO::DirectoryFilter filter;
ofx::IO::DirectoryUtils::list(ofToDataPath(_path, true),
files,
true,
&filter);
std::vector<std::string>::iterator iter = files.begin();
while(iter != files.end())
{
ofLogVerbose("ProjectManager::ProjectManager") << *iter;
_projects.push_back(Project(*iter));
++iter;
}
}
ProjectManager::~ProjectManager()
{
}
// can this function be: return getProjectRef(projectName); only?
const Project& ProjectManager::getProject(const std::string& projectName) const
{
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
return _projects[i];
}
}
return _projects[0]; //fallback
}
Project& ProjectManager::getProjectRef(const std::string& projectName)
{
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
return _projects[i];
}
}
return _projects[0]; //fallback
}
const std::vector<Project>& ProjectManager::getProjects() const
{
return _projects;
}
// std::string sketchPath = ofToDataPath("HelloWorldSketch/src/main.cpp",true);
//
// ofBuffer buffer = ofBufferFromFile(sketchPath);
//
// Json::Value setEditorSource;
// setEditorSource["method"] = "setEditorSource";
// Json::Value editorSource;
// editorSource["source"] = buffer.getText();
// setEditorSource["data"] = editorSource;
//
// cout << setEditorSource.toStyledString() << endl;
//
// evt.getConnectionRef().sendFrame(WebSocketFrame(setEditorSource.toStyledString()));
//
// cout << "Connection opened from: " << evt.getConnectionRef().getClientAddress().toString() << endl;
void ProjectManager::getProjectList(const void* pSender, JSONRPC::MethodArgs& args)
{
Json::Value projectList;
for (int i = 0; i < _projects.size(); i++) {
projectList[i]["projectName"] = _projects[i].getName();
}
args.result = projectList;
}
void ProjectManager::loadProject(const void* pSender, JSONRPC::MethodArgs& args)
{
if (args.params.isMember("projectName")){
std::string projectName = args.params["projectName"].asString();
if (projectExists(projectName)) {
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
Project& project = _projects[i];
if (!project.isLoaded()) {
project.load(project.getPath(), projectName);
}
args.result = project.getData();
return;
}
}
ofLogError("Project::loadProject") << "Project: "<< projectName << " was not found.";
}
else
{
ofLogError("Project::loadProject") << "Error loading project";
}
}
else
{
ofLogError("Project::loadProject") << "ProjectName is not a member.";
}
}
void ProjectManager::loadTemplateProject(const void *pSender, JSONRPC::MethodArgs &args)
{
if (!_templateProject.isLoaded()) {
_templateProject.load(_templateProject.getPath(), _templateProject.getName());
}
args.result = _templateProject.getData();
}
void ProjectManager::saveProject(const void* pSender, ofx::JSONRPC::MethodArgs& args)
{
if (args.params.isMember("projectData")) {
ofLogNotice("ProjectManager::saveProject") << "Saving project...";
Json::Value projectData = args.params["projectData"];
std::string projectName = projectData["projectFile"]["name"].asString();
if (projectExists(projectName)) {
Project& project = getProjectRef(projectName);
project.save(projectData);
}
} else args.error = "A projectData object was not sent.";
}
void ProjectManager::createProject(const void* pSender, ofx::JSONRPC::MethodArgs& args)
{
Json::Value projectData = args.params["projectData"];
std::string projectName = args.params["projectData"]["projectFile"]["name"].asString();
ofDirectory projectDir(_templateProject.getPath());
projectDir.copyTo(ofToDataPath("Projects/" + projectName));
ofFile templateProjectFile(ofToDataPath("Projects/" + projectName) + "/sketch/NewProject.sketch");
templateProjectFile.remove();
Project project(ofToDataPath("Projects/" + projectName));
project.save(projectData);
_projects.push_back(project);
args.result = project.getData();
}
void ProjectManager::deleteProject(const void *pSender, ofx::JSONRPC::MethodArgs &args)
{
std::string projectName = args.params["projectName"].asString();
Project& project = getProjectRef(projectName);
project.remove();
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
_projects.erase(_projects.begin() + i);
args.result["message"] = "Deleted " + projectName + " project.";
return;
}
}
args.error["message"] = "Error deleting " + projectName + " project.";
}
void ProjectManager::renameProject(const void *pSender, ofx::JSONRPC::MethodArgs &args)
{
std::string projectName = args.params["projectName"].asString();
std::string newProjectName = args.params["newProjectName"].asString();
Project& project = getProjectRef(projectName);
if (project.rename(newProjectName)) {
args.result["message"] = "Renamed " + projectName + " project to " + newProjectName + ".";
} else {
args.error["message"] = "Error renaming " + projectName + " project.";
}
}
bool ProjectManager::projectExists(const std::string& projectName) const
{
for (int i = 0; i < _projects.size(); i++) {
if (projectName == _projects[i].getName())
return true;
}
return false;
}
void ProjectManager::reloadProjects()
{
}
void ProjectManager::updateProject(const std::string& projectName)
{
}
void ProjectManager::onDirectoryWatcherItemAdded(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Added: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemRemoved(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Removed: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemModified(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Modified: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemMovedFrom(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofLogNotice("ofApp::onDirectoryWatcherItemMovedFrom") << "Moved From: " << evt.item.path();
}
void ProjectManager::onDirectoryWatcherItemMovedTo(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofLogNotice("ofApp::onDirectoryWatcherItemMovedTo") << "Moved To: " << evt.item.path();
}
void ProjectManager::onDirectoryWatcherError(const Poco::Exception& exc)
{
ofLogError("ofApp::onDirectoryWatcherError") << "Error: " << exc.displayText();
}
} } // namespace of::Sketch
<commit_msg>ProjectManager now reuses _path variable.<commit_after>// =============================================================================
//
// Copyright (c) 2013 Christopher Baker <http://christopherbaker.net>
// 2014 Brannon Dorsey <http://brannondorsey.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 "ProjectManager.h"
using namespace ofx;
namespace of {
namespace Sketch {
ProjectManager::ProjectManager(const std::string& path):
_path(path),
_templateProject(ofToDataPath("Resources/Templates/NewProject", true))
{
_projectWatcher.addPath(_path);
ofLogNotice("ProjectManager::ProjectManager") << _path;
std::vector<std::string> files;
ofx::IO::DirectoryFilter filter;
ofx::IO::DirectoryUtils::list(ofToDataPath(_path, true),
files,
true,
&filter);
std::vector<std::string>::iterator iter = files.begin();
while(iter != files.end())
{
ofLogVerbose("ProjectManager::ProjectManager") << *iter;
_projects.push_back(Project(*iter));
++iter;
}
}
ProjectManager::~ProjectManager()
{
}
// can this function be: return getProjectRef(projectName); only?
const Project& ProjectManager::getProject(const std::string& projectName) const
{
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
return _projects[i];
}
}
return _projects[0]; //fallback
}
Project& ProjectManager::getProjectRef(const std::string& projectName)
{
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
return _projects[i];
}
}
return _projects[0]; //fallback
}
const std::vector<Project>& ProjectManager::getProjects() const
{
return _projects;
}
// std::string sketchPath = ofToDataPath("HelloWorldSketch/src/main.cpp",true);
//
// ofBuffer buffer = ofBufferFromFile(sketchPath);
//
// Json::Value setEditorSource;
// setEditorSource["method"] = "setEditorSource";
// Json::Value editorSource;
// editorSource["source"] = buffer.getText();
// setEditorSource["data"] = editorSource;
//
// cout << setEditorSource.toStyledString() << endl;
//
// evt.getConnectionRef().sendFrame(WebSocketFrame(setEditorSource.toStyledString()));
//
// cout << "Connection opened from: " << evt.getConnectionRef().getClientAddress().toString() << endl;
void ProjectManager::getProjectList(const void* pSender, JSONRPC::MethodArgs& args)
{
Json::Value projectList;
for (int i = 0; i < _projects.size(); i++) {
projectList[i]["projectName"] = _projects[i].getName();
}
args.result = projectList;
}
void ProjectManager::loadProject(const void* pSender, JSONRPC::MethodArgs& args)
{
if (args.params.isMember("projectName")){
std::string projectName = args.params["projectName"].asString();
if (projectExists(projectName)) {
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
Project& project = _projects[i];
if (!project.isLoaded()) {
project.load(project.getPath(), projectName);
}
args.result = project.getData();
return;
}
}
ofLogError("Project::loadProject") << "Project: "<< projectName << " was not found.";
}
else
{
ofLogError("Project::loadProject") << "Error loading project";
}
}
else
{
ofLogError("Project::loadProject") << "ProjectName is not a member.";
}
}
void ProjectManager::loadTemplateProject(const void *pSender, JSONRPC::MethodArgs &args)
{
if (!_templateProject.isLoaded()) {
_templateProject.load(_templateProject.getPath(), _templateProject.getName());
}
args.result = _templateProject.getData();
}
void ProjectManager::saveProject(const void* pSender, ofx::JSONRPC::MethodArgs& args)
{
if (args.params.isMember("projectData")) {
ofLogNotice("ProjectManager::saveProject") << "Saving project...";
Json::Value projectData = args.params["projectData"];
std::string projectName = projectData["projectFile"]["name"].asString();
if (projectExists(projectName)) {
Project& project = getProjectRef(projectName);
project.save(projectData);
}
} else args.error = "A projectData object was not sent.";
}
void ProjectManager::createProject(const void* pSender, ofx::JSONRPC::MethodArgs& args)
{
Json::Value projectData = args.params["projectData"];
std::string projectName = args.params["projectData"]["projectFile"]["name"].asString();
ofDirectory projectDir(_templateProject.getPath());
projectDir.copyTo(_path + "/" + projectName);
ofFile templateProjectFile(_path + "/" + projectName + "/sketch/NewProject.sketch");
templateProjectFile.remove();
Project project(_path + "/" + projectName);
project.save(projectData);
_projects.push_back(project);
args.result = project.getData();
}
void ProjectManager::deleteProject(const void *pSender, ofx::JSONRPC::MethodArgs &args)
{
std::string projectName = args.params["projectName"].asString();
Project& project = getProjectRef(projectName);
project.remove();
for (int i = 0; i < _projects.size(); i++) {
if (_projects[i].getName() == projectName) {
_projects.erase(_projects.begin() + i);
args.result["message"] = "Deleted " + projectName + " project.";
return;
}
}
args.error["message"] = "Error deleting " + projectName + " project.";
}
void ProjectManager::renameProject(const void *pSender, ofx::JSONRPC::MethodArgs &args)
{
std::string projectName = args.params["projectName"].asString();
std::string newProjectName = args.params["newProjectName"].asString();
Project& project = getProjectRef(projectName);
if (project.rename(newProjectName)) {
args.result["message"] = "Renamed " + projectName + " project to " + newProjectName + ".";
} else {
args.error["message"] = "Error renaming " + projectName + " project.";
}
}
bool ProjectManager::projectExists(const std::string& projectName) const
{
for (int i = 0; i < _projects.size(); i++) {
if (projectName == _projects[i].getName())
return true;
}
return false;
}
void ProjectManager::reloadProjects()
{
}
void ProjectManager::updateProject(const std::string& projectName)
{
}
void ProjectManager::onDirectoryWatcherItemAdded(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Added: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemRemoved(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Removed: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemModified(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofSendMessage("Modified: " + evt.item.path());
}
void ProjectManager::onDirectoryWatcherItemMovedFrom(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofLogNotice("ofApp::onDirectoryWatcherItemMovedFrom") << "Moved From: " << evt.item.path();
}
void ProjectManager::onDirectoryWatcherItemMovedTo(const Poco::DirectoryWatcher::DirectoryEvent& evt)
{
ofLogNotice("ofApp::onDirectoryWatcherItemMovedTo") << "Moved To: " << evt.item.path();
}
void ProjectManager::onDirectoryWatcherError(const Poco::Exception& exc)
{
ofLogError("ofApp::onDirectoryWatcherError") << "Error: " << exc.displayText();
}
} } // namespace of::Sketch
<|endoftext|> |
<commit_before>/*
* VariableList.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/TypeNode.h>
#include "VariableList.h"
using namespace opencog;
void VariableList::validate_vardecl(const HandleSeq& oset)
{
for (const Handle& h: oset)
{
Type t = h->getType();
if (VARIABLE_NODE == t or GLOB_NODE == t)
{
_varlist.varset.insert(h); // tree (unordered)
_varlist.varseq.emplace_back(h); // vector (ordered)
}
else if (TYPED_VARIABLE_LINK == t)
{
get_vartype(h);
}
else
throw InvalidParamException(TRACE_INFO,
"Expected a VariableNode or a TypedVariableLink, got: %s",
classserver().getTypeName(t).c_str());
}
build_index();
}
VariableList::VariableList(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(VARIABLE_LIST, oset, tv, av)
{
validate_vardecl(oset);
}
VariableList::VariableList(Type t, const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, oset, tv, av)
{
// derived classes have a different initialization order
if (VARIABLE_LIST != t) return;
validate_vardecl(oset);
}
VariableList::VariableList(Link &l)
: Link(l)
{
// Type must be as expected
Type tscope = l.getType();
if (not classserver().isA(tscope, VARIABLE_LIST))
{
const std::string& tname = classserver().getTypeName(tscope);
throw InvalidParamException(TRACE_INFO,
"Expecting a VariableList, got %s", tname.c_str());
}
// Dervided types have a different initialization sequence
if (VARIABLE_LIST != tscope) return;
validate_vardecl(_outgoing);
}
/* ================================================================= */
/**
* Extract the variable type(s) from a TypedVariableLink
*
* The call is expecting htypelink to point to one of the two
* following structures:
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeNode "ConceptNode"
*
* or
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeChoice
* TypeNode "ConceptNode"
* TypeNode "NumberNode"
* TypeNode "WordNode"
*
* or possibly types that are SignatureLink's or FuyzzyLink's or
* polymorphic combinations thereof: e.g. the following is valid:
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeChoice
* TypeNode "ConceptNode"
* SignatureLink
* InheritanceLink
* PredicateNode "foobar"
* TypeNode "ListLink"
* FuzzyLink
* InheritanceLink
* ConceptNode "animal"
* ConceptNode "tiger"
*
* In either case, the variable itself is appended to "vset",
* and the list of allowed types are associated with the variable
* via the map "typemap".
*/
void VariableList::get_vartype(const Handle& htypelink)
{
const std::vector<Handle>& oset = LinkCast(htypelink)->getOutgoingSet();
if (2 != oset.size())
{
throw InvalidParamException(TRACE_INFO,
"TypedVariableLink has wrong size, got %lu", oset.size());
}
Handle varname = oset[0];
Handle vartype = oset[1];
// The vartype is either a single type name, or a list of typenames.
Type t = vartype->getType();
if (TYPE_NODE == t)
{
Type vt = TypeNodeCast(vartype)->get_value();
if (vt != ATOM) // Atom type is same as untyped.
{
std::set<Type> ts = {vt};
_varlist._simple_typemap.insert({varname, ts});
}
}
else if (TYPE_CHOICE == t)
{
std::set<Type> typeset;
std::set<Handle> deepset;
std::set<Handle> fuzzset;
const HandleSeq& tset = LinkCast(vartype)->getOutgoingSet();
size_t tss = tset.size();
for (size_t i=0; i<tss; i++)
{
Handle ht(tset[i]);
Type var_type = ht->getType();
if (TYPE_NODE == var_type)
{
Type vt = TypeNodeCast(ht)->get_value();
if (ATOM != vt) typeset.insert(vt);
}
else if (SIGNATURE_LINK == var_type)
{
const HandleSeq& sig = LinkCast(ht)->getOutgoingSet();
if (1 != sig.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in SignatureLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
deepset.insert(ht);
}
else if (FUZZY_LINK == var_type)
{
const HandleSeq& fuz = LinkCast(ht)->getOutgoingSet();
if (1 != fuz.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in FuzzyLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
fuzzset.insert(ht);
}
else
{
throw InvalidParamException(TRACE_INFO,
"VariableChoice has unexpected content:\n"
"Expected TypeNode, got %s",
classserver().getTypeName(ht->getType()).c_str());
}
}
if (0 < typeset.size())
_varlist._simple_typemap.insert({varname, typeset});
if (0 < deepset.size())
_varlist._deep_typemap.insert({varname, deepset});
if (0 < fuzzset.size())
_varlist._fuzzy_typemap.insert({varname, fuzzset});
}
else if (SIGNATURE_LINK == t)
{
const HandleSeq& tset = LinkCast(vartype)->getOutgoingSet();
if (1 != tset.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in SignatureLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
std::set<Handle> ts;
ts.insert(vartype);
_varlist._deep_typemap.insert({varname, ts});
}
else if (FUZZY_LINK == t)
{
const HandleSeq& tset = LinkCast(vartype)->getOutgoingSet();
if (1 != tset.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in FuzzyLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
std::set<Handle> ts;
ts.insert(vartype);
_varlist._fuzzy_typemap.insert({varname, ts});
}
else
{
throw SyntaxException(TRACE_INFO,
"Unexpected contents in TypedVariableLink\n"
"Expected type specifier (e.g. TypeNode, TypeChoice, etc.), got %s",
classserver().getTypeName(t).c_str());
}
_varlist.varset.insert(varname);
_varlist.varseq.emplace_back(varname);
}
/* ================================================================= */
/**
* Validate variable declarations for syntax correctness.
*
* This will check to make sure that a set of variable declarations are
* of a reasonable form. Thus, for example, a structure similar to the
* below is expected.
*
* VariableList
* VariableNode "$var0"
* VariableNode "$var1"
* TypedVariableLink
* VariableNode "$var2"
* TypeNode "ConceptNode"
* TypedVariableLink
* VariableNode "$var3"
* TypeChoice
* TypeNode "PredicateNode"
* TypeNode "GroundedPredicateNode"
*
* As a side-effect, the variables and type restrictions are unpacked.
*/
void VariableList::validate_vardecl(const Handle& hdecls)
{
// Expecting the declaration list to be either a single
// variable, or a list of variable declarations
Type tdecls = hdecls->getType();
if (VARIABLE_NODE == tdecls or GLOB_NODE == tdecls)
{
_varlist.varset.insert(hdecls);
_varlist.varseq.emplace_back(hdecls);
}
else if (TYPED_VARIABLE_LINK == tdecls)
{
get_vartype(hdecls);
}
else if (VARIABLE_LIST == tdecls)
{
// The list of variable declarations should be .. a list of
// variables! Make sure its as expected.
const std::vector<Handle>& dset = LinkCast(hdecls)->getOutgoingSet();
validate_vardecl(dset);
}
else
{
throw InvalidParamException(TRACE_INFO,
"Expected a VariableList holding variable declarations");
}
build_index();
}
/* ================================================================= */
/**
* Build the index from variable name, to its ordinal number.
* The index is needed for variable substitution, i.e. for the
* substitute method below. The specific sequence order of the
* variables is essential for making substitution work.
*/
void VariableList::build_index(void)
{
if (0 < _varlist.index.size()) return;
size_t sz = _varlist.varseq.size();
for (size_t i=0; i<sz; i++)
{
_varlist.index.insert(std::pair<Handle, unsigned int>(_varlist.varseq[i], i));
}
}
/* ===================== END OF FILE ===================== */
<commit_msg>Remove some un-needed casts<commit_after>/*
* VariableList.cc
*
* Copyright (C) 2009, 2014, 2015 Linas Vepstas
*
* Author: Linas Vepstas <linasvepstas@gmail.com> January 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/base/ClassServer.h>
#include <opencog/atoms/TypeNode.h>
#include "VariableList.h"
using namespace opencog;
void VariableList::validate_vardecl(const HandleSeq& oset)
{
for (const Handle& h: oset)
{
Type t = h->getType();
if (VARIABLE_NODE == t or GLOB_NODE == t)
{
_varlist.varset.insert(h); // tree (unordered)
_varlist.varseq.emplace_back(h); // vector (ordered)
}
else if (TYPED_VARIABLE_LINK == t)
{
get_vartype(h);
}
else
throw InvalidParamException(TRACE_INFO,
"Expected a VariableNode or a TypedVariableLink, got: %s",
classserver().getTypeName(t).c_str());
}
build_index();
}
VariableList::VariableList(const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(VARIABLE_LIST, oset, tv, av)
{
validate_vardecl(oset);
}
VariableList::VariableList(Type t, const HandleSeq& oset,
TruthValuePtr tv, AttentionValuePtr av)
: Link(t, oset, tv, av)
{
// derived classes have a different initialization order
if (VARIABLE_LIST != t) return;
validate_vardecl(oset);
}
VariableList::VariableList(Link &l)
: Link(l)
{
// Type must be as expected
Type tscope = l.getType();
if (not classserver().isA(tscope, VARIABLE_LIST))
{
const std::string& tname = classserver().getTypeName(tscope);
throw InvalidParamException(TRACE_INFO,
"Expecting a VariableList, got %s", tname.c_str());
}
// Dervided types have a different initialization sequence
if (VARIABLE_LIST != tscope) return;
validate_vardecl(_outgoing);
}
/* ================================================================= */
/**
* Extract the variable type(s) from a TypedVariableLink
*
* The call is expecting htypelink to point to one of the two
* following structures:
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeNode "ConceptNode"
*
* or
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeChoice
* TypeNode "ConceptNode"
* TypeNode "NumberNode"
* TypeNode "WordNode"
*
* or possibly types that are SignatureLink's or FuyzzyLink's or
* polymorphic combinations thereof: e.g. the following is valid:
*
* TypedVariableLink
* VariableNode "$some_var_name"
* TypeChoice
* TypeNode "ConceptNode"
* SignatureLink
* InheritanceLink
* PredicateNode "foobar"
* TypeNode "ListLink"
* FuzzyLink
* InheritanceLink
* ConceptNode "animal"
* ConceptNode "tiger"
*
* In either case, the variable itself is appended to "vset",
* and the list of allowed types are associated with the variable
* via the map "typemap".
*/
void VariableList::get_vartype(const Handle& htypelink)
{
const std::vector<Handle>& oset = htypelink->getOutgoingSet();
if (2 != oset.size())
{
throw InvalidParamException(TRACE_INFO,
"TypedVariableLink has wrong size, got %lu", oset.size());
}
Handle varname = oset[0];
Handle vartype = oset[1];
// The vartype is either a single type name, or a list of typenames.
Type t = vartype->getType();
if (TYPE_NODE == t)
{
Type vt = TypeNodeCast(vartype)->get_value();
if (vt != ATOM) // Atom type is same as untyped.
{
std::set<Type> ts = {vt};
_varlist._simple_typemap.insert({varname, ts});
}
}
else if (TYPE_CHOICE == t)
{
std::set<Type> typeset;
std::set<Handle> deepset;
std::set<Handle> fuzzset;
const HandleSeq& tset = vartype->getOutgoingSet();
size_t tss = tset.size();
for (size_t i=0; i<tss; i++)
{
Handle ht(tset[i]);
Type var_type = ht->getType();
if (TYPE_NODE == var_type)
{
Type vt = TypeNodeCast(ht)->get_value();
if (ATOM != vt) typeset.insert(vt);
}
else if (SIGNATURE_LINK == var_type)
{
const HandleSeq& sig = ht->getOutgoingSet();
if (1 != sig.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in SignatureLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
deepset.insert(ht);
}
else if (FUZZY_LINK == var_type)
{
const HandleSeq& fuz = ht->getOutgoingSet();
if (1 != fuz.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in FuzzyLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
fuzzset.insert(ht);
}
else
{
throw InvalidParamException(TRACE_INFO,
"VariableChoice has unexpected content:\n"
"Expected TypeNode, got %s",
classserver().getTypeName(ht->getType()).c_str());
}
}
if (0 < typeset.size())
_varlist._simple_typemap.insert({varname, typeset});
if (0 < deepset.size())
_varlist._deep_typemap.insert({varname, deepset});
if (0 < fuzzset.size())
_varlist._fuzzy_typemap.insert({varname, fuzzset});
}
else if (SIGNATURE_LINK == t)
{
const HandleSeq& tset = vartype->getOutgoingSet();
if (1 != tset.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in SignatureLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
std::set<Handle> ts;
ts.insert(vartype);
_varlist._deep_typemap.insert({varname, ts});
}
else if (FUZZY_LINK == t)
{
const HandleSeq& tset = vartype->getOutgoingSet();
if (1 != tset.size())
throw SyntaxException(TRACE_INFO,
"Unexpected contents in FuzzyLink\n"
"Expected arity==1, got %s", vartype->toString().c_str());
std::set<Handle> ts;
ts.insert(vartype);
_varlist._fuzzy_typemap.insert({varname, ts});
}
else
{
throw SyntaxException(TRACE_INFO,
"Unexpected contents in TypedVariableLink\n"
"Expected type specifier (e.g. TypeNode, TypeChoice, etc.), got %s",
classserver().getTypeName(t).c_str());
}
_varlist.varset.insert(varname);
_varlist.varseq.emplace_back(varname);
}
/* ================================================================= */
/**
* Validate variable declarations for syntax correctness.
*
* This will check to make sure that a set of variable declarations are
* of a reasonable form. Thus, for example, a structure similar to the
* below is expected.
*
* VariableList
* VariableNode "$var0"
* VariableNode "$var1"
* TypedVariableLink
* VariableNode "$var2"
* TypeNode "ConceptNode"
* TypedVariableLink
* VariableNode "$var3"
* TypeChoice
* TypeNode "PredicateNode"
* TypeNode "GroundedPredicateNode"
*
* As a side-effect, the variables and type restrictions are unpacked.
*/
void VariableList::validate_vardecl(const Handle& hdecls)
{
// Expecting the declaration list to be either a single
// variable, or a list of variable declarations
Type tdecls = hdecls->getType();
if (VARIABLE_NODE == tdecls or GLOB_NODE == tdecls)
{
_varlist.varset.insert(hdecls);
_varlist.varseq.emplace_back(hdecls);
}
else if (TYPED_VARIABLE_LINK == tdecls)
{
get_vartype(hdecls);
}
else if (VARIABLE_LIST == tdecls)
{
// The list of variable declarations should be .. a list of
// variables! Make sure its as expected.
const std::vector<Handle>& dset = hdecls->getOutgoingSet();
validate_vardecl(dset);
}
else
{
throw InvalidParamException(TRACE_INFO,
"Expected a VariableList holding variable declarations");
}
build_index();
}
/* ================================================================= */
/**
* Build the index from variable name, to its ordinal number.
* The index is needed for variable substitution, i.e. for the
* substitute method below. The specific sequence order of the
* variables is essential for making substitution work.
*/
void VariableList::build_index(void)
{
if (0 < _varlist.index.size()) return;
size_t sz = _varlist.varseq.size();
for (size_t i=0; i<sz; i++)
{
_varlist.index.insert(std::pair<Handle, unsigned int>(_varlist.varseq[i], i));
}
}
/* ===================== END OF FILE ===================== */
<|endoftext|> |
<commit_before>#include "ncd_gateway.h"
#include "S3B.h"
#include "spark_wiring_eeprom.h"
String firmware_version = "000029";
S3B sModule;
String eventReturns[5];
unsigned long tOut = 3000;
void init_gateway(){
Particle.function("deviceComm", gatewayCommand);
Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES);
Particle.variable("ncd_version", firmware_version);
Serial1.begin(115200);
Wire.begin();
}
int hexToInt(String arg, byte bytes[], int length){
arg.getBytes(bytes, length+1);
for(int i=0;i<length;i++){
if(bytes[i]>70) bytes[i] -= 32;
if(bytes[i]>58) bytes[i] -= 7;
bytes[i] -= 48;
}
return 1;
}
int base64ToInt(String arg, byte buff[], int length){
byte bytes[length];
arg.getBytes(bytes, length+1);
int buffInd=0;
int cbits=0;
int cByte;
int adj;
for(int i=0;i<length;i++){
cByte = bytes[i];
if(cByte==43) cByte = 58;
if(cByte==47) cByte = 59;
if(cByte<65) cByte += 75;
if(cByte<97) cByte += 6;
cByte -= 71;
switch(cbits){
case 0:
buff[buffInd] = cByte << 2;
cbits = 6;
break;
case 2:
buff[buffInd] = buff[buffInd]+cByte;
buffInd++;
cbits = 0;
break;
case 4:
buff[buffInd] = buff[buffInd] + (cByte >> 2);
buffInd++;
buff[buffInd] = (cByte & 3) << 6;
cbits = 2;
break;
case 6:
buff[buffInd] = buff[buffInd] + (cByte >> 4);
buffInd++;
buff[buffInd] = (cByte & 15) << 4;
cbits = 4;
break;
}
}
return 1;
}
int gatewayCommand(String arg){
int length = arg.length();
byte buff[length];
base64ToInt(arg, buff, length);
return ncdApi(buff);
}
void commandHandler(const char *event, const char *data){
String newCommand = String(data);
gatewayCommand(newCommand);
}
int ncdApi(byte packetBytes[]){
int buffLen = 1;
Serial.println(String(packetBytes[0]));
switch(packetBytes[0]){
case 185:
{
return firmware_version.toInt();
}
case 186:
{
//I2C bus scan
int start = packetBytes[1]*32+1;
int end = start+32;
int addrStatus;
int status = 0;
for(start;start<end;start++){
Wire.beginTransmission(start);
addrStatus = Wire.endTransmission();
if(start+32 > end){
status = status << 1;
}
if(addrStatus > 0){
addrStatus = 1;
}
status+=addrStatus;
}
return status;
}
case 187:
{
//packet of packets
int i=2;
int max;
byte status[packetBytes[1]];
for(int pn = 0; pn<packetBytes[1]; pn++){
max=i+packetBytes[i];
Serial.println(max);
byte intPacket[packetBytes[i]];
i++;
int ni=0;
for(i;i<=max;i++){
intPacket[ni]=packetBytes[i];
ni++;
}
status[pn]=ncdApi(intPacket);
}
return bytesToInt(status, packetBytes[1]);
}
case 188:
{
//plain i2c w/r command
if(packetBytes[3] > 0){
buffLen = packetBytes[3];
}
byte buff[buffLen];
i2c_command(packetBytes, buff);
return bytesToInt(buff, buffLen);
}
case 189:
{
//masking command
int addr = packetBytes[1];
int maskOp = packetBytes[2];
int maskedOffsets = packetBytes[3];
int readCommandLen = packetBytes[4];
int readLen = packetBytes[5];
int readCommand[readCommandLen];
array_slice(packetBytes, 6, readCommandLen, readCommand);
int writeCommandLen = packetBytes[6+readCommandLen];
int writeCommand[writeCommandLen];
array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand);
int writeVals[writeCommandLen];
int wi=0;
for(wi; wi<maskedOffsets; wi++){
writeVals[wi]=writeCommand[wi];
Serial.println(writeVals[wi]);
}
writeCommandsI2C(addr, readCommand, readCommandLen);
Wire.requestFrom(addr, readLen);
for(int i=0;i<readLen;i++){
int current = Wire.read();
writeVals[wi] = mask(current, writeCommand[wi], maskOp);
Serial.println(current);
Serial.println(writeVals[wi]);
wi++;
}
return writeCommandsI2C(addr, writeVals, writeCommandLen);
}
case 190:
{
int delayTime = (packetBytes[1] << 8) + packetBytes[2];
delay(delayTime);
return 1;
}
}
return 1;
}
int mask(int val, int mask, int type){
switch(type){
case 0:
val |= mask;
break;
case 1:
val ^= mask;
break;
case 2:
val &= ~mask;
break;
case 3:
val &= mask;
break;
case 4:
val = val << mask;
break;
case 5:
val = val >> mask;
}
return val;
}
void i2c_command(byte bytes[], byte *buff){
if(bytes[0] == 188){
int commands[bytes[2]];
array_slice(bytes, 4, bytes[2], commands);
int addr = bytes[1];
if(bytes[3] == 0){
//write command
buff[0]=writeCommandsI2C(addr, commands, bytes[2]);
}else{
//read command
writeCommandsI2C(addr, commands, bytes[2]);
Wire.requestFrom(addr, bytes[3]);
for(int i=0;i<bytes[3];i++){
buff[i] = Wire.read();
}
}
}
}
void array_slice(byte bytes[], int start, int len, byte *buff){
int ni = 0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
void array_slice(byte bytes[], int start, int len, int *buff){
int ni=0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
int sendEvent(String key){
int i = key.toInt();
String eventName = "";
eventName = "eventReturn_"+key;
Particle.publish(eventName, eventReturns[i], 60, PRIVATE);
eventReturns[i] = "";
return 1;
};
int setEventReturn(String value){
int index = 0;
while(eventReturns[index].length() > 1){
index++;
}
eventReturns[index] = value;
return index;
};
int writeCommandsI2C(int addr, int* commands, int commandsLen){
Serial.printf("Running I2C Command, address: %i data: ",addr);
Wire.beginTransmission(addr);
for(int i = 0; i < commandsLen; i++){
Wire.write(commands[i]);
Serial.printf("%i, ",commands[i]);
}
int status = Wire.endTransmission();
Serial.printf(" Status: %i \n", status);
return status;
};
int bytesToInt(byte bytes[], int length){
int ret = bytes[0];
for(int i=1; i<length; i++){
ret = ret << 8;
ret += bytes[i];
}
return ret;
}
<commit_msg>Update ncd_gateway.cpp<commit_after>#include "ncd_gateway.h"
#include "spark_wiring_eeprom.h"
String firmware_version = "000029";
String eventReturns[5];
unsigned long tOut = 3000;
void init_gateway(){
Particle.function("deviceComm", gatewayCommand);
Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES);
Particle.variable("ncd_version", firmware_version);
Wire.begin();
}
int hexToInt(String arg, byte bytes[], int length){
arg.getBytes(bytes, length+1);
for(int i=0;i<length;i++){
if(bytes[i]>70) bytes[i] -= 32;
if(bytes[i]>58) bytes[i] -= 7;
bytes[i] -= 48;
}
return 1;
}
int base64ToInt(String arg, byte buff[], int length){
byte bytes[length];
arg.getBytes(bytes, length+1);
int buffInd=0;
int cbits=0;
int cByte;
int adj;
for(int i=0;i<length;i++){
cByte = bytes[i];
if(cByte==43) cByte = 58;
if(cByte==47) cByte = 59;
if(cByte<65) cByte += 75;
if(cByte<97) cByte += 6;
cByte -= 71;
switch(cbits){
case 0:
buff[buffInd] = cByte << 2;
cbits = 6;
break;
case 2:
buff[buffInd] = buff[buffInd]+cByte;
buffInd++;
cbits = 0;
break;
case 4:
buff[buffInd] = buff[buffInd] + (cByte >> 2);
buffInd++;
buff[buffInd] = (cByte & 3) << 6;
cbits = 2;
break;
case 6:
buff[buffInd] = buff[buffInd] + (cByte >> 4);
buffInd++;
buff[buffInd] = (cByte & 15) << 4;
cbits = 4;
break;
}
}
return 1;
}
int gatewayCommand(String arg){
int length = arg.length();
byte buff[length];
base64ToInt(arg, buff, length);
Serial.println(arg);
return ncdApi(buff);
}
void commandHandler(const char *event, const char *data){
String newCommand = String(data);
gatewayCommand(newCommand);
}
int ncdApi(byte packetBytes[]){
int buffLen = 1;
Serial.println(String(packetBytes[0]));
switch(packetBytes[0]){
case 185:
{
return firmware_version.toInt();
}
case 186:
{
//I2C bus scan
Serial.println(String(packetBytes[1]));
Serial.println(String(packetBytes[2]));
int start = packetBytes[1]*32+1;
int end = start+32;
int addrStatus;
int status = 0;
for(start;start<end;start++){
Wire.beginTransmission(start);
addrStatus = Wire.endTransmission();
if(start+32 > end){
status = status << 1;
}
if(addrStatus > 0){
addrStatus = 1;
}else{
Serial.print("Device found on: ");
Serial.println(start);
}
status+=addrStatus;
}
return status;
}
case 187:
{
//packet of packets
int i=2;
int max;
byte status[packetBytes[1]];
for(int pn = 0; pn<packetBytes[1]; pn++){
max=i+packetBytes[i];
Serial.println(max);
byte intPacket[packetBytes[i]];
i++;
int ni=0;
for(i;i<=max;i++){
intPacket[ni]=packetBytes[i];
ni++;
}
status[pn]=ncdApi(intPacket);
}
return bytesToInt(status, packetBytes[1]);
}
case 188:
{
//plain i2c w/r command
if(packetBytes[3] > 0){
buffLen = packetBytes[3];
}
byte buff[buffLen];
i2c_command(packetBytes, buff);
return bytesToInt(buff, buffLen);
}
case 189:
{
//masking command
int addr = packetBytes[1];
int maskOp = packetBytes[2];
int maskedOffsets = packetBytes[3];
int readCommandLen = packetBytes[4];
int readLen = packetBytes[5];
int readCommand[readCommandLen];
array_slice(packetBytes, 6, readCommandLen, readCommand);
int writeCommandLen = packetBytes[6+readCommandLen];
int writeCommand[writeCommandLen];
array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand);
int writeVals[writeCommandLen];
int wi=0;
for(wi; wi<maskedOffsets; wi++){
writeVals[wi]=writeCommand[wi];
Serial.println(writeVals[wi]);
}
writeCommandsI2C(addr, readCommand, readCommandLen);
Wire.requestFrom(addr, readLen);
for(int i=0;i<readLen;i++){
int current = Wire.read();
writeVals[wi] = mask(current, writeCommand[wi], maskOp);
Serial.println(current);
Serial.println(writeVals[wi]);
wi++;
}
return writeCommandsI2C(addr, writeVals, writeCommandLen);
}
case 190:
{
int delayTime = (packetBytes[1] << 8) + packetBytes[2];
delay(delayTime);
return 1;
}
}
return 1;
}
int mask(int val, int mask, int type){
switch(type){
case 0:
val |= mask;
break;
case 1:
val ^= mask;
break;
case 2:
val &= ~mask;
break;
case 3:
val &= mask;
break;
case 4:
val = val << mask;
break;
case 5:
val = val >> mask;
}
return val;
}
void i2c_command(byte bytes[], byte *buff){
if(bytes[0] == 188){
int commands[bytes[2]];
array_slice(bytes, 4, bytes[2], commands);
int addr = bytes[1];
if(bytes[3] == 0){
//write command
buff[0]=writeCommandsI2C(addr, commands, bytes[2]);
}else{
//read command
writeCommandsI2C(addr, commands, bytes[2]);
Wire.requestFrom(addr, bytes[3]);
for(int i=0;i<bytes[3];i++){
buff[i] = Wire.read();
}
}
}
}
void array_slice(byte bytes[], int start, int len, byte *buff){
int ni = 0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
void array_slice(byte bytes[], int start, int len, int *buff){
int ni=0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
int sendEvent(String key){
int i = key.toInt();
String eventName = "";
eventName = "eventReturn_"+key;
Particle.publish(eventName, eventReturns[i], 60, PRIVATE);
eventReturns[i] = "";
return 1;
};
int setEventReturn(String value){
int index = 0;
while(eventReturns[index].length() > 1){
index++;
}
eventReturns[index] = value;
return index;
};
int writeCommandsI2C(int addr, int* commands, int commandsLen){
Serial.printf("Running I2C Command, address: %i data: ",addr);
Wire.beginTransmission(addr);
for(int i = 0; i < commandsLen; i++){
Wire.write(commands[i]);
Serial.printf("%i, ",commands[i]);
}
int status = Wire.endTransmission();
Serial.printf(" Status: %i \n", status);
return status;
};
int bytesToInt(byte bytes[], int length){
int ret = bytes[0];
for(int i=1; i<length; i++){
ret = ret << 8;
ret += bytes[i];
}
return ret;
}
<|endoftext|> |
<commit_before>/*
nsjail - logging
-----------------------------------------
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "logs.h"
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "macros.h"
#include "util.h"
#include <string.h>
namespace logs {
static int _log_fd = STDERR_FILENO;
static bool _log_fd_isatty = true;
static enum llevel_t _log_level = INFO;
static bool _log_set = false;
__attribute__((constructor)) static void log_init(void) {
_log_fd_isatty = isatty(_log_fd);
}
bool logSet() {
return _log_set;
}
/*
* Log to stderr by default. Use a dup()d fd, because in the future we'll associate the
* connection socket with fd (0, 1, 2).
*/
void logLevel(enum llevel_t ll) {
_log_level = ll;
}
void logFile(const std::string& logfile) {
_log_set = true;
/* Close previous log_fd */
if (_log_fd > STDERR_FILENO) {
close(_log_fd);
_log_fd = STDERR_FILENO;
}
if (logfile.empty()) {
_log_fd = fcntl(_log_fd, F_DUPFD_CLOEXEC, 0);
} else {
if (TEMP_FAILURE_RETRY(_log_fd = open(logfile.c_str(),
O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640)) == -1) {
_log_fd = STDERR_FILENO;
_log_fd_isatty = (isatty(_log_fd) == 1 ? true : false);
PLOG_E("Couldn't open logfile open('%s')", logfile.c_str());
}
}
_log_fd_isatty = (isatty(_log_fd) == 1 ? true : false);
}
void logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) {
if (ll < _log_level) {
return;
}
char strerr[512];
if (perr) {
snprintf(strerr, sizeof(strerr), "%s", strerror(errno));
}
struct ll_t {
const char* const descr;
const char* const prefix;
const bool print_funcline;
const bool print_time;
};
static struct ll_t const logLevels[] = {
{"D", "\033[0;4m", true, true},
{"I", "\033[1m", false, true},
{"W", "\033[0;33m", true, true},
{"E", "\033[1;31m", true, true},
{"F", "\033[7;35m", true, true},
{"HR", "\033[0m", false, false},
{"HB", "\033[1m", false, false},
};
/* Start printing logs */
if (_log_fd_isatty) {
dprintf(_log_fd, "%s", logLevels[ll].prefix);
}
if (logLevels[ll].print_time) {
const auto timestr = util::timeToStr(time(NULL));
dprintf(_log_fd, "[%s] ", timestr.c_str());
}
if (logLevels[ll].print_funcline) {
dprintf(_log_fd, "[%s][%d] %s():%d ", logLevels[ll].descr, (int)getpid(), fn, ln);
}
va_list args;
va_start(args, fmt);
vdprintf(_log_fd, fmt, args);
va_end(args);
if (perr) {
dprintf(_log_fd, ": %s", strerr);
}
if (_log_fd_isatty) {
dprintf(_log_fd, "\033[0m");
}
dprintf(_log_fd, "\n");
/* End printing logs */
if (ll == FATAL) {
exit(0xff);
}
}
void logStop(int sig) {
LOG_I("Server stops due to fatal signal (%d) caught. Exiting", sig);
}
} // namespace logs
<commit_msg>logs: lower logfile error to warning<commit_after>/*
nsjail - logging
-----------------------------------------
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "logs.h"
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include "macros.h"
#include "util.h"
#include <string.h>
namespace logs {
static int _log_fd = STDERR_FILENO;
static bool _log_fd_isatty = true;
static enum llevel_t _log_level = INFO;
static bool _log_set = false;
__attribute__((constructor)) static void log_init(void) {
_log_fd_isatty = isatty(_log_fd);
}
bool logSet() {
return _log_set;
}
/*
* Log to stderr by default. Use a dup()d fd, because in the future we'll associate the
* connection socket with fd (0, 1, 2).
*/
void logLevel(enum llevel_t ll) {
_log_level = ll;
}
void logFile(const std::string& logfile) {
_log_set = true;
/* Close previous log_fd */
if (_log_fd > STDERR_FILENO) {
close(_log_fd);
_log_fd = STDERR_FILENO;
}
if (logfile.empty()) {
_log_fd = fcntl(_log_fd, F_DUPFD_CLOEXEC, 0);
} else {
if (TEMP_FAILURE_RETRY(_log_fd = open(logfile.c_str(),
O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640)) == -1) {
_log_fd = STDERR_FILENO;
_log_fd_isatty = (isatty(_log_fd) == 1 ? true : false);
PLOG_W("Couldn't open logfile open('%s')", logfile.c_str());
}
}
_log_fd_isatty = (isatty(_log_fd) == 1);
}
void logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) {
if (ll < _log_level) {
return;
}
char strerr[512];
if (perr) {
snprintf(strerr, sizeof(strerr), "%s", strerror(errno));
}
struct ll_t {
const char* const descr;
const char* const prefix;
const bool print_funcline;
const bool print_time;
};
static struct ll_t const logLevels[] = {
{"D", "\033[0;4m", true, true},
{"I", "\033[1m", false, true},
{"W", "\033[0;33m", true, true},
{"E", "\033[1;31m", true, true},
{"F", "\033[7;35m", true, true},
{"HR", "\033[0m", false, false},
{"HB", "\033[1m", false, false},
};
/* Start printing logs */
if (_log_fd_isatty) {
dprintf(_log_fd, "%s", logLevels[ll].prefix);
}
if (logLevels[ll].print_time) {
const auto timestr = util::timeToStr(time(NULL));
dprintf(_log_fd, "[%s] ", timestr.c_str());
}
if (logLevels[ll].print_funcline) {
dprintf(_log_fd, "[%s][%d] %s():%d ", logLevels[ll].descr, (int)getpid(), fn, ln);
}
va_list args;
va_start(args, fmt);
vdprintf(_log_fd, fmt, args);
va_end(args);
if (perr) {
dprintf(_log_fd, ": %s", strerr);
}
if (_log_fd_isatty) {
dprintf(_log_fd, "\033[0m");
}
dprintf(_log_fd, "\n");
/* End printing logs */
if (ll == FATAL) {
exit(0xff);
}
}
void logStop(int sig) {
LOG_I("Server stops due to fatal signal (%d) caught. Exiting", sig);
}
} // namespace logs
<|endoftext|> |
<commit_before>
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkExampleDataStructure.h"
#include "mitkGeometry3D.h"
// implementation of virtual methods
void mitk::ExampleDataStructure::UpdateOutputInformation()
{
}
void mitk::ExampleDataStructure::SetRequestedRegionToLargestPossibleRegion()
{
}
bool mitk::ExampleDataStructure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
bool mitk::ExampleDataStructure::VerifyRequestedRegion()
{
return true;
}
void mitk::ExampleDataStructure::SetRequestedRegion(const itk::DataObject *)
{
}
/* Constructor and Destructor */
mitk::ExampleDataStructure::ExampleDataStructure()
: m_Data("Initialized")
{
this->SetGeometry(mitk::Geometry3D::New());
}
mitk::ExampleDataStructure::~ExampleDataStructure()
{
}
void mitk::ExampleDataStructure::AppendAString(const std::string input)
{
m_Data.append( input );
}
bool mitk::Equal( mitk::ExampleDataStructure* leftHandSide, mitk::ExampleDataStructure* rightHandSide, mitk::ScalarType eps, bool verbose )
{
bool noDifferenceFound = true;
if( rightHandSide == NULL )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] rightHandSide NULL.";
}
return false;
}
if( leftHandSide == NULL )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] leftHandSide NULL.";
}
return false;
}
if (!(leftHandSide->GetData() == rightHandSide->GetData()) )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] Data not equal. ";
MITK_INFO << leftHandSide->GetData() << " != " << rightHandSide->GetData();
}
noDifferenceFound = false;
}
return noDifferenceFound;
}
<commit_msg>Comment out unused variable<commit_after>
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkExampleDataStructure.h"
#include "mitkGeometry3D.h"
// implementation of virtual methods
void mitk::ExampleDataStructure::UpdateOutputInformation()
{
}
void mitk::ExampleDataStructure::SetRequestedRegionToLargestPossibleRegion()
{
}
bool mitk::ExampleDataStructure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
bool mitk::ExampleDataStructure::VerifyRequestedRegion()
{
return true;
}
void mitk::ExampleDataStructure::SetRequestedRegion(const itk::DataObject *)
{
}
/* Constructor and Destructor */
mitk::ExampleDataStructure::ExampleDataStructure()
: m_Data("Initialized")
{
this->SetGeometry(mitk::Geometry3D::New());
}
mitk::ExampleDataStructure::~ExampleDataStructure()
{
}
void mitk::ExampleDataStructure::AppendAString(const std::string input)
{
m_Data.append( input );
}
bool mitk::Equal( mitk::ExampleDataStructure* leftHandSide, mitk::ExampleDataStructure* rightHandSide, mitk::ScalarType /*eps*/, bool verbose )
{
bool noDifferenceFound = true;
if( rightHandSide == NULL )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] rightHandSide NULL.";
}
return false;
}
if( leftHandSide == NULL )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] leftHandSide NULL.";
}
return false;
}
if (!(leftHandSide->GetData() == rightHandSide->GetData()) )
{
if(verbose)
{
MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] Data not equal. ";
MITK_INFO << leftHandSide->GetData() << " != " << rightHandSide->GetData();
}
noDifferenceFound = false;
}
return noDifferenceFound;
}
<|endoftext|> |
<commit_before><commit_msg>Prevent duplicate issued orders log output on listen servers.<commit_after><|endoftext|> |
<commit_before>#include "visgraph.hpp"
#include "../utils/utils.hpp"
#include <cstring>
#include <cstdio>
#include <cerrno>
static unsigned int Npolys = 500;
static unsigned int Maxverts = 8;
static double Minrad = 0.05;
static double Maxrad = 0.075;
static const char *outfile;
static void randpolys(std::vector<Polygon>&);
static double rnddbl(double, double);
static void usage(void);
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0)
usage();
else if (i < argc - 1 && strcmp(argv[i], "-n") == 0)
Npolys = strtoll(argv[++i], NULL, 10);
else if (i < argc - 1 && strcmp(argv[i], "-v") == 0)
Maxverts = strtoll(argv[++i], NULL, 10);
else if (i < argc - 1 && strcmp(argv[i], "-o") == 0)
outfile = argv[++i];
else if (i < argc - 1 && strcmp(argv[i], "-m") == 0)
Minrad = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-x") == 0)
Maxrad = strtod(argv[++i], NULL);
}
std::vector<Polygon> polys;
randpolys(polys);
VisGraph graph(polys);
if (outfile) {
FILE *f = fopen(outfile, "w");
if (!f)
fatalx(errno, "Failed to open %s:", outfile);
graph.output(stdout);
fclose(f);
} else {
graph.output(stdout);
}
return 0;
}
static void randpolys(std::vector<Polygon> &polys) {
for (unsigned int i = 0; i < Npolys; i++) {
redo:
double r = rnddbl(Minrad, Maxrad);
double x = rnddbl(r, 1 - r);
double y = rnddbl(r, 1 - r);
assert (x >= 0.0);
assert (y >= 0.0);
assert (r >= 0.0);
Polygon p = Polygon::random(randgen.integer(3, Maxverts), x, y, r);
for (unsigned int i = 0; i < polys.size(); i++) {
if (polys[i].bbox.isect(p.bbox))
goto redo;
}
polys.push_back(p);
}
}
static double rnddbl(double min, double max) {
assert (max > min);
return randgen.real() * (max - min) + min;
}
static void usage(void) {
puts("Usage: rand [options]");
puts("\nPlaces random polygons in the unit square. Computes the");
puts("visibility graph and prints the instance to standard output");
puts("\nOptions:");
puts(" -h prints this help message");
puts(" -n <num> specify the number of polygons (default: 500)");
puts(" -v <num> specify the max number of vertices (default: 8)");
puts(" -o <file> output to the specified file instead of standard output");
puts(" -m <num> minimum polygon radius (default: 0.05)");
puts(" -x <num> maximum polygon radius (default: 0.075)");
exit(0);
}<commit_msg>visnav: tiny formatting fix.<commit_after>#include "visgraph.hpp"
#include "../utils/utils.hpp"
#include <cstring>
#include <cstdio>
#include <cerrno>
static void randpolys(std::vector<Polygon>&);
static double rnddbl(double, double);
static void usage(void);
static unsigned int Npolys = 500;
static unsigned int Maxverts = 8;
static double Minrad = 0.05;
static double Maxrad = 0.075;
static const char *outfile;
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0)
usage();
else if (i < argc - 1 && strcmp(argv[i], "-n") == 0)
Npolys = strtoll(argv[++i], NULL, 10);
else if (i < argc - 1 && strcmp(argv[i], "-v") == 0)
Maxverts = strtoll(argv[++i], NULL, 10);
else if (i < argc - 1 && strcmp(argv[i], "-o") == 0)
outfile = argv[++i];
else if (i < argc - 1 && strcmp(argv[i], "-m") == 0)
Minrad = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-x") == 0)
Maxrad = strtod(argv[++i], NULL);
}
std::vector<Polygon> polys;
randpolys(polys);
VisGraph graph(polys);
if (outfile) {
FILE *f = fopen(outfile, "w");
if (!f)
fatalx(errno, "Failed to open %s:", outfile);
graph.output(stdout);
fclose(f);
} else {
graph.output(stdout);
}
return 0;
}
static void randpolys(std::vector<Polygon> &polys) {
for (unsigned int i = 0; i < Npolys; i++) {
redo:
double r = rnddbl(Minrad, Maxrad);
double x = rnddbl(r, 1 - r);
double y = rnddbl(r, 1 - r);
assert (x >= 0.0);
assert (y >= 0.0);
assert (r >= 0.0);
Polygon p = Polygon::random(randgen.integer(3, Maxverts), x, y, r);
for (unsigned int i = 0; i < polys.size(); i++) {
if (polys[i].bbox.isect(p.bbox))
goto redo;
}
polys.push_back(p);
}
}
static double rnddbl(double min, double max) {
assert (max > min);
return randgen.real() * (max - min) + min;
}
static void usage(void) {
puts("Usage: rand [options]");
puts("\nPlaces random polygons in the unit square. Computes the");
puts("visibility graph and prints the instance to standard output");
puts("\nOptions:");
puts(" -h prints this help message");
puts(" -n <num> specify the number of polygons (default: 500)");
puts(" -v <num> specify the max number of vertices (default: 8)");
puts(" -o <file> output to the specified file instead of standard output");
puts(" -m <num> minimum polygon radius (default: 0.05)");
puts(" -x <num> maximum polygon radius (default: 0.075)");
exit(0);
}<|endoftext|> |
<commit_before>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "common/linux/google_crashdump_uploader.h"
#include "third_party/linux/include/gflags/gflags.h"
#include <string>
#include <iostream>
using std::string;
DEFINE_string(crash_server, "http://clients2.google.com/cr",
"The crash server to upload minidumps to.");
DEFINE_string(product_name, "",
"The product name that the minidump corresponds to.");
DEFINE_string(product_version, "",
"The version of the product that produced the minidump.");
DEFINE_string(client_id, "",
"The client GUID");
DEFINE_string(minidump_path, "",
"The path of the minidump file.");
DEFINE_string(ptime, "",
"The process uptime in milliseconds.");
DEFINE_string(ctime, "",
"The cumulative process uptime in milliseconds.");
DEFINE_string(email, "",
"The user's email address.");
DEFINE_string(comments, "",
"Extra user comments");
DEFINE_string(proxy_host, "",
"Proxy host");
DEFINE_string(proxy_userpasswd, "",
"Proxy username/password in user:pass format.");
bool CheckForRequiredFlagsOrDie() {
std::string error_text = "";
if (FLAGS_product_name.empty()) {
error_text.append("\nProduct name must be specified.");
}
if (FLAGS_product_version.empty()) {
error_text.append("\nProduct version must be specified.");
}
if (FLAGS_client_id.empty()) {
error_text.append("\nClient ID must be specified.");
}
if (FLAGS_minidump_path.empty()) {
error_text.append("\nMinidump pathname must be specified.");
}
if (!error_text.empty()) {
std::cout << error_text;
return false;
}
return true;
}
int main(int argc, char *argv[]) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
if (!CheckForRequiredFlagsOrDie()) {
return 1;
}
google_breakpad::GoogleCrashdumpUploader g(FLAGS_product_name,
FLAGS_product_version,
FLAGS_client_id,
FLAGS_ptime,
FLAGS_ctime,
FLAGS_email,
FLAGS_comments,
FLAGS_minidump_path,
FLAGS_crash_server,
FLAGS_proxy_host,
FLAGS_proxy_userpasswd);
g.Upload();
}
<commit_msg>Send crash dumps to Google via HTTPS instead of HTTP, since they might contain sensitive information.<commit_after>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "common/linux/google_crashdump_uploader.h"
#include "third_party/linux/include/gflags/gflags.h"
#include <string>
#include <iostream>
using std::string;
DEFINE_string(crash_server, "https://clients2.google.com/cr",
"The crash server to upload minidumps to.");
DEFINE_string(product_name, "",
"The product name that the minidump corresponds to.");
DEFINE_string(product_version, "",
"The version of the product that produced the minidump.");
DEFINE_string(client_id, "",
"The client GUID");
DEFINE_string(minidump_path, "",
"The path of the minidump file.");
DEFINE_string(ptime, "",
"The process uptime in milliseconds.");
DEFINE_string(ctime, "",
"The cumulative process uptime in milliseconds.");
DEFINE_string(email, "",
"The user's email address.");
DEFINE_string(comments, "",
"Extra user comments");
DEFINE_string(proxy_host, "",
"Proxy host");
DEFINE_string(proxy_userpasswd, "",
"Proxy username/password in user:pass format.");
bool CheckForRequiredFlagsOrDie() {
std::string error_text = "";
if (FLAGS_product_name.empty()) {
error_text.append("\nProduct name must be specified.");
}
if (FLAGS_product_version.empty()) {
error_text.append("\nProduct version must be specified.");
}
if (FLAGS_client_id.empty()) {
error_text.append("\nClient ID must be specified.");
}
if (FLAGS_minidump_path.empty()) {
error_text.append("\nMinidump pathname must be specified.");
}
if (!error_text.empty()) {
std::cout << error_text;
return false;
}
return true;
}
int main(int argc, char *argv[]) {
google::InitGoogleLogging(argv[0]);
google::ParseCommandLineFlags(&argc, &argv, true);
if (!CheckForRequiredFlagsOrDie()) {
return 1;
}
google_breakpad::GoogleCrashdumpUploader g(FLAGS_product_name,
FLAGS_product_version,
FLAGS_client_id,
FLAGS_ptime,
FLAGS_ctime,
FLAGS_email,
FLAGS_comments,
FLAGS_minidump_path,
FLAGS_crash_server,
FLAGS_proxy_host,
FLAGS_proxy_userpasswd);
g.Upload();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* main.cpp
* copyright (C)2003 by Sebastian Sauer (mail@dipe.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
* This 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
* Library General Public License for more details.
* You should have received a copy of the GNU Library General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
***************************************************************************/
#include <Python.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qfile.h>
#include <kdebug.h>
#include <kinstance.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "../CXX/Objects.hxx"
#include "../kexidb/pythonkexidb.h"
#include "../kexidb/pythonkexidbdriver.h"
#include "../main/pythonmanager.h"
KApplication *app = 0;
static KCmdLineOptions options[] =
{
{ "file <filename>", I18N_NOOP("Pythonfile to execute."), "test.py" },
{ 0, 0, 0}
};
int main(int argc, char **argv)
{
int result = 0;
KCmdLineArgs::init(argc, argv,
new KAboutData("KrossPythonTest", "KrossPythonTest",
"0.1", "", KAboutData::License_GPL,
"(c) 2004, Sebastian Sauer (mail@dipe.org)\n"
"http://www.koffice.org/kexi\n"
"http://www.dipe.org/kross",
"kross@dipe.org"
)
);
KCmdLineArgs::addCmdLineOptions(options);
app = new KApplication(true, true);
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
Kross::PythonManager* pymanager = new Kross::PythonManager("Kross");
QFile f(QFile::encodeName( args->getOption("file") ));
if(f.exists() && f.open(IO_ReadOnly)) {
QString data = f.readAll();
f.close();
kdDebug() << "##############################################" << endl;
pymanager->execute(data, QStringList() << "kexidb");
kdDebug() << "##############################################" << endl;
}
else {
kdWarning() << "Failed to load Python scriptfile: " << args->getOption("file") << endl;
result = -1;
}
delete pymanager;
delete app;
return result;
}
<commit_msg>s/GPL/LGPL/; as well.<commit_after>/***************************************************************************
* main.cpp
* copyright (C)2003 by Sebastian Sauer (mail@dipe.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
* This 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
* Library General Public License for more details.
* You should have received a copy of the GNU Library General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
***************************************************************************/
#include <Python.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qfile.h>
#include <kdebug.h>
#include <kinstance.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "../CXX/Objects.hxx"
#include "../kexidb/pythonkexidb.h"
#include "../kexidb/pythonkexidbdriver.h"
#include "../main/pythonmanager.h"
KApplication *app = 0;
static KCmdLineOptions options[] =
{
{ "file <filename>", I18N_NOOP("Pythonfile to execute."), "test.py" },
{ 0, 0, 0}
};
int main(int argc, char **argv)
{
int result = 0;
KCmdLineArgs::init(argc, argv,
new KAboutData("KrossPythonTest", "KrossPythonTest",
"0.1", "", KAboutData::License_LGPL,
"(c) 2004, Sebastian Sauer (mail@dipe.org)\n"
"http://www.koffice.org/kexi\n"
"http://www.dipe.org/kross",
"kross@dipe.org"
)
);
KCmdLineArgs::addCmdLineOptions(options);
app = new KApplication(true, true);
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
Kross::PythonManager* pymanager = new Kross::PythonManager("Kross");
QFile f(QFile::encodeName( args->getOption("file") ));
if(f.exists() && f.open(IO_ReadOnly)) {
QString data = f.readAll();
f.close();
kdDebug() << "##############################################" << endl;
pymanager->execute(data, QStringList() << "kexidb");
kdDebug() << "##############################################" << endl;
}
else {
kdWarning() << "Failed to load Python scriptfile: " << args->getOption("file") << endl;
result = -1;
}
delete pymanager;
delete app;
return result;
}
<|endoftext|> |
<commit_before>/*
Copyright 2012 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 17/02/2012.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/filter/gaussian_smooth.h"
#include "image/filter/anisotropic_smooth.h"
#include "progressbar.h"
using namespace MR;
using namespace App;
void usage ()
{
DESCRIPTION
+ "smooth n-dimensional images by a convolution with a Gaussian kernel. "
+ "Note that if the input volume is 4D, then by default each 3D volume is smoothed independently. However "
"this behaviour can be overridden by manually setting the stdev for all dimensions.";
ARGUMENTS
+ Argument ("input", "input image to be smoothed.").type_image_in ()
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
"The standard deviation is defined in mm (Default 1 voxel). "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the stdev for each axis.")
+ Argument ("mm").type_sequence_float()
+ Option ("fwhm", "apply Gaussian smoothing with the specified full-width half maximum. "
"The FWHM is defined in mm (Default 1 voxel * 2.3548). "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the FWHM for each axis.")
+ Argument ("mm").type_sequence_float()
+ Option ("extent", "specify the extent (width) of kernel size in voxels. "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the extent for each axis. "
"The default extent is 2 * ceil(2.5 * stdev / voxel_size) - 1.")
+ Argument ("voxels").type_sequence_int()
+ Option ("anisotropic", "smooth each 3D volume of a 4D image using an anisotropic gaussian kernel "
"oriented along a corresponding direction. Note that when this option is used "
"the -stdev option takes two comma separated values, the first value defines the standard "
"deviation along the major eigenvector of the kernel (default: 1.27mm (FWHM = 3mm)) and "
"the second value defines the standard deviation along the other two eigenvectors "
"(default: 0.42mm (FWHM = 1mm)). The directions can be specified within the header of the input image, "
"or by using the -directions option.")
+ Option ("directions", "the directions for anisotropic smoothing.")
+ Argument ("file", "a list of directions [az el] generated using the gendir command.").type_file()
+ Image::Stride::StrideOption;
}
void run () {
Image::Header header (argument[0]);
Image::BufferPreload<float> input_data (header);
Image::BufferPreload<float>::voxel_type input_vox (input_data);
bool do_anisotropic = false;
Options opt = get_options ("anisotropic");
if (opt.size())
do_anisotropic = true;
std::vector<float> stdev;
if (do_anisotropic) {
stdev.resize(2, 3.0 / 2.3548);
stdev[1] = 1.0 / 2.3548;
} else {
stdev.resize(3);
for (size_t dim = 0; dim < 3; dim++)
stdev[dim] = input_data.vox (dim);
}
opt = get_options ("stdev");
int stdev_supplied = opt.size();
if (stdev_supplied) {
stdev = parse_floats (opt[0][0]);
}
opt = get_options ("fwhm");
if (opt.size()) {
if (stdev_supplied)
throw Exception ("The stdev and FWHM options are mutually exclusive.");
stdev = parse_floats (opt[0][0]);
for (size_t d = 0; d < stdev.size(); ++d)
stdev[d] = stdev[d] / 2.3548; //convert FWHM to stdev
}
opt = get_options ("stride");
std::vector<int> strides;
if (opt.size()) {
strides = opt[0][0];
if (strides.size() > header.ndim())
throw Exception ("too many axes supplied to -stride option");
}
if (do_anisotropic) {
Math::Matrix<float> directions;;
opt = get_options ("directions");
if (opt.size()) {
directions.load(opt[0][0]);
} else {
if (!header["directions"].size())
throw Exception ("no mask directions have been specified.");
std::vector<float> dir_vector;
std::vector<std::string > lines = split (header["directions"], "\n", true);
for (size_t l = 0; l < lines.size(); l++) {
std::vector<float> v (parse_floats(lines[l]));
dir_vector.insert (dir_vector.end(), v.begin(), v.end());
}
directions.resize(dir_vector.size() / 2, 2);
for (size_t i = 0; i < dir_vector.size(); i += 2) {
directions(i / 2, 0) = dir_vector[i];
directions(i / 2, 1) = dir_vector[i + 1];
}
}
Image::Filter::AnisotropicSmooth smooth_filter (input_vox, stdev, directions);
header.info() = smooth_filter.info();
if (strides.size()) {
for (size_t n = 0; n < strides.size(); ++n)
header.stride(n) = strides[n];
}
Image::Buffer<float> output_data (argument[1], header);
Image::Buffer<float>::voxel_type output_vox (output_data);
smooth_filter (input_vox, output_vox);
} else {
Image::Filter::GaussianSmooth<> smooth_filter (input_vox, stdev);
opt = get_options ("extent");
if (opt.size())
smooth_filter.set_extent(parse_ints (opt[0][0]));
header.info() = smooth_filter.info();
if (strides.size()) {
for (size_t n = 0; n < strides.size(); ++n)
header.stride(n) = strides[n];
}
Image::Buffer<float> output_data (argument[1], header);
Image::Buffer<float>::voxel_type output_vox (output_data);
smooth_filter (input_vox, output_vox);
}
}
<commit_msg>removed -anisotropic (directional smoothing) option from mrsmooth<commit_after>/*
Copyright 2012 Brain Research Institute, Melbourne, Australia
Written by David Raffelt, 17/02/2012.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/filter/gaussian_smooth.h"
#include "progressbar.h"
using namespace MR;
using namespace App;
void usage ()
{
DESCRIPTION
+ "smooth n-dimensional images by a convolution with a Gaussian kernel. "
+ "Note that if the input volume is 4D, then by default each 3D volume is smoothed independently. However "
"this behaviour can be overridden by manually setting the stdev for all dimensions.";
ARGUMENTS
+ Argument ("input", "input image to be smoothed.").type_image_in ()
+ Argument ("output", "the output image.").type_image_out ();
OPTIONS
+ Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
"The standard deviation is defined in mm (Default 1 voxel). "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the stdev for each axis.")
+ Argument ("mm").type_sequence_float()
+ Option ("fwhm", "apply Gaussian smoothing with the specified full-width half maximum. "
"The FWHM is defined in mm (Default 1 voxel * 2.3548). "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the FWHM for each axis.")
+ Argument ("mm").type_sequence_float()
+ Option ("extent", "specify the extent (width) of kernel size in voxels. "
"This can be specified either as a single value to be used for all axes, "
"or as a comma-separated list of the extent for each axis. "
"The default extent is 2 * ceil(2.5 * stdev / voxel_size) - 1.")
+ Argument ("voxels").type_sequence_int()
+ Image::Stride::StrideOption;
}
void run () {
Image::Header header (argument[0]);
Image::BufferPreload<float> input_data (header);
Image::BufferPreload<float>::voxel_type input_vox (input_data);
std::vector<float> stdev;
stdev.resize(3);
for (size_t dim = 0; dim < 3; dim++)
stdev[dim] = input_data.vox (dim);
Options opt = get_options ("stdev");
int stdev_supplied = opt.size();
if (stdev_supplied) {
stdev = parse_floats (opt[0][0]);
}
opt = get_options ("fwhm");
if (opt.size()) {
if (stdev_supplied)
throw Exception ("The stdev and FWHM options are mutually exclusive.");
stdev = parse_floats (opt[0][0]);
for (size_t d = 0; d < stdev.size(); ++d)
stdev[d] = stdev[d] / 2.3548; //convert FWHM to stdev
}
opt = get_options ("stride");
std::vector<int> strides;
if (opt.size()) {
strides = opt[0][0];
if (strides.size() > header.ndim())
throw Exception ("too many axes supplied to -stride option");
}
Image::Filter::GaussianSmooth<> smooth_filter (input_vox, stdev);
opt = get_options ("extent");
if (opt.size())
smooth_filter.set_extent(parse_ints (opt[0][0]));
header.info() = smooth_filter.info();
if (strides.size()) {
for (size_t n = 0; n < strides.size(); ++n)
header.stride(n) = strides[n];
}
Image::Buffer<float> output_data (argument[1], header);
Image::Buffer<float>::voxel_type output_vox (output_data);
smooth_filter (input_vox, output_vox);
}
<|endoftext|> |
<commit_before>#include "update_dialog.hpp"
#include "info_dialog.hpp"
#include "../platform/settings.hpp"
#include "../base/assert.hpp"
#include "../std/bind.hpp"
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTreeWidget>
#include <QtGui/QHeaderView>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtCore/QDateTime>
#define CHECK_FOR_UPDATE "Check for update"
#define LAST_UPDATE_CHECK "Last update check: "
/// used in settings
#define LAST_CHECK_TIME_KEY "LastUpdateCheckTime"
using namespace storage;
enum
{
// KItemIndexFlag = 0,
KColumnIndexCountry,
KColumnIndexStatus,
KColumnIndexSize,
KNumberOfColumns
};
#define COLOR_NOTDOWNLOADED Qt::black
#define COLOR_ONDISK Qt::darkGreen
#define COLOR_INPROGRESS Qt::blue
#define COLOR_DOWNLOADFAILED Qt::red
#define COLOR_INQUEUE Qt::gray
namespace qt
{
///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////
/// adds custom sorting for "Size" column
class QTreeWidgetItemWithCustomSorting : public QTreeWidgetItem
{
public:
virtual bool operator<(QTreeWidgetItem const & other) const
{
return data(KColumnIndexSize, Qt::UserRole).toULongLong() < other.data(KColumnIndexSize, Qt::UserRole).toULongLong();
}
};
////////////////////////////////////////////////////////////////////////////////
UpdateDialog::UpdateDialog(QWidget * parent, Storage & storage)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), m_storage(storage)
{
setWindowModality(Qt::WindowModal);
QPushButton * closeButton = new QPushButton(QObject::tr("Close"), this);
closeButton->setDefault(true);
connect(closeButton, SIGNAL(clicked()), this, SLOT(OnCloseClick()));
m_tree = new QTreeWidget(this);
m_tree->setColumnCount(KNumberOfColumns);
QStringList columnLabels;
columnLabels << tr("Country") << tr("Status") << tr("Size");
m_tree->setHeaderLabels(columnLabels);
connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(OnItemClick(QTreeWidgetItem *, int)));
QHBoxLayout * horizontalLayout = new QHBoxLayout();
horizontalLayout->addStretch();
horizontalLayout->addWidget(closeButton);
QVBoxLayout * verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(m_tree);
verticalLayout->addLayout(horizontalLayout);
setLayout(verticalLayout);
setWindowTitle(tr("Geographical Regions"));
resize(600, 500);
// we want to receive all download progress and result events
m_storage.Subscribe(bind(&UpdateDialog::OnCountryChanged, this, _1),
bind(&UpdateDialog::OnCountryDownloadProgress, this, _1, _2));
}
UpdateDialog::~UpdateDialog()
{
// tell download manager that we're gone...
m_storage.Unsubscribe();
}
/// when user clicks on any map row in the table
void UpdateDialog::OnItemClick(QTreeWidgetItem * item, int /*column*/)
{
// calculate index of clicked item
QList<int> treeIndex;
{
QTreeWidgetItem * parent = item;
while (parent)
{
treeIndex.insert(0, parent->data(KColumnIndexCountry, Qt::UserRole).toInt());
parent = parent->parent();
}
while (treeIndex.size() < 3)
treeIndex.append(TIndex::INVALID);
}
TIndex const countryIndex(treeIndex[0], treeIndex[1], treeIndex[2]);
switch (m_storage.CountryStatus(countryIndex))
{
case EOnDisk:
{
// map is already downloaded, so ask user about deleting!
QMessageBox ask(this);
ask.setText(tr("Do you want to delete %1?").arg(item->text(KColumnIndexCountry)));
ask.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
ask.setDefaultButton(QMessageBox::No);
if (ask.exec() == QMessageBox::Yes)
m_storage.DeleteCountry(countryIndex);
}
break;
case ENotDownloaded:
case EDownloadFailed:
m_storage.DownloadCountry(countryIndex);
break;
case EInQueue:
case EDownloading:
m_storage.DeleteCountry(countryIndex);
break;
case EGeneratingIndex:
// we can't stop index genertion at this moment
break;
}
}
QTreeWidgetItem * MatchedItem(QTreeWidgetItem & parent, int index)
{
if (index >= 0)
{
for (int i = 0; i < parent.childCount(); ++i)
{
QTreeWidgetItem * item = parent.child(i);
if (index == item->data(KColumnIndexCountry, Qt::UserRole).toInt())
return item;
}
}
return NULL;
}
/// @return can be null if index is invalid
QTreeWidgetItem * GetTreeItemByIndex(QTreeWidget & tree, TIndex const & index)
{
QTreeWidgetItem * item = 0;
if (index.m_group >= 0)
{
for (int i = 0; i < tree.topLevelItemCount(); ++i)
{
QTreeWidgetItem * grItem = tree.topLevelItem(i);
if (index.m_group == grItem->data(KColumnIndexCountry, Qt::UserRole).toInt())
{
item = grItem;
break;
}
}
}
if (item && index.m_country >= 0)
{
item = MatchedItem(*item, index.m_country);
if (item && index.m_region >= 0)
item = MatchedItem(*item, index.m_region);
}
return item;
}
void UpdateDialog::OnCloseClick()
{
done(0);
}
/// Changes row's text color
void SetRowColor(QTreeWidgetItem & item, QColor const & color)
{
for (int column = 0; column < item.columnCount(); ++column)
item.setTextColor(column, color);
}
void UpdateDialog::UpdateRowWithCountryInfo(TIndex const & index)
{
QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
if (item)
{
QColor rowColor;
QString statusString;
LocalAndRemoteSizeT size(0, 0);
switch (m_storage.CountryStatus(index))
{
case ENotDownloaded:
statusString = tr("Click to download");
rowColor = COLOR_NOTDOWNLOADED;
size = m_storage.CountrySizeInBytes(index);
break;
case EOnDisk:
statusString = tr("Installed (click to delete)");
rowColor = COLOR_ONDISK;
size = m_storage.CountrySizeInBytes(index);
break;
case EDownloadFailed:
statusString = tr("Download has failed");
rowColor = COLOR_DOWNLOADFAILED;
size = m_storage.CountrySizeInBytes(index);
break;
case EDownloading:
statusString = tr("Downloading ...");
rowColor = COLOR_INPROGRESS;
break;
case EInQueue:
statusString = tr("Marked for download");
rowColor = COLOR_INQUEUE;
size = m_storage.CountrySizeInBytes(index);
break;
case EGeneratingIndex:
statusString = tr("Generatin search index ...");
rowColor = COLOR_INPROGRESS;
break;
}
if (statusString.size())
item->setText(KColumnIndexStatus, statusString);
if (size.second)
{
if (size.second > 1000 * 1000 * 1000)
item->setText(KColumnIndexSize, QString("%1/%2 GB").arg(
uint(size.first / (1000 * 1000 * 1000))).arg(uint(size.second / (1000 * 1000 * 1000))));
else if (size.second > 1000 * 1000)
item->setText(KColumnIndexSize, QString("%1/%2 MB").arg(
uint(size.first / (1000 * 1000))).arg(uint(size.second / (1000 * 1000))));
else
item->setText(KColumnIndexSize, QString("%1/%2 kB").arg(
uint((size.first + 999) / 1000)).arg(uint((size.second + 999) / 1000)));
// needed for column sorting
item->setData(KColumnIndexSize, Qt::UserRole, QVariant(qint64(size.second)));
}
if (statusString.size())
SetRowColor(*item, rowColor);
}
}
void UpdateDialog::FillTree()
{
m_tree->setSortingEnabled(false);
m_tree->clear();
for (int group = 0; group < static_cast<int>(m_storage.CountriesCount(TIndex())); ++group)
{
TIndex const grIndex(group);
QStringList groupText(QString::fromUtf8(m_storage.CountryName(grIndex).c_str()));
QTreeWidgetItem * groupItem = new QTreeWidgetItem(groupText);
groupItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(group));
m_tree->addTopLevelItem(groupItem);
// set color by status and update country size
UpdateRowWithCountryInfo(grIndex);
for (int country = 0; country < static_cast<int>(m_storage.CountriesCount(grIndex)); ++country)
{
TIndex cIndex(group, country);
QStringList countryText(QString::fromUtf8(m_storage.CountryName(cIndex).c_str()));
QTreeWidgetItem * countryItem = new QTreeWidgetItem(groupItem, countryText);
countryItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(country));
// set color by status and update country size
UpdateRowWithCountryInfo(cIndex);
for (int region = 0; region < static_cast<int>(m_storage.CountriesCount(cIndex)); ++region)
{
TIndex const rIndex(group, country, region);
QStringList regionText(QString::fromUtf8(m_storage.CountryName(rIndex).c_str()));
QTreeWidgetItem * regionItem = new QTreeWidgetItem(countryItem, regionText);
regionItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(region));
// set color by status and update country size
UpdateRowWithCountryInfo(rIndex);
}
}
}
// // Size column, actual size will be set later
// QTableWidgetItemWithCustomSorting * sizeItem = new QTableWidgetItemWithCustomSorting;
// sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);
// m_table->setItem(row, KItemIndexSize, sizeItem);
m_tree->sortByColumn(KColumnIndexCountry, Qt::AscendingOrder);
m_tree->setSortingEnabled(true);
m_tree->header()->setResizeMode(KColumnIndexCountry, QHeaderView::ResizeToContents);
m_tree->header()->setResizeMode(KColumnIndexStatus, QHeaderView::ResizeToContents);
}
void UpdateDialog::OnCountryChanged(TIndex const & index)
{
UpdateRowWithCountryInfo(index);
}
void UpdateDialog::OnCountryDownloadProgress(TIndex const & index,
pair<int64_t, int64_t> const & progress)
{
QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
if (item)
{
// QString speed;
// if (progress.m_bytesPerSec > 1000 * 1000)
// speed = QString(" %1 MB/s").arg(QString::number(static_cast<double>(progress.m_bytesPerSec) / (1000.0 * 1000.0),
// 'f', 1));
// else if (progress.m_bytesPerSec > 1000)
// speed = QString(" %1 kB/s").arg(progress.m_bytesPerSec / 1000);
// else if (progress.m_bytesPerSec >= 0)
// speed = QString(" %1 B/sec").arg(progress.m_bytesPerSec);
item->setText(KColumnIndexSize, QString("%1%").arg(progress.first * 100 / progress.second));
// item->setText(KColumnIndexSize, QString("%1%%2").arg(progress.m_current * 100 / progress.m_total)
// .arg(speed));
}
}
void UpdateDialog::ShowDialog()
{
// if called for first time
if (!m_tree->topLevelItemCount())
FillTree();
exec();
}
}
<commit_msg>Spelling fix.<commit_after>#include "update_dialog.hpp"
#include "info_dialog.hpp"
#include "../platform/settings.hpp"
#include "../base/assert.hpp"
#include "../std/bind.hpp"
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTreeWidget>
#include <QtGui/QHeaderView>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtCore/QDateTime>
#define CHECK_FOR_UPDATE "Check for update"
#define LAST_UPDATE_CHECK "Last update check: "
/// used in settings
#define LAST_CHECK_TIME_KEY "LastUpdateCheckTime"
using namespace storage;
enum
{
// KItemIndexFlag = 0,
KColumnIndexCountry,
KColumnIndexStatus,
KColumnIndexSize,
KNumberOfColumns
};
#define COLOR_NOTDOWNLOADED Qt::black
#define COLOR_ONDISK Qt::darkGreen
#define COLOR_INPROGRESS Qt::blue
#define COLOR_DOWNLOADFAILED Qt::red
#define COLOR_INQUEUE Qt::gray
namespace qt
{
///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////
/// adds custom sorting for "Size" column
class QTreeWidgetItemWithCustomSorting : public QTreeWidgetItem
{
public:
virtual bool operator<(QTreeWidgetItem const & other) const
{
return data(KColumnIndexSize, Qt::UserRole).toULongLong() < other.data(KColumnIndexSize, Qt::UserRole).toULongLong();
}
};
////////////////////////////////////////////////////////////////////////////////
UpdateDialog::UpdateDialog(QWidget * parent, Storage & storage)
: QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), m_storage(storage)
{
setWindowModality(Qt::WindowModal);
QPushButton * closeButton = new QPushButton(QObject::tr("Close"), this);
closeButton->setDefault(true);
connect(closeButton, SIGNAL(clicked()), this, SLOT(OnCloseClick()));
m_tree = new QTreeWidget(this);
m_tree->setColumnCount(KNumberOfColumns);
QStringList columnLabels;
columnLabels << tr("Country") << tr("Status") << tr("Size");
m_tree->setHeaderLabels(columnLabels);
connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(OnItemClick(QTreeWidgetItem *, int)));
QHBoxLayout * horizontalLayout = new QHBoxLayout();
horizontalLayout->addStretch();
horizontalLayout->addWidget(closeButton);
QVBoxLayout * verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(m_tree);
verticalLayout->addLayout(horizontalLayout);
setLayout(verticalLayout);
setWindowTitle(tr("Geographical Regions"));
resize(600, 500);
// we want to receive all download progress and result events
m_storage.Subscribe(bind(&UpdateDialog::OnCountryChanged, this, _1),
bind(&UpdateDialog::OnCountryDownloadProgress, this, _1, _2));
}
UpdateDialog::~UpdateDialog()
{
// tell download manager that we're gone...
m_storage.Unsubscribe();
}
/// when user clicks on any map row in the table
void UpdateDialog::OnItemClick(QTreeWidgetItem * item, int /*column*/)
{
// calculate index of clicked item
QList<int> treeIndex;
{
QTreeWidgetItem * parent = item;
while (parent)
{
treeIndex.insert(0, parent->data(KColumnIndexCountry, Qt::UserRole).toInt());
parent = parent->parent();
}
while (treeIndex.size() < 3)
treeIndex.append(TIndex::INVALID);
}
TIndex const countryIndex(treeIndex[0], treeIndex[1], treeIndex[2]);
switch (m_storage.CountryStatus(countryIndex))
{
case EOnDisk:
{
// map is already downloaded, so ask user about deleting!
QMessageBox ask(this);
ask.setText(tr("Do you want to delete %1?").arg(item->text(KColumnIndexCountry)));
ask.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
ask.setDefaultButton(QMessageBox::No);
if (ask.exec() == QMessageBox::Yes)
m_storage.DeleteCountry(countryIndex);
}
break;
case ENotDownloaded:
case EDownloadFailed:
m_storage.DownloadCountry(countryIndex);
break;
case EInQueue:
case EDownloading:
m_storage.DeleteCountry(countryIndex);
break;
case EGeneratingIndex:
// we can't stop index genertion at this moment
break;
}
}
QTreeWidgetItem * MatchedItem(QTreeWidgetItem & parent, int index)
{
if (index >= 0)
{
for (int i = 0; i < parent.childCount(); ++i)
{
QTreeWidgetItem * item = parent.child(i);
if (index == item->data(KColumnIndexCountry, Qt::UserRole).toInt())
return item;
}
}
return NULL;
}
/// @return can be null if index is invalid
QTreeWidgetItem * GetTreeItemByIndex(QTreeWidget & tree, TIndex const & index)
{
QTreeWidgetItem * item = 0;
if (index.m_group >= 0)
{
for (int i = 0; i < tree.topLevelItemCount(); ++i)
{
QTreeWidgetItem * grItem = tree.topLevelItem(i);
if (index.m_group == grItem->data(KColumnIndexCountry, Qt::UserRole).toInt())
{
item = grItem;
break;
}
}
}
if (item && index.m_country >= 0)
{
item = MatchedItem(*item, index.m_country);
if (item && index.m_region >= 0)
item = MatchedItem(*item, index.m_region);
}
return item;
}
void UpdateDialog::OnCloseClick()
{
done(0);
}
/// Changes row's text color
void SetRowColor(QTreeWidgetItem & item, QColor const & color)
{
for (int column = 0; column < item.columnCount(); ++column)
item.setTextColor(column, color);
}
void UpdateDialog::UpdateRowWithCountryInfo(TIndex const & index)
{
QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
if (item)
{
QColor rowColor;
QString statusString;
LocalAndRemoteSizeT size(0, 0);
switch (m_storage.CountryStatus(index))
{
case ENotDownloaded:
statusString = tr("Click to download");
rowColor = COLOR_NOTDOWNLOADED;
size = m_storage.CountrySizeInBytes(index);
break;
case EOnDisk:
statusString = tr("Installed (click to delete)");
rowColor = COLOR_ONDISK;
size = m_storage.CountrySizeInBytes(index);
break;
case EDownloadFailed:
statusString = tr("Download has failed");
rowColor = COLOR_DOWNLOADFAILED;
size = m_storage.CountrySizeInBytes(index);
break;
case EDownloading:
statusString = tr("Downloading ...");
rowColor = COLOR_INPROGRESS;
break;
case EInQueue:
statusString = tr("Marked for download");
rowColor = COLOR_INQUEUE;
size = m_storage.CountrySizeInBytes(index);
break;
case EGeneratingIndex:
statusString = tr("Generating search index ...");
rowColor = COLOR_INPROGRESS;
break;
}
if (statusString.size())
item->setText(KColumnIndexStatus, statusString);
if (size.second)
{
if (size.second > 1000 * 1000 * 1000)
item->setText(KColumnIndexSize, QString("%1/%2 GB").arg(
uint(size.first / (1000 * 1000 * 1000))).arg(uint(size.second / (1000 * 1000 * 1000))));
else if (size.second > 1000 * 1000)
item->setText(KColumnIndexSize, QString("%1/%2 MB").arg(
uint(size.first / (1000 * 1000))).arg(uint(size.second / (1000 * 1000))));
else
item->setText(KColumnIndexSize, QString("%1/%2 kB").arg(
uint((size.first + 999) / 1000)).arg(uint((size.second + 999) / 1000)));
// needed for column sorting
item->setData(KColumnIndexSize, Qt::UserRole, QVariant(qint64(size.second)));
}
if (statusString.size())
SetRowColor(*item, rowColor);
}
}
void UpdateDialog::FillTree()
{
m_tree->setSortingEnabled(false);
m_tree->clear();
for (int group = 0; group < static_cast<int>(m_storage.CountriesCount(TIndex())); ++group)
{
TIndex const grIndex(group);
QStringList groupText(QString::fromUtf8(m_storage.CountryName(grIndex).c_str()));
QTreeWidgetItem * groupItem = new QTreeWidgetItem(groupText);
groupItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(group));
m_tree->addTopLevelItem(groupItem);
// set color by status and update country size
UpdateRowWithCountryInfo(grIndex);
for (int country = 0; country < static_cast<int>(m_storage.CountriesCount(grIndex)); ++country)
{
TIndex cIndex(group, country);
QStringList countryText(QString::fromUtf8(m_storage.CountryName(cIndex).c_str()));
QTreeWidgetItem * countryItem = new QTreeWidgetItem(groupItem, countryText);
countryItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(country));
// set color by status and update country size
UpdateRowWithCountryInfo(cIndex);
for (int region = 0; region < static_cast<int>(m_storage.CountriesCount(cIndex)); ++region)
{
TIndex const rIndex(group, country, region);
QStringList regionText(QString::fromUtf8(m_storage.CountryName(rIndex).c_str()));
QTreeWidgetItem * regionItem = new QTreeWidgetItem(countryItem, regionText);
regionItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(region));
// set color by status and update country size
UpdateRowWithCountryInfo(rIndex);
}
}
}
// // Size column, actual size will be set later
// QTableWidgetItemWithCustomSorting * sizeItem = new QTableWidgetItemWithCustomSorting;
// sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);
// m_table->setItem(row, KItemIndexSize, sizeItem);
m_tree->sortByColumn(KColumnIndexCountry, Qt::AscendingOrder);
m_tree->setSortingEnabled(true);
m_tree->header()->setResizeMode(KColumnIndexCountry, QHeaderView::ResizeToContents);
m_tree->header()->setResizeMode(KColumnIndexStatus, QHeaderView::ResizeToContents);
}
void UpdateDialog::OnCountryChanged(TIndex const & index)
{
UpdateRowWithCountryInfo(index);
}
void UpdateDialog::OnCountryDownloadProgress(TIndex const & index,
pair<int64_t, int64_t> const & progress)
{
QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
if (item)
{
// QString speed;
// if (progress.m_bytesPerSec > 1000 * 1000)
// speed = QString(" %1 MB/s").arg(QString::number(static_cast<double>(progress.m_bytesPerSec) / (1000.0 * 1000.0),
// 'f', 1));
// else if (progress.m_bytesPerSec > 1000)
// speed = QString(" %1 kB/s").arg(progress.m_bytesPerSec / 1000);
// else if (progress.m_bytesPerSec >= 0)
// speed = QString(" %1 B/sec").arg(progress.m_bytesPerSec);
item->setText(KColumnIndexSize, QString("%1%").arg(progress.first * 100 / progress.second));
// item->setText(KColumnIndexSize, QString("%1%%2").arg(progress.m_current * 100 / progress.m_total)
// .arg(speed));
}
}
void UpdateDialog::ShowDialog()
{
// if called for first time
if (!m_tree->topLevelItemCount())
FillTree();
exec();
}
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <os>
#include <memdisk>
#include <net/inet>
#include <net/interfaces>
#include "serial.hpp"
// transport streams used when testing
#include "../fuzz/fuzzy_stream.hpp"
static fuzzy::Stream* ossl_fuzz_ptr = nullptr;
static fuzzy::Stream* s2n_fuzz_ptr = nullptr;
inline fuzzy::Stream_ptr create_stream(fuzzy::Stream** dest)
{
return std::make_unique<fuzzy::Stream> (net::Socket{}, net::Socket{},
[dest] (net::Stream::buffer_t buffer) -> void {
(*dest)->give_payload(std::move(buffer));
}, true);
}
static void do_test_serializing_tls(int index);
static void do_test_send_data();
static void do_test_completed();
static bool are_all_streams_at_stage(int stage);
static bool are_all_streams_atleast_stage(int stage);
static void test_failure(const std::string& data) {
printf("Received unexpected data: %s\n", data.c_str());
printf("Length: %zu bytes\n", data.size());
std::abort();
}
static std::string long_string(32000, '-');
struct Testing
{
static const int NUM_STAGES = 7;
int index = 0;
int test_stage = 0;
s2n::TLS_stream* stream = nullptr;
std::string read_buffer = "";
void send_data()
{
this->stream->write("Hello!");
this->stream->write("Second write");
this->stream->write(long_string);
}
void onread_function(net::Stream::buffer_t buffer)
{
assert(this->stream != nullptr && stream->is_connected());
read_buffer += std::string(buffer->begin(), buffer->end());
if (read_buffer == "Hello!") this->test_stage_advance();
else if (read_buffer == "Second write") this->test_stage_advance();
else if (read_buffer == long_string) this->test_stage_advance();
// else: ... wait for more data
}
void connect_function(net::Stream& stream)
{
this->test_stage_advance();
printf("TLS stream connected (%d / 2)\n", test_stage);
this->send_data();
}
void test_stage_advance()
{
this->test_stage ++;
this->read_buffer.clear();
printf("[%d] Test stage: %d / %d\n",
this->index, this->test_stage, NUM_STAGES);
if (are_all_streams_atleast_stage(1))
{
// serialize and deserialize TLS after connected
do_test_serializing_tls(this->index);
}
if (are_all_streams_at_stage(4))
{
printf("Now resending test data\n");
// perform some writes at stage 4
do_test_send_data();
}
if (are_all_streams_atleast_stage(1))
{
// serialize and deserialize TLS again
do_test_serializing_tls(this->index);
}
if (are_all_streams_at_stage(NUM_STAGES)) {
do_test_completed();
}
}
void setup_callbacks()
{
stream->on_connect({this, &Testing::connect_function});
stream->on_read(8192, {this, &Testing::onread_function});
}
};
static struct Testing server_test;
static struct Testing client_test;
bool are_all_streams_at_stage(int stage)
{
return server_test.test_stage == stage &&
client_test.test_stage == stage;
}
bool are_all_streams_atleast_stage(int stage)
{
return server_test.test_stage >= stage &&
client_test.test_stage >= stage;
}
void do_test_serializing_tls(int index)
{
char sbuffer[64*1024]; // 64KB server buffer
char cbuffer[64*1024]; // 64KB client buffer
printf("Now serializing TLS state\n");
// 1. serialize TLS, destroy streams
const size_t sbytes =
server_test.stream->serialize_to(sbuffer, sizeof(sbuffer));
assert(sbytes > 0 && "Its only failed if it returned zero");
//printf("Server channel used %zu bytes\n", sbytes);
const size_t cbytes =
client_test.stream->serialize_to(cbuffer, sizeof(cbuffer));
assert(cbytes > 0 && "Its only failed if it returned zero");
//printf("Client channel used %zu bytes\n", cbytes);
// 2. deserialize TLS, create new streams
printf("Now deserializing TLS state\n");
// 2.1: create new transport streams
auto server_side = create_stream(&ossl_fuzz_ptr);
s2n_fuzz_ptr = server_side.get();
auto client_side = create_stream(&s2n_fuzz_ptr);
ossl_fuzz_ptr = client_side.get();
// 2.2: deserialize TLS config/context
auto* config = s2n::serial_get_config();
// 2.3: deserialize TLS streams
// 2.3.1:
auto dstream = s2n::TLS_stream::deserialize_from(
config,
std::move(server_side),
false,
sbuffer, sbytes
);
assert(dstream != nullptr && "Deserialization must return stream");
server_test.stream = dstream.release();
dstream = s2n::TLS_stream::deserialize_from(
config,
std::move(client_side),
false,
cbuffer, cbytes
);
assert(dstream != nullptr && "Deserialization must return stream");
client_test.stream = dstream.release();
// 3. set all delegates again
server_test.setup_callbacks();
client_test.setup_callbacks();
}
void do_test_send_data()
{
server_test.send_data();
client_test.send_data();
}
void do_test_completed()
{
printf("SUCCESS\n");
s2n::serial_test_over();
OS::shutdown();
}
void Service::start()
{
fs::memdisk().init_fs(
[] (fs::error_t err, fs::File_system&) {
assert(!err);
});
auto& filesys = fs::memdisk().fs();
auto ca_cert = filesys.read_file("/test.pem");
assert(ca_cert.is_valid());
auto ca_key = filesys.read_file("/test.key");
assert(ca_key.is_valid());
auto srv_key = filesys.read_file("/server.key");
assert(srv_key.is_valid());
printf("*** Loaded certificates and keys\n");
// initialize S2N
s2n::serial_test(ca_cert.to_string(), ca_key.to_string());
// server fuzzy stream
auto server_side = create_stream(&ossl_fuzz_ptr);
s2n_fuzz_ptr = server_side.get();
// client fuzzy stream
auto client_side = create_stream(&s2n_fuzz_ptr);
ossl_fuzz_ptr = client_side.get();
server_test.index = 0;
server_test.stream =
new s2n::TLS_stream(s2n::serial_get_config(), std::move(server_side), false);
client_test.index = 1;
client_test.stream =
new s2n::TLS_stream(s2n::serial_get_config(), std::move(client_side), true);
server_test.setup_callbacks();
client_test.setup_callbacks();
}
<commit_msg>s2n: Do more serialization passes early on<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <os>
#include <memdisk>
#include <net/inet>
#include <net/interfaces>
#include "serial.hpp"
// transport streams used when testing
#include "../fuzz/fuzzy_stream.hpp"
static fuzzy::Stream* ossl_fuzz_ptr = nullptr;
static fuzzy::Stream* s2n_fuzz_ptr = nullptr;
inline fuzzy::Stream_ptr create_stream(fuzzy::Stream** dest)
{
return std::make_unique<fuzzy::Stream> (net::Socket{}, net::Socket{},
[dest] (net::Stream::buffer_t buffer) -> void {
(*dest)->give_payload(std::move(buffer));
}, true);
}
static void do_test_serializing_tls(int index);
static void do_test_send_data();
static void do_test_completed();
static bool are_all_streams_at_stage(int stage);
static bool are_all_streams_atleast_stage(int stage);
static void test_failure(const std::string& data) {
printf("Received unexpected data: %s\n", data.c_str());
printf("Length: %zu bytes\n", data.size());
std::abort();
}
static std::string long_string(32000, '-');
struct Testing
{
static const int NUM_STAGES = 7;
int index = 0;
int test_stage = 0;
s2n::TLS_stream* stream = nullptr;
std::string read_buffer = "";
void send_data()
{
this->stream->write("Hello!");
this->stream->write("Second write");
this->stream->write(long_string);
}
void onread_function(net::Stream::buffer_t buffer)
{
assert(this->stream != nullptr && stream->is_connected());
read_buffer += std::string(buffer->begin(), buffer->end());
if (read_buffer == "Hello!") this->test_stage_advance();
else if (read_buffer == "Second write") this->test_stage_advance();
else if (read_buffer == long_string) this->test_stage_advance();
// else: ... wait for more data
}
void connect_function(net::Stream& stream)
{
this->test_stage_advance();
printf("TLS stream connected (%d / 2)\n", test_stage);
this->send_data();
}
void test_stage_advance()
{
this->test_stage ++;
this->read_buffer.clear();
printf("[%d] Test stage: %d / %d\n",
this->index, this->test_stage, NUM_STAGES);
// serialize and deserialize TLS after connected
do_test_serializing_tls(this->index);
if (are_all_streams_at_stage(4))
{
printf("Now resending test data\n");
// perform some writes at stage 4
do_test_send_data();
}
// serialize and deserialize TLS again
do_test_serializing_tls(this->index);
if (are_all_streams_at_stage(NUM_STAGES)) {
do_test_completed();
}
}
void setup_callbacks()
{
stream->on_connect({this, &Testing::connect_function});
stream->on_read(8192, {this, &Testing::onread_function});
}
};
static struct Testing server_test;
static struct Testing client_test;
bool are_all_streams_at_stage(int stage)
{
return server_test.test_stage == stage &&
client_test.test_stage == stage;
}
bool are_all_streams_atleast_stage(int stage)
{
return server_test.test_stage >= stage &&
client_test.test_stage >= stage;
}
void do_test_serializing_tls(int index)
{
char sbuffer[128*1024]; // server buffer
char cbuffer[128*1024]; // client buffer
printf(">>> Performing serialization / deserialization\n");
// 1. serialize TLS, destroy streams
const size_t sbytes =
server_test.stream->serialize_to(sbuffer, sizeof(sbuffer));
assert(sbytes > 0 && "Its only failed if it returned zero");
const size_t cbytes =
client_test.stream->serialize_to(cbuffer, sizeof(cbuffer));
assert(cbytes > 0 && "Its only failed if it returned zero");
// 2. deserialize TLS, create new streams
//printf("Now deserializing TLS state\n");
// 2.1: create new transport streams
auto server_side = create_stream(&ossl_fuzz_ptr);
s2n_fuzz_ptr = server_side.get();
auto client_side = create_stream(&s2n_fuzz_ptr);
ossl_fuzz_ptr = client_side.get();
// 2.2: deserialize TLS config/context
auto* config = s2n::serial_get_config();
// 2.3: deserialize TLS streams
// 2.3.1:
auto dstream = s2n::TLS_stream::deserialize_from(
config,
std::move(server_side),
false,
sbuffer, sbytes
);
assert(dstream != nullptr && "Deserialization must return stream");
server_test.stream = dstream.release();
dstream = s2n::TLS_stream::deserialize_from(
config,
std::move(client_side),
false,
cbuffer, cbytes
);
assert(dstream != nullptr && "Deserialization must return stream");
client_test.stream = dstream.release();
// 3. set all delegates again
server_test.setup_callbacks();
client_test.setup_callbacks();
}
void do_test_send_data()
{
server_test.send_data();
client_test.send_data();
}
void do_test_completed()
{
printf("SUCCESS\n");
s2n::serial_test_over();
OS::shutdown();
}
void Service::start()
{
fs::memdisk().init_fs(
[] (fs::error_t err, fs::File_system&) {
assert(!err);
});
auto& filesys = fs::memdisk().fs();
auto ca_cert = filesys.read_file("/test.pem");
assert(ca_cert.is_valid());
auto ca_key = filesys.read_file("/test.key");
assert(ca_key.is_valid());
auto srv_key = filesys.read_file("/server.key");
assert(srv_key.is_valid());
printf("*** Loaded certificates and keys\n");
// initialize S2N
s2n::serial_test(ca_cert.to_string(), ca_key.to_string());
// server fuzzy stream
auto server_side = create_stream(&ossl_fuzz_ptr);
s2n_fuzz_ptr = server_side.get();
// client fuzzy stream
auto client_side = create_stream(&s2n_fuzz_ptr);
ossl_fuzz_ptr = client_side.get();
server_test.index = 0;
server_test.stream =
new s2n::TLS_stream(s2n::serial_get_config(), std::move(server_side), false);
client_test.index = 1;
client_test.stream =
new s2n::TLS_stream(s2n::serial_get_config(), std::move(client_side), true);
server_test.setup_callbacks();
client_test.setup_callbacks();
printf("* TLS streams created!\n");
// try serializing and deserializing just after creation
do_test_serializing_tls(0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "webkit/dom_storage/dom_storage_area.h"
namespace {
// The tests server is started separately for each test function (including PRE_
// functions). We need a test server which always uses the same port, so that
// the pages can be accessed with the same URLs after restoring the browser
// session.
class FixedPortTestServer : public net::LocalTestServer {
public:
explicit FixedPortTestServer(uint16 port)
: LocalTestServer(
net::TestServer::TYPE_HTTP,
net::TestServer::kLocalhost,
FilePath().AppendASCII("chrome/test/data")) {
BaseTestServer::SetPort(port);
}
private:
DISALLOW_COPY_AND_ASSIGN(FixedPortTestServer);
};
} // namespace
class BetterSessionRestoreTest : public InProcessBrowserTest {
public:
BetterSessionRestoreTest()
: test_server_(8001),
title_pass_(ASCIIToUTF16("PASS")),
title_storing_(ASCIIToUTF16("STORING")),
title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")) {
CHECK(test_server_.Start());
}
protected:
void StoreDataWithPage(const std::string& filename) {
GURL url = test_server_.GetURL("files/session_restore/" + filename);
content::WebContents* web_contents =
chrome::GetActiveWebContents(browser());
content::TitleWatcher title_watcher(web_contents, title_storing_);
title_watcher.AlsoWaitForTitle(title_pass_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
ui_test_utils::NavigateToURL(browser(), url);
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_storing_, final_title);
}
void CheckReloadedPage() {
content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
content::TitleWatcher title_watcher(web_contents, title_pass_);
title_watcher.AlsoWaitForTitle(title_storing_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
// It's possible that the title was already the right one before
// title_watcher was created.
if (web_contents->GetTitle() != title_pass_) {
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_pass_, final_title);
}
}
private:
FixedPortTestServer test_server_;
string16 title_pass_;
string16 title_storing_;
string16 title_error_write_failed_;
string16 title_error_empty_;
DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};
// BetterSessionRestoreTest tests fail under AddressSanitizer, see
// http://crbug.com/156444.
#if defined(ADDRESS_SANITIZER)
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#else
// SessionCookies and SessionStorage are failing consistently on webkit canary
// builders. http://crbug.com/156444.
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#endif
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionCookies) {
// Set the startup preference to "continue where I left off" and visit a page
// which stores a session cookie.
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_cookies.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionCookies) {
// The browsing session will be continued; just wait for the page to reload
// and check the stored data.
CheckReloadedPage();
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionStorage) {
// Write the data on disk less lazily.
dom_storage::DomStorageArea::DisableCommitDelayForTesting();
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_storage.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionStorage) {
CheckReloadedPage();
}
<commit_msg>Better session restore test fix: Don't use a test server with a fixed port.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_test_job.h"
#include "webkit/dom_storage/dom_storage_area.h"
namespace {
// We need to serve the test files so that PRE_Test and Test can access the same
// page using the same URL. In addition, perceived security origin of the page
// needs to stay the same, so e.g., redirecting the URL requests doesn't
// work. (If we used a test server, the PRE_Test and Test would have separate
// instances running on separate ports.)
static base::LazyInstance<std::map<std::string, std::string> > file_contents =
LAZY_INSTANCE_INITIALIZER;
net::URLRequestJob* URLRequestFaker(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const std::string& scheme) {
return new net::URLRequestTestJob(
request, network_delegate, net::URLRequestTestJob::test_headers(),
file_contents.Get()[request->url().path()], true);
}
} // namespace
class BetterSessionRestoreTest : public InProcessBrowserTest {
public:
BetterSessionRestoreTest()
: title_pass_(ASCIIToUTF16("PASS")),
title_storing_(ASCIIToUTF16("STORING")),
title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")),
fake_server_address_("http://www.test.com/"),
test_path_("session_restore/") {
// Set up the URL request filtering.
std::vector<std::string> test_files;
test_files.push_back("common.js");
test_files.push_back("session_cookies.html");
test_files.push_back("session_storage.html");
FilePath test_file_dir;
CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &test_file_dir));
test_file_dir =
test_file_dir.AppendASCII("chrome/test/data").AppendASCII(test_path_);
for (std::vector<std::string>::const_iterator it = test_files.begin();
it != test_files.end(); ++it) {
FilePath path = test_file_dir.AppendASCII(*it);
std::string contents;
CHECK(file_util::ReadFileToString(path, &contents));
file_contents.Get()["/" + test_path_ + *it] = contents;
net::URLRequestFilter::GetInstance()->AddUrlHandler(
GURL(fake_server_address_ + test_path_ + *it),
&URLRequestFaker);
}
}
protected:
void StoreDataWithPage(const std::string& filename) {
content::WebContents* web_contents =
chrome::GetActiveWebContents(browser());
content::TitleWatcher title_watcher(web_contents, title_storing_);
title_watcher.AlsoWaitForTitle(title_pass_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
ui_test_utils::NavigateToURL(
browser(), GURL(fake_server_address_ + test_path_ + filename));
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_storing_, final_title);
}
void CheckReloadedPage() {
content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
content::TitleWatcher title_watcher(web_contents, title_pass_);
title_watcher.AlsoWaitForTitle(title_storing_);
title_watcher.AlsoWaitForTitle(title_error_write_failed_);
title_watcher.AlsoWaitForTitle(title_error_empty_);
// It's possible that the title was already the right one before
// title_watcher was created.
if (web_contents->GetTitle() != title_pass_) {
string16 final_title = title_watcher.WaitAndGetTitle();
EXPECT_EQ(title_pass_, final_title);
}
}
private:
string16 title_pass_;
string16 title_storing_;
string16 title_error_write_failed_;
string16 title_error_empty_;
std::string fake_server_address_;
std::string test_path_;
DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};
// BetterSessionRestoreTest tests fail under AddressSanitizer, see
// http://crbug.com/156444.
#if defined(ADDRESS_SANITIZER)
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#else
# define MAYBE_PRE_SessionCookies PRE_SessionCookies
# define MAYBE_SessionCookies SessionCookies
# define MAYBE_PRE_SessionStorage PRE_SessionStorage
# define MAYBE_SessionStorage SessionStorage
#endif
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionCookies) {
// Set the startup preference to "continue where I left off" and visit a page
// which stores a session cookie.
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_cookies.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionCookies) {
// The browsing session will be continued; just wait for the page to reload
// and check the stored data.
CheckReloadedPage();
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionStorage) {
// Write the data on disk less lazily.
dom_storage::DomStorageArea::DisableCommitDelayForTesting();
SessionStartupPref::SetStartupPref(
browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
StoreDataWithPage("session_storage.html");
}
// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionStorage) {
CheckReloadedPage();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
#include "base/debug/dump_without_crashing.h"
#include "base/rand_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_version_info.h"
namespace browser_sync {
void ChromeReportUnrecoverableError() {
// Only upload on canary/dev builds to avoid overwhelming crash server.
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
channel != chrome::VersionInfo::CHANNEL_DEV) {
return;
}
// We only want to upload |kErrorUploadRatio| ratio of errors.
const double kErrorUploadRatio = 0.15;
if (kErrorUploadRatio <= 0.0)
return; // We are not allowed to upload errors.
double random_number = base::RandDouble();
if (random_number > kErrorUploadRatio)
return;
base::debug::DumpWithoutCrashing();
}
} // namespace browser_sync
<commit_msg>[Sync] Disable unrecoverable error uploading<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
#include "base/debug/dump_without_crashing.h"
#include "base/rand_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_version_info.h"
namespace browser_sync {
void ChromeReportUnrecoverableError() {
// Only upload on canary/dev builds to avoid overwhelming crash server.
chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
channel != chrome::VersionInfo::CHANNEL_DEV) {
return;
}
// We only want to upload |kErrorUploadRatio| ratio of errors.
const double kErrorUploadRatio = 0.0;
if (kErrorUploadRatio <= 0.0)
return; // We are not allowed to upload errors.
double random_number = base::RandDouble();
if (random_number > kErrorUploadRatio)
return;
base::debug::DumpWithoutCrashing();
}
} // namespace browser_sync
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
int kInputPasswordMinWidth = 8;
namespace browser {
// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
const std::string& slot_name,
browser::CryptoModulePasswordReason reason,
const std::string& server,
const base::Callback<void(const char*)>& callback)
: callback_(callback) {
Init(server, slot_name, reason);
}
CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}
void CryptoModulePasswordDialogView::Init(
const std::string& server,
const std::string& slot_name,
browser::CryptoModulePasswordReason reason) {
// Select an appropriate text for the reason.
std::string text;
const string16& server16 = UTF8ToUTF16(server);
const string16& slot16 = UTF8ToUTF16(slot_name);
switch (reason) {
case browser::kCryptoModulePasswordKeygen:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
break;
case browser::kCryptoModulePasswordCertEnrollment:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
break;
case browser::kCryptoModulePasswordClientAuth:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
break;
case browser::kCryptoModulePasswordListCerts:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
break;
case browser::kCryptoModulePasswordCertImport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
break;
case browser::kCryptoModulePasswordCertExport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
break;
default:
NOTREACHED();
}
reason_label_ = new views::Label(UTF8ToUTF16(text));
reason_label_->SetMultiLine(true);
password_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));
password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
password_entry_->SetController(this);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
reason_column_set->AddColumn(
views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
views::GridLayout::USE_PREF, 0, 0);
views::ColumnSet* column_set = layout->AddColumnSet(1);
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(
0, views::kUnrelatedControlLargeHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 0);
layout->AddView(reason_label_);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
layout->StartRow(0, 1);
layout->AddView(password_label_);
layout->AddView(password_entry_);
}
views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
return this;
}
string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
ui::DialogButton button) const {
if (button == ui::DIALOG_BUTTON_OK)
return UTF8ToUTF16(l10n_util::GetStringUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL));
else if (button == ui::DIALOG_BUTTON_CANCEL)
return UTF8ToUTF16(l10n_util::GetStringUTF8(IDS_CANCEL));
const string16 empty;
return empty;
}
bool CryptoModulePasswordDialogView::Accept() {
callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::Cancel() {
callback_.Run(static_cast<const char*>(NULL));
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::HandleKeyEvent(
views::Textfield* sender,
const views::KeyEvent& keystroke) {
return false;
}
void CryptoModulePasswordDialogView::ContentsChanged(
views::Textfield* sender,
const string16& new_contents) {
}
string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
return UTF8ToUTF16(l10n_util::GetStringUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE));
}
void ShowCryptoModulePasswordDialog(
const std::string& slot_name,
bool retry,
CryptoModulePasswordReason reason,
const std::string& server,
const CryptoModulePasswordCallback& callback) {
CryptoModulePasswordDialogView* dialog =
new CryptoModulePasswordDialogView(
slot_name, reason, server, callback);
views::Widget::CreateWindowWithParent(dialog, NULL)->Show();
}
} // namespace browser
<commit_msg>views: Avoid conversions from UTF8 to UTF16 in CryptoModulePasswordDialogView.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"
int kInputPasswordMinWidth = 8;
namespace browser {
// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
const std::string& slot_name,
browser::CryptoModulePasswordReason reason,
const std::string& server,
const base::Callback<void(const char*)>& callback)
: callback_(callback) {
Init(server, slot_name, reason);
}
CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}
void CryptoModulePasswordDialogView::Init(
const std::string& server,
const std::string& slot_name,
browser::CryptoModulePasswordReason reason) {
// Select an appropriate text for the reason.
std::string text;
const string16& server16 = UTF8ToUTF16(server);
const string16& slot16 = UTF8ToUTF16(slot_name);
switch (reason) {
case browser::kCryptoModulePasswordKeygen:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
break;
case browser::kCryptoModulePasswordCertEnrollment:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
break;
case browser::kCryptoModulePasswordClientAuth:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
break;
case browser::kCryptoModulePasswordListCerts:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
break;
case browser::kCryptoModulePasswordCertImport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
break;
case browser::kCryptoModulePasswordCertExport:
text = l10n_util::GetStringFUTF8(
IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
break;
default:
NOTREACHED();
}
reason_label_ = new views::Label(UTF8ToUTF16(text));
reason_label_->SetMultiLine(true);
password_label_ = new views::Label(l10n_util::GetStringUTF16(
IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));
password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
password_entry_->SetController(this);
views::GridLayout* layout = views::GridLayout::CreatePanel(this);
SetLayoutManager(layout);
views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
reason_column_set->AddColumn(
views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
views::GridLayout::USE_PREF, 0, 0);
views::ColumnSet* column_set = layout->AddColumnSet(1);
column_set->AddColumn(views::GridLayout::LEADING,
views::GridLayout::LEADING, 0,
views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(
0, views::kUnrelatedControlLargeHorizontalSpacing);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, 0);
layout->AddView(reason_label_);
layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);
layout->StartRow(0, 1);
layout->AddView(password_label_);
layout->AddView(password_entry_);
}
views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
return this;
}
string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
ui::DialogButton button) const {
return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL);
}
bool CryptoModulePasswordDialogView::Accept() {
callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::Cancel() {
callback_.Run(static_cast<const char*>(NULL));
const string16 empty;
password_entry_->SetText(empty);
return true;
}
bool CryptoModulePasswordDialogView::HandleKeyEvent(
views::Textfield* sender,
const views::KeyEvent& keystroke) {
return false;
}
void CryptoModulePasswordDialogView::ContentsChanged(
views::Textfield* sender,
const string16& new_contents) {
}
string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE);
}
void ShowCryptoModulePasswordDialog(
const std::string& slot_name,
bool retry,
CryptoModulePasswordReason reason,
const std::string& server,
const CryptoModulePasswordCallback& callback) {
CryptoModulePasswordDialogView* dialog =
new CryptoModulePasswordDialogView(slot_name, reason, server, callback);
views::Widget::CreateWindowWithParent(dialog, NULL)->Show();
}
} // namespace browser
<|endoftext|> |
<commit_before>#include "math/Polygon.h"
#include "math/mathdef.h"
using fei::Polygon;
int fei::Polygon::getDataSize() const
{
return _data.size();
}
const float* Polygon::getDataPtr() const
{
if (!_data.empty()) {
return &_data[0].x;
}
return nullptr;
}
float Polygon::getArea() const
{
float area = 0.0f;
if (!isValid()) {
return area;
}
auto lastVec = getVertex(1) - getVertex(0);
for (int i = 2; i < static_cast<int>(_data.size()); i++) {
auto curVec = getVertex(i) - getVertex(0);
area += lastVec.cross(curVec);
lastVec = curVec;
}
area *= 0.5f;
return area;
}
bool Polygon::isCCW() const
{
return getArea() > 0.0f;
}
void Polygon::setVertices(int vertexNumber, float* dataPtr)
{
_data.resize(vertexNumber);
for (int i = 0; i < vertexNumber; i++) {
_data[i] = fei::Vec2(dataPtr[i << 1], dataPtr[i << 1 | 1]);
}
}
void Polygon::insertVertex(const fei::Vec2& p, int index)
{
//TODO: assertion
_data.insert(_data.begin() + index, p);
}
void Polygon::insertVertexOnClosestSegment(const Vec2& p)
{
int loc = closestWhichSegment(p);
loc = indexNormalize(loc + 1);
insertVertex(p, loc);
}
void Polygon::deleteVertex(int index)
{
//TODO: assertion
_data.erase(_data.begin() + index);
}
void Polygon::moveVertices(const fei::Vec2& v)
{
for (auto& vertex : _data) {
vertex.add(v);
}
}
void Polygon::reverseVertices()
{
std::reverse(_data.begin(), _data.end());
}
void Polygon::zoom(float f)
{
for (auto& vertex : _data) {
vertex.zoom(f);
}
}
const std::vector<Polygon> Polygon::cut(int index) const
{
std::vector<Polygon> result;
int best = getBestCutVertexIndex(index);
if (best != -1) {
result = cut(index, best);
} else {
int prev = indexNormalize(index - 1);
bool isConcave = isConcaveVertex(index);
auto leftVec = -getVector(prev);
auto rightVec = getVector(index);
auto middleVec = (leftVec.normalized() + rightVec.normalized()).normalized();
if (isConcave) {
middleVec *= -1.0f;
}
auto pl = collideRay(getVertex(index), middleVec);
if (!pl.empty()) {
Polygon polyCopy(*this);
int segIndex = polyCopy.closestWhichSegment(pl[0]);
int insertLoc = polyCopy.indexNormalize(segIndex + 1);
polyCopy.insertVertex(pl[0], insertLoc);
if (insertLoc <= index) {
index = polyCopy.indexNormalize(index + 1);
}
result = polyCopy.cut(index, insertLoc);
}
}
return result;
}
const std::vector<Polygon> Polygon::cut(int a, int b) const
{
int curVertex;
std::vector<Polygon> result;
Polygon tmpPoly = *this;
tmpPoly.clearVertex();
curVertex = b;
tmpPoly.pushVertex(getVertex(a));
do {
tmpPoly.pushVertex(getVertex(curVertex));
curVertex = indexNormalize(curVertex + 1);
} while(curVertex != a);
result.push_back(tmpPoly);
tmpPoly.clearVertex();
curVertex = a;
tmpPoly.pushVertex(getVertex(b));
do {
tmpPoly.pushVertex(getVertex(curVertex));
curVertex = indexNormalize(curVertex + 1);
} while(curVertex != b);
result.push_back(tmpPoly);
return result;
}
int Polygon::closestWhichSegment(const fei::Vec2& p) const
{
int ans = -1;
float minR = 1e32f;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto seg = getSegment(i);
float curRatio = std::abs(((p - seg.a).getLength() + (p - seg.b).getLength()) / seg.getLength() - 1.0f);
if (curRatio <= minR) {
minR = curRatio;
ans = i;
}
}
return ans;
}
int Polygon::onWhichSegment(const fei::Vec2& p) const
{
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
if (getSegment(i).collidePoint(p)) {
return i;
}
}
return -1;
}
int Polygon::collideVertex(const fei::Vec2& p, float radius) const
{
float rSq = radius * radius;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
if ((getVertex(i) - p).getLengthSq() <= rSq) {
return i;
}
}
return -1;
}
static bool cmpLength(const fei::Vec2& a, const fei::Vec2& b)
{
return a.getLengthSq() < b.getLengthSq();
}
const std::vector<fei::Vec2> Polygon::rawCollideRay(const fei::Vec2& src, const fei::Vec2& drct) const
{
std::vector<fei::Vec2> result;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto seg = getSegment(i);
fei::Vec2 tmp;
if (seg.collideRay(tmp, src, drct)) {
result.push_back(tmp - src);
}
}
return result;
}
const std::vector<fei::Vec2> Polygon::collideRay(const fei::Vec2& src, const fei::Vec2& drct) const
{
std::vector<fei::Vec2> result = rawCollideRay(src, drct);
std::vector<fei::Vec2> uniqueResult;
std::sort(result.begin(), result.end(), cmpLength);
for (int i = 0; i < static_cast<int>(result.size()); i++) {
if (result[i].getLengthSq() < 0.01f) continue;
if (i == 0 || result[i] != result[i - 1]) {
uniqueResult.push_back(result[i] + src);
}
}
return uniqueResult;
}
void Polygon::normalize()
{
std::vector<fei::Vec2> nData;
int sz = _data.size();
for (int i = 0; i < sz; i++) {
int prev = indexNormalize(i - 1);
if ((getVector(prev).getLengthSq() >= 0.01f)
&& (getVector(i).normalized() != getVector(prev).normalized())) {
nData.push_back(getVertex(i));
}
}
setDataVector(nData);
if (!isCCW()) {
reverseVertices();
}
}
const Polygon Polygon::normalized() const
{
Polygon poly(*this);
poly.normalize();
return poly;
}
bool Polygon::isConcaveVertex(int index) const
{
//TODO: assertion
int prevIndex = indexNormalize(index - 1);
auto prev = getVector(prevIndex);
auto cur = getVector(index);
float cp = prev.cross(cur);
return cp < 0;
}
int Polygon::getOneConcaveVertex() const
{
int sz = static_cast<int>(_data.size());
for (int i = 0; i < sz; i++) {
if (isConcaveVertex(i)) {
return i;
}
}
return -1;
}
typedef struct CutStruct
{
CutStruct(const Polygon* pp, int ii, int xx)
: poly(pp), index(ii), x(xx)
{
}
bool operator>(const CutStruct& rhs) const
{
int ai = x;
int bi = rhs.x;
int sz = poly->getDataSize();
bool aConcave = poly->isConcaveVertex(ai);
bool bConcave = poly->isConcaveVertex(bi);
if (aConcave == bConcave) {
int disIA = std::abs(index - ai);
if (sz - disIA < disIA) {
disIA = sz - disIA;
}
int disIB = std::abs(index - bi);
if (sz - disIB < disIB) {
disIB = sz - disIB;
}
return disIA > disIB;
} else {
return aConcave;
}
}
const Polygon* poly;
int index;
int x;
} PolyCutPair;
int Polygon::getBestCutVertexIndex(int index) const
{
int ans = -1;
auto iList = getVisibleVerticesIndex(index);
std::vector<PolyCutPair> uList;
if (isConcaveVertex(index)) {
auto left = getSegment(index);
auto right = getSegment(indexNormalize(index - 1));
right.swapAB();
left.b = left.a - left.getVector();
right.b = right.a - right.getVector();
for (int vertex : iList) {
auto p = getVertex(vertex);
if (left.onLeftOrRight(p) == 1
&& right.onLeftOrRight(p) == -1) {
auto pl = collideRay(getVertex(index), p - getVertex(index));
if (pl.size() == 0 || pl[0] == p) {
uList.push_back(PolyCutPair(this, index, vertex));
}
}
}
} else {
for (int vertex : iList) {
uList.push_back(PolyCutPair(this, index, vertex));
}
}
if (!uList.empty()) {
auto maxPcp = uList[0];
for (auto& pcp : uList) {
if (pcp > maxPcp) {
maxPcp = pcp;
}
}
ans = maxPcp.x;
}
return ans;
}
std::vector<int> Polygon::getVisibleVerticesIndex(int index) const
{
std::vector<int> result;
int left = indexNormalize(index - 1);
int right = indexNormalize(index + 1);
bool isConcave = isConcaveVertex(index);
auto leftSeg = getSegment(left);
auto rightSeg = getSegment(index);
leftSeg.swapAB();
if (isConcave) {
auto tmp = leftSeg;
leftSeg = rightSeg;
rightSeg = tmp;
}
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto p = getVertex(i);
if (i == index || i == left || i == right ||
(leftSeg.onLeftOrRight(p) == 1 && rightSeg.onLeftOrRight(p) == -1) == isConcave) {
continue;
}
auto vertexList = collideRay(getVertex(index), p - getVertex(index));
if (vertexList.size() == 0 || vertexList[0] == p) {
result.push_back(i);
}
}
return result;
}
bool Polygon::isConvex() const
{
return getOneConcaveVertex() < 0;
}
const std::vector<Polygon> Polygon::convexDecomposition() const
{
std::vector<Polygon> result;
std::queue<Polygon> processQueue;
processQueue.push(normalized());
while(!processQueue.empty()) {
auto currentPoly = processQueue.front();
processQueue.pop();
if (currentPoly.isValid()) {
int concavePoint = currentPoly.getOneConcaveVertex();
if (concavePoint == -1) {
result.push_back(currentPoly);
} else {
auto twoPoly = currentPoly.cut(concavePoint);
for (auto& poly : twoPoly) {
poly.normalize();
if (poly.isValid()) {
processQueue.push(poly);
}
}
}
}
if (result.size() > 100 || processQueue.size() > 100) {
break;
}
}
return result;
}
const std::vector<Polygon> Polygon::box2dDecomposition() const
{
std::vector<Polygon> result;
std::queue<Polygon> processQueue;
auto convexList = convexDecomposition();
for (auto& poly : convexList) {
processQueue.push(poly);
}
while(!processQueue.empty()) {
auto currentPoly = processQueue.front();
processQueue.pop();
if (currentPoly.isValid()) {
if (currentPoly.getDataSize() <= 8) {
result.push_back(currentPoly);
} else {
auto twoPoly = currentPoly.cut(0);
for (auto& poly : twoPoly) {
poly.normalize();
if (poly.isValid() && (poly.getArea() > fei::epsf)) {
processQueue.push(poly);
}
}
}
}
if (result.size() > 100 || processQueue.size() > 100) {
break;
}
}
return result;
}
bool Polygon::collide(const fei::Shape* shape) const
{
bool result = false;
switch (shape->getType()) {
//TODO: implement cases
//case fei::Shape::Type::CIRCLE:
//case fei::Shape::Type::POLYGON:
//case fei::Shape::Type::RECT:
//case fei::Shape::Type::SEGMENT:
}
return result;
}
bool Polygon::collidePoint(const fei::Vec2& p) const
{
auto points = rawCollideRay(p, fei::Vec2(1.0f, 0.001f));
return (points.size() & 1) == 1;
}
const Polygon Polygon::makeRegularPolygon(int edgeNum, float radius, float offset)
{
Polygon polygon;
for (int i = 0; i < edgeNum; i++) {
float angle = static_cast<float>(2.0 * fei::pi / edgeNum * i + fei::D2R(offset));
polygon.pushVertex(fei::Vec2(std::cos(angle), std::sin(angle)) * radius);
}
return polygon;
}
<commit_msg>namespace fix<commit_after>#include "math/Polygon.h"
#include "math/mathdef.h"
using fei::Polygon;
int fei::Polygon::getDataSize() const
{
return _data.size();
}
const float* Polygon::getDataPtr() const
{
if (!_data.empty()) {
return &_data[0].x;
}
return nullptr;
}
float Polygon::getArea() const
{
float area = 0.0f;
if (!isValid()) {
return area;
}
auto lastVec = getVertex(1) - getVertex(0);
for (int i = 2; i < static_cast<int>(_data.size()); i++) {
auto curVec = getVertex(i) - getVertex(0);
area += lastVec.cross(curVec);
lastVec = curVec;
}
area *= 0.5f;
return area;
}
bool Polygon::isCCW() const
{
return getArea() > 0.0f;
}
void Polygon::setVertices(int vertexNumber, float* dataPtr)
{
_data.resize(vertexNumber);
for (int i = 0; i < vertexNumber; i++) {
_data[i] = fei::Vec2(dataPtr[i << 1], dataPtr[i << 1 | 1]);
}
}
void Polygon::insertVertex(const fei::Vec2& p, int index)
{
//TODO: assertion
_data.insert(_data.begin() + index, p);
}
void Polygon::insertVertexOnClosestSegment(const fei::Vec2& p)
{
int loc = closestWhichSegment(p);
loc = indexNormalize(loc + 1);
insertVertex(p, loc);
}
void Polygon::deleteVertex(int index)
{
//TODO: assertion
_data.erase(_data.begin() + index);
}
void Polygon::moveVertices(const fei::Vec2& v)
{
for (auto& vertex : _data) {
vertex.add(v);
}
}
void Polygon::reverseVertices()
{
std::reverse(_data.begin(), _data.end());
}
void Polygon::zoom(float f)
{
for (auto& vertex : _data) {
vertex.zoom(f);
}
}
const std::vector<Polygon> Polygon::cut(int index) const
{
std::vector<Polygon> result;
int best = getBestCutVertexIndex(index);
if (best != -1) {
result = cut(index, best);
} else {
int prev = indexNormalize(index - 1);
bool isConcave = isConcaveVertex(index);
auto leftVec = -getVector(prev);
auto rightVec = getVector(index);
auto middleVec = (leftVec.normalized() + rightVec.normalized()).normalized();
if (isConcave) {
middleVec *= -1.0f;
}
auto pl = collideRay(getVertex(index), middleVec);
if (!pl.empty()) {
Polygon polyCopy(*this);
int segIndex = polyCopy.closestWhichSegment(pl[0]);
int insertLoc = polyCopy.indexNormalize(segIndex + 1);
polyCopy.insertVertex(pl[0], insertLoc);
if (insertLoc <= index) {
index = polyCopy.indexNormalize(index + 1);
}
result = polyCopy.cut(index, insertLoc);
}
}
return result;
}
const std::vector<Polygon> Polygon::cut(int a, int b) const
{
int curVertex;
std::vector<Polygon> result;
Polygon tmpPoly = *this;
tmpPoly.clearVertex();
curVertex = b;
tmpPoly.pushVertex(getVertex(a));
do {
tmpPoly.pushVertex(getVertex(curVertex));
curVertex = indexNormalize(curVertex + 1);
} while(curVertex != a);
result.push_back(tmpPoly);
tmpPoly.clearVertex();
curVertex = a;
tmpPoly.pushVertex(getVertex(b));
do {
tmpPoly.pushVertex(getVertex(curVertex));
curVertex = indexNormalize(curVertex + 1);
} while(curVertex != b);
result.push_back(tmpPoly);
return result;
}
int Polygon::closestWhichSegment(const fei::Vec2& p) const
{
int ans = -1;
float minR = 1e32f;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto seg = getSegment(i);
float curRatio = std::abs(((p - seg.a).getLength() + (p - seg.b).getLength()) / seg.getLength() - 1.0f);
if (curRatio <= minR) {
minR = curRatio;
ans = i;
}
}
return ans;
}
int Polygon::onWhichSegment(const fei::Vec2& p) const
{
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
if (getSegment(i).collidePoint(p)) {
return i;
}
}
return -1;
}
int Polygon::collideVertex(const fei::Vec2& p, float radius) const
{
float rSq = radius * radius;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
if ((getVertex(i) - p).getLengthSq() <= rSq) {
return i;
}
}
return -1;
}
static bool cmpLength(const fei::Vec2& a, const fei::Vec2& b)
{
return a.getLengthSq() < b.getLengthSq();
}
const std::vector<fei::Vec2> Polygon::rawCollideRay(const fei::Vec2& src, const fei::Vec2& drct) const
{
std::vector<fei::Vec2> result;
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto seg = getSegment(i);
fei::Vec2 tmp;
if (seg.collideRay(tmp, src, drct)) {
result.push_back(tmp - src);
}
}
return result;
}
const std::vector<fei::Vec2> Polygon::collideRay(const fei::Vec2& src, const fei::Vec2& drct) const
{
std::vector<fei::Vec2> result = rawCollideRay(src, drct);
std::vector<fei::Vec2> uniqueResult;
std::sort(result.begin(), result.end(), cmpLength);
for (int i = 0; i < static_cast<int>(result.size()); i++) {
if (result[i].getLengthSq() < 0.01f) continue;
if (i == 0 || result[i] != result[i - 1]) {
uniqueResult.push_back(result[i] + src);
}
}
return uniqueResult;
}
void Polygon::normalize()
{
std::vector<fei::Vec2> nData;
int sz = _data.size();
for (int i = 0; i < sz; i++) {
int prev = indexNormalize(i - 1);
if ((getVector(prev).getLengthSq() >= 0.01f)
&& (getVector(i).normalized() != getVector(prev).normalized())) {
nData.push_back(getVertex(i));
}
}
setDataVector(nData);
if (!isCCW()) {
reverseVertices();
}
}
const Polygon Polygon::normalized() const
{
Polygon poly(*this);
poly.normalize();
return poly;
}
bool Polygon::isConcaveVertex(int index) const
{
//TODO: assertion
int prevIndex = indexNormalize(index - 1);
auto prev = getVector(prevIndex);
auto cur = getVector(index);
float cp = prev.cross(cur);
return cp < 0;
}
int Polygon::getOneConcaveVertex() const
{
int sz = static_cast<int>(_data.size());
for (int i = 0; i < sz; i++) {
if (isConcaveVertex(i)) {
return i;
}
}
return -1;
}
typedef struct CutStruct
{
CutStruct(const Polygon* pp, int ii, int xx)
: poly(pp), index(ii), x(xx)
{
}
bool operator>(const CutStruct& rhs) const
{
int ai = x;
int bi = rhs.x;
int sz = poly->getDataSize();
bool aConcave = poly->isConcaveVertex(ai);
bool bConcave = poly->isConcaveVertex(bi);
if (aConcave == bConcave) {
int disIA = std::abs(index - ai);
if (sz - disIA < disIA) {
disIA = sz - disIA;
}
int disIB = std::abs(index - bi);
if (sz - disIB < disIB) {
disIB = sz - disIB;
}
return disIA > disIB;
} else {
return aConcave;
}
}
const Polygon* poly;
int index;
int x;
} PolyCutPair;
int Polygon::getBestCutVertexIndex(int index) const
{
int ans = -1;
auto iList = getVisibleVerticesIndex(index);
std::vector<PolyCutPair> uList;
if (isConcaveVertex(index)) {
auto left = getSegment(index);
auto right = getSegment(indexNormalize(index - 1));
right.swapAB();
left.b = left.a - left.getVector();
right.b = right.a - right.getVector();
for (int vertex : iList) {
auto p = getVertex(vertex);
if (left.onLeftOrRight(p) == 1
&& right.onLeftOrRight(p) == -1) {
auto pl = collideRay(getVertex(index), p - getVertex(index));
if (pl.size() == 0 || pl[0] == p) {
uList.push_back(PolyCutPair(this, index, vertex));
}
}
}
} else {
for (int vertex : iList) {
uList.push_back(PolyCutPair(this, index, vertex));
}
}
if (!uList.empty()) {
auto maxPcp = uList[0];
for (auto& pcp : uList) {
if (pcp > maxPcp) {
maxPcp = pcp;
}
}
ans = maxPcp.x;
}
return ans;
}
std::vector<int> Polygon::getVisibleVerticesIndex(int index) const
{
std::vector<int> result;
int left = indexNormalize(index - 1);
int right = indexNormalize(index + 1);
bool isConcave = isConcaveVertex(index);
auto leftSeg = getSegment(left);
auto rightSeg = getSegment(index);
leftSeg.swapAB();
if (isConcave) {
auto tmp = leftSeg;
leftSeg = rightSeg;
rightSeg = tmp;
}
for (int i = 0; i < static_cast<int>(_data.size()); i++) {
auto p = getVertex(i);
if (i == index || i == left || i == right ||
(leftSeg.onLeftOrRight(p) == 1 && rightSeg.onLeftOrRight(p) == -1) == isConcave) {
continue;
}
auto vertexList = collideRay(getVertex(index), p - getVertex(index));
if (vertexList.size() == 0 || vertexList[0] == p) {
result.push_back(i);
}
}
return result;
}
bool Polygon::isConvex() const
{
return getOneConcaveVertex() < 0;
}
const std::vector<Polygon> Polygon::convexDecomposition() const
{
std::vector<Polygon> result;
std::queue<Polygon> processQueue;
processQueue.push(normalized());
while(!processQueue.empty()) {
auto currentPoly = processQueue.front();
processQueue.pop();
if (currentPoly.isValid()) {
int concavePoint = currentPoly.getOneConcaveVertex();
if (concavePoint == -1) {
result.push_back(currentPoly);
} else {
auto twoPoly = currentPoly.cut(concavePoint);
for (auto& poly : twoPoly) {
poly.normalize();
if (poly.isValid()) {
processQueue.push(poly);
}
}
}
}
if (result.size() > 100 || processQueue.size() > 100) {
break;
}
}
return result;
}
const std::vector<Polygon> Polygon::box2dDecomposition() const
{
std::vector<Polygon> result;
std::queue<Polygon> processQueue;
auto convexList = convexDecomposition();
for (auto& poly : convexList) {
processQueue.push(poly);
}
while(!processQueue.empty()) {
auto currentPoly = processQueue.front();
processQueue.pop();
if (currentPoly.isValid()) {
if (currentPoly.getDataSize() <= 8) {
result.push_back(currentPoly);
} else {
auto twoPoly = currentPoly.cut(0);
for (auto& poly : twoPoly) {
poly.normalize();
if (poly.isValid() && (poly.getArea() > fei::epsf)) {
processQueue.push(poly);
}
}
}
}
if (result.size() > 100 || processQueue.size() > 100) {
break;
}
}
return result;
}
bool Polygon::collide(const fei::Shape* shape) const
{
bool result = false;
switch (shape->getType()) {
//TODO: implement cases
//case fei::Shape::Type::CIRCLE:
//case fei::Shape::Type::POLYGON:
//case fei::Shape::Type::RECT:
//case fei::Shape::Type::SEGMENT:
}
return result;
}
bool Polygon::collidePoint(const fei::Vec2& p) const
{
auto points = rawCollideRay(p, fei::Vec2(1.0f, 0.001f));
return (points.size() & 1) == 1;
}
const Polygon Polygon::makeRegularPolygon(int edgeNum, float radius, float offset)
{
Polygon polygon;
for (int i = 0; i < edgeNum; i++) {
float angle = static_cast<float>(2.0 * fei::pi / edgeNum * i + fei::D2R(offset));
polygon.pushVertex(fei::Vec2(std::cos(angle), std::sin(angle)) * radius);
}
return polygon;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fontsubs.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2005-01-21 16:35:55 $
*
* 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 _SVX_FONT_SUBSTITUTION_HXX
#define _SVX_FONT_SUBSTITUTION_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX //autogen
#include "simptabl.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _CTRLBOX_HXX //autogen
#include <svtools/ctrlbox.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// class SvxFontSubstCheckListBox ------------------------------------------
class SvxFontSubstCheckListBox : public SvxSimpleTable
{
friend class SvxFontSubstTabPage;
protected:
virtual void SetTabs();
virtual void KeyInput( const KeyEvent& rKEvt );
public:
SvxFontSubstCheckListBox(Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId ){}
inline void *GetUserData(ULONG nPos) { return GetEntry(nPos)->GetUserData(); }
inline void SetUserData(ULONG nPos, void *pData ) { GetEntry(nPos)->SetUserData(pData); }
BOOL IsChecked(ULONG nPos, USHORT nCol = 0);
BOOL IsChecked(SvLBoxEntry* pEntry, USHORT nCol = 0);
void CheckEntryPos(ULONG nPos, USHORT nCol, BOOL bChecked);
void CheckEntry(SvLBoxEntry* pEntry, USHORT nCol, BOOL bChecked);
SvButtonState GetCheckButtonState( SvLBoxEntry*, USHORT nCol ) const;
void SetCheckButtonState( SvLBoxEntry*, USHORT nCol, SvButtonState );
};
// class SvxFontSubstTabPage ----------------------------------------------------
class SvtFontSubstConfig;
namespace svt {class SourceViewConfig;}
class SVX_DLLPUBLIC SvxFontSubstTabPage : public SfxTabPage
{
CheckBox aUseTableCB;
FixedText aFont1FT;
FontNameBox aFont1CB;
FixedText aFont2FT;
FontNameBox aFont2CB;
ToolBox aNewDelTBX;
SvxFontSubstCheckListBox aCheckLB;
FixedLine aSourceViewFontsFL;
FixedText aFontNameFT;
ListBox aFontNameLB;
CheckBox aNonPropFontsOnlyCB;
FixedText aFontHeightFT;
ListBox aFontHeightLB;
ImageList aImageList;
String sAutomatic;
SvtFontSubstConfig* pConfig;
svt::SourceViewConfig* pSourceViewConfig;
String sHeader1;
String sHeader2;
String sHeader3;
String sHeader4;
Bitmap aChkunBmp;
Bitmap aChkchBmp;
Bitmap aChkchhiBmp;
Bitmap aChkunhiBmp;
Bitmap aChktriBmp;
Bitmap aChktrihiBmp;
Color aTextColor;
ByteString sFontGroup;
SvLBoxButtonData* pCheckButtonData;
DECL_LINK(SelectHdl, Window *pWin = 0);
DECL_LINK(NonPropFontsHdl, CheckBox* pBox);
SvLBoxEntry* CreateEntry(String& rFont1, String& rFont2);
void CheckEnable();
SvxFontSubstTabPage( Window* pParent, const SfxItemSet& rSet );
~SvxFontSubstTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif // _SVX_FONT_SUBSTITUTION_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.430); FILE MERGED 2005/09/05 14:19:28 rt 1.3.430.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fontsubs.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:06:14 $
*
* 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 _SVX_FONT_SUBSTITUTION_HXX
#define _SVX_FONT_SUBSTITUTION_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SVX_SIMPTABL_HXX //autogen
#include "simptabl.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX //autogen
#include <vcl/toolbox.hxx>
#endif
#ifndef _CTRLBOX_HXX //autogen
#include <svtools/ctrlbox.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
// class SvxFontSubstCheckListBox ------------------------------------------
class SvxFontSubstCheckListBox : public SvxSimpleTable
{
friend class SvxFontSubstTabPage;
protected:
virtual void SetTabs();
virtual void KeyInput( const KeyEvent& rKEvt );
public:
SvxFontSubstCheckListBox(Window* pParent, const ResId& rResId ) :
SvxSimpleTable( pParent, rResId ){}
inline void *GetUserData(ULONG nPos) { return GetEntry(nPos)->GetUserData(); }
inline void SetUserData(ULONG nPos, void *pData ) { GetEntry(nPos)->SetUserData(pData); }
BOOL IsChecked(ULONG nPos, USHORT nCol = 0);
BOOL IsChecked(SvLBoxEntry* pEntry, USHORT nCol = 0);
void CheckEntryPos(ULONG nPos, USHORT nCol, BOOL bChecked);
void CheckEntry(SvLBoxEntry* pEntry, USHORT nCol, BOOL bChecked);
SvButtonState GetCheckButtonState( SvLBoxEntry*, USHORT nCol ) const;
void SetCheckButtonState( SvLBoxEntry*, USHORT nCol, SvButtonState );
};
// class SvxFontSubstTabPage ----------------------------------------------------
class SvtFontSubstConfig;
namespace svt {class SourceViewConfig;}
class SVX_DLLPUBLIC SvxFontSubstTabPage : public SfxTabPage
{
CheckBox aUseTableCB;
FixedText aFont1FT;
FontNameBox aFont1CB;
FixedText aFont2FT;
FontNameBox aFont2CB;
ToolBox aNewDelTBX;
SvxFontSubstCheckListBox aCheckLB;
FixedLine aSourceViewFontsFL;
FixedText aFontNameFT;
ListBox aFontNameLB;
CheckBox aNonPropFontsOnlyCB;
FixedText aFontHeightFT;
ListBox aFontHeightLB;
ImageList aImageList;
String sAutomatic;
SvtFontSubstConfig* pConfig;
svt::SourceViewConfig* pSourceViewConfig;
String sHeader1;
String sHeader2;
String sHeader3;
String sHeader4;
Bitmap aChkunBmp;
Bitmap aChkchBmp;
Bitmap aChkchhiBmp;
Bitmap aChkunhiBmp;
Bitmap aChktriBmp;
Bitmap aChktrihiBmp;
Color aTextColor;
ByteString sFontGroup;
SvLBoxButtonData* pCheckButtonData;
DECL_LINK(SelectHdl, Window *pWin = 0);
DECL_LINK(NonPropFontsHdl, CheckBox* pBox);
SvLBoxEntry* CreateEntry(String& rFont1, String& rFont2);
void CheckEnable();
SvxFontSubstTabPage( Window* pParent, const SfxItemSet& rSet );
~SvxFontSubstTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet);
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif // _SVX_FONT_SUBSTITUTION_HXX
<|endoftext|> |
<commit_before>#include "videotargetfactory.h"
#ifdef USE_OPENCV
#include "opencv_video_target.h"
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_target.h"
#endif
namespace gg
{
VideoTargetFactory::VideoTargetFactory()
{
// nop
}
VideoTargetFactory::~VideoTargetFactory()
{
// nop
}
VideoTargetFactory & VideoTargetFactory::get_instance()
{
static VideoTargetFactory _factory_singleton;
return _factory_singleton;
}
IVideoTarget * VideoTargetFactory::create_file_writer(enum Codec codec,
const std::string filename,
const float frame_rate)
{
IVideoTarget * target = nullptr;
switch (codec)
{
case Xvid:
#ifdef USE_OPENCV
target = new VideoTargetOpenCV("XVID", filename, frame_rate);
break;
#endif
case HEVC:
#ifdef USE_FFMPEG
target = new VideoTargetFFmpeg("HEVC", filename, frame_rate);
break;
#endif
case VP9:
#ifdef USE_FFMPEG
target = new VideoTargetFFmpeg("VP9", filename, frame_rate);
break;
#endif
default:
std::string msg;
msg.append("Video target codec ")
.append(std::to_string(codec))
.append(" not supported");
throw VideoTargetError(msg);
}
return target;
}
}
<commit_msg>Issue #19: revised static var name in VideoTargetFactory::get_instance for clarity<commit_after>#include "videotargetfactory.h"
#ifdef USE_OPENCV
#include "opencv_video_target.h"
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_target.h"
#endif
namespace gg
{
VideoTargetFactory::VideoTargetFactory()
{
// nop
}
VideoTargetFactory::~VideoTargetFactory()
{
// nop
}
VideoTargetFactory & VideoTargetFactory::get_instance()
{
static VideoTargetFactory _video_target_factory_singleton;
return _video_target_factory_singleton;
}
IVideoTarget * VideoTargetFactory::create_file_writer(enum Codec codec,
const std::string filename,
const float frame_rate)
{
IVideoTarget * target = nullptr;
switch (codec)
{
case Xvid:
#ifdef USE_OPENCV
target = new VideoTargetOpenCV("XVID", filename, frame_rate);
break;
#endif
case HEVC:
#ifdef USE_FFMPEG
target = new VideoTargetFFmpeg("HEVC", filename, frame_rate);
break;
#endif
case VP9:
#ifdef USE_FFMPEG
target = new VideoTargetFFmpeg("VP9", filename, frame_rate);
break;
#endif
default:
std::string msg;
msg.append("Video target codec ")
.append(std::to_string(codec))
.append(" not supported");
throw VideoTargetError(msg);
}
return target;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: SpellDialog.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-23 11:04:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_SPELLDDIALOG_HXX
#define _SVX_SPELLDDIALOG_HXX
// include ---------------------------------------------------------------
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _MENUBTN_HXX //autogen
#include <vcl/menubtn.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_DECOVIEW_HXX //autogen
#include <vcl/decoview.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _SVX_BOX_HXX //autogen
#include "svxbox.hxx"
#endif
#ifndef _SVX_LANGBOX_HXX
#include <langbox.hxx>
#endif
#include <memory>
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _XTEXTEDT_HXX //autogen
#include <svtools/xtextedt.hxx>
#endif
#ifndef SVX_SPELL_PORTIONS_HXX
#include <SpellPortions.hxx>
#endif
class ScrollBar;
class TextEngine;
class ExtTextView;
namespace svx{ class SpellUndoAction_Impl;}
// forward ---------------------------------------------------------------
struct SpellDialog_Impl;
namespace com{namespace sun{namespace star{
namespace linguistic2{
class XSpellChecker1;
}}}}
namespace svx{
class SpellDialog;
// ------------------------------------------------------------------
class SentenceEditWindow_Impl : public MultiLineEdit/*, public SfxListener*/
{
private:
USHORT m_nErrorStart;
USHORT m_nErrorEnd;
bool m_bIsUndoEditMode;
Link m_aModifyLink;
void CallModifyLink() {m_aModifyLink.Call(this);}
SpellDialog* GetSpellDialog() const {return (SpellDialog*)GetParent();}
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
public:
SentenceEditWindow_Impl( SpellDialog* pParent, const ResId& rResId );
~SentenceEditWindow_Impl();
void SetModifyHdl(const Link& rLink) { m_aModifyLink = rLink;}
void SetAttrib( const TextAttrib& rAttr, ULONG nPara, USHORT nStart, USHORT nEnd );
void SetText( const String& rStr );
bool MarkNextError();
void ChangeMarkedWord(const String& rNewWord, LanguageType eLanguage);
void MoveErrorMarkTo(USHORT nErrorStart, USHORT nErrorEnd);
String GetErrorText() const;
void RestoreCurrentError();
com::sun::star::uno::Reference<com::sun::star::linguistic2::XSpellAlternatives> GetAlternatives();
void SetAlternatives(
com::sun::star::uno::Reference<com::sun::star::linguistic2::XSpellAlternatives> );
void ResetModified() { GetTextEngine()->SetModified(FALSE); m_bIsUndoEditMode = false;}
BOOL IsModified() const { return GetTextEngine()->IsModified(); }
bool IsUndoEditMode() const { return m_bIsUndoEditMode;}
void SetUndoEditMode(bool bSet);
svx::SpellPortions CreateSpellPortions() const;
void ResetUndo();
void Undo();
void AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg=FALSE );
USHORT GetUndoActionCount();
void UndoActionStart( USHORT nId );
void UndoActionEnd( USHORT nId );
void MoveErrorEnd(long nOffset);
};
// class SvxSpellDialog ---------------------------------------------
class SpellDialogChildWindow;
class SpellDialog : public SfxModelessDialog
{
friend class SentenceEditWindow_Impl;
private:
FixedText aNotInDictFT;
SentenceEditWindow_Impl aSentenceED;
FixedText aSuggestionFT;
ListBox aSuggestionLB;
FixedText aLanguageFT;
SvxLanguageBox aLanguageLB;
PushButton aIgnorePB;
PushButton aIgnoreAllPB;
MenuButton aAddToDictMB;
PushButton aChangePB;
PushButton aChangeAllPB;
PushButton aAutoCorrPB;
PushButton aOptionsPB;
HelpButton aHelpPB;
PushButton aUndoPB;
PushButton aClosePB;
GroupBox aBackgroundGB;
String aTitel;
String aResumeST;
String aIgnoreOnceST;
String aNoSuggestionsST;
Size aOldWordEDSize;
Link aDialogUndoLink;
bool bModified;
bool bFocusLocked;
svx::SpellDialogChildWindow& rParent;
svx::SpellPortions m_aSavedSentence;
SpellDialog_Impl* pImpl;
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker1 > xSpell;
String aOldWord;
LanguageType nOldLang;
DECL_LINK( ChangeHdl, Button * );
DECL_LINK( ChangeAllHdl, Button * );
DECL_LINK( IgnoreAllHdl, Button * );
DECL_LINK( IgnoreHdl, Button * );
DECL_LINK( ExtClickHdl, Button * );
DECL_LINK( CancelHdl, Button * );
DECL_LINK( ModifyHdl, SentenceEditWindow_Impl *);
DECL_LINK( UndoHdl, Button * );
DECL_LINK( AddToDictionaryHdl, MenuButton* );
DECL_LINK( LanguageSelectHdl, SvxLanguageBox* );
DECL_LINK( DialogUndoHdl, SpellUndoAction_Impl* );
DECL_STATIC_LINK( SpellDialog, InitHdl, SpellDialog * );
void StartSpellOptDlg_Impl();
void InitUserDicts();
void UpdateBoxes_Impl();
void Init_Impl();
void SpellContinue_Impl(bool UseSavedSentence = false);
void LockFocusChanges( bool bLock ) {bFocusLocked = bLock;}
void SetSelectedLang_Impl( LanguageType nLang );
LanguageType GetSelectedLang_Impl() const;
/** Retrieves the next sentence.
*/
bool GetNextSentence_Impl(bool bUseSavedSentence);
/** Corrects all errors that have been selected to be changed always
*/
bool ApplyChangeAllList_Impl(SpellPortions& rSentence, bool& bHasReplaced);
protected:
virtual void Paint( const Rectangle& rRect );
virtual long Notify( NotifyEvent& rNEvt );
public:
SpellDialog(
svx::SpellDialogChildWindow* pChildWindow,
Window * pParent,
SfxBindings* pBindings);
~SpellDialog();
void SetLanguage( sal_uInt16 nLang );
virtual sal_Bool Close();
void Invalidate();
};
} //namespace svx
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.252); FILE MERGED 2005/09/05 14:24:59 rt 1.3.252.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SpellDialog.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:10:28 $
*
* 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 _SVX_SPELLDDIALOG_HXX
#define _SVX_SPELLDDIALOG_HXX
// include ---------------------------------------------------------------
#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _MENUBTN_HXX //autogen
#include <vcl/menubtn.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_DECOVIEW_HXX //autogen
#include <vcl/decoview.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _SVX_BOX_HXX //autogen
#include "svxbox.hxx"
#endif
#ifndef _SVX_LANGBOX_HXX
#include <langbox.hxx>
#endif
#include <memory>
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _XTEXTEDT_HXX //autogen
#include <svtools/xtextedt.hxx>
#endif
#ifndef SVX_SPELL_PORTIONS_HXX
#include <SpellPortions.hxx>
#endif
class ScrollBar;
class TextEngine;
class ExtTextView;
namespace svx{ class SpellUndoAction_Impl;}
// forward ---------------------------------------------------------------
struct SpellDialog_Impl;
namespace com{namespace sun{namespace star{
namespace linguistic2{
class XSpellChecker1;
}}}}
namespace svx{
class SpellDialog;
// ------------------------------------------------------------------
class SentenceEditWindow_Impl : public MultiLineEdit/*, public SfxListener*/
{
private:
USHORT m_nErrorStart;
USHORT m_nErrorEnd;
bool m_bIsUndoEditMode;
Link m_aModifyLink;
void CallModifyLink() {m_aModifyLink.Call(this);}
SpellDialog* GetSpellDialog() const {return (SpellDialog*)GetParent();}
protected:
virtual long PreNotify( NotifyEvent& rNEvt );
public:
SentenceEditWindow_Impl( SpellDialog* pParent, const ResId& rResId );
~SentenceEditWindow_Impl();
void SetModifyHdl(const Link& rLink) { m_aModifyLink = rLink;}
void SetAttrib( const TextAttrib& rAttr, ULONG nPara, USHORT nStart, USHORT nEnd );
void SetText( const String& rStr );
bool MarkNextError();
void ChangeMarkedWord(const String& rNewWord, LanguageType eLanguage);
void MoveErrorMarkTo(USHORT nErrorStart, USHORT nErrorEnd);
String GetErrorText() const;
void RestoreCurrentError();
com::sun::star::uno::Reference<com::sun::star::linguistic2::XSpellAlternatives> GetAlternatives();
void SetAlternatives(
com::sun::star::uno::Reference<com::sun::star::linguistic2::XSpellAlternatives> );
void ResetModified() { GetTextEngine()->SetModified(FALSE); m_bIsUndoEditMode = false;}
BOOL IsModified() const { return GetTextEngine()->IsModified(); }
bool IsUndoEditMode() const { return m_bIsUndoEditMode;}
void SetUndoEditMode(bool bSet);
svx::SpellPortions CreateSpellPortions() const;
void ResetUndo();
void Undo();
void AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg=FALSE );
USHORT GetUndoActionCount();
void UndoActionStart( USHORT nId );
void UndoActionEnd( USHORT nId );
void MoveErrorEnd(long nOffset);
};
// class SvxSpellDialog ---------------------------------------------
class SpellDialogChildWindow;
class SpellDialog : public SfxModelessDialog
{
friend class SentenceEditWindow_Impl;
private:
FixedText aNotInDictFT;
SentenceEditWindow_Impl aSentenceED;
FixedText aSuggestionFT;
ListBox aSuggestionLB;
FixedText aLanguageFT;
SvxLanguageBox aLanguageLB;
PushButton aIgnorePB;
PushButton aIgnoreAllPB;
MenuButton aAddToDictMB;
PushButton aChangePB;
PushButton aChangeAllPB;
PushButton aAutoCorrPB;
PushButton aOptionsPB;
HelpButton aHelpPB;
PushButton aUndoPB;
PushButton aClosePB;
GroupBox aBackgroundGB;
String aTitel;
String aResumeST;
String aIgnoreOnceST;
String aNoSuggestionsST;
Size aOldWordEDSize;
Link aDialogUndoLink;
bool bModified;
bool bFocusLocked;
svx::SpellDialogChildWindow& rParent;
svx::SpellPortions m_aSavedSentence;
SpellDialog_Impl* pImpl;
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker1 > xSpell;
String aOldWord;
LanguageType nOldLang;
DECL_LINK( ChangeHdl, Button * );
DECL_LINK( ChangeAllHdl, Button * );
DECL_LINK( IgnoreAllHdl, Button * );
DECL_LINK( IgnoreHdl, Button * );
DECL_LINK( ExtClickHdl, Button * );
DECL_LINK( CancelHdl, Button * );
DECL_LINK( ModifyHdl, SentenceEditWindow_Impl *);
DECL_LINK( UndoHdl, Button * );
DECL_LINK( AddToDictionaryHdl, MenuButton* );
DECL_LINK( LanguageSelectHdl, SvxLanguageBox* );
DECL_LINK( DialogUndoHdl, SpellUndoAction_Impl* );
DECL_STATIC_LINK( SpellDialog, InitHdl, SpellDialog * );
void StartSpellOptDlg_Impl();
void InitUserDicts();
void UpdateBoxes_Impl();
void Init_Impl();
void SpellContinue_Impl(bool UseSavedSentence = false);
void LockFocusChanges( bool bLock ) {bFocusLocked = bLock;}
void SetSelectedLang_Impl( LanguageType nLang );
LanguageType GetSelectedLang_Impl() const;
/** Retrieves the next sentence.
*/
bool GetNextSentence_Impl(bool bUseSavedSentence);
/** Corrects all errors that have been selected to be changed always
*/
bool ApplyChangeAllList_Impl(SpellPortions& rSentence, bool& bHasReplaced);
protected:
virtual void Paint( const Rectangle& rRect );
virtual long Notify( NotifyEvent& rNEvt );
public:
SpellDialog(
svx::SpellDialogChildWindow* pChildWindow,
Window * pParent,
SfxBindings* pBindings);
~SpellDialog();
void SetLanguage( sal_uInt16 nLang );
virtual sal_Bool Close();
void Invalidate();
};
} //namespace svx
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdhlpln.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-10-12 13:10:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "svdhlpln.hxx"
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _OUTDEV_HXX //autogen
#include <vcl/outdev.hxx>
#endif
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SV_LINEINFO_HXX
#include <vcl/lineinfo.hxx>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
Pointer SdrHelpLine::GetPointer() const
{
switch (eKind) {
case SDRHELPLINE_VERTICAL : return Pointer(POINTER_ESIZE);
case SDRHELPLINE_HORIZONTAL: return Pointer(POINTER_SSIZE);
default : return Pointer(POINTER_MOVE);
} // switch
}
// #i27493#
// Helper method to draw a hor or ver two-colored dashed line
void SdrHelpLine::ImpDrawDashedTwoColorLine(OutputDevice& rOut, sal_Int32 nStart, sal_Int32 nEnd, sal_Int32 nFixPos,
sal_Int32 nStepWidth, Color aColA, Color aColB, sal_Bool bHorizontal) const
{
for(sal_Int32 a(nStart), b(0L); a < nEnd; a += nStepWidth, b++)
{
rOut.SetLineColor((b % 2) ? aColA : aColB);
sal_Int32 nNextPos(a + nStepWidth - 1L);
if(nNextPos > nEnd)
nNextPos = nEnd;
if(bHorizontal)
rOut.DrawLine(Point(a, nFixPos), Point(nNextPos, nFixPos));
else
rOut.DrawLine(Point(nFixPos, a), Point(nFixPos, nNextPos));
}
}
void SdrHelpLine::Draw(OutputDevice& rOut, const Point& rOfs) const
{
// #i27493# New implementation for 8. Will be replaced later when we have overlays.
Point aPnt(rOut.LogicToPixel(aPos + rOfs));
const sal_Int32 xPos(aPnt.X());
const sal_Int32 yPos(aPnt.Y());
const sal_Bool bOldMapModeWasEnabled(rOut.IsMapModeEnabled());
const Size aOutSizePixel(rOut.GetOutputSizePixel());
rOut.EnableMapMode(sal_False);
switch(eKind)
{
case SDRHELPLINE_VERTICAL :
{
ImpDrawDashedTwoColorLine(rOut, 0L, aOutSizePixel.Height(),
xPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_False);
break;
}
case SDRHELPLINE_HORIZONTAL :
{
ImpDrawDashedTwoColorLine(rOut, 0L, aOutSizePixel.Width(),
yPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_True);
break;
}
case SDRHELPLINE_POINT :
{
ImpDrawDashedTwoColorLine(rOut, xPos - SDRHELPLINE_POINT_PIXELSIZE, xPos + SDRHELPLINE_POINT_PIXELSIZE,
yPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_True);
ImpDrawDashedTwoColorLine(rOut, yPos - SDRHELPLINE_POINT_PIXELSIZE, yPos + SDRHELPLINE_POINT_PIXELSIZE,
xPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_False);
break;
}
}
rOut.EnableMapMode(bOldMapModeWasEnabled);
}
FASTBOOL SdrHelpLine::IsHit(const Point& rPnt, USHORT nTolLog, const OutputDevice& rOut) const
{
Size a1Pix(rOut.PixelToLogic(Size(1,1)));
FASTBOOL bXHit=rPnt.X()>=aPos.X()-nTolLog && rPnt.X()<=aPos.X()+nTolLog+a1Pix.Width();
FASTBOOL bYHit=rPnt.Y()>=aPos.Y()-nTolLog && rPnt.Y()<=aPos.Y()+nTolLog+a1Pix.Height();
switch (eKind) {
case SDRHELPLINE_VERTICAL : return bXHit;
case SDRHELPLINE_HORIZONTAL: return bYHit;
case SDRHELPLINE_POINT: {
if (bXHit || bYHit) {
Size aRad(rOut.PixelToLogic(Size(SDRHELPLINE_POINT_PIXELSIZE,SDRHELPLINE_POINT_PIXELSIZE)));
return rPnt.X()>=aPos.X()-aRad.Width() && rPnt.X()<=aPos.X()+aRad.Width()+a1Pix.Width() &&
rPnt.Y()>=aPos.Y()-aRad.Height() && rPnt.Y()<=aPos.Y()+aRad.Height()+a1Pix.Height();
}
} break;
} // switch
return FALSE;
}
Rectangle SdrHelpLine::GetBoundRect(const OutputDevice& rOut) const
{
Rectangle aRet(aPos,aPos);
Point aOfs(rOut.GetMapMode().GetOrigin());
Size aSiz(rOut.GetOutputSize());
switch (eKind) {
case SDRHELPLINE_VERTICAL : aRet.Top()=-aOfs.Y(); aRet.Bottom()=-aOfs.Y()+aSiz.Height(); break;
case SDRHELPLINE_HORIZONTAL: aRet.Left()=-aOfs.X(); aRet.Right()=-aOfs.X()+aSiz.Width(); break;
case SDRHELPLINE_POINT : {
Size aRad(rOut.PixelToLogic(Size(SDRHELPLINE_POINT_PIXELSIZE,SDRHELPLINE_POINT_PIXELSIZE)));
aRet.Left() -=aRad.Width();
aRet.Right() +=aRad.Width();
aRet.Top() -=aRad.Height();
aRet.Bottom()+=aRad.Height();
} break;
} // switch
return aRet;
}
bool SdrHelpLine::IsVisibleEqual( const SdrHelpLine& rHelpLine, const OutputDevice& rOut ) const
{
if( eKind == rHelpLine.eKind)
{
Point aPt1(rOut.LogicToPixel(aPos)), aPt2(rOut.LogicToPixel(rHelpLine.aPos));
switch( eKind )
{
case SDRHELPLINE_POINT:
return aPt1 == aPt2;
case SDRHELPLINE_VERTICAL:
return aPt1.X() == aPt2.X();
case SDRHELPLINE_HORIZONTAL:
return aPt1.Y() == aPt2.Y();
}
}
return false;
}
//BFS01SvStream& operator<<(SvStream& rOut, const SdrHelpLine& rHL)
//BFS01{
//BFS01 SdrIOHeader aHead(rOut,STREAM_WRITE,SdrIOHlpLID);
//BFS01 rOut<<UINT16(rHL.eKind);
//BFS01 rOut<<rHL.aPos;
//BFS01 return rOut;
//BFS01}
//BFS01SvStream& operator>>(SvStream& rIn, SdrHelpLine& rHL)
//BFS01{
//BFS01 SdrIOHeader aHead(rIn,STREAM_READ);
//BFS01 UINT16 nDum;
//BFS01 rIn>>nDum;
//BFS01 rHL.eKind=(SdrHelpLineKind)nDum;
//BFS01 rIn>>rHL.aPos;
//BFS01 return rIn;
//BFS01}
void SdrHelpLineList::Clear()
{
USHORT nAnz=GetCount();
for (USHORT i=0; i<nAnz; i++) {
delete GetObject(i);
}
aList.Clear();
}
void SdrHelpLineList::operator=(const SdrHelpLineList& rSrcList)
{
Clear();
USHORT nAnz=rSrcList.GetCount();
for (USHORT i=0; i<nAnz; i++) {
Insert(rSrcList[i]);
}
}
bool SdrHelpLineList::operator==(const SdrHelpLineList& rSrcList) const
{
FASTBOOL bEqual=FALSE;
USHORT nAnz=GetCount();
if (nAnz==rSrcList.GetCount()) {
bEqual=TRUE;
for (USHORT i=0; i<nAnz && bEqual; i++) {
if (*GetObject(i)!=*rSrcList.GetObject(i)) {
bEqual=FALSE;
}
}
}
return bEqual;
}
void SdrHelpLineList::DrawAll(OutputDevice& rOut, const Point& rOfs) const
{
sal_uInt16 nAnz = GetCount();
sal_uInt16 i,j;
SdrHelpLine *pHL, *pHL2;
for(i=0; i<nAnz; i++)
{
pHL = GetObject(i);
// check if we already drawn a help line like this one
if( pHL )
{
for(j=0;j<i;j++)
{
pHL2 = GetObject(j);
if( pHL2 && pHL->IsVisibleEqual( *pHL2, rOut) )
{
pHL = NULL;
break;
}
}
}
if( pHL )
pHL->Draw(rOut,rOfs);
}
}
USHORT SdrHelpLineList::HitTest(const Point& rPnt, USHORT nTolLog, const OutputDevice& rOut) const
{
USHORT nAnz=GetCount();
for (USHORT i=nAnz; i>0;) {
i--;
if (GetObject(i)->IsHit(rPnt,nTolLog,rOut)) return i;
}
return SDRHELPLINE_NOTFOUND;
}
//BFS01SvStream& operator<<(SvStream& rOut, const SdrHelpLineList& rHLL)
//BFS01{
//BFS01 SdrIOHeader aHead(rOut,STREAM_WRITE,SdrIOHLstID);
//BFS01 USHORT nAnz=rHLL.GetCount();
//BFS01 rOut<<nAnz;
//BFS01 for (USHORT i=0; i<nAnz; i++) {
//BFS01 rOut<<rHLL[i];
//BFS01 }
//BFS01 return rOut;
//BFS01}
//BFS01SvStream& operator>>(SvStream& rIn, SdrHelpLineList& rHLL)
//BFS01{
//BFS01 SdrIOHeader aHead(rIn,STREAM_READ);
//BFS01 rHLL.Clear();
//BFS01 USHORT nAnz;
//BFS01 rIn>>nAnz;
//BFS01 for (USHORT i=0; i<nAnz; i++) {
//BFS01 SdrHelpLine* pHL=new SdrHelpLine;
//BFS01 rIn>>*pHL;
//BFS01 rHLL.aList.Insert(pHL,CONTAINER_APPEND);
//BFS01 }
//BFS01 return rIn;
//BFS01}
// eof
<commit_msg>INTEGRATION: CWS aw024 (1.8.140); FILE MERGED 2006/11/10 03:43:22 aw 1.8.140.5: RESYNC: (1.12-1.13); FILE MERGED 2006/09/21 19:27:45 aw 1.8.140.4: RESYNC: (1.11-1.12); FILE MERGED 2006/07/04 13:15:06 aw 1.8.140.3: RESYNC: (1.9-1.10); FILE MERGED 2005/09/18 05:03:28 aw 1.8.140.2: RESYNC: (1.8-1.9); FILE MERGED 2004/12/23 16:52:45 aw 1.8.140.1: #i39525<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdhlpln.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:42:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "svdhlpln.hxx"
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _OUTDEV_HXX //autogen
#include <vcl/outdev.hxx>
#endif
#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SV_LINEINFO_HXX
#include <vcl/lineinfo.hxx>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
Pointer SdrHelpLine::GetPointer() const
{
switch (eKind) {
case SDRHELPLINE_VERTICAL : return Pointer(POINTER_ESIZE);
case SDRHELPLINE_HORIZONTAL: return Pointer(POINTER_SSIZE);
default : return Pointer(POINTER_MOVE);
} // switch
}
// #i27493#
// Helper method to draw a hor or ver two-colored dashed line
void SdrHelpLine::ImpDrawDashedTwoColorLine(OutputDevice& rOut, sal_Int32 nStart, sal_Int32 nEnd, sal_Int32 nFixPos,
sal_Int32 nStepWidth, Color aColA, Color aColB, sal_Bool bHorizontal) const
{
for(sal_Int32 a(nStart), b(0L); a < nEnd; a += nStepWidth, b++)
{
rOut.SetLineColor((b % 2) ? aColA : aColB);
sal_Int32 nNextPos(a + nStepWidth - 1L);
if(nNextPos > nEnd)
nNextPos = nEnd;
if(bHorizontal)
rOut.DrawLine(Point(a, nFixPos), Point(nNextPos, nFixPos));
else
rOut.DrawLine(Point(nFixPos, a), Point(nFixPos, nNextPos));
}
}
void SdrHelpLine::Draw(OutputDevice& rOut, const Point& rOfs) const
{
// #i27493# New implementation for 8. Will be replaced later when we have overlays.
Point aPnt(rOut.LogicToPixel(aPos + rOfs));
const sal_Int32 xPos(aPnt.X());
const sal_Int32 yPos(aPnt.Y());
const sal_Bool bOldMapModeWasEnabled(rOut.IsMapModeEnabled());
const Size aOutSizePixel(rOut.GetOutputSizePixel());
rOut.EnableMapMode(sal_False);
switch(eKind)
{
case SDRHELPLINE_VERTICAL :
{
ImpDrawDashedTwoColorLine(rOut, 0L, aOutSizePixel.Height(),
xPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_False);
break;
}
case SDRHELPLINE_HORIZONTAL :
{
ImpDrawDashedTwoColorLine(rOut, 0L, aOutSizePixel.Width(),
yPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_True);
break;
}
case SDRHELPLINE_POINT :
{
ImpDrawDashedTwoColorLine(rOut, xPos - SDRHELPLINE_POINT_PIXELSIZE, xPos + SDRHELPLINE_POINT_PIXELSIZE,
yPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_True);
ImpDrawDashedTwoColorLine(rOut, yPos - SDRHELPLINE_POINT_PIXELSIZE, yPos + SDRHELPLINE_POINT_PIXELSIZE,
xPos, 4L , Color(COL_BLACK), Color(COL_WHITE), sal_False);
break;
}
}
rOut.EnableMapMode(bOldMapModeWasEnabled);
}
FASTBOOL SdrHelpLine::IsHit(const Point& rPnt, USHORT nTolLog, const OutputDevice& rOut) const
{
Size a1Pix(rOut.PixelToLogic(Size(1,1)));
FASTBOOL bXHit=rPnt.X()>=aPos.X()-nTolLog && rPnt.X()<=aPos.X()+nTolLog+a1Pix.Width();
FASTBOOL bYHit=rPnt.Y()>=aPos.Y()-nTolLog && rPnt.Y()<=aPos.Y()+nTolLog+a1Pix.Height();
switch (eKind) {
case SDRHELPLINE_VERTICAL : return bXHit;
case SDRHELPLINE_HORIZONTAL: return bYHit;
case SDRHELPLINE_POINT: {
if (bXHit || bYHit) {
Size aRad(rOut.PixelToLogic(Size(SDRHELPLINE_POINT_PIXELSIZE,SDRHELPLINE_POINT_PIXELSIZE)));
return rPnt.X()>=aPos.X()-aRad.Width() && rPnt.X()<=aPos.X()+aRad.Width()+a1Pix.Width() &&
rPnt.Y()>=aPos.Y()-aRad.Height() && rPnt.Y()<=aPos.Y()+aRad.Height()+a1Pix.Height();
}
} break;
} // switch
return FALSE;
}
Rectangle SdrHelpLine::GetBoundRect(const OutputDevice& rOut) const
{
Rectangle aRet(aPos,aPos);
Point aOfs(rOut.GetMapMode().GetOrigin());
Size aSiz(rOut.GetOutputSize());
switch (eKind) {
case SDRHELPLINE_VERTICAL : aRet.Top()=-aOfs.Y(); aRet.Bottom()=-aOfs.Y()+aSiz.Height(); break;
case SDRHELPLINE_HORIZONTAL: aRet.Left()=-aOfs.X(); aRet.Right()=-aOfs.X()+aSiz.Width(); break;
case SDRHELPLINE_POINT : {
Size aRad(rOut.PixelToLogic(Size(SDRHELPLINE_POINT_PIXELSIZE,SDRHELPLINE_POINT_PIXELSIZE)));
aRet.Left() -=aRad.Width();
aRet.Right() +=aRad.Width();
aRet.Top() -=aRad.Height();
aRet.Bottom()+=aRad.Height();
} break;
} // switch
return aRet;
}
bool SdrHelpLine::IsVisibleEqual( const SdrHelpLine& rHelpLine, const OutputDevice& rOut ) const
{
if( eKind == rHelpLine.eKind)
{
Point aPt1(rOut.LogicToPixel(aPos)), aPt2(rOut.LogicToPixel(rHelpLine.aPos));
switch( eKind )
{
case SDRHELPLINE_POINT:
return aPt1 == aPt2;
case SDRHELPLINE_VERTICAL:
return aPt1.X() == aPt2.X();
case SDRHELPLINE_HORIZONTAL:
return aPt1.Y() == aPt2.Y();
}
}
return false;
}
void SdrHelpLineList::Clear()
{
USHORT nAnz=GetCount();
for (USHORT i=0; i<nAnz; i++) {
delete GetObject(i);
}
aList.Clear();
}
void SdrHelpLineList::operator=(const SdrHelpLineList& rSrcList)
{
Clear();
USHORT nAnz=rSrcList.GetCount();
for (USHORT i=0; i<nAnz; i++) {
Insert(rSrcList[i]);
}
}
bool SdrHelpLineList::operator==(const SdrHelpLineList& rSrcList) const
{
FASTBOOL bEqual=FALSE;
USHORT nAnz=GetCount();
if (nAnz==rSrcList.GetCount()) {
bEqual=TRUE;
for (USHORT i=0; i<nAnz && bEqual; i++) {
if (*GetObject(i)!=*rSrcList.GetObject(i)) {
bEqual=FALSE;
}
}
}
return bEqual;
}
void SdrHelpLineList::DrawAll(OutputDevice& rOut, const Point& rOfs) const
{
sal_uInt16 nAnz = GetCount();
sal_uInt16 i,j;
SdrHelpLine *pHL, *pHL2;
for(i=0; i<nAnz; i++)
{
pHL = GetObject(i);
// check if we already drawn a help line like this one
if( pHL )
{
for(j=0;j<i;j++)
{
pHL2 = GetObject(j);
if( pHL2 && pHL->IsVisibleEqual( *pHL2, rOut) )
{
pHL = NULL;
break;
}
}
}
if( pHL )
pHL->Draw(rOut,rOfs);
}
}
USHORT SdrHelpLineList::HitTest(const Point& rPnt, USHORT nTolLog, const OutputDevice& rOut) const
{
USHORT nAnz=GetCount();
for (USHORT i=nAnz; i>0;) {
i--;
if (GetObject(i)->IsHit(rPnt,nTolLog,rOut)) return i;
}
return SDRHELPLINE_NOTFOUND;
}
// eof
<|endoftext|> |
<commit_before>#include "output_test.h"
#include "../src/check.h" // NOTE: check.h is for internal use only!
#include "../src/re.h" // NOTE: re.h is for internal use only
#include <memory>
#include <map>
#include <iostream>
#include <sstream>
// ========================================================================= //
// ------------------------------ Internals -------------------------------- //
// ========================================================================= //
namespace internal { namespace {
using TestCaseList = std::vector<TestCase>;
// Use a vector because the order elements are added matters during iteration.
// std::map/unordered_map don't guarantee that.
// For example:
// SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}});
// Substitute("%HelloWorld") // Always expands to Hello.
using SubMap = std::vector<std::pair<std::string, std::string>>;
TestCaseList& GetTestCaseList(TestCaseID ID) {
// Uses function-local statics to ensure initialization occurs
// before first use.
static TestCaseList lists[TC_NumID];
return lists[ID];
}
SubMap& GetSubstitutions() {
// Don't use 'dec_re' from header because it may not yet be initialized.
static std::string dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?";
static SubMap map = {
{"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"},
{"%int", "[ ]*[0-9]+"},
{" %s ", "[ ]+"},
{"%time", "[ ]*[0-9]{1,5} ns"},
{"%console_report", "[ ]*[0-9]{1,5} ns [ ]*[0-9]{1,5} ns [ ]*[0-9]+"},
{"%csv_report", "[0-9]+," + dec_re + "," + dec_re + ",ns,,,,,"}
};
return map;
}
std::string PerformSubstitutions(std::string source) {
SubMap const& subs = GetSubstitutions();
using SizeT = std::string::size_type;
for (auto const& KV : subs) {
SizeT pos;
SizeT next_start = 0;
while ((pos = source.find(KV.first, next_start)) != std::string::npos) {
next_start = pos + KV.second.size();
source.replace(pos, KV.first.size(), KV.second);
}
}
return source;
}
void CheckCase(std::stringstream& remaining_output, TestCase const& TC,
TestCaseList const& not_checks)
{
std::string first_line;
bool on_first = true;
std::string line;
while (remaining_output.eof() == false) {
CHECK(remaining_output.good());
std::getline(remaining_output, line);
if (on_first) {
first_line = line;
on_first = false;
}
for (auto& NC : not_checks) {
CHECK(!NC.regex->Match(line)) << "Unexpected match for line \""
<< line << "\" for MR_Not regex \""
<< NC.regex_str << "\"";
}
if (TC.regex->Match(line)) return;
CHECK(TC.match_rule != MR_Next) << "Expected line \"" << line
<< "\" to match regex \"" << TC.regex_str << "\"";
}
CHECK(remaining_output.eof() == false)
<< "End of output reached before match for regex \"" << TC.regex_str
<< "\" was found"
<< "\n actual regex string \"" << TC.substituted_regex << "\""
<< "\n started matching near: " << first_line;
}
void CheckCases(TestCaseList const& checks, std::stringstream& output) {
std::vector<TestCase> not_checks;
for (size_t i=0; i < checks.size(); ++i) {
const auto& TC = checks[i];
if (TC.match_rule == MR_Not) {
not_checks.push_back(TC);
continue;
}
CheckCase(output, TC, not_checks);
not_checks.clear();
}
}
class TestReporter : public benchmark::BenchmarkReporter {
public:
TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)
: reporters_(reps) {}
virtual bool ReportContext(const Context& context) {
bool last_ret = false;
bool first = true;
for (auto rep : reporters_) {
bool new_ret = rep->ReportContext(context);
CHECK(first || new_ret == last_ret)
<< "Reports return different values for ReportContext";
first = false;
last_ret = new_ret;
}
return last_ret;
}
void ReportRuns(const std::vector<Run>& report)
{ for (auto rep : reporters_) rep->ReportRuns(report); }
void Finalize() { for (auto rep : reporters_) rep->Finalize(); }
private:
std::vector<benchmark::BenchmarkReporter*> reporters_;
};
}} // end namespace internal
// ========================================================================= //
// -------------------------- Public API Definitions------------------------ //
// ========================================================================= //
TestCase::TestCase(std::string re, int rule)
: regex_str(std::move(re)), match_rule(rule),
substituted_regex(internal::PerformSubstitutions(regex_str)),
regex(std::make_shared<benchmark::Regex>())
{
std::string err_str;
regex->Init(substituted_regex, &err_str);
CHECK(err_str.empty())
<< "Could not construct regex \"" << substituted_regex << "\""
<< "\n originally \"" << regex_str << "\""
<< "\n got error: " << err_str;
}
int AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {
auto& L = internal::GetTestCaseList(ID);
L.insert(L.end(), il);
return 0;
}
int SetSubstitutions(std::initializer_list<std::pair<std::string, std::string>> il) {
auto& subs = internal::GetSubstitutions();
for (auto const& KV : il) {
bool exists = false;
for (auto& EKV : subs) {
if (EKV.first == KV.first) {
EKV.second = KV.second;
exists = true;
break;
}
}
if (!exists) subs.push_back(KV);
}
return 0;
}
void RunOutputTests(int argc, char* argv[]) {
using internal::GetTestCaseList;
benchmark::Initialize(&argc, argv);
benchmark::ConsoleReporter CR(benchmark::ConsoleReporter::OO_None);
benchmark::JSONReporter JR;
benchmark::CSVReporter CSVR;
struct ReporterTest {
const char* name;
std::vector<TestCase>& output_cases;
std::vector<TestCase>& error_cases;
benchmark::BenchmarkReporter& reporter;
std::stringstream out_stream;
std::stringstream err_stream;
ReporterTest(const char* n,
std::vector<TestCase>& out_tc,
std::vector<TestCase>& err_tc,
benchmark::BenchmarkReporter& br)
: name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
reporter.SetOutputStream(&out_stream);
reporter.SetErrorStream(&err_stream);
}
} TestCases[] = {
{"ConsoleReporter", GetTestCaseList(TC_ConsoleOut),
GetTestCaseList(TC_ConsoleErr), CR},
{"JSONReporter", GetTestCaseList(TC_JSONOut),
GetTestCaseList(TC_JSONErr), JR},
{"CSVReporter", GetTestCaseList(TC_CSVOut),
GetTestCaseList(TC_CSVErr), CSVR},
};
// Create the test reporter and run the benchmarks.
std::cout << "Running benchmarks...\n";
internal::TestReporter test_rep({&CR, &JR, &CSVR});
benchmark::RunSpecifiedBenchmarks(&test_rep);
for (auto& rep_test : TestCases) {
std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n";
std::string banner(msg.size() - 1, '-');
std::cout << banner << msg << banner << "\n";
std::cerr << rep_test.err_stream.str();
std::cout << rep_test.out_stream.str();
internal::CheckCases(rep_test.error_cases,rep_test.err_stream);
internal::CheckCases(rep_test.output_cases, rep_test.out_stream);
std::cout << "\n";
}
}
<commit_msg>Improve diagnostic output for output tests.<commit_after>#include "output_test.h"
#include "../src/check.h" // NOTE: check.h is for internal use only!
#include "../src/re.h" // NOTE: re.h is for internal use only
#include <memory>
#include <map>
#include <iostream>
#include <sstream>
// ========================================================================= //
// ------------------------------ Internals -------------------------------- //
// ========================================================================= //
namespace internal { namespace {
using TestCaseList = std::vector<TestCase>;
// Use a vector because the order elements are added matters during iteration.
// std::map/unordered_map don't guarantee that.
// For example:
// SetSubstitutions({{"%HelloWorld", "Hello"}, {"%Hello", "Hi"}});
// Substitute("%HelloWorld") // Always expands to Hello.
using SubMap = std::vector<std::pair<std::string, std::string>>;
TestCaseList& GetTestCaseList(TestCaseID ID) {
// Uses function-local statics to ensure initialization occurs
// before first use.
static TestCaseList lists[TC_NumID];
return lists[ID];
}
SubMap& GetSubstitutions() {
// Don't use 'dec_re' from header because it may not yet be initialized.
static std::string dec_re = "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?";
static SubMap map = {
{"%float", "[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?"},
{"%int", "[ ]*[0-9]+"},
{" %s ", "[ ]+"},
{"%time", "[ ]*[0-9]{1,5} ns"},
{"%console_report", "[ ]*[0-9]{1,5} ns [ ]*[0-9]{1,5} ns [ ]*[0-9]+"},
{"%csv_report", "[0-9]+," + dec_re + "," + dec_re + ",ns,,,,,"}
};
return map;
}
std::string PerformSubstitutions(std::string source) {
SubMap const& subs = GetSubstitutions();
using SizeT = std::string::size_type;
for (auto const& KV : subs) {
SizeT pos;
SizeT next_start = 0;
while ((pos = source.find(KV.first, next_start)) != std::string::npos) {
next_start = pos + KV.second.size();
source.replace(pos, KV.first.size(), KV.second);
}
}
return source;
}
void CheckCase(std::stringstream& remaining_output, TestCase const& TC,
TestCaseList const& not_checks)
{
std::string first_line;
bool on_first = true;
std::string line;
while (remaining_output.eof() == false) {
CHECK(remaining_output.good());
std::getline(remaining_output, line);
if (on_first) {
first_line = line;
on_first = false;
}
for (auto& NC : not_checks) {
CHECK(!NC.regex->Match(line))
<< "Unexpected match for line \"" << line
<< "\" for MR_Not regex \"" << NC.regex_str << "\""
<< "\n actual regex string \"" << TC.substituted_regex << "\""
<< "\n started matching near: " << first_line;
}
if (TC.regex->Match(line)) return;
CHECK(TC.match_rule != MR_Next)
<< "Expected line \"" << line << "\" to match regex \"" << TC.regex_str << "\""
<< "\n actual regex string \"" << TC.substituted_regex << "\""
<< "\n started matching near: " << first_line;
}
CHECK(remaining_output.eof() == false)
<< "End of output reached before match for regex \"" << TC.regex_str
<< "\" was found"
<< "\n actual regex string \"" << TC.substituted_regex << "\""
<< "\n started matching near: " << first_line;
}
void CheckCases(TestCaseList const& checks, std::stringstream& output) {
std::vector<TestCase> not_checks;
for (size_t i=0; i < checks.size(); ++i) {
const auto& TC = checks[i];
if (TC.match_rule == MR_Not) {
not_checks.push_back(TC);
continue;
}
CheckCase(output, TC, not_checks);
not_checks.clear();
}
}
class TestReporter : public benchmark::BenchmarkReporter {
public:
TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)
: reporters_(reps) {}
virtual bool ReportContext(const Context& context) {
bool last_ret = false;
bool first = true;
for (auto rep : reporters_) {
bool new_ret = rep->ReportContext(context);
CHECK(first || new_ret == last_ret)
<< "Reports return different values for ReportContext";
first = false;
last_ret = new_ret;
}
return last_ret;
}
void ReportRuns(const std::vector<Run>& report)
{ for (auto rep : reporters_) rep->ReportRuns(report); }
void Finalize() { for (auto rep : reporters_) rep->Finalize(); }
private:
std::vector<benchmark::BenchmarkReporter*> reporters_;
};
}} // end namespace internal
// ========================================================================= //
// -------------------------- Public API Definitions------------------------ //
// ========================================================================= //
TestCase::TestCase(std::string re, int rule)
: regex_str(std::move(re)), match_rule(rule),
substituted_regex(internal::PerformSubstitutions(regex_str)),
regex(std::make_shared<benchmark::Regex>())
{
std::string err_str;
regex->Init(substituted_regex, &err_str);
CHECK(err_str.empty())
<< "Could not construct regex \"" << substituted_regex << "\""
<< "\n originally \"" << regex_str << "\""
<< "\n got error: " << err_str;
}
int AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {
auto& L = internal::GetTestCaseList(ID);
L.insert(L.end(), il);
return 0;
}
int SetSubstitutions(std::initializer_list<std::pair<std::string, std::string>> il) {
auto& subs = internal::GetSubstitutions();
for (auto const& KV : il) {
bool exists = false;
for (auto& EKV : subs) {
if (EKV.first == KV.first) {
EKV.second = KV.second;
exists = true;
break;
}
}
if (!exists) subs.push_back(KV);
}
return 0;
}
void RunOutputTests(int argc, char* argv[]) {
using internal::GetTestCaseList;
benchmark::Initialize(&argc, argv);
benchmark::ConsoleReporter CR(benchmark::ConsoleReporter::OO_None);
benchmark::JSONReporter JR;
benchmark::CSVReporter CSVR;
struct ReporterTest {
const char* name;
std::vector<TestCase>& output_cases;
std::vector<TestCase>& error_cases;
benchmark::BenchmarkReporter& reporter;
std::stringstream out_stream;
std::stringstream err_stream;
ReporterTest(const char* n,
std::vector<TestCase>& out_tc,
std::vector<TestCase>& err_tc,
benchmark::BenchmarkReporter& br)
: name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {
reporter.SetOutputStream(&out_stream);
reporter.SetErrorStream(&err_stream);
}
} TestCases[] = {
{"ConsoleReporter", GetTestCaseList(TC_ConsoleOut),
GetTestCaseList(TC_ConsoleErr), CR},
{"JSONReporter", GetTestCaseList(TC_JSONOut),
GetTestCaseList(TC_JSONErr), JR},
{"CSVReporter", GetTestCaseList(TC_CSVOut),
GetTestCaseList(TC_CSVErr), CSVR},
};
// Create the test reporter and run the benchmarks.
std::cout << "Running benchmarks...\n";
internal::TestReporter test_rep({&CR, &JR, &CSVR});
benchmark::RunSpecifiedBenchmarks(&test_rep);
for (auto& rep_test : TestCases) {
std::string msg = std::string("\nTesting ") + rep_test.name + " Output\n";
std::string banner(msg.size() - 1, '-');
std::cout << banner << msg << banner << "\n";
std::cerr << rep_test.err_stream.str();
std::cout << rep_test.out_stream.str();
internal::CheckCases(rep_test.error_cases,rep_test.err_stream);
internal::CheckCases(rep_test.output_cases, rep_test.out_stream);
std::cout << "\n";
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdotxln.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: hr $ $Date: 2007-06-27 19:09:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#ifndef _UCBHELPER_CONTENT_HXX_
#include <ucbhelper/content.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX_
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UNOTOOLS_DATETIME_HXX_
#include <unotools/datetime.hxx>
#endif
#include <svx/svdotext.hxx>
#include "svditext.hxx"
#include <svx/svdmodel.hxx>
#include <svx/editdata.hxx>
#ifndef SVX_LIGHT
#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif
#endif
#ifndef _SVXLINKMGR_HXX //autogen
#include <linkmgr.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#include <svtools/urihelper.hxx>
// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
#ifndef SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@@ @@@@@@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@@@@@ @@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@ @@@ @@ @@
// @@@@ @@@@@ @@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
// ImpSdrObjTextLink zur Verbindung von SdrTextObj und LinkManager
//
// Einem solchen Link merke ich mir als SdrObjUserData am Objekt. Im Gegensatz
// zum Grafik-Link werden die ObjektDaten jedoch kopiert (fuer Paint, etc.).
// Die Information ob das Objekt ein Link ist besteht genau darin, dass dem
// Objekt ein entsprechender UserData-Record angehaengt ist oder nicht.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
BOOL Connect() { return 0 != SvBaseLink::GetRealObject(); }
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// pLink des Objekts auf NULL setzen, da die Link-Instanz ja gerade destruiert wird.
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
void ImpSdrObjTextLink::DataChanged( const String& /*rMimeType*/,
const ::com::sun::star::uno::Any & /*rValue */)
{
FASTBOOL bForceReload=FALSE;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
SvxLinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
String aFile;
String aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( !pData->aFileName.Equals( aFile ) ||
!pData->aFilterName.Equals( aFilter ))
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = TRUE;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
}
#endif // SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@@ @@@@@ @@@@@ @@@@ @@@@@@ @@@@
// @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@@@@ @@ @@ @@@@@@ @@ @@@@@@
// @@ @@ @@ @@@ @@@@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@@@@ @@ @@ @@ @@ @@ @@@@ @@@@@ @@@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
#ifndef SVX_LIGHT
delete pLink;
#endif
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@@@ @@@@@ @@ @@ @@@@@@ @@@@ @@@@@ @@@@@@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@@@ @@@ @@ @@ @@ @@@@@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@
// @@ @@@@@ @@ @@ @@ @@@@ @@@@@ @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
void SdrTextObj::SetTextLink(const String& rFileName, const String& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = gsl_getSystemTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
InsertUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
FASTBOOL SdrTextObj::ReloadLinkedText( FASTBOOL bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
FASTBOOL bRet = TRUE;
if( pData )
{
::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get();
DateTime aFileDT;
BOOL bExists = FALSE, bLoad = FALSE;
if( pBroker )
{
bExists = TRUE;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucbhelper::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DateModified" ) ) ) );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = FALSE;
}
}
if( bExists )
{
if( bForceLoad )
bLoad = TRUE;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
FASTBOOL SdrTextObj::LoadText(const String& rFileName, const String& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
BOOL bRet = FALSE;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ );
if( pIStm )
{
// #90477# pIStm->SetStreamCharSet( eCharSet );
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet, (sal_uInt16)pIStm->GetVersion()));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
BOOL bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), sal::static_int_cast< USHORT >( bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT ) );
bRet = TRUE;
}
delete pIStm;
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
ImpSdrObjTextLinkUserData* pData=NULL;
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0 && pData==NULL;) {
nNum--;
pData=(ImpSdrObjTextLinkUserData*)GetUserData(nNum);
if (pData->GetInventor()!=SdrInventor || pData->GetId()!=SDRUSERDATA_OBJTEXTLINK) {
pData=NULL;
}
}
return pData;
}
void SdrTextObj::ImpLinkAnmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // Nicht 2x Anmelden
pData->pLink=new ImpSdrObjTextLink(this);
#ifdef GCC
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ?
&pData->aFilterName : (const String *)NULL,
(const String *)NULL);
#else
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ? &pData->aFilterName : NULL,NULL);
#endif
pData->pLink->Connect();
}
#endif // SVX_LIGHT
}
void SdrTextObj::ImpLinkAbmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // Nicht 2x Abmelden
// Bei Remove wird *pLink implizit deleted
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
#endif // SVX_LIGHT
}
<commit_msg>INTEGRATION: CWS changefileheader (1.16.368); FILE MERGED 2008/04/01 15:51:43 thb 1.16.368.3: #i85898# Stripping all external header guards 2008/04/01 12:50:03 thb 1.16.368.2: #i85898# Stripping all external header guards 2008/03/31 14:23:34 rt 1.16.368.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: svdotxln.cxx,v $
* $Revision: 1.17 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#ifndef _UCBHELPER_CONTENT_HXX_
#include <ucbhelper/content.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX_
#include <ucbhelper/contentbroker.hxx>
#endif
#include <unotools/datetime.hxx>
#include <svx/svdotext.hxx>
#include "svditext.hxx"
#include <svx/svdmodel.hxx>
#include <svx/editdata.hxx>
#ifndef SVX_LIGHT
#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif
#endif
#include <linkmgr.hxx>
#include <tools/urlobj.hxx>
#include <svtools/urihelper.hxx>
// #90477#
#include <tools/tenccvt.hxx>
#ifndef SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@@ @@@@@@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@@@@@ @@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@ @@@ @@ @@
// @@@@ @@@@@ @@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
// ImpSdrObjTextLink zur Verbindung von SdrTextObj und LinkManager
//
// Einem solchen Link merke ich mir als SdrObjUserData am Objekt. Im Gegensatz
// zum Grafik-Link werden die ObjektDaten jedoch kopiert (fuer Paint, etc.).
// Die Information ob das Objekt ein Link ist besteht genau darin, dass dem
// Objekt ein entsprechender UserData-Record angehaengt ist oder nicht.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
BOOL Connect() { return 0 != SvBaseLink::GetRealObject(); }
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// pLink des Objekts auf NULL setzen, da die Link-Instanz ja gerade destruiert wird.
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
void ImpSdrObjTextLink::DataChanged( const String& /*rMimeType*/,
const ::com::sun::star::uno::Any & /*rValue */)
{
FASTBOOL bForceReload=FALSE;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
SvxLinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
String aFile;
String aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( !pData->aFileName.Equals( aFile ) ||
!pData->aFilterName.Equals( aFilter ))
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = TRUE;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
}
#endif // SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@@ @@@@@ @@@@@ @@@@ @@@@@@ @@@@
// @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@@@@ @@ @@ @@@@@@ @@ @@@@@@
// @@ @@ @@ @@@ @@@@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@@@@ @@ @@ @@ @@ @@ @@@@ @@@@@ @@@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
#ifndef SVX_LIGHT
delete pLink;
#endif
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@@@ @@@@@ @@ @@ @@@@@@ @@@@ @@@@@ @@@@@@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@@@ @@@ @@ @@ @@ @@@@@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@
// @@ @@@@@ @@ @@ @@ @@@@ @@@@@ @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
void SdrTextObj::SetTextLink(const String& rFileName, const String& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = gsl_getSystemTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
InsertUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
FASTBOOL SdrTextObj::ReloadLinkedText( FASTBOOL bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
FASTBOOL bRet = TRUE;
if( pData )
{
::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get();
DateTime aFileDT;
BOOL bExists = FALSE, bLoad = FALSE;
if( pBroker )
{
bExists = TRUE;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucbhelper::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DateModified" ) ) ) );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = FALSE;
}
}
if( bExists )
{
if( bForceLoad )
bLoad = TRUE;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
FASTBOOL SdrTextObj::LoadText(const String& rFileName, const String& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
BOOL bRet = FALSE;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ );
if( pIStm )
{
// #90477# pIStm->SetStreamCharSet( eCharSet );
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet, (sal_uInt16)pIStm->GetVersion()));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
BOOL bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), sal::static_int_cast< USHORT >( bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT ) );
bRet = TRUE;
}
delete pIStm;
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
ImpSdrObjTextLinkUserData* pData=NULL;
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0 && pData==NULL;) {
nNum--;
pData=(ImpSdrObjTextLinkUserData*)GetUserData(nNum);
if (pData->GetInventor()!=SdrInventor || pData->GetId()!=SDRUSERDATA_OBJTEXTLINK) {
pData=NULL;
}
}
return pData;
}
void SdrTextObj::ImpLinkAnmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // Nicht 2x Anmelden
pData->pLink=new ImpSdrObjTextLink(this);
#ifdef GCC
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ?
&pData->aFilterName : (const String *)NULL,
(const String *)NULL);
#else
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ? &pData->aFilterName : NULL,NULL);
#endif
pData->pLink->Connect();
}
#endif // SVX_LIGHT
}
void SdrTextObj::ImpLinkAbmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // Nicht 2x Abmelden
// Bei Remove wird *pLink implizit deleted
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
#endif // SVX_LIGHT
}
<|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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hdl>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// remember SPoint-values of current cursor
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// A special treatment for SwFeShell:
// When deleting the header/footer, footnotes SwFeShell sets the
// Cursor to NULL (Node + Content).
// If the Cursor is not on a CntntNode (ContentNode) this fact gets
// saved in NdType.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // see ctor
return ;
// If travelling over Nodes check formats and register them anew at the
// new Node.
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
bool bUpdatedTable = false;
SwFrm *myFrm=pCNd->GetFrm();
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm( );
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
if ( pNode != NULL )
{
SwFrm *myFrm2=pNode->GetFrm();
if (myFrm2!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm2->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
}
if ( bUpdatedTable )
rShell.GetWin( )->Invalidate( 0 );
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// Register the Shell as dependent at the current Node. By doing this all
// attribute changes can be signaled over the link.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
// Every time a switch between nodes occurs, there is a chance that
// new attributes do apply - meaning text-attributes.
// So the currently applying attributes would have to be determined.
// That can be done in one go by the handler.
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// If travelling with left/right only and the frame is
// unchanged (columns!) then check text hints.
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & select
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// If "only start" or "start and end equal" then call on
// every overflow of start.
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// If the attribute has an area and that area is not empty ...
else if( pEnd && nStart < *pEnd &&
// ... then test if travelling occurred via start/end.
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( pBreakIt->GetBreakIter().is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
// If travelling more than one character with home/end/.. then
// always call ChgLnk, because it can not be determined here what
// has changed. Something may have changed.
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
OSL_ENSURE( pIndex, "Fly ohne Cntnt" );
if (!pIndex)
return;
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>SwCallLink: Removed unnecesarry Invalidate() call.<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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hdl>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// remember SPoint-values of current cursor
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// A special treatment for SwFeShell:
// When deleting the header/footer, footnotes SwFeShell sets the
// Cursor to NULL (Node + Content).
// If the Cursor is not on a CntntNode (ContentNode) this fact gets
// saved in NdType.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // see ctor
return ;
// If travelling over Nodes check formats and register them anew at the
// new Node.
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
SwFrm *myFrm=pCNd->GetFrm();
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm( );
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
}
}
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
if ( pNode != NULL )
{
SwFrm *myFrm2=pNode->GetFrm();
if (myFrm2!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm2->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
}
}
}
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// Register the Shell as dependent at the current Node. By doing this all
// attribute changes can be signaled over the link.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
// Every time a switch between nodes occurs, there is a chance that
// new attributes do apply - meaning text-attributes.
// So the currently applying attributes would have to be determined.
// That can be done in one go by the handler.
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// If travelling with left/right only and the frame is
// unchanged (columns!) then check text hints.
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & select
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// If "only start" or "start and end equal" then call on
// every overflow of start.
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// If the attribute has an area and that area is not empty ...
else if( pEnd && nStart < *pEnd &&
// ... then test if travelling occurred via start/end.
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( pBreakIt->GetBreakIter().is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
// If travelling more than one character with home/end/.. then
// always call ChgLnk, because it can not be determined here what
// has changed. Something may have changed.
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
OSL_ENSURE( pIndex, "Fly ohne Cntnt" );
if (!pIndex)
return;
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "quickstarter.hxx"
#include <psapi.h>
#include <tlhelp32.h>
#include <malloc.h>
std::string GetOfficeInstallationPath(MSIHANDLE handle)
{
std::string progpath;
DWORD sz = 0;
LPTSTR dummy = TEXT("");
if (MsiGetProperty(handle, TEXT("OfficeFolder"), dummy, &sz) == ERROR_MORE_DATA)
{
sz++; // space for the final '\0'
DWORD nbytes = sz * sizeof(TCHAR);
LPTSTR buff = reinterpret_cast<LPTSTR>(_alloca(nbytes));
ZeroMemory(buff, nbytes);
MsiGetProperty(handle, TEXT("OfficeFolder"), buff, &sz);
progpath = buff;
}
return progpath;
}
std::string GetOfficeProductName(MSIHANDLE handle)
{
std::string productname;
DWORD sz = 0;
LPTSTR dummy = TEXT("");
if (MsiGetProperty(handle, TEXT("ProductName"), dummy, &sz) == ERROR_MORE_DATA)
{
sz++; // space for the final '\0'
DWORD nbytes = sz * sizeof(TCHAR);
LPTSTR buff = reinterpret_cast<LPTSTR>(_alloca(nbytes));
ZeroMemory(buff, nbytes);
MsiGetProperty(handle, TEXT("ProductName"), buff, &sz);
productname = buff;
}
return productname;
}
inline bool IsValidHandle( HANDLE handle )
{
return NULL != handle && INVALID_HANDLE_VALUE != handle;
}
static HANDLE WINAPI _CreateToolhelp32Snapshot( DWORD dwFlags, DWORD th32ProcessID )
{
typedef HANDLE (WINAPI *FN_PROC)( DWORD dwFlags, DWORD th32ProcessID );
static FN_PROC lpProc = NULL;
HANDLE hSnapshot = NULL;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "CreateToolhelp32Snapshot" ));
}
if ( lpProc )
hSnapshot = lpProc( dwFlags, th32ProcessID );
return hSnapshot;
}
static BOOL WINAPI _Process32First( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 )
{
typedef BOOL (WINAPI *FN_PROC)( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 );
static FN_PROC lpProc = NULL;
BOOL fSuccess = FALSE;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "Process32First" ));
}
if ( lpProc )
fSuccess = lpProc( hSnapshot, lppe32 );
return fSuccess;
}
static BOOL WINAPI _Process32Next( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 )
{
typedef BOOL (WINAPI *FN_PROC)( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 );
static FN_PROC lpProc = NULL;
BOOL fSuccess = FALSE;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "Process32Next" ));
}
if ( lpProc )
fSuccess = lpProc( hSnapshot, lppe32 );
return fSuccess;
}
static std::string GetProcessImagePath_9x( DWORD dwProcessId )
{
std::string sImagePath;
HANDLE hSnapshot = _CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if ( IsValidHandle( hSnapshot ) )
{
PROCESSENTRY32 pe32 = { 0 };
pe32.dwSize = sizeof(PROCESSENTRY32);
BOOL fSuccess = _Process32First( hSnapshot, &pe32 );
bool found = false;
while ( !found && fSuccess )
{
if ( pe32.th32ProcessID == dwProcessId )
{
found = true;
sImagePath = pe32.szExeFile;
}
if ( !found )
fSuccess = _Process32Next( hSnapshot, &pe32 );
}
CloseHandle( hSnapshot );
}
return sImagePath;
}
static DWORD WINAPI _GetModuleFileNameExA( HANDLE hProcess, HMODULE hModule, LPSTR lpFileName, DWORD nSize )
{
typedef DWORD (WINAPI *FN_PROC)( HANDLE hProcess, HMODULE hModule, LPSTR lpFileName, DWORD nSize );
static FN_PROC lpProc = NULL;
if ( !lpProc )
{
HMODULE hLibrary = LoadLibrary("PSAPI.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "GetModuleFileNameExA" ));
}
if ( lpProc )
return lpProc( hProcess, hModule, lpFileName, nSize );
return 0;
}
static std::string GetProcessImagePath_NT( DWORD dwProcessId )
{
std::string sImagePath;
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessId );
if ( IsValidHandle( hProcess ) )
{
CHAR szPathBuffer[MAX_PATH] = "";
if ( _GetModuleFileNameExA( hProcess, NULL, szPathBuffer, sizeof(szPathBuffer) ) )
sImagePath = szPathBuffer;
CloseHandle( hProcess );
}
return sImagePath;
}
std::string GetProcessImagePath( DWORD dwProcessId )
{
return (LONG)GetVersion() < 0 ? GetProcessImagePath_9x( dwProcessId ) : GetProcessImagePath_NT( dwProcessId );
}
<commit_msg>INTEGRATION: CWS customizer (1.2.2); FILE MERGED 2004/08/24 15:52:03 is 1.2.2.1: #i33203# INSTALLLOCATION instead of OfficeFolder<commit_after>#include "quickstarter.hxx"
#include <psapi.h>
#include <tlhelp32.h>
#include <malloc.h>
std::string GetOfficeInstallationPath(MSIHANDLE handle)
{
std::string progpath;
DWORD sz = 0;
LPTSTR dummy = TEXT("");
if (MsiGetProperty(handle, TEXT("INSTALLLOCATION"), dummy, &sz) == ERROR_MORE_DATA)
{
sz++; // space for the final '\0'
DWORD nbytes = sz * sizeof(TCHAR);
LPTSTR buff = reinterpret_cast<LPTSTR>(_alloca(nbytes));
ZeroMemory(buff, nbytes);
MsiGetProperty(handle, TEXT("INSTALLLOCATION"), buff, &sz);
progpath = buff;
}
return progpath;
}
std::string GetOfficeProductName(MSIHANDLE handle)
{
std::string productname;
DWORD sz = 0;
LPTSTR dummy = TEXT("");
if (MsiGetProperty(handle, TEXT("ProductName"), dummy, &sz) == ERROR_MORE_DATA)
{
sz++; // space for the final '\0'
DWORD nbytes = sz * sizeof(TCHAR);
LPTSTR buff = reinterpret_cast<LPTSTR>(_alloca(nbytes));
ZeroMemory(buff, nbytes);
MsiGetProperty(handle, TEXT("ProductName"), buff, &sz);
productname = buff;
}
return productname;
}
inline bool IsValidHandle( HANDLE handle )
{
return NULL != handle && INVALID_HANDLE_VALUE != handle;
}
static HANDLE WINAPI _CreateToolhelp32Snapshot( DWORD dwFlags, DWORD th32ProcessID )
{
typedef HANDLE (WINAPI *FN_PROC)( DWORD dwFlags, DWORD th32ProcessID );
static FN_PROC lpProc = NULL;
HANDLE hSnapshot = NULL;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "CreateToolhelp32Snapshot" ));
}
if ( lpProc )
hSnapshot = lpProc( dwFlags, th32ProcessID );
return hSnapshot;
}
static BOOL WINAPI _Process32First( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 )
{
typedef BOOL (WINAPI *FN_PROC)( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 );
static FN_PROC lpProc = NULL;
BOOL fSuccess = FALSE;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "Process32First" ));
}
if ( lpProc )
fSuccess = lpProc( hSnapshot, lppe32 );
return fSuccess;
}
static BOOL WINAPI _Process32Next( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 )
{
typedef BOOL (WINAPI *FN_PROC)( HANDLE hSnapshot, PROCESSENTRY32 *lppe32 );
static FN_PROC lpProc = NULL;
BOOL fSuccess = FALSE;
if ( !lpProc )
{
HMODULE hLibrary = GetModuleHandle("KERNEL32.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "Process32Next" ));
}
if ( lpProc )
fSuccess = lpProc( hSnapshot, lppe32 );
return fSuccess;
}
static std::string GetProcessImagePath_9x( DWORD dwProcessId )
{
std::string sImagePath;
HANDLE hSnapshot = _CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if ( IsValidHandle( hSnapshot ) )
{
PROCESSENTRY32 pe32 = { 0 };
pe32.dwSize = sizeof(PROCESSENTRY32);
BOOL fSuccess = _Process32First( hSnapshot, &pe32 );
bool found = false;
while ( !found && fSuccess )
{
if ( pe32.th32ProcessID == dwProcessId )
{
found = true;
sImagePath = pe32.szExeFile;
}
if ( !found )
fSuccess = _Process32Next( hSnapshot, &pe32 );
}
CloseHandle( hSnapshot );
}
return sImagePath;
}
static DWORD WINAPI _GetModuleFileNameExA( HANDLE hProcess, HMODULE hModule, LPSTR lpFileName, DWORD nSize )
{
typedef DWORD (WINAPI *FN_PROC)( HANDLE hProcess, HMODULE hModule, LPSTR lpFileName, DWORD nSize );
static FN_PROC lpProc = NULL;
if ( !lpProc )
{
HMODULE hLibrary = LoadLibrary("PSAPI.DLL");
if ( hLibrary )
lpProc = reinterpret_cast< FN_PROC >(GetProcAddress( hLibrary, "GetModuleFileNameExA" ));
}
if ( lpProc )
return lpProc( hProcess, hModule, lpFileName, nSize );
return 0;
}
static std::string GetProcessImagePath_NT( DWORD dwProcessId )
{
std::string sImagePath;
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessId );
if ( IsValidHandle( hProcess ) )
{
CHAR szPathBuffer[MAX_PATH] = "";
if ( _GetModuleFileNameExA( hProcess, NULL, szPathBuffer, sizeof(szPathBuffer) ) )
sImagePath = szPathBuffer;
CloseHandle( hProcess );
}
return sImagePath;
}
std::string GetProcessImagePath( DWORD dwProcessId )
{
return (LONG)GetVersion() < 0 ? GetProcessImagePath_9x( dwProcessId ) : GetProcessImagePath_NT( dwProcessId );
}
<|endoftext|> |
<commit_before>#include "FBVLC_Win.h"
////////////////////////////////////////////////////////////////////////////////
//FBVLC_Win class
////////////////////////////////////////////////////////////////////////////////
FBVLC_Win::FBVLC_Win()
:m_hBgBrush( NULL )
{
vlc_player_options& o = get_options();
COLORREF bg_color = HtmlColor2RGB( o.get_bg_color(), RGB(0, 0, 0) );
m_hBgBrush = CreateSolidBrush( bg_color );
}
FBVLC_Win::~FBVLC_Win()
{
DeleteObject(m_hBgBrush);
}
bool FBVLC_Win::onRefreshEvent(FB::RefreshEvent *evt, FB::PluginWindowlessWin* w)
{
HDC hDC = w->getHDC();
FB::Rect fbRect = evt->bounds;
RECT Rect = {fbRect.left, fbRect.top, fbRect.right, fbRect.bottom};
FillRect(hDC, &Rect, m_hBgBrush);
if ( m_frame_buf.size() &&
m_frame_buf.size() >= m_media_width * m_media_height * DEF_PIXEL_BYTES)
{
HDC hMemDC = CreateCompatibleDC(hDC);
HBITMAP hBmp = CreateCompatibleBitmap(hDC, m_media_width, m_media_height);
BITMAPINFO BmpInfo; ZeroMemory(&BmpInfo, sizeof(BmpInfo));
BITMAPINFOHEADER& BmpH = BmpInfo.bmiHeader;
BmpH.biSize = sizeof(BITMAPINFOHEADER);
BmpH.biWidth = m_media_width;
BmpH.biHeight = m_media_height;
BmpH.biPlanes = 1;
BmpH.biBitCount = DEF_PIXEL_BYTES*8;
BmpH.biCompression = BI_RGB;
//following members are already zeroed
//BmpH.biSizeImage = 0;
//BmpH.biXPelsPerMeter = 0;
//BmpH.biYPelsPerMeter = 0;
//BmpH.biClrUsed = 0;
//BmpH.biClrImportant = 0;
SetDIBits(hMemDC, hBmp, 0, m_media_height,
&m_frame_buf[0], &BmpInfo, DIB_RGB_COLORS);
HBITMAP hOldBmp = (HBITMAP)SelectObject(hMemDC, hBmp);
DeleteObject(hOldBmp);
BOOL r =
StretchBlt( hDC,
fbRect.left + (w->getWindowWidth() - m_media_width)/2,
fbRect.top + (w->getWindowHeight() - m_media_height)/2,
m_media_width, m_media_height,
hMemDC, 0, m_media_height,
m_media_width, -((signed)m_media_height), SRCCOPY);
DeleteDC(hMemDC);
}
return true;
}
void FBVLC_Win::on_option_change(vlc_player_option_e option)
{
FBVLC::on_option_change(option);
vlc_player_options& o = get_options();
switch (option) {
case po_bg_color: {
HBRUSH hTmpBrush = m_hBgBrush;
COLORREF bg_color = HtmlColor2RGB( o.get_bg_color(), RGB(0, 0, 0) );
m_hBgBrush = CreateSolidBrush( bg_color );
DeleteObject(hTmpBrush);
GetWindow()->InvalidateWindow();
break;
}
default:
break;
}
}
<commit_msg>fixed drawing with active scrollbars<commit_after>#include "FBVLC_Win.h"
////////////////////////////////////////////////////////////////////////////////
//FBVLC_Win class
////////////////////////////////////////////////////////////////////////////////
FBVLC_Win::FBVLC_Win()
:m_hBgBrush( NULL )
{
vlc_player_options& o = get_options();
COLORREF bg_color = HtmlColor2RGB( o.get_bg_color(), RGB(0, 0, 0) );
m_hBgBrush = CreateSolidBrush( bg_color );
}
FBVLC_Win::~FBVLC_Win()
{
DeleteObject(m_hBgBrush);
}
bool FBVLC_Win::onRefreshEvent(FB::RefreshEvent *evt, FB::PluginWindowlessWin* w)
{
HDC hDC = w->getHDC();
FB::Rect fbRect = evt->bounds;
RECT Rect = {fbRect.left, fbRect.top, fbRect.right, fbRect.bottom};
FillRect(hDC, &Rect, m_hBgBrush);
if ( m_frame_buf.size() &&
m_frame_buf.size() >= m_media_width * m_media_height * DEF_PIXEL_BYTES)
{
HDC hMemDC = CreateCompatibleDC(hDC);
HBITMAP hBmp = CreateCompatibleBitmap(hDC, m_media_width, m_media_height);
BITMAPINFO BmpInfo; ZeroMemory(&BmpInfo, sizeof(BmpInfo));
BITMAPINFOHEADER& BmpH = BmpInfo.bmiHeader;
BmpH.biSize = sizeof(BITMAPINFOHEADER);
BmpH.biWidth = m_media_width;
BmpH.biHeight = m_media_height;
BmpH.biPlanes = 1;
BmpH.biBitCount = DEF_PIXEL_BYTES*8;
BmpH.biCompression = BI_RGB;
//following members are already zeroed
//BmpH.biSizeImage = 0;
//BmpH.biXPelsPerMeter = 0;
//BmpH.biYPelsPerMeter = 0;
//BmpH.biClrUsed = 0;
//BmpH.biClrImportant = 0;
SetDIBits(hMemDC, hBmp, 0, m_media_height,
&m_frame_buf[0], &BmpInfo, DIB_RGB_COLORS);
HBITMAP hOldBmp = (HBITMAP)SelectObject(hMemDC, hBmp);
DeleteObject(hOldBmp);
FB::Rect wrect = w->getWindowPosition();
BOOL r =
StretchBlt( hDC,
wrect.left + (w->getWindowWidth() - m_media_width)/2,
wrect.top + (w->getWindowHeight() - m_media_height)/2,
m_media_width, m_media_height,
hMemDC, 0, m_media_height,
m_media_width, -((signed)m_media_height), SRCCOPY);
DeleteDC(hMemDC);
}
return true;
}
void FBVLC_Win::on_option_change(vlc_player_option_e option)
{
FBVLC::on_option_change(option);
vlc_player_options& o = get_options();
switch (option) {
case po_bg_color: {
HBRUSH hTmpBrush = m_hBgBrush;
COLORREF bg_color = HtmlColor2RGB( o.get_bg_color(), RGB(0, 0, 0) );
m_hBgBrush = CreateSolidBrush( bg_color );
DeleteObject(hTmpBrush);
GetWindow()->InvalidateWindow();
break;
}
default:
break;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_special_storage_policy.h"
#include "base/bind.h"
#include "base/logging.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/common/content_settings.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
ExtensionSpecialStoragePolicy::ExtensionSpecialStoragePolicy(
HostContentSettingsMap* host_content_settings_map)
: host_content_settings_map_(host_content_settings_map) {}
ExtensionSpecialStoragePolicy::~ExtensionSpecialStoragePolicy() {}
bool ExtensionSpecialStoragePolicy::IsStorageProtected(const GURL& origin) {
if (origin.SchemeIs(chrome::kExtensionScheme))
return true;
base::AutoLock locker(lock_);
return protected_apps_.Contains(origin);
}
bool ExtensionSpecialStoragePolicy::IsStorageUnlimited(const GURL& origin) {
base::AutoLock locker(lock_);
return unlimited_extensions_.Contains(origin);
}
bool ExtensionSpecialStoragePolicy::IsStorageSessionOnly(const GURL& origin) {
if (host_content_settings_map_ == NULL)
return false;
ContentSetting content_setting = host_content_settings_map_->
GetCookieContentSetting(origin, origin, true);
return (content_setting == CONTENT_SETTING_SESSION_ONLY);
}
bool ExtensionSpecialStoragePolicy::HasSessionOnlyOrigins() {
if (host_content_settings_map_ == NULL)
return false;
if (host_content_settings_map_->GetDefaultContentSetting(
CONTENT_SETTINGS_TYPE_COOKIES, NULL) == CONTENT_SETTING_SESSION_ONLY)
return true;
HostContentSettingsMap::SettingsForOneType entries;
host_content_settings_map_->GetSettingsForOneType(
CONTENT_SETTINGS_TYPE_COOKIES, "", &entries);
for (size_t i = 0; i < entries.size(); ++i) {
if (entries[i].c == CONTENT_SETTING_SESSION_ONLY)
return true;
}
return false;
}
bool ExtensionSpecialStoragePolicy::IsFileHandler(
const std::string& extension_id) {
base::AutoLock locker(lock_);
return file_handler_extensions_.ContainsExtension(extension_id);
}
void ExtensionSpecialStoragePolicy::GrantRightsForExtension(
const Extension* extension) {
DCHECK(extension);
if (!extension->is_hosted_app() &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kUnlimitedStorage) &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
return;
}
{
base::AutoLock locker(lock_);
if (extension->is_hosted_app())
protected_apps_.Add(extension);
if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
unlimited_extensions_.Add(extension);
if (extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
file_handler_extensions_.Add(extension);
}
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::RevokeRightsForExtension(
const Extension* extension) {
DCHECK(extension);
if (!extension->is_hosted_app() &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kUnlimitedStorage) &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
return;
}
{
base::AutoLock locker(lock_);
if (extension->is_hosted_app())
protected_apps_.Remove(extension);
if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
unlimited_extensions_.Remove(extension);
if (extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
file_handler_extensions_.Remove(extension);
}
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::RevokeRightsForAllExtensions() {
{
base::AutoLock locker(lock_);
protected_apps_.Clear();
unlimited_extensions_.Clear();
file_handler_extensions_.Clear();
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::NotifyChanged() {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&ExtensionSpecialStoragePolicy::NotifyChanged, this));
return;
}
SpecialStoragePolicy::NotifyObservers();
}
//-----------------------------------------------------------------------------
// SpecialCollection helper class
//-----------------------------------------------------------------------------
ExtensionSpecialStoragePolicy::SpecialCollection::SpecialCollection() {}
ExtensionSpecialStoragePolicy::SpecialCollection::~SpecialCollection() {}
bool ExtensionSpecialStoragePolicy::SpecialCollection::Contains(
const GURL& origin) {
CachedResults::const_iterator found = cached_results_.find(origin);
if (found != cached_results_.end())
return found->second;
for (Extensions::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
if (iter->second->OverlapsWithOrigin(origin)) {
cached_results_[origin] = true;
return true;
}
}
cached_results_[origin] = false;
return false;
}
bool ExtensionSpecialStoragePolicy::SpecialCollection::ContainsExtension(
const std::string& extension_id) {
return extensions_.find(extension_id) != extensions_.end();
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Add(
const Extension* extension) {
cached_results_.clear();
extensions_[extension->id()] = extension;
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Remove(
const Extension* extension) {
cached_results_.clear();
extensions_.erase(extension->id());
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Clear() {
cached_results_.clear();
extensions_.clear();
}
<commit_msg>Don't protect the storage of origins associated with bookmark apps. Review URL: http://codereview.chromium.org/8366022<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_special_storage_policy.h"
#include "base/bind.h"
#include "base/logging.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/common/content_settings.h"
#include "chrome/common/content_settings_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
ExtensionSpecialStoragePolicy::ExtensionSpecialStoragePolicy(
HostContentSettingsMap* host_content_settings_map)
: host_content_settings_map_(host_content_settings_map) {}
ExtensionSpecialStoragePolicy::~ExtensionSpecialStoragePolicy() {}
bool ExtensionSpecialStoragePolicy::IsStorageProtected(const GURL& origin) {
if (origin.SchemeIs(chrome::kExtensionScheme))
return true;
base::AutoLock locker(lock_);
return protected_apps_.Contains(origin);
}
bool ExtensionSpecialStoragePolicy::IsStorageUnlimited(const GURL& origin) {
base::AutoLock locker(lock_);
return unlimited_extensions_.Contains(origin);
}
bool ExtensionSpecialStoragePolicy::IsStorageSessionOnly(const GURL& origin) {
if (host_content_settings_map_ == NULL)
return false;
ContentSetting content_setting = host_content_settings_map_->
GetCookieContentSetting(origin, origin, true);
return (content_setting == CONTENT_SETTING_SESSION_ONLY);
}
bool ExtensionSpecialStoragePolicy::HasSessionOnlyOrigins() {
if (host_content_settings_map_ == NULL)
return false;
if (host_content_settings_map_->GetDefaultContentSetting(
CONTENT_SETTINGS_TYPE_COOKIES, NULL) == CONTENT_SETTING_SESSION_ONLY)
return true;
HostContentSettingsMap::SettingsForOneType entries;
host_content_settings_map_->GetSettingsForOneType(
CONTENT_SETTINGS_TYPE_COOKIES, "", &entries);
for (size_t i = 0; i < entries.size(); ++i) {
if (entries[i].c == CONTENT_SETTING_SESSION_ONLY)
return true;
}
return false;
}
bool ExtensionSpecialStoragePolicy::IsFileHandler(
const std::string& extension_id) {
base::AutoLock locker(lock_);
return file_handler_extensions_.ContainsExtension(extension_id);
}
void ExtensionSpecialStoragePolicy::GrantRightsForExtension(
const Extension* extension) {
DCHECK(extension);
if (!extension->is_hosted_app() &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kUnlimitedStorage) &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
return;
}
{
base::AutoLock locker(lock_);
if (extension->is_hosted_app() && !extension->from_bookmark())
protected_apps_.Add(extension);
if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
unlimited_extensions_.Add(extension);
if (extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
file_handler_extensions_.Add(extension);
}
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::RevokeRightsForExtension(
const Extension* extension) {
DCHECK(extension);
if (!extension->is_hosted_app() &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kUnlimitedStorage) &&
!extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
return;
}
{
base::AutoLock locker(lock_);
if (extension->is_hosted_app() && !extension->from_bookmark())
protected_apps_.Remove(extension);
if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
unlimited_extensions_.Remove(extension);
if (extension->HasAPIPermission(
ExtensionAPIPermission::kFileBrowserHandler)) {
file_handler_extensions_.Remove(extension);
}
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::RevokeRightsForAllExtensions() {
{
base::AutoLock locker(lock_);
protected_apps_.Clear();
unlimited_extensions_.Clear();
file_handler_extensions_.Clear();
}
NotifyChanged();
}
void ExtensionSpecialStoragePolicy::NotifyChanged() {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&ExtensionSpecialStoragePolicy::NotifyChanged, this));
return;
}
SpecialStoragePolicy::NotifyObservers();
}
//-----------------------------------------------------------------------------
// SpecialCollection helper class
//-----------------------------------------------------------------------------
ExtensionSpecialStoragePolicy::SpecialCollection::SpecialCollection() {}
ExtensionSpecialStoragePolicy::SpecialCollection::~SpecialCollection() {}
bool ExtensionSpecialStoragePolicy::SpecialCollection::Contains(
const GURL& origin) {
CachedResults::const_iterator found = cached_results_.find(origin);
if (found != cached_results_.end())
return found->second;
for (Extensions::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
if (iter->second->OverlapsWithOrigin(origin)) {
cached_results_[origin] = true;
return true;
}
}
cached_results_[origin] = false;
return false;
}
bool ExtensionSpecialStoragePolicy::SpecialCollection::ContainsExtension(
const std::string& extension_id) {
return extensions_.find(extension_id) != extensions_.end();
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Add(
const Extension* extension) {
cached_results_.clear();
extensions_[extension->id()] = extension;
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Remove(
const Extension* extension) {
cached_results_.clear();
extensions_.erase(extension->id());
}
void ExtensionSpecialStoragePolicy::SpecialCollection::Clear() {
cached_results_.clear();
extensions_.clear();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edglss.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:08: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
*
************************************************************************/
#pragma hdrstop
#ifndef _OSL_ENDIAN_H_
#include <osl/endian.h>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _CACHESTR_HXX //autogen
#include <tools/cachestr.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer die UndoIds
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx> // fuers kopieren von Tabellen
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx> // SwTextBlocks
#endif
#ifndef _ACORRECT_HXX
#include <acorrect.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h> // SwTextBlocks
#endif
/******************************************************************************
* jetzt mit einem verkappten Reader/Writer/Dokument
******************************************************************************/
void SwEditShell::InsertGlossary( SwTextBlocks& rGlossary, const String& rStr )
{
StartAllAction();
GetDoc()->InsertGlossary( rGlossary, rStr, *GetCrsr(), this );
EndAllAction();
}
/******************************************************************************
* aktuelle Selektion zum Textbaustein machen und ins
* Textbausteindokument einfuegen, einschliesslich Vorlagen
******************************************************************************/
USHORT SwEditShell::MakeGlossary( SwTextBlocks& rBlks, const String& rName, const String& rShortName,
BOOL bSaveRelFile, BOOL bSaveRelNet,
const String* pOnlyTxt )
{
SwDoc* pGDoc = rBlks.GetDoc();
String sBase;
if(bSaveRelFile)
{
INetURLObject aURL( rBlks.GetFileName() );
sBase = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
rBlks.SetBaseURL( sBase );
USHORT nRet;
if( pOnlyTxt )
nRet = rBlks.PutText( rShortName, rName, *pOnlyTxt );
else
{
rBlks.ClearDoc();
if( rBlks.BeginPutDoc( rShortName, rName ) )
{
rBlks.GetDoc()->SetRedlineMode_intern( IDocumentRedlineAccess::REDLINE_DELETE_REDLINES );
_CopySelToDoc( pGDoc );
rBlks.GetDoc()->SetRedlineMode_intern( 0 );
nRet = rBlks.PutDoc();
}
else
nRet = (USHORT) -1;
}
return nRet;
}
USHORT SwEditShell::SaveGlossaryDoc( SwTextBlocks& rBlock,
const String& rName,
const String& rShortName,
BOOL bSaveRelFile, BOOL bSaveRelNet,
BOOL bOnlyTxt )
{
StartAllAction();
SwDoc* pGDoc = rBlock.GetDoc();
SwDoc* pDoc = GetDoc();
String sBase;
if(bSaveRelFile)
{
INetURLObject aURL( rBlock.GetFileName() );
sBase = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
rBlock.SetBaseURL( sBase );
USHORT nRet = USHRT_MAX;
if( bOnlyTxt )
{
KillPams();
SwPaM* pCrsr = GetCrsr();
SwNodeIndex aStt( pDoc->GetNodes().GetEndOfExtras(), 1 );
SwCntntNode* pCntntNd = pDoc->GetNodes().GoNext( &aStt );
const SwNode* pNd = pCntntNd->FindTableNode();
if( !pNd )
pNd = pCntntNd;
pCrsr->GetPoint()->nNode = *pNd;
if( pNd == pCntntNd )
pCrsr->GetPoint()->nContent.Assign( pCntntNd, 0 );
pCrsr->SetMark();
// dann bis zum Ende vom Nodes Array
pCrsr->GetPoint()->nNode = pDoc->GetNodes().GetEndOfContent().GetIndex()-1;
pCntntNd = pCrsr->GetCntntNode();
if( pCntntNd )
pCrsr->GetPoint()->nContent.Assign( pCntntNd, pCntntNd->Len() );
String sBuf;
if( GetSelectedText( sBuf, GETSELTXT_PARABRK_TO_ONLYCR ) && sBuf.Len() )
nRet = rBlock.PutText( rShortName, rName, sBuf );
}
else
{
rBlock.ClearDoc();
if( rBlock.BeginPutDoc( rShortName, rName ) )
{
SwNodeIndex aStt( pDoc->GetNodes().GetEndOfExtras(), 1 );
SwCntntNode* pCntntNd = pDoc->GetNodes().GoNext( &aStt );
const SwNode* pNd = pCntntNd->FindTableNode();
if( !pNd ) pNd = pCntntNd;
SwPaM aCpyPam( *pNd );
aCpyPam.SetMark();
// dann bis zum Ende vom Nodes Array
aCpyPam.GetPoint()->nNode = pDoc->GetNodes().GetEndOfContent().GetIndex()-1;
pCntntNd = aCpyPam.GetCntntNode();
aCpyPam.GetPoint()->nContent.Assign( pCntntNd, pCntntNd->Len() );
aStt = pGDoc->GetNodes().GetEndOfExtras();
pCntntNd = pGDoc->GetNodes().GoNext( &aStt );
SwPosition aInsPos( aStt, SwIndex( pCntntNd ));
pDoc->Copy( aCpyPam, aInsPos );
nRet = rBlock.PutDoc();
}
}
EndAllAction();
return nRet;
}
/******************************************************************************
* kopiere alle Selectionen und das Doc
******************************************************************************/
BOOL SwEditShell::_CopySelToDoc( SwDoc* pInsDoc, SwNodeIndex* pSttNd )
{
ASSERT( pInsDoc, "kein Ins.Dokument" );
SwNodes& rNds = pInsDoc->GetNodes();
SwNodeIndex aIdx( rNds.GetEndOfContent(), -1 );
SwCntntNode * pNd = aIdx.GetNode().GetCntntNode();
SwPosition aPos( aIdx, SwIndex( pNd, pNd->Len() ));
// soll der Index auf Anfang returnt werden ?
if( pSttNd )
{
*pSttNd = aPos.nNode;
(*pSttNd)--;
}
BOOL bRet = FALSE;
SET_CURR_SHELL( this );
pInsDoc->LockExpFlds();
if( IsTableMode() )
{
// kopiere Teile aus einer Tabelle: lege eine Tabelle mit der Breite
// von der Originalen an und kopiere die selectierten Boxen.
// Die Groessen werden prozentual korrigiert.
// lasse ueber das Layout die Boxen suchen
SwTableNode* pTblNd;
SwSelBoxes aBoxes;
GetTblSel( *this, aBoxes );
if( aBoxes.Count() && 0 != (pTblNd = (SwTableNode*)aBoxes[0]
->GetSttNd()->FindTableNode() ))
{
// teste ob der TabellenName kopiert werden kann
BOOL bCpyTblNm = aBoxes.Count() == pTblNd->GetTable().GetTabSortBoxes().Count();
if( bCpyTblNm )
{
const String& rTblName = pTblNd->GetTable().GetFrmFmt()->GetName();
const SwFrmFmts& rTblFmts = *pInsDoc->GetTblFrmFmts();
for( USHORT n = rTblFmts.Count(); n; )
if( rTblFmts[ --n ]->GetName() == rTblName )
{
bCpyTblNm = FALSE;
break;
}
}
bRet = pInsDoc->InsCopyOfTbl( aPos, aBoxes, 0, bCpyTblNm, FALSE );
}
else
bRet = FALSE;
}
else
{
FOREACHPAM_START(this)
if( !PCURCRSR->HasMark() )
{
if( 0 != (pNd = PCURCRSR->GetCntntNode()) && !pNd->GetTxtNode() )
{
PCURCRSR->SetMark();
PCURCRSR->Move( fnMoveForward, fnGoCntnt );
bRet |= GetDoc()->Copy( *PCURCRSR, aPos );
PCURCRSR->Exchange();
PCURCRSR->DeleteMark();
}
}
else
bRet |= GetDoc()->Copy( *PCURCRSR, aPos );
FOREACHPAM_END()
}
pInsDoc->UnlockExpFlds();
if( !pInsDoc->IsExpFldsLocked() )
pInsDoc->UpdateExpFlds(NULL, true);
// die gemerkte Node-Position wieder auf den richtigen Node
if( bRet && pSttNd )
(*pSttNd)++;
return bRet;
}
/*------------------------------------------------------------------------
Beschreibung: Text innerhalb der Selektion erfragen
Returnwert: liefert FALSE, wenn der selektierte Bereich
zu gross ist, um in den Stringpuffer kopiert zu werden.
------------------------------------------------------------------------*/
BOOL SwEditShell::GetSelectedText( String &rBuf, int nHndlParaBrk )
{
BOOL bRet = FALSE;
GetCrsr(); // ggfs. alle Cursor erzeugen lassen
if( IsSelOnePara() )
{
rBuf = GetSelTxt();
if( GETSELTXT_PARABRK_TO_BLANK == nHndlParaBrk )
{
xub_StrLen nPos = 0;
while( STRING_NOTFOUND !=
( nPos = rBuf.SearchAndReplace( 0x0a, ' ', nPos )) )
;
}
else if( IsSelFullPara() &&
GETSELTXT_PARABRK_TO_ONLYCR != nHndlParaBrk )
{
#if defined(MAC)
rBuf += '\015';
#elif defined(UNX)
rBuf += '\012';
#else
rBuf += String::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( "\015\012" ));
#endif
}
bRet = TRUE;
}
else if( IsSelection() )
{
SvCacheStream aStream(20480);
#ifdef OSL_BIGENDIAN
aStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
#else
aStream.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
#endif
WriterRef xWrt;
SwIoSystem::GetWriter( String::CreateFromAscii( FILTER_TEXT ), String(), xWrt );
if( xWrt.Is() )
{
// Selektierte Bereiche in ein ASCII Dokument schreiben
SwWriter aWriter( aStream, *this);
xWrt->SetShowProgress( FALSE );
switch( nHndlParaBrk )
{
case GETSELTXT_PARABRK_TO_BLANK:
xWrt->bASCII_ParaAsBlanc = TRUE;
xWrt->bASCII_NoLastLineEnd = TRUE;
break;
case GETSELTXT_PARABRK_TO_ONLYCR:
xWrt->bASCII_ParaAsCR = TRUE;
xWrt->bASCII_NoLastLineEnd = TRUE;
break;
}
//JP 09.05.00: write as UNICODE ! (and not as ANSI)
SwAsciiOptions aAsciiOpt( xWrt->GetAsciiOptions() );
aAsciiOpt.SetCharSet( RTL_TEXTENCODING_UCS2 );
xWrt->SetAsciiOptions( aAsciiOpt );
xWrt->bUCS2_WithStartChar = FALSE;
long lLen;
if( !IsError( aWriter.Write( xWrt ) ) &&
STRING_MAXLEN > (( lLen = aStream.GetSize() )
/ sizeof( sal_Unicode )) + 1 )
{
aStream << (sal_Unicode)'\0';
const sal_Unicode *p = (sal_Unicode*)aStream.GetBuffer();
if( p )
rBuf = p;
else
{
sal_Unicode* pStrBuf = rBuf.AllocBuffer( xub_StrLen(
( lLen / sizeof( sal_Unicode ))) );
aStream.Seek( 0 );
aStream.ResetError();
aStream.Read( pStrBuf, lLen );
pStrBuf[ lLen / sizeof( sal_Unicode ) ] = '\0';
}
}
}
}
return TRUE;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.11.2); FILE MERGED 2006/09/01 17:51:37 kaib 1.11.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edglss.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:06:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _OSL_ENDIAN_H_
#include <osl/endian.h>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif
#ifndef _CACHESTR_HXX //autogen
#include <tools/cachestr.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#ifndef _EDIMP_HXX
#include <edimp.hxx>
#endif
#ifndef _FRMFMT_HXX //autogen
#include <frmfmt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer die UndoIds
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _SWTABLE_HXX
#include <swtable.hxx> // fuers kopieren von Tabellen
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx> // SwTextBlocks
#endif
#ifndef _ACORRECT_HXX
#include <acorrect.hxx>
#endif
#ifndef _SWSWERROR_H
#include <swerror.h> // SwTextBlocks
#endif
/******************************************************************************
* jetzt mit einem verkappten Reader/Writer/Dokument
******************************************************************************/
void SwEditShell::InsertGlossary( SwTextBlocks& rGlossary, const String& rStr )
{
StartAllAction();
GetDoc()->InsertGlossary( rGlossary, rStr, *GetCrsr(), this );
EndAllAction();
}
/******************************************************************************
* aktuelle Selektion zum Textbaustein machen und ins
* Textbausteindokument einfuegen, einschliesslich Vorlagen
******************************************************************************/
USHORT SwEditShell::MakeGlossary( SwTextBlocks& rBlks, const String& rName, const String& rShortName,
BOOL bSaveRelFile, BOOL bSaveRelNet,
const String* pOnlyTxt )
{
SwDoc* pGDoc = rBlks.GetDoc();
String sBase;
if(bSaveRelFile)
{
INetURLObject aURL( rBlks.GetFileName() );
sBase = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
rBlks.SetBaseURL( sBase );
USHORT nRet;
if( pOnlyTxt )
nRet = rBlks.PutText( rShortName, rName, *pOnlyTxt );
else
{
rBlks.ClearDoc();
if( rBlks.BeginPutDoc( rShortName, rName ) )
{
rBlks.GetDoc()->SetRedlineMode_intern( IDocumentRedlineAccess::REDLINE_DELETE_REDLINES );
_CopySelToDoc( pGDoc );
rBlks.GetDoc()->SetRedlineMode_intern( 0 );
nRet = rBlks.PutDoc();
}
else
nRet = (USHORT) -1;
}
return nRet;
}
USHORT SwEditShell::SaveGlossaryDoc( SwTextBlocks& rBlock,
const String& rName,
const String& rShortName,
BOOL bSaveRelFile, BOOL bSaveRelNet,
BOOL bOnlyTxt )
{
StartAllAction();
SwDoc* pGDoc = rBlock.GetDoc();
SwDoc* pDoc = GetDoc();
String sBase;
if(bSaveRelFile)
{
INetURLObject aURL( rBlock.GetFileName() );
sBase = aURL.GetMainURL( INetURLObject::NO_DECODE );
}
rBlock.SetBaseURL( sBase );
USHORT nRet = USHRT_MAX;
if( bOnlyTxt )
{
KillPams();
SwPaM* pCrsr = GetCrsr();
SwNodeIndex aStt( pDoc->GetNodes().GetEndOfExtras(), 1 );
SwCntntNode* pCntntNd = pDoc->GetNodes().GoNext( &aStt );
const SwNode* pNd = pCntntNd->FindTableNode();
if( !pNd )
pNd = pCntntNd;
pCrsr->GetPoint()->nNode = *pNd;
if( pNd == pCntntNd )
pCrsr->GetPoint()->nContent.Assign( pCntntNd, 0 );
pCrsr->SetMark();
// dann bis zum Ende vom Nodes Array
pCrsr->GetPoint()->nNode = pDoc->GetNodes().GetEndOfContent().GetIndex()-1;
pCntntNd = pCrsr->GetCntntNode();
if( pCntntNd )
pCrsr->GetPoint()->nContent.Assign( pCntntNd, pCntntNd->Len() );
String sBuf;
if( GetSelectedText( sBuf, GETSELTXT_PARABRK_TO_ONLYCR ) && sBuf.Len() )
nRet = rBlock.PutText( rShortName, rName, sBuf );
}
else
{
rBlock.ClearDoc();
if( rBlock.BeginPutDoc( rShortName, rName ) )
{
SwNodeIndex aStt( pDoc->GetNodes().GetEndOfExtras(), 1 );
SwCntntNode* pCntntNd = pDoc->GetNodes().GoNext( &aStt );
const SwNode* pNd = pCntntNd->FindTableNode();
if( !pNd ) pNd = pCntntNd;
SwPaM aCpyPam( *pNd );
aCpyPam.SetMark();
// dann bis zum Ende vom Nodes Array
aCpyPam.GetPoint()->nNode = pDoc->GetNodes().GetEndOfContent().GetIndex()-1;
pCntntNd = aCpyPam.GetCntntNode();
aCpyPam.GetPoint()->nContent.Assign( pCntntNd, pCntntNd->Len() );
aStt = pGDoc->GetNodes().GetEndOfExtras();
pCntntNd = pGDoc->GetNodes().GoNext( &aStt );
SwPosition aInsPos( aStt, SwIndex( pCntntNd ));
pDoc->Copy( aCpyPam, aInsPos );
nRet = rBlock.PutDoc();
}
}
EndAllAction();
return nRet;
}
/******************************************************************************
* kopiere alle Selectionen und das Doc
******************************************************************************/
BOOL SwEditShell::_CopySelToDoc( SwDoc* pInsDoc, SwNodeIndex* pSttNd )
{
ASSERT( pInsDoc, "kein Ins.Dokument" );
SwNodes& rNds = pInsDoc->GetNodes();
SwNodeIndex aIdx( rNds.GetEndOfContent(), -1 );
SwCntntNode * pNd = aIdx.GetNode().GetCntntNode();
SwPosition aPos( aIdx, SwIndex( pNd, pNd->Len() ));
// soll der Index auf Anfang returnt werden ?
if( pSttNd )
{
*pSttNd = aPos.nNode;
(*pSttNd)--;
}
BOOL bRet = FALSE;
SET_CURR_SHELL( this );
pInsDoc->LockExpFlds();
if( IsTableMode() )
{
// kopiere Teile aus einer Tabelle: lege eine Tabelle mit der Breite
// von der Originalen an und kopiere die selectierten Boxen.
// Die Groessen werden prozentual korrigiert.
// lasse ueber das Layout die Boxen suchen
SwTableNode* pTblNd;
SwSelBoxes aBoxes;
GetTblSel( *this, aBoxes );
if( aBoxes.Count() && 0 != (pTblNd = (SwTableNode*)aBoxes[0]
->GetSttNd()->FindTableNode() ))
{
// teste ob der TabellenName kopiert werden kann
BOOL bCpyTblNm = aBoxes.Count() == pTblNd->GetTable().GetTabSortBoxes().Count();
if( bCpyTblNm )
{
const String& rTblName = pTblNd->GetTable().GetFrmFmt()->GetName();
const SwFrmFmts& rTblFmts = *pInsDoc->GetTblFrmFmts();
for( USHORT n = rTblFmts.Count(); n; )
if( rTblFmts[ --n ]->GetName() == rTblName )
{
bCpyTblNm = FALSE;
break;
}
}
bRet = pInsDoc->InsCopyOfTbl( aPos, aBoxes, 0, bCpyTblNm, FALSE );
}
else
bRet = FALSE;
}
else
{
FOREACHPAM_START(this)
if( !PCURCRSR->HasMark() )
{
if( 0 != (pNd = PCURCRSR->GetCntntNode()) && !pNd->GetTxtNode() )
{
PCURCRSR->SetMark();
PCURCRSR->Move( fnMoveForward, fnGoCntnt );
bRet |= GetDoc()->Copy( *PCURCRSR, aPos );
PCURCRSR->Exchange();
PCURCRSR->DeleteMark();
}
}
else
bRet |= GetDoc()->Copy( *PCURCRSR, aPos );
FOREACHPAM_END()
}
pInsDoc->UnlockExpFlds();
if( !pInsDoc->IsExpFldsLocked() )
pInsDoc->UpdateExpFlds(NULL, true);
// die gemerkte Node-Position wieder auf den richtigen Node
if( bRet && pSttNd )
(*pSttNd)++;
return bRet;
}
/*------------------------------------------------------------------------
Beschreibung: Text innerhalb der Selektion erfragen
Returnwert: liefert FALSE, wenn der selektierte Bereich
zu gross ist, um in den Stringpuffer kopiert zu werden.
------------------------------------------------------------------------*/
BOOL SwEditShell::GetSelectedText( String &rBuf, int nHndlParaBrk )
{
BOOL bRet = FALSE;
GetCrsr(); // ggfs. alle Cursor erzeugen lassen
if( IsSelOnePara() )
{
rBuf = GetSelTxt();
if( GETSELTXT_PARABRK_TO_BLANK == nHndlParaBrk )
{
xub_StrLen nPos = 0;
while( STRING_NOTFOUND !=
( nPos = rBuf.SearchAndReplace( 0x0a, ' ', nPos )) )
;
}
else if( IsSelFullPara() &&
GETSELTXT_PARABRK_TO_ONLYCR != nHndlParaBrk )
{
#if defined(MAC)
rBuf += '\015';
#elif defined(UNX)
rBuf += '\012';
#else
rBuf += String::CreateFromAscii(
RTL_CONSTASCII_STRINGPARAM( "\015\012" ));
#endif
}
bRet = TRUE;
}
else if( IsSelection() )
{
SvCacheStream aStream(20480);
#ifdef OSL_BIGENDIAN
aStream.SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );
#else
aStream.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );
#endif
WriterRef xWrt;
SwIoSystem::GetWriter( String::CreateFromAscii( FILTER_TEXT ), String(), xWrt );
if( xWrt.Is() )
{
// Selektierte Bereiche in ein ASCII Dokument schreiben
SwWriter aWriter( aStream, *this);
xWrt->SetShowProgress( FALSE );
switch( nHndlParaBrk )
{
case GETSELTXT_PARABRK_TO_BLANK:
xWrt->bASCII_ParaAsBlanc = TRUE;
xWrt->bASCII_NoLastLineEnd = TRUE;
break;
case GETSELTXT_PARABRK_TO_ONLYCR:
xWrt->bASCII_ParaAsCR = TRUE;
xWrt->bASCII_NoLastLineEnd = TRUE;
break;
}
//JP 09.05.00: write as UNICODE ! (and not as ANSI)
SwAsciiOptions aAsciiOpt( xWrt->GetAsciiOptions() );
aAsciiOpt.SetCharSet( RTL_TEXTENCODING_UCS2 );
xWrt->SetAsciiOptions( aAsciiOpt );
xWrt->bUCS2_WithStartChar = FALSE;
long lLen;
if( !IsError( aWriter.Write( xWrt ) ) &&
STRING_MAXLEN > (( lLen = aStream.GetSize() )
/ sizeof( sal_Unicode )) + 1 )
{
aStream << (sal_Unicode)'\0';
const sal_Unicode *p = (sal_Unicode*)aStream.GetBuffer();
if( p )
rBuf = p;
else
{
sal_Unicode* pStrBuf = rBuf.AllocBuffer( xub_StrLen(
( lLen / sizeof( sal_Unicode ))) );
aStream.Seek( 0 );
aStream.ResetError();
aStream.Read( pStrBuf, lLen );
pStrBuf[ lLen / sizeof( sal_Unicode ) ] = '\0';
}
}
}
}
return TRUE;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include "tangram.h"
#include "platform.h"
#include "gl.h"
#include "util/shaderProgram.h"
#include "util/vertexLayout.h"
#include "util/typedMesh.h"
#include "util/geom.h"
#define KEY_ESC 113 // q
#define KEY_ZOOM_IN 45 // -
#define KEY_ZOOM_OUT 61 // =
#define KEY_UP 119 // w
#define KEY_LEFT 97 // a
#define KEY_RIGHT 115 // s
#define KEY_DOWN 122 // z
struct timeval tv;
typedef struct {
uint32_t screen_width;
uint32_t screen_height;
// OpenGL|ES objects
EGLDisplay display;
EGLSurface surface;
EGLContext context;
} CUBE_STATE_T;
static CUBE_STATE_T _state, *state=&_state;
typedef struct Mouse {
Mouse():x(0),y(0),button(0){};
float x,y;
float velX,velY;
int button;
};
static Mouse mouse;
bool bMouse = false;
float mouseSize = 100.0f;
std::shared_ptr<ShaderProgram> mouseShader;
std::string mouseVertex =
"precision mediump float;\n"
"uniform float u_time;\n"
"uniform vec2 u_mouse;\n"
"uniform vec2 u_resolution;\n"
"attribute vec4 a_position;\n"
"attribute vec4 a_color;\n"
"attribute vec2 a_texcoord;\n"
"varying vec4 v_color;\n"
"varying vec2 v_texcoord;\n"
"void main() {\n"
" v_texcoord = a_texcoord;\n"
" v_color = a_color;\n"
" vec2 mouse = vec2(u_mouse/u_resolution)*4.0-2.0;\n"
" gl_Position = a_position+vec4(mouse,0.0,1.0);\n"
"}\n";
std::string mouseFragment =
"precision mediump float;\n"
"uniform float u_time;\n"
"uniform vec2 u_mouse;\n"
"uniform vec2 u_resolution;\n"
"varying vec4 v_color;\n"
"varying vec2 v_texcoord;\n"
"\n"
"float box(in vec2 _st, in vec2 _size){\n"
" _size = vec2(0.5) - _size*0.5;\n"
" vec2 uv = smoothstep(_size, _size+vec2(0.001), _st);\n"
" uv *= smoothstep(_size, _size+vec2(0.001), vec2(1.0)-_st);\n"
" return uv.x*uv.y;\n"
"}\n"
"\n"
"float cross(in vec2 _st, float _size){\n"
" return box(_st, vec2(_size,_size/6.)) + box(_st, vec2(_size/6.,_size));\n"
"}\n"
"void main() {\n"
" gl_FragColor = v_color * cross(v_texcoord, 0.9 );\n"
"}\n";
struct PosUVColorVertex {
// Position Data
GLfloat pos_x;
GLfloat pos_y;
GLfloat pos_z;
// UV Data
GLfloat texcoord_x;
GLfloat texcoord_y;
// Color Data
GLuint abgr;
};
typedef TypedMesh<PosUVColorVertex> Mesh;
std::shared_ptr<Mesh> mouseMesh;
static void initOpenGL(){
bcm_host_init();
// Clear application state
memset( state, 0, sizeof( *state ) );
int32_t success = 0;
EGLBoolean result;
EGLint num_config;
static EGL_DISPMANX_WINDOW_T nativewindow;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
static const EGLint attribute_list[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
static const EGLint context_attributes[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
EGLConfig config;
// get an EGL display connection
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(state->display!=EGL_NO_DISPLAY);
// initialize the EGL display connection
result = eglInitialize(state->display, NULL, NULL);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(EGL_FALSE != result);
// create an EGL rendering context
state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
assert(state->context!=EGL_NO_CONTEXT);
// create an EGL window surface
success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
assert( success >= 0 );
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = state->screen_width;
dst_rect.height = state->screen_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = state->screen_width << 16;
src_rect.height = state->screen_height << 16;
dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
dispman_update = vc_dispmanx_update_start( 0 );
dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);
nativewindow.element = dispman_element;
nativewindow.width = state->screen_width;
nativewindow.height = state->screen_height;
vc_dispmanx_update_submit_sync( dispman_update );
state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
assert(state->surface != EGL_NO_SURFACE);
// connect the context to the surface
result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
assert(EGL_FALSE != result);
// Set background color and clear buffers
glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );
// Prepare viewport
glViewport( 0, 0, state->screen_width, state->screen_height );
// Prepair Mouse Shader
if (bMouse) {
mouseShader = std::shared_ptr<ShaderProgram>(new ShaderProgram());
mouseShader->setSourceStrings(mouseFragment, mouseVertex );
std::shared_ptr<VertexLayout> vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 3, GL_FLOAT, false, 0},
{"a_texcoord", 2, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0}
}));
std::vector<PosUVColorVertex> vertices;
std::vector<int> indices;
// Small billboard for the mouse
GLuint color = 0xffffffff;
{
float x = -mouseSize*0.5f/state->screen_width;
float y = -mouseSize*0.5f/state->screen_height;
float w = mouseSize/state->screen_width;
float h = mouseSize/state->screen_height;
vertices.push_back({ x, y, 0.0, 0.0, 0.0, color});
vertices.push_back({ x+w, y, 0.0, 0.0, 1.0, color});
vertices.push_back({ x+w, y+h, 0.0, 1.0, 1.0, color});
vertices.push_back({ x, y+h, 0.0, 0.0, 1.0, color });
indices.push_back(0); indices.push_back(1); indices.push_back(2);
indices.push_back(2); indices.push_back(3); indices.push_back(0);
}
mouseMesh = std::shared_ptr<Mesh>(new Mesh(vertexLayout, GL_TRIANGLES));
mouseMesh->addVertices(std::move(vertices), std::move(indices));
mouseMesh->compileVertexBuffer();
}
}
static bool updateMouse(){
static int fd = -1;
const int width=state->screen_width, height=state->screen_height;
//static int x=width, y=height;
const int XSIGN = 1<<4, YSIGN = 1<<5;
if (fd<0) {
fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
}
if (fd>=0) {
// Set values to 0
mouse.velX=0;
mouse.velY=0;
// Extract values from driver
struct {char buttons, dx, dy; } m;
while (1) {
int bytes = read(fd, &m, sizeof m);
if (bytes < (int)sizeof m) {
return false;
} else if (m.buttons&8) {
break; // This bit should always be set
}
read(fd, &m, 1); // Try to sync up again
}
// Set button value
if (m.buttons&3)
mouse.button = m.buttons&3;
else
mouse.button = 0;
// Set deltas
mouse.velX=m.dx;
mouse.velY=m.dy;
if (m.buttons&XSIGN) mouse.velX-=256;
if (m.buttons&YSIGN) mouse.velY-=256;
// Add movement
mouse.x+=mouse.velX;
mouse.y+=mouse.velY;
// Clamp values
if (mouse.x<0) mouse.x=0;
if (mouse.y<0) mouse.y=0;
if (mouse.x>width) mouse.x=width;
if (mouse.y>height) mouse.y=height;
return true;
}
return false;
}
int getkey() {
int character;
struct termios orig_term_attr;
struct termios new_term_attr;
/* set the terminal to raw mode */
tcgetattr(fileno(stdin), &orig_term_attr);
memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
new_term_attr.c_lflag &= ~(ECHO|ICANON);
new_term_attr.c_cc[VTIME] = 0;
new_term_attr.c_cc[VMIN] = 0;
tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
/* read a character from the stdin stream without blocking */
/* returns EOF (-1) if no character is available */
character = fgetc(stdin);
/* restore the original terminal attributes */
tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
return character;
}
//==============================================================================
int main(int argc, char **argv){
for (int i = 1; i < argc ; i++){
if ( std::string(argv[i]) == "-m" ){
bMouse = true;
}
}
// Start OpenGL context
initOpenGL();
// Set background color and clear buffers
Tangram::initialize();
Tangram::resize(state->screen_width, state->screen_height);
// Start clock
gettimeofday(&tv, NULL);
unsigned long long timePrev = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
unsigned long long timeStart = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
bool bContinue = true;
while (bContinue) {
// Update
unsigned long long timeNow = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
double delta = (timeNow - timePrev)*0.001;
float time = (timeNow - timeStart)*0.001;
Tangram::update(delta);
timePrev = timeNow;
if(updateMouse()){
if( mouse.button == 1 ){
Tangram::handlePanGesture( mouse.x-mouse.velX*1.0,
mouse.y+mouse.velY*1.0,
mouse.x,
mouse.y);
} else if( mouse.button == 2 ){
Tangram::handlePinchGesture( 0.0, 0.0, 1.0 + mouse.velY*0.001);
}
}
int key = getkey();
if(key != -1){
switch (key) {
case KEY_ZOOM_IN:
Tangram::handlePinchGesture(0.0,0.0,0.5);
break;
case KEY_ZOOM_OUT:
Tangram::handlePinchGesture(0.0,0.0,2.0);
break;
case KEY_UP:
Tangram::handlePanGesture(0.0,0.0,0.0,100.0);
break;
case KEY_DOWN:
Tangram::handlePanGesture(0.0,0.0,0.0,-100.0);
break;
case KEY_LEFT:
Tangram::handlePanGesture(0.0,0.0,100.0,0.0);
break;
case KEY_RIGHT:
Tangram::handlePanGesture(0.0,0.0,-100.0,0.0);
break;
case KEY_ESC:
bContinue = false;
break;
default:
logMsg(" -> %i\n",key);
}
}
// Render
Tangram::render();
if (bMouse) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
mouseShader->use();
mouseShader->setUniformf("u_time", time);
mouseShader->setUniformf("u_mouse", mouse.x, mouse.y);
mouseShader->setUniformf("u_resolution",state->screen_width, state->screen_height);
mouseMesh->draw(mouseShader);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}
eglSwapBuffers(state->display, state->surface);
}
Tangram::teardown();
return 0;
}
<commit_msg>fixing zoom from the center on RPI when dragging w right buttom<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include "tangram.h"
#include "platform.h"
#include "gl.h"
#include "util/shaderProgram.h"
#include "util/vertexLayout.h"
#include "util/typedMesh.h"
#include "util/geom.h"
#define KEY_ESC 113 // q
#define KEY_ZOOM_IN 45 // -
#define KEY_ZOOM_OUT 61 // =
#define KEY_UP 119 // w
#define KEY_LEFT 97 // a
#define KEY_RIGHT 115 // s
#define KEY_DOWN 122 // z
struct timeval tv;
typedef struct {
uint32_t screen_width;
uint32_t screen_height;
// OpenGL|ES objects
EGLDisplay display;
EGLSurface surface;
EGLContext context;
} CUBE_STATE_T;
static CUBE_STATE_T _state, *state=&_state;
typedef struct Mouse {
Mouse():x(0),y(0),button(0){};
float x,y;
float velX,velY;
int button;
};
static Mouse mouse;
bool bMouse = false;
float mouseSize = 100.0f;
std::shared_ptr<ShaderProgram> mouseShader;
std::string mouseVertex =
"precision mediump float;\n"
"uniform float u_time;\n"
"uniform vec2 u_mouse;\n"
"uniform vec2 u_resolution;\n"
"attribute vec4 a_position;\n"
"attribute vec4 a_color;\n"
"attribute vec2 a_texcoord;\n"
"varying vec4 v_color;\n"
"varying vec2 v_texcoord;\n"
"void main() {\n"
" v_texcoord = a_texcoord;\n"
" v_color = a_color;\n"
" vec2 mouse = vec2(u_mouse/u_resolution)*4.0-2.0;\n"
" gl_Position = a_position+vec4(mouse,0.0,1.0);\n"
"}\n";
std::string mouseFragment =
"precision mediump float;\n"
"uniform float u_time;\n"
"uniform vec2 u_mouse;\n"
"uniform vec2 u_resolution;\n"
"varying vec4 v_color;\n"
"varying vec2 v_texcoord;\n"
"\n"
"float box(in vec2 _st, in vec2 _size){\n"
" _size = vec2(0.5) - _size*0.5;\n"
" vec2 uv = smoothstep(_size, _size+vec2(0.001), _st);\n"
" uv *= smoothstep(_size, _size+vec2(0.001), vec2(1.0)-_st);\n"
" return uv.x*uv.y;\n"
"}\n"
"\n"
"float cross(in vec2 _st, float _size){\n"
" return box(_st, vec2(_size,_size/6.)) + box(_st, vec2(_size/6.,_size));\n"
"}\n"
"void main() {\n"
" gl_FragColor = v_color * cross(v_texcoord, 0.9 );\n"
"}\n";
struct PosUVColorVertex {
// Position Data
GLfloat pos_x;
GLfloat pos_y;
GLfloat pos_z;
// UV Data
GLfloat texcoord_x;
GLfloat texcoord_y;
// Color Data
GLuint abgr;
};
typedef TypedMesh<PosUVColorVertex> Mesh;
std::shared_ptr<Mesh> mouseMesh;
static void initOpenGL(){
bcm_host_init();
// Clear application state
memset( state, 0, sizeof( *state ) );
int32_t success = 0;
EGLBoolean result;
EGLint num_config;
static EGL_DISPMANX_WINDOW_T nativewindow;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
static const EGLint attribute_list[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
static const EGLint context_attributes[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
EGLConfig config;
// get an EGL display connection
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(state->display!=EGL_NO_DISPLAY);
// initialize the EGL display connection
result = eglInitialize(state->display, NULL, NULL);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(EGL_FALSE != result);
// create an EGL rendering context
state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
assert(state->context!=EGL_NO_CONTEXT);
// create an EGL window surface
success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
assert( success >= 0 );
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = state->screen_width;
dst_rect.height = state->screen_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = state->screen_width << 16;
src_rect.height = state->screen_height << 16;
dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
dispman_update = vc_dispmanx_update_start( 0 );
dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);
nativewindow.element = dispman_element;
nativewindow.width = state->screen_width;
nativewindow.height = state->screen_height;
vc_dispmanx_update_submit_sync( dispman_update );
state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
assert(state->surface != EGL_NO_SURFACE);
// connect the context to the surface
result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
assert(EGL_FALSE != result);
// Set background color and clear buffers
glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );
// Prepare viewport
glViewport( 0, 0, state->screen_width, state->screen_height );
// Prepair Mouse Shader
if (bMouse) {
mouseShader = std::shared_ptr<ShaderProgram>(new ShaderProgram());
mouseShader->setSourceStrings(mouseFragment, mouseVertex );
std::shared_ptr<VertexLayout> vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 3, GL_FLOAT, false, 0},
{"a_texcoord", 2, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0}
}));
std::vector<PosUVColorVertex> vertices;
std::vector<int> indices;
// Small billboard for the mouse
GLuint color = 0xffffffff;
{
float x = -mouseSize*0.5f/state->screen_width;
float y = -mouseSize*0.5f/state->screen_height;
float w = mouseSize/state->screen_width;
float h = mouseSize/state->screen_height;
vertices.push_back({ x, y, 0.0, 0.0, 0.0, color});
vertices.push_back({ x+w, y, 0.0, 0.0, 1.0, color});
vertices.push_back({ x+w, y+h, 0.0, 1.0, 1.0, color});
vertices.push_back({ x, y+h, 0.0, 0.0, 1.0, color });
indices.push_back(0); indices.push_back(1); indices.push_back(2);
indices.push_back(2); indices.push_back(3); indices.push_back(0);
}
mouseMesh = std::shared_ptr<Mesh>(new Mesh(vertexLayout, GL_TRIANGLES));
mouseMesh->addVertices(std::move(vertices), std::move(indices));
mouseMesh->compileVertexBuffer();
}
}
static bool updateMouse(){
static int fd = -1;
const int width=state->screen_width, height=state->screen_height;
//static int x=width, y=height;
const int XSIGN = 1<<4, YSIGN = 1<<5;
if (fd<0) {
fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
}
if (fd>=0) {
// Set values to 0
mouse.velX=0;
mouse.velY=0;
// Extract values from driver
struct {char buttons, dx, dy; } m;
while (1) {
int bytes = read(fd, &m, sizeof m);
if (bytes < (int)sizeof m) {
return false;
} else if (m.buttons&8) {
break; // This bit should always be set
}
read(fd, &m, 1); // Try to sync up again
}
// Set button value
if (m.buttons&3)
mouse.button = m.buttons&3;
else
mouse.button = 0;
// Set deltas
mouse.velX=m.dx;
mouse.velY=m.dy;
if (m.buttons&XSIGN) mouse.velX-=256;
if (m.buttons&YSIGN) mouse.velY-=256;
// Add movement
mouse.x+=mouse.velX;
mouse.y+=mouse.velY;
// Clamp values
if (mouse.x<0) mouse.x=0;
if (mouse.y<0) mouse.y=0;
if (mouse.x>width) mouse.x=width;
if (mouse.y>height) mouse.y=height;
return true;
}
return false;
}
int getkey() {
int character;
struct termios orig_term_attr;
struct termios new_term_attr;
/* set the terminal to raw mode */
tcgetattr(fileno(stdin), &orig_term_attr);
memcpy(&new_term_attr, &orig_term_attr, sizeof(struct termios));
new_term_attr.c_lflag &= ~(ECHO|ICANON);
new_term_attr.c_cc[VTIME] = 0;
new_term_attr.c_cc[VMIN] = 0;
tcsetattr(fileno(stdin), TCSANOW, &new_term_attr);
/* read a character from the stdin stream without blocking */
/* returns EOF (-1) if no character is available */
character = fgetc(stdin);
/* restore the original terminal attributes */
tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
return character;
}
//==============================================================================
int main(int argc, char **argv){
for (int i = 1; i < argc ; i++){
if ( std::string(argv[i]) == "-m" ){
bMouse = true;
}
}
// Start OpenGL context
initOpenGL();
// Set background color and clear buffers
Tangram::initialize();
Tangram::resize(state->screen_width, state->screen_height);
// Start clock
gettimeofday(&tv, NULL);
unsigned long long timePrev = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
unsigned long long timeStart = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
bool bContinue = true;
while (bContinue) {
// Update
unsigned long long timeNow = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000;
double delta = (timeNow - timePrev)*0.001;
float time = (timeNow - timeStart)*0.001;
Tangram::update(delta);
timePrev = timeNow;
if(updateMouse()){
if( mouse.button == 1 ){
Tangram::handlePanGesture( mouse.x-mouse.velX*1.0,
mouse.y+mouse.velY*1.0,
mouse.x,
mouse.y);
} else if( mouse.button == 2 ){
Tangram::handlePinchGesture( state->screen_width/2.0, state->screen_height/2.0, 1.0 + mouse.velY*0.001);
}
}
int key = getkey();
if(key != -1){
switch (key) {
case KEY_ZOOM_IN:
Tangram::handlePinchGesture(0.0,0.0,0.5);
break;
case KEY_ZOOM_OUT:
Tangram::handlePinchGesture(0.0,0.0,2.0);
break;
case KEY_UP:
Tangram::handlePanGesture(0.0,0.0,0.0,100.0);
break;
case KEY_DOWN:
Tangram::handlePanGesture(0.0,0.0,0.0,-100.0);
break;
case KEY_LEFT:
Tangram::handlePanGesture(0.0,0.0,100.0,0.0);
break;
case KEY_RIGHT:
Tangram::handlePanGesture(0.0,0.0,-100.0,0.0);
break;
case KEY_ESC:
bContinue = false;
break;
default:
logMsg(" -> %i\n",key);
}
}
// Render
Tangram::render();
if (bMouse) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
mouseShader->use();
mouseShader->setUniformf("u_time", time);
mouseShader->setUniformf("u_mouse", mouse.x, mouse.y);
mouseShader->setUniformf("u_resolution",state->screen_width, state->screen_height);
mouseMesh->draw(mouseShader);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}
eglSwapBuffers(state->display, state->surface);
}
Tangram::teardown();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/time.h"
#include "base/waitable_event.h"
#include "chrome/browser/sync/engine/syncapi.h"
#include "chrome/browser/sync/glue/autofill_change_processor.h"
#include "chrome/browser/sync/glue/autofill_data_type_controller.h"
#include "chrome/browser/sync/glue/autofill_model_associator.h"
#include "chrome/browser/sync/glue/sync_backend_host.h"
#include "chrome/browser/sync/profile_sync_factory.h"
#include "chrome/browser/sync/profile_sync_factory_mock.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_test_util.h"
#include "chrome/browser/sync/protocol/autofill_specifics.pb.h"
#include "chrome/browser/sync/test_profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gmock/include/gmock/gmock.h"
using base::Time;
using base::WaitableEvent;
using browser_sync::AutofillChangeProcessor;
using browser_sync::AutofillDataTypeController;
using browser_sync::AutofillModelAssociator;
using browser_sync::SyncBackendHost;
using browser_sync::UnrecoverableErrorHandler;
using sync_api::SyncManager;
using testing::_;
using testing::DoAll;
using testing::DoDefault;
using testing::Return;
using testing::SetArgumentPointee;
class TestAutofillModelAssociator
: public TestModelAssociator<AutofillModelAssociator> {
public:
TestAutofillModelAssociator(ProfileSyncService* service,
WebDatabase* web_database,
UnrecoverableErrorHandler* error_handler)
: TestModelAssociator<AutofillModelAssociator>(
service, web_database, error_handler) {
}
};
class WebDatabaseMock : public WebDatabase {
public:
MOCK_METHOD2(RemoveFormElement,
bool(const string16& name, const string16& value));
MOCK_METHOD1(GetAllAutofillEntries,
bool(std::vector<AutofillEntry>* entries));
MOCK_METHOD3(GetAutofillTimestamps,
bool(const string16& name,
const string16& value,
std::vector<base::Time>* timestamps));
MOCK_METHOD1(UpdateAutofillEntries,
bool(const std::vector<AutofillEntry>& entries));
};
class ProfileMock : public TestingProfile {
public:
MOCK_METHOD1(GetWebDataService, WebDataService*(ServiceAccessType access));
};
class DBThreadNotificationService :
public base::RefCountedThreadSafe<DBThreadNotificationService> {
public:
DBThreadNotificationService() : done_event_(false, false) {}
void Init() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &DBThreadNotificationService::InitTask));
done_event_.Wait();
}
void TearDown() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &DBThreadNotificationService::TearDownTask));
done_event_.Wait();
}
private:
friend class base::RefCountedThreadSafe<DBThreadNotificationService>;
void InitTask() {
service_.reset(new NotificationService());
done_event_.Signal();
}
void TearDownTask() {
service_.reset(NULL);
done_event_.Signal();
}
WaitableEvent done_event_;
scoped_ptr<NotificationService> service_;
};
class WebDataServiceFake : public WebDataService {
public:
virtual bool IsDatabaseLoaded() {
return true;
}
// Note that we inject the WebDatabase through the
// ProfileSyncFactory mock.
virtual WebDatabase* GetDatabase() {
return NULL;
}
};
ACTION(QuitUIMessageLoop) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoop::current()->Quit();
}
ACTION_P3(MakeAutofillSyncComponents, service, wd, dtc) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
AutofillModelAssociator* model_associator =
new TestAutofillModelAssociator(service, wd, dtc);
AutofillChangeProcessor* change_processor =
new AutofillChangeProcessor(model_associator, wd, service);
return ProfileSyncFactory::SyncComponents(model_associator, change_processor);
}
class ProfileSyncServiceAutofillTest : public testing::Test {
protected:
ProfileSyncServiceAutofillTest()
: ui_thread_(ChromeThread::UI, &message_loop_),
db_thread_(ChromeThread::DB),
done_event_(false, false) {
}
virtual void SetUp() {
web_data_service_ = new WebDataServiceFake();
db_thread_.Start();
notification_service_ = new DBThreadNotificationService();
notification_service_->Init();
}
virtual void TearDown() {
service_.reset();
notification_service_->TearDown();
db_thread_.Stop();
MessageLoop::current()->RunAllPending();
}
void StartSyncService() {
if (!service_.get()) {
service_.reset(new TestProfileSyncService(&factory_, &profile_, false));
service_->AddObserver(&observer_);
AutofillDataTypeController* data_type_controller =
new AutofillDataTypeController(&factory_,
&profile_,
service_.get());
EXPECT_CALL(factory_, CreateAutofillSyncComponents(_, _, _)).
WillOnce(MakeAutofillSyncComponents(service_.get(),
&web_database_,
data_type_controller));
EXPECT_CALL(factory_, CreateDataTypeManager(_)).
WillOnce(MakeDataTypeManager());
EXPECT_CALL(profile_, GetWebDataService(_)).
WillOnce(Return(web_data_service_.get()));
// State changes once for the backend init and once for startup done.
EXPECT_CALL(observer_, OnStateChanged()).
WillOnce(DoDefault()).
WillOnce(QuitUIMessageLoop());
service_->RegisterDataTypeController(data_type_controller);
service_->Initialize();
MessageLoop::current()->Run();
}
}
void GetAutofillEntriesFromSyncDB(std::vector<AutofillEntry>* entries) {
sync_api::ReadTransaction trans(service_->backend()->GetUserShareHandle());
int64 autofill_root_id =
GetFakeServerTaggedNode(&trans, "google_chrome_autofill");
if (autofill_root_id == sync_api::kInvalidId)
return;
sync_api::ReadNode autofill_root(&trans);
if (!autofill_root.InitByIdLookup(autofill_root_id))
return;
int64 child_id = autofill_root.GetFirstChildId();
while (child_id != sync_api::kInvalidId) {
sync_api::ReadNode child_node(&trans);
if (!child_node.InitByIdLookup(child_id))
return;
const sync_pb::AutofillSpecifics& autofill(
child_node.GetAutofillSpecifics());
AutofillKey key(UTF8ToUTF16(autofill.name()),
UTF8ToUTF16(autofill.value()));
std::vector<base::Time> timestamps;
int timestamps_count = autofill.usage_timestamp_size();
for (int i = 0; i < timestamps_count; ++i) {
timestamps.push_back(Time::FromInternalValue(
autofill.usage_timestamp(i)));
}
entries->push_back(AutofillEntry(key, timestamps));
child_id = child_node.GetSuccessorId();
}
}
int64 GetFakeServerTaggedNode(sync_api::ReadTransaction* trans,
const std::string& tag) {
std::wstring tag_wide;
if (!UTF8ToWide(tag.c_str(), tag.length(), &tag_wide))
return sync_api::kInvalidId;
sync_api::ReadNode root(trans);
root.InitByRootLookup();
int64 last_child_id = sync_api::kInvalidId;
for (int64 id = root.GetFirstChildId(); id != sync_api::kInvalidId; /***/) {
sync_api::ReadNode child(trans);
child.InitByIdLookup(id);
last_child_id = id;
if (tag_wide == child.GetTitle()) {
return id;
}
id = child.GetSuccessorId();
}
return sync_api::kInvalidId;
}
void SetIdleChangeProcessorExpectations() {
EXPECT_CALL(web_database_, RemoveFormElement(_, _)).Times(0);
EXPECT_CALL(web_database_, GetAutofillTimestamps(_, _, _)).Times(0);
EXPECT_CALL(web_database_, UpdateAutofillEntries(_)).Times(0);
}
static AutofillEntry MakeAutofillEntry(const char* name,
const char* value,
time_t timestamp) {
std::vector<Time> timestamps;
timestamps.push_back(Time::FromTimeT(timestamp));
return AutofillEntry(
AutofillKey(ASCIIToUTF16(name), ASCIIToUTF16(value)), timestamps);
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
ChromeThread db_thread_;
WaitableEvent done_event_;
scoped_refptr<DBThreadNotificationService> notification_service_;
scoped_ptr<TestProfileSyncService> service_;
ProfileMock profile_;
ProfileSyncFactoryMock factory_;
ProfileSyncServiceObserverMock observer_;
WebDatabaseMock web_database_;
scoped_refptr<WebDataService> web_data_service_;
};
// TODO(sync): Test unrecoverable error during MA.
// http://code.google.com/p/chromium/issues/detail?id=37244
TEST_F(ProfileSyncServiceAutofillTest, DISABLED_EmptyNativeEmptySync) {
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).WillOnce(Return(true));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
EXPECT_EQ(0U, sync_entries.size());
}
// http://code.google.com/p/chromium/issues/detail?id=37244
TEST_F(ProfileSyncServiceAutofillTest, DISABLED_HasNativeEmptySync) {
std::vector<AutofillEntry> entries;
entries.push_back(MakeAutofillEntry("foo", "bar", 1));
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).
WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
ASSERT_EQ(1U, entries.size());
EXPECT_TRUE(entries[0] == sync_entries[0]);
}
// http://code.google.com/p/chromium/issues/detail?id=37244
TEST_F(ProfileSyncServiceAutofillTest, DISABLED_HasNativeWithDuplicatesEmptySync) {
// There is buggy autofill code that allows duplicate name/value
// pairs to exist in the database with separate pair_ids.
std::vector<AutofillEntry> entries;
entries.push_back(MakeAutofillEntry("foo", "bar", 1));
entries.push_back(MakeAutofillEntry("dup", "", 2));
entries.push_back(MakeAutofillEntry("dup", "", 3));
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).
WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
EXPECT_EQ(2U, sync_entries.size());
}
<commit_msg>Fix autofill test hang The common TestProfileSyncService did some unexpected things with message loops, so use a custom version for this test. Hopfully in a more testable future we won't need magic testing classes such as this.<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 <vector>
#include "testing/gtest/include/gtest/gtest.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/time.h"
#include "base/waitable_event.h"
#include "chrome/browser/sync/engine/syncapi.h"
#include "chrome/browser/sync/glue/autofill_change_processor.h"
#include "chrome/browser/sync/glue/autofill_data_type_controller.h"
#include "chrome/browser/sync/glue/autofill_model_associator.h"
#include "chrome/browser/sync/glue/sync_backend_host.h"
#include "chrome/browser/sync/profile_sync_factory.h"
#include "chrome/browser/sync/profile_sync_factory_mock.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_test_util.h"
#include "chrome/browser/sync/protocol/autofill_specifics.pb.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gmock/include/gmock/gmock.h"
using base::Time;
using base::WaitableEvent;
using browser_sync::AutofillChangeProcessor;
using browser_sync::AutofillDataTypeController;
using browser_sync::AutofillModelAssociator;
using browser_sync::SyncBackendHost;
using browser_sync::UnrecoverableErrorHandler;
using sync_api::SyncManager;
using testing::_;
using testing::DoAll;
using testing::DoDefault;
using testing::Return;
using testing::SetArgumentPointee;
class TestingProfileSyncService : public ProfileSyncService {
public:
explicit TestingProfileSyncService(ProfileSyncFactory* factory,
Profile* profile,
bool bootstrap_sync_authentication)
: ProfileSyncService(factory, profile, bootstrap_sync_authentication) {
RegisterPreferences();
SetSyncSetupCompleted();
}
virtual ~TestingProfileSyncService() {
}
virtual void InitializeBackend(bool delete_sync_data_folder) {
browser_sync::TestHttpBridgeFactory* factory =
new browser_sync::TestHttpBridgeFactory();
browser_sync::TestHttpBridgeFactory* factory2 =
new browser_sync::TestHttpBridgeFactory();
backend()->InitializeForTestMode(L"testuser", factory, factory2,
delete_sync_data_folder, browser_sync::kDefaultNotificationMethod);
}
private:
// When testing under ChromiumOS, this method must not return an empty
// value value in order for the profile sync service to start.
virtual std::string GetLsidForAuthBootstraping() {
return "foo";
}
};
class TestAutofillModelAssociator
: public TestModelAssociator<AutofillModelAssociator> {
public:
TestAutofillModelAssociator(ProfileSyncService* service,
WebDatabase* web_database,
UnrecoverableErrorHandler* error_handler)
: TestModelAssociator<AutofillModelAssociator>(
service, web_database, error_handler) {
}
};
class WebDatabaseMock : public WebDatabase {
public:
MOCK_METHOD2(RemoveFormElement,
bool(const string16& name, const string16& value));
MOCK_METHOD1(GetAllAutofillEntries,
bool(std::vector<AutofillEntry>* entries));
MOCK_METHOD3(GetAutofillTimestamps,
bool(const string16& name,
const string16& value,
std::vector<base::Time>* timestamps));
MOCK_METHOD1(UpdateAutofillEntries,
bool(const std::vector<AutofillEntry>& entries));
};
class ProfileMock : public TestingProfile {
public:
MOCK_METHOD1(GetWebDataService, WebDataService*(ServiceAccessType access));
};
class DBThreadNotificationService :
public base::RefCountedThreadSafe<DBThreadNotificationService> {
public:
DBThreadNotificationService() : done_event_(false, false) {}
void Init() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &DBThreadNotificationService::InitTask));
done_event_.Wait();
}
void TearDown() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &DBThreadNotificationService::TearDownTask));
done_event_.Wait();
}
private:
friend class base::RefCountedThreadSafe<DBThreadNotificationService>;
void InitTask() {
service_.reset(new NotificationService());
done_event_.Signal();
}
void TearDownTask() {
service_.reset(NULL);
done_event_.Signal();
}
WaitableEvent done_event_;
scoped_ptr<NotificationService> service_;
};
class WebDataServiceFake : public WebDataService {
public:
virtual bool IsDatabaseLoaded() {
return true;
}
// Note that we inject the WebDatabase through the
// ProfileSyncFactory mock.
virtual WebDatabase* GetDatabase() {
return NULL;
}
};
ACTION(QuitUIMessageLoop) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
MessageLoop::current()->Quit();
}
ACTION_P3(MakeAutofillSyncComponents, service, wd, dtc) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
AutofillModelAssociator* model_associator =
new TestAutofillModelAssociator(service, wd, dtc);
AutofillChangeProcessor* change_processor =
new AutofillChangeProcessor(model_associator, wd, service);
return ProfileSyncFactory::SyncComponents(model_associator, change_processor);
}
class ProfileSyncServiceAutofillTest : public testing::Test {
protected:
ProfileSyncServiceAutofillTest()
: ui_thread_(ChromeThread::UI, &message_loop_),
db_thread_(ChromeThread::DB),
done_event_(false, false) {
}
virtual void SetUp() {
web_data_service_ = new WebDataServiceFake();
db_thread_.Start();
notification_service_ = new DBThreadNotificationService();
notification_service_->Init();
}
virtual void TearDown() {
service_.reset();
notification_service_->TearDown();
db_thread_.Stop();
MessageLoop::current()->RunAllPending();
}
void StartSyncService() {
if (!service_.get()) {
service_.reset(
new TestingProfileSyncService(&factory_, &profile_, false));
service_->AddObserver(&observer_);
AutofillDataTypeController* data_type_controller =
new AutofillDataTypeController(&factory_,
&profile_,
service_.get());
EXPECT_CALL(factory_, CreateAutofillSyncComponents(_, _, _)).
WillOnce(MakeAutofillSyncComponents(service_.get(),
&web_database_,
data_type_controller));
EXPECT_CALL(factory_, CreateDataTypeManager(_)).
WillOnce(MakeDataTypeManager());
EXPECT_CALL(profile_, GetWebDataService(_)).
WillOnce(Return(web_data_service_.get()));
// State changes once for the backend init and once for startup done.
EXPECT_CALL(observer_, OnStateChanged()).
WillOnce(DoDefault()).
WillOnce(QuitUIMessageLoop());
service_->RegisterDataTypeController(data_type_controller);
service_->Initialize();
MessageLoop::current()->Run();
}
}
void GetAutofillEntriesFromSyncDB(std::vector<AutofillEntry>* entries) {
sync_api::ReadTransaction trans(service_->backend()->GetUserShareHandle());
int64 autofill_root_id =
GetFakeServerTaggedNode(&trans, "google_chrome_autofill");
if (autofill_root_id == sync_api::kInvalidId)
return;
sync_api::ReadNode autofill_root(&trans);
if (!autofill_root.InitByIdLookup(autofill_root_id))
return;
int64 child_id = autofill_root.GetFirstChildId();
while (child_id != sync_api::kInvalidId) {
sync_api::ReadNode child_node(&trans);
if (!child_node.InitByIdLookup(child_id))
return;
const sync_pb::AutofillSpecifics& autofill(
child_node.GetAutofillSpecifics());
AutofillKey key(UTF8ToUTF16(autofill.name()),
UTF8ToUTF16(autofill.value()));
std::vector<base::Time> timestamps;
int timestamps_count = autofill.usage_timestamp_size();
for (int i = 0; i < timestamps_count; ++i) {
timestamps.push_back(Time::FromInternalValue(
autofill.usage_timestamp(i)));
}
entries->push_back(AutofillEntry(key, timestamps));
child_id = child_node.GetSuccessorId();
}
}
int64 GetFakeServerTaggedNode(sync_api::ReadTransaction* trans,
const std::string& tag) {
std::wstring tag_wide;
if (!UTF8ToWide(tag.c_str(), tag.length(), &tag_wide))
return sync_api::kInvalidId;
sync_api::ReadNode root(trans);
root.InitByRootLookup();
int64 last_child_id = sync_api::kInvalidId;
for (int64 id = root.GetFirstChildId(); id != sync_api::kInvalidId; /***/) {
sync_api::ReadNode child(trans);
child.InitByIdLookup(id);
last_child_id = id;
if (tag_wide == child.GetTitle()) {
return id;
}
id = child.GetSuccessorId();
}
return sync_api::kInvalidId;
}
void SetIdleChangeProcessorExpectations() {
EXPECT_CALL(web_database_, RemoveFormElement(_, _)).Times(0);
EXPECT_CALL(web_database_, GetAutofillTimestamps(_, _, _)).Times(0);
EXPECT_CALL(web_database_, UpdateAutofillEntries(_)).Times(0);
}
static AutofillEntry MakeAutofillEntry(const char* name,
const char* value,
time_t timestamp) {
std::vector<Time> timestamps;
timestamps.push_back(Time::FromTimeT(timestamp));
return AutofillEntry(
AutofillKey(ASCIIToUTF16(name), ASCIIToUTF16(value)), timestamps);
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
ChromeThread db_thread_;
WaitableEvent done_event_;
scoped_refptr<DBThreadNotificationService> notification_service_;
scoped_ptr<TestingProfileSyncService> service_;
ProfileMock profile_;
ProfileSyncFactoryMock factory_;
ProfileSyncServiceObserverMock observer_;
WebDatabaseMock web_database_;
scoped_refptr<WebDataService> web_data_service_;
};
// TODO(sync): Test unrecoverable error during MA.
TEST_F(ProfileSyncServiceAutofillTest, EmptyNativeEmptySync) {
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).WillOnce(Return(true));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
EXPECT_EQ(0U, sync_entries.size());
}
TEST_F(ProfileSyncServiceAutofillTest, HasNativeEmptySync) {
std::vector<AutofillEntry> entries;
entries.push_back(MakeAutofillEntry("foo", "bar", 1));
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).
WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
ASSERT_EQ(1U, entries.size());
EXPECT_TRUE(entries[0] == sync_entries[0]);
}
TEST_F(ProfileSyncServiceAutofillTest, HasNativeWithDuplicatesEmptySync) {
// There is buggy autofill code that allows duplicate name/value
// pairs to exist in the database with separate pair_ids.
std::vector<AutofillEntry> entries;
entries.push_back(MakeAutofillEntry("foo", "bar", 1));
entries.push_back(MakeAutofillEntry("dup", "", 2));
entries.push_back(MakeAutofillEntry("dup", "", 3));
EXPECT_CALL(web_database_, GetAllAutofillEntries(_)).
WillOnce(DoAll(SetArgumentPointee<0>(entries), Return(true)));
SetIdleChangeProcessorExpectations();
StartSyncService();
std::vector<AutofillEntry> sync_entries;
GetAutofillEntriesFromSyncDB(&sync_entries);
EXPECT_EQ(2U, sync_entries.size());
}
<|endoftext|> |
<commit_before>/* Copyright 2019 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/lite/experimental/delegates/hexagon/hexagon_nn/hexagon_nn_init.h"
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include "remote.h" // NOLINT
#include "rpcmem.h" // NOLINT
#include "tensorflow/lite/experimental/delegates/hexagon/hexagon_nn/soc_model.h"
#ifdef __cplusplus
extern "C" {
#endif
// Version 1.14
static const int kHexagonNNVersion = 136193;
#pragma weak remote_handle_control // Declare it as a weak symbol
void hexagon_nn_global_init() {
rpcmem_init();
// Non-domains QoS invocation
struct remote_rpc_control_latency data;
data.enable = 1;
if (remote_handle_control) { // Check if API is available before invoking
remote_handle_control(DSPRPC_CONTROL_LATENCY, (void*)&data, sizeof(data));
}
}
void hexagon_nn_global_teardown() { rpcmem_deinit(); }
bool hexagon_nn_is_device_supported() {
return tflite::delegates::getsoc_model().mode != UNSPECIFIED_MODE;
}
int hexagon_nn_hexagon_interface_version() { return kHexagonNNVersion; }
#ifdef __cplusplus
}
#endif
<commit_msg>Internal code change<commit_after>/* Copyright 2019 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/lite/experimental/delegates/hexagon/hexagon_nn/hexagon_nn_init.h"
#include <fcntl.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include "remote.h" // NOLINT
#include "rpcmem.h" // NOLINT
#include "tensorflow/lite/experimental/delegates/hexagon/hexagon_nn/soc_model.h"
#ifdef __cplusplus
extern "C" {
#endif
// Version 1.17
static const int kHexagonNNVersion = 136960;
#pragma weak remote_handle_control // Declare it as a weak symbol
void hexagon_nn_global_init() {
rpcmem_init();
// Non-domains QoS invocation
struct remote_rpc_control_latency data;
data.enable = 1;
if (remote_handle_control) { // Check if API is available before invoking
remote_handle_control(DSPRPC_CONTROL_LATENCY, (void*)&data, sizeof(data));
}
}
void hexagon_nn_global_teardown() { rpcmem_deinit(); }
bool hexagon_nn_is_device_supported() {
return tflite::delegates::getsoc_model().mode != UNSPECIFIED_MODE;
}
int hexagon_nn_hexagon_interface_version() { return kHexagonNNVersion; }
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/autofill/autofill_popup_view_views.h"
#include "chrome/browser/ui/autofill/autofill_popup_controller.h"
#include "grit/ui_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAutofillClient.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/display.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/border.h"
#include "ui/views/widget/widget.h"
using WebKit::WebAutofillClient;
namespace {
const SkColor kBorderColor = SkColorSetARGB(0xFF, 0xC7, 0xCA, 0xCE);
const SkColor kHoveredBackgroundColor = SkColorSetARGB(0xFF, 0xCD, 0xCD, 0xCD);
const SkColor kItemTextColor = SkColorSetARGB(0xFF, 0x7F, 0x7F, 0x7F);
const SkColor kPopupBackground = SkColorSetARGB(0xFF, 0xFF, 0xFF, 0xFF);
const SkColor kValueTextColor = SkColorSetARGB(0xFF, 0x00, 0x00, 0x00);
} // namespace
AutofillPopupViewViews::AutofillPopupViewViews(
AutofillPopupController* controller)
: controller_(controller),
observing_widget_(NULL) {}
AutofillPopupViewViews::~AutofillPopupViewViews() {
if (observing_widget_)
observing_widget_->RemoveObserver(this);
controller_->ViewDestroyed();
}
void AutofillPopupViewViews::Hide() {
if (GetWidget()) {
// This deletes |this|.
GetWidget()->Close();
} else {
delete this;
}
}
void AutofillPopupViewViews::OnPaint(gfx::Canvas* canvas) {
canvas->DrawColor(kPopupBackground);
OnPaintBorder(canvas);
for (size_t i = 0; i < controller_->names().size(); ++i) {
gfx::Rect line_rect = controller_->GetRowBounds(i);
if (controller_->identifiers()[i] ==
WebAutofillClient::MenuItemIDSeparator) {
canvas->DrawRect(line_rect, kItemTextColor);
} else {
DrawAutofillEntry(canvas, i, line_rect);
}
}
}
void AutofillPopupViewViews::OnMouseCaptureLost() {
controller_->MouseExitedPopup();
}
bool AutofillPopupViewViews::OnMouseDragged(const ui::MouseEvent& event) {
if (HitTestPoint(gfx::Point(event.x(), event.y()))) {
controller_->MouseHovered(event.x(), event.y());
// We must return true in order to get future OnMouseDragged and
// OnMouseReleased events.
return true;
}
// If we move off of the popup, we lose the selection.
controller_->MouseExitedPopup();
return false;
}
void AutofillPopupViewViews::OnMouseExited(const ui::MouseEvent& event) {
controller_->MouseExitedPopup();
}
void AutofillPopupViewViews::OnMouseMoved(const ui::MouseEvent& event) {
controller_->MouseHovered(event.x(), event.y());
}
bool AutofillPopupViewViews::OnMousePressed(const ui::MouseEvent& event) {
// We must return true in order to get the OnMouseReleased event later.
return true;
}
void AutofillPopupViewViews::OnMouseReleased(const ui::MouseEvent& event) {
// We only care about the left click.
if (event.IsOnlyLeftMouseButton() &&
HitTestPoint(gfx::Point(event.x(), event.y())))
controller_->MouseClicked(event.x(), event.y());
}
void AutofillPopupViewViews::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
Hide();
}
void AutofillPopupViewViews::Show() {
if (!GetWidget()) {
// The widget is destroyed by the corresponding NativeWidget, so we use
// a weak pointer to hold the reference and don't have to worry about
// deletion.
views::Widget* widget = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
params.delegate = this;
params.can_activate = false;
params.transparent = true;
params.parent = controller_->container_view();
widget->Init(params);
widget->SetContentsView(this);
widget->Show();
// Allow the popup to appear anywhere on the screen, since it may need
// to go beyond the bounds of the window.
// TODO(csharp): allow the popup to still appear on the border of
// two screens.
widget->SetBounds(gfx::Rect(GetScreenSize()));
// Setup an observer to check for when the browser moves or changes size,
// since the popup should always be hidden in those cases.
observing_widget_ = views::Widget::GetTopLevelWidgetForNativeView(
controller_->container_view());
observing_widget_->AddObserver(this);
}
set_border(views::Border::CreateSolidBorder(kBorderThickness, kBorderColor));
SetInitialBounds();
UpdateBoundsAndRedrawPopup();
}
void AutofillPopupViewViews::InvalidateRow(size_t row) {
SchedulePaintInRect(controller_->GetRowBounds(row));
}
void AutofillPopupViewViews::UpdateBoundsAndRedrawPopup() {
SetBoundsRect(controller_->popup_bounds());
SchedulePaintInRect(controller_->popup_bounds());
}
void AutofillPopupViewViews::DrawAutofillEntry(gfx::Canvas* canvas,
int index,
const gfx::Rect& entry_rect) {
// TODO(csharp): support RTL
if (controller_->selected_line() == index)
canvas->FillRect(entry_rect, kHoveredBackgroundColor);
canvas->DrawStringInt(
controller_->names()[index],
controller_->name_font(),
kValueTextColor,
kEndPadding,
entry_rect.y(),
canvas->GetStringWidth(controller_->names()[index],
controller_->name_font()),
entry_rect.height(),
gfx::Canvas::TEXT_ALIGN_CENTER);
// Use this to figure out where all the other Autofill items should be placed.
int x_align_left = entry_rect.width() - kEndPadding;
// Draw the delete icon, if one is needed.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
int row_height = controller_->GetRowBounds(index).height();
if (controller_->CanDelete(index)) {
x_align_left -= kDeleteIconWidth;
// TODO(csharp): Create a custom resource for the delete icon.
// http://crbug.com/131801
canvas->DrawImageInt(
*rb.GetImageSkiaNamed(IDR_CLOSE_BAR),
x_align_left,
entry_rect.y() + (row_height - kDeleteIconHeight) / 2);
x_align_left -= kIconPadding;
}
// Draw the Autofill icon, if one exists
if (!controller_->icons()[index].empty()) {
int icon = controller_->GetIconResourceID(controller_->icons()[index]);
DCHECK_NE(-1, icon);
int icon_y = entry_rect.y() + (row_height - kAutofillIconHeight) / 2;
x_align_left -= kAutofillIconWidth;
canvas->DrawImageInt(*rb.GetImageSkiaNamed(icon), x_align_left, icon_y);
x_align_left -= kIconPadding;
}
// Draw the name text.
x_align_left -= canvas->GetStringWidth(controller_->subtexts()[index],
controller_->subtext_font());
canvas->DrawStringInt(
controller_->subtexts()[index],
controller_->subtext_font(),
kItemTextColor,
x_align_left + kEndPadding,
entry_rect.y(),
canvas->GetStringWidth(controller_->subtexts()[index],
controller_->subtext_font()),
entry_rect.height(),
gfx::Canvas::TEXT_ALIGN_CENTER);
}
void AutofillPopupViewViews::SetInitialBounds() {
int bottom_of_field = controller_->element_bounds().bottom();
int popup_height = controller_->GetPopupRequiredHeight();
// Find the correct top position of the popup so that it doesn't go off
// the screen.
int top_of_popup = 0;
if (GetScreenSize().height() < bottom_of_field + popup_height) {
// The popup must appear above the field.
top_of_popup = controller_->element_bounds().y() - popup_height;
} else {
// The popup can appear below the field.
top_of_popup = bottom_of_field;
}
controller_->SetPopupBounds(gfx::Rect(
controller_->element_bounds().x(),
top_of_popup,
controller_->GetPopupRequiredWidth(),
popup_height));
}
gfx::Size AutofillPopupViewViews::GetScreenSize() {
gfx::Screen* screen =
gfx::Screen::GetScreenFor(controller_->container_view());
gfx::Display display =
screen->GetDisplayNearestPoint(controller_->element_bounds().origin());
return display.GetSizeInPixel();
}
AutofillPopupView* AutofillPopupView::Create(
AutofillPopupController* controller) {
return new AutofillPopupViewViews(controller);
}
<commit_msg>make views autofill popup dismiss when user clicks outside of its bounds<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/autofill/autofill_popup_view_views.h"
#include "chrome/browser/ui/autofill/autofill_popup_controller.h"
#include "grit/ui_resources.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAutofillClient.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/display.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/screen.h"
#include "ui/views/border.h"
#include "ui/views/widget/widget.h"
using WebKit::WebAutofillClient;
namespace {
const SkColor kBorderColor = SkColorSetARGB(0xFF, 0xC7, 0xCA, 0xCE);
const SkColor kHoveredBackgroundColor = SkColorSetARGB(0xFF, 0xCD, 0xCD, 0xCD);
const SkColor kItemTextColor = SkColorSetARGB(0xFF, 0x7F, 0x7F, 0x7F);
const SkColor kPopupBackground = SkColorSetARGB(0xFF, 0xFF, 0xFF, 0xFF);
const SkColor kValueTextColor = SkColorSetARGB(0xFF, 0x00, 0x00, 0x00);
} // namespace
AutofillPopupViewViews::AutofillPopupViewViews(
AutofillPopupController* controller)
: controller_(controller),
observing_widget_(NULL) {}
AutofillPopupViewViews::~AutofillPopupViewViews() {
if (observing_widget_)
observing_widget_->RemoveObserver(this);
controller_->ViewDestroyed();
}
void AutofillPopupViewViews::Hide() {
if (GetWidget()) {
// This deletes |this|.
GetWidget()->Close();
} else {
delete this;
}
}
void AutofillPopupViewViews::OnPaint(gfx::Canvas* canvas) {
canvas->DrawColor(kPopupBackground);
OnPaintBorder(canvas);
for (size_t i = 0; i < controller_->names().size(); ++i) {
gfx::Rect line_rect = controller_->GetRowBounds(i);
if (controller_->identifiers()[i] ==
WebAutofillClient::MenuItemIDSeparator) {
canvas->DrawRect(line_rect, kItemTextColor);
} else {
DrawAutofillEntry(canvas, i, line_rect);
}
}
}
void AutofillPopupViewViews::OnMouseCaptureLost() {
controller_->MouseExitedPopup();
}
bool AutofillPopupViewViews::OnMouseDragged(const ui::MouseEvent& event) {
if (HitTestPoint(gfx::Point(event.x(), event.y()))) {
controller_->MouseHovered(event.x(), event.y());
// We must return true in order to get future OnMouseDragged and
// OnMouseReleased events.
return true;
}
// If we move off of the popup, we lose the selection.
controller_->MouseExitedPopup();
return false;
}
void AutofillPopupViewViews::OnMouseExited(const ui::MouseEvent& event) {
controller_->MouseExitedPopup();
}
void AutofillPopupViewViews::OnMouseMoved(const ui::MouseEvent& event) {
controller_->MouseHovered(event.x(), event.y());
}
bool AutofillPopupViewViews::OnMousePressed(const ui::MouseEvent& event) {
// We must return true in order to get the OnMouseReleased event later.
return true;
}
void AutofillPopupViewViews::OnMouseReleased(const ui::MouseEvent& event) {
// We only care about the left click.
if (event.IsOnlyLeftMouseButton() &&
HitTestPoint(gfx::Point(event.x(), event.y())))
controller_->MouseClicked(event.x(), event.y());
}
void AutofillPopupViewViews::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
Hide();
}
void AutofillPopupViewViews::Show() {
if (!GetWidget()) {
// The widget is destroyed by the corresponding NativeWidget, so we use
// a weak pointer to hold the reference and don't have to worry about
// deletion.
views::Widget* widget = new views::Widget;
views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
params.delegate = this;
params.transparent = true;
params.parent = controller_->container_view();
widget->Init(params);
widget->SetContentsView(this);
widget->SetBounds(controller_->popup_bounds());
widget->Show();
// Setup an observer to check for when the browser moves or changes size,
// since the popup should always be hidden in those cases.
observing_widget_ = views::Widget::GetTopLevelWidgetForNativeView(
controller_->container_view());
observing_widget_->AddObserver(this);
}
set_border(views::Border::CreateSolidBorder(kBorderThickness, kBorderColor));
SetInitialBounds();
UpdateBoundsAndRedrawPopup();
}
void AutofillPopupViewViews::InvalidateRow(size_t row) {
SchedulePaintInRect(controller_->GetRowBounds(row));
}
void AutofillPopupViewViews::UpdateBoundsAndRedrawPopup() {
GetWidget()->SetBounds(controller_->popup_bounds());
SchedulePaint();
}
void AutofillPopupViewViews::DrawAutofillEntry(gfx::Canvas* canvas,
int index,
const gfx::Rect& entry_rect) {
// TODO(csharp): support RTL
if (controller_->selected_line() == index)
canvas->FillRect(entry_rect, kHoveredBackgroundColor);
canvas->DrawStringInt(
controller_->names()[index],
controller_->name_font(),
kValueTextColor,
kEndPadding,
entry_rect.y(),
canvas->GetStringWidth(controller_->names()[index],
controller_->name_font()),
entry_rect.height(),
gfx::Canvas::TEXT_ALIGN_CENTER);
// Use this to figure out where all the other Autofill items should be placed.
int x_align_left = entry_rect.width() - kEndPadding;
// Draw the delete icon, if one is needed.
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
int row_height = controller_->GetRowBounds(index).height();
if (controller_->CanDelete(index)) {
x_align_left -= kDeleteIconWidth;
// TODO(csharp): Create a custom resource for the delete icon.
// http://crbug.com/131801
canvas->DrawImageInt(
*rb.GetImageSkiaNamed(IDR_CLOSE_BAR),
x_align_left,
entry_rect.y() + (row_height - kDeleteIconHeight) / 2);
x_align_left -= kIconPadding;
}
// Draw the Autofill icon, if one exists
if (!controller_->icons()[index].empty()) {
int icon = controller_->GetIconResourceID(controller_->icons()[index]);
DCHECK_NE(-1, icon);
int icon_y = entry_rect.y() + (row_height - kAutofillIconHeight) / 2;
x_align_left -= kAutofillIconWidth;
canvas->DrawImageInt(*rb.GetImageSkiaNamed(icon), x_align_left, icon_y);
x_align_left -= kIconPadding;
}
// Draw the name text.
x_align_left -= canvas->GetStringWidth(controller_->subtexts()[index],
controller_->subtext_font());
canvas->DrawStringInt(
controller_->subtexts()[index],
controller_->subtext_font(),
kItemTextColor,
x_align_left + kEndPadding,
entry_rect.y(),
canvas->GetStringWidth(controller_->subtexts()[index],
controller_->subtext_font()),
entry_rect.height(),
gfx::Canvas::TEXT_ALIGN_CENTER);
}
void AutofillPopupViewViews::SetInitialBounds() {
int bottom_of_field = controller_->element_bounds().bottom();
int popup_height = controller_->GetPopupRequiredHeight();
// Find the correct top position of the popup so that it doesn't go off
// the screen.
int top_of_popup = 0;
if (GetScreenSize().height() < bottom_of_field + popup_height) {
// The popup must appear above the field.
top_of_popup = controller_->element_bounds().y() - popup_height;
} else {
// The popup can appear below the field.
top_of_popup = bottom_of_field;
}
controller_->SetPopupBounds(gfx::Rect(
controller_->element_bounds().x(),
top_of_popup,
controller_->GetPopupRequiredWidth(),
popup_height));
}
gfx::Size AutofillPopupViewViews::GetScreenSize() {
gfx::Screen* screen =
gfx::Screen::GetScreenFor(controller_->container_view());
gfx::Display display =
screen->GetDisplayNearestPoint(controller_->element_bounds().origin());
return display.GetSizeInPixel();
}
AutofillPopupView* AutofillPopupView::Create(
AutofillPopupController* controller) {
return new AutofillPopupViewViews(controller);
}
<|endoftext|> |
<commit_before>#pragma once
#include "Constants.hpp"
#include "Geometry2d/Point.hpp"
#include "time.hpp"
#include <cmath>
#include <deque>
#include <QString>
#include <stdexcept>
#include <stdint.h>
#include <sys/time.h>
#include <typeinfo>
#include <vector>
const static bool THROW_DEBUG_EXCEPTIONS = true;
static inline void debugThrow(const std::string &string) {
if (THROW_DEBUG_EXCEPTIONS) {
throw std::runtime_error(string);
}
}
static inline void debugThrow(const std::exception &exception) {
if (THROW_DEBUG_EXCEPTIONS) {
throw exception;
}
}
/**
* @brief Restricts the given angle to be between pi and -pi
*
* @param a An angle in radians
* @return An equivalent angle in radians restricted to [-pi, pi]
*/
static inline float fixAngleRadians(float a)
{
a = remainder(a, 2*M_PI);
while (a < -M_PI) a += 2.0*M_PI;
while (a > M_PI) a -= 2.0*M_PI;
return a;
}
/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
if (std::abs(point.x) < Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) // Ball is in center (rectangular) portion of defensive bubble
{
return point.y > 0 && point.y < Field_Dimensions::Current_Dimensions.ArcRadius();
} else if (std::abs(point.x) < (Field_Dimensions::Current_Dimensions.ArcRadius() + Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) // Ball is in one of the side (arc) portions of defensive bubble
{
double adjusted_x = std::abs(point.x) - (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
double max_y = sqrt( (Field_Dimensions::Current_Dimensions.ArcRadius() * Field_Dimensions::Current_Dimensions.ArcRadius()) - (adjusted_x * adjusted_x));
return point.y > 0 && point.y <= max_y;
}
return false;
}
static Geometry2d::Point fromOursToTheirs(Geometry2d::Point &pt) {
Geometry2d::Point c;
c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
c.x = -pt.x;
return c;
}
static bool ballIsInTheirGoalieBox(Geometry2d::Point &pt) {
Geometry2d::Point converted = fromOursToTheirs(pt);
return ballIsInGoalieBox(converted);
}
/** Returns @value if it is in bounds, otherwise returns the bound it is closest to */
template<class T>
float clamp(T value, T min, T max)
{
if (value > max)
{
return max;
}
else if (value < min)
{
return min;
}
return value;
}
// Removes all entries in a std::map which associate to the given value.
template<class Map_Type, class Data_Type>
void map_remove(Map_Type &map, Data_Type &value)
{
typename Map_Type::iterator i = map.begin();
while (i != map.end())
{
typename Map_Type::iterator next = i;
++next;
if (i->second == value)
{
map.erase(i);
}
i = next;
}
}
// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template<typename Map>
typename Map::mapped_type map_lookup(const Map &map, typename Map::key_type key)
{
typename Map::const_iterator i = map.find(key);
if (i != map.end())
{
return i->second;
} else {
return 0;
}
}
/**
* A basic FIR filter of variable type with float coeffs
*
* Note, coefficients will be normalized so that inputs
* will always be scaled appropriately
*/
template<typename T>
class FIRFilter {
public:
typedef std::vector<float> Coeffs;
FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
if (nrTaps == 0)
throw std::invalid_argument("FIR Filter: number of taps must be greater than zero");
// initialize
_taps.assign(nrTaps, _zero);
_coeffs.assign(nrTaps, 0.0f);
_coeffs[0] = 1.0;
}
T filter(const T& x) {
_taps.push_front(x);
_taps.pop_back();
T y = _zero;
for (size_t i = 0; i<_taps.size(); ++i)
y += _taps.at(i) * _coeffs.at(i);
return y;
}
/** reinitializes the coeffs and taps to new values */
void setCoeffs(const Coeffs& coeffs) {
size_t nrTaps = coeffs.size();
if (nrTaps == 0)
throw std::invalid_argument("FIR Filter: number of coeffs must be greater than zero");
_taps.assign(nrTaps, _zero);
_coeffs.assign(nrTaps, 0.0);
// find the normalizer
float normalizer = 0.0;
for (size_t i = 0; i<coeffs.size(); ++i)
normalizer += coeffs.at(i);
// set the normalized coefficients
for (size_t i=0; i<coeffs.size(); ++i)
_coeffs[i] = coeffs.at(i) / normalizer;
}
protected:
T _zero;
std::deque<T> _taps;
Coeffs _coeffs;
};
// An output iterator which throws an exception when it's used.
// This is used for example to determine if the output of set_difference would be non-empty without
// calculating all of it.
template<typename T>
class ExceptionIterator: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
ExceptionIterator &operator=(const T &value)
{
throw std::exception();
}
ExceptionIterator &operator*()
{
return *this;
}
ExceptionIterator &operator++()
{
return *this;
}
ExceptionIterator &operator++(int)
{
return *this;
}
};
// Sets str to the name of a class.
// Use it like this:
// Object *obj = new Object();
// QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info &info);
// Like typeName, but only returns the final class name part.
QString className(const std::type_info &info);
<commit_msg>Fix the debugThrow Util<commit_after>#pragma once
#include "Constants.hpp"
#include "Geometry2d/Point.hpp"
#include "time.hpp"
#include <cmath>
#include <deque>
#include <QString>
#include <stdexcept>
#include <stdint.h>
#include <sys/time.h>
#include <typeinfo>
#include <vector>
const static bool THROW_DEBUG_EXCEPTIONS = true;
static inline void debugThrow(const std::string &string) {
if (THROW_DEBUG_EXCEPTIONS) {
throw std::runtime_error(string);
}
}
template <class exception>
static inline void debugThrow(const exception &e) {
if (THROW_DEBUG_EXCEPTIONS) {
throw e;
}
}
/**
* @brief Restricts the given angle to be between pi and -pi
*
* @param a An angle in radians
* @return An equivalent angle in radians restricted to [-pi, pi]
*/
static inline float fixAngleRadians(float a)
{
a = remainder(a, 2*M_PI);
while (a < -M_PI) a += 2.0*M_PI;
while (a > M_PI) a -= 2.0*M_PI;
return a;
}
/** Checks whether or not the given ball is in the defense area. */
static inline bool ballIsInGoalieBox(Geometry2d::Point point) {
if (std::abs(point.x) < Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f) // Ball is in center (rectangular) portion of defensive bubble
{
return point.y > 0 && point.y < Field_Dimensions::Current_Dimensions.ArcRadius();
} else if (std::abs(point.x) < (Field_Dimensions::Current_Dimensions.ArcRadius() + Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f)) // Ball is in one of the side (arc) portions of defensive bubble
{
double adjusted_x = std::abs(point.x) - (Field_Dimensions::Current_Dimensions.GoalFlat() / 2.0f);
double max_y = sqrt( (Field_Dimensions::Current_Dimensions.ArcRadius() * Field_Dimensions::Current_Dimensions.ArcRadius()) - (adjusted_x * adjusted_x));
return point.y > 0 && point.y <= max_y;
}
return false;
}
static Geometry2d::Point fromOursToTheirs(Geometry2d::Point &pt) {
Geometry2d::Point c;
c.y = Field_Dimensions::Current_Dimensions.Length() - pt.y;
c.x = -pt.x;
return c;
}
static bool ballIsInTheirGoalieBox(Geometry2d::Point &pt) {
Geometry2d::Point converted = fromOursToTheirs(pt);
return ballIsInGoalieBox(converted);
}
/** Returns @value if it is in bounds, otherwise returns the bound it is closest to */
template<class T>
float clamp(T value, T min, T max)
{
if (value > max)
{
return max;
}
else if (value < min)
{
return min;
}
return value;
}
// Removes all entries in a std::map which associate to the given value.
template<class Map_Type, class Data_Type>
void map_remove(Map_Type &map, Data_Type &value)
{
typename Map_Type::iterator i = map.begin();
while (i != map.end())
{
typename Map_Type::iterator next = i;
++next;
if (i->second == value)
{
map.erase(i);
}
i = next;
}
}
// If <key> exists in <map>, returns map[key].
// If not, returns 0.
template<typename Map>
typename Map::mapped_type map_lookup(const Map &map, typename Map::key_type key)
{
typename Map::const_iterator i = map.find(key);
if (i != map.end())
{
return i->second;
} else {
return 0;
}
}
/**
* A basic FIR filter of variable type with float coeffs
*
* Note, coefficients will be normalized so that inputs
* will always be scaled appropriately
*/
template<typename T>
class FIRFilter {
public:
typedef std::vector<float> Coeffs;
FIRFilter(const T& zero, size_t nrTaps) : _zero(zero) {
if (nrTaps == 0)
throw std::invalid_argument("FIR Filter: number of taps must be greater than zero");
// initialize
_taps.assign(nrTaps, _zero);
_coeffs.assign(nrTaps, 0.0f);
_coeffs[0] = 1.0;
}
T filter(const T& x) {
_taps.push_front(x);
_taps.pop_back();
T y = _zero;
for (size_t i = 0; i<_taps.size(); ++i)
y += _taps.at(i) * _coeffs.at(i);
return y;
}
/** reinitializes the coeffs and taps to new values */
void setCoeffs(const Coeffs& coeffs) {
size_t nrTaps = coeffs.size();
if (nrTaps == 0)
throw std::invalid_argument("FIR Filter: number of coeffs must be greater than zero");
_taps.assign(nrTaps, _zero);
_coeffs.assign(nrTaps, 0.0);
// find the normalizer
float normalizer = 0.0;
for (size_t i = 0; i<coeffs.size(); ++i)
normalizer += coeffs.at(i);
// set the normalized coefficients
for (size_t i=0; i<coeffs.size(); ++i)
_coeffs[i] = coeffs.at(i) / normalizer;
}
protected:
T _zero;
std::deque<T> _taps;
Coeffs _coeffs;
};
// An output iterator which throws an exception when it's used.
// This is used for example to determine if the output of set_difference would be non-empty without
// calculating all of it.
template<typename T>
class ExceptionIterator: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
ExceptionIterator &operator=(const T &value)
{
throw std::exception();
}
ExceptionIterator &operator*()
{
return *this;
}
ExceptionIterator &operator++()
{
return *this;
}
ExceptionIterator &operator++(int)
{
return *this;
}
};
// Sets str to the name of a class.
// Use it like this:
// Object *obj = new Object();
// QString name = typeName(typeid(*obj));
// The returned name is in the usual C++ format: "Namespace::Namespace::Class"
QString typeName(const std::type_info &info);
// Like typeName, but only returns the final class name part.
QString className(const std::type_info &info);
<|endoftext|> |
<commit_before>
#include <iostream>
#include "SDL2/SDL.h"
#include "sdl/error.h"
#include "sdl/window.h"
#include "sdl/renderer.h"
#include "sdl/texture.h"
#include "sdl/sdl_init.h"
#include "sdl/color.h"
#include "sdl/timer.h"
#include "phys/system.h"
#include "phys/basic_material.h"
#include "phys/detector.h"
#include "phys/fuel_material.h"
#include "phys/moderator_material.h"
#include "phys/absorb_material.h"
#include "phys/stream_src.h"
#include "draw/sys_view.h"
using sdl::Color;
const int neutron_burst = 1000;
int main(int argc, char** argv) {
std::ranlux48_base rand_gen;
std::uniform_real_distribution<> uniform01;
try {
sdl::SDLinit init(SDL_INIT_EVERYTHING);
// create window and renderer
int w = 850;
int h = 650;
sdl::Window win("Reactor", w, h, 0);
win.Center();
win.Show();
sdl::Renderer ren(win, SDL_RENDERER_ACCELERATED);
// create material geometry
phys::BasicMaterial reflector1{0, 0, .1, 1, 0};
phys::Object::Rect r1{w/2 - 40, h/2 - 40, 120, 120};
reflector1.Init(r1, sdl::Color::white());
phys::BasicMaterial reflector2(&reflector1);
phys::BasicMaterial reflector3(&reflector1);
phys::BasicMaterial reflector4(&reflector1);
phys::Absorber absorber1{.1};
phys::Object::Rect r2{w/2 - 130, h/2 - 40, 80, 80};
absorber1.Init(r2, sdl::Color::blue());
phys::Absorber absorber2(&absorber1);
phys::Absorber absorber3(&absorber1);
phys::Absorber absorber4(&absorber1);
phys::BasicMaterial moderator1{0, 0, .03, .3, 0};
phys::Object::Rect r3{w/2 + 50, h/2 - 40, 80, 80};
moderator1.Init(r3, sdl::Color::green());
phys::BasicMaterial moderator2(&moderator1);
phys::BasicMaterial moderator3(&moderator1);
phys::BasicMaterial moderator4(&moderator1);
phys::Moderator voidmoderator1(.03, .3, 200);
phys::Object::Rect r3b{w/2 + 130, h/2 - 40, 60, 60};
voidmoderator1.Init(r3b, sdl::Color::lime());
phys::Fuel fuel1(0, 0.070, 2);
phys::Object::Rect r4{w/2 - 20, h/2 + 50, 40, 40};
fuel1.Init(r4, sdl::Color::purple());
phys::Fuel fuel2(&fuel1);
phys::Fuel fuel3(&fuel1);
phys::Fuel fuel4(&fuel1);
phys::Fuel fuel5(&fuel1);
phys::Fuel fuel6(&fuel1);
phys::Fuel fuel7(&fuel1);
phys::Fuel fuel8(&fuel1);
phys::Fuel fuel9(&fuel1);
phys::Object::Rect r5{w/2 + 130, h/2 + 140, 100, 100};
phys::Detector detector1;
detector1.Init(r5, sdl::Color::yellow(128));
phys::Detector detector2(&detector1);
phys::Object::Rect r6{w/2 + 80, h/2 + 80, 50, 50};
phys::Detector detector3;
detector3.Init(r6, sdl::Color::yellow(128));
phys::Detector detector4(&detector3);
phys::StreamSource stream1;
phys::Object::Rect r7{w/2 + 130, h/2 - 40, 40, 40};
stream1.Init(r7, sdl::Color::olive());
// create system and a view for drawing it
phys::System sys(w, h);
sys.AddToolbar();
phys::Object::Rect tb_r = sys.toolbar().rect();
//add fuel item inside toolbar
phys::Fuel fuel(0, 0.070, 2);
phys::Object::Rect fr{tb_r.x+tb_r.w/2-20,tb_r.y+(int)((double)tb_r.h*.25)-20,40,40};
fuel.Init(fr, sdl::Color::purple());
sys.AddObject(&fuel);
phys::BasicMaterial reflector{0, 0, .1, 1, 0};
phys::Object::Rect rr{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.6)-40,80,80};
reflector.Init(rr, sdl::Color::white());
sys.AddObject(&reflector);
phys::Absorber absorber{.1};
phys::Object::Rect ar{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.75)-40,80,80};
absorber.Init(ar, sdl::Color::blue());
sys.AddObject(&absorber);
phys::BasicMaterial moderator{0, 0, .03, .3, 0};
phys::Object::Rect mr{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.9)-40,80,80};
moderator.Init(mr, sdl::Color::green());
sys.AddObject(&moderator);
stream1.sys(&sys);
draw::SysView view(&sys, &ren);
// start up the main loop
SDL_Event ev;
sdl::Timer timer;
timer.Start();
bool done = false;
bool dragging = false;
phys::Object* dragged = nullptr;
phys::Object* clicked = nullptr;
while(!done) {
// process events
while(SDL_PollEvent(&ev)) {
if (ev.type == SDL_QUIT) {
done = true;
} else if (ev.type == SDL_MOUSEBUTTONDOWN &&
ev.button.button == SDL_BUTTON_RIGHT) {
clicked = sys.ObjectFor(ev.button.x, ev.button.y);
if (clicked->OnClick(ev.button.x, ev.button.y))
continue;
// create some neutrons
phys::Neutron::Pop ns;
for (int i = 0; i < neutron_burst; ++i) {
double theta = uniform01(rand_gen) * 2 * 3.141592654;
int vx = std::cos(theta) * phys::Neutron::kNomSpeed;
int vy = std::sin(theta) * phys::Neutron::kNomSpeed;
ns.push_back(phys::Neutron(ev.button.x, ev.button.y, vx, vy));
}
sys.AddNeutrons(ns);
} else if (ev.type == SDL_MOUSEBUTTONDOWN &&
ev.button.button == SDL_BUTTON_LEFT) {
dragged = sys.ObjectFor(ev.button.x, ev.button.y);
if(dragged->isToolbar())
continue;
if(sys.inToolbar(dragged) && !dragged->detector())
{
phys::Object* temp = dragged->clone();
sys.AddObject(&(*temp));
}
sys.MoveTop(dragged);
dragging = true;
} else if (ev.type == SDL_KEYDOWN) {
if (dragged == nullptr) {
continue;
}
if (ev.key.keysym.sym == SDLK_DOWN) {
dragged->Shift(0, 5);
} else if (ev.key.keysym.sym == SDLK_UP) {
dragged->Shift(0, -5);
} else if (ev.key.keysym.sym == SDLK_LEFT) {
dragged->Shift(-5, 0);
} else if (ev.key.keysym.sym == SDLK_RIGHT) {
dragged->Shift(5, 0);
}
} else if (ev.type == SDL_MOUSEBUTTONUP && ev.button.button == SDL_BUTTON_LEFT) {
dragging = false;
} else if (ev.type == SDL_MOUSEMOTION && dragging) {
dragged->Shift(ev.motion.xrel, ev.motion.yrel);
}
}
double dt = (double)timer.Mark();
sys.Tick(dt / 1000);
view.Render(((double)1000) / dt);
}
return 0;
} catch (sdl::FatalErr err) {
std::cout << "ERROR: " << err.what() << "\n";
return 1;
}
}
<commit_msg>Moved fuel object down a bit in the toolbar.<commit_after>
#include <iostream>
#include "SDL2/SDL.h"
#include "sdl/error.h"
#include "sdl/window.h"
#include "sdl/renderer.h"
#include "sdl/texture.h"
#include "sdl/sdl_init.h"
#include "sdl/color.h"
#include "sdl/timer.h"
#include "phys/system.h"
#include "phys/basic_material.h"
#include "phys/detector.h"
#include "phys/fuel_material.h"
#include "phys/moderator_material.h"
#include "phys/absorb_material.h"
#include "phys/stream_src.h"
#include "draw/sys_view.h"
using sdl::Color;
const int neutron_burst = 1000;
int main(int argc, char** argv) {
std::ranlux48_base rand_gen;
std::uniform_real_distribution<> uniform01;
try {
sdl::SDLinit init(SDL_INIT_EVERYTHING);
// create window and renderer
int w = 850;
int h = 650;
sdl::Window win("Reactor", w, h, 0);
win.Center();
win.Show();
sdl::Renderer ren(win, SDL_RENDERER_ACCELERATED);
// create material geometry
phys::BasicMaterial reflector1{0, 0, .1, 1, 0};
phys::Object::Rect r1{w/2 - 40, h/2 - 40, 120, 120};
reflector1.Init(r1, sdl::Color::white());
phys::BasicMaterial reflector2(&reflector1);
phys::BasicMaterial reflector3(&reflector1);
phys::BasicMaterial reflector4(&reflector1);
phys::Absorber absorber1{.1};
phys::Object::Rect r2{w/2 - 130, h/2 - 40, 80, 80};
absorber1.Init(r2, sdl::Color::blue());
phys::Absorber absorber2(&absorber1);
phys::Absorber absorber3(&absorber1);
phys::Absorber absorber4(&absorber1);
phys::BasicMaterial moderator1{0, 0, .03, .3, 0};
phys::Object::Rect r3{w/2 + 50, h/2 - 40, 80, 80};
moderator1.Init(r3, sdl::Color::green());
phys::BasicMaterial moderator2(&moderator1);
phys::BasicMaterial moderator3(&moderator1);
phys::BasicMaterial moderator4(&moderator1);
phys::Moderator voidmoderator1(.03, .3, 200);
phys::Object::Rect r3b{w/2 + 130, h/2 - 40, 60, 60};
voidmoderator1.Init(r3b, sdl::Color::lime());
phys::Fuel fuel1(0, 0.070, 2);
phys::Object::Rect r4{w/2 - 20, h/2 + 50, 40, 40};
fuel1.Init(r4, sdl::Color::purple());
phys::Fuel fuel2(&fuel1);
phys::Fuel fuel3(&fuel1);
phys::Fuel fuel4(&fuel1);
phys::Fuel fuel5(&fuel1);
phys::Fuel fuel6(&fuel1);
phys::Fuel fuel7(&fuel1);
phys::Fuel fuel8(&fuel1);
phys::Fuel fuel9(&fuel1);
phys::Object::Rect r5{w/2 + 130, h/2 + 140, 100, 100};
phys::Detector detector1;
detector1.Init(r5, sdl::Color::yellow(128));
phys::Detector detector2(&detector1);
phys::Object::Rect r6{w/2 + 80, h/2 + 80, 50, 50};
phys::Detector detector3;
detector3.Init(r6, sdl::Color::yellow(128));
phys::Detector detector4(&detector3);
phys::StreamSource stream1;
phys::Object::Rect r7{w/2 + 130, h/2 - 40, 40, 40};
stream1.Init(r7, sdl::Color::olive());
// create system and a view for drawing it
phys::System sys(w, h);
sys.AddToolbar();
phys::Object::Rect tb_r = sys.toolbar().rect();
//add fuel item inside toolbar
phys::Fuel fuel(0, 0.070, 2);
phys::Object::Rect fr{tb_r.x+tb_r.w/2-20,tb_r.y+(int)((double)tb_r.h*.45)-20,40,40};
fuel.Init(fr, sdl::Color::purple());
sys.AddObject(&fuel);
phys::BasicMaterial reflector{0, 0, .1, 1, 0};
phys::Object::Rect rr{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.6)-40,80,80};
reflector.Init(rr, sdl::Color::white());
sys.AddObject(&reflector);
phys::Absorber absorber{.1};
phys::Object::Rect ar{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.75)-40,80,80};
absorber.Init(ar, sdl::Color::blue());
sys.AddObject(&absorber);
phys::BasicMaterial moderator{0, 0, .03, .3, 0};
phys::Object::Rect mr{tb_r.x+tb_r.w/2-40,tb_r.y+(int)((double)tb_r.h*.9)-40,80,80};
moderator.Init(mr, sdl::Color::green());
sys.AddObject(&moderator);
stream1.sys(&sys);
draw::SysView view(&sys, &ren);
// start up the main loop
SDL_Event ev;
sdl::Timer timer;
timer.Start();
bool done = false;
bool dragging = false;
phys::Object* dragged = nullptr;
phys::Object* clicked = nullptr;
while(!done) {
// process events
while(SDL_PollEvent(&ev)) {
if (ev.type == SDL_QUIT) {
done = true;
} else if (ev.type == SDL_MOUSEBUTTONDOWN &&
ev.button.button == SDL_BUTTON_RIGHT) {
clicked = sys.ObjectFor(ev.button.x, ev.button.y);
if (clicked->OnClick(ev.button.x, ev.button.y))
continue;
// create some neutrons
phys::Neutron::Pop ns;
for (int i = 0; i < neutron_burst; ++i) {
double theta = uniform01(rand_gen) * 2 * 3.141592654;
int vx = std::cos(theta) * phys::Neutron::kNomSpeed;
int vy = std::sin(theta) * phys::Neutron::kNomSpeed;
ns.push_back(phys::Neutron(ev.button.x, ev.button.y, vx, vy));
}
sys.AddNeutrons(ns);
} else if (ev.type == SDL_MOUSEBUTTONDOWN &&
ev.button.button == SDL_BUTTON_LEFT) {
dragged = sys.ObjectFor(ev.button.x, ev.button.y);
if(dragged->isToolbar())
continue;
if(sys.inToolbar(dragged) && !dragged->detector())
{
phys::Object* temp = dragged->clone();
sys.AddObject(&(*temp));
}
sys.MoveTop(dragged);
dragging = true;
} else if (ev.type == SDL_KEYDOWN) {
if (dragged == nullptr) {
continue;
}
if (ev.key.keysym.sym == SDLK_DOWN) {
dragged->Shift(0, 5);
} else if (ev.key.keysym.sym == SDLK_UP) {
dragged->Shift(0, -5);
} else if (ev.key.keysym.sym == SDLK_LEFT) {
dragged->Shift(-5, 0);
} else if (ev.key.keysym.sym == SDLK_RIGHT) {
dragged->Shift(5, 0);
}
} else if (ev.type == SDL_MOUSEBUTTONUP && ev.button.button == SDL_BUTTON_LEFT) {
dragging = false;
} else if (ev.type == SDL_MOUSEMOTION && dragging) {
dragged->Shift(ev.motion.xrel, ev.motion.yrel);
}
}
double dt = (double)timer.Mark();
sys.Tick(dt / 1000);
view.Render(((double)1000) / dt);
}
return 0;
} catch (sdl::FatalErr err) {
std::cout << "ERROR: " << err.what() << "\n";
return 1;
}
}
<|endoftext|> |
<commit_before>#ifndef CLIENT_HTTPS_HPP
#define CLIENT_HTTPS_HPP
#include "client_http.hpp"
#include <boost/asio/ssl.hpp>
namespace SimpleWeb {
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> HTTPS;
template<>
class Client<HTTPS> : public ClientBase<HTTPS> {
public:
Client(const std::string& server_port_path, bool verify_certificate=true,
const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(),
const std::string& verify_file=std::string()) :
ClientBase<HTTPS>::ClientBase(server_port_path, 443), context(boost::asio::ssl::context::tlsv12) {
if(verify_certificate) {
context.set_verify_mode(boost::asio::ssl::verify_peer);
context.set_default_verify_paths();
}
else
context.set_verify_mode(boost::asio::ssl::verify_none);
if(cert_file.size()>0 && private_key_file.size()>0) {
context.use_certificate_chain_file(cert_file);
context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
}
if(verify_file.size()>0)
context.load_verify_file(verify_file);
}
protected:
boost::asio::ssl::context context;
std::string protocol() const {
return "https";
}
void connect() {
if(!socket || !socket->lowest_layer().is_open()) {
std::unique_ptr<boost::asio::ip::tcp::resolver::query> query;
if(config.proxy_server.empty())
query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(host, std::to_string(port)));
else {
auto proxy_host_port=parse_host_port(config.proxy_server, 8080);
query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(proxy_host_port.first, std::to_string(proxy_host_port.second)));
}
resolver.async_resolve(*query, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
{
std::lock_guard<std::mutex> lock(socket_mutex);
socket=std::unique_ptr<HTTPS>(new HTTPS(io_service, context));
}
boost::asio::async_connect(socket->lowest_layer(), it, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator /*it*/){
if(!ec) {
boost::asio::ip::tcp::no_delay option(true);
this->socket->lowest_layer().set_option(option);
}
else {
std::lock_guard<std::mutex> lock(socket_mutex);
this->socket=nullptr;
throw boost::system::system_error(ec);
}
});
}
else {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
if(!config.proxy_server.empty()) {
boost::asio::streambuf write_buffer;
std::ostream write_stream(&write_buffer);
auto host_port=host+':'+std::to_string(port);
write_stream << "CONNECT "+host_port+" HTTP/1.1\r\n" << "Host: " << host_port << "\r\n\r\n";
auto timer=get_timeout_timer();
boost::asio::async_write(*socket, write_buffer,
[this, timer](const boost::system::error_code &ec, size_t /*bytes_transferred*/) {
if(timer)
timer->cancel();
if(ec) {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
auto response=request_read();
if (response->status_code.size()>0 && response->status_code.substr(0,3) != "200") {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(boost::system::error_code(boost::system::errc::permission_denied, boost::system::generic_category()));
}
}
auto timer=get_timeout_timer();
this->socket->async_handshake(boost::asio::ssl::stream_base::client,
[this, timer](const boost::system::error_code& ec) {
if(timer)
timer->cancel();
if(ec) {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
}
}
};
}
#endif /* CLIENT_HTTPS_HPP */
<commit_msg>Fixed proxy status code check<commit_after>#ifndef CLIENT_HTTPS_HPP
#define CLIENT_HTTPS_HPP
#include "client_http.hpp"
#include <boost/asio/ssl.hpp>
namespace SimpleWeb {
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> HTTPS;
template<>
class Client<HTTPS> : public ClientBase<HTTPS> {
public:
Client(const std::string& server_port_path, bool verify_certificate=true,
const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(),
const std::string& verify_file=std::string()) :
ClientBase<HTTPS>::ClientBase(server_port_path, 443), context(boost::asio::ssl::context::tlsv12) {
if(verify_certificate) {
context.set_verify_mode(boost::asio::ssl::verify_peer);
context.set_default_verify_paths();
}
else
context.set_verify_mode(boost::asio::ssl::verify_none);
if(cert_file.size()>0 && private_key_file.size()>0) {
context.use_certificate_chain_file(cert_file);
context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
}
if(verify_file.size()>0)
context.load_verify_file(verify_file);
}
protected:
boost::asio::ssl::context context;
std::string protocol() const {
return "https";
}
void connect() {
if(!socket || !socket->lowest_layer().is_open()) {
std::unique_ptr<boost::asio::ip::tcp::resolver::query> query;
if(config.proxy_server.empty())
query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(host, std::to_string(port)));
else {
auto proxy_host_port=parse_host_port(config.proxy_server, 8080);
query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(proxy_host_port.first, std::to_string(proxy_host_port.second)));
}
resolver.async_resolve(*query, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it){
if(!ec) {
{
std::lock_guard<std::mutex> lock(socket_mutex);
socket=std::unique_ptr<HTTPS>(new HTTPS(io_service, context));
}
boost::asio::async_connect(socket->lowest_layer(), it, [this]
(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator /*it*/){
if(!ec) {
boost::asio::ip::tcp::no_delay option(true);
this->socket->lowest_layer().set_option(option);
}
else {
std::lock_guard<std::mutex> lock(socket_mutex);
this->socket=nullptr;
throw boost::system::system_error(ec);
}
});
}
else {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
if(!config.proxy_server.empty()) {
boost::asio::streambuf write_buffer;
std::ostream write_stream(&write_buffer);
auto host_port=host+':'+std::to_string(port);
write_stream << "CONNECT "+host_port+" HTTP/1.1\r\n" << "Host: " << host_port << "\r\n\r\n";
auto timer=get_timeout_timer();
boost::asio::async_write(*socket, write_buffer,
[this, timer](const boost::system::error_code &ec, size_t /*bytes_transferred*/) {
if(timer)
timer->cancel();
if(ec) {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
auto response=request_read();
if (response->status_code.empty() || response->status_code.substr(0,3) != "200") {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(boost::system::error_code(boost::system::errc::permission_denied, boost::system::generic_category()));
}
}
auto timer=get_timeout_timer();
this->socket->async_handshake(boost::asio::ssl::stream_base::client,
[this, timer](const boost::system::error_code& ec) {
if(timer)
timer->cancel();
if(ec) {
std::lock_guard<std::mutex> lock(socket_mutex);
socket=nullptr;
throw boost::system::system_error(ec);
}
});
io_service.reset();
io_service.run();
}
}
};
}
#endif /* CLIENT_HTTPS_HPP */
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <ctime>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "gaussian.h"
#define BLUR_RADIUS 3
#define PATHS_PER_SCAN 4
#define MAX_SHORT std::numeric_limits<unsigned short>::max()
#define SMALL_PENALTY 3
#define LARGE_PENALTY 20
#define DEBUG false
struct path {
short rowDiff;
short colDiff;
short index;
};
void printArray(unsigned short ***array, int rows, int cols, int depth) {
for (int d = 0; d < depth; ++d) {
std::cout << "disparity: " << d << std::endl;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
std::cout << "\t" << array[row][col][d];
}
std::cout << std::endl;
}
}
}
unsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {
char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax;
if(leftCol<0)
leftValue = 0;
else
leftValue = leftImage.at<uchar>(row, leftCol);
if(rightCol<0)
rightValue = 0;
else
rightValue = rightImage.at<uchar>(row, rightCol);
if (rightCol > 0) {
beforeRightValue = rightImage.at<uchar>(row, rightCol - 1);
} else {
beforeRightValue = rightValue;
}
//std::cout << rightCol <<" " <<leftCol<< std::endl;
if (rightCol + 1 < rightImage.cols && rightCol>0) {
afterRightValue = rightImage.at<uchar>(row, rightCol + 1);
} else {
afterRightValue = rightValue;
}
rightValueMinus = round((rightValue + beforeRightValue) / 2.f);
rightValuePlus = round((rightValue + afterRightValue) / 2.f);
rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus));
rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus));
return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue)));
}
inline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {
return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage),
calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage));
}
void calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) {
for (int row = 0; row < firstImage.rows; ++row) {
for (int col = 0; col < firstImage.cols; ++col) {
for (int d = 0; d < disparityRange; ++d) {
//std::cout << col << " " << d << " "<<disparityRange << " " << col - d << std::endl;
C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage);
}
}
}
}
// pathCount can be 1, 2, 4, or 8
void initializeFirstScanPaths(std::vector<path> &paths, unsigned short pathCount) {
for (unsigned short i = 0; i < pathCount; ++i) {
paths.push_back(path());
}
if(paths.size() >= 1) {
paths[0].rowDiff = 0;
paths[0].colDiff = -1;
paths[0].index = 1;
}
if(paths.size() >= 2) {
paths[1].rowDiff = -1;
paths[1].colDiff = 0;
paths[1].index = 2;
}
if(paths.size() >= 4) {
paths[2].rowDiff = -1;
paths[2].colDiff = 1;
paths[2].index = 4;
paths[3].rowDiff = -1;
paths[3].colDiff = -1;
paths[3].index = 7;
}
if(paths.size() >= 8) {
paths[4].rowDiff = -2;
paths[4].colDiff = 1;
paths[4].index = 8;
paths[5].rowDiff = -2;
paths[5].colDiff = -1;
paths[5].index = 9;
paths[6].rowDiff = -1;
paths[6].colDiff = -2;
paths[6].index = 13;
paths[7].rowDiff = -1;
paths[7].colDiff = 2;
paths[7].index = 15;
}
}
// pathCount can be 1, 2, 4, or 8
void initializeSecondScanPaths(std::vector<path> &paths, unsigned short pathCount) {
for (unsigned short i = 0; i < pathCount; ++i) {
paths.push_back(path());
}
if(paths.size() >= 1) {
paths[0].rowDiff = 0;
paths[0].colDiff = 1;
paths[0].index = 0;
}
if(paths.size() >= 2) {
paths[1].rowDiff = 1;
paths[1].colDiff = 0;
paths[1].index = 3;
}
if(paths.size() >= 4) {
paths[2].rowDiff = 1;
paths[2].colDiff = 1;
paths[2].index = 5;
paths[3].rowDiff = 1;
paths[3].colDiff = -1;
paths[3].index = 6;
}
if(paths.size() >= 8) {
paths[4].rowDiff = 2;
paths[4].colDiff = 1;
paths[4].index = 10;
paths[5].rowDiff = 2;
paths[5].colDiff = -1;
paths[5].index = 11;
paths[6].rowDiff = 1;
paths[6].colDiff = -2;
paths[6].index = 12;
paths[7].rowDiff = 1;
paths[7].colDiff = 2;
paths[7].index = 14;
}
}
unsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ***A) {
unsigned short aggregatedCost = 0;
aggregatedCost += C[row][col][d];
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)\n", p.index, row, col, d);
}
if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) {
// border
A[row][col][d] += aggregatedCost;
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)-> %d <BORDER>\n", p.index, row, col, d, A[row][col][d]);
}
return A[row][col][d];
}
unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus;
prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT;
for (int disp = 0; disp < disparityRange; ++disp) {
unsigned short tmp = A[row + p.rowDiff][col + p.colDiff][disp];
if(minPrev > tmp) {
minPrev = tmp;
}
if(disp == d) {
prev = tmp;
} else if(disp == d + 1) {
prevPlus = tmp;
} else if (disp == d - 1) {
prevMinus = tmp;
} else {
if(minPrevOther > tmp + LARGE_PENALTY) {
minPrevOther = tmp + LARGE_PENALTY;
}
}
}
aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY));
aggregatedCost -= minPrev;
A[row][col][d] += aggregatedCost;
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)-> %d<CALCULATED>\n", p.index, row, col, d, A[row][col][d]);
}
return A[row][col][d];
}
float printProgress(unsigned int current, unsigned int max, int lastProgressPrinted) {
int progress = floor(100 * current / (float) max);
if(progress >= lastProgressPrinted + 5) {
lastProgressPrinted = lastProgressPrinted + 5;
std::cout << lastProgressPrinted << "%" << std::endl;
}
return lastProgressPrinted;
}
void aggregateCosts(int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ****A, unsigned short ***S) {
std::vector<path> firstScanPaths;
std::vector<path> secondScanPaths;
initializeFirstScanPaths(firstScanPaths, PATHS_PER_SCAN);
initializeSecondScanPaths(secondScanPaths, PATHS_PER_SCAN);
int lastProgressPrinted = 0;
std::cout << "First scan..." << std::endl;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
for (unsigned int path = 0; path < firstScanPaths.size(); ++path) {
for (int d = 0; d < disparityRange; ++d) {
S[row][col][d] += aggregateCost(row, col, d, firstScanPaths[path], rows, cols, disparityRange, C, A[path]);
}
}
}
lastProgressPrinted = printProgress(row, rows - 1, lastProgressPrinted);
}
lastProgressPrinted = 0;
std::cout << "Second scan..." << std::endl;
for (int row = rows - 1; row >= 0; --row) {
for (int col = cols - 1; col >= 0; --col) {
for (unsigned int path = 0; path < secondScanPaths.size(); ++path) {
for (int d = 0; d < disparityRange; ++d) {
S[row][col][d] += aggregateCost(row, col, d, secondScanPaths[path], rows, cols, disparityRange, C, A[path]);
}
}
}
lastProgressPrinted = printProgress(rows - 1 - row, rows - 1, lastProgressPrinted);
}
}
void computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) {
unsigned int disparity = 0, minCost;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
minCost = MAX_SHORT;
for (int d = disparityRange - 1; d >= 0; --d) {
if(minCost > S[row][col][d]) {
minCost = S[row][col][d];
disparity = d;
}
}
disparityMap.at<uchar>(row, col) = disparity;
}
}
}
void saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) {
double factor = 256.0 / disparityRange;
for (int row = 0; row < disparityMap.rows; ++row) {
for (int col = 0; col < disparityMap.cols; ++col) {
disparityMap.at<uchar>(row, col) *= factor;
}
}
cv::imwrite(outputFile, disparityMap);
}
int main(int argc, char** argv) {
if (argc != 5) {
std::cerr << "Usage: " << argv[0] << " <left image> <right image> <output image file> <disparity range>" << std::endl;
return -1;
}
char *firstFileName = argv[1];
char *secondFileName = argv[2];
char *outFileName = argv[3];
cv::Mat firstImage;
cv::Mat secondImage;
firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE);
secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE);
if(!firstImage.data || !secondImage.data) {
std::cerr << "Could not open or find one of the images!" << std::endl;
return -1;
}
unsigned int disparityRange = atoi(argv[4]);
unsigned short ***C; // pixel cost array W x H x D
unsigned short ***S; // aggregated cost array W x H x D
unsigned short ****A; // single path cost array 2 x W x H x D
/*
* TODO
* variable LARGE_PENALTY
*/
clock_t begin = clock();
std::cout << "Allocating space..." << std::endl;
// allocate cost arrays
C = new unsigned short**[firstImage.rows];
S = new unsigned short**[firstImage.rows];
for (int row = 0; row < firstImage.rows; ++row) {
C[row] = new unsigned short*[firstImage.cols];
S[row] = new unsigned short*[firstImage.cols]();
for (int col = 0; col < firstImage.cols; ++col) {
C[row][col] = new unsigned short[disparityRange];
S[row][col] = new unsigned short[disparityRange](); // initialize to 0
}
}
A = new unsigned short ***[PATHS_PER_SCAN];
for(int path = 0; path < PATHS_PER_SCAN; ++path) {
A[path] = new unsigned short **[firstImage.rows];
for (int row = 0; row < firstImage.rows; ++row) {
A[path][row] = new unsigned short*[firstImage.cols];
for (int col = 0; col < firstImage.cols; ++col) {
A[path][row][col] = new unsigned short[disparityRange];
for (unsigned int d = 0; d < disparityRange; ++d) {
A[path][row][col][d] = 0;
}
}
}
}
std::cout << "Smoothing images..." << std::endl;
grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS);
grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS);
std::cout << "Calculating pixel cost for the image..." << std::endl;
calculatePixelCost(firstImage, secondImage, disparityRange, C);
if(DEBUG) {
printArray(C, firstImage.rows, firstImage.cols, disparityRange);
}
std::cout << "Aggregating costs..." << std::endl;
aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, C, A, S);
cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0));
std::cout << "Computing disparity..." << std::endl;
computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
printf("Done in %.2lf seconds.\n", elapsed_secs);
saveDisparityMap(disparityMap, disparityRange, outFileName);
return 0;
}<commit_msg>Update main.cc, penalty compare at other<commit_after>#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <ctime>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "gaussian.h"
#define BLUR_RADIUS 3
#define PATHS_PER_SCAN 4
#define MAX_SHORT std::numeric_limits<unsigned short>::max()
#define SMALL_PENALTY 3
#define LARGE_PENALTY 20
#define DEBUG false
struct path {
short rowDiff;
short colDiff;
short index;
};
void printArray(unsigned short ***array, int rows, int cols, int depth) {
for (int d = 0; d < depth; ++d) {
std::cout << "disparity: " << d << std::endl;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
std::cout << "\t" << array[row][col][d];
}
std::cout << std::endl;
}
}
}
unsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {
char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax;
if(leftCol<0)
leftValue = 0;
else
leftValue = leftImage.at<uchar>(row, leftCol);
if(rightCol<0)
rightValue = 0;
else
rightValue = rightImage.at<uchar>(row, rightCol);
if (rightCol > 0) {
beforeRightValue = rightImage.at<uchar>(row, rightCol - 1);
} else {
beforeRightValue = rightValue;
}
//std::cout << rightCol <<" " <<leftCol<< std::endl;
if (rightCol + 1 < rightImage.cols && rightCol>0) {
afterRightValue = rightImage.at<uchar>(row, rightCol + 1);
} else {
afterRightValue = rightValue;
}
rightValueMinus = round((rightValue + beforeRightValue) / 2.f);
rightValuePlus = round((rightValue + afterRightValue) / 2.f);
rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus));
rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus));
return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue)));
}
inline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {
return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage),
calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage));
}
void calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) {
for (int row = 0; row < firstImage.rows; ++row) {
for (int col = 0; col < firstImage.cols; ++col) {
for (int d = 0; d < disparityRange; ++d) {
//std::cout << col << " " << d << " "<<disparityRange << " " << col - d << std::endl;
C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage);
}
}
}
}
// pathCount can be 1, 2, 4, or 8
void initializeFirstScanPaths(std::vector<path> &paths, unsigned short pathCount) {
for (unsigned short i = 0; i < pathCount; ++i) {
paths.push_back(path());
}
if(paths.size() >= 1) {
paths[0].rowDiff = 0;
paths[0].colDiff = -1;
paths[0].index = 1;
}
if(paths.size() >= 2) {
paths[1].rowDiff = -1;
paths[1].colDiff = 0;
paths[1].index = 2;
}
if(paths.size() >= 4) {
paths[2].rowDiff = -1;
paths[2].colDiff = 1;
paths[2].index = 4;
paths[3].rowDiff = -1;
paths[3].colDiff = -1;
paths[3].index = 7;
}
if(paths.size() >= 8) {
paths[4].rowDiff = -2;
paths[4].colDiff = 1;
paths[4].index = 8;
paths[5].rowDiff = -2;
paths[5].colDiff = -1;
paths[5].index = 9;
paths[6].rowDiff = -1;
paths[6].colDiff = -2;
paths[6].index = 13;
paths[7].rowDiff = -1;
paths[7].colDiff = 2;
paths[7].index = 15;
}
}
// pathCount can be 1, 2, 4, or 8
void initializeSecondScanPaths(std::vector<path> &paths, unsigned short pathCount) {
for (unsigned short i = 0; i < pathCount; ++i) {
paths.push_back(path());
}
if(paths.size() >= 1) {
paths[0].rowDiff = 0;
paths[0].colDiff = 1;
paths[0].index = 0;
}
if(paths.size() >= 2) {
paths[1].rowDiff = 1;
paths[1].colDiff = 0;
paths[1].index = 3;
}
if(paths.size() >= 4) {
paths[2].rowDiff = 1;
paths[2].colDiff = 1;
paths[2].index = 5;
paths[3].rowDiff = 1;
paths[3].colDiff = -1;
paths[3].index = 6;
}
if(paths.size() >= 8) {
paths[4].rowDiff = 2;
paths[4].colDiff = 1;
paths[4].index = 10;
paths[5].rowDiff = 2;
paths[5].colDiff = -1;
paths[5].index = 11;
paths[6].rowDiff = 1;
paths[6].colDiff = -2;
paths[6].index = 12;
paths[7].rowDiff = 1;
paths[7].colDiff = 2;
paths[7].index = 14;
}
}
unsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ***A) {
unsigned short aggregatedCost = 0;
aggregatedCost += C[row][col][d];
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)\n", p.index, row, col, d);
}
if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) {
// border
A[row][col][d] += aggregatedCost;
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)-> %d <BORDER>\n", p.index, row, col, d, A[row][col][d]);
}
return A[row][col][d];
}
unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus;
prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT;
for (int disp = 0; disp < disparityRange; ++disp) {
unsigned short tmp = A[row + p.rowDiff][col + p.colDiff][disp];
if(minPrev > tmp) {
minPrev = tmp;
}
if(disp == d) {
prev = tmp;
} else if(disp == d + 1) {
prevPlus = tmp;
} else if (disp == d - 1) {
prevMinus = tmp;
} else {
if(minPrevOther > tmp) {
minPrevOther = tmp;
}
}
}
aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY));
aggregatedCost -= minPrev;
A[row][col][d] += aggregatedCost;
if(DEBUG) {
printf("{P%d}[%d][%d](d%d)-> %d<CALCULATED>\n", p.index, row, col, d, A[row][col][d]);
}
return A[row][col][d];
}
float printProgress(unsigned int current, unsigned int max, int lastProgressPrinted) {
int progress = floor(100 * current / (float) max);
if(progress >= lastProgressPrinted + 5) {
lastProgressPrinted = lastProgressPrinted + 5;
std::cout << lastProgressPrinted << "%" << std::endl;
}
return lastProgressPrinted;
}
void aggregateCosts(int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ****A, unsigned short ***S) {
std::vector<path> firstScanPaths;
std::vector<path> secondScanPaths;
initializeFirstScanPaths(firstScanPaths, PATHS_PER_SCAN);
initializeSecondScanPaths(secondScanPaths, PATHS_PER_SCAN);
int lastProgressPrinted = 0;
std::cout << "First scan..." << std::endl;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
for (unsigned int path = 0; path < firstScanPaths.size(); ++path) {
for (int d = 0; d < disparityRange; ++d) {
S[row][col][d] += aggregateCost(row, col, d, firstScanPaths[path], rows, cols, disparityRange, C, A[path]);
}
}
}
lastProgressPrinted = printProgress(row, rows - 1, lastProgressPrinted);
}
lastProgressPrinted = 0;
std::cout << "Second scan..." << std::endl;
for (int row = rows - 1; row >= 0; --row) {
for (int col = cols - 1; col >= 0; --col) {
for (unsigned int path = 0; path < secondScanPaths.size(); ++path) {
for (int d = 0; d < disparityRange; ++d) {
S[row][col][d] += aggregateCost(row, col, d, secondScanPaths[path], rows, cols, disparityRange, C, A[path]);
}
}
}
lastProgressPrinted = printProgress(rows - 1 - row, rows - 1, lastProgressPrinted);
}
}
void computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) {
unsigned int disparity = 0, minCost;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
minCost = MAX_SHORT;
for (int d = disparityRange - 1; d >= 0; --d) {
if(minCost > S[row][col][d]) {
minCost = S[row][col][d];
disparity = d;
}
}
disparityMap.at<uchar>(row, col) = disparity;
}
}
}
void saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) {
double factor = 256.0 / disparityRange;
for (int row = 0; row < disparityMap.rows; ++row) {
for (int col = 0; col < disparityMap.cols; ++col) {
disparityMap.at<uchar>(row, col) *= factor;
}
}
cv::imwrite(outputFile, disparityMap);
}
int main(int argc, char** argv) {
if (argc != 5) {
std::cerr << "Usage: " << argv[0] << " <left image> <right image> <output image file> <disparity range>" << std::endl;
return -1;
}
char *firstFileName = argv[1];
char *secondFileName = argv[2];
char *outFileName = argv[3];
cv::Mat firstImage;
cv::Mat secondImage;
firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE);
secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE);
if(!firstImage.data || !secondImage.data) {
std::cerr << "Could not open or find one of the images!" << std::endl;
return -1;
}
unsigned int disparityRange = atoi(argv[4]);
unsigned short ***C; // pixel cost array W x H x D
unsigned short ***S; // aggregated cost array W x H x D
unsigned short ****A; // single path cost array 2 x W x H x D
/*
* TODO
* variable LARGE_PENALTY
*/
clock_t begin = clock();
std::cout << "Allocating space..." << std::endl;
// allocate cost arrays
C = new unsigned short**[firstImage.rows];
S = new unsigned short**[firstImage.rows];
for (int row = 0; row < firstImage.rows; ++row) {
C[row] = new unsigned short*[firstImage.cols];
S[row] = new unsigned short*[firstImage.cols]();
for (int col = 0; col < firstImage.cols; ++col) {
C[row][col] = new unsigned short[disparityRange];
S[row][col] = new unsigned short[disparityRange](); // initialize to 0
}
}
A = new unsigned short ***[PATHS_PER_SCAN];
for(int path = 0; path < PATHS_PER_SCAN; ++path) {
A[path] = new unsigned short **[firstImage.rows];
for (int row = 0; row < firstImage.rows; ++row) {
A[path][row] = new unsigned short*[firstImage.cols];
for (int col = 0; col < firstImage.cols; ++col) {
A[path][row][col] = new unsigned short[disparityRange];
for (unsigned int d = 0; d < disparityRange; ++d) {
A[path][row][col][d] = 0;
}
}
}
}
std::cout << "Smoothing images..." << std::endl;
grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS);
grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS);
std::cout << "Calculating pixel cost for the image..." << std::endl;
calculatePixelCost(firstImage, secondImage, disparityRange, C);
if(DEBUG) {
printArray(C, firstImage.rows, firstImage.cols, disparityRange);
}
std::cout << "Aggregating costs..." << std::endl;
aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, C, A, S);
cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0));
std::cout << "Computing disparity..." << std::endl;
computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap);
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
printf("Done in %.2lf seconds.\n", elapsed_secs);
saveDisparityMap(disparityMap, disparityRange, outFileName);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: w1par.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:19:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _PAM_HXX
#include <pam.hxx> // fuer SwPam
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx> // class SwTxtNode
#endif
#ifndef _FLTINI_HXX
#include <fltini.hxx> // Ww1Reader
#endif
#ifndef _W1PAR_HXX
#include <w1par.hxx>
#endif
#ifndef _SWFLTOPT_HXX
#include <swfltopt.hxx>
#endif
#ifndef _MDIEXP_HXX
#include <mdiexp.hxx> // StatLine...()
#endif
#ifndef _SWSWERROR_H
#include <swerror.h> // ERR_WW1_...
#endif
#ifndef _STATSTR_HRC
#include <statstr.hrc> // ResId fuer Statusleiste
#endif
//----------------------------------------
// Initialisieren der Feld-FilterFlags
//----------------------------------------
static ULONG WW1_Read_FieldIniFlags()
{
// USHORT i;
static const sal_Char* aNames[ 1 ] = { "WinWord/WW1F" };
sal_uInt32 aVal[ 1 ];
SwFilterOptions aOpt( 1, aNames, aVal );
ULONG nFieldFlags = aVal[ 0 ];
if ( SwFltGetFlag( nFieldFlags, SwFltControlStack::HYPO ) )
{
SwFltSetFlag( nFieldFlags, SwFltControlStack::BOOK_TO_VAR_REF );
SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_DO_ID );
SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_IN_TEXT );
SwFltSetFlag( nFieldFlags, SwFltControlStack::ALLOW_FLD_CR );
}
return nFieldFlags;
}
////////////////////////////////////////////////// StarWriter-Interface
//
// Eine Methode liefern die call-Schnittstelle fuer den Writer.
// Read() liest eine Datei. hierzu werden zwei Objekte erzeugt, die Shell,
// die die Informationen aufnimmt und der Manager der sie aus der Datei liest.
// Diese werden dann einfach per Pipe 'uebertragen'.
//
ULONG WW1Reader::Read(SwDoc& rDoc, const String& rBaseURL, SwPaM& rPam, const String& cName)
{
ULONG nRet = ERR_SWG_READ_ERROR;
ASSERT(pStrm!=NULL, "W1-Read ohne Stream");
if (pStrm != NULL)
{
BOOL bNew = !bInsertMode; // Neues Doc ( kein Einfuegen )
// erstmal eine shell konstruieren: die ist schnittstelle
// zum writer-dokument
ULONG nFieldFlags = WW1_Read_FieldIniFlags();
Ww1Shell* pRdr = new Ww1Shell( rDoc, rPam, rBaseURL, bNew, nFieldFlags );
if( pRdr )
{
// dann den manager, der liest die struktur des word-streams
Ww1Manager* pMan = new Ww1Manager( *pStrm, nFieldFlags );
if( pMan )
{
if( !pMan->GetError() )
{
::StartProgress( STR_STATSTR_W4WREAD, 0, 100,
rDoc.GetDocShell() );
::SetProgressState( 0, rDoc.GetDocShell() );
// jetzt nur noch alles rueberschieben
*pRdr << *pMan;
if( !pMan->GetError() )
// und nur hier, wenn kein fehler auftrat
// fehlerfreiheit melden
nRet = 0; // besser waere: WARN_SWG_FEATURES_LOST;
::EndProgress( rDoc.GetDocShell() );
}
else
{
if( pMan->GetFib().GetFIB().fComplexGet() )
//!!! ACHTUNG: hier muss eigentlich ein Error
// wegen Fastsave kommen, das der PMW-Filter
// das nicht unterstuetzt. Stattdessen temporaer
// nur eine Warnung, bis die entsprechende
// Meldung und Behandlung weiter oben eingebaut ist.
// nRet = WARN_WW6_FASTSAVE_ERR;
// Zum Einchecken mit neuem String:
nRet = ERR_WW6_FASTSAVE_ERR;
}
}
delete pMan;
}
delete pRdr;
}
Ww1Sprm::DeinitTab();
return nRet;
}
///////////////////////////////////////////////////////////////// Shell
//
// Die Shell ist die Schnittstelle vom Filter zum Writer. Sie ist
// abgeleitet von der mit ww-filter gemeinsam benutzten Shell
// SwFltShell und enthaelt alle fuer ww1 noetigen Erweiterungen. Wie
// in einen Stream werden alle Informationen, die aus der Datei
// gelesen werden, in die shell ge'piped'.
//
Ww1Shell::Ww1Shell( SwDoc& rD, SwPaM& rPam, const String& rBaseURL, BOOL bNew, ULONG nFieldFlags)
: SwFltShell(&rD, rPam, rBaseURL, bNew, nFieldFlags)
{
}
<commit_msg>INTEGRATION: CWS swwarnings (1.7.222); FILE MERGED 2007/03/15 15:52:15 tl 1.7.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: w1par.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2007-09-27 09:58:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _PAM_HXX
#include <pam.hxx> // fuer SwPam
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx> // class SwTxtNode
#endif
#ifndef _FLTINI_HXX
#include <fltini.hxx> // Ww1Reader
#endif
#ifndef _W1PAR_HXX
#include <w1par.hxx>
#endif
#ifndef _SWFLTOPT_HXX
#include <swfltopt.hxx>
#endif
#ifndef _MDIEXP_HXX
#include <mdiexp.hxx> // StatLine...()
#endif
#ifndef _SWSWERROR_H
#include <swerror.h> // ERR_WW1_...
#endif
#ifndef _STATSTR_HRC
#include <statstr.hrc> // ResId fuer Statusleiste
#endif
//----------------------------------------
// Initialisieren der Feld-FilterFlags
//----------------------------------------
static ULONG WW1_Read_FieldIniFlags()
{
// USHORT i;
static const sal_Char* aNames[ 1 ] = { "WinWord/WW1F" };
sal_uInt32 aVal[ 1 ];
SwFilterOptions aOpt( 1, aNames, aVal );
ULONG nFieldFlags = aVal[ 0 ];
if ( SwFltGetFlag( nFieldFlags, SwFltControlStack::HYPO ) )
{
SwFltSetFlag( nFieldFlags, SwFltControlStack::BOOK_TO_VAR_REF );
SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_DO_ID );
SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_IN_TEXT );
SwFltSetFlag( nFieldFlags, SwFltControlStack::ALLOW_FLD_CR );
}
return nFieldFlags;
}
////////////////////////////////////////////////// StarWriter-Interface
//
// Eine Methode liefern die call-Schnittstelle fuer den Writer.
// Read() liest eine Datei. hierzu werden zwei Objekte erzeugt, die Shell,
// die die Informationen aufnimmt und der Manager der sie aus der Datei liest.
// Diese werden dann einfach per Pipe 'uebertragen'.
//
ULONG WW1Reader::Read(SwDoc& rDoc, const String& rBaseURL, SwPaM& rPam, const String& /*cName*/)
{
ULONG nRet = ERR_SWG_READ_ERROR;
ASSERT(pStrm!=NULL, "W1-Read ohne Stream");
if (pStrm != NULL)
{
BOOL bNew = !bInsertMode; // Neues Doc ( kein Einfuegen )
// erstmal eine shell konstruieren: die ist schnittstelle
// zum writer-dokument
ULONG nFieldFlags = WW1_Read_FieldIniFlags();
Ww1Shell* pRdr = new Ww1Shell( rDoc, rPam, rBaseURL, bNew, nFieldFlags );
if( pRdr )
{
// dann den manager, der liest die struktur des word-streams
Ww1Manager* pMan = new Ww1Manager( *pStrm, nFieldFlags );
if( pMan )
{
if( !pMan->GetError() )
{
::StartProgress( STR_STATSTR_W4WREAD, 0, 100,
rDoc.GetDocShell() );
::SetProgressState( 0, rDoc.GetDocShell() );
// jetzt nur noch alles rueberschieben
*pRdr << *pMan;
if( !pMan->GetError() )
// und nur hier, wenn kein fehler auftrat
// fehlerfreiheit melden
nRet = 0; // besser waere: WARN_SWG_FEATURES_LOST;
::EndProgress( rDoc.GetDocShell() );
}
else
{
if( pMan->GetFib().GetFIB().fComplexGet() )
//!!! ACHTUNG: hier muss eigentlich ein Error
// wegen Fastsave kommen, das der PMW-Filter
// das nicht unterstuetzt. Stattdessen temporaer
// nur eine Warnung, bis die entsprechende
// Meldung und Behandlung weiter oben eingebaut ist.
// nRet = WARN_WW6_FASTSAVE_ERR;
// Zum Einchecken mit neuem String:
nRet = ERR_WW6_FASTSAVE_ERR;
}
}
delete pMan;
}
delete pRdr;
}
Ww1Sprm::DeinitTab();
return nRet;
}
///////////////////////////////////////////////////////////////// Shell
//
// Die Shell ist die Schnittstelle vom Filter zum Writer. Sie ist
// abgeleitet von der mit ww-filter gemeinsam benutzten Shell
// SwFltShell und enthaelt alle fuer ww1 noetigen Erweiterungen. Wie
// in einen Stream werden alle Informationen, die aus der Datei
// gelesen werden, in die shell ge'piped'.
//
Ww1Shell::Ww1Shell( SwDoc& rD, SwPaM& rPam, const String& rBaseURL, BOOL bNew, ULONG nFieldFlags)
: SwFltShell(&rD, rPam, rBaseURL, bNew, nFieldFlags)
{
}
<|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.
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include "hintids.hxx"
#include <svx/htmlmode.hxx>
#include <svl/style.hxx>
#include <svtools/htmlcfg.hxx>
#include <svl/svstdarr.hxx>
#include <svl/cjkoptions.hxx>
#include "docsh.hxx"
#include "wrtsh.hxx"
#include "frmatr.hxx"
#include "view.hxx"
#include "globals.hrc"
#include "swuipardlg.hxx"
#include "pagedesc.hxx"
#include "paratr.hxx"
#include "drpcps.hxx"
#include "uitool.hxx"
#include "viewopt.hxx"
#include <numpara.hxx>
#include "chrdlg.hrc"
#include "poolfmt.hrc"
#include <svx/svxids.hrc>
#include <svl/eitem.hxx>
#include <svl/intitem.hxx>
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
#include <svx/flagsdef.hxx>
SwParaDlg::SwParaDlg(Window *pParent,
SwView& rVw,
const SfxItemSet& rCoreSet,
sal_uInt8 nDialogMode,
const String *pTitle,
sal_Bool bDraw,
sal_uInt16 nDefPage):
SfxTabDialog(pParent, bDraw ? SW_RES(DLG_DRAWPARA) : SW_RES(DLG_PARA),
&rCoreSet, 0 != pTitle),
rView(rVw),
nDlgMode(nDialogMode),
bDrawParaDlg(bDraw)
{
FreeResource();
nHtmlMode = ::GetHtmlMode(rVw.GetDocShell());
sal_Bool bHtmlMode = static_cast< sal_Bool >(nHtmlMode & HTMLMODE_ON);
if(pTitle)
{
// Update title
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_TEXTCOLL_HEADER);
aTmp += *pTitle;
aTmp += ')';
SetText(aTmp);
}
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_STD_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_STD_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_STD, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_STD_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_STD_PARAGRAPH) );
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_ALIGN, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_ALIGN_PARAGRAPH) );
SvxHtmlOptions& rHtmlOpt = SvxHtmlOptions::Get();
if (!bDrawParaDlg && (!bHtmlMode || rHtmlOpt.IsPrintLayoutExtension()))
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_EXT_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_EXT_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_EXT, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_EXT_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_EXT_PARAGRAPH) );
}
else
RemoveTabPage(TP_PARA_EXT);
SvtCJKOptions aCJKOptions;
if(!bHtmlMode && aCJKOptions.IsAsianTypographyEnabled())
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_ASIAN, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), pFact->GetTabPageRangesFunc(RID_SVXPAGE_PARA_ASIAN) );
}
else
RemoveTabPage(TP_PARA_ASIAN);
sal_uInt16 nWhich(rCoreSet.GetPool()->GetWhich(SID_ATTR_LRSPACE));
sal_Bool bLRValid = SFX_ITEM_AVAILABLE <= rCoreSet.GetItemState(nWhich);
if(bHtmlMode || !bLRValid)
RemoveTabPage(TP_TABULATOR);
else
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_TABULATOR), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_TABULATOR), "GetTabPageRangesFunc fail!");
AddTabPage( TP_TABULATOR, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_TABULATOR), pFact->GetTabPageRangesFunc(RID_SVXPAGE_TABULATOR) );
}
if (!bDrawParaDlg)
{
if(!(nDlgMode & DLG_ENVELOP))
AddTabPage(TP_NUMPARA, SwParagraphNumTabPage::Create,SwParagraphNumTabPage::GetRanges);
else
RemoveTabPage(TP_NUMPARA);
if(!bHtmlMode || (nHtmlMode & HTMLMODE_FULL_STYLES))
{
AddTabPage(TP_DROPCAPS, SwDropCapsPage::Create, SwDropCapsPage::GetRanges);
}
else
{
RemoveTabPage(TP_DROPCAPS);
}
if(!bHtmlMode || (nHtmlMode & (HTMLMODE_SOME_STYLES|HTMLMODE_FULL_STYLES)))
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageRangesFunc fail!");
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), pFact->GetTabPageRangesFunc( RID_SVXPAGE_BACKGROUND ) );
}
else
{
RemoveTabPage(TP_BACKGROUND);
}
OSL_ENSURE(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc( RID_SVXPAGE_BORDER ), "GetTabPageRangesFunc fail!");
AddTabPage(TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), pFact->GetTabPageRangesFunc( RID_SVXPAGE_BORDER ) );
}
if (nDefPage)
SetCurPageId(nDefPage);
}
SwParaDlg::~SwParaDlg()
{
}
void SwParaDlg::PageCreated(sal_uInt16 nId, SfxTabPage& rPage)
{
SwWrtShell& rSh = rView.GetWrtShell();
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
// Table borders cannot get any shade in Writer
if (nId == TP_BORDER)
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_PARA));
rPage.PageCreated(aSet);
}
else if( nId == TP_PARA_STD )
{
aSet.Put(SfxUInt16Item(SID_SVXSTDPARAGRAPHTABPAGE_PAGEWIDTH,
static_cast< sal_uInt16 >(rSh.GetAnyCurRect(RECT_PAGE_PRT).Width()) ));
if (!bDrawParaDlg)
{
aSet.Put(SfxUInt32Item(SID_SVXSTDPARAGRAPHTABPAGE_FLAGSET,0x001E));
aSet.Put(SfxUInt32Item(SID_SVXSTDPARAGRAPHTABPAGE_ABSLINEDIST, MM50/10));
}
rPage.PageCreated(aSet);
}
else if( TP_PARA_ALIGN == nId)
{
if (!bDrawParaDlg)
{
aSet.Put(SfxBoolItem(SID_SVXPARAALIGNTABPAGE_ENABLEJUSTIFYEXT,sal_True));
rPage.PageCreated(aSet);
}
}
else if( TP_PARA_EXT == nId )
{
// pagebreak only when the cursor is in the body-area and not in a table
const sal_uInt16 eType = rSh.GetFrmType(0,sal_True);
if( !(FRMTYPE_BODY & eType) ||
rSh.GetSelectionType() & nsSelectionType::SEL_TBL )
{
aSet.Put(SfxBoolItem(SID_DISABLE_SVXEXTPARAGRAPHTABPAGE_PAGEBREAK,sal_True));
rPage.PageCreated(aSet);
}
}
else if( TP_DROPCAPS == nId )
{
((SwDropCapsPage&)rPage).SetFormat(sal_False);
}
else if( TP_BACKGROUND == nId )
{
if(!( nHtmlMode & HTMLMODE_ON ) ||
nHtmlMode & HTMLMODE_SOME_STYLES)
{
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, SVX_SHOW_SELECTOR));
rPage.PageCreated(aSet);
}
}
else if( TP_NUMPARA == nId)
{
SwTxtFmtColl* pTmpColl = rSh.GetCurTxtFmtColl();
if( pTmpColl && pTmpColl->IsAssignedToListLevelOfOutlineStyle() )
{
((SwParagraphNumTabPage&)rPage).DisableOutline() ;
}
((SwParagraphNumTabPage&)rPage).EnableNewStart();
ListBox & rBox = ((SwParagraphNumTabPage&)rPage).GetStyleBox();
SfxStyleSheetBasePool* pPool = rView.GetDocShell()->GetStyleSheetPool();
pPool->SetSearchMask(SFX_STYLE_FAMILY_PSEUDO, SFXSTYLEBIT_ALL);
const SfxStyleSheetBase* pBase = pPool->First();
std::set<String> aNames;
while(pBase)
{
aNames.insert(pBase->GetName());
pBase = pPool->Next();
}
for(std::set<String>::const_iterator it = aNames.begin(); it != aNames.end(); ++it)
rBox.InsertEntry(*it);
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>SwParaDlg::PageCreated: replace this hardwired 0x001E with something readable<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.
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include "hintids.hxx"
#include <svx/htmlmode.hxx>
#include <svl/style.hxx>
#include <svtools/htmlcfg.hxx>
#include <svl/svstdarr.hxx>
#include <svl/cjkoptions.hxx>
#include "docsh.hxx"
#include "wrtsh.hxx"
#include "frmatr.hxx"
#include "view.hxx"
#include "globals.hrc"
#include "swuipardlg.hxx"
#include "pagedesc.hxx"
#include "paratr.hxx"
#include "drpcps.hxx"
#include "uitool.hxx"
#include "viewopt.hxx"
#include <numpara.hxx>
#include "chrdlg.hrc"
#include "poolfmt.hrc"
#include <svx/svxids.hrc>
#include <svl/eitem.hxx>
#include <svl/intitem.hxx>
#include <svx/svxdlg.hxx>
#include <svx/dialogs.hrc>
#include <svx/flagsdef.hxx>
SwParaDlg::SwParaDlg(Window *pParent,
SwView& rVw,
const SfxItemSet& rCoreSet,
sal_uInt8 nDialogMode,
const String *pTitle,
sal_Bool bDraw,
sal_uInt16 nDefPage):
SfxTabDialog(pParent, bDraw ? SW_RES(DLG_DRAWPARA) : SW_RES(DLG_PARA),
&rCoreSet, 0 != pTitle),
rView(rVw),
nDlgMode(nDialogMode),
bDrawParaDlg(bDraw)
{
FreeResource();
nHtmlMode = ::GetHtmlMode(rVw.GetDocShell());
sal_Bool bHtmlMode = static_cast< sal_Bool >(nHtmlMode & HTMLMODE_ON);
if(pTitle)
{
// Update title
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_TEXTCOLL_HEADER);
aTmp += *pTitle;
aTmp += ')';
SetText(aTmp);
}
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_STD_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_STD_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_STD, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_STD_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_STD_PARAGRAPH) );
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_ALIGN, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_ALIGN_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_ALIGN_PARAGRAPH) );
SvxHtmlOptions& rHtmlOpt = SvxHtmlOptions::Get();
if (!bDrawParaDlg && (!bHtmlMode || rHtmlOpt.IsPrintLayoutExtension()))
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_EXT_PARAGRAPH), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_EXT_PARAGRAPH), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_EXT, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_EXT_PARAGRAPH), pFact->GetTabPageRangesFunc(RID_SVXPAGE_EXT_PARAGRAPH) );
}
else
RemoveTabPage(TP_PARA_EXT);
SvtCJKOptions aCJKOptions;
if(!bHtmlMode && aCJKOptions.IsAsianTypographyEnabled())
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_PARA_ASIAN), "GetTabPageRangesFunc fail!");
AddTabPage( TP_PARA_ASIAN, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_PARA_ASIAN), pFact->GetTabPageRangesFunc(RID_SVXPAGE_PARA_ASIAN) );
}
else
RemoveTabPage(TP_PARA_ASIAN);
sal_uInt16 nWhich(rCoreSet.GetPool()->GetWhich(SID_ATTR_LRSPACE));
sal_Bool bLRValid = SFX_ITEM_AVAILABLE <= rCoreSet.GetItemState(nWhich);
if(bHtmlMode || !bLRValid)
RemoveTabPage(TP_TABULATOR);
else
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc(RID_SVXPAGE_TABULATOR), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc(RID_SVXPAGE_TABULATOR), "GetTabPageRangesFunc fail!");
AddTabPage( TP_TABULATOR, pFact->GetTabPageCreatorFunc(RID_SVXPAGE_TABULATOR), pFact->GetTabPageRangesFunc(RID_SVXPAGE_TABULATOR) );
}
if (!bDrawParaDlg)
{
if(!(nDlgMode & DLG_ENVELOP))
AddTabPage(TP_NUMPARA, SwParagraphNumTabPage::Create,SwParagraphNumTabPage::GetRanges);
else
RemoveTabPage(TP_NUMPARA);
if(!bHtmlMode || (nHtmlMode & HTMLMODE_FULL_STYLES))
{
AddTabPage(TP_DROPCAPS, SwDropCapsPage::Create, SwDropCapsPage::GetRanges);
}
else
{
RemoveTabPage(TP_DROPCAPS);
}
if(!bHtmlMode || (nHtmlMode & (HTMLMODE_SOME_STYLES|HTMLMODE_FULL_STYLES)))
{
OSL_ENSURE(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc( RID_SVXPAGE_BACKGROUND ), "GetTabPageRangesFunc fail!");
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), pFact->GetTabPageRangesFunc( RID_SVXPAGE_BACKGROUND ) );
}
else
{
RemoveTabPage(TP_BACKGROUND);
}
OSL_ENSURE(pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), "GetTabPageCreatorFunc fail!");
OSL_ENSURE(pFact->GetTabPageRangesFunc( RID_SVXPAGE_BORDER ), "GetTabPageRangesFunc fail!");
AddTabPage(TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), pFact->GetTabPageRangesFunc( RID_SVXPAGE_BORDER ) );
}
if (nDefPage)
SetCurPageId(nDefPage);
}
SwParaDlg::~SwParaDlg()
{
}
void SwParaDlg::PageCreated(sal_uInt16 nId, SfxTabPage& rPage)
{
SwWrtShell& rSh = rView.GetWrtShell();
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
// Table borders cannot get any shade in Writer
if (nId == TP_BORDER)
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_PARA));
rPage.PageCreated(aSet);
}
else if( nId == TP_PARA_STD )
{
aSet.Put(SfxUInt16Item(SID_SVXSTDPARAGRAPHTABPAGE_PAGEWIDTH,
static_cast< sal_uInt16 >(rSh.GetAnyCurRect(RECT_PAGE_PRT).Width()) ));
if (!bDrawParaDlg)
{
// See SvxStdParagraphTabPage::PageCreated: enable RegisterMode, AutoFirstLine, NegativeMode, ContextualMode
aSet.Put(SfxUInt32Item(SID_SVXSTDPARAGRAPHTABPAGE_FLAGSET,0x0002|0x0004|0x0008|0x0010));
aSet.Put(SfxUInt32Item(SID_SVXSTDPARAGRAPHTABPAGE_ABSLINEDIST, MM50/10));
}
rPage.PageCreated(aSet);
}
else if( TP_PARA_ALIGN == nId)
{
if (!bDrawParaDlg)
{
aSet.Put(SfxBoolItem(SID_SVXPARAALIGNTABPAGE_ENABLEJUSTIFYEXT,sal_True));
rPage.PageCreated(aSet);
}
}
else if( TP_PARA_EXT == nId )
{
// pagebreak only when the cursor is in the body-area and not in a table
const sal_uInt16 eType = rSh.GetFrmType(0,sal_True);
if( !(FRMTYPE_BODY & eType) ||
rSh.GetSelectionType() & nsSelectionType::SEL_TBL )
{
aSet.Put(SfxBoolItem(SID_DISABLE_SVXEXTPARAGRAPHTABPAGE_PAGEBREAK,sal_True));
rPage.PageCreated(aSet);
}
}
else if( TP_DROPCAPS == nId )
{
((SwDropCapsPage&)rPage).SetFormat(sal_False);
}
else if( TP_BACKGROUND == nId )
{
if(!( nHtmlMode & HTMLMODE_ON ) ||
nHtmlMode & HTMLMODE_SOME_STYLES)
{
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, SVX_SHOW_SELECTOR));
rPage.PageCreated(aSet);
}
}
else if( TP_NUMPARA == nId)
{
SwTxtFmtColl* pTmpColl = rSh.GetCurTxtFmtColl();
if( pTmpColl && pTmpColl->IsAssignedToListLevelOfOutlineStyle() )
{
((SwParagraphNumTabPage&)rPage).DisableOutline() ;
}
((SwParagraphNumTabPage&)rPage).EnableNewStart();
ListBox & rBox = ((SwParagraphNumTabPage&)rPage).GetStyleBox();
SfxStyleSheetBasePool* pPool = rView.GetDocShell()->GetStyleSheetPool();
pPool->SetSearchMask(SFX_STYLE_FAMILY_PSEUDO, SFXSTYLEBIT_ALL);
const SfxStyleSheetBase* pBase = pPool->First();
std::set<String> aNames;
while(pBase)
{
aNames.insert(pBase->GetName());
pBase = pPool->Next();
}
for(std::set<String>::const_iterator it = aNames.begin(); it != aNames.end(); ++it)
rBox.InsertEntry(*it);
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <iostream>
#include <utility>
#include <unordered_set>
#include <unordered_map>
using namespace std;
#include "scx/Dir.hpp"
#include "scx/FileInfo.hpp"
using namespace scx;
#include "Tools.h"
#include "ConsUnit.h"
#include "Parallel.h"
static const unordered_set<string> C_EXT = { "c" };
static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" };
static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" };
namespace Error {
enum {
Argument = 1,
Permission,
Exist,
Empty,
Dependency,
Compile,
Link
};
}
static void Usage(const string& cmd)
{
const string sp(cmd.size(), ' ');
cout << ""
"Usage:\n"
"\t" + cmd + " [ file1 file2 ... | dir1 dir2 ... ]\n"
"\t" + sp + " as=? assembler\n"
"\t" + sp + " asflags=? assembler flags\n"
"\t" + sp + " cc=? c compiler\n"
"\t" + sp + " cflags=? c compiler flags\n"
"\t" + sp + " cxx=? c++ compiler\n"
"\t" + sp + " cxxflags=? c++ compiler flags\n"
"\t" + sp + " flags=? compiler common flags\n"
"\t" + sp + " ld=? linker\n"
"\t" + sp + " ldflags=? linker flags\n"
"\t" + sp + " ldfirst=? anchor first object file\n"
"\t" + sp + " jobs=? parallel build\n"
"\t" + sp + " workdir=? work direcotry\n"
"\t" + sp + " out=? binary output file name\n"
"\t" + sp + " prefix=? search head file and library in\n"
"\t" + sp + " nolink do not link\n"
"\t" + sp + " verbose verbose output\n"
"\t" + sp + " clean clean build output\n"
"\t" + sp + " help show this help message\n"
"\n"
"\t" + sp + " thread link against pthread\n"
"\t" + sp + " shared generate shared library\n"
"\n"
"\t" + sp + " strict -Wall -Wextra -Werror\n"
"\t" + sp + " release -DNDEBUG\n"
"\t" + sp + " debug -g\n"
"\t" + sp + " c++11 -std=c++11\n"
"\t" + sp + " c++14 -std=c++14\n"
"\t" + sp + " c++1y -std=c++1y\n"
"\t" + sp + " c++1z -std=c++1z\n"
"\n";
cout << ""
"Author:\n"
"\tYanhui Shen <@bsdelf on Twitter>\n";
}
int main(int argc, char** argv)
{
unordered_map<string, string> ArgTable = {
{ "as", "as" },
{ "asflags", "" },
{ "cc", "cc" },
{ "cflags", "" },
{ "cxx", "c++" },
{ "cxxflags", "" },
{ "flags", "" },
{ "ld", "cc" },
{ "ldflags", "" },
{ "ldfirst", "" },
{ "jobs", "0" },
{ "workdir", "" },
{ "out", "b.out" }
};
bool clean = false;
bool nolink = false;
bool verbose = false;
vector<string> allsrc;
vector<string> prefixes;
// Parse arguments.
{
bool useThread = false;
bool useShared = false;
bool useRelease = false;
bool useDebug = false;
bool useStrict = false;
bool usePipe = true;
bool useC89 = false;
bool useC99 = true;
bool useC11 = false;
bool useCXX11 = false;
bool useCXX14 = false;
bool useCXX1y = false;
bool useCXX1z = false;
for (int i = 1; i < argc; ++i) {
const string& arg(argv[i]);
// So obvisously, file name should not contain '='.
size_t pos = arg.find('=');
if (pos != string::npos && pos != arg.size()-1) {
const auto& key = arg.substr(0, pos);
const auto& val = arg.substr(pos+1);
// Update key-value.
auto iter = ArgTable.find(key);
if (iter != ArgTable.end()) {
iter->second = val;
} else if (key == "prefix") {
prefixes.push_back(val);
} else {
cout << "Argument ignored!" << endl;
cout << " Argument: " << arg << endl;
}
} else if (arg == "help") {
Usage(argv[0]);
return 0;
} else if (arg == "verbose") {
verbose = true;
} else if (arg == "nolink") {
nolink = true;
} else if (arg == "clean") {
clean = true;
} else if (arg == "thread") {
useThread = true;
} else if (arg == "strict") {
useStrict = true;
} else if (arg == "release") {
useRelease = true;
} else if (arg == "debug") {
useDebug = true;
} else if (arg == "shared") {
useShared = true;
} else if (arg == "c89") {
useC89 = true;
} else if (arg == "c99") {
useC99 = true;
} else if (arg == "c11") {
useC11 = true;
} else if (arg == "c++11") {
useCXX11 = true;
} else if (arg == "c++14") {
useCXX14 = true;
} else if (arg == "c++1y") {
useCXX1y = true;
} else if (arg == "c++1z") {
useCXX1z = true;
} else {
// Add source files
switch (FileInfo(arg).Type()) {
case FileType::Directory:
{
const auto& files = Dir::ListDir(arg);
allsrc.reserve(allsrc.size() + files.size());
allsrc.insert(allsrc.end(), files.begin(), files.end());
}
break;
case FileType::Regular:
{
allsrc.push_back(arg);
}
break;
default:
{
cerr << "FATAL: bad argument: " << endl;
cerr << "arg: " << arg << endl;
return Error::Argument;
}
break;
}
}
}
if (!ArgTable["workdir"].empty()) {
auto& dir = ArgTable["workdir"];
if (dir[dir.size()-1] != '/') {
dir += "/";
}
const auto& info = FileInfo(dir);
if (!info.Exists()) {
if (!Dir::MakeDir(dir, 0744)) {
cerr << "Failed to create directory!" << endl;
cerr << " Directory: " << dir << endl;
return Error::Permission;
}
} else if (info.Type() != FileType::Directory) {
cerr << "Bad work directory! " << endl;
cerr << " Directory: " << dir << endl;
cerr << " File type: " << FileType::ToString(info.Type()) << endl;
return Error::Exist;
}
}
//-------------------------------------------------------------
// additional compiler common flags
if (!ArgTable["flags"].empty()) {
ArgTable["flags"].insert(0, 1, ' ');
}
for (const auto& prefix: prefixes) {
ArgTable["flags"] += " -I " + prefix + "/include";
ArgTable["ldflags"] += " -L " + prefix + "/lib";
}
if (useStrict) {
ArgTable["flags"] += " -Wall -Wextra -Werror";
}
if (useRelease) {
ArgTable["flags"] += " -DNDEBUG";
} else if (useDebug) {
ArgTable["flags"] += " -g";
}
if (usePipe) {
ArgTable["flags"] += " -pipe";
}
if (useShared) {
ArgTable["flags"] += " -fPIC";
ArgTable["ldflags"] += " -shared";
}
//-------------------------------------------------------------
// additional link flags
if (!ArgTable["ldflags"].empty()) {
ArgTable["ldflags"].insert(0, 1, ' ');
}
if (useThread) {
ArgTable["flags"] += " -pthread";
#ifndef __APPLE__
ArgTable["ldflags"] += " -pthread";
#endif
}
//-------------------------------------------------------------
// additional c/c++ compiler flags
if (ArgTable["cflags"].empty()) {
ArgTable["cflags"] = ArgTable["flags"];
} else {
ArgTable["cflags"].insert(0, ArgTable["flags"] + " ");
}
if (useC89) {
ArgTable["cflags"] += " -std=c89";
} else if (useC99) {
ArgTable["cflags"] += " -std=c99";
} else if (useC11) {
ArgTable["cflags"] += " -std=c11";
}
if (ArgTable["cxxflags"].empty()) {
ArgTable["cxxflags"] = ArgTable["flags"];
} else {
ArgTable["cxxflags"].insert(0, ArgTable["flags"] + " ");
}
if (useCXX11) {
ArgTable["cxxflags"] += " -std=c++11";
} else if (useCXX14) {
ArgTable["cxxflags"] += " -std=c++14";
} else if (useCXX1y) {
ArgTable["cxxflags"] += " -std=c++1y";
} else if (useCXX1z) {
ArgTable["cxxflags"] += " -std=c++1z";
}
//-------------------------------------------------------------
// if unspecified, take all files under current folder
if (allsrc.empty()) {
allsrc = Dir::ListDir(".");
}
if (allsrc.empty()) {
cerr << "FATAL: nothing to build!" << endl;
return Error::Empty;
}
// sort by file path
std::sort(allsrc.begin(), allsrc.end(), [](const std::string& str1, const std::string& str2) {
return std::strcoll(str1.c_str(), str2.c_str()) < 0 ? true : false;
});
}
// Prepare construct units.
// Note: "workdir" & "out" should occur together
bool hasCpp = false;
bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists();
vector<ConsUnit> newUnits;
string allObjects;
for (const auto& file: allsrc) {
ConsUnit unit(ArgTable["workdir"], file);
string compiler;
string compilerFlag;
// Calculate dependence.
bool ok = false;
const string ext(FileInfo(file).Suffix());
if (C_EXT.find(ext) != C_EXT.end()) {
compiler = ArgTable["cc"];
compilerFlag = ArgTable["cflags"];
ok = ConsUnit::InitC(unit, compiler, compilerFlag);
} else if (CXX_EXT.find(ext) != CXX_EXT.end()) {
hasCpp = true;
compiler = ArgTable["cxx"];
compilerFlag = ArgTable["cxxflags"];
ok = ConsUnit::InitCpp(unit, compiler, compilerFlag);
} else if (ASM_EXT.find(ext) != ASM_EXT.end()) {
compiler = ArgTable["as"];
compilerFlag = ArgTable["asflags"];
ok = ConsUnit::InitAsm(unit, compiler, compilerFlag);
} else {
continue;
}
if (ok) {
if (unit.out == ArgTable["ldfirst"]) {
allObjects = " " + unit.out + allObjects;
} else {
allObjects += " " + unit.out;
}
if (!unit.cmd.empty()) {
newUnits.push_back(std::move(unit));
}
} else {
cerr << "FATAL: failed to calculate dependence!" << endl;
cerr << " file: " << file << endl;
cerr << " compiler: " << compiler << endl;
cerr << " flags: " << ArgTable["flags"] << endl;
cerr << " cflags: " << ArgTable["cflags"] << endl;
cerr << " cxxflags: " << ArgTable["cxxflags"] << endl;
return Error::Dependency;
}
}
if (hasCpp) {
ArgTable["ld"] = ArgTable["cxx"];
}
#ifdef DEBUG
// Debug info.
{
auto fn = [](const vector<ConsUnit>& units) {
for (const auto& unit: units) {
cout << "in: " << unit.in << ", " << "out: " << unit.out << endl;
cout << "\t" << unit.cmd << endl;
cout << "\t";
for (const auto& dep: unit.deps) {
cout << dep << ", ";
}
cout << endl;
}
};
cout << "new units: " << endl;
fn(newUnits);
}
#endif
// clean
if (clean) {
const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
cout << cmd << endl;
::system(cmd.c_str());
return 0;
}
// compile
if (!newUnits.empty()) {
cout << "* Build: ";
if (!verbose) {
cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
} else {
for (size_t i = 0; i < newUnits.size(); ++i) {
cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : "");
}
}
cout << endl;
ParallelCompiler pc(newUnits);
pc.SetVerbose(verbose);
if (pc.Run(std::stoi(ArgTable["jobs"])) != 0) {
return Error::Compile;
}
}
// link
if ((!hasOut || !newUnits.empty()) && !nolink) {
string ldCmd = ArgTable["ld"] + ArgTable["ldflags"];
ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
if (!verbose) {
cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl;
} else {
cout << "- Link - " << ldCmd << endl;
}
if (::system(ldCmd.c_str()) != 0) {
cerr << "FATAL: failed to link!" << endl;
cerr << " file: " << allObjects << endl;
cerr << " ld: " << ArgTable["ld"] << endl;
cerr << " ldflags: " << ArgTable["ldflags"] << endl;
return Error::Compile;
}
}
return 0;
}
<commit_msg>Minor change to help message<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <iostream>
#include <utility>
#include <unordered_set>
#include <unordered_map>
using namespace std;
#include "scx/Dir.hpp"
#include "scx/FileInfo.hpp"
using namespace scx;
#include "Tools.h"
#include "ConsUnit.h"
#include "Parallel.h"
static const unordered_set<string> C_EXT = { "c" };
static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" };
static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" };
namespace Error {
enum {
Argument = 1,
Permission,
Exist,
Empty,
Dependency,
Compile,
Link
};
}
static void Usage(const string& cmd)
{
const string sp(cmd.size(), ' ');
cout << ""
"Usage:\n"
"\t" + cmd + " [files ...] [dirs ...]\n"
"\t" + sp + " as=? assembler\n"
"\t" + sp + " asflags=? assembler flags\n"
"\t" + sp + " cc=? c compiler\n"
"\t" + sp + " cflags=? c compiler flags\n"
"\t" + sp + " cxx=? c++ compiler\n"
"\t" + sp + " cxxflags=? c++ compiler flags\n"
"\t" + sp + " flags=? compiler common flags\n"
"\t" + sp + " ld=? linker\n"
"\t" + sp + " ldflags=? linker flags\n"
"\t" + sp + " ldfirst=? anchor first object file\n"
"\t" + sp + " jobs=? parallel build\n"
"\t" + sp + " workdir=? work direcotry\n"
"\t" + sp + " out=? binary output file name\n"
"\t" + sp + " prefix=? search head file and library in\n"
"\t" + sp + " nolink do not link\n"
"\t" + sp + " verbose verbose output\n"
"\t" + sp + " clean clean build output\n"
"\t" + sp + " help show this help message\n"
"\n"
"\t" + sp + " thread link against pthread\n"
"\t" + sp + " shared generate shared library\n"
"\n"
"\t" + sp + " strict -Wall -Wextra -Werror\n"
"\t" + sp + " release -DNDEBUG\n"
"\t" + sp + " debug -g\n"
"\t" + sp + " c++11 -std=c++11\n"
"\t" + sp + " c++14 -std=c++14\n"
"\t" + sp + " c++1y -std=c++1y\n"
"\t" + sp + " c++1z -std=c++1z\n"
"\n";
cout << ""
"Author:\n"
"\tYanhui Shen <@bsdelf on Twitter>\n";
}
int main(int argc, char** argv)
{
unordered_map<string, string> ArgTable = {
{ "as", "as" },
{ "asflags", "" },
{ "cc", "cc" },
{ "cflags", "" },
{ "cxx", "c++" },
{ "cxxflags", "" },
{ "flags", "" },
{ "ld", "cc" },
{ "ldflags", "" },
{ "ldfirst", "" },
{ "jobs", "0" },
{ "workdir", "" },
{ "out", "b.out" }
};
bool clean = false;
bool nolink = false;
bool verbose = false;
vector<string> allsrc;
vector<string> prefixes;
// Parse arguments.
{
bool useThread = false;
bool useShared = false;
bool useRelease = false;
bool useDebug = false;
bool useStrict = false;
bool usePipe = true;
bool useC89 = false;
bool useC99 = true;
bool useC11 = false;
bool useCXX11 = false;
bool useCXX14 = false;
bool useCXX1y = false;
bool useCXX1z = false;
for (int i = 1; i < argc; ++i) {
const string& arg(argv[i]);
// So obvisously, file name should not contain '='.
size_t pos = arg.find('=');
if (pos != string::npos && pos != arg.size()-1) {
const auto& key = arg.substr(0, pos);
const auto& val = arg.substr(pos+1);
// Update key-value.
auto iter = ArgTable.find(key);
if (iter != ArgTable.end()) {
iter->second = val;
} else if (key == "prefix") {
prefixes.push_back(val);
} else {
cout << "Argument ignored!" << endl;
cout << " Argument: " << arg << endl;
}
} else if (arg == "help") {
Usage(argv[0]);
return 0;
} else if (arg == "verbose") {
verbose = true;
} else if (arg == "nolink") {
nolink = true;
} else if (arg == "clean") {
clean = true;
} else if (arg == "thread") {
useThread = true;
} else if (arg == "strict") {
useStrict = true;
} else if (arg == "release") {
useRelease = true;
} else if (arg == "debug") {
useDebug = true;
} else if (arg == "shared") {
useShared = true;
} else if (arg == "c89") {
useC89 = true;
} else if (arg == "c99") {
useC99 = true;
} else if (arg == "c11") {
useC11 = true;
} else if (arg == "c++11") {
useCXX11 = true;
} else if (arg == "c++14") {
useCXX14 = true;
} else if (arg == "c++1y") {
useCXX1y = true;
} else if (arg == "c++1z") {
useCXX1z = true;
} else {
// Add source files
switch (FileInfo(arg).Type()) {
case FileType::Directory:
{
const auto& files = Dir::ListDir(arg);
allsrc.reserve(allsrc.size() + files.size());
allsrc.insert(allsrc.end(), files.begin(), files.end());
}
break;
case FileType::Regular:
{
allsrc.push_back(arg);
}
break;
default:
{
cerr << "FATAL: bad argument: " << endl;
cerr << "arg: " << arg << endl;
return Error::Argument;
}
break;
}
}
}
if (!ArgTable["workdir"].empty()) {
auto& dir = ArgTable["workdir"];
if (dir[dir.size()-1] != '/') {
dir += "/";
}
const auto& info = FileInfo(dir);
if (!info.Exists()) {
if (!Dir::MakeDir(dir, 0744)) {
cerr << "Failed to create directory!" << endl;
cerr << " Directory: " << dir << endl;
return Error::Permission;
}
} else if (info.Type() != FileType::Directory) {
cerr << "Bad work directory! " << endl;
cerr << " Directory: " << dir << endl;
cerr << " File type: " << FileType::ToString(info.Type()) << endl;
return Error::Exist;
}
}
//-------------------------------------------------------------
// additional compiler common flags
if (!ArgTable["flags"].empty()) {
ArgTable["flags"].insert(0, 1, ' ');
}
for (const auto& prefix: prefixes) {
ArgTable["flags"] += " -I " + prefix + "/include";
ArgTable["ldflags"] += " -L " + prefix + "/lib";
}
if (useStrict) {
ArgTable["flags"] += " -Wall -Wextra -Werror";
}
if (useRelease) {
ArgTable["flags"] += " -DNDEBUG";
} else if (useDebug) {
ArgTable["flags"] += " -g";
}
if (usePipe) {
ArgTable["flags"] += " -pipe";
}
if (useShared) {
ArgTable["flags"] += " -fPIC";
ArgTable["ldflags"] += " -shared";
}
//-------------------------------------------------------------
// additional link flags
if (!ArgTable["ldflags"].empty()) {
ArgTable["ldflags"].insert(0, 1, ' ');
}
if (useThread) {
ArgTable["flags"] += " -pthread";
#ifndef __APPLE__
ArgTable["ldflags"] += " -pthread";
#endif
}
//-------------------------------------------------------------
// additional c/c++ compiler flags
if (ArgTable["cflags"].empty()) {
ArgTable["cflags"] = ArgTable["flags"];
} else {
ArgTable["cflags"].insert(0, ArgTable["flags"] + " ");
}
if (useC89) {
ArgTable["cflags"] += " -std=c89";
} else if (useC99) {
ArgTable["cflags"] += " -std=c99";
} else if (useC11) {
ArgTable["cflags"] += " -std=c11";
}
if (ArgTable["cxxflags"].empty()) {
ArgTable["cxxflags"] = ArgTable["flags"];
} else {
ArgTable["cxxflags"].insert(0, ArgTable["flags"] + " ");
}
if (useCXX11) {
ArgTable["cxxflags"] += " -std=c++11";
} else if (useCXX14) {
ArgTable["cxxflags"] += " -std=c++14";
} else if (useCXX1y) {
ArgTable["cxxflags"] += " -std=c++1y";
} else if (useCXX1z) {
ArgTable["cxxflags"] += " -std=c++1z";
}
//-------------------------------------------------------------
// if unspecified, take all files under current folder
if (allsrc.empty()) {
allsrc = Dir::ListDir(".");
}
if (allsrc.empty()) {
cerr << "FATAL: nothing to build!" << endl;
return Error::Empty;
}
// sort by file path
std::sort(allsrc.begin(), allsrc.end(), [](const std::string& str1, const std::string& str2) {
return std::strcoll(str1.c_str(), str2.c_str()) < 0 ? true : false;
});
}
// Prepare construct units.
// Note: "workdir" & "out" should occur together
bool hasCpp = false;
bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists();
vector<ConsUnit> newUnits;
string allObjects;
for (const auto& file: allsrc) {
ConsUnit unit(ArgTable["workdir"], file);
string compiler;
string compilerFlag;
// Calculate dependence.
bool ok = false;
const string ext(FileInfo(file).Suffix());
if (C_EXT.find(ext) != C_EXT.end()) {
compiler = ArgTable["cc"];
compilerFlag = ArgTable["cflags"];
ok = ConsUnit::InitC(unit, compiler, compilerFlag);
} else if (CXX_EXT.find(ext) != CXX_EXT.end()) {
hasCpp = true;
compiler = ArgTable["cxx"];
compilerFlag = ArgTable["cxxflags"];
ok = ConsUnit::InitCpp(unit, compiler, compilerFlag);
} else if (ASM_EXT.find(ext) != ASM_EXT.end()) {
compiler = ArgTable["as"];
compilerFlag = ArgTable["asflags"];
ok = ConsUnit::InitAsm(unit, compiler, compilerFlag);
} else {
continue;
}
if (ok) {
if (unit.out == ArgTable["ldfirst"]) {
allObjects = " " + unit.out + allObjects;
} else {
allObjects += " " + unit.out;
}
if (!unit.cmd.empty()) {
newUnits.push_back(std::move(unit));
}
} else {
cerr << "FATAL: failed to calculate dependence!" << endl;
cerr << " file: " << file << endl;
cerr << " compiler: " << compiler << endl;
cerr << " flags: " << ArgTable["flags"] << endl;
cerr << " cflags: " << ArgTable["cflags"] << endl;
cerr << " cxxflags: " << ArgTable["cxxflags"] << endl;
return Error::Dependency;
}
}
if (hasCpp) {
ArgTable["ld"] = ArgTable["cxx"];
}
#ifdef DEBUG
// Debug info.
{
auto fn = [](const vector<ConsUnit>& units) {
for (const auto& unit: units) {
cout << "in: " << unit.in << ", " << "out: " << unit.out << endl;
cout << "\t" << unit.cmd << endl;
cout << "\t";
for (const auto& dep: unit.deps) {
cout << dep << ", ";
}
cout << endl;
}
};
cout << "new units: " << endl;
fn(newUnits);
}
#endif
// clean
if (clean) {
const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
cout << cmd << endl;
::system(cmd.c_str());
return 0;
}
// compile
if (!newUnits.empty()) {
cout << "* Build: ";
if (!verbose) {
cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
} else {
for (size_t i = 0; i < newUnits.size(); ++i) {
cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : "");
}
}
cout << endl;
ParallelCompiler pc(newUnits);
pc.SetVerbose(verbose);
if (pc.Run(std::stoi(ArgTable["jobs"])) != 0) {
return Error::Compile;
}
}
// link
if ((!hasOut || !newUnits.empty()) && !nolink) {
string ldCmd = ArgTable["ld"] + ArgTable["ldflags"];
ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
if (!verbose) {
cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl;
} else {
cout << "- Link - " << ldCmd << endl;
}
if (::system(ldCmd.c_str()) != 0) {
cerr << "FATAL: failed to link!" << endl;
cerr << " file: " << allObjects << endl;
cerr << " ld: " << ArgTable["ld"] << endl;
cerr << " ldflags: " << ArgTable["ldflags"] << endl;
return Error::Compile;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
* All rights reserved.
*/
#include "terrain.h"
#include <vector>
#include "../common/log.h"
#include <png.h>
#include "../common/debugging.h"
namespace game { namespace strat
{
Noise_Raii::Noise_Raii(int64_t seed, osn_context** ptr) noexcept
{
// Pointer to an empty pointer given, allocate it and point our parameter
// to it.
if(!(*ptr))
{
open_simplex_noise(seed, ptr);
ptr_ = *ptr;
allocated_ = true;
}
else allocated_ = false;
// If the ptr was valid it doesn't need to be initialized so don't do it.
}
Noise_Raii::~Noise_Raii() noexcept
{
if(allocated_) open_simplex_noise_free(ptr_);
}
// This function could be run alone.
void terrain_v1_radial_land(Grid_Map& map, Terrain_Params const& tp) noexcept
{
osn_context* osn = nullptr;
auto noise_init = Noise_Raii{tp.seed, &osn};
for(int i = 0; i < map.extents.y; ++i)
{
for(int j = 0; j < map.extents.x; ++j)
{
// Point from the continent origin to here.
Vec<float> to_here = Vec<int>{j, i} - tp.origin;
auto to_here_dir = normalize(to_here);
// Tp size is more like diameter, but not necessarily any particular
// value.
auto radius = tp.size / 2.0f;
// Given the direction and radius find the circle edge. This value
// should be the same for every vector with equal direction, but not
// necessarily length.
auto circle_edge = tp.origin + to_here_dir * radius;
// Angle from origin
auto angle = std::atan2(to_here_dir.y, to_here_dir.x);
// Get a small delta from the angle. We will use this to modify the
auto delta = open_simplex_noise2(osn, to_here_dir.y,
to_here_dir.x) * tp.radial.amplitude;
auto modified_radius = radius + delta;
// This tile is land.
if(length(to_here) < modified_radius)
{
map.values[i * map.extents.x + j].type = Cell_Type::Land;
}
else
{
map.values[i * map.extents.x + j].type = Cell_Type::Water;
}
}
}
}
void terrain_v1_map(Grid_Map& map, Terrain_Params const& ter_params) noexcept
{
switch(ter_params.algorithm)
{
case Landmass_Algorithm::Radial:
terrain_v1_radial_land(map, ter_params);
break;
case Landmass_Algorithm::Other:
ter_params.other.gen_fn(map, ter_params);
}
}
void write_png_heightmap(Grid_Map const& map,
std::string const& filename) noexcept
{
// All this code is pretty much based completely on the libpng manual so
// check that out.
std::FILE* fp = std::fopen(filename.data(), "wb");
if(!fp)
{
log_w("Failed to open file '%'", filename);
return;
}
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if(!png_ptr)
{
log_w("Failed to initialize libpng to write file '%'", filename);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_write_struct(&png_ptr, NULL);
log_w("Failed to initialize png info to write '%'", filename);
return;
}
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
log_w("libpng error for '%'", filename);
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr, map.extents.x, map.extents.y, 8,
PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
std::vector<uint8_t*> ptrs;
for(int i = 0; i < map.extents.y; ++i)
{
ptrs.push_back(new uint8_t[map.extents.x * 3]);
for(int j = 0; j < map.extents.x; ++j)
{
uint8_t value = 0xff;
if(map.values[i * map.extents.x + j].type == Cell_Type::Water)
{
value = 0;
}
ptrs.back()[j * 3] = value;
ptrs.back()[j * 3 + 1] = value;
ptrs.back()[j * 3 + 2] = value;
}
}
png_set_rows(png_ptr, info_ptr, &ptrs[0]);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
for(auto* ptr : ptrs) delete ptr;
png_destroy_write_struct(&png_ptr, &info_ptr);
}
} }
<commit_msg>Remove an unused variable in terrain.cpp<commit_after>/*
* Copyright (C) 2015 Luke San Antonio and Hazza Alkaabi
* All rights reserved.
*/
#include "terrain.h"
#include <vector>
#include "../common/log.h"
#include <png.h>
#include "../common/debugging.h"
namespace game { namespace strat
{
Noise_Raii::Noise_Raii(int64_t seed, osn_context** ptr) noexcept
{
// Pointer to an empty pointer given, allocate it and point our parameter
// to it.
if(!(*ptr))
{
open_simplex_noise(seed, ptr);
ptr_ = *ptr;
allocated_ = true;
}
else allocated_ = false;
// If the ptr was valid it doesn't need to be initialized so don't do it.
}
Noise_Raii::~Noise_Raii() noexcept
{
if(allocated_) open_simplex_noise_free(ptr_);
}
// This function could be run alone.
void terrain_v1_radial_land(Grid_Map& map, Terrain_Params const& tp) noexcept
{
osn_context* osn = nullptr;
auto noise_init = Noise_Raii{tp.seed, &osn};
for(int i = 0; i < map.extents.y; ++i)
{
for(int j = 0; j < map.extents.x; ++j)
{
// Point from the continent origin to here.
Vec<float> to_here = Vec<int>{j, i} - tp.origin;
auto to_here_dir = normalize(to_here);
// Tp size is more like diameter, but not necessarily any particular
// value.
auto radius = tp.size / 2.0f;
// Angle from origin
auto angle = std::atan2(to_here_dir.y, to_here_dir.x);
// Get a small delta from the angle. We will use this to modify the
auto delta = open_simplex_noise2(osn, to_here_dir.y,
to_here_dir.x) * tp.radial.amplitude;
auto modified_radius = radius + delta;
// This tile is land.
if(length(to_here) < modified_radius)
{
map.values[i * map.extents.x + j].type = Cell_Type::Land;
}
else
{
map.values[i * map.extents.x + j].type = Cell_Type::Water;
}
}
}
}
void terrain_v1_map(Grid_Map& map, Terrain_Params const& ter_params) noexcept
{
switch(ter_params.algorithm)
{
case Landmass_Algorithm::Radial:
terrain_v1_radial_land(map, ter_params);
break;
case Landmass_Algorithm::Other:
ter_params.other.gen_fn(map, ter_params);
}
}
void write_png_heightmap(Grid_Map const& map,
std::string const& filename) noexcept
{
// All this code is pretty much based completely on the libpng manual so
// check that out.
std::FILE* fp = std::fopen(filename.data(), "wb");
if(!fp)
{
log_w("Failed to open file '%'", filename);
return;
}
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if(!png_ptr)
{
log_w("Failed to initialize libpng to write file '%'", filename);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
{
png_destroy_write_struct(&png_ptr, NULL);
log_w("Failed to initialize png info to write '%'", filename);
return;
}
if(setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
log_w("libpng error for '%'", filename);
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr, map.extents.x, map.extents.y, 8,
PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
std::vector<uint8_t*> ptrs;
for(int i = 0; i < map.extents.y; ++i)
{
ptrs.push_back(new uint8_t[map.extents.x * 3]);
for(int j = 0; j < map.extents.x; ++j)
{
uint8_t value = 0xff;
if(map.values[i * map.extents.x + j].type == Cell_Type::Water)
{
value = 0;
}
ptrs.back()[j * 3] = value;
ptrs.back()[j * 3 + 1] = value;
ptrs.back()[j * 3 + 2] = value;
}
}
png_set_rows(png_ptr, info_ptr, &ptrs[0]);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
for(auto* ptr : ptrs) delete ptr;
png_destroy_write_struct(&png_ptr, &info_ptr);
}
} }
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: convert.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:32:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _MODOPT_HXX //autogen
#include <modcfg.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "tblafmt.hxx"
#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx"
namespace swui
{
SwAbstractDialogFactory * GetFactory();
}
//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';
void SwConvertTableDlg::GetValues( sal_Unicode& rDelim,
SwInsertTableOptions& rInsTblOpts,
SwTableAutoFmt *& prTAFmt )
{
if( aTabBtn.IsChecked() )
{
//0x0b mustn't be set when re-converting table into text
bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
rDelim = bIsKeepColumn ? 0x09 : 0x0b;
nSaveButtonState = 0;
}
else if( aSemiBtn.IsChecked() )
{
rDelim = ';';
nSaveButtonState = 1;
}
else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
{
uOther = aOtherEd.GetText().GetChar( 0 );
rDelim = uOther;
nSaveButtonState = 3;
}
else
{
nSaveButtonState = 2;
rDelim = cParaDelim;
if(aOtherBtn.IsChecked())
{
nSaveButtonState = 3;
uOther = 0;
}
}
USHORT nInsMode = 0;
if (aBorderCB.IsChecked())
nInsMode |= tabopts::DEFAULT_BORDER;
if (aHeaderCB.IsChecked())
nInsMode |= tabopts::HEADLINE;
if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
else
rInsTblOpts.mnRowsToRepeat = 0;
if (!aDontSplitCB.IsChecked())
nInsMode |= tabopts::SPLIT_LAYOUT;
if( pTAutoFmt )
prTAFmt = new SwTableAutoFmt( *pTAutoFmt );
rInsTblOpts.mnInsMode = nInsMode;
}
SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )
: SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
aTabBtn (this, SW_RES(CB_TAB)),
aSemiBtn (this, SW_RES(CB_SEMI)),
aParaBtn (this, SW_RES(CB_PARA)),
aOtherBtn (this, SW_RES(RB_OTHER)),
aOtherEd (this, SW_RES(ED_OTHER)),
aKeepColumn (this, SW_RES(CB_KEEPCOLUMN)),
aDelimFL (this, SW_RES(FL_DELIM)),
aHeaderCB (this, SW_RES(CB_HEADER)),
aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),
aRepeatHeaderFT (this, SW_RES(FT_REPEAT_HEADER)),
aRepeatHeaderBeforeFT (this),
aRepeatHeaderNF (this, SW_RES(NF_REPEAT_HEADER)),
aRepeatHeaderAfterFT (this),
aRepeatHeaderCombo (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),
aDontSplitCB (this, SW_RES(CB_DONT_SPLIT)),
aBorderCB (this, SW_RES(CB_BORDER)),
aOptionsFL (this, SW_RES(FL_OPTIONS)),
aOkBtn(this,SW_RES(BT_OK)),
aCancelBtn(this,SW_RES(BT_CANCEL)),
aHelpBtn(this, SW_RES(BT_HELP)),
aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE)),
pTAutoFmt( 0 ),
pShell( &rView.GetWrtShell() )
{
FreeResource();
if(nSaveButtonState > -1)
{
switch (nSaveButtonState)
{
case 0:
aTabBtn.Check();
aKeepColumn.Check(bIsKeepColumn);
break;
case 1: aSemiBtn.Check();break;
case 2: aParaBtn.Check();break;
case 3:
aOtherBtn.Check();
if(uOther)
aOtherEd.SetText(uOther);
break;
}
}
if( bToTable )
{
SetText( sConvertTextTable );
aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
aAutoFmtBtn.Show();
aKeepColumn.Show();
aKeepColumn.Enable( aTabBtn.IsChecked() );
aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
}
else
{
//Einfuege-Optionen verstecken
aHeaderCB .Show(FALSE);
aRepeatHeaderCB .Show(FALSE);
aDontSplitCB .Show(FALSE);
aBorderCB .Show(FALSE);
aOptionsFL .Show(FALSE);
aRepeatHeaderCombo.Show(FALSE);
//Groesse anpassen
Size aSize(GetSizePixel());
aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
SetOutputSizePixel(aSize);
}
aKeepColumn.SaveValue();
Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
aTabBtn.SetClickHdl( aLk );
aSemiBtn.SetClickHdl( aLk );
aParaBtn.SetClickHdl( aLk );
aOtherBtn.SetClickHdl(aLk );
aOtherEd.Enable( aOtherBtn.IsChecked() );
const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();
BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);
SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
USHORT nInsTblFlags = aInsOpts.mnInsMode;
aHeaderCB.Check( 0 != (nInsTblFlags & tabopts::HEADLINE) );
aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
aDontSplitCB.Check( 0 == (nInsTblFlags & tabopts::SPLIT_LAYOUT));
aBorderCB.Check( 0!= (nInsTblFlags & tabopts::DEFAULT_BORDER) );
aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
ReapeatHeaderCheckBoxHdl();
CheckBoxHdl();
}
SwConvertTableDlg:: ~SwConvertTableDlg()
{
delete pTAutoFmt;
}
IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
SwAbstractDialogFactory* pFact = swui::GetFactory();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
DBG_ASSERT(pDlg, "Dialogdiet fail!");
if( RET_OK == pDlg->Execute())
pDlg->FillAutoFmtOfIndex( pTAutoFmt );
delete pDlg;
return 0;
}
IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
if( pButton == &aTabBtn )
aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
else
{
if( aKeepColumn.IsEnabled() )
aKeepColumn.SaveValue();
aKeepColumn.Check( TRUE );
}
aKeepColumn.Enable( aTabBtn.IsChecked() );
aOtherEd.Enable( aOtherBtn.IsChecked() );
return 0;
}
/*********************************************************************/
/* */
/*********************************************************************/
IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
ReapeatHeaderCheckBoxHdl();
return 0;
}
IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
aRepeatHeaderBeforeFT.Enable(bEnable);
aRepeatHeaderAfterFT.Enable(bEnable);
aRepeatHeaderNF.Enable(bEnable);
return 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.15.242); FILE MERGED 2008/04/01 15:59:42 thb 1.15.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:52 thb 1.15.242.2: #i85898# Stripping all external header guards 2008/03/31 16:59:32 rt 1.15.242.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: convert.cxx,v $
* $Revision: 1.16 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#include <vcl/msgbox.hxx>
#include <svtools/stritem.hxx>
#include <sfx2/viewfrm.hxx>
#include <modcfg.hxx>
#include <svx/htmlmode.hxx>
#include <viewopt.hxx>
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "tblafmt.hxx"
#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx"
namespace swui
{
SwAbstractDialogFactory * GetFactory();
}
//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';
void SwConvertTableDlg::GetValues( sal_Unicode& rDelim,
SwInsertTableOptions& rInsTblOpts,
SwTableAutoFmt *& prTAFmt )
{
if( aTabBtn.IsChecked() )
{
//0x0b mustn't be set when re-converting table into text
bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
rDelim = bIsKeepColumn ? 0x09 : 0x0b;
nSaveButtonState = 0;
}
else if( aSemiBtn.IsChecked() )
{
rDelim = ';';
nSaveButtonState = 1;
}
else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
{
uOther = aOtherEd.GetText().GetChar( 0 );
rDelim = uOther;
nSaveButtonState = 3;
}
else
{
nSaveButtonState = 2;
rDelim = cParaDelim;
if(aOtherBtn.IsChecked())
{
nSaveButtonState = 3;
uOther = 0;
}
}
USHORT nInsMode = 0;
if (aBorderCB.IsChecked())
nInsMode |= tabopts::DEFAULT_BORDER;
if (aHeaderCB.IsChecked())
nInsMode |= tabopts::HEADLINE;
if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
else
rInsTblOpts.mnRowsToRepeat = 0;
if (!aDontSplitCB.IsChecked())
nInsMode |= tabopts::SPLIT_LAYOUT;
if( pTAutoFmt )
prTAFmt = new SwTableAutoFmt( *pTAutoFmt );
rInsTblOpts.mnInsMode = nInsMode;
}
SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )
: SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
aTabBtn (this, SW_RES(CB_TAB)),
aSemiBtn (this, SW_RES(CB_SEMI)),
aParaBtn (this, SW_RES(CB_PARA)),
aOtherBtn (this, SW_RES(RB_OTHER)),
aOtherEd (this, SW_RES(ED_OTHER)),
aKeepColumn (this, SW_RES(CB_KEEPCOLUMN)),
aDelimFL (this, SW_RES(FL_DELIM)),
aHeaderCB (this, SW_RES(CB_HEADER)),
aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),
aRepeatHeaderFT (this, SW_RES(FT_REPEAT_HEADER)),
aRepeatHeaderBeforeFT (this),
aRepeatHeaderNF (this, SW_RES(NF_REPEAT_HEADER)),
aRepeatHeaderAfterFT (this),
aRepeatHeaderCombo (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),
aDontSplitCB (this, SW_RES(CB_DONT_SPLIT)),
aBorderCB (this, SW_RES(CB_BORDER)),
aOptionsFL (this, SW_RES(FL_OPTIONS)),
aOkBtn(this,SW_RES(BT_OK)),
aCancelBtn(this,SW_RES(BT_CANCEL)),
aHelpBtn(this, SW_RES(BT_HELP)),
aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE)),
pTAutoFmt( 0 ),
pShell( &rView.GetWrtShell() )
{
FreeResource();
if(nSaveButtonState > -1)
{
switch (nSaveButtonState)
{
case 0:
aTabBtn.Check();
aKeepColumn.Check(bIsKeepColumn);
break;
case 1: aSemiBtn.Check();break;
case 2: aParaBtn.Check();break;
case 3:
aOtherBtn.Check();
if(uOther)
aOtherEd.SetText(uOther);
break;
}
}
if( bToTable )
{
SetText( sConvertTextTable );
aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
aAutoFmtBtn.Show();
aKeepColumn.Show();
aKeepColumn.Enable( aTabBtn.IsChecked() );
aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
}
else
{
//Einfuege-Optionen verstecken
aHeaderCB .Show(FALSE);
aRepeatHeaderCB .Show(FALSE);
aDontSplitCB .Show(FALSE);
aBorderCB .Show(FALSE);
aOptionsFL .Show(FALSE);
aRepeatHeaderCombo.Show(FALSE);
//Groesse anpassen
Size aSize(GetSizePixel());
aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
SetOutputSizePixel(aSize);
}
aKeepColumn.SaveValue();
Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
aTabBtn.SetClickHdl( aLk );
aSemiBtn.SetClickHdl( aLk );
aParaBtn.SetClickHdl( aLk );
aOtherBtn.SetClickHdl(aLk );
aOtherEd.Enable( aOtherBtn.IsChecked() );
const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();
BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);
SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
USHORT nInsTblFlags = aInsOpts.mnInsMode;
aHeaderCB.Check( 0 != (nInsTblFlags & tabopts::HEADLINE) );
aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
aDontSplitCB.Check( 0 == (nInsTblFlags & tabopts::SPLIT_LAYOUT));
aBorderCB.Check( 0!= (nInsTblFlags & tabopts::DEFAULT_BORDER) );
aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
ReapeatHeaderCheckBoxHdl();
CheckBoxHdl();
}
SwConvertTableDlg:: ~SwConvertTableDlg()
{
delete pTAutoFmt;
}
IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
SwAbstractDialogFactory* pFact = swui::GetFactory();
DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");
AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
DBG_ASSERT(pDlg, "Dialogdiet fail!");
if( RET_OK == pDlg->Execute())
pDlg->FillAutoFmtOfIndex( pTAutoFmt );
delete pDlg;
return 0;
}
IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
if( pButton == &aTabBtn )
aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
else
{
if( aKeepColumn.IsEnabled() )
aKeepColumn.SaveValue();
aKeepColumn.Check( TRUE );
}
aKeepColumn.Enable( aTabBtn.IsChecked() );
aOtherEd.Enable( aOtherBtn.IsChecked() );
return 0;
}
/*********************************************************************/
/* */
/*********************************************************************/
IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
ReapeatHeaderCheckBoxHdl();
return 0;
}
IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
aRepeatHeaderBeforeFT.Enable(bEnable);
aRepeatHeaderAfterFT.Enable(bEnable);
aRepeatHeaderNF.Enable(bEnable);
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
// LTODO: Maybe some argument class pairing names with
// extensions and other attributes would be a better choice here?
static string const g_argAbiStr = "abi";
static string const g_argAsmStr = "asm";
static string const g_argAstStr = "ast";
static string const g_argBinaryStr = "binary";
static string const g_argOpcodesStr = "opcodes";
static string const g_argNatspecDevStr = "natspec-dev";
static string const g_argNatspecUserStr = "natspec-user";
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, string const& _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, g_argAbiStr) || argToStdout(_args, g_argNatspecUserStr) ||
argToStdout(_args, g_argNatspecDevStr) || argToStdout(_args, g_argAsmStr) ||
argToStdout(_args, g_argOpcodesStr) || argToStdout(_args, g_argBinaryStr);
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBinary(string const& _contract)
{
auto choice = m_args[g_argBinaryStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Binary: " << endl;
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".binary");
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleOpcode(string const& _contract)
{
auto choice = m_args[g_argOpcodesStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Opcodes: " << endl;
cout << eth::disassemble(m_compiler.getBytecode(_contract));
cout << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".opcode");
outFile << eth::disassemble(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleBytecode(string const& _contract)
{
if (m_args.count(g_argOpcodesStr))
handleOpcode(_contract);
if (m_args.count(g_argBinaryStr))
handleBinary(_contract);
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = g_argAbiStr;
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "g_argNatspecUserStr";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = g_argNatspecDevStr;
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
(g_argAstStr.c_str(), po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
(g_argAsmStr.c_str(), po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
(g_argOpcodesStr.c_str(), po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
(g_argBinaryStr.c_str(), po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
(g_argAbiStr.c_str(), po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
(g_argNatspecUserStr.c_str(), po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
(g_argNatspecDevStr.c_str(), po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
{
auto path = boost::filesystem::path(infile);
if (!boost::filesystem::exists(path))
{
cout << "Skipping non existant input file \"" << infile << "\"" << endl;
continue;
}
if (!boost::filesystem::is_regular_file(path))
{
cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
continue;
}
m_sourceCodes[infile] = asString(dev::contents(infile));
}
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count(g_argAstStr))
{
auto choice = m_args[g_argAstStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count(g_argAsmStr))
{
auto choice = m_args[g_argAsmStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode(contract);
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<commit_msg>Assertions that throw InternalCompilerErrors.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
// LTODO: Maybe some argument class pairing names with
// extensions and other attributes would be a better choice here?
static string const g_argAbiStr = "abi";
static string const g_argAsmStr = "asm";
static string const g_argAstStr = "ast";
static string const g_argBinaryStr = "binary";
static string const g_argOpcodesStr = "opcodes";
static string const g_argNatspecDevStr = "natspec-dev";
static string const g_argNatspecUserStr = "natspec-user";
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, string const& _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, g_argAbiStr) || argToStdout(_args, g_argNatspecUserStr) ||
argToStdout(_args, g_argNatspecDevStr) || argToStdout(_args, g_argAsmStr) ||
argToStdout(_args, g_argOpcodesStr) || argToStdout(_args, g_argBinaryStr);
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBinary(string const& _contract)
{
auto choice = m_args[g_argBinaryStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Binary: " << endl;
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".binary");
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleOpcode(string const& _contract)
{
auto choice = m_args[g_argOpcodesStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Opcodes: " << endl;
cout << eth::disassemble(m_compiler.getBytecode(_contract));
cout << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + ".opcode");
outFile << eth::disassemble(m_compiler.getBytecode(_contract));
outFile.close();
}
}
void CommandLineInterface::handleBytecode(string const& _contract)
{
if (m_args.count(g_argOpcodesStr))
handleOpcode(_contract);
if (m_args.count(g_argBinaryStr))
handleBinary(_contract);
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = g_argAbiStr;
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "g_argNatspecUserStr";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = g_argNatspecDevStr;
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
(g_argAstStr.c_str(), po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
(g_argAsmStr.c_str(), po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
(g_argOpcodesStr.c_str(), po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
(g_argBinaryStr.c_str(), po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
(g_argAbiStr.c_str(), po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
(g_argNatspecUserStr.c_str(), po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
(g_argNatspecDevStr.c_str(), po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
{
auto path = boost::filesystem::path(infile);
if (!boost::filesystem::exists(path))
{
cout << "Skipping non existant input file \"" << infile << "\"" << endl;
continue;
}
if (!boost::filesystem::is_regular_file(path))
{
cout << "\"" << infile << "\" is not a valid file. Skipping" << endl;
continue;
}
m_sourceCodes[infile] = asString(dev::contents(infile));
}
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
cerr << "Internal compiler error during compilation:" << endl
<< boost::diagnostic_information(exception);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count(g_argAstStr))
{
auto choice = m_args[g_argAstStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count(g_argAsmStr))
{
auto choice = m_args[g_argAsmStr].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode(contract);
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2008-2015 The Communi Project
You may use this file under the terms of BSD license as follows:
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 HOLDERS 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 "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>
IRC_USE_NAMESPACE
ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
d.model = 0;
d.timestamp = QDateTime::fromTime_t(0);
setModel(qobject_cast<IrcBufferModel*>(parent));
}
ZncManager::~ZncManager()
{
}
IrcBufferModel* ZncManager::model() const
{
return d.model;
}
void ZncManager::setModel(IrcBufferModel* model)
{
if (d.model != model) {
if (d.model && d.model->connection()) {
IrcConnection* connection = d.model->connection();
disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
connection->removeMessageFilter(this);
disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
}
d.model = model;
if (d.model && d.model->connection()) {
IrcNetwork* network = d.model->network();
QStringList caps = network->requestedCapabilities();
caps += "batch";
caps += "server-time";
caps += "echo-message";
caps += "znc.in/batch";
caps += "znc.in/playback";
caps += "znc.in/server-time";
caps += "znc.in/echo-message";
caps += "znc.in/server-time-iso";
network->setRequestedCapabilities(caps);
IrcConnection* connection = d.model->connection();
connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
connection->installMessageFilter(this);
connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
}
emit modelChanged(model);
}
}
bool ZncManager::messageFilter(IrcMessage* message)
{
if (message->connection()->isConnected())
d.timestamp = qMax(d.timestamp, message->timeStamp());
if (message->type() == IrcMessage::Batch) {
IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);
if (batch->batch() == "znc.in/playback") {
IrcBuffer* buffer = d.model->add(batch->parameters().value(2));
foreach (IrcMessage* msg, batch->messages()) {
msg->setFlags(msg->flags() | IrcMessage::Playback);
if (msg->type() == IrcMessage::Private)
processMessage(static_cast<IrcPrivateMessage*>(msg));
}
buffer->receiveMessage(batch);
return true;
}
}
return IgnoreManager::instance()->messageFilter(message);
}
void ZncManager::processMessage(IrcPrivateMessage* message)
{
if (message->nick() == "*buffextras") {
const QString msg = message->content();
const int idx = msg.indexOf(" ");
const QString prefix = msg.left(idx);
const QString content = msg.mid(idx + 1);
message->setPrefix(prefix);
if (content.startsWith("joined")) {
message->setTag("intent", "JOIN");
message->setParameters(QStringList() << message->target());
} else if (content.startsWith("parted")) {
message->setTag("intent", "PART");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
message->setParameters(QStringList() << message->target() << reason);
} else if (content.startsWith("quit")) {
message->setTag("intent", "QUIT");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
message->setParameters(QStringList() << reason);
} else if (content.startsWith("is")) {
message->setTag("intent", "NICK");
const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
message->setParameters(QStringList() << tokens.last());
} else if (content.startsWith("set")) {
message->setTag("intent", "MODE");
QStringList tokens = content.split(" ", QString::SkipEmptyParts);
const QString user = tokens.takeLast();
const QString mode = tokens.takeLast();
message->setParameters(QStringList() << message->target() << mode << user);
} else if (content.startsWith("changed")) {
message->setTag("intent", "TOPIC");
const QString topic = content.mid(content.indexOf(":") + 2);
message->setParameters(QStringList() << message->target() << topic);
} else if (content.startsWith("kicked")) {
message->setTag("intent", "KICK");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
QStringList tokens = content.split(" ", QString::SkipEmptyParts);
message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);
}
}
}
void ZncManager::requestPlayback()
{
if (d.model->network()->isCapable("znc.in/playback")) {
IrcConnection* connection = d.model->connection();
IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));
cmd->setParent(this);
connection->sendCommand(cmd);
}
}
void ZncManager::clearBuffer(IrcBuffer* buffer)
{
if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<commit_msg>ZncManager: don't filter out batch messages<commit_after>/*
Copyright (C) 2008-2015 The Communi Project
You may use this file under the terms of BSD license as follows:
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 HOLDERS 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 "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>
IRC_USE_NAMESPACE
ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
d.model = 0;
d.timestamp = QDateTime::fromTime_t(0);
setModel(qobject_cast<IrcBufferModel*>(parent));
}
ZncManager::~ZncManager()
{
}
IrcBufferModel* ZncManager::model() const
{
return d.model;
}
void ZncManager::setModel(IrcBufferModel* model)
{
if (d.model != model) {
if (d.model && d.model->connection()) {
IrcConnection* connection = d.model->connection();
disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
connection->removeMessageFilter(this);
disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
}
d.model = model;
if (d.model && d.model->connection()) {
IrcNetwork* network = d.model->network();
QStringList caps = network->requestedCapabilities();
caps += "batch";
caps += "server-time";
caps += "echo-message";
caps += "znc.in/batch";
caps += "znc.in/playback";
caps += "znc.in/server-time";
caps += "znc.in/echo-message";
caps += "znc.in/server-time-iso";
network->setRequestedCapabilities(caps);
IrcConnection* connection = d.model->connection();
connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
connection->installMessageFilter(this);
connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
}
emit modelChanged(model);
}
}
bool ZncManager::messageFilter(IrcMessage* message)
{
if (message->connection()->isConnected())
d.timestamp = qMax(d.timestamp, message->timeStamp());
if (message->type() == IrcMessage::Batch) {
IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);
if (batch->batch() == "znc.in/playback") {
IrcBuffer* buffer = d.model->add(batch->parameters().value(2));
foreach (IrcMessage* msg, batch->messages()) {
msg->setFlags(msg->flags() | IrcMessage::Playback);
if (msg->type() == IrcMessage::Private)
processMessage(static_cast<IrcPrivateMessage*>(msg));
}
buffer->receiveMessage(batch);
}
}
return IgnoreManager::instance()->messageFilter(message);
}
void ZncManager::processMessage(IrcPrivateMessage* message)
{
if (message->nick() == "*buffextras") {
const QString msg = message->content();
const int idx = msg.indexOf(" ");
const QString prefix = msg.left(idx);
const QString content = msg.mid(idx + 1);
message->setPrefix(prefix);
if (content.startsWith("joined")) {
message->setTag("intent", "JOIN");
message->setParameters(QStringList() << message->target());
} else if (content.startsWith("parted")) {
message->setTag("intent", "PART");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
message->setParameters(QStringList() << message->target() << reason);
} else if (content.startsWith("quit")) {
message->setTag("intent", "QUIT");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
message->setParameters(QStringList() << reason);
} else if (content.startsWith("is")) {
message->setTag("intent", "NICK");
const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
message->setParameters(QStringList() << tokens.last());
} else if (content.startsWith("set")) {
message->setTag("intent", "MODE");
QStringList tokens = content.split(" ", QString::SkipEmptyParts);
const QString user = tokens.takeLast();
const QString mode = tokens.takeLast();
message->setParameters(QStringList() << message->target() << mode << user);
} else if (content.startsWith("changed")) {
message->setTag("intent", "TOPIC");
const QString topic = content.mid(content.indexOf(":") + 2);
message->setParameters(QStringList() << message->target() << topic);
} else if (content.startsWith("kicked")) {
message->setTag("intent", "KICK");
QString reason = content.mid(content.indexOf("[") + 1);
reason.chop(1);
QStringList tokens = content.split(" ", QString::SkipEmptyParts);
message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);
}
}
}
void ZncManager::requestPlayback()
{
if (d.model->network()->isCapable("znc.in/playback")) {
IrcConnection* connection = d.model->connection();
IrcCommand* cmd = IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));
cmd->setParent(this);
connection->sendCommand(cmd);
}
}
void ZncManager::clearBuffer(IrcBuffer* buffer)
{
if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2016 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreUnifiedHighLevelGpuProgram.h"
#include "OgreException.h"
#include "OgreGpuProgramManager.h"
namespace Ogre
{
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::CmdDelegate UnifiedHighLevelGpuProgram::msCmdDelegate;
static const String sLanguage = "unified";
std::map<String,int> UnifiedHighLevelGpuProgram::mLanguagePriorities;
int UnifiedHighLevelGpuProgram::getPriority(String shaderLanguage)
{
std::map<String,int>::iterator it = mLanguagePriorities.find(shaderLanguage);
if (it == mLanguagePriorities.end())
return -1;
else
return (*it).second;
}
void UnifiedHighLevelGpuProgram::setPrioriry(String shaderLanguage,int priority)
{
mLanguagePriorities[shaderLanguage] = priority;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::UnifiedHighLevelGpuProgram(
ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
:HighLevelGpuProgram(creator, name, handle, group, isManual, loader)
{
if (createParamDictionary("UnifiedHighLevelGpuProgram"))
{
setupBaseParamDictionary();
ParamDictionary* dict = getParamDictionary();
dict->addParameter(ParameterDef("delegate",
"Additional delegate programs containing implementations.",
PT_STRING),&msCmdDelegate);
}
}
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::~UnifiedHighLevelGpuProgram()
{
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::chooseDelegate() const
{
OGRE_LOCK_AUTO_MUTEX;
mChosenDelegate.setNull();
HighLevelGpuProgramPtr tmpDelegate;
tmpDelegate.setNull();
int tmpPriority = -10;
for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
{
HighLevelGpuProgramPtr deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i, mGroup);
//recheck with auto resource group
if (deleg.isNull())
deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i);
// Silently ignore missing links
if(!deleg.isNull() && deleg->isSupported())
{
int priority = getPriority(deleg->getLanguage());
//Find the delegate with the highest prioriry
if (priority > tmpPriority)
{
tmpDelegate = deleg;
tmpPriority = priority;
}
}
}
mChosenDelegate = tmpDelegate;
}
//-----------------------------------------------------------------------
const HighLevelGpuProgramPtr& UnifiedHighLevelGpuProgram::_getDelegate() const
{
if (mChosenDelegate.isNull())
{
chooseDelegate();
}
return mChosenDelegate;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::addDelegateProgram(const String& name)
{
OGRE_LOCK_AUTO_MUTEX;
mDelegateNames.push_back(name);
// reset chosen delegate
mChosenDelegate.setNull();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::clearDelegatePrograms()
{
OGRE_LOCK_AUTO_MUTEX;
mDelegateNames.clear();
mChosenDelegate.setNull();
}
//-----------------------------------------------------------------------------
size_t UnifiedHighLevelGpuProgram::calculateSize(void) const
{
size_t memSize = 0;
memSize += HighLevelGpuProgram::calculateSize();
// Delegate Names
for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
memSize += (*i).size() * sizeof(char);
return memSize;
}
//-----------------------------------------------------------------------
const String& UnifiedHighLevelGpuProgram::getLanguage(void) const
{
return sLanguage;
}
//-----------------------------------------------------------------------
GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::createParameters(void)
{
if (isSupported())
{
return _getDelegate()->createParameters();
}
else
{
// return a default set
GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters();
// avoid any errors on parameter names that don't exist
params->setIgnoreMissingParams(true);
return params;
}
}
//-----------------------------------------------------------------------
GpuProgram* UnifiedHighLevelGpuProgram::_getBindingDelegate(void)
{
if (!_getDelegate().isNull())
return _getDelegate()->_getBindingDelegate();
else
return 0;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isSupported(void) const
{
// Supported if one of the delegates is
return !(_getDelegate().isNull());
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isSkeletalAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isSkeletalAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isMorphAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isMorphAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isPoseAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isPoseAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
ushort UnifiedHighLevelGpuProgram::getNumberOfPosesIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getNumberOfPosesIncluded();
else
return 0;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isVertexTextureFetchRequired(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isVertexTextureFetchRequired();
else
return false;
}
//-----------------------------------------------------------------------
GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::getDefaultParameters(void)
{
if (!_getDelegate().isNull())
return _getDelegate()->getDefaultParameters();
else
return GpuProgramParametersSharedPtr();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::hasDefaultParameters(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->hasDefaultParameters();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassSurfaceAndLightStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassSurfaceAndLightStates();
else
return HighLevelGpuProgram::getPassSurfaceAndLightStates();
}
//---------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassFogStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassFogStates();
else
return HighLevelGpuProgram::getPassFogStates();
}
//---------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassTransformStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassTransformStates();
else
return HighLevelGpuProgram::getPassTransformStates();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::hasCompileError(void) const
{
if (_getDelegate().isNull())
{
return false;
}
else
{
return _getDelegate()->hasCompileError();
}
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::resetCompileError(void)
{
if (!_getDelegate().isNull())
_getDelegate()->resetCompileError();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::load(bool backgroundThread)
{
if (!_getDelegate().isNull())
_getDelegate()->load(backgroundThread);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::reload(LoadingFlags flags)
{
if (!_getDelegate().isNull())
_getDelegate()->reload(flags);
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isReloadable(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isReloadable();
else
return true;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::unload(void)
{
if (!_getDelegate().isNull())
_getDelegate()->unload();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isLoaded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isLoaded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isLoading() const
{
if (!_getDelegate().isNull())
return _getDelegate()->isLoading();
else
return false;
}
//-----------------------------------------------------------------------
Resource::LoadingState UnifiedHighLevelGpuProgram::getLoadingState() const
{
if (!_getDelegate().isNull())
return _getDelegate()->getLoadingState();
else
return Resource::LOADSTATE_UNLOADED;
}
//-----------------------------------------------------------------------
size_t UnifiedHighLevelGpuProgram::getSize(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getSize();
else
return 0;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::touch(void)
{
if (!_getDelegate().isNull())
_getDelegate()->touch();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isBackgroundLoaded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isBackgroundLoaded();
else
return false;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::setBackgroundLoaded(bool bl)
{
if (!_getDelegate().isNull())
_getDelegate()->setBackgroundLoaded(bl);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::escalateLoading()
{
if (!_getDelegate().isNull())
_getDelegate()->escalateLoading();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::addListener(Resource::Listener* lis)
{
if (!_getDelegate().isNull())
_getDelegate()->addListener(lis);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::removeListener(Resource::Listener* lis)
{
if (!_getDelegate().isNull())
_getDelegate()->removeListener(lis);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::createLowLevelImpl(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::createLowLevelImpl");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::unloadHighLevelImpl(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::unloadHighLevelImpl");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::buildConstantDefinitions() const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::buildConstantDefinitions");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::loadFromSource(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::loadFromSource");
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
String UnifiedHighLevelGpuProgram::CmdDelegate::doGet(const void* target) const
{
// Can't do this (not one delegate), shouldn't matter
return BLANKSTRING;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::CmdDelegate::doSet(void* target, const String& val)
{
static_cast<UnifiedHighLevelGpuProgram*>(target)->addDelegateProgram(val);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgramFactory::UnifiedHighLevelGpuProgramFactory()
{
}
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgramFactory::~UnifiedHighLevelGpuProgramFactory()
{
}
//-----------------------------------------------------------------------
const String& UnifiedHighLevelGpuProgramFactory::getLanguage(void) const
{
return sLanguage;
}
//-----------------------------------------------------------------------
HighLevelGpuProgram* UnifiedHighLevelGpuProgramFactory::create(ResourceManager* creator,
const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
{
return OGRE_NEW UnifiedHighLevelGpuProgram(creator, name, handle, group, isManual, loader);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgramFactory::destroy(HighLevelGpuProgram* prog)
{
OGRE_DELETE prog;
}
//-----------------------------------------------------------------------
}
<commit_msg>Revert "Unified material did select the last program with the same priority which is wrong in the case of GL3+."<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2016 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreUnifiedHighLevelGpuProgram.h"
#include "OgreException.h"
#include "OgreGpuProgramManager.h"
namespace Ogre
{
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::CmdDelegate UnifiedHighLevelGpuProgram::msCmdDelegate;
static const String sLanguage = "unified";
std::map<String,int> UnifiedHighLevelGpuProgram::mLanguagePriorities;
int UnifiedHighLevelGpuProgram::getPriority(String shaderLanguage)
{
std::map<String,int>::iterator it = mLanguagePriorities.find(shaderLanguage);
if (it == mLanguagePriorities.end())
return -1;
else
return (*it).second;
}
void UnifiedHighLevelGpuProgram::setPrioriry(String shaderLanguage,int priority)
{
mLanguagePriorities[shaderLanguage] = priority;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::UnifiedHighLevelGpuProgram(
ResourceManager* creator, const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
:HighLevelGpuProgram(creator, name, handle, group, isManual, loader)
{
if (createParamDictionary("UnifiedHighLevelGpuProgram"))
{
setupBaseParamDictionary();
ParamDictionary* dict = getParamDictionary();
dict->addParameter(ParameterDef("delegate",
"Additional delegate programs containing implementations.",
PT_STRING),&msCmdDelegate);
}
}
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgram::~UnifiedHighLevelGpuProgram()
{
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::chooseDelegate() const
{
OGRE_LOCK_AUTO_MUTEX;
mChosenDelegate.setNull();
HighLevelGpuProgramPtr tmpDelegate;
tmpDelegate.setNull();
int tmpPriority = -1;
for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
{
HighLevelGpuProgramPtr deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i, mGroup);
//recheck with auto resource group
if (deleg.isNull())
deleg = HighLevelGpuProgramManager::getSingleton().getByName(*i);
// Silently ignore missing links
if(!deleg.isNull() && deleg->isSupported())
{
int priority = getPriority(deleg->getLanguage());
//Find the delegate with the highest prioriry
if (priority >= tmpPriority)
{
tmpDelegate = deleg;
tmpPriority = priority;
}
}
}
mChosenDelegate = tmpDelegate;
}
//-----------------------------------------------------------------------
const HighLevelGpuProgramPtr& UnifiedHighLevelGpuProgram::_getDelegate() const
{
if (mChosenDelegate.isNull())
{
chooseDelegate();
}
return mChosenDelegate;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::addDelegateProgram(const String& name)
{
OGRE_LOCK_AUTO_MUTEX;
mDelegateNames.push_back(name);
// reset chosen delegate
mChosenDelegate.setNull();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::clearDelegatePrograms()
{
OGRE_LOCK_AUTO_MUTEX;
mDelegateNames.clear();
mChosenDelegate.setNull();
}
//-----------------------------------------------------------------------------
size_t UnifiedHighLevelGpuProgram::calculateSize(void) const
{
size_t memSize = 0;
memSize += HighLevelGpuProgram::calculateSize();
// Delegate Names
for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i)
memSize += (*i).size() * sizeof(char);
return memSize;
}
//-----------------------------------------------------------------------
const String& UnifiedHighLevelGpuProgram::getLanguage(void) const
{
return sLanguage;
}
//-----------------------------------------------------------------------
GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::createParameters(void)
{
if (isSupported())
{
return _getDelegate()->createParameters();
}
else
{
// return a default set
GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters();
// avoid any errors on parameter names that don't exist
params->setIgnoreMissingParams(true);
return params;
}
}
//-----------------------------------------------------------------------
GpuProgram* UnifiedHighLevelGpuProgram::_getBindingDelegate(void)
{
if (!_getDelegate().isNull())
return _getDelegate()->_getBindingDelegate();
else
return 0;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isSupported(void) const
{
// Supported if one of the delegates is
return !(_getDelegate().isNull());
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isSkeletalAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isSkeletalAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isMorphAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isMorphAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isPoseAnimationIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isPoseAnimationIncluded();
else
return false;
}
//-----------------------------------------------------------------------
ushort UnifiedHighLevelGpuProgram::getNumberOfPosesIncluded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getNumberOfPosesIncluded();
else
return 0;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isVertexTextureFetchRequired(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isVertexTextureFetchRequired();
else
return false;
}
//-----------------------------------------------------------------------
GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::getDefaultParameters(void)
{
if (!_getDelegate().isNull())
return _getDelegate()->getDefaultParameters();
else
return GpuProgramParametersSharedPtr();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::hasDefaultParameters(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->hasDefaultParameters();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassSurfaceAndLightStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassSurfaceAndLightStates();
else
return HighLevelGpuProgram::getPassSurfaceAndLightStates();
}
//---------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassFogStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassFogStates();
else
return HighLevelGpuProgram::getPassFogStates();
}
//---------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::getPassTransformStates(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getPassTransformStates();
else
return HighLevelGpuProgram::getPassTransformStates();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::hasCompileError(void) const
{
if (_getDelegate().isNull())
{
return false;
}
else
{
return _getDelegate()->hasCompileError();
}
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::resetCompileError(void)
{
if (!_getDelegate().isNull())
_getDelegate()->resetCompileError();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::load(bool backgroundThread)
{
if (!_getDelegate().isNull())
_getDelegate()->load(backgroundThread);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::reload(LoadingFlags flags)
{
if (!_getDelegate().isNull())
_getDelegate()->reload(flags);
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isReloadable(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isReloadable();
else
return true;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::unload(void)
{
if (!_getDelegate().isNull())
_getDelegate()->unload();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isLoaded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isLoaded();
else
return false;
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isLoading() const
{
if (!_getDelegate().isNull())
return _getDelegate()->isLoading();
else
return false;
}
//-----------------------------------------------------------------------
Resource::LoadingState UnifiedHighLevelGpuProgram::getLoadingState() const
{
if (!_getDelegate().isNull())
return _getDelegate()->getLoadingState();
else
return Resource::LOADSTATE_UNLOADED;
}
//-----------------------------------------------------------------------
size_t UnifiedHighLevelGpuProgram::getSize(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->getSize();
else
return 0;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::touch(void)
{
if (!_getDelegate().isNull())
_getDelegate()->touch();
}
//-----------------------------------------------------------------------
bool UnifiedHighLevelGpuProgram::isBackgroundLoaded(void) const
{
if (!_getDelegate().isNull())
return _getDelegate()->isBackgroundLoaded();
else
return false;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::setBackgroundLoaded(bool bl)
{
if (!_getDelegate().isNull())
_getDelegate()->setBackgroundLoaded(bl);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::escalateLoading()
{
if (!_getDelegate().isNull())
_getDelegate()->escalateLoading();
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::addListener(Resource::Listener* lis)
{
if (!_getDelegate().isNull())
_getDelegate()->addListener(lis);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::removeListener(Resource::Listener* lis)
{
if (!_getDelegate().isNull())
_getDelegate()->removeListener(lis);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::createLowLevelImpl(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::createLowLevelImpl");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::unloadHighLevelImpl(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::unloadHighLevelImpl");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::buildConstantDefinitions() const
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::buildConstantDefinitions");
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::loadFromSource(void)
{
OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
"This method should never get called!",
"UnifiedHighLevelGpuProgram::loadFromSource");
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
String UnifiedHighLevelGpuProgram::CmdDelegate::doGet(const void* target) const
{
// Can't do this (not one delegate), shouldn't matter
return BLANKSTRING;
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgram::CmdDelegate::doSet(void* target, const String& val)
{
static_cast<UnifiedHighLevelGpuProgram*>(target)->addDelegateProgram(val);
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgramFactory::UnifiedHighLevelGpuProgramFactory()
{
}
//-----------------------------------------------------------------------
UnifiedHighLevelGpuProgramFactory::~UnifiedHighLevelGpuProgramFactory()
{
}
//-----------------------------------------------------------------------
const String& UnifiedHighLevelGpuProgramFactory::getLanguage(void) const
{
return sLanguage;
}
//-----------------------------------------------------------------------
HighLevelGpuProgram* UnifiedHighLevelGpuProgramFactory::create(ResourceManager* creator,
const String& name, ResourceHandle handle,
const String& group, bool isManual, ManualResourceLoader* loader)
{
return OGRE_NEW UnifiedHighLevelGpuProgram(creator, name, handle, group, isManual, loader);
}
//-----------------------------------------------------------------------
void UnifiedHighLevelGpuProgramFactory::destroy(HighLevelGpuProgram* prog)
{
OGRE_DELETE prog;
}
//-----------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TGeoMaterial.h"
#include "TGeoManager.h"
#include "TFlukaCerenkov.h"
#include "TFluka.h"
#include "Fdimpar.h" //(DIMPAR) fluka include
#include "Ftrackr.h" //(TRACKR) fluka common
#ifndef WIN32
# define endraw endraw_
#else
# define endraw ENDRAW
#endif
extern "C" {
void endraw(Int_t& icode, Int_t& mreg, Double_t& rull, Double_t& xsco, Double_t& ysco, Double_t& zsco)
{
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel >= 3)? kTRUE : kFALSE;
fluka->SetCaller(3);
fluka->SetRull(rull);
fluka->SetXsco(xsco);
fluka->SetYsco(ysco);
fluka->SetZsco(zsco);
fluka->SetMreg(mreg);
if (icode == 11) {
if (debug) cout << " For icode=" << icode << " Stepping is NOT called" << endl;
return;
}
if (TRACKR.jtrack == -1) {
// Handle quantum efficiency the G3 way
if (debug) printf("endraw: Cerenkov photon depositing energy: %d %e\n", mreg, rull);
TGeoMaterial* material = (gGeoManager->GetCurrentVolume())->GetMaterial();
// Int_t nmat = material->GetIndex();
TFlukaCerenkov* cerenkov = dynamic_cast<TFlukaCerenkov*> (material->GetCerenkovProperties());
if (cerenkov) {
Double_t eff = (cerenkov->GetQuantumEfficiency(rull));
if (gRandom->Rndm() > eff) {
rull = 0.;
fluka->SetRull(rull);
}
}
}
if (debug) printf("endraw: Depositing energy for : %d %e icode: %d \n", TRACKR.ispusr[mkbmx2-1], rull, icode);
(TVirtualMCApplication::Instance())->Stepping();
//
// for icode 21,22 the particle has fallen below thresshold
// This has to be signalled to the StepManager()
//
fluka->SetTrackIsNew(kFALSE);
fluka->SetIcode(icode);
(TVirtualMCApplication::Instance())->Stepping();
} // end of endraw
} // end of extern "C"
<commit_msg>In case of double step, set deposited energy to 0 in first step.<commit_after>#include <Riostream.h>
#include "TVirtualMCApplication.h"
#include "TGeoMaterial.h"
#include "TGeoManager.h"
#include "TFlukaCerenkov.h"
#include "TFluka.h"
#include "Fdimpar.h" //(DIMPAR) fluka include
#include "Ftrackr.h" //(TRACKR) fluka common
#ifndef WIN32
# define endraw endraw_
#else
# define endraw ENDRAW
#endif
extern "C" {
void endraw(Int_t& icode, Int_t& mreg, Double_t& rull, Double_t& xsco, Double_t& ysco, Double_t& zsco)
{
TFluka* fluka = (TFluka*) gMC;
Int_t verbosityLevel = fluka->GetVerbosityLevel();
Bool_t debug = (verbosityLevel >= 3)? kTRUE : kFALSE;
fluka->SetCaller(3);
fluka->SetRull(rull);
fluka->SetXsco(xsco);
fluka->SetYsco(ysco);
fluka->SetZsco(zsco);
fluka->SetMreg(mreg);
Float_t edep = rull;
if (icode == 11) {
if (debug) cout << " For icode=" << icode << " Stepping is NOT called" << endl;
return;
}
if (TRACKR.jtrack == -1) {
// Handle quantum efficiency the G3 way
if (debug) printf("endraw: Cerenkov photon depositing energy: %d %e\n", mreg, rull);
TGeoMaterial* material = (gGeoManager->GetCurrentVolume())->GetMaterial();
// Int_t nmat = material->GetIndex();
TFlukaCerenkov* cerenkov = dynamic_cast<TFlukaCerenkov*> (material->GetCerenkovProperties());
if (cerenkov) {
Double_t eff = (cerenkov->GetQuantumEfficiency(rull));
if (gRandom->Rndm() > eff) {
edep = 0.;
}
}
}
if (debug) printf("endraw: Depositing energy for : %d %e icode: %d \n", TRACKR.ispusr[mkbmx2-1], rull, icode);
if (icode != 21 && icode != 22) {
fluka->SetRull(edep);
(TVirtualMCApplication::Instance())->Stepping();
} else {
//
// for icode 21,22 the particle has fallen below thresshold
// This has to be signalled to the StepManager()
//
fluka->SetRull(0.);
(TVirtualMCApplication::Instance())->Stepping();
fluka->SetTrackIsNew(kFALSE);
fluka->SetIcode(icode);
fluka->SetRull(edep);
(TVirtualMCApplication::Instance())->Stepping();
}
} // end of endraw
} // end of extern "C"
<|endoftext|> |
<commit_before>#include "QCachingLocale.h"
#include "Parser.h"
#include "Analyst.h"
#include <QObject>
#include <QTime>
int main(int argc, char *argv[]) {
QCachingLocale cl;
// Merely instantiating QCachingLocale activates it. Use Q_UNUSED to prevent
// compiler warnings.
Q_UNUSED(cl);
// FIXME: argc and argv are not yet being used.
Q_UNUSED(argc)
Q_UNUSED(argv);
QTextStream cout(stdout);
QTextStream cerr(stderr);
QTime timer;
EpisodesParser::Parser * parser;
Analytics::Analyst * analyst;
EpisodesParser::Parser::initParserHelpers("./config/browscap.csv",
"./config/browscap-index.db",
"./config/GeoIPCity.dat",
"./config/GeoIPASNum.dat",
"./config/EpisodesSpeeds.csv"
);
// Instantiate the EpisodesParser and the Analytics. Then connect them.
parser = new EpisodesParser::Parser();
// TODO: when these parameters have been figured out, they should be the defaults
// and therefor they should be moved to the Analyst constructor.
analyst = new Analytics::Analyst(0.05, 0.04, 0.2);
// Set constraints. This defines which associations will be found. By
// default, only causes for slow episodes will be searched.
analyst->addFrequentItemsetItemConstraint("episode:*", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
analyst->addRuleConsequentItemConstraint("duration:slow", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
//analyst->addRuleConsequentItemConstraint("duration:acceptable", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
//analyst->addRuleConsequentItemConstraint("duration:fast", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
QObject::connect(parser, SIGNAL(processedChunk(QList<QStringList>, double)), analyst, SLOT(analyzeTransactions(QList<QStringList>, double)));
timer.start();
// Execute the EpisodesParser. This will generate transactions. These will
// automatically be sent to Analytics' Analyst.
int linesParsed = parser->parse("/Users/wimleers/School/masterthesis/logs/driverpacks.net.episodes.log");
int timePassed = timer.elapsed();
cout << QString("Duration: %1 ms. Parsed %2 lines. That's %3 lines/ms or %4 ms/line.")
.arg(timePassed)
.arg(linesParsed)
.arg((float)linesParsed/timePassed)
.arg((float)timePassed/linesParsed)
<< endl;
delete parser;
EpisodesParser::Parser::clearParserHelperCaches();
// FIXME: remove this eventually. This is merely here to check on memory
// consumption after everything has been deleted from memory.
QTextStream in(stdin);
forever {
QString line = in.readLine();
if (!line.isNull())
break;
}
}
<commit_msg>Finally, the commit in which all the hard work over the last 4 weeks reaches its ultimate status: it is now all working! In this commit, I enable rule mining over user-configurable time (bucket) ranges in the PatternTree that was generated by the FPStream algorithm implementation I built over these last 4 weeks. The essence of my thesis now *works*! :) Hurray!<commit_after>#include "QCachingLocale.h"
#include "Parser.h"
#include "Analyst.h"
#include <QObject>
#include <QTime>
int main(int argc, char *argv[]) {
QCachingLocale cl;
// Merely instantiating QCachingLocale activates it. Use Q_UNUSED to prevent
// compiler warnings.
Q_UNUSED(cl);
// FIXME: argc and argv are not yet being used.
Q_UNUSED(argc)
Q_UNUSED(argv);
QTextStream cout(stdout);
QTextStream cerr(stderr);
QTime timer;
EpisodesParser::Parser * parser;
Analytics::Analyst * analyst;
EpisodesParser::Parser::initParserHelpers("./config/browscap.csv",
"./config/browscap-index.db",
"./config/GeoIPCity.dat",
"./config/GeoIPASNum.dat",
"./config/EpisodesSpeeds.csv"
);
// Instantiate the EpisodesParser and the Analytics. Then connect them.
parser = new EpisodesParser::Parser();
// TODO: when these parameters have been figured out, they should be the defaults
// and therefor they should be moved to the Analyst constructor.
analyst = new Analytics::Analyst(0.05, 0.04, 0.2);
// Set constraints. This defines which associations will be found. By
// default, only causes for slow episodes will be searched.
analyst->addFrequentItemsetItemConstraint("episode:*", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
analyst->addRuleConsequentItemConstraint("duration:slow", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
//analyst->addRuleConsequentItemConstraint("duration:acceptable", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
//analyst->addRuleConsequentItemConstraint("duration:fast", Analytics::CONSTRAINT_POSITIVE_MATCH_ANY);
QObject::connect(parser, SIGNAL(processedChunk(QList<QStringList>, double)), analyst, SLOT(analyzeTransactions(QList<QStringList>, double)));
timer.start();
// Execute the EpisodesParser. This will generate transactions. These will
// automatically be sent to Analytics' Analyst.
int linesParsed = parser->parse("/Users/wimleers/School/masterthesis/logs/driverpacks.net.episodes.log");
int timePassed = timer.elapsed();
cout << QString("Duration: %1 ms. Parsed %2 lines. That's %3 lines/ms or %4 ms/line.")
.arg(timePassed)
.arg(linesParsed)
.arg((float)linesParsed/timePassed)
.arg((float)timePassed/linesParsed)
<< endl;
delete parser;
EpisodesParser::Parser::clearParserHelperCaches();
// Mine association rules.
analyst->mineRules(0, (uint) TTW_NUM_BUCKETS - 1); // Rules over the entire dataset.
analyst->mineRules(4, 4); // Rules over the past hour.
// FIXME: remove this eventually. This is merely here to check on memory
// consumption after everything has been deleted from memory.
QTextStream in(stdin);
forever {
QString line = in.readLine();
if (!line.isNull())
break;
}
}
<|endoftext|> |
<commit_before>// @(#)root/roofitcore:$name: $:$id$
// Authors: Wouter Verkerke November 2007
// C/C++ headers
#include <list>
#include <iostream>
#include <iomanip>
// ROOT headers
#include "TWebFile.h"
#include "TSystem.h"
#include "TString.h"
#include "TROOT.h"
#include "TFile.h"
#include "TBenchmark.h"
// RooFit headers
#include "RooNumIntConfig.h"
#include "RooResolutionModel.h"
#include "RooAbsData.h"
#include "RooTrace.h"
#include "RooMath.h"
#include "RooUnitTest.h"
// Tests file
#include "stressHistFactory_tests.cxx"
using namespace std ;
using namespace RooFit ;
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//
// //
// RooStats Unit Test S.T.R.E.S.S. Suite //
// Authors: Ioan Gabriel Bucur, Lorenzo Moneta, Wouter Verkerke //
// //
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//
//------------------------------------------------------------------------
void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth)
{
// Print test program number and its title
TString header = TString::Format("Test %d : %s ", id, title.Data());
cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl;
}
//______________________________________________________________________________
Int_t stressHistFactory(const char* refFile, Bool_t writeRef, Int_t verbose, Bool_t allTests, Bool_t oneTest, Int_t testNumber, Bool_t dryRun)
{
// width of lines when printing test results
const Int_t lineWidth = 120;
// Save memory directory location
RooUnitTest::setMemDir(gDirectory) ;
std::cout << "using reference file " << refFile << std::endl;
TFile* fref = 0 ;
if (!dryRun) {
if (TString(refFile).Contains("http:")) {
if (writeRef) {
cout << "stressHistFactory ERROR: reference file must be local file in writing mode" << endl ;
return -1 ;
}
fref = new TWebFile(refFile) ;
} else {
fref = new TFile(refFile, writeRef ? "RECREATE" : "") ;
}
if (fref->IsZombie()) {
cout << "stressHistFactory ERROR: cannot open reference file " << refFile << endl ;
return -1;
}
}
if (dryRun) {
// Preload singletons here so they don't show up in trace accounting
RooNumIntConfig::defaultConfig() ;
RooResolutionModel::identity() ;
RooTrace::active(1) ;
}
// Add dedicated logging stream for errors that will remain active in silent mode
RooMsgService::instance().addStream(RooFit::ERROR) ;
cout << left << setw(lineWidth) << setfill('*') << "" << endl;
cout << "*" << setw(lineWidth - 2) << setfill(' ') << " Histfactory S.T.R.E.S.S. suite " << "*" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
TStopwatch timer;
timer.Start();
list<RooUnitTest*> testList;
testList.push_back(new PdfComparison(fref, writeRef, verbose));
TString suiteType = TString::Format(" Starting S.T.R.E.S.S. %s",
allTests ? "full suite" : (oneTest ? TString::Format("test %d", testNumber).Data() : "basic suite")
);
cout << "*" << setw(lineWidth - 3) << setfill(' ') << suiteType << " *" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
gBenchmark->Start("stressHistFactory");
int nFailed = 0;
{
Int_t i;
list<RooUnitTest*>::iterator iter;
if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) {
cout << "Tests are numbered from 1 to " << testList.size() << endl;
return -1;
} else {
for (iter = testList.begin(), i = 1; iter != testList.end(); iter++, i++) {
if (!oneTest || testNumber == i) {
int status = (*iter)->isTestAvailable() ? (*iter)->runTest() : -1;
StatusPrint(i, (*iter)->GetName(), status , lineWidth);
if (!status) nFailed++;
}
delete *iter;
}
}
}
if (dryRun) {
RooTrace::dump();
}
gBenchmark->Stop("stressHistFactory");
//Print table with results
Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0;
cout << setw(lineWidth) << setfill('*') << "" << endl;
if (UNIX) {
TString sp = gSystem->GetFromPipe("uname -a");
cout << "* SYS: " << sp << endl;
if (strstr(gSystem->GetBuildNode(), "Linux")) {
sp = gSystem->GetFromPipe("lsb_release -d -s");
cout << "* SYS: " << sp << endl;
}
if (strstr(gSystem->GetBuildNode(), "Darwin")) {
sp = gSystem->GetFromPipe("sw_vers -productVersion");
sp += " Mac OS X ";
cout << "* SYS: " << sp << endl;
}
} else {
const Char_t *os = gSystem->Getenv("OS");
if (!os) cout << "* SYS: Windows 95" << endl;
else cout << "* SYS: " << os << " " << gSystem->Getenv("PROCESSOR_IDENTIFIER") << endl;
}
cout << setw(lineWidth) << setfill('*') << "" << endl;
gBenchmark->Print("stressHistFactory");
#ifdef __CINT__
Double_t reftime = 186.34; //pcbrun4 interpreted
#else
Double_t reftime = 93.59; //pcbrun4 compiled
#endif
const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("stressHistFactory");
cout << setw(lineWidth) << setfill('*') << "" << endl;
cout << TString::Format("* ROOTMARKS = %6.1f * Root %-8s %d/%d", rootmarks, gROOT->GetVersion(),
gROOT->GetVersionDate(), gROOT->GetVersionTime()) << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
// NOTE: The function TStopwatch::CpuTime() calls Tstopwatch::Stop(), so you do not need to stop the timer separately.
cout << "Time at the end of job = " << timer.CpuTime() << " seconds" << endl;
if (fref) {
fref->Close() ;
delete fref ;
}
delete gBenchmark ;
gBenchmark = 0 ;
return nFailed;
}
//_____________________________batch only_____________________
#ifndef __CINT__
int main(int argc, const char *argv[])
{
Bool_t doWrite = kFALSE;
Int_t verbose = 0;
Bool_t allTests = kFALSE;
Bool_t oneTest = kFALSE;
Int_t testNumber = 0;
Bool_t dryRun = kFALSE;
string refFileName = "$ROOTSYS/test/stressHistFactory_ref.root" ;
// Parse command line arguments
for (Int_t i = 1 ; i < argc ; i++) {
string arg = argv[i] ;
if (arg == "-f") {
cout << "stressHistFactory: using reference file " << argv[i + 1] << endl ;
refFileName = argv[++i] ;
} else if (arg == "-w") {
cout << "stressHistFactory: running in writing mode to update reference file" << endl ;
doWrite = kTRUE ;
} else if (arg == "-mc") {
cout << "stressHistFactory: running in memcheck mode, no regression tests are performed" << endl;
dryRun = kTRUE;
} else if (arg == "-v") {
cout << "stressHistFactory: running in verbose mode" << endl;
verbose = 1;
} else if (arg == "-vv") {
cout << "stressHistFactory: running in very verbose mode" << endl;
verbose = 2;
} else if (arg == "-a") {
cout << "stressHistFactory: deploying full suite of tests" << endl;
allTests = kTRUE;
} else if (arg == "-n") {
cout << "stressHistFactory: running single test" << endl;
oneTest = kTRUE;
testNumber = atoi(argv[++i]);
} else if (arg == "-d") {
cout << "stressHistFactory: setting gDebug to " << argv[i + 1] << endl;
gDebug = atoi(argv[++i]);
} else if (arg == "-h") {
cout << "usage: stressHistFactory [ options ] " << endl;
cout << "" << endl;
cout << " -f <file> : use given reference file instead of default (" << refFileName << ")" << endl;
cout << " -w : write reference file, instead of reading file and running comparison tests" << endl;
cout << " -n N : only run test with sequential number N" << endl;
cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl;
cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl;
cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl;
cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl;
cout << " -d N : set ROOT gDebug flag to N" << endl ;
cout << " " << endl ;
return 0 ;
}
}
// Disable caching of complex error function calculation, as we don't
// want to write out the cache file as part of the validation procedure
RooMath::cacheCERF(kFALSE) ;
gBenchmark = new TBenchmark();
return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun);
}
#endif
<commit_msg>cosider skipped tests as failed ones<commit_after>// @(#)root/roofitcore:$name: $:$id$
// Authors: Wouter Verkerke November 2007
// C/C++ headers
#include <list>
#include <iostream>
#include <iomanip>
// ROOT headers
#include "TWebFile.h"
#include "TSystem.h"
#include "TString.h"
#include "TROOT.h"
#include "TFile.h"
#include "TBenchmark.h"
// RooFit headers
#include "RooNumIntConfig.h"
#include "RooResolutionModel.h"
#include "RooAbsData.h"
#include "RooTrace.h"
#include "RooMath.h"
#include "RooUnitTest.h"
// Tests file
#include "stressHistFactory_tests.cxx"
using namespace std ;
using namespace RooFit ;
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//
// //
// RooStats Unit Test S.T.R.E.S.S. Suite //
// Authors: Ioan Gabriel Bucur, Lorenzo Moneta, Wouter Verkerke //
// //
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*//
//------------------------------------------------------------------------
void StatusPrint(const Int_t id, const TString &title, const Int_t status, const Int_t lineWidth)
{
// Print test program number and its title
TString header = TString::Format("Test %d : %s ", id, title.Data());
cout << left << setw(lineWidth) << setfill('.') << header << " " << (status > 0 ? "OK" : (status < 0 ? "SKIPPED" : "FAILED")) << endl;
}
//______________________________________________________________________________
Int_t stressHistFactory(const char* refFile, Bool_t writeRef, Int_t verbose, Bool_t allTests, Bool_t oneTest, Int_t testNumber, Bool_t dryRun)
{
// width of lines when printing test results
const Int_t lineWidth = 120;
// Save memory directory location
RooUnitTest::setMemDir(gDirectory) ;
std::cout << "using reference file " << refFile << std::endl;
TFile* fref = 0 ;
if (!dryRun) {
if (TString(refFile).Contains("http:")) {
if (writeRef) {
cout << "stressHistFactory ERROR: reference file must be local file in writing mode" << endl ;
return -1 ;
}
fref = new TWebFile(refFile) ;
} else {
fref = new TFile(refFile, writeRef ? "RECREATE" : "") ;
}
if (fref->IsZombie()) {
cout << "stressHistFactory ERROR: cannot open reference file " << refFile << endl ;
return -1;
}
}
if (dryRun) {
// Preload singletons here so they don't show up in trace accounting
RooNumIntConfig::defaultConfig() ;
RooResolutionModel::identity() ;
RooTrace::active(1) ;
}
// Add dedicated logging stream for errors that will remain active in silent mode
RooMsgService::instance().addStream(RooFit::ERROR) ;
cout << left << setw(lineWidth) << setfill('*') << "" << endl;
cout << "*" << setw(lineWidth - 2) << setfill(' ') << " Histfactory S.T.R.E.S.S. suite " << "*" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
TStopwatch timer;
timer.Start();
list<RooUnitTest*> testList;
testList.push_back(new PdfComparison(fref, writeRef, verbose));
TString suiteType = TString::Format(" Starting S.T.R.E.S.S. %s",
allTests ? "full suite" : (oneTest ? TString::Format("test %d", testNumber).Data() : "basic suite")
);
cout << "*" << setw(lineWidth - 3) << setfill(' ') << suiteType << " *" << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
gBenchmark->Start("stressHistFactory");
int nFailed = 0;
{
Int_t i;
list<RooUnitTest*>::iterator iter;
if (oneTest && (testNumber <= 0 || (UInt_t) testNumber > testList.size())) {
cout << "Tests are numbered from 1 to " << testList.size() << endl;
return -1;
} else {
for (iter = testList.begin(), i = 1; iter != testList.end(); iter++, i++) {
if (!oneTest || testNumber == i) {
int status = (*iter)->isTestAvailable() ? (*iter)->runTest() : -1;
StatusPrint(i, (*iter)->GetName(), status , lineWidth);
if (status <= 0) nFailed++; // successfull tests return a positive number
}
delete *iter;
}
}
}
if (dryRun) {
RooTrace::dump();
}
gBenchmark->Stop("stressHistFactory");
//Print table with results
Bool_t UNIX = strcmp(gSystem->GetName(), "Unix") == 0;
cout << setw(lineWidth) << setfill('*') << "" << endl;
if (UNIX) {
TString sp = gSystem->GetFromPipe("uname -a");
cout << "* SYS: " << sp << endl;
if (strstr(gSystem->GetBuildNode(), "Linux")) {
sp = gSystem->GetFromPipe("lsb_release -d -s");
cout << "* SYS: " << sp << endl;
}
if (strstr(gSystem->GetBuildNode(), "Darwin")) {
sp = gSystem->GetFromPipe("sw_vers -productVersion");
sp += " Mac OS X ";
cout << "* SYS: " << sp << endl;
}
} else {
const Char_t *os = gSystem->Getenv("OS");
if (!os) cout << "* SYS: Windows 95" << endl;
else cout << "* SYS: " << os << " " << gSystem->Getenv("PROCESSOR_IDENTIFIER") << endl;
}
cout << setw(lineWidth) << setfill('*') << "" << endl;
gBenchmark->Print("stressHistFactory");
Double_t reftime = 2.4; //maclm compiled
const Double_t rootmarks = 860 * reftime / gBenchmark->GetCpuTime("stressHistFactory");
cout << setw(lineWidth) << setfill('*') << "" << endl;
cout << TString::Format("* ROOTMARKS = %6.1f * Root %-8s %d/%d", rootmarks, gROOT->GetVersion(),
gROOT->GetVersionDate(), gROOT->GetVersionTime()) << endl;
cout << setw(lineWidth) << setfill('*') << "" << endl;
// NOTE: The function TStopwatch::CpuTime() calls Tstopwatch::Stop(), so you do not need to stop the timer separately.
cout << "Time at the end of job = " << timer.CpuTime() << " seconds" << endl;
if (fref) {
fref->Close() ;
delete fref ;
}
delete gBenchmark ;
gBenchmark = 0 ;
return nFailed;
}
//_____________________________batch only_____________________
#ifndef __CINT__
int main(int argc, const char *argv[])
{
Bool_t doWrite = kFALSE;
Int_t verbose = 0;
Bool_t allTests = kFALSE;
Bool_t oneTest = kFALSE;
Int_t testNumber = 0;
Bool_t dryRun = kFALSE;
string refFileName = "$ROOTSYS/test/stressHistFactory_ref.root" ;
// Parse command line arguments
for (Int_t i = 1 ; i < argc ; i++) {
string arg = argv[i] ;
if (arg == "-f") {
cout << "stressHistFactory: using reference file " << argv[i + 1] << endl ;
refFileName = argv[++i] ;
} else if (arg == "-w") {
cout << "stressHistFactory: running in writing mode to update reference file" << endl ;
doWrite = kTRUE ;
} else if (arg == "-mc") {
cout << "stressHistFactory: running in memcheck mode, no regression tests are performed" << endl;
dryRun = kTRUE;
} else if (arg == "-v") {
cout << "stressHistFactory: running in verbose mode" << endl;
verbose = 1;
} else if (arg == "-vv") {
cout << "stressHistFactory: running in very verbose mode" << endl;
verbose = 2;
} else if (arg == "-a") {
cout << "stressHistFactory: deploying full suite of tests" << endl;
allTests = kTRUE;
} else if (arg == "-n") {
cout << "stressHistFactory: running single test" << endl;
oneTest = kTRUE;
testNumber = atoi(argv[++i]);
} else if (arg == "-d") {
cout << "stressHistFactory: setting gDebug to " << argv[i + 1] << endl;
gDebug = atoi(argv[++i]);
} else if (arg == "-h") {
cout << "usage: stressHistFactory [ options ] " << endl;
cout << "" << endl;
cout << " -f <file> : use given reference file instead of default (" << refFileName << ")" << endl;
cout << " -w : write reference file, instead of reading file and running comparison tests" << endl;
cout << " -n N : only run test with sequential number N" << endl;
cout << " -a : run full suite of tests (default is basic suite); this overrides the -n single test option" << endl;
cout << " -mc : memory check mode, no regression test are performed. Set this flag when running with valgrind" << endl;
cout << " -vs : use vector-based storage for all datasets (default is tree-based storage)" << endl;
cout << " -v/-vv : set verbose mode (show result of each regression test) or very verbose mode (show all roofit output as well)" << endl;
cout << " -d N : set ROOT gDebug flag to N" << endl ;
cout << " " << endl ;
return 0 ;
}
}
// Disable caching of complex error function calculation, as we don't
// want to write out the cache file as part of the validation procedure
RooMath::cacheCERF(kFALSE) ;
gBenchmark = new TBenchmark();
return stressHistFactory(refFileName.c_str(), doWrite, verbose, allTests, oneTest, testNumber, dryRun);
}
#endif
<|endoftext|> |
<commit_before>#include <rai/node/utility.hpp>
#include <rai/lib/interface.h>
#include <lmdb/libraries/liblmdb/lmdb.h>
#include <ed25519-donna/ed25519.h>
boost::filesystem::path rai::unique_path ()
{
auto result (working_path () / boost::filesystem::unique_path ());
return result;
}
rai::mdb_env::mdb_env (bool & error_a, boost::filesystem::path const & path_a)
{
boost::system::error_code error;
if (path_a.has_parent_path ())
{
boost::filesystem::create_directories (path_a.parent_path (), error);
if (!error)
{
auto status1 (mdb_env_create (&environment));
assert (status1 == 0);
auto status2 (mdb_env_set_maxdbs (environment, 128));
assert (status2 == 0);
auto status3 (mdb_env_set_mapsize (environment, 1ULL * 1024 * 1024 * 1024 * 1024)); // 1 Terabyte
assert (status3 == 0);
auto status4 (mdb_env_open (environment, path_a.string ().c_str (), MDB_NOSUBDIR, 00600));
error_a = status4 != 0;
}
else
{
error_a = true;
environment = nullptr;
}
}
else
{
error_a = true;
environment = nullptr;
}
}
rai::mdb_env::~mdb_env ()
{
if (environment != nullptr)
{
mdb_env_close (environment);
}
}
rai::mdb_env::operator MDB_env * () const
{
return environment;
}
rai::mdb_val::mdb_val () :
value ({0, nullptr})
{
}
rai::mdb_val::mdb_val (MDB_val const & value_a) :
value (value_a)
{
}
rai::mdb_val::mdb_val (size_t size_a, void * data_a) :
value ({size_a, data_a})
{
}
rai::mdb_val::mdb_val (rai::uint128_union const & val_a) :
mdb_val (sizeof (val_a), const_cast <rai::uint128_union *> (&val_a))
{
}
rai::mdb_val::mdb_val (rai::uint256_union const & val_a) :
mdb_val (sizeof (val_a), const_cast <rai::uint256_union *> (&val_a))
{
}
void * rai::mdb_val::data () const
{
return value.mv_data;
}
size_t rai::mdb_val::size () const
{
return value.mv_size;
}
rai::uint256_union rai::mdb_val::uint256 () const
{
rai::uint256_union result;
assert (size () == sizeof (result));
std::copy (reinterpret_cast <uint8_t const *> (data ()), reinterpret_cast <uint8_t const *> (data ()) + sizeof (result), result.bytes.data ());
return result;
}
rai::mdb_val::operator MDB_val * () const
{
// Allow passing a temporary to a non-c++ function which doesn't have constness
return const_cast <MDB_val *> (&value);
};
rai::mdb_val::operator MDB_val const & () const
{
return value;
}
rai::transaction::transaction (rai::mdb_env & environment_a, MDB_txn * parent_a, bool write) :
environment (environment_a)
{
auto status (mdb_txn_begin (environment_a, parent_a, write ? 0 : MDB_RDONLY, &handle));
assert (status == 0);
}
rai::transaction::~transaction ()
{
auto status (mdb_txn_commit (handle));
assert (status == 0);
}
rai::transaction::operator MDB_txn * () const
{
return handle;
}
void rai::open_or_create (std::fstream & stream_a, std::string const & path_a)
{
stream_a.open (path_a, std::ios_base::in);
if (stream_a.fail ())
{
stream_a.open (path_a, std::ios_base::out);
}
stream_a.close ();
stream_a.open (path_a, std::ios_base::in | std::ios_base::out);
}
<commit_msg>Using safer MDB_NOTLS in case io_threads > mdb_env_set_maxreaders<commit_after>#include <rai/node/utility.hpp>
#include <rai/lib/interface.h>
#include <lmdb/libraries/liblmdb/lmdb.h>
#include <ed25519-donna/ed25519.h>
boost::filesystem::path rai::unique_path ()
{
auto result (working_path () / boost::filesystem::unique_path ());
return result;
}
rai::mdb_env::mdb_env (bool & error_a, boost::filesystem::path const & path_a)
{
boost::system::error_code error;
if (path_a.has_parent_path ())
{
boost::filesystem::create_directories (path_a.parent_path (), error);
if (!error)
{
auto status1 (mdb_env_create (&environment));
assert (status1 == 0);
auto status2 (mdb_env_set_maxdbs (environment, 128));
assert (status2 == 0);
auto status3 (mdb_env_set_mapsize (environment, 1ULL * 1024 * 1024 * 1024 * 1024)); // 1 Terabyte
assert (status3 == 0);
// It seems if there's ever more threads than mdb_env_set_maxreaders has read slots available, we get failures on transaction creation unless MDB_NOTLS is specified
// This can happen if something like 256 io_threads are specified in the node config
auto status4 (mdb_env_open (environment, path_a.string ().c_str (), MDB_NOSUBDIR | MDB_NOTLS, 00600));
error_a = status4 != 0;
}
else
{
error_a = true;
environment = nullptr;
}
}
else
{
error_a = true;
environment = nullptr;
}
}
rai::mdb_env::~mdb_env ()
{
if (environment != nullptr)
{
mdb_env_close (environment);
}
}
rai::mdb_env::operator MDB_env * () const
{
return environment;
}
rai::mdb_val::mdb_val () :
value ({0, nullptr})
{
}
rai::mdb_val::mdb_val (MDB_val const & value_a) :
value (value_a)
{
}
rai::mdb_val::mdb_val (size_t size_a, void * data_a) :
value ({size_a, data_a})
{
}
rai::mdb_val::mdb_val (rai::uint128_union const & val_a) :
mdb_val (sizeof (val_a), const_cast <rai::uint128_union *> (&val_a))
{
}
rai::mdb_val::mdb_val (rai::uint256_union const & val_a) :
mdb_val (sizeof (val_a), const_cast <rai::uint256_union *> (&val_a))
{
}
void * rai::mdb_val::data () const
{
return value.mv_data;
}
size_t rai::mdb_val::size () const
{
return value.mv_size;
}
rai::uint256_union rai::mdb_val::uint256 () const
{
rai::uint256_union result;
assert (size () == sizeof (result));
std::copy (reinterpret_cast <uint8_t const *> (data ()), reinterpret_cast <uint8_t const *> (data ()) + sizeof (result), result.bytes.data ());
return result;
}
rai::mdb_val::operator MDB_val * () const
{
// Allow passing a temporary to a non-c++ function which doesn't have constness
return const_cast <MDB_val *> (&value);
};
rai::mdb_val::operator MDB_val const & () const
{
return value;
}
rai::transaction::transaction (rai::mdb_env & environment_a, MDB_txn * parent_a, bool write) :
environment (environment_a)
{
auto status (mdb_txn_begin (environment_a, parent_a, write ? 0 : MDB_RDONLY, &handle));
assert (status == 0);
}
rai::transaction::~transaction ()
{
auto status (mdb_txn_commit (handle));
assert (status == 0);
}
rai::transaction::operator MDB_txn * () const
{
return handle;
}
void rai::open_or_create (std::fstream & stream_a, std::string const & path_a)
{
stream_a.open (path_a, std::ios_base::in);
if (stream_a.fail ())
{
stream_a.open (path_a, std::ios_base::out);
}
stream_a.close ();
stream_a.open (path_a, std::ios_base::in | std::ios_base::out);
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/PoseStamped.h>
#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
#include <tf/tf.h>
#define ROS_RATE 10
using namespace std;
ClientSocket client_socket("", 54300);
const int ENC_MAX = 3932159;
const int SPEED_MAX = 32767;
const float DIST_PER_PULSE = 0.552486; // mm par pulse
const int WHEEL_DIST = 570; // 533;
// long int ENC_L = 0;
// long int ENC_R = 0;
pthread_t thread_odom;
pthread_t thread_pub;
pthread_mutex_t mutex_socket = PTHREAD_MUTEX_INITIALIZER;
class MachinePose_s {
private:
public:
MachinePose_s() {
ROS_DEBUG("In Mimamorukun Constructor");
this->pos_odom.x = 0.0;
this->pos_odom.y = 0.0;
this->pos_odom.theta = 0.0;
this->vel_odom.x = 0.0;
this->vel_odom.y = 0.0;
this->vel_odom.theta = 0.0;
};
~MachinePose_s() {};
void updateOdom();
bool goPose(/*const geometry_msgs::Pose2D::ConstPtr& cmd_pose*/);
bool postPose();
geometry_msgs::Twist tgtTwist;
geometry_msgs::Pose2D pos_odom;
// geometry_msgs::PoseStamped pos_odom;
// geometry_msgs::Twist vel_odom;
geometry_msgs::Pose2D vel_odom;
void setCurrentPosition(geometry_msgs::Pose2D pose);
geometry_msgs::Pose2D getCurrentPosition();
// bool goPose2(/*const geometry_msgs::Pose2D::ConstPtr& cmd_pose*/);
} mchn_pose;
int Dist2Pulse(int dist) { return ((float)dist) / DIST_PER_PULSE; }
int Pulse2Dist(int pulse) { return ((float)pulse) * DIST_PER_PULSE; }
double Rad2Deg(double rad) { return rad * (180.0) / M_PI; }
double Deg2Rad(double deg) { return deg * M_PI / 180.0; }
// double Deg2Rad(double deg) { return deg * 3 / 180.0; }
double MM2M(double mm) { return mm * 0.001; }
double M2MM(double M) { return M * 1000; }
double sqr(double val) { return pow(val, 2); }
double Limit(double val, double max, double min) {
if (val > max)
return max;
else if (min > val)
return min;
else
return val;
}
double nomalizeAng(double rad) {
while (rad > M_PI) { //角度を-180°~180°(-π~π)の範囲に合わせる
rad = rad - (2 * M_PI);
}
while (rad < -M_PI) {
rad = rad + (2 * M_PI);
}
return rad;
}
void MachinePose_s::updateOdom() {
// update Encoder value
long int ENC_L, ENC_R;
long int tmpENC_L = 0;
long int tmpENC_R = 0;
string reply;
pthread_mutex_lock(&mutex_socket);
client_socket << "@GP1@GP2"; /*use 250ms for send and get reply*/
client_socket >> reply;
pthread_mutex_unlock(&mutex_socket);
ROS_DEBUG_STREAM("@GP raw:" << reply);
sscanf(reply.c_str(), "@GP1,%ld@GP2,%ld", &tmpENC_L, &tmpENC_R);
ROS_DEBUG_STREAM("tmpENC_L:" << tmpENC_L << " tmpENC_R:" << tmpENC_R);
if (tmpENC_L > ENC_MAX / 2)
ENC_L = tmpENC_L - (ENC_MAX + 1);
else
ENC_L = tmpENC_L;
if (tmpENC_R > ENC_MAX / 2)
ENC_R = tmpENC_R - (ENC_MAX + 1);
else
ENC_R = tmpENC_R;
static long int ENC_R_old = 0;
static long int ENC_L_old = 0;
double detLp /*,r , dX ,dY,dL*/;
if (fabs(ENC_L - ENC_L_old) > ENC_MAX / 2) ENC_L_old -= ENC_MAX + 1;
if (fabs(ENC_R - ENC_R_old) > ENC_MAX / 2) ENC_R_old -= ENC_MAX + 1;
//エンコーダーの位置での前回からの移動距離dL_R,dL_Lを算出
double dL_L = (double)(ENC_L - ENC_L_old) * (-DIST_PER_PULSE);
double dL_R = (double)(ENC_R - ENC_R_old) * DIST_PER_PULSE;
//角速度SIGMAを算出
double POS_SIGMA = (dL_R - dL_L) / WHEEL_DIST;
double dL = (dL_R + dL_L) * 0.50000;
double dX = dL * cos(mchn_pose.pos_odom.theta + POS_SIGMA); // X,Yの前回からの移動量計算
double dY = dL * sin(mchn_pose.pos_odom.theta + POS_SIGMA);
ENC_R_old = ENC_R; //前回のエンコーダーの値を記録
ENC_L_old = ENC_L;
mchn_pose.pos_odom.x += dX;
mchn_pose.pos_odom.y += dY;
mchn_pose.pos_odom.theta += POS_SIGMA;
mchn_pose.pos_odom.theta = nomalizeAng(mchn_pose.pos_odom.theta);
mchn_pose.vel_odom.x = dX;
mchn_pose.vel_odom.y = dY;
mchn_pose.vel_odom.theta = POS_SIGMA;
return;
}
/*------------------------------------
* send command to mbed in wheel chair
* argument:
* arg_speed: forward speed [mm/sec]
* arg_theta: CCW turn speed [radian/sec]
* ----------------------------------*/
void spinWheel(/*double arg_speed, double arg_theta*/) {
double arg_speed = mchn_pose.tgtTwist.linear.x;
double arg_theta = mchn_pose.tgtTwist.angular.z;
// ROS_INFO("X:%4.2f Theta:%4.2f",arg_speed,arg_theta);
double val_L = -Dist2Pulse(arg_speed) + Dist2Pulse((WHEEL_DIST / 2) * arg_theta);
double val_R = Dist2Pulse(arg_speed) + Dist2Pulse((WHEEL_DIST / 2) * arg_theta);
val_L = (int)Limit(val_L, (double)SPEED_MAX, (double)-SPEED_MAX);
val_R = (int)Limit(val_R, (double)SPEED_MAX, (double)-SPEED_MAX);
printf("val_L:%2.f val_R:%2.f", val_L, val_R);
string cmd_L = boost::lexical_cast<string>(val_L);
string cmd_R = boost::lexical_cast<string>(val_R);
string message;
message = "@SS1," + cmd_L + "@SS2," + cmd_R;
pthread_mutex_lock(&mutex_socket);
client_socket << message;
// message = "@SS2," + cmd_R;
// client_socket << message;
string reply;
client_socket >> reply;
pthread_mutex_unlock(&mutex_socket);
ROS_DEBUG_STREAM("@SS raw: " << reply);
// cout << "Response:" << reply << " ";
}
void receiveCmdVel(const geometry_msgs::Twist::ConstPtr &cmd_vel) {
mchn_pose.tgtTwist = *cmd_vel;
// spinWheel(/*cmd_vel->linear.x,cmd_vel->angular.z*/);
}
void *odom_update(void *ptr) {
// ros::Rate r(30);
ros::Rate r(ROS_RATE);
while (ros::ok()) {
mchn_pose.updateOdom();
r.sleep();
}
}
void *publish_odom(void *ptr) {
static ros::NodeHandle nh("~");
// static ros::Publisher pub = nh.advertise<geometry_msgs::PoseStamped>("kalman_pose", 1);
static ros::Publisher pub = nh.advertise<nav_msgs::Odometry>("odom", 1);
nav_msgs::Odometry odom;
odom.header.frame_id = "/odom";
odom.child_frame_id = "/base_link_footprint";
odom.pose.pose.position.z = 0.0;
ros::Rate r(ROS_RATE);
while (ros::ok()) {
odom.pose.pose.position.x = mchn_pose.pos_odom.x;
odom.pose.pose.position.y = mchn_pose.pos_odom.y;
odom.header.stamp = ros::Time::now();
odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(mchn_pose.pos_odom.theta);
odom.twist.twist.linear.x = 0.0;
odom.twist.twist.linear.y = 0.0;
odom.twist.twist.angular.z = 0.0;
pub.publish(odom);
r.sleep();
}
}
int main(int argc, char **argv) {
ROS_INFO("wc_controller");
ros::init(argc, argv, "wc_controller");
ros::NodeHandle n;
int Kp_, Ki_, Kd_;
string s_Kp_, s_Ki_, s_Kd_;
ros::NodeHandle nh_param("~");
string tmp_ip;
nh_param.param<string>("IP_ADDR", tmp_ip, "192.168.11.99");
nh_param.param<int>("spin_Kp", Kp_, 4800);
nh_param.param<int>("spin_Ki", Ki_, /*30*/ 100);
nh_param.param<int>("spin_Kd", Kd_, 40000);
// acces like "mimamorukun_controller/spd_Kp"
client_socket.init(tmp_ip, 54300);
s_Kp_ = boost::lexical_cast<string>(Kp_);
s_Ki_ = boost::lexical_cast<string>(Ki_);
s_Kd_ = boost::lexical_cast<string>(Kd_);
try {
string reply;
try {
// koyuusinndou 3Hz at Kp = 8000
// client_socket << "@CR1@CR2@SM1,1@SM2,1@PP1,50@PP2,50@PI1,100@PI2,100@PD1,10@PD2,10";
client_socket << "@CR1@CR2@SM1,1@SM2,1@PP1," + s_Kp_ + "@PP2," + s_Kp_ + "@PI1," + s_Ki_ +
"@PI2," + s_Ki_ + "@PD1," + s_Kd_ + "@PD2," + s_Kd_;
client_socket >> reply;
}
catch (SocketException &) {
}
cout << "Response:" << reply << "\n";
;
}
catch (SocketException &e) {
cout << "Exception was caught:" << e.description() << "\n";
}
// mchn_pose.updateVicon();
printf("initial val x:%4.2lf y:%4.2lf th:%4.2lf\n\r", mchn_pose.pos_odom.x, mchn_pose.pos_odom.y,
Rad2Deg(mchn_pose.pos_odom.theta));
// mchn_pose.setCurrentPosition(mchn_pose.pos_vicon);
if (pthread_create(&thread_odom, NULL, odom_update, NULL)) {
cout << "error creating thread." << endl;
abort();
}
if (pthread_create(&thread_pub, NULL, publish_odom, NULL)) {
cout << "error creating thread." << endl;
abort();
}
ros::Rate r(ROS_RATE);
while (n.ok()) {
spinWheel();
ros::spinOnce();
r.sleep();
}
return (0);
}
/*****************************************************************************************************/
void MachinePose_s::setCurrentPosition(geometry_msgs::Pose2D pose) { pos_odom = pose; }
<commit_msg>オドメトリと速度のクラスをROSのメッセージに変更<commit_after>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/PoseStamped.h>
#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
#include <tf/tf.h>
#define ROS_RATE 10
using namespace std;
ClientSocket client_socket("", 54300);
const int ENC_MAX = 3932159;
const int SPEED_MAX = 32767;
const float DIST_PER_PULSE = 0.552486; // mm par pulse
const int WHEEL_DIST = 570; // 533;
// long int ENC_L = 0;
// long int ENC_R = 0;
pthread_t thread_odom;
pthread_t thread_pub;
pthread_mutex_t mutex_socket = PTHREAD_MUTEX_INITIALIZER;
class MachinePose_s {
private:
public:
MachinePose_s() {
ROS_DEBUG("In Mimamorukun Constructor");
m_Odom.header.frame_id = "/odom";
m_Odom.child_frame_id = "/base_link_footprint";
m_Odom.pose.pose.position.z = 0.0;
// this->pos_odom.x = 0.0;
// this->pos_odom.y = 0.0;
// this->pos_odom.theta = 0.0;
// this->vel_odom.x = 0.0;
// this->vel_odom.y = 0.0;
// this->vel_odom.theta = 0.0;
};
~MachinePose_s() {};
void updateOdom();
bool goPose(/*const geometry_msgs::Pose2D::ConstPtr& cmd_pose*/);
bool postPose();
nav_msgs::Odometry m_Odom;
geometry_msgs::Twist tgtTwist;
// geometry_msgs::Pose2D pos_odom;
// geometry_msgs::PoseStamped pos_odom;
// geometry_msgs::Twist vel_odom;
// geometry_msgs::Pose2D vel_odom;
// void setCurrentPosition(geometry_msgs::Pose2D pose);
void setCurrentPosition(geometry_msgs::Pose pose);
geometry_msgs::Pose2D getCurrentPosition();
// bool goPose2(/*const geometry_msgs::Pose2D::ConstPtr& cmd_pose*/);
} mchn_pose;
int Dist2Pulse(int dist) { return ((float)dist) / DIST_PER_PULSE; }
int Pulse2Dist(int pulse) { return ((float)pulse) * DIST_PER_PULSE; }
double Rad2Deg(double rad) { return rad * (180.0) / M_PI; }
double Deg2Rad(double deg) { return deg * M_PI / 180.0; }
// double Deg2Rad(double deg) { return deg * 3 / 180.0; }
double MM2M(double mm) { return mm * 0.001; }
double M2MM(double M) { return M * 1000; }
double sqr(double val) { return pow(val, 2); }
double Limit(double val, double max, double min) {
if (val > max)
return max;
else if (min > val)
return min;
else
return val;
}
double nomalizeAng(double rad) {
while (rad > M_PI) { //角度を-180°~180°(-π~π)の範囲に合わせる
rad = rad - (2 * M_PI);
}
while (rad < -M_PI) {
rad = rad + (2 * M_PI);
}
return rad;
}
void MachinePose_s::updateOdom() {
// update Encoder value
long int ENC_L, ENC_R;
long int tmpENC_L = 0;
long int tmpENC_R = 0;
string reply;
pthread_mutex_lock(&mutex_socket);
client_socket << "@GP1@GP2"; /*use 250ms for send and get reply*/
client_socket >> reply;
pthread_mutex_unlock(&mutex_socket);
ROS_DEBUG_STREAM("@GP raw:" << reply);
sscanf(reply.c_str(), "@GP1,%ld@GP2,%ld", &tmpENC_L, &tmpENC_R);
ROS_DEBUG_STREAM("tmpENC_L:" << tmpENC_L << " tmpENC_R:" << tmpENC_R);
if (tmpENC_L > ENC_MAX / 2)
ENC_L = tmpENC_L - (ENC_MAX + 1);
else
ENC_L = tmpENC_L;
if (tmpENC_R > ENC_MAX / 2)
ENC_R = tmpENC_R - (ENC_MAX + 1);
else
ENC_R = tmpENC_R;
static long int ENC_R_old = 0;
static long int ENC_L_old = 0;
double detLp /*,r , dX ,dY,dL*/;
if (fabs(ENC_L - ENC_L_old) > ENC_MAX / 2) ENC_L_old -= ENC_MAX + 1;
if (fabs(ENC_R - ENC_R_old) > ENC_MAX / 2) ENC_R_old -= ENC_MAX + 1;
//エンコーダーの位置での前回からの移動距離dL_R,dL_Lを算出
double dL_L = (double)(ENC_L - ENC_L_old) * (-DIST_PER_PULSE);
double dL_R = (double)(ENC_R - ENC_R_old) * DIST_PER_PULSE;
//角速度SIGMAを算出
double POS_SIGMA = (dL_R - dL_L) / WHEEL_DIST;
double dL = (dL_R + dL_L) * 0.50000;
// double dX = dL * cos(mchn_pose.pos_odom.theta + POS_SIGMA); // X,Yの前回からの移動量計算
// double dY = dL * sin(mchn_pose.pos_odom.theta + POS_SIGMA);
double dX =
dL * cos(tf::getYaw(m_Odom.pose.pose.orientation) + POS_SIGMA); // X,Yの前回からの移動量計算
double dY = dL * sin(tf::getYaw(m_Odom.pose.pose.orientation) + POS_SIGMA);
ENC_R_old = ENC_R; //前回のエンコーダーの値を記録
ENC_L_old = ENC_L;
// mchn_pose.pos_odom.x += dX;
// mchn_pose.pos_odom.y += dY;
// mchn_pose.pos_odom.theta += POS_SIGMA;
// mchn_pose.pos_odom.theta = nomalizeAng(mchn_pose.pos_odom.theta);
// mchn_pose.vel_odom.x = dX;
// mchn_pose.vel_odom.y = dY;
// mchn_pose.vel_odom.theta = POS_SIGMA;
m_Odom.pose.pose.position.x += MM2M(dX);
m_Odom.pose.pose.position.y += MM2M(dY);
// m_Odom.pose.pose.orientation += POS_SIGMA;
// m_Odom.pos_odom.theta = nomalizeAng(mchn_pose.pos_odom.theta);
tf::Quaternion q1;
tf::quaternionMsgToTF(m_Odom.pose.pose.orientation, q1);
tf::Quaternion q2;
tf::quaternionMsgToTF(tf::createQuaternionMsgFromYaw(POS_SIGMA), q2);
q1 += q2;
tf::quaternionTFToMsg(q1, m_Odom.pose.pose.orientation);
m_Odom.twist.twist.linear.x = MM2M(dL) / (double)ROS_RATE;
m_Odom.twist.twist.linear.y = 0.0;
m_Odom.twist.twist.angular.z = POS_SIGMA;
return;
}
/*------------------------------------
* send command to mbed in wheel chair
* argument:
* arg_speed: forward speed [mm/sec]
* arg_theta: CCW turn speed [radian/sec]
* ----------------------------------*/
void spinWheel(/*double arg_speed, double arg_theta*/) {
double arg_speed = M2MM(mchn_pose.tgtTwist.linear.x);
double arg_theta = mchn_pose.tgtTwist.angular.z;
// ROS_INFO("X:%4.2f Theta:%4.2f",arg_speed,arg_theta);
double val_L = -Dist2Pulse(arg_speed) + Dist2Pulse((WHEEL_DIST / 2) * arg_theta);
double val_R = Dist2Pulse(arg_speed) + Dist2Pulse((WHEEL_DIST / 2) * arg_theta);
val_L = (int)Limit(val_L, (double)SPEED_MAX, (double)-SPEED_MAX);
val_R = (int)Limit(val_R, (double)SPEED_MAX, (double)-SPEED_MAX);
printf("val_L:%2.f val_R:%2.f", val_L, val_R);
string cmd_L = boost::lexical_cast<string>(val_L);
string cmd_R = boost::lexical_cast<string>(val_R);
string message;
message = "@SS1," + cmd_L + "@SS2," + cmd_R;
pthread_mutex_lock(&mutex_socket);
client_socket << message;
// message = "@SS2," + cmd_R;
// client_socket << message;
string reply;
client_socket >> reply;
pthread_mutex_unlock(&mutex_socket);
ROS_DEBUG_STREAM("@SS raw: " << reply);
// cout << "Response:" << reply << " ";
}
void receiveCmdVel(const geometry_msgs::Twist::ConstPtr &cmd_vel) {
mchn_pose.tgtTwist = *cmd_vel;
// spinWheel(/*cmd_vel->linear.x,cmd_vel->angular.z*/);
}
void *odom_update(void *ptr) {
// ros::Rate r(30);
ros::Rate r(ROS_RATE);
while (ros::ok()) {
mchn_pose.updateOdom();
r.sleep();
}
}
void *publish_odom(void *ptr) {
static ros::NodeHandle nh("~");
// static ros::Publisher pub = nh.advertise<geometry_msgs::PoseStamped>("kalman_pose", 1);
static ros::Publisher pub = nh.advertise<nav_msgs::Odometry>("odom", 1);
// nav_msgs::Odometry tmp_odom;
// tmp_odom.header.frame_id = "/odom";
// tmp_odom.child_frame_id = "/base_link_footprint";
// tmp_odom.pose.pose.position.z = 0.0;
ros::Rate r(ROS_RATE);
while (ros::ok()) {
// tmp_odom.pose.pose.position.x = mchn_pose.pos_odom.x;
// tmp_odom.pose.pose.position.y = mchn_pose.pos_odom.y;
// tmp_odom.header.stamp = ros::Time::now();
// tmp_odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(mchn_pose.pos_odom.theta);
// tmp_odom.twist.twist.linear.x = 0.0;
// tmp_odom.twist.twist.linear.y = 0.0;
// tmp_odom.twist.twist.angular.z = 0.0;
// pub.publish(tmp_odom);
pub.publish(mchn_pose.m_Odom);
r.sleep();
}
}
int main(int argc, char **argv) {
ROS_INFO("wc_controller");
ros::init(argc, argv, "wc_controller");
ros::NodeHandle n;
int Kp_, Ki_, Kd_;
string s_Kp_, s_Ki_, s_Kd_;
ros::NodeHandle nh_param("~");
string tmp_ip;
nh_param.param<string>("IP_ADDR", tmp_ip, "192.168.11.99");
nh_param.param<int>("spin_Kp", Kp_, 4800);
nh_param.param<int>("spin_Ki", Ki_, /*30*/ 100);
nh_param.param<int>("spin_Kd", Kd_, 40000);
// acces like "mimamorukun_controller/spd_Kp"
client_socket.init(tmp_ip, 54300);
s_Kp_ = boost::lexical_cast<string>(Kp_);
s_Ki_ = boost::lexical_cast<string>(Ki_);
s_Kd_ = boost::lexical_cast<string>(Kd_);
try {
string reply;
try {
// koyuusinndou 3Hz at Kp = 8000
// client_socket << "@CR1@CR2@SM1,1@SM2,1@PP1,50@PP2,50@PI1,100@PI2,100@PD1,10@PD2,10";
client_socket << "@CR1@CR2@SM1,1@SM2,1@PP1," + s_Kp_ + "@PP2," + s_Kp_ + "@PI1," + s_Ki_ +
"@PI2," + s_Ki_ + "@PD1," + s_Kd_ + "@PD2," + s_Kd_;
client_socket >> reply;
}
catch (SocketException &) {
}
cout << "Response:" << reply << "\n";
;
}
catch (SocketException &e) {
cout << "Exception was caught:" << e.description() << "\n";
}
// mchn_pose.updateVicon();
// printf("initial val x:%4.2lf y:%4.2lf th:%4.2lf\n\r", mchn_pose.pos_odom.x,
// mchn_pose.pos_odom.y,
// Rad2Deg(mchn_pose.pos_odom.theta));
printf("initial val x:%4.2lf y:%4.2lf th:%4.2lf\n\r", mchn_pose.m_Odom.pose.pose.position.x,
mchn_pose.m_Odom.pose.pose.position.y,
Rad2Deg(tf::getYaw(mchn_pose.m_Odom.pose.pose.orientation)));
// mchn_pose.setCurrentPosition(mchn_pose.pos_vicon);
if (pthread_create(&thread_odom, NULL, odom_update, NULL)) {
cout << "error creating thread." << endl;
abort();
}
if (pthread_create(&thread_pub, NULL, publish_odom, NULL)) {
cout << "error creating thread." << endl;
abort();
}
ros::Rate r(ROS_RATE);
while (n.ok()) {
spinWheel();
ros::spinOnce();
r.sleep();
}
return (0);
}
/*****************************************************************************************************/
// void MachinePose_s::setCurrentPosition(geometry_msgs::Pose2D pose) { pos_odom = pose; }
void MachinePose_s::setCurrentPosition(geometry_msgs::Pose pose) {
m_Odom.pose.pose = pose;
// pos_odom = pose;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unordered_map>
#include <drc_utils/LcmWrapper.hpp>
#include <ConciseArgs>
#include <lcm/lcm-cpp.hpp>
#include <bot_lcmgl_client/lcmgl.h>
#include <maps/BotWrapper.hpp>
#include <maps/Collector.hpp>
#include <maps/Utils.hpp>
#include <maps/MapManager.hpp>
#include <maps/LocalMap.hpp>
#include <maps/PointCloudView.hpp>
#include <lcmtypes/bot_core/rigid_transform_t.hpp>
#include <pcl/registration/icp.h>
struct State : public maps::Collector::DataListener {
std::shared_ptr<drc::LcmWrapper> mLcmWrapper;
std::shared_ptr<lcm::LCM> mLcm;
std::shared_ptr<maps::BotWrapper> mBotWrapper;
std::shared_ptr<maps::Collector> mCollector;
std::string mLaserChannel;
std::string mUpdateChannel;
bot_lcmgl_t* mLcmGl;
int64_t mActiveMapId;
int64_t mTimeMin;
int64_t mTimeMax;
maps::PointCloud::Ptr mRefCloud;
maps::PointCloud::Ptr mCurCloud;
Eigen::Isometry3f mCurToRef;
State() {
// initialize some variables
mLcmWrapper.reset(new drc::LcmWrapper());
mLcm = mLcmWrapper->get();
mBotWrapper.reset(new maps::BotWrapper(mLcm));
mCollector.reset(new maps::Collector());
mCollector->setBotWrapper(mBotWrapper);
mLaserChannel = "SCAN_FREE";
mUpdateChannel = "MAPS_LOCAL_CORRECTION";
mActiveMapId = 1;
mTimeMin = mTimeMax = 0;
mLcmGl = bot_lcmgl_init(mBotWrapper->getLcm()->getUnderlyingLCM(),
"maps-registrar");
mCurToRef = Eigen::Isometry3f::Identity();
}
~State() {
bot_lcmgl_destroy(mLcmGl);
}
void start() {
// create new submap
maps::LocalMap::Spec mapSpec;
mapSpec.mId = mActiveMapId;
mapSpec.mPointBufferSize = 5000;
mapSpec.mActive = true;
mapSpec.mBoundMin = Eigen::Vector3f(-1,-1,-1)*1e10;
mapSpec.mBoundMax = Eigen::Vector3f(1,1,1)*1e10;
mapSpec.mResolution = 0.01;
mCollector->getMapManager()->createMap(mapSpec);
// start running wrapper
mCollector->getDataReceiver()->addChannel
(mLaserChannel, maps::SensorDataReceiver::SensorTypePlanarLidar,
mLaserChannel, "local");
mCollector->addListener(*this);
mCollector->start();
// start lcm thread running
mLcmWrapper->startHandleThread(true);
}
void notify(const maps::SensorDataReceiver::SensorData& iData) {
const float kPi = 4*atan(1);
const float kDegToRad = kPi/180;
// find time range of swath and check if it overlaps previous one
int64_t timeMin(0), timeMax(0);
if (!mCollector->getLatestSwath(10*kDegToRad, 190*kDegToRad,
timeMin, timeMax)) return;
if ((timeMin == mTimeMin) && (timeMax == mTimeMax)) return;
mTimeMin = timeMin;
mTimeMax = timeMax;
std::cout << "time range: " << timeMin << " " << timeMax << std::endl;
// create space-time bounds from desired time range and around head
Eigen::Isometry3f headToLocal;
mBotWrapper->getTransform("head","local",headToLocal);
Eigen::Vector3f headPos = headToLocal.translation();
std::cout << "HEAD POS " << headPos.transpose() << std::endl;
maps::LocalMap::SpaceTimeBounds bounds;
bounds.mTimeMin = timeMin;
bounds.mTimeMax = timeMax;
Eigen::Vector3f minPoint(-2,-2,-3), maxPoint(2,2,0.5);
bounds.mPlanes =
maps::Utils::planesFromBox(minPoint+headPos, maxPoint+headPos);
// get point cloud corresponding to this time range
maps::LocalMap::Ptr localMap =
mCollector->getMapManager()->getMap(mActiveMapId);
maps::PointCloudView::Ptr cloudView =
localMap->getAsPointCloud(0.01, bounds);
mCurCloud = cloudView->getAsPointCloud();
if (mRefCloud == NULL) {
mRefCloud = mCurCloud;
}
Eigen::Isometry3f curToRef;
if (registerToReference(mCurCloud, curToRef)) {
std::cout << "SUCCESS" << std::endl;
mCurToRef = curToRef;
publishMessage(mCurToRef, timeMax);
}
}
void publishMessage(const Eigen::Isometry3f& iTransform,
const int64_t iTime) {
bot_core::rigid_transform_t msg;
msg.utime = iTime;
for (int k = 0; k < 3; ++k) msg.trans[k] = iTransform(k,3);
Eigen::Quaternionf q(iTransform.linear());
msg.quat[0] = q.w();
msg.quat[1] = q.x();
msg.quat[2] = q.y();
msg.quat[3] = q.z();
mLcm->publish(mUpdateChannel, &msg);
}
bool registerToReference(const maps::PointCloud::Ptr& iCurCloud,
Eigen::Isometry3f& oCurToRef) {
typedef maps::PointCloud::PointType PointType;
if (mRefCloud == NULL) return false;
pcl::IterativeClosestPoint<PointType, PointType> icp;
icp.setInputCloud(iCurCloud);
icp.setInputTarget(mRefCloud);
icp.setMaxCorrespondenceDistance(0.05);
pcl::PointCloud<PointType> finalCloud;
icp.align(finalCloud, mCurToRef.matrix());
std::cout << "has converged:" << icp.hasConverged() << " score: " <<
icp.getFitnessScore() << std::endl;
std::cout << "matching points:" << finalCloud.size() << std::endl;
std::cout << icp.getFinalTransformation() << std::endl;
oCurToRef.matrix() = icp.getFinalTransformation();
// debug
bot_lcmgl_t* lcmgl = mLcmGl;
bot_lcmgl_color4f(lcmgl, 0.5, 0, 0, 0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < iCurCloud->size(); ++i) {
maps::PointCloud::PointType point = (*iCurCloud)[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color4f(lcmgl, 0, 0.5, 0, 0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < mRefCloud->size(); ++i) {
maps::PointCloud::PointType point = (*mRefCloud)[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color4f(lcmgl, 0, 0, 0.5,0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < finalCloud.size(); ++i) {
maps::PointCloud::PointType point = finalCloud[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_switch_buffer(lcmgl);
return icp.hasConverged();
}
};
int main(const int iArgc, const char** iArgv) {
// instantiate state object
State state;
// parse arguments
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(state.mUpdateChannel, "u", "update_channel",
"channel on which to publish pose updates");
opt.parse();
state.start();
return 0;
}
<commit_msg>added registration control message to reset module<commit_after>#include <iostream>
#include <unordered_map>
#include <thread>
#include <drc_utils/LcmWrapper.hpp>
#include <ConciseArgs>
#include <lcm/lcm-cpp.hpp>
#include <bot_lcmgl_client/lcmgl.h>
#include <maps/BotWrapper.hpp>
#include <maps/Collector.hpp>
#include <maps/Utils.hpp>
#include <maps/MapManager.hpp>
#include <maps/LocalMap.hpp>
#include <maps/PointCloudView.hpp>
#include <lcmtypes/bot_core/rigid_transform_t.hpp>
#include <lcmtypes/drc/map_registration_command_t.hpp>
#include <pcl/registration/icp.h>
struct State : public maps::Collector::DataListener {
std::shared_ptr<drc::LcmWrapper> mLcmWrapper;
std::shared_ptr<lcm::LCM> mLcm;
std::shared_ptr<maps::BotWrapper> mBotWrapper;
std::shared_ptr<maps::Collector> mCollector;
std::string mLaserChannel;
std::string mUpdateChannel;
bot_lcmgl_t* mLcmGl;
int64_t mActiveMapId;
int64_t mTimeMin;
int64_t mTimeMax;
maps::PointCloud::Ptr mRefCloud;
maps::PointCloud::Ptr mCurCloud;
Eigen::Isometry3f mCurToRef;
std::mutex mMutex;
State() {
// initialize some variables
mLcmWrapper.reset(new drc::LcmWrapper());
mLcm = mLcmWrapper->get();
mBotWrapper.reset(new maps::BotWrapper(mLcm));
mCollector.reset(new maps::Collector());
mCollector->setBotWrapper(mBotWrapper);
mLaserChannel = "SCAN_FREE";
mUpdateChannel = "MAP_LOCAL_CORRECTION";
mActiveMapId = 1;
mTimeMin = mTimeMax = 0;
mLcmGl = bot_lcmgl_init(mBotWrapper->getLcm()->getUnderlyingLCM(),
"maps-registrar");
mCurToRef = Eigen::Isometry3f::Identity();
mLcm->subscribe("MAP_REGISTRATION_COMMAND", &State::onCommand, this);
}
~State() {
bot_lcmgl_destroy(mLcmGl);
}
void onCommand(const lcm::ReceiveBuffer* iBuf,
const std::string& iChannel,
const drc::map_registration_command_t* iMessage) {
if (iMessage->command == drc::map_registration_command_t::RESET_REFERENCE) {
std::unique_lock<std::mutex> lock(mMutex);
mRefCloud.reset();
mCurToRef = Eigen::Isometry3f::Identity();
}
}
void start() {
// create new submap
maps::LocalMap::Spec mapSpec;
mapSpec.mId = mActiveMapId;
mapSpec.mPointBufferSize = 5000;
mapSpec.mActive = true;
mapSpec.mBoundMin = Eigen::Vector3f(-1,-1,-1)*1e10;
mapSpec.mBoundMax = Eigen::Vector3f(1,1,1)*1e10;
mapSpec.mResolution = 0.01;
mCollector->getMapManager()->createMap(mapSpec);
// start running wrapper
mCollector->getDataReceiver()->addChannel
(mLaserChannel, maps::SensorDataReceiver::SensorTypePlanarLidar,
mLaserChannel, "local");
mCollector->addListener(*this);
mCollector->start();
// start lcm thread running
mLcmWrapper->startHandleThread(true);
}
void notify(const maps::SensorDataReceiver::SensorData& iData) {
const float kPi = 4*atan(1);
const float kDegToRad = kPi/180;
// find time range of swath and check if it overlaps previous one
int64_t timeMin(0), timeMax(0);
if (!mCollector->getLatestSwath(10*kDegToRad, 190*kDegToRad,
timeMin, timeMax)) return;
if ((timeMin == mTimeMin) && (timeMax == mTimeMax)) return;
mTimeMin = timeMin;
mTimeMax = timeMax;
std::cout << "time range: " << timeMin << " " << timeMax << std::endl;
// create space-time bounds from desired time range and around head
Eigen::Isometry3f headToLocal;
mBotWrapper->getTransform("head","local",headToLocal);
Eigen::Vector3f headPos = headToLocal.translation();
std::cout << "HEAD POS " << headPos.transpose() << std::endl;
maps::LocalMap::SpaceTimeBounds bounds;
bounds.mTimeMin = timeMin;
bounds.mTimeMax = timeMax;
Eigen::Vector3f minPoint(-2,-2,-3), maxPoint(2,2,0.5);
bounds.mPlanes =
maps::Utils::planesFromBox(minPoint+headPos, maxPoint+headPos);
// get point cloud corresponding to this time range
maps::LocalMap::Ptr localMap =
mCollector->getMapManager()->getMap(mActiveMapId);
maps::PointCloudView::Ptr cloudView =
localMap->getAsPointCloud(0.01, bounds);
mCurCloud = cloudView->getAsPointCloud();
{
// align clouds
std::unique_lock<std::mutex> lock(mMutex);
if (mRefCloud == NULL) {
mRefCloud = mCurCloud;
}
Eigen::Isometry3f curToRef;
if (registerToReference(mCurCloud, curToRef)) {
std::cout << "SUCCESS" << std::endl;
mCurToRef = curToRef;
publishMessage(mCurToRef, timeMax);
}
}
}
void publishMessage(const Eigen::Isometry3f& iTransform,
const int64_t iTime) {
bot_core::rigid_transform_t msg;
msg.utime = iTime;
for (int k = 0; k < 3; ++k) msg.trans[k] = iTransform(k,3);
Eigen::Quaternionf q(iTransform.linear());
msg.quat[0] = q.w();
msg.quat[1] = q.x();
msg.quat[2] = q.y();
msg.quat[3] = q.z();
mLcm->publish(mUpdateChannel, &msg);
}
bool registerToReference(const maps::PointCloud::Ptr& iCurCloud,
Eigen::Isometry3f& oCurToRef) {
typedef maps::PointCloud::PointType PointType;
if (mRefCloud == NULL) return false;
pcl::IterativeClosestPoint<PointType, PointType> icp;
icp.setInputCloud(iCurCloud);
icp.setInputTarget(mRefCloud);
icp.setMaxCorrespondenceDistance(0.05);
pcl::PointCloud<PointType> finalCloud;
icp.align(finalCloud, mCurToRef.matrix());
std::cout << "converged?:" << icp.hasConverged() << " score: " <<
icp.getFitnessScore() << std::endl;
std::cout << "matching points:" << finalCloud.size() << std::endl;
std::cout << icp.getFinalTransformation() << std::endl;
oCurToRef.matrix() = icp.getFinalTransformation();
// debug
bot_lcmgl_t* lcmgl = mLcmGl;
bot_lcmgl_color4f(lcmgl, 0.5, 0, 0, 0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < iCurCloud->size(); ++i) {
maps::PointCloud::PointType point = (*iCurCloud)[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color4f(lcmgl, 0, 0.5, 0, 0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < mRefCloud->size(); ++i) {
maps::PointCloud::PointType point = (*mRefCloud)[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_color4f(lcmgl, 0, 0, 0.5,0.3);
bot_lcmgl_point_size(lcmgl, 3);
for (int i = 0; i < finalCloud.size(); ++i) {
maps::PointCloud::PointType point = finalCloud[i];
bot_lcmgl_begin(lcmgl, LCMGL_POINTS);
bot_lcmgl_vertex3f(lcmgl, point.x, point.y, point.z);
bot_lcmgl_end(lcmgl);
}
bot_lcmgl_switch_buffer(lcmgl);
return icp.hasConverged();
}
};
int main(const int iArgc, const char** iArgv) {
// instantiate state object
State state;
// parse arguments
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(state.mUpdateChannel, "u", "update_channel",
"channel on which to publish pose updates");
opt.parse();
state.start();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
// TEST Foundation::IO::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Process.h"
#include "Stroika/Foundation/IO/FileSystem/DirectoryIterable.h"
#include "Stroika/Foundation/IO/FileSystem/DirectoryIterator.h"
#include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h"
#include "Stroika/Foundation/IO/FileSystem/FileSystem.h"
#include "Stroika/Foundation/IO/FileSystem/MountedFilesystem.h"
#include "Stroika/Foundation/IO/FileSystem/PathName.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::IO::FileSystem;
namespace {
void Test1_DirectoryIterator_ ()
{
Debug::TraceContextBumper ctx ("Test1_DirectoryIterator_");
{
Debug::TraceContextBumper ctx1 ("simple test");
for (DirectoryIterator i{WellKnownLocations::GetTemporary ()}; not i.Done (); ++i) {
DbgTrace (L"filename = %s", i->c_str ());
}
}
{
Debug::TraceContextBumper ctx1 ("t2");
DirectoryIterator i{WellKnownLocations::GetTemporary ()};
for (DirectoryIterator i2 = i; not i2.Done (); ++i2) {
DbgTrace (L"filename = %s", i2->c_str ());
}
}
}
}
namespace {
void Test2_DirectoryIterable_ ()
{
Debug::TraceContextBumper ctx ("Test2_DirectoryIterable_");
for (String filename : DirectoryIterable (WellKnownLocations::GetTemporary ())) {
DbgTrace (L"filename = %s", filename.c_str ());
}
{
Debug::TraceContextBumper ctx1 ("test-known-dir");
static const Containers::Set<filesystem::path> kFileNamesForDir_{L"foo.txt", L"bar.png", L"t3.txt", L"blag.nope"};
static const filesystem::path kTestSubDir_ = WellKnownLocations::GetTemporary () / ToPath (L"Regtest-write-files-" + Characters::ToString (Execution::GetCurrentProcessID ()));
IO::FileSystem::Default ().RemoveDirectoryIf (kTestSubDir_, IO::FileSystem::eRemoveAnyContainedFiles);
[[maybe_unused]] auto&& cleanup = Execution::Finally ([]() noexcept {
IgnoreExceptionsForCall (IO::FileSystem::Default ().RemoveDirectoryIf (kTestSubDir_, IO::FileSystem::eRemoveAnyContainedFiles));
});
IO::FileSystem::Directory (kTestSubDir_).AssureExists ();
kFileNamesForDir_.Apply ([](filesystem::path i) { IO::FileSystem::FileOutputStream::New (kTestSubDir_ / i); });
//DbgTrace (L"kTestSubDir_=%s", kTestSubDir_.c_str ());
//DbgTrace (L"kFileNamesForDir_=%s", Characters::ToString (kFileNamesForDir_).c_str ());
//DbgTrace (L"DirectoryIterable (kTestSubDir_)=%s", Characters::ToString (DirectoryIterable (kTestSubDir_)).c_str ());
VerifyTestResult (Containers::Set<filesystem::path>::EqualsComparer{}(kFileNamesForDir_, DirectoryIterable (kTestSubDir_)));
{
Containers::Set<filesystem::path> answers1;
Containers::Set<filesystem::path> answers2;
DirectoryIterable tmp (kTestSubDir_);
Traversal::Iterator<filesystem::path> i2 = tmp.end (); // we had a bug with copying iterator - when refcnt != 1 - hangs - never advances... Windows only
for (Traversal::Iterator<filesystem::path> i = tmp.begin (); i != tmp.end (); ++i) {
answers1 += *i;
i2 = i;
answers2 += *i;
}
VerifyTestResult (kFileNamesForDir_ == answers1);
VerifyTestResult (kFileNamesForDir_ == answers2);
}
}
}
}
namespace {
namespace Test3_Pathnames_ {
void Test_ExtractDirAndBaseName_ ()
{
// Tests from DOCS line in ExtractDirAndBaseName
#if qPlatform_POSIX
VerifyTestResult ((ExtractDirAndBaseName (L"/usr/lib") == pair<String, String>{L"/usr/", L"lib"}));
VerifyTestResult ((ExtractDirAndBaseName (L"/usr/") == pair<String, String>{L"/", L"usr/"}));
VerifyTestResult ((ExtractDirAndBaseName (L"usr") == pair<String, String>{L"./", L"usr"}));
VerifyTestResult ((ExtractDirAndBaseName (L"/") == pair<String, String>{L"/", L""}));
VerifyTestResult ((ExtractDirAndBaseName (L".") == pair<String, String>{L"./", L"."}));
VerifyTestResult ((ExtractDirAndBaseName (L"..") == pair<String, String>{L"./", L".."}));
#elif qPlatform_Windows
VerifyTestResult ((ExtractDirAndBaseName (L"\\usr\\lib") == pair<String, String>{L"\\usr\\", L"lib"}));
VerifyTestResult ((ExtractDirAndBaseName (L"\\usr\\") == pair<String, String>{L"\\", L"usr\\"}));
VerifyTestResult ((ExtractDirAndBaseName (L"usr") == pair<String, String>{L".\\", L"usr"}));
VerifyTestResult ((ExtractDirAndBaseName (L"\\") == pair<String, String>{L"\\", L""}));
VerifyTestResult ((ExtractDirAndBaseName (L".") == pair<String, String>{L".\\", L"."}));
VerifyTestResult ((ExtractDirAndBaseName (L"..") == pair<String, String>{L".\\", L".."}));
VerifyTestResult ((ExtractDirAndBaseName (L"c:\\h\\m.t") == pair<String, String>{L"c:\\h\\", L"m.t"}));
#endif
}
void Test_GetFileBaseName_ ()
{
VerifyTestResult (GetFileBaseName (L"foo") == L"foo");
VerifyTestResult (GetFileBaseName (L"foo.cpp") == L"foo");
VerifyTestResult (GetFileBaseName (L"foo.exe") == L"foo");
VerifyTestResult (GetFileBaseName (L".exe") == L".exe");
#if qPlatform_POSIX
VerifyTestResult (GetFileBaseName (L"/tmp/.CPUBurner") == L".CPUBurner");
#elif qPlatform_Windows
VerifyTestResult (GetFileBaseName (L"c:\\tmp\\.CPUBurner") == L".CPUBurner");
#endif
}
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test3_Pathnames_");
Test_ExtractDirAndBaseName_ ();
Test_GetFileBaseName_ ();
}
}
}
namespace {
namespace Test4_MountedFilesystems_ {
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test4_MountedFilesystems_");
for (auto i : IO::FileSystem::GetMountedFilesystems ()) {
DbgTrace (L"fs=%s", Characters::ToString (i).c_str ());
}
}
}
}
namespace {
namespace Test5_DisksPresent_ {
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test5_DisksPresent_");
for (auto i : IO::FileSystem::GetAvailableDisks ()) {
DbgTrace (L"d=%s", Characters::ToString (i).c_str ());
}
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_DirectoryIterator_ ();
Test2_DirectoryIterable_ ();
Test3_Pathnames_::DoTest ();
Test4_MountedFilesystems_::DoTest ();
Test5_DisksPresent_::DoTest ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>fix regression due to filesystem change<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
// TEST Foundation::IO::Other
#include "Stroika/Foundation/StroikaPreComp.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/Containers/Set.h"
#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/Process.h"
#include "Stroika/Foundation/IO/FileSystem/DirectoryIterable.h"
#include "Stroika/Foundation/IO/FileSystem/DirectoryIterator.h"
#include "Stroika/Foundation/IO/FileSystem/FileOutputStream.h"
#include "Stroika/Foundation/IO/FileSystem/FileSystem.h"
#include "Stroika/Foundation/IO/FileSystem/MountedFilesystem.h"
#include "Stroika/Foundation/IO/FileSystem/PathName.h"
#include "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::IO::FileSystem;
namespace {
void Test1_DirectoryIterator_ ()
{
Debug::TraceContextBumper ctx ("Test1_DirectoryIterator_");
{
Debug::TraceContextBumper ctx1 ("simple test");
for (DirectoryIterator i{WellKnownLocations::GetTemporary ()}; not i.Done (); ++i) {
DbgTrace (L"filename = %s", i->c_str ());
}
}
{
Debug::TraceContextBumper ctx1 ("t2");
DirectoryIterator i{WellKnownLocations::GetTemporary ()};
for (DirectoryIterator i2 = i; not i2.Done (); ++i2) {
DbgTrace (L"filename = %s", i2->c_str ());
}
}
}
}
namespace {
void Test2_DirectoryIterable_ ()
{
Debug::TraceContextBumper ctx ("Test2_DirectoryIterable_");
for (filesystem::path filename : DirectoryIterable (WellKnownLocations::GetTemporary ())) {
DbgTrace (L"filename = %s", Characters::ToString (filename).c_str ());
}
{
Debug::TraceContextBumper ctx1 ("test-known-dir");
static const Containers::Set<filesystem::path> kFileNamesForDir_{L"foo.txt", L"bar.png", L"t3.txt", L"blag.nope"};
static const filesystem::path kTestSubDir_ = WellKnownLocations::GetTemporary () / ToPath (L"Regtest-write-files-" + Characters::ToString (Execution::GetCurrentProcessID ()));
IO::FileSystem::Default ().RemoveDirectoryIf (kTestSubDir_, IO::FileSystem::eRemoveAnyContainedFiles);
[[maybe_unused]] auto&& cleanup = Execution::Finally ([]() noexcept {
IgnoreExceptionsForCall (IO::FileSystem::Default ().RemoveDirectoryIf (kTestSubDir_, IO::FileSystem::eRemoveAnyContainedFiles));
});
IO::FileSystem::Directory (kTestSubDir_).AssureExists ();
kFileNamesForDir_.Apply ([](filesystem::path i) { IO::FileSystem::FileOutputStream::New (kTestSubDir_ / i); });
//DbgTrace (L"kTestSubDir_=%s", kTestSubDir_.c_str ());
//DbgTrace (L"kFileNamesForDir_=%s", Characters::ToString (kFileNamesForDir_).c_str ());
//DbgTrace (L"DirectoryIterable (kTestSubDir_)=%s", Characters::ToString (DirectoryIterable (kTestSubDir_)).c_str ());
VerifyTestResult (Containers::Set<filesystem::path>::EqualsComparer{}(kFileNamesForDir_, DirectoryIterable (kTestSubDir_)));
{
Containers::Set<filesystem::path> answers1;
Containers::Set<filesystem::path> answers2;
DirectoryIterable tmp (kTestSubDir_);
Traversal::Iterator<filesystem::path> i2 = tmp.end (); // we had a bug with copying iterator - when refcnt != 1 - hangs - never advances... Windows only
for (Traversal::Iterator<filesystem::path> i = tmp.begin (); i != tmp.end (); ++i) {
answers1 += *i;
i2 = i;
answers2 += *i;
}
VerifyTestResult (kFileNamesForDir_ == answers1);
VerifyTestResult (kFileNamesForDir_ == answers2);
}
}
}
}
namespace {
namespace Test3_Pathnames_ {
void Test_ExtractDirAndBaseName_ ()
{
// Tests from DOCS line in ExtractDirAndBaseName
#if qPlatform_POSIX
VerifyTestResult ((ExtractDirAndBaseName (L"/usr/lib") == pair<String, String>{L"/usr/", L"lib"}));
VerifyTestResult ((ExtractDirAndBaseName (L"/usr/") == pair<String, String>{L"/", L"usr/"}));
VerifyTestResult ((ExtractDirAndBaseName (L"usr") == pair<String, String>{L"./", L"usr"}));
VerifyTestResult ((ExtractDirAndBaseName (L"/") == pair<String, String>{L"/", L""}));
VerifyTestResult ((ExtractDirAndBaseName (L".") == pair<String, String>{L"./", L"."}));
VerifyTestResult ((ExtractDirAndBaseName (L"..") == pair<String, String>{L"./", L".."}));
#elif qPlatform_Windows
VerifyTestResult ((ExtractDirAndBaseName (L"\\usr\\lib") == pair<String, String>{L"\\usr\\", L"lib"}));
VerifyTestResult ((ExtractDirAndBaseName (L"\\usr\\") == pair<String, String>{L"\\", L"usr\\"}));
VerifyTestResult ((ExtractDirAndBaseName (L"usr") == pair<String, String>{L".\\", L"usr"}));
VerifyTestResult ((ExtractDirAndBaseName (L"\\") == pair<String, String>{L"\\", L""}));
VerifyTestResult ((ExtractDirAndBaseName (L".") == pair<String, String>{L".\\", L"."}));
VerifyTestResult ((ExtractDirAndBaseName (L"..") == pair<String, String>{L".\\", L".."}));
VerifyTestResult ((ExtractDirAndBaseName (L"c:\\h\\m.t") == pair<String, String>{L"c:\\h\\", L"m.t"}));
#endif
}
void Test_GetFileBaseName_ ()
{
VerifyTestResult (GetFileBaseName (L"foo") == L"foo");
VerifyTestResult (GetFileBaseName (L"foo.cpp") == L"foo");
VerifyTestResult (GetFileBaseName (L"foo.exe") == L"foo");
VerifyTestResult (GetFileBaseName (L".exe") == L".exe");
#if qPlatform_POSIX
VerifyTestResult (GetFileBaseName (L"/tmp/.CPUBurner") == L".CPUBurner");
#elif qPlatform_Windows
VerifyTestResult (GetFileBaseName (L"c:\\tmp\\.CPUBurner") == L".CPUBurner");
#endif
}
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test3_Pathnames_");
Test_ExtractDirAndBaseName_ ();
Test_GetFileBaseName_ ();
}
}
}
namespace {
namespace Test4_MountedFilesystems_ {
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test4_MountedFilesystems_");
for (auto i : IO::FileSystem::GetMountedFilesystems ()) {
DbgTrace (L"fs=%s", Characters::ToString (i).c_str ());
}
}
}
}
namespace {
namespace Test5_DisksPresent_ {
void DoTest ()
{
Debug::TraceContextBumper ctx ("Test5_DisksPresent_");
for (auto i : IO::FileSystem::GetAvailableDisks ()) {
DbgTrace (L"d=%s", Characters::ToString (i).c_str ());
}
}
}
}
namespace {
void DoRegressionTests_ ()
{
Test1_DirectoryIterator_ ();
Test2_DirectoryIterable_ ();
Test3_Pathnames_::DoTest ();
Test4_MountedFilesystems_::DoTest ();
Test5_DisksPresent_::DoTest ();
}
}
int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[])
{
Stroika::TestHarness::Setup ();
return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TournamentsAmbiguityNumber {
int scrutinizeTable(vector <string> t) {
const int q = sz(t);
int c = 0;
fr(i, q) for (int j = i+1; j < q; ++j) for (int k = j+1; k < q; ++k) {
if (t[i][j] == '1' && t[j][k] == '1' && t[k][i] == '1') {
++c;
}
}
return c;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TournamentsAmbiguityNumber *obj;
int answer;
obj = new TournamentsAmbiguityNumber();
clock_t startTime = clock();
answer = obj->scrutinizeTable(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"-10","0-1","10-"};
p1 = 3;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"----","----","----","----"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"-1","0-"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"--1-10-1---1--1-00","--0110000--0---10-","01--00000100-00011","-0---0010-11110100","001--01-00-0001-1-","11111--100--1-1-01","-1110--00110-11-01","0110-01--100110-10","-111111---01--0-01","--0-1100----10011-","--10--011--1--101-","01101-110-0--1-0-1","---010-0-0---00-11","--101-00-1-01-0-0-","0-110001110-11-110","-010-----011--0--0","11010110100-010--0","1-01-0010--00-111-"};
p1 = 198;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>TournamentsAmbiguityNumber<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct TournamentsAmbiguityNumber {
int scrutinizeTable(vector <string> t) {
const int q = sz(t);
int c = 0;
fr(i, q) fr(j, q) fr(k, q) {
if (t[i][j] == '1' && t[j][k] == '1' && t[k][i] == '1') {
++c;
}
}
return c;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, int p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
TournamentsAmbiguityNumber *obj;
int answer;
obj = new TournamentsAmbiguityNumber();
clock_t startTime = clock();
answer = obj->scrutinizeTable(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p1 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
vector <string> p0;
int p1;
// ----- test 0 -----
disabled = false;
p0 = {"-10","0-1","10-"};
p1 = 3;
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = {"----","----","----","----"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = {"-1","0-"};
p1 = 0;
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = {"--1-10-1---1--1-00","--0110000--0---10-","01--00000100-00011","-0---0010-11110100","001--01-00-0001-1-","11111--100--1-1-01","-1110--00110-11-01","0110-01--100110-10","-111111---01--0-01","--0-1100----10011-","--10--011--1--101-","01101-110-0--1-0-1","---010-0-0---00-11","--101-00-1-01-0-0-","0-110001110-11-110","-010-----011--0--0","11010110100-010--0","1-01-0010--00-111-"};
p1 = 198;
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|> |
<commit_before>
// This file is part of lipstick, a QML desktop library
//
// 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.
//
// This code 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.
//
// Copyright (c) 2011, Robin Burchell
// Copyright (c) 2012, Timur Kristóf <venemo@fedoraproject.org>
#include <QDebug>
#include <QProcess>
#include <QFile>
#include <QDir>
#include <QSettings>
#include <mlite/mdesktopentry.h>
#ifdef HAS_CONTENTACTION
#include <contentaction.h>
#endif
#include "launcheritem.h"
static QString findIconHelper(const QString &pathName, const QString &icon)
{
QStringList extensions;
extensions << "";
extensions << ".png";
extensions << ".svg";
// qDebug() << "Trying " << pathName << " for " << icon;
foreach (const QString &extension, extensions) {
if (QFile::exists(pathName + QDir::separator() + icon + extension))
return pathName + QDir::separator() + icon + extension;
}
QStringList entryList = QDir(pathName).entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot);
foreach (const QString &dir, entryList) {
QString retval = findIconHelper(QDir(pathName).absoluteFilePath(dir), icon);
if (!retval.isNull())
return retval;
}
// all else failed
return QString();
}
static QString getIconPath(const QString &name)
{
if (QFile::exists(name)) {
// fast path: file given
return name;
}
QSettings settings("MeeGo", "IconCache");
QString cachedPath = settings.value(name).toString();
if (!QFile::exists(cachedPath)) {
qDebug() << Q_FUNC_INFO << "Negative cache hit for " << name << " to " << cachedPath;
} else {
return cachedPath;
}
QStringList themes = QDir("/usr/share/themes").entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot);
if (themes.isEmpty())
return QString();
// TODO: look up active theme in gconf and set it to the first search path, don't hardcode it.
// TODO: would be nice to investigate if our fallback behaviour is actually correct, too, but meh.
if (themes.contains("n900de") &&
themes.at(0) != "n900de") {
themes.removeAll("n900de");
themes.insert(0, "n900de");
}
foreach (const QString &theme, themes) {
QString retval = findIconHelper("/usr/share/themes/" + theme, name);
if (!retval.isNull()) {
settings.setValue(name, retval);
return retval;
}
}
// they also seem to get plonked here
QString retval = findIconHelper("/usr/share/pixmaps/", name);
if (!retval.isNull()) {
settings.setValue(name, retval);
return retval;
}
// I hate all application developers
retval = findIconHelper("/usr/share/icons/hicolor/64x64/", name);
if (!retval.isNull()) {
settings.setValue(name, retval);
return retval;
}
return QString();
}
LauncherItem::LauncherItem(const QString &path, QObject *parent)
: QObject(parent),
_desktopEntry(new MDesktopEntry(path))
{
emit this->itemChanged();
}
LauncherItem::~LauncherItem()
{
delete _desktopEntry;
}
QString LauncherItem::filePath() const
{
return _desktopEntry->fileName();
}
QString LauncherItem::title() const
{
return _desktopEntry->name();
}
QString LauncherItem::entryType() const
{
return _desktopEntry->type();
}
QString LauncherItem::iconFilePath() const
{
return "file://" + getIconPath(_desktopEntry->icon());
}
QStringList LauncherItem::desktopCategories() const
{
return _desktopEntry->categories();
}
bool LauncherItem::shouldDisplay() const
{
return !_desktopEntry->noDisplay();
}
bool LauncherItem::isValid() const
{
return _desktopEntry->isValid();
}
void LauncherItem::launchApplication() const
{
#if defined(HAVE_CONTENTACTION)
ContentAction::Action action = ContentAction::Action::launcherAction(m_entry, QStringList());
action.trigger();
#else
// Get the command text from the desktop entry
QString commandText = _desktopEntry->exec();
// Take care of the freedesktop standards things
commandText.replace(QRegExp("%k"), filePath());
commandText.replace(QRegExp("%c"), _desktopEntry->name());
commandText.remove(QRegExp("%[fFuU]"));
if (!_desktopEntry->icon().isEmpty())
commandText.replace(QRegExp("%i"), QString("--icon ") + _desktopEntry->icon());
// DETAILS: http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
// DETAILS: http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
// Launch the application
QProcess::startDetached(commandText);
#endif
}
<commit_msg>Icon path will not be returned unless it really exists.<commit_after>
// This file is part of lipstick, a QML desktop library
//
// 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.
//
// This code 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.
//
// Copyright (c) 2011, Robin Burchell
// Copyright (c) 2012, Timur Kristóf <venemo@fedoraproject.org>
#include <QDebug>
#include <QProcess>
#include <QFile>
#include <QDir>
#include <QSettings>
#include <mlite/mdesktopentry.h>
#ifdef HAS_CONTENTACTION
#include <contentaction.h>
#endif
#include "launcheritem.h"
static QString findIconHelper(const QString &pathName, const QString &icon)
{
QStringList extensions;
extensions << "";
extensions << ".png";
extensions << ".svg";
// qDebug() << "Trying " << pathName << " for " << icon;
foreach (const QString &extension, extensions) {
if (QFile::exists(pathName + QDir::separator() + icon + extension))
return pathName + QDir::separator() + icon + extension;
}
QStringList entryList = QDir(pathName).entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot);
foreach (const QString &dir, entryList) {
QString retval = findIconHelper(QDir(pathName).absoluteFilePath(dir), icon);
if (!retval.isNull())
return retval;
}
// all else failed
return QString();
}
static QString getIconPath(const QString &name)
{
if (QFile::exists(name)) {
// fast path: file given
return name;
}
QSettings settings("MeeGo", "IconCache");
QString cachedPath = settings.value(name).toString();
if (!QFile::exists(cachedPath))
{
qDebug() << Q_FUNC_INFO << "Negative cache hit for " << name << " to " << cachedPath;
}
else
{
return cachedPath;
}
QStringList themes = QDir("/usr/share/themes").entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot);
if (!themes.isEmpty())
{
// TODO: look up active theme in gconf and set it to the first search path, don't hardcode it.
// TODO: would be nice to investigate if our fallback behaviour is actually correct, too, but meh.
if (themes.contains("n900de") && themes.at(0) != "n900de")
{
themes.removeAll("n900de");
themes.insert(0, "n900de");
}
foreach (const QString &theme, themes)
{
QString retval = findIconHelper("/usr/share/themes/" + theme, name);
if (!retval.isNull())
{
if (QFile::exists(retval))
{
settings.setValue(name, retval);
return retval;
}
}
}
}
// they also seem to get plonked here
QString retval = findIconHelper("/usr/share/pixmaps/", name);
if (!retval.isNull())
{
if (QFile::exists(retval))
{
settings.setValue(name, retval);
return retval;
}
}
// I hate all application developers
retval = findIconHelper("/usr/share/icons/hicolor/64x64/", name);
if (!retval.isNull())
{
if (QFile::exists(retval))
{
settings.setValue(name, retval);
return retval;
}
}
return QString();
}
LauncherItem::LauncherItem(const QString &path, QObject *parent)
: QObject(parent),
_desktopEntry(new MDesktopEntry(path))
{
emit this->itemChanged();
}
LauncherItem::~LauncherItem()
{
delete _desktopEntry;
}
QString LauncherItem::filePath() const
{
return _desktopEntry->fileName();
}
QString LauncherItem::title() const
{
return _desktopEntry->name();
}
QString LauncherItem::entryType() const
{
return _desktopEntry->type();
}
QString LauncherItem::iconFilePath() const
{
return "file://" + getIconPath(_desktopEntry->icon());
}
QStringList LauncherItem::desktopCategories() const
{
return _desktopEntry->categories();
}
bool LauncherItem::shouldDisplay() const
{
return !_desktopEntry->noDisplay();
}
bool LauncherItem::isValid() const
{
return _desktopEntry->isValid();
}
void LauncherItem::launchApplication() const
{
#if defined(HAVE_CONTENTACTION)
ContentAction::Action action = ContentAction::Action::launcherAction(m_entry, QStringList());
action.trigger();
#else
// Get the command text from the desktop entry
QString commandText = _desktopEntry->exec();
// Take care of the freedesktop standards things
commandText.replace(QRegExp("%k"), filePath());
commandText.replace(QRegExp("%c"), _desktopEntry->name());
commandText.remove(QRegExp("%[fFuU]"));
if (!_desktopEntry->icon().isEmpty())
commandText.replace(QRegExp("%i"), QString("--icon ") + _desktopEntry->icon());
// DETAILS: http://standards.freedesktop.org/desktop-entry-spec/latest/index.html
// DETAILS: http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
// Launch the application
QProcess::startDetached(commandText);
#endif
}
<|endoftext|> |
<commit_before>// Modified from chromium/src/webkit/glue/gl_bindings_skia_cmd_buffer.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gl/GrGLInterface.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
const GrGLInterface* GrGLCreateNativeInterface() {
static SkAutoTUnref<GrGLInterface> glInterface;
if (!glInterface.get()) {
GrGLInterface* interface = new GrGLInterface;
glInterface.reset(interface);
interface->fBindingsExported = kES2_GrGLBinding;
interface->fActiveTexture = glActiveTexture;
interface->fAttachShader = glAttachShader;
interface->fBindAttribLocation = glBindAttribLocation;
interface->fBindBuffer = glBindBuffer;
interface->fBindTexture = glBindTexture;
interface->fBlendColor = glBlendColor;
interface->fBlendFunc = glBlendFunc;
interface->fBufferData = glBufferData;
interface->fBufferSubData = glBufferSubData;
interface->fClear = glClear;
interface->fClearColor = glClearColor;
interface->fClearStencil = glClearStencil;
interface->fColorMask = glColorMask;
interface->fCompileShader = glCompileShader;
interface->fCompressedTexImage2D = glCompressedTexImage2D;
interface->fCreateProgram = glCreateProgram;
interface->fCreateShader = glCreateShader;
interface->fCullFace = glCullFace;
interface->fDeleteBuffers = glDeleteBuffers;
interface->fDeleteProgram = glDeleteProgram;
interface->fDeleteShader = glDeleteShader;
interface->fDeleteTextures = glDeleteTextures;
interface->fDepthMask = glDepthMask;
interface->fDisable = glDisable;
interface->fDisableVertexAttribArray = glDisableVertexAttribArray;
interface->fDrawArrays = glDrawArrays;
interface->fDrawElements = glDrawElements;
interface->fEnable = glEnable;
interface->fEnableVertexAttribArray = glEnableVertexAttribArray;
interface->fFinish = glFinish;
interface->fFlush = glFlush;
interface->fFrontFace = glFrontFace;
interface->fGenBuffers = glGenBuffers;
interface->fGenTextures = glGenTextures;
interface->fGetBufferParameteriv = glGetBufferParameteriv;
interface->fGetError = glGetError;
interface->fGetIntegerv = glGetIntegerv;
interface->fGetProgramInfoLog = glGetProgramInfoLog;
interface->fGetProgramiv = glGetProgramiv;
interface->fGetShaderInfoLog = glGetShaderInfoLog;
interface->fGetShaderiv = glGetShaderiv;
interface->fGetString = glGetString;
interface->fGetUniformLocation = glGetUniformLocation;
interface->fLineWidth = glLineWidth;
interface->fLinkProgram = glLinkProgram;
interface->fPixelStorei = glPixelStorei;
interface->fReadPixels = glReadPixels;
interface->fScissor = glScissor;
interface->fShaderSource = glShaderSource;
interface->fStencilFunc = glStencilFunc;
interface->fStencilFuncSeparate = glStencilFuncSeparate;
interface->fStencilMask = glStencilMask;
interface->fStencilMaskSeparate = glStencilMaskSeparate;
interface->fStencilOp = glStencilOp;
interface->fStencilOpSeparate = glStencilOpSeparate;
interface->fTexImage2D = glTexImage2D;
interface->fTexParameteri = glTexParameteri;
interface->fTexParameteriv = glTexParameteriv;
interface->fTexSubImage2D = glTexSubImage2D;
#if GL_ARB_texture_storage
interface->fTexStorage2D = glTexStorage2D;
#elif GL_EXT_texture_storage
interface->fTexStorage2D = glTexStorage2DEXT;
#endif
interface->fUniform1f = glUniform1f;
interface->fUniform1i = glUniform1i;
interface->fUniform1fv = glUniform1fv;
interface->fUniform1iv = glUniform1iv;
interface->fUniform2f = glUniform2f;
interface->fUniform2i = glUniform2i;
interface->fUniform2fv = glUniform2fv;
interface->fUniform2iv = glUniform2iv;
interface->fUniform3f = glUniform3f;
interface->fUniform3i = glUniform3i;
interface->fUniform3fv = glUniform3fv;
interface->fUniform3iv = glUniform3iv;
interface->fUniform4f = glUniform4f;
interface->fUniform4i = glUniform4i;
interface->fUniform4fv = glUniform4fv;
interface->fUniform4iv = glUniform4iv;
interface->fUniformMatrix2fv = glUniformMatrix2fv;
interface->fUniformMatrix3fv = glUniformMatrix3fv;
interface->fUniformMatrix4fv = glUniformMatrix4fv;
interface->fUseProgram = glUseProgram;
interface->fVertexAttrib4fv = glVertexAttrib4fv;
interface->fVertexAttribPointer = glVertexAttribPointer;
interface->fViewport = glViewport;
interface->fBindFramebuffer = glBindFramebuffer;
interface->fBindRenderbuffer = glBindRenderbuffer;
interface->fCheckFramebufferStatus = glCheckFramebufferStatus;
interface->fDeleteFramebuffers = glDeleteFramebuffers;
interface->fDeleteRenderbuffers = glDeleteRenderbuffers;
interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
interface->fFramebufferTexture2D = glFramebufferTexture2D;
interface->fGenFramebuffers = glGenFramebuffers;
interface->fGenRenderbuffers = glGenRenderbuffers;
interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
interface->fRenderbufferStorage = glRenderbufferStorage;
#if GL_OES_mapbuffer
interface->fMapBuffer = glMapBufferOES;
interface->fUnmapBuffer = glUnmapBufferOES;
#endif
}
glInterface.get()->ref();
return glInterface.get();
}
<commit_msg>Fix GrGLCreateNativeInterface_android Review URL: https://codereview.appspot.com/6503101<commit_after>// Modified from chromium/src/webkit/glue/gl_bindings_skia_cmd_buffer.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gl/GrGLInterface.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <EGL/egl.h>
const GrGLInterface* GrGLCreateNativeInterface() {
static SkAutoTUnref<GrGLInterface> glInterface;
if (!glInterface.get()) {
GrGLInterface* interface = new GrGLInterface;
glInterface.reset(interface);
interface->fBindingsExported = kES2_GrGLBinding;
interface->fActiveTexture = glActiveTexture;
interface->fAttachShader = glAttachShader;
interface->fBindAttribLocation = glBindAttribLocation;
interface->fBindBuffer = glBindBuffer;
interface->fBindTexture = glBindTexture;
interface->fBlendColor = glBlendColor;
interface->fBlendFunc = glBlendFunc;
interface->fBufferData = glBufferData;
interface->fBufferSubData = glBufferSubData;
interface->fClear = glClear;
interface->fClearColor = glClearColor;
interface->fClearStencil = glClearStencil;
interface->fColorMask = glColorMask;
interface->fCompileShader = glCompileShader;
interface->fCompressedTexImage2D = glCompressedTexImage2D;
interface->fCreateProgram = glCreateProgram;
interface->fCreateShader = glCreateShader;
interface->fCullFace = glCullFace;
interface->fDeleteBuffers = glDeleteBuffers;
interface->fDeleteProgram = glDeleteProgram;
interface->fDeleteShader = glDeleteShader;
interface->fDeleteTextures = glDeleteTextures;
interface->fDepthMask = glDepthMask;
interface->fDisable = glDisable;
interface->fDisableVertexAttribArray = glDisableVertexAttribArray;
interface->fDrawArrays = glDrawArrays;
interface->fDrawElements = glDrawElements;
interface->fEnable = glEnable;
interface->fEnableVertexAttribArray = glEnableVertexAttribArray;
interface->fFinish = glFinish;
interface->fFlush = glFlush;
interface->fFrontFace = glFrontFace;
interface->fGenBuffers = glGenBuffers;
interface->fGenTextures = glGenTextures;
interface->fGetBufferParameteriv = glGetBufferParameteriv;
interface->fGetError = glGetError;
interface->fGetIntegerv = glGetIntegerv;
interface->fGetProgramInfoLog = glGetProgramInfoLog;
interface->fGetProgramiv = glGetProgramiv;
interface->fGetShaderInfoLog = glGetShaderInfoLog;
interface->fGetShaderiv = glGetShaderiv;
interface->fGetString = glGetString;
interface->fGetUniformLocation = glGetUniformLocation;
interface->fLineWidth = glLineWidth;
interface->fLinkProgram = glLinkProgram;
interface->fPixelStorei = glPixelStorei;
interface->fReadPixels = glReadPixels;
interface->fScissor = glScissor;
interface->fShaderSource = glShaderSource;
interface->fStencilFunc = glStencilFunc;
interface->fStencilFuncSeparate = glStencilFuncSeparate;
interface->fStencilMask = glStencilMask;
interface->fStencilMaskSeparate = glStencilMaskSeparate;
interface->fStencilOp = glStencilOp;
interface->fStencilOpSeparate = glStencilOpSeparate;
interface->fTexImage2D = glTexImage2D;
interface->fTexParameteri = glTexParameteri;
interface->fTexParameteriv = glTexParameteriv;
interface->fTexSubImage2D = glTexSubImage2D;
#if GL_ARB_texture_storage
interface->fTexStorage2D = glTexStorage2D;
#elif GL_EXT_texture_storage
interface->fTexStorage2D = glTexStorage2DEXT;
#else
interface->fTexStorage2D = (GrGLTexStorage2DProc) eglGetProcAddress("glTexStorage2DEXT");
#endif
interface->fUniform1f = glUniform1f;
interface->fUniform1i = glUniform1i;
interface->fUniform1fv = glUniform1fv;
interface->fUniform1iv = glUniform1iv;
interface->fUniform2f = glUniform2f;
interface->fUniform2i = glUniform2i;
interface->fUniform2fv = glUniform2fv;
interface->fUniform2iv = glUniform2iv;
interface->fUniform3f = glUniform3f;
interface->fUniform3i = glUniform3i;
interface->fUniform3fv = glUniform3fv;
interface->fUniform3iv = glUniform3iv;
interface->fUniform4f = glUniform4f;
interface->fUniform4i = glUniform4i;
interface->fUniform4fv = glUniform4fv;
interface->fUniform4iv = glUniform4iv;
interface->fUniformMatrix2fv = glUniformMatrix2fv;
interface->fUniformMatrix3fv = glUniformMatrix3fv;
interface->fUniformMatrix4fv = glUniformMatrix4fv;
interface->fUseProgram = glUseProgram;
interface->fVertexAttrib4fv = glVertexAttrib4fv;
interface->fVertexAttribPointer = glVertexAttribPointer;
interface->fViewport = glViewport;
interface->fBindFramebuffer = glBindFramebuffer;
interface->fBindRenderbuffer = glBindRenderbuffer;
interface->fCheckFramebufferStatus = glCheckFramebufferStatus;
interface->fDeleteFramebuffers = glDeleteFramebuffers;
interface->fDeleteRenderbuffers = glDeleteRenderbuffers;
interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer;
interface->fFramebufferTexture2D = glFramebufferTexture2D;
interface->fGenFramebuffers = glGenFramebuffers;
interface->fGenRenderbuffers = glGenRenderbuffers;
interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv;
interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv;
interface->fRenderbufferStorage = glRenderbufferStorage;
#if GL_OES_mapbuffer
interface->fMapBuffer = glMapBufferOES;
interface->fUnmapBuffer = glUnmapBufferOES;
#else
interface->fMapBuffer = (GrGLMapBufferProc) eglGetProcAddress("glMapBufferOES");
interface->fUnmapBuffer = (GrGLUnmapBufferProc) eglGetProcAddress("glUnmapBufferOES");
#endif
}
glInterface.get()->ref();
return glInterface.get();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "common/common.h"
#include <assert.h>
#include <time.h>
#include <sys/timeb.h>
#include "store/api/iterator.h"
#include "store/api/temp_seq.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "system/globalenv.h"
#include "context/dynamic_context.h"
#include "context/static_context.h"
#include "compiler/expression/var_expr.h"
#include "types/root_typemanager.h"
#include "runtime/api/plan_wrapper.h"
#include "zorbautils/strutil.h"
#include "indexing/value_index.h"
using namespace std;
namespace zorba {
bool dynamic_context::static_init = false;
string dynamic_context::var_key (const void *var)
{
if (var == NULL) return "";
const var_expr *ve = static_cast<const var_expr *> (var);
return xqpString::concat(to_string(var), ":", ve->get_varname ()->getStringValue ());
}
xqp_string dynamic_context::expand_varname(static_context *sctx, xqp_string qname)
{
if(!sctx)
{
///actually the whole static context is missing
ZORBA_ERROR_PARAM( XPST0001, "entire static context", "");
return (const char*)NULL;
}
void *var = static_cast<void *> (sctx->lookup_var (qname));
return var_key (var);
}
void dynamic_context::init()
{
if (!dynamic_context::static_init) {
dynamic_context::static_init = true;
}
}
dynamic_context::dynamic_context(dynamic_context *parent)
{
this->parent = parent;
if(!parent)
{
#if defined (WIN32)
struct _timeb timebuffer;
_ftime_s( &timebuffer );
struct ::tm gmtm;
localtime_s(&gmtm, &timebuffer.time); //thread safe localtime on Windows
#else
struct timeb timebuffer;
ftime( &timebuffer );
struct ::tm gmtm;
localtime_r(&timebuffer.time, &gmtm); //thread safe localtime on Linux
#endif
set_implicit_timezone( -timebuffer.timezone * 60 );//in seconds
GENV_ITEMFACTORY->createDateTime(current_date_time_item, gmtm.tm_year + 1900, gmtm.tm_mon + 1, gmtm.tm_mday,
gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec + timebuffer.millitm/1000.0, implicit_timezone/3600);
ctxt_position = 0;
}
else
{
current_date_time_item = parent->current_date_time_item;
implicit_timezone = parent->implicit_timezone;
default_collection_uri = parent->default_collection_uri;
ctxt_item = parent->ctxt_item;
ctxt_position = parent->ctxt_position;
}
}
void dynamic_context::destroy_dctx_value (const dctx_value_t* val) {
switch (val->type) {
case dynamic_context::dctx_value_t::no_val:
break;
case dynamic_context::dctx_value_t::var_iterator_val:
RCHelper::removeReference (val->val.var_iterator);
break;
case dynamic_context::dctx_value_t::temp_seq_val:
RCHelper::removeReference (val->val.temp_seq);
break;
default:
ZORBA_ASSERT (false);
}
}
dynamic_context::~dynamic_context()
{
///free the pointers from ctx_value_t from keymap
checked_vector<hashmap<dctx_value_t>::entry>::const_iterator it;
const char *keybuff;//[50];
for(it = keymap.begin(); it != keymap.end(); it++)
{
///it is an entry
keybuff = (*it).key.c_str();
if(strncmp(keybuff, "var:", 4) == 0)
{
destroy_dctx_value (&(*it).val);
}
}
}
void dynamic_context::set_context_item(
const store::Item_t& context_item,
unsigned long position)
{
this->ctxt_item = context_item;
this->ctxt_position = position;
}
store::Item_t dynamic_context::context_item() const
{
return ctxt_item;
}
unsigned long dynamic_context::context_position()
{
return ctxt_position;
}
xqtref_t dynamic_context::context_item_type() const
{
return GENV_TYPESYSTEM.ITEM_TYPE_STAR;
}
void dynamic_context::set_context_item_type(xqtref_t v)
{
}
void dynamic_context::set_current_date_time( const store::Item_t& aDateTimeItem )
{
this->current_date_time_item = aDateTimeItem;
}
store::Item_t dynamic_context::get_current_date_time()
{
return current_date_time_item;
}
void dynamic_context::set_implicit_timezone(int tzone_seconds)
{
this->implicit_timezone = tzone_seconds;
}
int dynamic_context::get_implicit_timezone()
{
return implicit_timezone;
}
/*
var_name is expanded name localname:nsURI
constructed by static_context::qname_internal_key( .. )
*/
void dynamic_context::set_variable(
const std::string& var_name,
store::Iterator_t var_iterator)
{
if (var_name.empty()) return;
dctx_value_t v;
string key = "var:" + var_name;
hashmap<dctx_value_t> *map;
if (! context_value (key, v, &map))
ZORBA_ASSERT (false);
var_iterator->open ();
store::TempSeq_t seq = GENV_STORE.createTempSeq (var_iterator.getp());
var_iterator->close ();
RCHelper::addReference (seq);
v.type = dynamic_context::dctx_value_t::temp_seq_val;
v.in_progress = false;
v.val.temp_seq = seq.getp();
map->put (key, v);
}
void dynamic_context::declare_variable(const std::string& var_name)
{
if (var_name.empty()) return;
dctx_value_t v;
string key = "var:" + var_name;
if (keymap.get (key, v))
destroy_dctx_value (&v);
v.type = dynamic_context::dctx_value_t::no_val;
v.in_progress = true;
keymap.put (key, v);
}
void dynamic_context::add_variable(
const std::string& varname,
store::Iterator_t var_iterator)
{
declare_variable (varname);
set_variable (varname, var_iterator);
}
store::Iterator_t dynamic_context::get_variable(const store::Item_t& varname)
{
return lookup_var_iter("var:" + varname->getStringValue()->str());
}
store::Iterator_t dynamic_context::lookup_var_iter(const std::string& key)
{
dctx_value_t val = {dctx_value_t::no_val, false, {0} };
if(!keymap.get(key, val))
{
if(parent)
return parent->lookup_var_iter(key);
else
return NULL;///variable not found
}
if (val.in_progress)
ZORBA_ERROR (XQST0054);
assert (val.type == dynamic_context::dctx_value_t::temp_seq_val);
return val.val.temp_seq->getIterator ();
}
store::Item_t dynamic_context::get_default_collection()
{
return default_collection_uri;
}
void dynamic_context::set_default_collection(const store::Item_t& default_collection_uri)
{
this->default_collection_uri = default_collection_uri;
}
void dynamic_context::bind_index(
const std::string& indexUri,
store::Index* index)
{
if (val_idx_ins_session_map.find(indexUri) != val_idx_ins_session_map.end()) {
ZORBA_ERROR_PARAM(XQP0034_INDEX_ALREADY_EXISTS, indexUri.c_str(), "");
}
std::pair<store::Index_t, ValueIndexInsertSession_t> v;
v.first = index;
v.second = NULL;
val_idx_ins_session_map[indexUri] = v;
}
void dynamic_context::unbind_index(
const std::string& indexUri)
{
IndexMap::iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
val_idx_ins_session_map.erase(i);
}
else if (parent != NULL)
{
return parent->unbind_index(indexUri);
}
else
{
ZORBA_ERROR_PARAM(XQP0033_INDEX_DOES_NOT_EXIST, indexUri.c_str(), "");
}
}
store::Index* dynamic_context::lookup_index(const std::string& indexUri) const
{
IndexMap::const_iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
return i->second.first.getp();
}
else if (parent != NULL)
{
return parent->lookup_index(indexUri);
}
else
{
ZORBA_ERROR_PARAM(XQP0033_INDEX_DOES_NOT_EXIST, indexUri.c_str(), "");
}
}
ValueIndexInsertSession* dynamic_context::get_index_insert_session(
const std::string& indexUri) const
{
IndexMap::const_iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
return i->second.second.getp();
}
else if (parent != NULL)
{
return parent->get_index_insert_session(indexUri);
}
else
{
ZORBA_ASSERT(false);
}
}
void dynamic_context::set_index_insert_session (
const std::string& indexUri,
ValueIndexInsertSession* s)
{
IndexMap::iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
i->second.second = s;
}
else if (parent != NULL)
{
parent->set_index_insert_session(indexUri, s);
}
else
{
ZORBA_ASSERT(false);
}
}
} /* namespace zorba */
<commit_msg>added daylight saving time to current date time in the dynamic context<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "common/common.h"
#include <assert.h>
#include <time.h>
#include <sys/timeb.h>
#include "store/api/iterator.h"
#include "store/api/temp_seq.h"
#include "store/api/item_factory.h"
#include "store/api/store.h"
#include "system/globalenv.h"
#include "context/dynamic_context.h"
#include "context/static_context.h"
#include "compiler/expression/var_expr.h"
#include "types/root_typemanager.h"
#include "runtime/api/plan_wrapper.h"
#include "zorbautils/strutil.h"
#include "indexing/value_index.h"
using namespace std;
namespace zorba {
bool dynamic_context::static_init = false;
string dynamic_context::var_key (const void *var)
{
if (var == NULL) return "";
const var_expr *ve = static_cast<const var_expr *> (var);
return xqpString::concat(to_string(var), ":", ve->get_varname ()->getStringValue ());
}
xqp_string dynamic_context::expand_varname(static_context *sctx, xqp_string qname)
{
if(!sctx)
{
///actually the whole static context is missing
ZORBA_ERROR_PARAM( XPST0001, "entire static context", "");
return (const char*)NULL;
}
void *var = static_cast<void *> (sctx->lookup_var (qname));
return var_key (var);
}
void dynamic_context::init()
{
if (!dynamic_context::static_init) {
dynamic_context::static_init = true;
}
}
dynamic_context::dynamic_context(dynamic_context *parent)
{
this->parent = parent;
if(!parent)
{
#if defined (WIN32)
struct _timeb timebuffer;
_ftime_s( &timebuffer );
struct ::tm gmtm;
localtime_s(&gmtm, &timebuffer.time); //thread safe localtime on Windows
#else
struct timeb timebuffer;
ftime( &timebuffer );
struct ::tm gmtm;
localtime_r(&timebuffer.time, &gmtm); //thread safe localtime on Linux
#endif
{
int lSummerTimeShift = 0;
if (gmtm.tm_isdst != 0) {
lSummerTimeShift = 3600;
}
set_implicit_timezone( -timebuffer.timezone * 60 + lSummerTimeShift );//in seconds
}
GENV_ITEMFACTORY->createDateTime(current_date_time_item, gmtm.tm_year + 1900, gmtm.tm_mon + 1, gmtm.tm_mday,
gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec + timebuffer.millitm/1000.0, implicit_timezone/3600);
ctxt_position = 0;
}
else
{
current_date_time_item = parent->current_date_time_item;
implicit_timezone = parent->implicit_timezone;
default_collection_uri = parent->default_collection_uri;
ctxt_item = parent->ctxt_item;
ctxt_position = parent->ctxt_position;
}
}
void dynamic_context::destroy_dctx_value (const dctx_value_t* val) {
switch (val->type) {
case dynamic_context::dctx_value_t::no_val:
break;
case dynamic_context::dctx_value_t::var_iterator_val:
RCHelper::removeReference (val->val.var_iterator);
break;
case dynamic_context::dctx_value_t::temp_seq_val:
RCHelper::removeReference (val->val.temp_seq);
break;
default:
ZORBA_ASSERT (false);
}
}
dynamic_context::~dynamic_context()
{
///free the pointers from ctx_value_t from keymap
checked_vector<hashmap<dctx_value_t>::entry>::const_iterator it;
const char *keybuff;//[50];
for(it = keymap.begin(); it != keymap.end(); it++)
{
///it is an entry
keybuff = (*it).key.c_str();
if(strncmp(keybuff, "var:", 4) == 0)
{
destroy_dctx_value (&(*it).val);
}
}
}
void dynamic_context::set_context_item(
const store::Item_t& context_item,
unsigned long position)
{
this->ctxt_item = context_item;
this->ctxt_position = position;
}
store::Item_t dynamic_context::context_item() const
{
return ctxt_item;
}
unsigned long dynamic_context::context_position()
{
return ctxt_position;
}
xqtref_t dynamic_context::context_item_type() const
{
return GENV_TYPESYSTEM.ITEM_TYPE_STAR;
}
void dynamic_context::set_context_item_type(xqtref_t v)
{
}
void dynamic_context::set_current_date_time( const store::Item_t& aDateTimeItem )
{
this->current_date_time_item = aDateTimeItem;
}
store::Item_t dynamic_context::get_current_date_time()
{
return current_date_time_item;
}
void dynamic_context::set_implicit_timezone(int tzone_seconds)
{
this->implicit_timezone = tzone_seconds;
}
int dynamic_context::get_implicit_timezone()
{
return implicit_timezone;
}
/*
var_name is expanded name localname:nsURI
constructed by static_context::qname_internal_key( .. )
*/
void dynamic_context::set_variable(
const std::string& var_name,
store::Iterator_t var_iterator)
{
if (var_name.empty()) return;
dctx_value_t v;
string key = "var:" + var_name;
hashmap<dctx_value_t> *map;
if (! context_value (key, v, &map))
ZORBA_ASSERT (false);
var_iterator->open ();
store::TempSeq_t seq = GENV_STORE.createTempSeq (var_iterator.getp());
var_iterator->close ();
RCHelper::addReference (seq);
v.type = dynamic_context::dctx_value_t::temp_seq_val;
v.in_progress = false;
v.val.temp_seq = seq.getp();
map->put (key, v);
}
void dynamic_context::declare_variable(const std::string& var_name)
{
if (var_name.empty()) return;
dctx_value_t v;
string key = "var:" + var_name;
if (keymap.get (key, v))
destroy_dctx_value (&v);
v.type = dynamic_context::dctx_value_t::no_val;
v.in_progress = true;
keymap.put (key, v);
}
void dynamic_context::add_variable(
const std::string& varname,
store::Iterator_t var_iterator)
{
declare_variable (varname);
set_variable (varname, var_iterator);
}
store::Iterator_t dynamic_context::get_variable(const store::Item_t& varname)
{
return lookup_var_iter("var:" + varname->getStringValue()->str());
}
store::Iterator_t dynamic_context::lookup_var_iter(const std::string& key)
{
dctx_value_t val = {dctx_value_t::no_val, false, {0} };
if(!keymap.get(key, val))
{
if(parent)
return parent->lookup_var_iter(key);
else
return NULL;///variable not found
}
if (val.in_progress)
ZORBA_ERROR (XQST0054);
assert (val.type == dynamic_context::dctx_value_t::temp_seq_val);
return val.val.temp_seq->getIterator ();
}
store::Item_t dynamic_context::get_default_collection()
{
return default_collection_uri;
}
void dynamic_context::set_default_collection(const store::Item_t& default_collection_uri)
{
this->default_collection_uri = default_collection_uri;
}
void dynamic_context::bind_index(
const std::string& indexUri,
store::Index* index)
{
if (val_idx_ins_session_map.find(indexUri) != val_idx_ins_session_map.end()) {
ZORBA_ERROR_PARAM(XQP0034_INDEX_ALREADY_EXISTS, indexUri.c_str(), "");
}
std::pair<store::Index_t, ValueIndexInsertSession_t> v;
v.first = index;
v.second = NULL;
val_idx_ins_session_map[indexUri] = v;
}
void dynamic_context::unbind_index(
const std::string& indexUri)
{
IndexMap::iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
val_idx_ins_session_map.erase(i);
}
else if (parent != NULL)
{
return parent->unbind_index(indexUri);
}
else
{
ZORBA_ERROR_PARAM(XQP0033_INDEX_DOES_NOT_EXIST, indexUri.c_str(), "");
}
}
store::Index* dynamic_context::lookup_index(const std::string& indexUri) const
{
IndexMap::const_iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
return i->second.first.getp();
}
else if (parent != NULL)
{
return parent->lookup_index(indexUri);
}
else
{
ZORBA_ERROR_PARAM(XQP0033_INDEX_DOES_NOT_EXIST, indexUri.c_str(), "");
}
}
ValueIndexInsertSession* dynamic_context::get_index_insert_session(
const std::string& indexUri) const
{
IndexMap::const_iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
return i->second.second.getp();
}
else if (parent != NULL)
{
return parent->get_index_insert_session(indexUri);
}
else
{
ZORBA_ASSERT(false);
}
}
void dynamic_context::set_index_insert_session (
const std::string& indexUri,
ValueIndexInsertSession* s)
{
IndexMap::iterator i = val_idx_ins_session_map.find(indexUri);
if (i != val_idx_ins_session_map.end())
{
i->second.second = s;
}
else if (parent != NULL)
{
parent->set_index_insert_session(indexUri, s);
}
else
{
ZORBA_ASSERT(false);
}
}
} /* namespace zorba */
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include <dsn/internal/perf_counters.h>
# include <dsn/service_api_c.h>
# include <dsn/internal/command.h>
# include <dsn/internal/task.h>
# include <dsn/cpp/json_helper.h>
# include "service_engine.h"
DSN_API dsn_handle_t dsn_perf_counter_create(const char* section, const char* name, dsn_perf_counter_type_t type, const char* description)
{
auto cnode = dsn::task::get_current_node2();
dassert(cnode != nullptr, "cannot get current service node!");
auto c = dsn::perf_counters::instance().get_counter(cnode->name(), section, name, type, description, true);
c->add_ref();
return c.get();
}
DSN_API void dsn_perf_counter_remove(dsn_handle_t handle)
{
auto sptr = reinterpret_cast<dsn::perf_counter*>(handle);
if (dsn::perf_counters::instance().remove_counter(sptr->full_name()))
sptr->release_ref();
else
{
dwarn("cannot remove counter %s as it is not found in our repo", sptr->full_name());
}
}
DSN_API void dsn_perf_counter_increment(dsn_handle_t handle)
{
reinterpret_cast<dsn::perf_counter*>(handle)->increment();
}
DSN_API void dsn_perf_counter_decrement(dsn_handle_t handle)
{
reinterpret_cast<dsn::perf_counter*>(handle)->decrement();
}
DSN_API void dsn_perf_counter_add(dsn_handle_t handle, uint64_t val)
{
reinterpret_cast<dsn::perf_counter*>(handle)->add(val);
}
DSN_API void dsn_perf_counter_set(dsn_handle_t handle, uint64_t val)
{
reinterpret_cast<dsn::perf_counter*>(handle)->set(val);
}
DSN_API double dsn_perf_counter_get_value(dsn_handle_t handle)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_value();
}
DSN_API uint64_t dsn_perf_counter_get_integer_value(dsn_handle_t handle)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_integer_value();
}
DSN_API double dsn_perf_counter_get_percentile(dsn_handle_t handle, dsn_perf_counter_percentile_type_t type)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_percentile(type);
}
namespace dsn {
perf_counters::perf_counters(void)
{
_max_counter_count = dsn_config_get_value_uint64(
"core",
"perf_counter_max_count",
10000,
"maximum number of performance counters"
);
dassert(_max_counter_count > 0 && _max_counter_count < 1000000,
"invalid given perf_counter_max_count value %" PRIu64,
_max_counter_count
);
_quick_counters = new perf_counter*[_max_counter_count];
memset((void*)_quick_counters, 0, sizeof(perf_counter*) * _max_counter_count);
// index << 32 | version
// zero is reserved for invalid
for (uint64_t i = 1; i < _max_counter_count; i++)
{
_quick_counters_empty_slots.push((i << 32) | 0x0);
}
::dsn::register_command("counter.list",
"counter.list - get the list of all counters",
"counter.list",
&perf_counters::list_counter
);
::dsn::register_command("counter.value",
"counter.value - get current value of a specific counter",
"counter.value app-name*section-name*counter-name",
&perf_counters::get_counter_value
);
::dsn::register_command("counter.sample",
"counter.sample - get latest sample of a specific counter",
"counter.sample app-name*section-name*counter-name",
&perf_counters::get_counter_sample
);
::dsn::register_command("counter.valuei",
"counter.valuei - get current value of a specific counter",
"counter.valuei counter-index",
&perf_counters::get_counter_value_i
);
::dsn::register_command("counter.samplei",
"counter.samplei - get latest sample of a specific counter",
"counter.samplei counter-index",
&perf_counters::get_counter_sample_i
);
::dsn::register_command("counter.getindex",
"counter.getindex - get index of a list of counters by name",
"counter.getindex app-name1*section-name1*counter-name1 app-name2*section-name2*counter-name2 ...",
&perf_counters::get_counter_index
);
}
perf_counters::~perf_counters(void)
{
delete[] _quick_counters;
}
perf_counter_ptr perf_counters::get_counter(const char* app, const char *section, const char *name, dsn_perf_counter_type_t flags, const char *dsptr, bool create_if_not_exist /*= false*/)
{
std::string full_name;
perf_counter::build_full_name(app, section, name, full_name);
if (create_if_not_exist)
{
utils::auto_write_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
{
dassert(_quick_counters_empty_slots.size() > 0,
"no more slots for perf counters, please increase [core] perf_counter_max_count"
);
uint64_t idx = _quick_counters_empty_slots.front();
_quick_counters_empty_slots.pop();
// increase version
idx++;
perf_counter_ptr counter = _factory(app, section, name, flags, dsptr);
counter->_index = idx; // index << 32 | version
_quick_counters[idx >> 32] = counter.get();
_counters.emplace(std::piecewise_construct, std::forward_as_tuple(full_name), std::forward_as_tuple(counter));
return counter;
}
else
{
dassert (it->second->type() == flags,
"counters with the same name %s with differnt types",
full_name.c_str()
);
return it->second;
}
}
else
{
utils::auto_read_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return nullptr;
else
return it->second;
}
}
perf_counter_ptr perf_counters::get_counter(const char* full_name)
{
utils::auto_read_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return nullptr;
else
return it->second;
}
perf_counter_ptr perf_counters::get_counter(uint64_t index)
{
utils::auto_read_lock l(_lock);
auto slot = (index >> 32);
if (slot >= _max_counter_count)
return nullptr;
if (_quick_counters[slot] && _quick_counters[slot]->index() == index)
{
return _quick_counters[slot];
}
else
{
return nullptr;
}
}
bool perf_counters::remove_counter(const char* full_name)
{
{
utils::auto_write_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return false;
else
{
_quick_counters_empty_slots.push(it->second->index());
auto& c = _quick_counters[it->second->index() >> 32];
dassert(c == it->second.get(),
"invalid perf counter pointer stored in quick access array");
c = nullptr;
_counters.erase(it);
}
}
dinfo("performance counter %s is removed", full_name);
return true;
}
void perf_counters::register_factory(perf_counter::factory factory)
{
utils::auto_write_lock l(_lock);
_factory = factory;
}
std::string perf_counters::list_counter(const std::vector<std::string>& args)
{
return perf_counters::instance().list_counter_internal(args);
}
struct counter_info
{
std::string name;
uint64_t index;
DEFINE_JSON_SERIALIZATION(name, index)
};
struct value_resp {
double val;
uint64_t time;
DEFINE_JSON_SERIALIZATION(val, time)
};
struct sample_resp {
uint64_t val;
uint64_t time;
DEFINE_JSON_SERIALIZATION(time, val)
};
std::string perf_counters::list_counter_internal(const std::vector<std::string>& args)
{
// <app, <section, counter_info[] > > counters
std::map<std::string, std::map< std::string, std::vector<counter_info> > > counters;
std::map< std::string, std::vector<counter_info> > empty_m;
std::vector<counter_info> empty_v;
std::map< std::string, std::vector<counter_info> >* pp;
std::vector<counter_info>* pv;
{
utils::auto_read_lock l(_lock);
for (auto& c : _counters)
{
pp = &counters.insert(
std::map<std::string, std::map< std::string, std::vector<counter_info> > >::value_type(
c.second->app(),
empty_m
)
).first->second;
pv = &pp->insert(
std::map< std::string, std::vector<counter_info> >::value_type(
c.second->section(),
empty_v
)
).first->second;
pv->push_back({ c.second->name(), c.second->index() });
}
}
std::stringstream ss;
std::json_encode(ss, counters);
return ss.str();
}
std::string perf_counters::get_counter_value(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
double value = 0;
if (args.size() < 1)
{
value_resp{ value, ts }.json_state(ss);
return ss.str();
}
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(args[0].c_str());
if (counter && counter->type() != COUNTER_TYPE_NUMBER_PERCENTILES)
value = counter->get_value();
value_resp{ value, ts }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_sample(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
uint64_t sample = 0;
if (args.size() < 1)
{
sample_resp{ sample, ts }.json_state(ss);
return ss.str();
}
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(args[0].c_str());
if (counter)
sample = counter->get_latest_sample();
sample_resp{ sample, ts }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_value_i(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
double value = 0;
if (args.size() < 1)
{
value_resp{ value, ts }.json_state(ss);
return ss.str();
}
uint64_t idx = atoll(args[0].c_str());
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(idx);
if (counter && counter->type() != COUNTER_TYPE_NUMBER_PERCENTILES)
value = counter->get_value();
value_resp{ value, ts }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_sample_i(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
uint64_t sample = 0;
if (args.size() < 1)
{
sample_resp{ sample, ts }.json_state(ss);
return ss.str();
}
uint64_t idx = atoll(args[0].c_str());
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(idx);
if (counter)
sample = counter->get_latest_sample();
sample_resp{ sample, ts }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_index(const std::vector<std::string>& args)
{
std::stringstream ss;
std::vector<uint64_t> counter_index_list;
for (auto counter_name : args)
{
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(counter_name.c_str());
if (counter)
counter_index_list.push_back(counter->index());
else
counter_index_list.push_back(0);
}
std::json_encode(ss, counter_index_list);
return ss.str();
}
} // end namespace
<commit_msg>changed the output of counter.value/sample/valuei/samplei, now results include counter_name and counter_value<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
# include <dsn/internal/perf_counters.h>
# include <dsn/service_api_c.h>
# include <dsn/internal/command.h>
# include <dsn/internal/task.h>
# include <dsn/cpp/json_helper.h>
# include "service_engine.h"
DSN_API dsn_handle_t dsn_perf_counter_create(const char* section, const char* name, dsn_perf_counter_type_t type, const char* description)
{
auto cnode = dsn::task::get_current_node2();
dassert(cnode != nullptr, "cannot get current service node!");
auto c = dsn::perf_counters::instance().get_counter(cnode->name(), section, name, type, description, true);
c->add_ref();
return c.get();
}
DSN_API void dsn_perf_counter_remove(dsn_handle_t handle)
{
auto sptr = reinterpret_cast<dsn::perf_counter*>(handle);
if (dsn::perf_counters::instance().remove_counter(sptr->full_name()))
sptr->release_ref();
else
{
dwarn("cannot remove counter %s as it is not found in our repo", sptr->full_name());
}
}
DSN_API void dsn_perf_counter_increment(dsn_handle_t handle)
{
reinterpret_cast<dsn::perf_counter*>(handle)->increment();
}
DSN_API void dsn_perf_counter_decrement(dsn_handle_t handle)
{
reinterpret_cast<dsn::perf_counter*>(handle)->decrement();
}
DSN_API void dsn_perf_counter_add(dsn_handle_t handle, uint64_t val)
{
reinterpret_cast<dsn::perf_counter*>(handle)->add(val);
}
DSN_API void dsn_perf_counter_set(dsn_handle_t handle, uint64_t val)
{
reinterpret_cast<dsn::perf_counter*>(handle)->set(val);
}
DSN_API double dsn_perf_counter_get_value(dsn_handle_t handle)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_value();
}
DSN_API uint64_t dsn_perf_counter_get_integer_value(dsn_handle_t handle)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_integer_value();
}
DSN_API double dsn_perf_counter_get_percentile(dsn_handle_t handle, dsn_perf_counter_percentile_type_t type)
{
return reinterpret_cast<dsn::perf_counter*>(handle)->get_percentile(type);
}
namespace dsn {
perf_counters::perf_counters(void)
{
_max_counter_count = dsn_config_get_value_uint64(
"core",
"perf_counter_max_count",
10000,
"maximum number of performance counters"
);
dassert(_max_counter_count > 0 && _max_counter_count < 1000000,
"invalid given perf_counter_max_count value %" PRIu64,
_max_counter_count
);
_quick_counters = new perf_counter*[_max_counter_count];
memset((void*)_quick_counters, 0, sizeof(perf_counter*) * _max_counter_count);
// index << 32 | version
// zero is reserved for invalid
for (uint64_t i = 1; i < _max_counter_count; i++)
{
_quick_counters_empty_slots.push((i << 32) | 0x0);
}
::dsn::register_command("counter.list",
"counter.list - get the list of all counters",
"counter.list",
&perf_counters::list_counter
);
::dsn::register_command("counter.value",
"counter.value - get current value of a specific counter",
"counter.value app-name*section-name*counter-name",
&perf_counters::get_counter_value
);
::dsn::register_command("counter.sample",
"counter.sample - get latest sample of a specific counter",
"counter.sample app-name*section-name*counter-name",
&perf_counters::get_counter_sample
);
::dsn::register_command("counter.valuei",
"counter.valuei - get current value of a specific counter",
"counter.valuei counter-index",
&perf_counters::get_counter_value_i
);
::dsn::register_command("counter.samplei",
"counter.samplei - get latest sample of a specific counter",
"counter.samplei counter-index",
&perf_counters::get_counter_sample_i
);
::dsn::register_command("counter.getindex",
"counter.getindex - get index of a list of counters by name",
"counter.getindex app-name1*section-name1*counter-name1 app-name2*section-name2*counter-name2 ...",
&perf_counters::get_counter_index
);
}
perf_counters::~perf_counters(void)
{
delete[] _quick_counters;
}
perf_counter_ptr perf_counters::get_counter(const char* app, const char *section, const char *name, dsn_perf_counter_type_t flags, const char *dsptr, bool create_if_not_exist /*= false*/)
{
std::string full_name;
perf_counter::build_full_name(app, section, name, full_name);
if (create_if_not_exist)
{
utils::auto_write_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
{
dassert(_quick_counters_empty_slots.size() > 0,
"no more slots for perf counters, please increase [core] perf_counter_max_count"
);
uint64_t idx = _quick_counters_empty_slots.front();
_quick_counters_empty_slots.pop();
// increase version
idx++;
perf_counter_ptr counter = _factory(app, section, name, flags, dsptr);
counter->_index = idx; // index << 32 | version
_quick_counters[idx >> 32] = counter.get();
_counters.emplace(std::piecewise_construct, std::forward_as_tuple(full_name), std::forward_as_tuple(counter));
return counter;
}
else
{
dassert (it->second->type() == flags,
"counters with the same name %s with differnt types",
full_name.c_str()
);
return it->second;
}
}
else
{
utils::auto_read_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return nullptr;
else
return it->second;
}
}
perf_counter_ptr perf_counters::get_counter(const char* full_name)
{
utils::auto_read_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return nullptr;
else
return it->second;
}
perf_counter_ptr perf_counters::get_counter(uint64_t index)
{
utils::auto_read_lock l(_lock);
auto slot = (index >> 32);
if (slot >= _max_counter_count)
return nullptr;
if (_quick_counters[slot] && _quick_counters[slot]->index() == index)
{
return _quick_counters[slot];
}
else
{
return nullptr;
}
}
bool perf_counters::remove_counter(const char* full_name)
{
{
utils::auto_write_lock l(_lock);
auto it = _counters.find(full_name);
if (it == _counters.end())
return false;
else
{
_quick_counters_empty_slots.push(it->second->index());
auto& c = _quick_counters[it->second->index() >> 32];
dassert(c == it->second.get(),
"invalid perf counter pointer stored in quick access array");
c = nullptr;
_counters.erase(it);
}
}
dinfo("performance counter %s is removed", full_name);
return true;
}
void perf_counters::register_factory(perf_counter::factory factory)
{
utils::auto_write_lock l(_lock);
_factory = factory;
}
std::string perf_counters::list_counter(const std::vector<std::string>& args)
{
return perf_counters::instance().list_counter_internal(args);
}
struct counter_info
{
std::string name;
uint64_t index;
DEFINE_JSON_SERIALIZATION(name, index)
};
struct value_resp {
double val;
uint64_t time;
std::string counter_name;
uint64_t counter_index;
DEFINE_JSON_SERIALIZATION(val, time, counter_name, counter_index)
};
struct sample_resp {
uint64_t val;
uint64_t time;
std::string counter_name;
uint64_t counter_index;
DEFINE_JSON_SERIALIZATION(val, time, counter_name, counter_index)
};
std::string perf_counters::list_counter_internal(const std::vector<std::string>& args)
{
// <app, <section, counter_info[] > > counters
std::map<std::string, std::map< std::string, std::vector<counter_info> > > counters;
std::map< std::string, std::vector<counter_info> > empty_m;
std::vector<counter_info> empty_v;
std::map< std::string, std::vector<counter_info> >* pp;
std::vector<counter_info>* pv;
{
utils::auto_read_lock l(_lock);
for (auto& c : _counters)
{
pp = &counters.insert(
std::map<std::string, std::map< std::string, std::vector<counter_info> > >::value_type(
c.second->app(),
empty_m
)
).first->second;
pv = &pp->insert(
std::map< std::string, std::vector<counter_info> >::value_type(
c.second->section(),
empty_v
)
).first->second;
pv->push_back({ c.second->name(), c.second->index() });
}
}
std::stringstream ss;
std::json_encode(ss, counters);
return ss.str();
}
std::string perf_counters::get_counter_value(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
double value = 0;
uint64_t counter_index = 0;
if (args.size() < 1)
{
value_resp{ value, ts, std::string(), 0 }.json_state(ss);
return ss.str();
}
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(args[0].c_str());
if (counter)
{
counter_index = counter->index();
if(counter->type() != COUNTER_TYPE_NUMBER_PERCENTILES)
value = counter->get_value();
}
value_resp{ value, ts, args[0], counter_index }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_sample(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
uint64_t sample = 0;
uint64_t counter_index = 0;
if (args.size() < 1)
{
sample_resp{ sample, ts, std::string(), 0 }.json_state(ss);
return ss.str();
}
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(args[0].c_str());
if (counter)
{
sample = counter->get_latest_sample();
counter_index = counter->index();
}
sample_resp{ sample, ts, args[0], counter_index }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_value_i(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
double value = 0;
std::string counter_name = std::string();
if (args.size() < 1)
{
value_resp{ value, ts, std::string(), 0 }.json_state(ss);
return ss.str();
}
uint64_t idx = atoll(args[0].c_str());
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(idx);
if (counter)
{
counter_name = std::string(counter->full_name());
if(counter->type() != COUNTER_TYPE_NUMBER_PERCENTILES)
value = counter->get_value();
}
value_resp{ value, ts, counter_name, idx }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_sample_i(const std::vector<std::string>& args)
{
std::stringstream ss;
uint64_t ts = dsn_now_ns();
uint64_t sample = 0;
std::string counter_name = std::string();
if (args.size() < 1)
{
sample_resp{ sample, ts, std::string(), 0 }.json_state(ss);
return ss.str();
}
uint64_t idx = atoll(args[0].c_str());
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(idx);
if (counter)
{
sample = counter->get_latest_sample();
counter_name = std::string(counter->full_name());
}
sample_resp{ sample, ts, counter_name, idx }.json_state(ss);
return ss.str();
}
std::string perf_counters::get_counter_index(const std::vector<std::string>& args)
{
std::stringstream ss;
std::vector<uint64_t> counter_index_list;
for (auto counter_name : args)
{
perf_counters& c = perf_counters::instance();
auto counter = c.get_counter(counter_name.c_str());
if (counter)
counter_index_list.push_back(counter->index());
else
counter_index_list.push_back(0);
}
std::json_encode(ss, counter_index_list);
return ss.str();
}
} // end namespace
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/OlympusDecompressor.h"
#include "common/Common.h" // for uint32, ushort16, uchar8
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB.h" // for BitPumpMSB
#include "io/ByteStream.h" // for ByteStream
#include <algorithm> // for min
#include <array> // for array, array<>::value_type
#include <cassert> // for assert
#include <cmath> // for abs
#include <cstdlib> // for abs
#include <memory> // for unique_ptr
#include <type_traits> // for enable_if_t, is_integral
namespace {
// Normally, we'd just use std::signbit(int) here. But, some (non-conforming?)
// compilers do not provide that overload, so the code simply fails to compile.
// One could cast the int to the double, but at least right now that results
// in a horrible code. So let's just provide our own signbit(). It compiles to
// the exact same code as the std::signbit(int).
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
constexpr __attribute__((const)) bool SignBit(T x) {
return x < 0;
}
} // namespace
namespace rawspeed {
OlympusDecompressor::OlympusDecompressor(const RawImage& img) : mRaw(img) {
if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
mRaw->getBpp() != 2)
ThrowRDE("Unexpected component count / data type");
const uint32 w = mRaw->dim.x;
const uint32 h = mRaw->dim.y;
if (w == 0 || h == 0 || w % 2 != 0 || w > 10400 || h > 7792)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", w, h);
}
/* This is probably the slowest decoder of them all.
* I cannot see any way to effectively speed up the prediction
* phase, which is by far the slowest part of this algorithm.
* Also there is no way to multithread this code, since prediction
* is based on the output of all previous pixel (bar the first four)
*/
void OlympusDecompressor::decompress(ByteStream input) const {
assert(mRaw->dim.y > 0);
assert(mRaw->dim.x > 0);
assert(mRaw->dim.x % 2 == 0);
int nbits;
int sign;
int low;
int high;
int i;
std::array<int, 2> left{{}};
std::array<int, 2> nw{{}};
int pred;
int diff;
uchar8* data = mRaw->getData();
int pitch = mRaw->pitch;
/* Build a table to quickly look up "high" value */
std::unique_ptr<char[]> bittable(new char[4096]);
for (i = 0; i < 4096; i++) {
int b = i;
for (high = 0; high < 12; high++)
if ((b >> (11 - high)) & 1)
break;
bittable[i] = std::min(12, high);
}
input.skipBytes(7);
BitPumpMSB bits(input);
for (uint32 y = 0; y < static_cast<uint32>(mRaw->dim.y); y++) {
std::array<std::array<int, 3>, 2> acarry{{}};
auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]);
bool y_border = y < 2;
bool border = true;
for (uint32 x = 0; x < static_cast<uint32>(mRaw->dim.x); x++) {
int c = 0;
bits.fill();
i = 2 * (acarry[c][2] < 3);
for (nbits = 2 + i; static_cast<ushort16>(acarry[c][0]) >> (nbits + i);
nbits++)
;
int b = bits.peekBitsNoFill(15);
sign = (b >> 14) * -1;
low = (b >> 12) & 3;
high = bittable[b & 4095];
// Skip bytes used above or read bits
if (high == 12) {
bits.skipBitsNoFill(15);
high = bits.getBits(16 - nbits) >> 1;
} else
bits.skipBitsNoFill(high + 1 + 3);
acarry[c][0] = (high << nbits) | bits.getBits(nbits);
diff = (acarry[c][0] ^ sign) + acarry[c][1];
acarry[c][1] = (diff * 3 + acarry[c][1]) >> 5;
acarry[c][2] = acarry[c][0] > 16 ? 0 : acarry[c][2] + 1;
if (border) {
if (y_border && x < 2)
pred = 0;
else {
if (y_border)
pred = left[c];
else {
pred = dest[-pitch + (static_cast<int>(x))];
nw[c] = pred;
}
}
// Set predictor
left[c] = pred + ((diff * 4) | low);
// Set the pixel
dest[x] = left[c];
} else {
// Have local variables for values used several tiles
// (having a "ushort16 *dst_up" that caches dest[-pitch+((int)x)] is
// actually slower, probably stack spill or aliasing)
int up = dest[-pitch + (static_cast<int>(x))];
int leftMinusNw = left[c] - nw[c];
int upMinusNw = up - nw[c];
// Check if sign is different, and they are both not zero
if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) &&
(leftMinusNw != 0 && upMinusNw != 0)) {
if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32)
pred = left[c] + upMinusNw;
else
pred = (left[c] + up) >> 1;
} else
pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up;
// Set predictors
left[c] = pred + ((diff * 4) | low);
nw[c] = up;
// Set the pixel
dest[x] = left[c];
}
// ODD PIXELS
x += 1;
c = 1;
bits.fill();
i = 2 * (acarry[c][2] < 3);
for (nbits = 2 + i; static_cast<ushort16>(acarry[c][0]) >> (nbits + i);
nbits++)
;
b = bits.peekBitsNoFill(15);
sign = (b >> 14) * -1;
low = (b >> 12) & 3;
high = bittable[b & 4095];
// Skip bytes used above or read bits
if (high == 12) {
bits.skipBitsNoFill(15);
high = bits.getBits(16 - nbits) >> 1;
} else
bits.skipBitsNoFill(high + 1 + 3);
acarry[c][0] = (high << nbits) | bits.getBits(nbits);
diff = (acarry[c][0] ^ sign) + acarry[c][1];
acarry[c][1] = (diff * 3 + acarry[c][1]) >> 5;
acarry[c][2] = acarry[c][0] > 16 ? 0 : acarry[c][2] + 1;
if (border) {
if (y_border && x < 2)
pred = 0;
else {
if (y_border)
pred = left[c];
else {
pred = dest[-pitch + (static_cast<int>(x))];
nw[c] = pred;
}
}
// Set predictor
left[c] = pred + ((diff * 4) | low);
// Set the pixel
dest[x] = left[c];
} else {
int up = dest[-pitch + (static_cast<int>(x))];
int leftMinusNw = left[c] - nw[c];
int upMinusNw = up - nw[c];
// Check if sign is different, and they are both not zero
if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) &&
(leftMinusNw != 0 && upMinusNw != 0)) {
if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32)
pred = left[c] + upMinusNw;
else
pred = (left[c] + up) >> 1;
} else
pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up;
// Set predictors
left[c] = pred + ((diff * 4) | low);
nw[c] = up;
// Set the pixel
dest[x] = left[c];
}
border = y_border;
}
}
}
} // namespace rawspeed
<commit_msg>Partially revert "OlympusDecompressor: address implicit-truncation issue #143"<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/OlympusDecompressor.h"
#include "common/Common.h" // for uint32, ushort16, uchar8
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpMSB.h" // for BitPumpMSB
#include "io/ByteStream.h" // for ByteStream
#include <algorithm> // for min
#include <array> // for array, array<>::value_type
#include <cassert> // for assert
#include <cmath> // for abs
#include <cstdlib> // for abs
#include <memory> // for unique_ptr
#include <type_traits> // for enable_if_t, is_integral
namespace {
// Normally, we'd just use std::signbit(int) here. But, some (non-conforming?)
// compilers do not provide that overload, so the code simply fails to compile.
// One could cast the int to the double, but at least right now that results
// in a horrible code. So let's just provide our own signbit(). It compiles to
// the exact same code as the std::signbit(int).
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
constexpr __attribute__((const)) bool SignBit(T x) {
return x < 0;
}
} // namespace
namespace rawspeed {
OlympusDecompressor::OlympusDecompressor(const RawImage& img) : mRaw(img) {
if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
mRaw->getBpp() != 2)
ThrowRDE("Unexpected component count / data type");
const uint32 w = mRaw->dim.x;
const uint32 h = mRaw->dim.y;
if (w == 0 || h == 0 || w % 2 != 0 || w > 10400 || h > 7792)
ThrowRDE("Unexpected image dimensions found: (%u; %u)", w, h);
}
/* This is probably the slowest decoder of them all.
* I cannot see any way to effectively speed up the prediction
* phase, which is by far the slowest part of this algorithm.
* Also there is no way to multithread this code, since prediction
* is based on the output of all previous pixel (bar the first four)
*/
void OlympusDecompressor::decompress(ByteStream input) const {
assert(mRaw->dim.y > 0);
assert(mRaw->dim.x > 0);
assert(mRaw->dim.x % 2 == 0);
int nbits;
int sign;
int low;
int high;
int i;
std::array<int, 2> left{{}};
std::array<int, 2> nw{{}};
int pred;
int diff;
uchar8* data = mRaw->getData();
int pitch = mRaw->pitch;
/* Build a table to quickly look up "high" value */
std::unique_ptr<char[]> bittable(new char[4096]);
for (i = 0; i < 4096; i++) {
int b = i;
for (high = 0; high < 12; high++)
if ((b >> (11 - high)) & 1)
break;
bittable[i] = std::min(12, high);
}
input.skipBytes(7);
BitPumpMSB bits(input);
for (uint32 y = 0; y < static_cast<uint32>(mRaw->dim.y); y++) {
std::array<std::array<int, 3>, 2> acarry{{}};
auto* dest = reinterpret_cast<ushort16*>(&data[y * pitch]);
bool y_border = y < 2;
bool border = true;
for (uint32 x = 0; x < static_cast<uint32>(mRaw->dim.x); x++) {
int c = 0;
bits.fill();
i = 2 * (acarry[c][2] < 3);
for (nbits = 2 + i; static_cast<ushort16>(acarry[c][0]) >> (nbits + i);
nbits++)
;
int b = bits.peekBitsNoFill(15);
sign = (b >> 14) * -1;
low = (b >> 12) & 3;
high = bittable[b & 4095];
// Skip bytes used above or read bits
if (high == 12) {
bits.skipBitsNoFill(15);
high = bits.getBits(16 - nbits) >> 1;
} else
bits.skipBitsNoFill(high + 1 + 3);
acarry[c][0] = (high << nbits) | bits.getBits(nbits);
diff = (acarry[c][0] ^ sign) + acarry[c][1];
acarry[c][1] = (diff * 3 + acarry[c][1]) >> 5;
acarry[c][2] = acarry[c][0] > 16 ? 0 : acarry[c][2] + 1;
if (border) {
if (y_border && x < 2)
pred = 0;
else {
if (y_border)
pred = left[c];
else {
pred = dest[-pitch + (static_cast<int>(x))];
nw[c] = pred;
}
}
// Set predictor
left[c] = pred + ((diff * 4) | low);
// Set the pixel
dest[x] = ushort16(left[c]);
} else {
// Have local variables for values used several tiles
// (having a "ushort16 *dst_up" that caches dest[-pitch+((int)x)] is
// actually slower, probably stack spill or aliasing)
int up = dest[-pitch + (static_cast<int>(x))];
int leftMinusNw = left[c] - nw[c];
int upMinusNw = up - nw[c];
// Check if sign is different, and they are both not zero
if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) &&
(leftMinusNw != 0 && upMinusNw != 0)) {
if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32)
pred = left[c] + upMinusNw;
else
pred = (left[c] + up) >> 1;
} else
pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up;
// Set predictors
left[c] = pred + ((diff * 4) | low);
nw[c] = up;
// Set the pixel
dest[x] = ushort16(left[c]);
}
// ODD PIXELS
x += 1;
c = 1;
bits.fill();
i = 2 * (acarry[c][2] < 3);
for (nbits = 2 + i; static_cast<ushort16>(acarry[c][0]) >> (nbits + i);
nbits++)
;
b = bits.peekBitsNoFill(15);
sign = (b >> 14) * -1;
low = (b >> 12) & 3;
high = bittable[b & 4095];
// Skip bytes used above or read bits
if (high == 12) {
bits.skipBitsNoFill(15);
high = bits.getBits(16 - nbits) >> 1;
} else
bits.skipBitsNoFill(high + 1 + 3);
acarry[c][0] = (high << nbits) | bits.getBits(nbits);
diff = (acarry[c][0] ^ sign) + acarry[c][1];
acarry[c][1] = (diff * 3 + acarry[c][1]) >> 5;
acarry[c][2] = acarry[c][0] > 16 ? 0 : acarry[c][2] + 1;
if (border) {
if (y_border && x < 2)
pred = 0;
else {
if (y_border)
pred = left[c];
else {
pred = dest[-pitch + (static_cast<int>(x))];
nw[c] = pred;
}
}
// Set predictor
left[c] = pred + ((diff * 4) | low);
// Set the pixel
dest[x] = ushort16(left[c]);
} else {
int up = dest[-pitch + (static_cast<int>(x))];
int leftMinusNw = left[c] - nw[c];
int upMinusNw = up - nw[c];
// Check if sign is different, and they are both not zero
if ((SignBit(leftMinusNw) ^ SignBit(upMinusNw)) &&
(leftMinusNw != 0 && upMinusNw != 0)) {
if (std::abs(leftMinusNw) > 32 || std::abs(upMinusNw) > 32)
pred = left[c] + upMinusNw;
else
pred = (left[c] + up) >> 1;
} else
pred = std::abs(leftMinusNw) > std::abs(upMinusNw) ? left[c] : up;
// Set predictors
left[c] = pred + ((diff * 4) | low);
nw[c] = up;
// Set the pixel
dest[x] = ushort16(left[c]);
}
border = y_border;
}
}
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>//
// Copyright (c) 2017 Michael W Powell <mwpowellhtx@gmail.com>
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
// Copyright 2017 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include <catch.hpp>
#include <nngcpp.h>
#include <string>
#include <memory>
#include <thread>
#ifndef _WIN32
#include <poll.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#else // _WIN32
#define poll WSAPoll
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <WinSock2.h>
#include <MSWSock.h>
#include <WS2tcpip.h>
#endif // _WIN32
TEST_CASE("Poll FDs", "[pollfd]") {
using namespace std;
using namespace nng;
using namespace nng::protocol;
using _opt_ = option_names;
std::unique_ptr<latest_pair_socket> s1;
std::unique_ptr<latest_pair_socket> s2;
SECTION("Given a connected Pair of Sockets") {
// Same as ::nng_pair_open(...) == 0
REQUIRE_NOTHROW(s1 = std::make_unique<latest_pair_socket>());
REQUIRE_NOTHROW(s2 = std::make_unique<latest_pair_socket>());
/* It is a known idiomatic thing that Windows Sockets are treated as 64-bit integers, sort of.
Yet, cross platform, and with the options, it is more accurate to simply treat them as 32-bit
integers. */
const auto inv_sock = INVALID_SOCKET;
const string addr = "inproc://yeahbaby";
// Should be ~= ::nng_listen(s, addr, listenerp, 0) == 0
REQUIRE_NOTHROW(s1->listen(addr));
this_thread::sleep_for(50ms);
REQUIRE_NOTHROW(s2->dial(addr));
this_thread::sleep_for(50ms);
SECTION("We can get a Receive File Descriptor") {
int fd;
//REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd));
REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd));
REQUIRE(fd != inv_sock);
SECTION("And it is always the same File Descriptor") {
int fd2;
REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd2));
REQUIRE(fd2 == fd);
}
SECTION("And they start non pollable") {
pollfd pfd{ (SOCKET)fd, POLLIN, 0 };
REQUIRE(::poll(&pfd, 1, 0) == 0);
REQUIRE(pfd.revents == 0);
}
SECTION("But if we write they are pollable") {
pollfd pfd{ (SOCKET)fd, POLLIN, 0 };
REQUIRE_NOTHROW(s2->send("kick")); // TODO: TBD: send appears to be blocking
REQUIRE(::poll(&pfd, 1, 1000) == 1);
REQUIRE((pfd.revents&POLLIN));
}
}
SECTION("We can get a Send File Descriptor") {
int fd;
REQUIRE_NOTHROW(s1->get_option_int(_opt_::send_file_descriptor, &fd));
REQUIRE(fd != inv_sock);
REQUIRE_NOTHROW(s1->send("oops"));
}
SECTION("Must have big enough size") {
INFO("At least for now, we simply do not expose the general get/set options API through the C++ wrapper.");
}
SECTION("We cannot get a Send File Descriptor for Pull Socket") {
std::unique_ptr<latest_pull_socket> s3;
REQUIRE_NOTHROW(s3 = std::make_unique<latest_pull_socket>());
int fd;
// TODO: TBD: work on exception handling...
REQUIRE_THROWS_AS(s3->get_option_int(_opt_::send_file_descriptor, &fd), nng_exception);
SECTION("Destructor cleans up correctly") {
REQUIRE(s3.release() == nullptr);
}
}
SECTION("We cannot get a Receive File Descriptor for Push Socket") {
std::unique_ptr<latest_push_socket> s3;
REQUIRE_NOTHROW(s3 = std::make_unique<latest_push_socket>());
int fd;
// TODO: TBD: work on exception handling...
REQUIRE_THROWS_AS(s3->get_option_int(_opt_::receive_file_descriptor, &fd), nng_exception);
SECTION("Destructor cleans up correctly") {
REQUIRE(s3.release() == nullptr);
}
}
}
SECTION("Destructors do not throw") {
REQUIRE_NOTHROW(s1.release() == nullptr);
REQUIRE_NOTHROW(s2.release() == nullptr);
}
}
<commit_msg>updated unit testing around latest patterns<commit_after>//
// Copyright (c) 2017 Michael W Powell <mwpowellhtx@gmail.com>
// Copyright 2017 Garrett D'Amore <garrett@damore.org>
// Copyright 2017 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt). A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
#include "../catch/catch_exception_matcher_base.hpp"
#include "../catch/catch_exception_translations.hpp"
#include "../catch/catch_nng_exception_matcher.hpp"
#include "../catch/catch_macros.hpp"
#include <nngcpp.h>
#include <string>
#include <memory>
#include <thread>
#ifndef _WIN32
#include <poll.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#else // _WIN32
#define poll WSAPoll
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif // WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <WinSock2.h>
#include <MSWSock.h>
#include <WS2tcpip.h>
#endif // _WIN32
namespace constants {
const std::string addr = "inproc://yeahbaby";
}
TEST_CASE("Poll FDs", "[pollfd]") {
using namespace std;
using namespace nng;
using namespace nng::protocol;
using namespace Catch::Matchers;
using namespace constants;
using _opt_ = option_names;
std::unique_ptr<latest_pair_socket> s1, s2;
REQUIRE(s1 == nullptr);
REQUIRE(s2 == nullptr);
SECTION("Given a connected Pair of Sockets") {
// Same as ::nng_pair_open(...) == 0
REQUIRE_NOTHROW(s1 = make_unique<latest_pair_socket>());
REQUIRE_NOTHROW(s2 = make_unique<latest_pair_socket>());
/* It is a known idiomatic thing that Windows Sockets are treated as 64-bit integers, sort of.
Yet, cross platform, and with the options, it is more accurate to simply treat them as 32-bit
integers. */
const auto inv_sock = INVALID_SOCKET;
// Should be ~= ::nng_listen(s, addr, listenerp, 0) == 0
REQUIRE_NOTHROW(s1->listen(addr));
this_thread::sleep_for(50ms);
REQUIRE_NOTHROW(s2->dial(addr));
this_thread::sleep_for(50ms);
SECTION("We can get a Receive File Descriptor") {
int fd;
//REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd));
REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd));
REQUIRE(fd != inv_sock);
SECTION("And it is always the same File Descriptor") {
int fd2;
REQUIRE_NOTHROW(s1->get_option_int(_opt_::receive_file_descriptor, &fd2));
REQUIRE(fd2 == fd);
}
SECTION("And they start non pollable") {
pollfd pfd{ (SOCKET)fd, POLLIN, 0 };
REQUIRE(::poll(&pfd, 1, 0) == 0);
REQUIRE(pfd.revents == 0);
}
SECTION("But if we write they are pollable") {
pollfd pfd{ (SOCKET)fd, POLLIN, 0 };
REQUIRE_NOTHROW(s2->send("kick")); // TODO: TBD: send appears to be blocking
REQUIRE(::poll(&pfd, 1, 1000) == 1);
REQUIRE((pfd.revents&POLLIN));
}
}
SECTION("We can get a Send File Descriptor") {
int fd;
REQUIRE_NOTHROW(s1->get_option_int(_opt_::send_file_descriptor, &fd));
REQUIRE(fd != inv_sock);
REQUIRE_NOTHROW(s1->send("oops"));
}
SECTION("Must have big enough size") {
INFO("At least for now, we simply do not expose the general get/set options API through the C++ wrapper.");
}
SECTION("We cannot get a Send File Descriptor for Pull Socket") {
std::unique_ptr<latest_pull_socket> s3;
REQUIRE_NOTHROW(s3 = make_unique<latest_pull_socket>());
int fd;
// TODO: TBD: ditto working interim answer...
REQUIRE_THROWS_AS_MATCHING(s3->get_option_int(_opt_::send_file_descriptor, &fd), nng_exception, ThrowsNngException(ec_enotsup));
SECTION("Destructor cleans up correctly") {
REQUIRE_NOTHROW(s3.reset());
REQUIRE(s3 == nullptr);
}
}
SECTION("We cannot get a Receive File Descriptor for Push Socket") {
std::unique_ptr<latest_push_socket> s3;
REQUIRE_NOTHROW(s3 = make_unique<latest_push_socket>());
int fd;
// TODO: TBD: this works as an interim measure, although the ResultBuilder needs a little help to better comprehend the result.
REQUIRE_THROWS_AS_MATCHING(s3->get_option_int(_opt_::receive_file_descriptor, &fd), nng_exception, ThrowsNngException(ec_enotsup));
SECTION("Destructor cleans up correctly") {
REQUIRE_NOTHROW(s3.reset());
REQUIRE(s3 == nullptr);
}
}
}
SECTION("Destructors do not throw") {
REQUIRE_NOTHROW(s1.reset());
REQUIRE_NOTHROW(s2.reset());
REQUIRE(s1 == nullptr);
REQUIRE(s2 == nullptr);
}
}
<|endoftext|> |
<commit_before>/* Copyright 2014 Jonas Platte
*
* This file is part of Cyvasse Online.
*
* Cyvasse Online is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _HEXAGONAL_BOARD_HPP_
#define _HEXAGONAL_BOARD_HPP_
#include <unordered_map>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <featherkit/rendering/renderer2d.hpp>
#include <featherkit/rendering/quad.hpp>
#include "hexagon.hpp"
template<int l>
class HexagonalBoard
{
public:
typedef typename cyvmath::hexagon<l> Hexagon;
typedef typename Hexagon::Coordinate Coordinate;
typedef typename std::unordered_map<Coordinate, fea::Quad*, std::hash<int>> tileMap;
typedef std::vector<fea::Quad*> tileVec;
private:
// non-copyable
HexagonalBoard(const HexagonalBoard&) = delete;
const HexagonalBoard& operator= (const HexagonalBoard&) = delete;
fea::Renderer2D& _renderer;
glm::vec2 _size;
glm::vec2 _position;
glm::vec2 _tileSize;
tileMap _tileMap;
tileVec _tileVec;
static int8_t getColorIndex(Coordinate c)
{
return (((c.x() - c.y()) % 3) + 3) % 3;
}
public:
glm::vec2 getTilePosition(Coordinate c)
{
return {_tileSize.x * c.x() + (_tileSize.x / 2) * (c.y() - (Hexagon::edgeLength - 1)) + _position.x,
_size.y - (_tileSize.y * c.y() + _position.y)};
}
HexagonalBoard(fea::Renderer2D& renderer, glm::vec2 size, glm::vec2 offset)
: _renderer(renderer)
, _size(size)
{
// the tiles map never changes so it is set up here instead of in setup()
fea::Color tileColors[3] = {
{1.0f, 1.0f, 1.0f},
{0.8f, 0.8f, 0.8f},
{0.6f, 0.6f, 0.6f}
};
fea::Color tileColorsDark[3] = {
{0.4f, 0.4f, 0.4f},
{0.3f, 0.3f, 0.3f},
{0.2f, 0.2f, 0.2f}
};
float tileWidth = _size.x / static_cast<float>(l * 2 - 1);
_tileSize = {tileWidth, tileWidth / 3 * 2};
_position = {
offset.x,
offset.y + (_size.y - ((l * 2 - 1) * _tileSize.y)) / 2
};
for(Coordinate c : Hexagon::getAllCoordinates())
{
fea::Quad* quad = new fea::Quad(_tileSize);
quad->setPosition(getTilePosition(c));
// may be no permanent solution
if(c.y() >= (l - 1))
quad->setColor(tileColorsDark[getColorIndex(c)]);
else
quad->setColor(tileColors[getColorIndex(c)]);
// add the tile to the map and vector
_tileVec.push_back(quad);
std::pair<typename tileMap::iterator, bool> res = _tileMap.insert({c, quad});
assert(res.second); // assert the insertion was successful
}
}
~HexagonalBoard()
{
for(fea::Quad* it : _tileVec)
{
delete it;
}
}
const glm::vec2& getTileSize() const
{
return _tileSize;
}
void tick()
{
for(const fea::Quad* it : _tileVec)
{
_renderer.queue(*it);
}
}
};
#endif // _HEXAGONAL_BOARD_HPP_
<commit_msg>Fixed vertical positioning of the board<commit_after>/* Copyright 2014 Jonas Platte
*
* This file is part of Cyvasse Online.
*
* Cyvasse Online is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _HEXAGONAL_BOARD_HPP_
#define _HEXAGONAL_BOARD_HPP_
#include <unordered_map>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <featherkit/rendering/renderer2d.hpp>
#include <featherkit/rendering/quad.hpp>
#include "hexagon.hpp"
template<int l>
class HexagonalBoard
{
public:
typedef typename cyvmath::hexagon<l> Hexagon;
typedef typename Hexagon::Coordinate Coordinate;
typedef typename std::unordered_map<Coordinate, fea::Quad*, std::hash<int>> tileMap;
typedef std::vector<fea::Quad*> tileVec;
private:
// non-copyable
HexagonalBoard(const HexagonalBoard&) = delete;
const HexagonalBoard& operator= (const HexagonalBoard&) = delete;
fea::Renderer2D& _renderer;
glm::vec2 _size;
glm::vec2 _realSize;
glm::vec2 _position;
glm::vec2 _tileSize;
tileMap _tileMap;
tileVec _tileVec;
static int8_t getColorIndex(Coordinate c)
{
return (((c.x() - c.y()) % 3) + 3) % 3;
}
public:
glm::vec2 getTilePosition(Coordinate c)
{
// TODO: document
return {_position.x + _tileSize.x * c.x() + (_tileSize.x / 2) * (c.y() - (Hexagon::edgeLength - 1)),
_position.y - _tileSize.y + (_realSize.y - (_tileSize.y * c.y()))};
}
HexagonalBoard(fea::Renderer2D& renderer, glm::vec2 size, glm::vec2 offset)
: _renderer(renderer)
, _size(size)
{
// the tiles map never changes so it is set up here instead of in setup()
fea::Color tileColors[3] = {
{1.0f, 1.0f, 1.0f},
{0.8f, 0.8f, 0.8f},
{0.6f, 0.6f, 0.6f}
};
fea::Color tileColorsDark[3] = {
{0.4f, 0.4f, 0.4f},
{0.3f, 0.3f, 0.3f},
{0.2f, 0.2f, 0.2f}
};
float tileWidth = _size.x / static_cast<float>(l * 2 - 1);
_tileSize = {tileWidth, tileWidth / 3 * 2};
_realSize = {_size.x, (l * 2 - 1) * _tileSize.y};
_position = {
offset.x,
offset.y + (_size.y - _realSize.y) / 2
};
for(Coordinate c : Hexagon::getAllCoordinates())
{
fea::Quad* quad = new fea::Quad(_tileSize);
quad->setPosition(getTilePosition(c));
// may be no permanent solution
if(c.y() >= (l - 1))
quad->setColor(tileColorsDark[getColorIndex(c)]);
else
quad->setColor(tileColors[getColorIndex(c)]);
// add the tile to the map and vector
_tileVec.push_back(quad);
std::pair<typename tileMap::iterator, bool> res = _tileMap.insert({c, quad});
assert(res.second); // assert the insertion was successful
}
}
~HexagonalBoard()
{
for(fea::Quad* it : _tileVec)
{
delete it;
}
}
const glm::vec2& getTileSize() const
{
return _tileSize;
}
void tick()
{
for(const fea::Quad* it : _tileVec)
{
_renderer.queue(*it);
}
}
};
#endif // _HEXAGONAL_BOARD_HPP_
<|endoftext|> |
<commit_before>#include "game/state/base/base.h"
#include "framework/framework.h"
#include "game/state/base/facility.h"
#include "game/state/city/building.h"
#include "game/state/organisation.h"
#include <random>
namespace OpenApoc
{
Base::Base(GameState &state, StateRef<Building> building) : building(building)
{
corridors = std::vector<std::vector<bool>>(SIZE, std::vector<bool>(SIZE, false));
for (auto &rect : building->base_layout->baseCorridors)
{
for (int x = rect.p0.x; x < rect.p1.x; ++x)
{
for (int y = rect.p0.y; y < rect.p1.y; ++y)
{
corridors[x][y] = true;
}
}
}
StateRef<FacilityType> type = {&state, FacilityType::getPrefix() + "ACCESS_LIFT"};
if (canBuildFacility(type, building->base_layout->baseLift, true) != BuildError::NoError)
{
LogError("Building %s has invalid lift location", building->name.c_str());
}
else
{
buildFacility(type, building->base_layout->baseLift, true);
}
}
sp<Facility> Base::getFacility(Vec2<int> pos) const
{
for (auto &facility : facilities)
{
if (pos.x >= facility->pos.x && pos.x < facility->pos.x + facility->type->size &&
pos.y >= facility->pos.y && pos.y < facility->pos.y + facility->type->size)
{
return facility;
}
}
return nullptr;
}
void Base::startingBase(GameState &state)
{
// Figure out positions available for placement
std::vector<Vec2<int>> positions;
for (int x = 0; x < SIZE; ++x)
{
for (int y = 0; y < SIZE; ++y)
{
if (corridors[x][y] && getFacility({x, y}) == nullptr)
{
// FIXME: Store free positions for every possible size?
positions.push_back({x, y});
}
}
}
// Randomly fill them with facilities
for (auto &facilityTypePair : state.initial_facilities)
{
auto type = facilityTypePair.first;
auto count = facilityTypePair.second;
StateRef<FacilityType> facility = {&state, type};
while (count > 0)
{
if (positions.size() < facility->size * facility->size)
{
LogError("Can't place all starting facilities in building %s", building->name.c_str());
return;
}
auto facilityPos = std::uniform_int_distribution<int>(0, positions.size() - 1);
Vec2<int> random;
BuildError error;
do
{
random = positions[facilityPos(state.rng)];
error = canBuildFacility(facility, random, true);
} while (error != BuildError::NoError); // Try harder
buildFacility(facility, random, true);
// Clear used positions
for (auto pos = positions.begin(); pos != positions.end();)
{
if (getFacility(*pos) != nullptr)
{
pos = positions.erase(pos);
}
else
{
++pos;
}
}
count--;
}
}
}
Base::BuildError Base::canBuildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free) const
{
if (pos.x < 0 || pos.y < 0 || pos.x + type->size > SIZE || pos.y + type->size > SIZE)
{
return BuildError::OutOfBounds;
}
for (int x = pos.x; x < pos.x + type->size; ++x)
{
for (int y = pos.y; y < pos.y + type->size; ++y)
{
if (!corridors[x][y])
{
return BuildError::OutOfBounds;
}
}
}
for (int x = pos.x; x < pos.x + type->size; ++x)
{
for (int y = pos.y; y < pos.y + type->size; ++y)
{
if (getFacility({x, y}) != nullptr)
{
return BuildError::Occupied;
}
}
}
if (!free)
{
if (!building)
{
LogError("Building disappeared");
return BuildError::OutOfBounds;
}
else if (building->owner->balance - type->buildCost < 0)
{
return BuildError::NoMoney;
}
}
return BuildError::NoError;
}
void Base::buildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free)
{
if (canBuildFacility(type, pos, free) == BuildError::NoError)
{
auto facility = mksp<Facility>(type);
facilities.push_back(facility);
facility->pos = pos;
if (!free)
{
if (!building)
{
LogError("Building disappeared");
}
else
{
building->owner->balance -= type->buildCost;
}
facility->buildTime = type->buildTime;
}
}
}
Base::BuildError Base::canDestroyFacility(Vec2<int> pos) const
{
auto facility = getFacility(pos);
if (facility == nullptr)
{
return BuildError::OutOfBounds;
}
if (facility->type->fixed)
{
return BuildError::Occupied;
}
// TODO: Check if facility is in use
return BuildError::NoError;
}
void Base::destroyFacility(Vec2<int> pos)
{
if (canDestroyFacility(pos) == BuildError::NoError)
{
auto facility = getFacility(pos);
for (auto f = facilities.begin(); f != facilities.end(); ++f)
{
if (*f == facility)
{
facilities.erase(f);
break;
}
}
}
}
template <> sp<Base> StateObject<Base>::get(const GameState &state, const UString &id)
{
auto it = state.player_bases.find(id);
if (it == state.player_bases.end())
{
LogError("No baseas matching ID \"%s\"", id.c_str());
return nullptr;
}
return it->second;
}
template <> const UString &StateObject<Base>::getPrefix()
{
static UString prefix = "BASE_";
return prefix;
}
template <> const UString &StateObject<Base>::getTypeName()
{
static UString name = "Base";
return name;
}
template <> const UString &StateObject<Base>::getId(const GameState &state, const sp<Base> ptr)
{
static const UString emptyString = "";
for (auto &b : state.player_bases)
{
if (b.second == ptr)
return b.first;
}
LogError("No base matching pointer %p", ptr.get());
return emptyString;
}
}; // namespace OpenApoc
<commit_msg>format<commit_after>#include "game/state/base/base.h"
#include "framework/framework.h"
#include "game/state/base/facility.h"
#include "game/state/city/building.h"
#include "game/state/organisation.h"
#include <random>
namespace OpenApoc
{
Base::Base(GameState &state, StateRef<Building> building) : building(building)
{
corridors = std::vector<std::vector<bool>>(SIZE, std::vector<bool>(SIZE, false));
for (auto &rect : building->base_layout->baseCorridors)
{
for (int x = rect.p0.x; x < rect.p1.x; ++x)
{
for (int y = rect.p0.y; y < rect.p1.y; ++y)
{
corridors[x][y] = true;
}
}
}
StateRef<FacilityType> type = {&state, FacilityType::getPrefix() + "ACCESS_LIFT"};
if (canBuildFacility(type, building->base_layout->baseLift, true) != BuildError::NoError)
{
LogError("Building %s has invalid lift location", building->name.c_str());
}
else
{
buildFacility(type, building->base_layout->baseLift, true);
}
}
sp<Facility> Base::getFacility(Vec2<int> pos) const
{
for (auto &facility : facilities)
{
if (pos.x >= facility->pos.x && pos.x < facility->pos.x + facility->type->size &&
pos.y >= facility->pos.y && pos.y < facility->pos.y + facility->type->size)
{
return facility;
}
}
return nullptr;
}
void Base::startingBase(GameState &state)
{
// Figure out positions available for placement
std::vector<Vec2<int>> positions;
for (int x = 0; x < SIZE; ++x)
{
for (int y = 0; y < SIZE; ++y)
{
if (corridors[x][y] && getFacility({x, y}) == nullptr)
{
// FIXME: Store free positions for every possible size?
positions.push_back({x, y});
}
}
}
// Randomly fill them with facilities
for (auto &facilityTypePair : state.initial_facilities)
{
auto type = facilityTypePair.first;
auto count = facilityTypePair.second;
StateRef<FacilityType> facility = {&state, type};
while (count > 0)
{
if (positions.size() < facility->size * facility->size)
{
LogError("Can't place all starting facilities in building %s",
building->name.c_str());
return;
}
auto facilityPos = std::uniform_int_distribution<int>(0, positions.size() - 1);
Vec2<int> random;
BuildError error;
do
{
random = positions[facilityPos(state.rng)];
error = canBuildFacility(facility, random, true);
} while (error != BuildError::NoError); // Try harder
buildFacility(facility, random, true);
// Clear used positions
for (auto pos = positions.begin(); pos != positions.end();)
{
if (getFacility(*pos) != nullptr)
{
pos = positions.erase(pos);
}
else
{
++pos;
}
}
count--;
}
}
}
Base::BuildError Base::canBuildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free) const
{
if (pos.x < 0 || pos.y < 0 || pos.x + type->size > SIZE || pos.y + type->size > SIZE)
{
return BuildError::OutOfBounds;
}
for (int x = pos.x; x < pos.x + type->size; ++x)
{
for (int y = pos.y; y < pos.y + type->size; ++y)
{
if (!corridors[x][y])
{
return BuildError::OutOfBounds;
}
}
}
for (int x = pos.x; x < pos.x + type->size; ++x)
{
for (int y = pos.y; y < pos.y + type->size; ++y)
{
if (getFacility({x, y}) != nullptr)
{
return BuildError::Occupied;
}
}
}
if (!free)
{
if (!building)
{
LogError("Building disappeared");
return BuildError::OutOfBounds;
}
else if (building->owner->balance - type->buildCost < 0)
{
return BuildError::NoMoney;
}
}
return BuildError::NoError;
}
void Base::buildFacility(StateRef<FacilityType> type, Vec2<int> pos, bool free)
{
if (canBuildFacility(type, pos, free) == BuildError::NoError)
{
auto facility = mksp<Facility>(type);
facilities.push_back(facility);
facility->pos = pos;
if (!free)
{
if (!building)
{
LogError("Building disappeared");
}
else
{
building->owner->balance -= type->buildCost;
}
facility->buildTime = type->buildTime;
}
}
}
Base::BuildError Base::canDestroyFacility(Vec2<int> pos) const
{
auto facility = getFacility(pos);
if (facility == nullptr)
{
return BuildError::OutOfBounds;
}
if (facility->type->fixed)
{
return BuildError::Occupied;
}
// TODO: Check if facility is in use
return BuildError::NoError;
}
void Base::destroyFacility(Vec2<int> pos)
{
if (canDestroyFacility(pos) == BuildError::NoError)
{
auto facility = getFacility(pos);
for (auto f = facilities.begin(); f != facilities.end(); ++f)
{
if (*f == facility)
{
facilities.erase(f);
break;
}
}
}
}
template <> sp<Base> StateObject<Base>::get(const GameState &state, const UString &id)
{
auto it = state.player_bases.find(id);
if (it == state.player_bases.end())
{
LogError("No baseas matching ID \"%s\"", id.c_str());
return nullptr;
}
return it->second;
}
template <> const UString &StateObject<Base>::getPrefix()
{
static UString prefix = "BASE_";
return prefix;
}
template <> const UString &StateObject<Base>::getTypeName()
{
static UString name = "Base";
return name;
}
template <> const UString &StateObject<Base>::getId(const GameState &state, const sp<Base> ptr)
{
static const UString emptyString = "";
for (auto &b : state.player_bases)
{
if (b.second == ptr)
return b.first;
}
LogError("No base matching pointer %p", ptr.get());
return emptyString;
}
}; // namespace OpenApoc
<|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <utility>
#include <iostream>
#include <streambuf>
#include <tuple>
namespace NSaveLoad {
template<class T, typename E = void>
class TSerializer {
public:
static void Save(std::ostream& out, const T& object) {
object.Save(out);
}
static void Load(std::istream& in, T& object) {
object.Load(in);
}
};
template <class T>
static inline void Save(std::ostream& out, const T& t);
template <class T>
static inline void Load(std::istream& in, T& t);
template <class A, class B>
class TSerializer<std::pair<A, B> > {
public:
static void Save(std::ostream& out, const std::pair<A, B>& object) {
NSaveLoad::Save(out, object.first);
NSaveLoad::Save(out, object.second);
}
static void Load(std::istream& in, std::pair<A, B>& object) {
NSaveLoad::Load(in, object.first);
NSaveLoad::Load(in, object.second);
}
};
template<std::size_t> struct int_{};
template <class Tuple, size_t Pos>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<Pos>) {
SaveTuple(out, tuple, int_<Pos-1>());
NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}
template <class Tuple>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<1>) {
NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}
template <class Tuple, size_t Pos>
void LoadTuple(std::istream& in, Tuple& tuple, int_<Pos>) {
LoadTuple(in, tuple, int_<Pos-1>());
NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}
template <class Tuple>
void LoadTuple(std::istream& in, Tuple& tuple, int_<1>) {
NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}
template <class... Args>
class TSerializer<std::tuple<Args...>> {
public:
static void Save(std::ostream& out, const std::tuple<Args...>& object) {
SaveTuple(out, object, int_<sizeof...(Args)>());
}
static void Load(std::istream& in, std::tuple<Args...>& object) {
LoadTuple(in, object, int_<sizeof...(Args)>());
}
};
template<class TVec, class TObj>
class TVectorSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
unsigned short size = object.size();
out.write((const char*)(&size), 2);
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
unsigned short size;
in.read((char*)(&size), 2);
object.clear();
for (size_t i = 0; i < size; ++i) {
TObj obj;
NSaveLoad::Load(in, obj);
object.push_back(std::move(obj));
}
}
};
template<class TVec, class TKey, class TValue>
class TMapSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
unsigned short size = object.size();
out.write((const char*)(&size), 2);
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
unsigned short size;
in.read((char*)(&size), 2);
object.clear();
for (size_t i = 0; i < size; ++i) {
std::pair<TKey, TValue> obj;
NSaveLoad::Load(in, obj);
object.insert(std::move(obj));
}
}
};
template<class TVec, class TObj>
class TSetSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
unsigned short size = object.size();
out.write((const char*)(&size), 2);
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
unsigned short size;
in.read((char*)(&size), 2);
object.clear();
for (size_t i = 0; i < size; ++i) {
TObj obj;
NSaveLoad::Load(in, obj);
object.insert(std::move(obj));
}
}
};
template <class T> class TSerializer<std::vector<T> >: public TVectorSerializer<std::vector<T>, T > {};
template <class T> class TSerializer<std::list<T> >: public TVectorSerializer<std::list<T>, T > {};
template <> class TSerializer<std::string>: public TVectorSerializer<std::string, char> {};
template <> class TSerializer<std::wstring>: public TVectorSerializer<std::wstring, wchar_t> {};
template <class K, class V> class TSerializer<std::map<K, V> >: public TMapSerializer<std::map<K, V>, K, V > {};
template <class K, class V, class H> class TSerializer<std::unordered_map<K, V, H> >: public TMapSerializer<std::unordered_map<K, V, H>, K, V > {};
template <class T> class TSerializer<std::set<T> >: public TSetSerializer<std::set<T>, T > {};
template <class T> class TSerializer<std::unordered_set<T> >: public TSetSerializer<std::unordered_set<T>, T > {};
template <class T>
class TPodSerializer {
public:
static inline void Save(std::ostream& out, const T& object) {
out.write((const char*)(&object), sizeof(T));
}
static inline void Load(std::istream& in, T& object) {
in.read((char*)(&object), sizeof(T));
}
};
template<class T>
class TSerializer<T, typename std::enable_if<!std::is_class<T>::value>::type>: public TPodSerializer<T> {};
template <class T>
static inline void Save(std::ostream& out, const T& t) {
TSerializer<T>::Save(out, t);
}
template<class T, class... Args>
static inline void Save(std::ostream& out, T first, Args... args) {
NSaveLoad::Save(out, first);
NSaveLoad::Save(out, args...);
}
template <class T>
static inline void Load(std::istream& in, T& t) {
TSerializer<T>::Load(in, t);
}
template <class T, class... Args>
static inline void Load(std::istream& in, T& first, Args&... args) {
NSaveLoad::Load(in, first);
NSaveLoad::Load(in, args...);
}
#define SAVELOAD(...) \
inline virtual void Save(std::ostream& out) const { \
NSaveLoad::Save(out, __VA_ARGS__); \
} \
\
inline virtual void Load(std::istream& in) { \
NSaveLoad::Load(in, __VA_ARGS__); \
}
struct membuf: std::streambuf {
membuf(char const* base, size_t size) {
char* p(const_cast<char*>(base));
this->setg(p, p, p + size);
}
};
struct imemstream: virtual membuf, std::istream {
imemstream(char const* base, size_t size)
: membuf(base, size)
, std::istream(static_cast<std::streambuf*>(this)) {
}
};
#define SAVELOAD_POD(TypeName) template <> class TSerializer<TypeName>: public TPodSerializer<TypeName> {};
} // NSaveLoad
<commit_msg>increased container size<commit_after>#pragma once
#include <string>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <utility>
#include <iostream>
#include <streambuf>
#include <tuple>
namespace NSaveLoad {
template<class T, typename E = void>
class TSerializer {
public:
static void Save(std::ostream& out, const T& object) {
object.Save(out);
}
static void Load(std::istream& in, T& object) {
object.Load(in);
}
};
template <class T>
static inline void Save(std::ostream& out, const T& t);
template <class T>
static inline void Load(std::istream& in, T& t);
template <class A, class B>
class TSerializer<std::pair<A, B> > {
public:
static void Save(std::ostream& out, const std::pair<A, B>& object) {
NSaveLoad::Save(out, object.first);
NSaveLoad::Save(out, object.second);
}
static void Load(std::istream& in, std::pair<A, B>& object) {
NSaveLoad::Load(in, object.first);
NSaveLoad::Load(in, object.second);
}
};
template<std::size_t> struct int_{};
template <class Tuple, size_t Pos>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<Pos>) {
SaveTuple(out, tuple, int_<Pos-1>());
NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}
template <class Tuple>
void SaveTuple(std::ostream& out, const Tuple& tuple, int_<1>) {
NSaveLoad::Save(out, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}
template <class Tuple, size_t Pos>
void LoadTuple(std::istream& in, Tuple& tuple, int_<Pos>) {
LoadTuple(in, tuple, int_<Pos-1>());
NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-Pos>(tuple));
}
template <class Tuple>
void LoadTuple(std::istream& in, Tuple& tuple, int_<1>) {
NSaveLoad::Load(in, std::get<std::tuple_size<Tuple>::value-1>(tuple));
}
template <class... Args>
class TSerializer<std::tuple<Args...>> {
public:
static void Save(std::ostream& out, const std::tuple<Args...>& object) {
SaveTuple(out, object, int_<sizeof...(Args)>());
}
static void Load(std::istream& in, std::tuple<Args...>& object) {
LoadTuple(in, object, int_<sizeof...(Args)>());
}
};
template<class TVec, class TObj>
class TVectorSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
uint32_t size = object.size();
out.write((const char*)(&size), sizeof(size));
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
uint32_t size;
in.read((char*)(&size), sizeof(size));
object.clear();
for (size_t i = 0; i < size; ++i) {
TObj obj;
NSaveLoad::Load(in, obj);
object.push_back(std::move(obj));
}
}
};
template<class TVec, class TKey, class TValue>
class TMapSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
uint32_t size = object.size();
out.write((const char*)(&size), sizeof(size));
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
uint32_t size;
in.read((char*)(&size), sizeof(size));
object.clear();
for (size_t i = 0; i < size; ++i) {
std::pair<TKey, TValue> obj;
NSaveLoad::Load(in, obj);
object.insert(std::move(obj));
}
}
};
template<class TVec, class TObj>
class TSetSerializer {
public:
static inline void Save(std::ostream& out, const TVec& object) {
uint32_t size = object.size();
out.write((const char*)(&size), sizeof(size));
for (const auto& obj: object) {
NSaveLoad::Save(out, obj);
}
}
static inline void Load(std::istream& in, TVec& object) {
uint32_t size;
in.read((char*)(&size), sizeof(size));
object.clear();
for (size_t i = 0; i < size; ++i) {
TObj obj;
NSaveLoad::Load(in, obj);
object.insert(std::move(obj));
}
}
};
template <class T> class TSerializer<std::vector<T> >: public TVectorSerializer<std::vector<T>, T > {};
template <class T> class TSerializer<std::list<T> >: public TVectorSerializer<std::list<T>, T > {};
template <> class TSerializer<std::string>: public TVectorSerializer<std::string, char> {};
template <> class TSerializer<std::wstring>: public TVectorSerializer<std::wstring, wchar_t> {};
template <class K, class V> class TSerializer<std::map<K, V> >: public TMapSerializer<std::map<K, V>, K, V > {};
template <class K, class V, class H> class TSerializer<std::unordered_map<K, V, H> >: public TMapSerializer<std::unordered_map<K, V, H>, K, V > {};
template <class T> class TSerializer<std::set<T> >: public TSetSerializer<std::set<T>, T > {};
template <class T> class TSerializer<std::unordered_set<T> >: public TSetSerializer<std::unordered_set<T>, T > {};
template <class T>
class TPodSerializer {
public:
static inline void Save(std::ostream& out, const T& object) {
out.write((const char*)(&object), sizeof(T));
}
static inline void Load(std::istream& in, T& object) {
in.read((char*)(&object), sizeof(T));
}
};
template<class T>
class TSerializer<T, typename std::enable_if<!std::is_class<T>::value>::type>: public TPodSerializer<T> {};
template <class T>
static inline void Save(std::ostream& out, const T& t) {
TSerializer<T>::Save(out, t);
}
template<class T, class... Args>
static inline void Save(std::ostream& out, T first, Args... args) {
NSaveLoad::Save(out, first);
NSaveLoad::Save(out, args...);
}
template <class T>
static inline void Load(std::istream& in, T& t) {
TSerializer<T>::Load(in, t);
}
template <class T, class... Args>
static inline void Load(std::istream& in, T& first, Args&... args) {
NSaveLoad::Load(in, first);
NSaveLoad::Load(in, args...);
}
#define SAVELOAD(...) \
inline virtual void Save(std::ostream& out) const { \
NSaveLoad::Save(out, __VA_ARGS__); \
} \
\
inline virtual void Load(std::istream& in) { \
NSaveLoad::Load(in, __VA_ARGS__); \
}
struct membuf: std::streambuf {
membuf(char const* base, size_t size) {
char* p(const_cast<char*>(base));
this->setg(p, p, p + size);
}
};
struct imemstream: virtual membuf, std::istream {
imemstream(char const* base, size_t size)
: membuf(base, size)
, std::istream(static_cast<std::streambuf*>(this)) {
}
};
#define SAVELOAD_POD(TypeName) template <> class TSerializer<TypeName>: public TPodSerializer<TypeName> {};
} // NSaveLoad
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.