commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
bc4dc5794f4309df697fdb38e21ab1df6bc9d354
|
src/import/generic/memory/lib/utils/shared/mss_generic_consts.H
|
src/import/generic/memory/lib/utils/shared/mss_generic_consts.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/shared/mss_generic_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_consts.H
/// @brief Common constants to be shared
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CONSTS_H_
#define _MSS_GENERIC_CONSTS_H_
#include <cstdint>
namespace mss
{
///
/// @brief FFDC generic codes
///
enum generic_ffdc_codes
{
// Starting at 0x1%%% to avoid
// any collisions with values
// from controller specific ffdc codes
SET_ATTR_DIMM_TYPE = 0x1000,
SET_ATTR_DRAM_GEN = 0x1001,
SET_ATTR_HYBRID = 0x1002,
SET_ATTR_HYBRID_MEDIA = 0x1003,
SET_ATTR_MASTER_RANKS = 0x1004,
PRE_DATA_ENGINE_CTOR = 0x1005,
EXTRACT_SPD_FLD = 0x1006,
SPD_READER = 0x1007,
BASE_CNFG_MAKE_OBJ = 0x1008,
DIMM_MODULE_MAKE_OBJ = 0x1009,
CREATE_BASE_CNFG_FACTORY = 0x100A,
CREATE_MODULE_FACTORY = 0x100B,
GET_TIMEBASES_FTB = 0x100F,
GET_TIMEBASES_MTB = 0x1010,
};
///
/// @brief DRAM generation selector
///
enum device_type
{
DDR4 = 0x0c,
};
enum rev : uint8_t
{
V1_0 = 0x10, ///< represents Rev 1.0
V1_1 = 0x11, ///< represents Rev 1.1
V1_2 = 0x12, ///< represents Rev 1.2
// These module revisions can vary independently
// so we track the largest decoded revision here.
GEN_SEC_MAX = V1_1,
RDIMM_MAX = V1_1,
LRDIMM_MAX = V1_2,
};
///
/// @brief SPD module parameters
/// @note helps distinguish SPD decoder sections
///
enum parameters
{
BASE_CNFG,
RDIMM_MODULE,
LRDIMM_MODULE,
};
}// mss
#endif
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/shared/mss_generic_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mss_generic_consts.H
/// @brief Common constants to be shared
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_GENERIC_CONSTS_H_
#define _MSS_GENERIC_CONSTS_H_
#include <cstdint>
namespace mss
{
///
/// @brief Common conversions
///
enum conversions
{
CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano
CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro
MHZ_TO_KHZ = 1000,
SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times
NIBBLES_PER_BYTE = 2,
BITS_PER_NIBBLE = 4,
BITS_PER_BYTE = 8,
};
///
/// @brief FFDC generic codes
///
enum generic_ffdc_codes
{
// Starting at 0x1%%% to avoid
// any collisions with values
// from controller specific ffdc codes
SET_ATTR_DIMM_TYPE = 0x1000,
SET_ATTR_DRAM_GEN = 0x1001,
SET_ATTR_HYBRID = 0x1002,
SET_ATTR_HYBRID_MEDIA = 0x1003,
SET_ATTR_MASTER_RANKS = 0x1004,
PRE_DATA_ENGINE_CTOR = 0x1005,
EXTRACT_SPD_FLD = 0x1006,
SPD_READER = 0x1007,
BASE_CFG_PARAM_SELECT = 0x1008,
DIMM_MODULE_PARAM_SELECT = 0x1009,
BASE_CFG_FACTORY = 0x100A,
DIMM_MODULE_FACTORY = 0x100B,
GET_TAAMIN = 0x100C,
GET_TCKMIN = 0x100D,
GET_TCKMAX = 0x100E,
GET_TIMEBASES_FTB = 0x100F,
GET_TIMEBASES_MTB = 0x1010,
GET_SUPPORTED_REV = 0x1011,
TRASMIN = 0x1012,
TRCMIN = 0x1013,
TRFC1MIN = 0x1014,
TRFC2MIN = 0x1015,
TRFC4MIN = 0x1016,
TFAWMIN = 0x1017,
TWTR_S_MIN = 0x1018,
TWRMIN = 0x1019,
TWTR_L_MIN = 0x101A,
DEVICE_TYPE = 0x101B,
BASE_MODULE_TYPE = 0x101C,
};
///
/// @brief Supported proc types
///
enum proc_type
{
NIMBUS,
AXONE,
};
///
/// @brief JEDEC supported DDR4 speeds
///
enum ddr4_dimm_speeds
{
DIMM_SPEED_1600 = 1600,
DIMM_SPEED_1866 = 1866,
DIMM_SPEED_2133 = 2133,
DIMM_SPEED_2400 = 2400,
DIMM_SPEED_2666 = 2666,
DIMM_SPEED_2933 = 2933,
DIMM_SPEED_3200 = 3200,
};
namespace spd
{
///
/// @brief SPD revisions - not tied any particular module
///
enum rev : uint8_t
{
V1_0 = 0x10, ///< represents Rev 1.0
V1_1 = 0x11, ///< represents Rev 1.1
V1_2 = 0x12, ///< represents Rev 1.2
// These module revisions can vary independently
// so we track the largest decoded revision here.
GEN_SEC_MAX = V1_1,
RDIMM_MAX = V1_1,
LRDIMM_MAX = V1_2,
};
///
/// @brief SPD module parameters
/// @note helps distinguish SPD decoder sections
///
enum parameters
{
UNINITIALIZED,
BASE_CNFG,
RDIMM_MODULE,
LRDIMM_MODULE,
NVDIMM_MODULE,
};
///
/// @brief DRAM generation selector
/// @note values set to SPD settings
///
enum device_type
{
DDR4 = 0x0c,
};
///
/// @brief DIMM type selector
/// @note values set to SPD settings
///
enum dimm_type
{
RDIMM = 0b0001,
LRDIMM = 0b0100,
};
enum guard_band : uint16_t
{
// Used for caclulating spd timing values - from JEDEC rounding algorithm
// Correction factor is 1% (for DDR3) or 2.5% (for DDR4)
// when doing integer math, we add-in the inverse correction factor
// Formula used for derivation:
// Guardband = 1000 * (1000* correction_factor) - 1
INVERSE_DDR4_CORRECTION_FACTOR = 974, ///< DDR4 correction factor
};
}// spd
}// mss
#endif
|
Remove Nimbus dependencies from the SPD decoder
|
Remove Nimbus dependencies from the SPD decoder
Created a new pre_data_engine to set preliminary data
needed before eff_config. Moved SPD to attribute mapping
to eff_dimm structure and away from the SPD decoder to make
it reusable for future memory controllers. Updated bugs in
unit tests. Added SPD factory classes.
This is only needed for Axone.
Change-Id: I8f0cf8be4e947fd701344739e75344acdee246eb
Original-Change-Id: Ief0a479ee1c7a4dab852ffb18b595564c0125e35
Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/58611
Tested-by: FSP CI Jenkins <[email protected]>
Dev-Ready: ANDRE A. MARIN <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: HWSV CI <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: STEPHEN GLANCY <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
114d081049157b2c27561dc681155988da75aa30
|
fbhackcup/2019/round1/16/16.cpp
|
fbhackcup/2019/round1/16/16.cpp
|
/* ========================================
* File Name : 16.cpp
* Creation Date : 09-08-2020
* Last Modified : Út 11. srpna 2020, 19:06:09
* Created By : Karel Ha <[email protected]>
* URL : https://www.facebook.com/codingcompetitions/hacker-cup/2019/round-1/problems/B
* Points Gained (in case of online contest) :
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
#define MOD 1000000007
#define UNDEF MOD
#define N_MAX 1000000
vector<int> powers(N_MAX + 1, UNDEF);
int mod_power(int base, int exp) {
powers[0] = 1;
FOR(i, 1, exp + 1) {
if (powers[i] == UNDEF) {
powers[i] = (powers[i-1] * base) % MOD;
// cout << endl; MSG(i) MSG(powers[i])
}
}
return powers[exp];
}
int get_result(const string & V, int K) {
int N = V.size();
int init_balance = 0; // n_B - n_A
int balance = 0;
FOR(i, N-K, N) {
init_balance += (V[i] == 'A') ? (-1) : 1;
balance = max(balance, init_balance);
// MSG(init_balance)
}
// cout << endl << "inital balance: "; MSG(balance)
int result = 0;
FOR(j, N-K, 0) {
// MSG(j) MSG(V[j])
// cout << "0: "; MSG(balance)
balance = max(balance, 0);
balance += (V[j] == 'A') ? (-1) : 1;
// cout << "1: "; MSG(balance) MSG(result)
if (balance > K) { // over threshold
balance -= 2; // swap 'B' for 'A'
result += mod_power(2, j + 1); // pay the charge
// MSG(mod_power(2, j + 1))
result %= MOD; // TODO: use memo table of pows
}
// cout << "2: "; MSG(balance) MSG(result)
}
return result;
}
int main() {
int T;
cin >> T;
// MSG(T)
REP(t,T) {
int N, K;
cin >> N >> K;
// MSG(N) MSG(K)
string V;
V.reserve(N);
cin >> V;
// MSG(V) cout << endl;
cout << "Case #" << t+1 << ": " << get_result(V, K) << endl;
}
return 0;
}
|
/* ========================================
* File Name : 16.cpp
* Creation Date : 09-08-2020
* Last Modified : St 12. srpna 2020, 22:27:49
* Created By : Karel Ha <[email protected]>
* URL : https://www.facebook.com/codingcompetitions/hacker-cup/2019/round-1/problems/B
* Points Gained (in case of online contest) :
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
#define MOD 1000000007
#define UNDEF MOD
#define N_MAX 1000000
vector<int> powers(N_MAX + 1, UNDEF);
int mod_power(int base, int exp) {
if (powers[exp] == UNDEF) {
powers[0] = 1;
FOR(i, 1, exp + 1) {
powers[i] = (powers[i-1] * base) % MOD;
// cout << endl; MSG(i) MSG(powers[i])
}
}
return powers[exp];
}
int get_result(const string & V, int K) {
int N = V.size();
int init_balance = 0; // n_B - n_A
int balance = 0;
FOR(i, N-K, N) {
init_balance += (V[i] == 'A') ? (-1) : 1;
balance = max(balance, init_balance);
// MSG(init_balance)
}
// cout << endl << "inital balance: "; MSG(balance)
int result = 0;
FOR(j, N-K, 0) {
// MSG(j) MSG(V[j])
// cout << "0: "; MSG(balance)
balance = max(balance, 0);
balance += (V[j] == 'A') ? (-1) : 1;
// cout << "1: "; MSG(balance) MSG(result)
if (balance > K) { // over threshold
balance -= 2; // swap 'B' for 'A'
result += mod_power(2, j + 1); // pay the charge
// MSG(mod_power(2, j + 1))
result %= MOD; // TODO: use memo table of pows
}
// cout << "2: "; MSG(balance) MSG(result)
}
return result;
}
int main() {
int T;
cin >> T;
// MSG(T)
REP(t,T) {
int N, K;
cin >> N >> K;
// MSG(N) MSG(K)
string V;
V.reserve(N);
cin >> V;
// MSG(V) cout << endl;
cout << "Case #" << t+1 << ": " << get_result(V, K) << endl;
}
return 0;
}
|
Use stored values when memoized already
|
Fix: Use stored values when memoized already
- Fb Hackercup '19 Round 1, 16
Signed-off-by: Karel Ha <[email protected]>
|
C++
|
mit
|
mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming,mathemage/CompetitiveProgramming
|
7d34a513f5ca2a501a4b33894bea86a28d0bf1e6
|
bitreader/include/ruberoid/bitreader/bitreader.hpp
|
bitreader/include/ruberoid/bitreader/bitreader.hpp
|
#pragma once
#include <cstdint>
#include <cstddef>
#include <type_traits>
#include <cassert>
#include <stdexcept>
template<typename T>
using if_unsigned_integral = std::enable_if_t<std::is_unsigned_v<T> && std::is_integral_v<T>, T>;
template<typename T>
using if_signed_integral = std::enable_if_t<std::is_signed_v<T> && std::is_integral_v<T>, T>;
template<typename T>
using if_floating_point = std::enable_if_t<std::is_floating_point_v<T>, T>;
template<typename T>
using if_bit_readable = std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, T>;
namespace rb::common {
//--------------------------------------------------------------------------
template<typename T>
struct bit_read_helper
{
static constexpr const size_t max_bits = 8 * sizeof(T);
static constexpr const size_t min_bits = 0;
static constexpr const bool is_signed = std::is_signed_v<T>;
};
//--------------------------------------------------------------------------
template<typename T>
struct floating_point_bit_read_helper
{
static constexpr const size_t max_bits = 8 * sizeof(T);
static constexpr const size_t min_bits = 8 * sizeof(T);
static constexpr const bool is_signed = std::is_signed_v<T>;
};
//--------------------------------------------------------------------------
template<> struct bit_read_helper<float>: floating_point_bit_read_helper<float> {};
template<> struct bit_read_helper<double>: floating_point_bit_read_helper<double> {};
template<> struct bit_read_helper<long double>: floating_point_bit_read_helper<long double> {};
//--------------------------------------------------------------------------
class bitreader {
public:
bitreader() = default;
//----------------------------------------------------------------------
void set_data(const uint8_t* data, size_t length) {
_data = data;
_data_end = data + length;
_state.ptr = data;
_next(_state);
}
//----------------------------------------------------------------------
template<typename T>
if_unsigned_integral<T> read(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_read(_state, bits, ret);
return ret;
}
//----------------------------------------------------------------------
template<typename T>
if_signed_integral<T> read(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_read(_state, bits, ret);
return _sign_extend(ret, bits);
}
//----------------------------------------------------------------------
template<typename T>
if_unsigned_integral<T> peek(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_peek(_state, bits, ret);
return ret;
}
//----------------------------------------------------------------------
template<typename T>
if_signed_integral<T> peek(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_peek(_state, bits, ret);
return _sign_extend(ret, bits);
}
//----------------------------------------------------------------------
size_t position() const
{
return _position(_state);
}
//----------------------------------------------------------------------
size_t available() const
{
return _available(_state);
}
//----------------------------------------------------------------------
void seek(size_t bitpos)
{
size_t diff = _data_end - _data;
if (diff*8 < bitpos) {
throw std::runtime_error("Can't seek beyond bitstream size");
}
_state.ptr = _data;
_skip(_state, bitpos);
}
//----------------------------------------------------------------------
void align(size_t bits)
{
_align(_state, bits);
}
//----------------------------------------------------------------------
void skip(size_t bits)
{
_skip(_state, bits);
}
private:
//----------------------------------------------------------------------
struct internal_state {
uint64_t buffer = 0;
size_t shift = 0;
const uint8_t* ptr = nullptr;
};
//----------------------------------------------------------------------
template<typename T>
T _sign_extend(T raw, size_t bits)
{
T m = 1U << (bits - 1);
return (raw ^ m) - m;
}
//----------------------------------------------------------------------
void _next(internal_state& state) const
{
size_t available = std::min<size_t>(
sizeof(state.buffer),
_data_end - state.ptr);
size_t to_read = available;
while (to_read) {
state.buffer <<= 8;
state.buffer |= *state.ptr;
++state.ptr;
--to_read;
}
state.shift = 8 * available;
}
//----------------------------------------------------------------------
void _skip(internal_state& state, size_t bits) const
{
if (_available(state) < bits) {
throw std::runtime_error("Cannot skip beyond end of bitstream");
}
if (bits < state.shift) {
state.shift -= bits;
} else if (bits == state.shift) {
_next(state);
} else {
size_t to_skip = bits - state.shift;
state.shift = 0;
state.ptr += to_skip / 8;
_next(state);
state.shift -= to_skip % 8;
}
}
//----------------------------------------------------------------------
size_t _position(const internal_state& state) const
{
return (_state.ptr - _data) * 8 - state.shift;
}
//----------------------------------------------------------------------
size_t _available(const internal_state& state) const
{
return (_data_end - state.ptr) * 8 + state.shift;
}
//----------------------------------------------------------------------
void _align(internal_state& state, size_t bits) const
{
size_t advance = _position(state) % bits;
if (advance) {
_skip(state, advance);
}
}
//----------------------------------------------------------------------
template<typename T>
static constexpr T _mask(size_t bits)
{
return (bits == sizeof(T)*8) ? (~0) : ((T(1) << bits) - 1);
}
//----------------------------------------------------------------------
template<typename T>
void _elementary_read(internal_state& state, size_t bits, T& ret) const
{
state.shift -= bits;
ret |= (state.buffer >> state.shift) & _mask<T>(bits);
}
//----------------------------------------------------------------------
template<typename T>
void _read(internal_state& state, size_t bits, T& ret) const
{
if (_available(state) < bits) {
throw std::runtime_error("Cannot read beyond the bitstream data");
}
if (bits < state.shift) {
_elementary_read(state, bits, ret);
} else if (bits == state.shift) {
_elementary_read(state, bits, ret);
_next(state);
} else {
bits -= state.shift;
_elementary_read(state, state.shift, ret);
ret <<= bits;
_next(state);
_elementary_read(state, bits, ret);
}
}
//----------------------------------------------------------------------
template<typename T>
void _peek(internal_state& state, size_t bits, T& ret) const
{
internal_state temporary = state;
_read(temporary, bits, ret);
}
//----------------------------------------------------------------------
template <typename T, size_t Size>
constexpr void _validate_read_static() const
{
static_assert(Size <= bit_read_helper<T>::max_bits);
static_assert(Size >= bit_read_helper<T>::min_bits);
}
//----------------------------------------------------------------------
template <typename T>
void _validate_read_dynamic(size_t size) const
{
assert(size <= bit_read_helper<T>::max_bits);
assert(size >= bit_read_helper<T>::min_bits);
}
internal_state _state;
const uint8_t* _data;
const uint8_t* _data_end;
};
}
|
#pragma once
#include <cstdint>
#include <cstddef>
#include <type_traits>
#include <cassert>
#include <stdexcept>
template<typename T>
using if_unsigned_integral = std::enable_if_t<std::is_unsigned_v<T> && std::is_integral_v<T>, T>;
template<typename T>
using if_signed_integral = std::enable_if_t<std::is_signed_v<T> && std::is_integral_v<T>, T>;
template<typename T>
using if_floating_point = std::enable_if_t<std::is_floating_point_v<T>, T>;
template<typename T>
using if_bit_readable = std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, T>;
namespace rb::common {
//--------------------------------------------------------------------------
template<typename T>
struct bit_read_helper
{
static constexpr const size_t max_bits = 8 * sizeof(T);
static constexpr const size_t min_bits = 0;
static constexpr const bool is_signed = std::is_signed_v<T>;
};
//--------------------------------------------------------------------------
template<typename T>
struct floating_point_bit_read_helper
{
static constexpr const size_t max_bits = 8 * sizeof(T);
static constexpr const size_t min_bits = 8 * sizeof(T);
static constexpr const bool is_signed = std::is_signed_v<T>;
};
//--------------------------------------------------------------------------
template<> struct bit_read_helper<float>: floating_point_bit_read_helper<float> {};
template<> struct bit_read_helper<double>: floating_point_bit_read_helper<double> {};
template<> struct bit_read_helper<long double>: floating_point_bit_read_helper<long double> {};
//--------------------------------------------------------------------------
class bitreader {
public:
bitreader() = default;
//----------------------------------------------------------------------
void set_data(const uint8_t* data, size_t length) {
_data = data;
_data_end = data + length;
_state.ptr = data;
_next(_state);
}
//----------------------------------------------------------------------
template<typename T>
if_unsigned_integral<T> read(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_read(_state, bits, ret);
return ret;
}
//----------------------------------------------------------------------
template<typename T>
if_signed_integral<T> read(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_read(_state, bits, ret);
return _sign_extend(ret, bits);
}
//----------------------------------------------------------------------
template<typename T>
if_unsigned_integral<T> peek(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_peek(_state, bits, ret);
return ret;
}
//----------------------------------------------------------------------
template<typename T>
if_signed_integral<T> peek(size_t bits)
{
_validate_read_dynamic<T>(bits);
T ret = T(0);
_peek(_state, bits, ret);
return _sign_extend(ret, bits);
}
//----------------------------------------------------------------------
size_t position() const
{
return _position(_state);
}
//----------------------------------------------------------------------
size_t available() const
{
return _available(_state);
}
//----------------------------------------------------------------------
void seek(size_t bitpos)
{
size_t diff = _data_end - _data;
if (diff*8 < bitpos) {
throw std::runtime_error("Can't seek beyond bitstream size");
}
_state.ptr = _data;
_skip(_state, bitpos);
}
//----------------------------------------------------------------------
void align(size_t bits)
{
_align(_state, bits);
}
//----------------------------------------------------------------------
void skip(size_t bits)
{
_skip(_state, bits);
}
private:
//----------------------------------------------------------------------
struct internal_state {
uint64_t buffer = 0;
size_t shift = 0;
const uint8_t* ptr = nullptr;
};
//----------------------------------------------------------------------
template<typename T>
T _sign_extend(T raw, size_t bits)
{
T m = 1U << (bits - 1);
return (raw ^ m) - m;
}
//----------------------------------------------------------------------
void _next(internal_state& state) const
{
size_t available = std::min<size_t>(
sizeof(state.buffer),
_data_end - state.ptr);
size_t to_read = available;
while (to_read) {
state.buffer <<= 8;
state.buffer |= *state.ptr;
++state.ptr;
--to_read;
}
state.shift = 8 * available;
}
//----------------------------------------------------------------------
void _skip(internal_state& state, size_t bits) const
{
if (_available(state) < bits) {
throw std::runtime_error("Cannot skip beyond end of bitstream");
}
if (bits < state.shift) {
state.shift -= bits;
} else if (bits == state.shift) {
_next(state);
} else {
size_t to_skip = bits - state.shift;
state.shift = 0;
state.ptr += to_skip / 8;
_next(state);
state.shift -= to_skip % 8;
}
}
//----------------------------------------------------------------------
size_t _position(const internal_state& state) const
{
return (_state.ptr - _data) * 8 - state.shift;
}
//----------------------------------------------------------------------
size_t _available(const internal_state& state) const
{
return (_data_end - state.ptr) * 8 + state.shift;
}
//----------------------------------------------------------------------
void _align(internal_state& state, size_t bits) const
{
// TODO: Rewrite
size_t advance = (bits - (_position(state) % bits)) % bits;
if (advance) {
_skip(state, advance);
}
}
//----------------------------------------------------------------------
template<typename T>
static constexpr T _mask(size_t bits)
{
return (bits == sizeof(T)*8) ? (~0) : ((T(1) << bits) - 1);
}
//----------------------------------------------------------------------
template<typename T>
void _elementary_read(internal_state& state, size_t bits, T& ret) const
{
state.shift -= bits;
ret |= (state.buffer >> state.shift) & _mask<T>(bits);
}
//----------------------------------------------------------------------
template<typename T>
void _read(internal_state& state, size_t bits, T& ret) const
{
if (_available(state) < bits) {
throw std::runtime_error("Cannot read beyond the bitstream data");
}
if (bits < state.shift) {
_elementary_read(state, bits, ret);
} else if (bits == state.shift) {
_elementary_read(state, bits, ret);
_next(state);
} else {
bits -= state.shift;
_elementary_read(state, state.shift, ret);
ret <<= bits;
_next(state);
_elementary_read(state, bits, ret);
}
}
//----------------------------------------------------------------------
template<typename T>
void _peek(internal_state& state, size_t bits, T& ret) const
{
internal_state temporary = state;
_read(temporary, bits, ret);
}
//----------------------------------------------------------------------
template <typename T, size_t Size>
constexpr void _validate_read_static() const
{
static_assert(Size <= bit_read_helper<T>::max_bits);
static_assert(Size >= bit_read_helper<T>::min_bits);
}
//----------------------------------------------------------------------
template <typename T>
void _validate_read_dynamic(size_t size) const
{
assert(size <= bit_read_helper<T>::max_bits);
assert(size >= bit_read_helper<T>::min_bits);
}
internal_state _state;
const uint8_t* _data;
const uint8_t* _data_end;
};
}
|
Fix align
|
Fix align
|
C++
|
bsd-3-clause
|
axethrower/ruberoid
|
9aa0b7ac8996b3bfdcfcb2e250c721544ba8be00
|
include/tudocomp/compressors/esacomp/decoding/LazySuccinctListBuffer.hpp
|
include/tudocomp/compressors/esacomp/decoding/LazySuccinctListBuffer.hpp
|
#pragma once
#include <vector>
#include <sdsl/int_vector.hpp>
#include <sdsl/rank_support.hpp>
#include <tudocomp/def.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/compressors/esacomp/decoding/DecodeQueueListBuffer.hpp>
#include <algorithm>
namespace tdc {
namespace esacomp {
class LazyDecoder {
Env& m_env;
IntVector<uliteral_t>& m_buffer;
const sdsl::bit_vector m_bv;
const sdsl::bit_vector::rank_1_type m_rank;
const len_t m_empty_entries;
len_t**const m_fwd = nullptr;
tdc_stats(len_t m_longest_chain = 0);
tdc_stats(len_t m_current_chain = 0);
public:
LazyDecoder(Env& env, IntVector<uliteral_t>& buffer)
: m_env(env)
, m_buffer { buffer }
, m_bv ( [&buffer] () -> sdsl::bit_vector {
sdsl::bit_vector bv { buffer.size(),0 };
for(len_t i = 0; i < buffer.size(); ++i) {
if(buffer[i]) continue;
bv[i] = 1;
}
return bv;
}() )
, m_rank { &m_bv }
//, m_empty_entries { static_cast<len_t>( buffer.size()) }
, m_empty_entries { static_cast<len_t>(std::count_if(buffer.cbegin(), buffer.cend(), [] (const uliteral_t& i) { return i == 0; })) }
, m_fwd { new len_t*[m_empty_entries+1] }
{
std::fill(m_fwd,m_fwd+m_empty_entries,nullptr);
}
len_t rank(len_t i) const {
DCHECK(m_bv[i]);
return m_rank.rank(i+1);
}
void decode(const std::vector<len_t>& m_target_pos, const std::vector<len_t>& m_source_pos, const std::vector<len_t>& m_length) {
const len_t factors = m_source_pos.size();
m_env.log_stat("factors", factors);
m_env.begin_stat_phase("Decoding Factors");
for(len_t j = 0; j < factors; ++j) {
const len_t& target_position = m_target_pos[j];
const len_t& source_position = m_source_pos[j];
const len_t& factor_length = m_length[j];
for(len_t i = 0; i < factor_length; ++i) {
if(m_buffer[source_position+i]) {
decode_literal_at(target_position+i, m_buffer[source_position+i]);
} else {
DCHECK_EQ(m_bv[source_position+i],1);
len_t*& bucket = m_fwd[rank(source_position+i)];
if(bucket == nullptr) {
bucket = new len_t[2];
bucket[0] = 2;
bucket[1] = target_position+i;
}
else
{ // this block implements the call of m_fwd[src]->push_back(m_cursor);
++bucket[0]; // increase the size of a bucket only by one!
bucket = (len_t*) realloc(bucket, sizeof(len_t)*bucket[0]);
bucket[bucket[0]-1] = target_position+i;
}
}
}
if(tdc_stats((j+1) % ((factors+5)/5) == 0 )) {
m_env.end_stat_phase();
m_env.begin_stat_phase("Decoding Factors at position " + std::to_string(target_position));
}
}
m_env.end_stat_phase();
}
inline void decode_literal_at(len_t pos, uliteral_t c) {
tdc_stats(++m_current_chain);
tdc_stats(m_longest_chain = std::max(m_longest_chain, m_current_chain));
DCHECK(m_buffer[pos] == 0 || m_buffer[pos] == c) << "would write " << c << " to mbuffer[" << pos << "] = " << m_buffer[pos];
m_buffer[pos] = c;
DCHECK(c != 0 || pos == m_buffer.size()-1); // we assume that the text to restore does not contain a NULL-byte but at its very end
if(m_bv[pos] == 1) {
const len_t rankpos = rank(pos);
DCHECK_LE(rankpos, m_empty_entries);
if(m_fwd[rankpos] != nullptr) {
const len_t*const& bucket = m_fwd[rankpos];
for(size_t i = 1; i < bucket[0]; ++i) {
decode_literal_at(bucket[i], c); // recursion
}
delete [] m_fwd[rankpos];
m_fwd[rankpos] = nullptr;
}
}
tdc_stats(--m_current_chain);
}
inline len_t longest_chain() const {
return m_longest_chain;
}
~LazyDecoder() {
DCHECK(m_fwd != nullptr);
for(size_t i = 0; i < m_empty_entries; ++i) {
if(m_fwd[i] == nullptr) continue;
delete [] m_fwd[i];
}
delete [] m_fwd;
}
};
class LazySuccinctListBuffer : public Algorithm {
public:
inline static Meta meta() {
Meta m("esadec", "LazySuccinctListBuffer");
m.option("lazy").dynamic("0");
return m;
}
inline void decode_lazy() {
size_t lazy = m_lazy;
while(lazy > 0) {
decode_lazy_();
--lazy;
}
}
inline void decode_eagerly() {
env().begin_stat_phase("Initialize Bit Vector");
LazyDecoder decoder(this->env(),m_buffer);
env().end_stat_phase();
decoder.decode(m_target_pos, m_source_pos, m_length);
tdc_stats(m_longest_chain = decoder.longest_chain());
}
private:
inline void decode_lazy_() {
const len_t factors = m_source_pos.size();
for(len_t j = 0; j < factors; ++j) {
const len_t& target_position = m_target_pos[j];
const len_t& source_position = m_source_pos[j];
const len_t& factor_length = m_length[j];
for(len_t i = 0; i < factor_length; ++i) {
m_buffer[target_position+i] = m_buffer[source_position+i];
}
}
}
const size_t m_lazy; // number of lazy rounds
len_t m_cursor;
IntVector<uliteral_t> m_buffer;
//storing factors
std::vector<len_t> m_target_pos;
std::vector<len_t> m_source_pos;
std::vector<len_t> m_length;
tdc_stats(len_t m_longest_chain = 0);
public:
LazySuccinctListBuffer(LazySuccinctListBuffer&& other)
: Algorithm(std::move(*this))
, m_lazy(std::move(other.m_lazy))
, m_cursor(std::move(other.m_cursor))
, m_buffer(std::move(other.m_buffer))
{ }
inline LazySuccinctListBuffer(Env&& env, len_t size)
: Algorithm(std::move(env))
, m_lazy(this->env().option("lazy").as_integer())
, m_cursor(0)
, m_buffer(size,0)
{ }
inline void decode_literal(uliteral_t c) {
m_buffer[m_cursor++] = c;
DCHECK(c != 0 || m_cursor == m_buffer.size()); // we assume that the text to restore does not contain a NULL-byte but at its very end
}
inline void decode_factor(const len_t source_position, const len_t factor_length) {
bool factor_stored = false;
for(len_t i = 0; i < factor_length; ++i) {
const len_t src_pos = source_position+i;
if(m_buffer[src_pos]) {
m_buffer[m_cursor] = m_buffer[src_pos];
}
else if(factor_stored == false) {
factor_stored = true;
m_target_pos.push_back(m_cursor);
m_source_pos.push_back(src_pos);
m_length.push_back(factor_length-i);
}
++m_cursor;
}
}
inline len_t longest_chain() const {
return m_longest_chain;
}
inline void write_to(std::ostream& out) const {
for(auto c : m_buffer) out << c;
}
};
}} //ns
|
#pragma once
#include <vector>
#include <sdsl/int_vector.hpp>
#include <sdsl/rank_support.hpp>
#include <tudocomp/def.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/compressors/esacomp/decoding/DecodeQueueListBuffer.hpp>
#include <algorithm>
namespace tdc {
namespace esacomp {
class LazyDecoder {
Env& m_env;
IntVector<uliteral_t>& m_buffer;
const sdsl::bit_vector m_bv;
const sdsl::bit_vector::rank_1_type m_rank;
const len_t m_empty_entries;
len_t**const m_fwd = nullptr;
tdc_stats(len_t m_longest_chain = 0);
tdc_stats(len_t m_current_chain = 0);
public:
LazyDecoder(Env& env, IntVector<uliteral_t>& buffer)
: m_env(env)
, m_buffer { buffer }
, m_bv ( [&buffer] () -> sdsl::bit_vector {
sdsl::bit_vector bv { buffer.size(),0 };
for(len_t i = 0; i < buffer.size(); ++i) {
if(buffer[i]) continue;
bv[i] = 1;
}
return bv;
}() )
, m_rank { &m_bv }
//, m_empty_entries { static_cast<len_t>( buffer.size()) }
, m_empty_entries { static_cast<len_t>(std::count_if(buffer.cbegin(), buffer.cend(), [] (const uliteral_t& i) { return i == 0; })) }
, m_fwd { new len_t*[m_empty_entries+1] }
{
std::fill(m_fwd,m_fwd+m_empty_entries,nullptr);
}
len_t rank(len_t i) const {
DCHECK(m_bv[i]);
return m_rank.rank(i+1);
}
void decode(const std::vector<len_t>& m_target_pos, const std::vector<len_t>& m_source_pos, const std::vector<len_t>& m_length) {
const len_t factors = m_source_pos.size();
m_env.log_stat("factors", factors);
m_env.begin_stat_phase("Decoding Factors");
for(len_t j = 0; j < factors; ++j) {
const len_t& target_position = m_target_pos[j];
const len_t& source_position = m_source_pos[j];
const len_t& factor_length = m_length[j];
for(len_t i = 0; i < factor_length; ++i) {
if(m_buffer[source_position+i]) {
decode_literal_at(target_position+i, m_buffer[source_position+i]);
} else {
DCHECK_EQ(m_bv[source_position+i],1);
len_t*& bucket = m_fwd[rank(source_position+i)];
if(bucket == nullptr) {
bucket = new len_t[2];
bucket[0] = 2;
bucket[1] = target_position+i;
}
else
{ // this block implements the call of m_fwd[src]->push_back(m_cursor);
++bucket[0]; // increase the size of a bucket only by one!
bucket = (len_t*) realloc(bucket, sizeof(len_t)*bucket[0]);
bucket[bucket[0]-1] = target_position+i;
}
}
}
if(tdc_stats((j+1) % ((factors+5)/5) == 0 )) {
m_env.end_stat_phase();
m_env.begin_stat_phase("Decoding Factors at position " + std::to_string(target_position));
}
}
m_env.end_stat_phase();
}
inline void decode_literal_at(len_t pos, uliteral_t c) {
tdc_stats(++m_current_chain);
tdc_stats(m_longest_chain = std::max(m_longest_chain, m_current_chain));
DCHECK(m_buffer[pos] == 0 || m_buffer[pos] == c) << "would write " << c << " to mbuffer[" << pos << "] = " << m_buffer[pos];
m_buffer[pos] = c;
DCHECK(c != 0 || pos == m_buffer.size()-1); // we assume that the text to restore does not contain a NULL-byte but at its very end
if(m_bv[pos] == 1) {
const len_t rankpos = rank(pos);
DCHECK_LE(rankpos, m_empty_entries);
if(m_fwd[rankpos] != nullptr) {
const len_t*const& bucket = m_fwd[rankpos];
for(size_t i = 1; i < bucket[0]; ++i) {
decode_literal_at(bucket[i], c); // recursion
}
delete [] m_fwd[rankpos];
m_fwd[rankpos] = nullptr;
}
}
tdc_stats(--m_current_chain);
}
inline len_t longest_chain() const {
return m_longest_chain;
}
~LazyDecoder() {
DCHECK(m_fwd != nullptr);
for(size_t i = 0; i < m_empty_entries; ++i) {
if(m_fwd[i] == nullptr) continue;
delete [] m_fwd[i];
}
delete [] m_fwd;
}
};
class LazySuccinctListBuffer : public Algorithm {
public:
inline static Meta meta() {
Meta m("esadec", "LazySuccinctListBuffer");
m.option("lazy").dynamic("0");
return m;
}
inline void decode_lazy() {
size_t lazy = m_lazy;
while(lazy > 0) {
decode_lazy_();
--lazy;
}
}
inline void decode_eagerly() {
{
env().begin_stat_phase("Initialize Bit Vector");
LazyDecoder decoder(this->env(),m_buffer);
env().end_stat_phase();
decoder.decode(m_target_pos, m_source_pos, m_length);
tdc_stats(m_longest_chain = decoder.longest_chain());
env().begin_stat_phase("Destructor LazyDecoder");
}
env().end_stat_phase();
}
private:
inline void decode_lazy_() {
const len_t factors = m_source_pos.size();
for(len_t j = 0; j < factors; ++j) {
const len_t& target_position = m_target_pos[j];
const len_t& source_position = m_source_pos[j];
const len_t& factor_length = m_length[j];
for(len_t i = 0; i < factor_length; ++i) {
m_buffer[target_position+i] = m_buffer[source_position+i];
}
}
}
const size_t m_lazy; // number of lazy rounds
len_t m_cursor;
IntVector<uliteral_t> m_buffer;
//storing factors
std::vector<len_t> m_target_pos;
std::vector<len_t> m_source_pos;
std::vector<len_t> m_length;
tdc_stats(len_t m_longest_chain = 0);
public:
LazySuccinctListBuffer(LazySuccinctListBuffer&& other)
: Algorithm(std::move(*this))
, m_lazy(std::move(other.m_lazy))
, m_cursor(std::move(other.m_cursor))
, m_buffer(std::move(other.m_buffer))
{ }
inline LazySuccinctListBuffer(Env&& env, len_t size)
: Algorithm(std::move(env))
, m_lazy(this->env().option("lazy").as_integer())
, m_cursor(0)
, m_buffer(size,0)
{ }
inline void decode_literal(uliteral_t c) {
m_buffer[m_cursor++] = c;
DCHECK(c != 0 || m_cursor == m_buffer.size()); // we assume that the text to restore does not contain a NULL-byte but at its very end
}
inline void decode_factor(const len_t source_position, const len_t factor_length) {
bool factor_stored = false;
for(len_t i = 0; i < factor_length; ++i) {
const len_t src_pos = source_position+i;
if(m_buffer[src_pos]) {
m_buffer[m_cursor] = m_buffer[src_pos];
}
else if(factor_stored == false) {
factor_stored = true;
m_target_pos.push_back(m_cursor);
m_source_pos.push_back(src_pos);
m_length.push_back(factor_length-i);
}
++m_cursor;
}
}
inline len_t longest_chain() const {
return m_longest_chain;
}
inline void write_to(std::ostream& out) const {
for(auto c : m_buffer) out << c;
}
};
}} //ns
|
add last stat to LazySuccinctListBuffer.hpp
|
add last stat to LazySuccinctListBuffer.hpp
|
C++
|
apache-2.0
|
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
|
45a915954650b0c2f5752ae9e958a194d2483852
|
bridging/plugins/nest_plugin/nest_objects/nest.cpp
|
bridging/plugins/nest_plugin/nest_objects/nest.cpp
|
//******************************************************************
//
// Copyright 2017 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <time.h>
#include <stdio.h>
#include <iostream>
#include "nest.h"
#include "curlClient.h"
#include "nestDefs.h"
#include "rapidjson.h"
#include "document.h"
#include "stringbuffer.h"
#include "writer.h"
#include "JsonHelper.h"
#include "logger.h"
using namespace rapidjson;
using namespace OC::Bridging;
#define TAG "NEST"
Nest::Nest(const ACCESS_TOKEN &accessToken) : m_accessToken(accessToken), m_isAuthorized(false)
{
m_metaInfo.awayMode = eAWUndefined;
}
Nest::Nest() : m_isAuthorized(false) {}
void Nest::setAccessToken(const ACCESS_TOKEN &token)
{
m_accessToken = token;
}
Nest::AWAY_MODE Nest::getAwayMode(const std::string &value) const
{
if (NEST_HOME_TAG == value)
{
return eAWHome;
}
else if (NEST_AWAY_TAG == value)
{
return eAWAway;
}
return eAWUndefined;
}
std::string Nest::getTok()
{
return m_accessToken.accessToken;
}
bool Nest::isAuthorized()
{
if (!strlen(m_accessToken.accessToken))
{
OIC_LOG(ERROR, TAG, "Length of access token is zero");
return false;
}
std::string uri(NEST_BASE_URL);
uri += NEST_STRUCTURE_AUTH_STR + std::string(m_accessToken.accessToken);
OIC_LOG_V(INFO, TAG, "uri: %s", uri.c_str());
CurlClient cc = CurlClient(CurlClient::CurlMethod::GET, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "Curl GET Request operation failed. Error code %d", curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
if (MPM_RESULT_OK != parseStructureJsonResponse(response, m_metaInfo))
{
OIC_LOG(ERROR, TAG, "Parsing Json response failed on authorization");
return false;
}
return true;
}
MPMResult Nest::getAccessToken(std::string &authorizationCode, ACCESS_TOKEN &accessToken,
std::string &nest_client_id, std::string &nest_client_secret)
{
MPMResult result = MPM_RESULT_OK;
std::string uri(ACCESS_TOKEN_URL);
uri += NEST_CLIENT_ID_STR + nest_client_id;
uri += NEST_CODE_STR + authorizationCode;
uri += NEST_CLIENT_SECRET_STR + nest_client_secret;
uri += NEST_AUTH_CODE_STR;
CurlClient cc = CurlClient(CurlClient::CurlMethod::POST, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "Post for getting access token failed. Error code %d", curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
rapidjson::Document doc;
doc.SetObject();
if (!doc.Parse<0>(response.c_str()).HasParseError())
{
if (doc.HasMember("error"))
{
OIC_LOG(ERROR, TAG, "get error message from nest server");
return MPM_RESULT_INTERNAL_ERROR;
}
time_t expires = time(NULL);
expires += doc[NEST_VALIDITY_TAG].GetInt();
struct tm *expTime = localtime(&expires);
if (expTime != NULL)
{
char *chExpTime = asctime(expTime);
if (chExpTime != NULL)
{
OICStrcpy(accessToken.expires, NEST_ACCESS_TOKEN_EXPIRY - 1, chExpTime);
}
}
OICStrcpy(accessToken.accessToken, NEST_ACCESS_TOKEN_LEN - 1,
doc[NEST_ACCESS_TOKEN_TAG].GetString());
accessToken.grantTime = doc[NEST_VALIDITY_TAG].GetInt();
m_accessToken = accessToken;
m_isAuthorized = true;
}
else
{
result = MPM_RESULT_JSON_ERROR;
}
return result;
}
MPMResult Nest::parseStructureJsonResponse(std::string &json, META_INFO &meta)
{
MPMResult result = MPM_RESULT_NOT_AUTHORIZED;
rapidjson::Document doc;
doc.SetObject();
if (doc.Parse<0>(json.c_str()).HasParseError())
{
return MPM_RESULT_JSON_ERROR;
}
for (Value::ConstMemberIterator it = doc.MemberBegin(); it != doc.MemberEnd(); it++)
{
if (doc.HasMember("error"))
{
OIC_LOG(ERROR, TAG, "access token invalid");
break;
}
std::string name = it->name.GetString();
if (doc[name.c_str()].HasMember(NEST_AWAY_TAG) &&
doc[name.c_str()].HasMember(NEST_NAME_TAG))
{
meta.homeName = it->value[NEST_NAME_TAG].GetString();
meta.countryCode = it->value[NEST_COUNTRY_TAG].GetString();
meta.timeZone = it->value[NEST_TIMEZONE_TAG].GetString();
meta.structId = it->value[NEST_STRUCT_ID_TAG].GetString();
meta.awayMode =
getAwayMode(it->value[NEST_AWAY_TAG].GetString());
m_isAuthorized = true;
result = MPM_RESULT_OK;
}
}
return result;
}
MPMResult Nest::parseDevJsonResponse(std::string &json,
std::vector<std::shared_ptr<NestThermostat> > &thermostats)
{
rapidjson::Document doc;
doc.SetObject();
if (doc.Parse<0>(json.c_str()).HasParseError())
{
return MPM_RESULT_JSON_ERROR;
}
if (doc.HasMember(NEST_THERMOSTAT_TAG)
&& doc[NEST_THERMOSTAT_TAG].IsObject())
{
// The thermostat object holds each thermostat instance
for (Value::ConstMemberIterator it = doc[NEST_THERMOSTAT_TAG].MemberBegin();
it != doc[NEST_THERMOSTAT_TAG].MemberEnd(); it++)
{
// Extract the string representation from each thermostat instance
std::string json = JsonHelper::toString(it);
// Create the thermostat object, internally parse the JSON reprsentation
// and add it to the thermostat vector
std::shared_ptr<NestThermostat> thermostat = std::make_shared<NestThermostat>
(m_accessToken.accessToken, json);
thermostats.push_back(thermostat);
}
}
else
{
return MPM_RESULT_NOT_AUTHORIZED;
}
return MPM_RESULT_OK;
}
MPMResult Nest::getThermostats(std::vector<std::shared_ptr<NestThermostat> > &thermostats)
{
if (!strlen(m_accessToken.accessToken))
{
OIC_LOG(ERROR, TAG, "Not authorized");
return MPM_RESULT_NOT_AUTHORIZED;
}
MPMResult result = MPM_RESULT_INTERNAL_ERROR;
std::string uri(NEST_BASE_URL);
uri += NEST_DEVICES_AUTH_STR + std::string(m_accessToken.accessToken);
OIC_LOG_V(INFO, TAG, "GET request Uri: %s", uri.c_str());
CurlClient cc = CurlClient(CurlClient::CurlMethod::GET, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "GET request failed while getting thermostat information. Error code %d",
curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
if ((result = parseDevJsonResponse(response, thermostats)) != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "GET request failed while parsing thermostat information with result: %d",
result);
return result;
}
return MPM_RESULT_OK;
}
MPMResult Nest::setAwayMode(const AWAY_MODE &awayMode)
{
MPMResult result = MPM_RESULT_INTERNAL_ERROR;
std::string awayValue;
std::string request = "{ }";
rapidjson::Document doc;
if (m_isAuthorized)
{
if (awayMode == eAWAway)
{
awayValue = NEST_AWAY_TAG;
}
else if (awayMode == eAWHome)
{
awayValue = NEST_HOME_TAG;
}
else
{
// bad request
result = MPM_RESULT_INVALID_DATA;
}
if (result != MPM_RESULT_INVALID_DATA)
{
// build the URI
std::string uri(NEST_BASE_URL);
uri += NEST_STRUCTURE_AUTH_STR;
uri += m_accessToken.accessToken;
// build the request
if (!doc.Parse<0>(request.c_str()).HasParseError())
{
Document::AllocatorType &allocator = doc.GetAllocator();
JsonHelper::setMember(doc, m_metaInfo.structId, "");
doc[m_metaInfo.structId.c_str()].SetObject();
rapidjson::Value val(awayValue.c_str(), allocator);
JsonHelper::setMember(doc, m_metaInfo.structId, NEST_AWAY_TAG, val);
// serialize the DOM to a string
request = JsonHelper::toString(doc);
CurlClient cc = CurlClient(CurlClient::CurlMethod::PUT, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON)
.setRequestBody(request);
int curlCode = cc.send();
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "PUT request for set away mode failed. Error code %d", curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
result = MPM_RESULT_OK;
}
else
{
result = MPM_RESULT_JSON_ERROR;
}
}
}
else
{
result = MPM_RESULT_NOT_AUTHORIZED;
}
return result;
}
|
//******************************************************************
//
// Copyright 2017 Intel Mobile Communications GmbH All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <time.h>
#include <stdio.h>
#include <iostream>
#include "nest.h"
#include "curlClient.h"
#include "nestDefs.h"
#include "rapidjson.h"
#include "document.h"
#include "stringbuffer.h"
#include "writer.h"
#include "JsonHelper.h"
#include "logger.h"
using namespace rapidjson;
using namespace OC::Bridging;
#define TAG "NEST"
Nest::Nest(const ACCESS_TOKEN &accessToken) : m_accessToken(accessToken), m_isAuthorized(false)
{
m_metaInfo.awayMode = eAWUndefined;
}
Nest::Nest() : m_isAuthorized(false) {}
void Nest::setAccessToken(const ACCESS_TOKEN &token)
{
m_accessToken = token;
}
Nest::AWAY_MODE Nest::getAwayMode(const std::string &value) const
{
if (NEST_HOME_TAG == value)
{
return eAWHome;
}
else if (NEST_AWAY_TAG == value)
{
return eAWAway;
}
return eAWUndefined;
}
std::string Nest::getTok()
{
return m_accessToken.accessToken;
}
bool Nest::isAuthorized()
{
if (!strlen(m_accessToken.accessToken))
{
OIC_LOG(ERROR, TAG, "Length of access token is zero");
return false;
}
std::string uri(NEST_BASE_URL);
uri += NEST_STRUCTURE_AUTH_STR + std::string(m_accessToken.accessToken);
OIC_LOG_V(INFO, TAG, "uri: %s", uri.c_str());
CurlClient cc = CurlClient(CurlClient::CurlMethod::GET, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "Curl GET Request operation failed. Error code %d", curlCode);
return false;
}
if (MPM_RESULT_OK != parseStructureJsonResponse(response, m_metaInfo))
{
OIC_LOG(ERROR, TAG, "Parsing Json response failed on authorization");
return false;
}
return true;
}
MPMResult Nest::getAccessToken(std::string &authorizationCode, ACCESS_TOKEN &accessToken,
std::string &nest_client_id, std::string &nest_client_secret)
{
MPMResult result = MPM_RESULT_OK;
std::string uri(ACCESS_TOKEN_URL);
uri += NEST_CLIENT_ID_STR + nest_client_id;
uri += NEST_CODE_STR + authorizationCode;
uri += NEST_CLIENT_SECRET_STR + nest_client_secret;
uri += NEST_AUTH_CODE_STR;
CurlClient cc = CurlClient(CurlClient::CurlMethod::POST, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "Post for getting access token failed. Error code %d", curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
rapidjson::Document doc;
doc.SetObject();
if (!doc.Parse<0>(response.c_str()).HasParseError())
{
if (doc.HasMember("error"))
{
OIC_LOG(ERROR, TAG, "get error message from nest server");
return MPM_RESULT_INTERNAL_ERROR;
}
time_t expires = time(NULL);
expires += doc[NEST_VALIDITY_TAG].GetInt();
struct tm *expTime = localtime(&expires);
if (expTime != NULL)
{
char *chExpTime = asctime(expTime);
if (chExpTime != NULL)
{
OICStrcpy(accessToken.expires, NEST_ACCESS_TOKEN_EXPIRY - 1, chExpTime);
}
}
OICStrcpy(accessToken.accessToken, NEST_ACCESS_TOKEN_LEN - 1,
doc[NEST_ACCESS_TOKEN_TAG].GetString());
accessToken.grantTime = doc[NEST_VALIDITY_TAG].GetInt();
m_accessToken = accessToken;
m_isAuthorized = true;
}
else
{
result = MPM_RESULT_JSON_ERROR;
}
return result;
}
MPMResult Nest::parseStructureJsonResponse(std::string &json, META_INFO &meta)
{
MPMResult result = MPM_RESULT_NOT_AUTHORIZED;
rapidjson::Document doc;
doc.SetObject();
if (doc.Parse<0>(json.c_str()).HasParseError())
{
return MPM_RESULT_JSON_ERROR;
}
for (Value::ConstMemberIterator it = doc.MemberBegin(); it != doc.MemberEnd(); it++)
{
if (doc.HasMember("error"))
{
OIC_LOG(ERROR, TAG, "access token invalid");
break;
}
std::string name = it->name.GetString();
if (doc[name.c_str()].HasMember(NEST_AWAY_TAG) &&
doc[name.c_str()].HasMember(NEST_NAME_TAG))
{
meta.homeName = it->value[NEST_NAME_TAG].GetString();
meta.countryCode = it->value[NEST_COUNTRY_TAG].GetString();
meta.timeZone = it->value[NEST_TIMEZONE_TAG].GetString();
meta.structId = it->value[NEST_STRUCT_ID_TAG].GetString();
meta.awayMode =
getAwayMode(it->value[NEST_AWAY_TAG].GetString());
m_isAuthorized = true;
result = MPM_RESULT_OK;
}
}
return result;
}
MPMResult Nest::parseDevJsonResponse(std::string &json,
std::vector<std::shared_ptr<NestThermostat> > &thermostats)
{
rapidjson::Document doc;
doc.SetObject();
if (doc.Parse<0>(json.c_str()).HasParseError())
{
return MPM_RESULT_JSON_ERROR;
}
if (doc.HasMember(NEST_THERMOSTAT_TAG)
&& doc[NEST_THERMOSTAT_TAG].IsObject())
{
// The thermostat object holds each thermostat instance
for (Value::ConstMemberIterator it = doc[NEST_THERMOSTAT_TAG].MemberBegin();
it != doc[NEST_THERMOSTAT_TAG].MemberEnd(); it++)
{
// Extract the string representation from each thermostat instance
std::string json = JsonHelper::toString(it);
// Create the thermostat object, internally parse the JSON reprsentation
// and add it to the thermostat vector
std::shared_ptr<NestThermostat> thermostat = std::make_shared<NestThermostat>
(m_accessToken.accessToken, json);
thermostats.push_back(thermostat);
}
}
else
{
return MPM_RESULT_NOT_AUTHORIZED;
}
return MPM_RESULT_OK;
}
MPMResult Nest::getThermostats(std::vector<std::shared_ptr<NestThermostat> > &thermostats)
{
if (!strlen(m_accessToken.accessToken))
{
OIC_LOG(ERROR, TAG, "Not authorized");
return MPM_RESULT_NOT_AUTHORIZED;
}
MPMResult result = MPM_RESULT_INTERNAL_ERROR;
std::string uri(NEST_BASE_URL);
uri += NEST_DEVICES_AUTH_STR + std::string(m_accessToken.accessToken);
OIC_LOG_V(INFO, TAG, "GET request Uri: %s", uri.c_str());
CurlClient cc = CurlClient(CurlClient::CurlMethod::GET, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON);
int curlCode = cc.send();
std::string response = cc.getResponseBody();
OIC_LOG_V(DEBUG, TAG, "The curl response string is: %s", response.c_str());
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "GET request failed while getting thermostat information. Error code %d",
curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
if ((result = parseDevJsonResponse(response, thermostats)) != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "GET request failed while parsing thermostat information with result: %d",
result);
return result;
}
return MPM_RESULT_OK;
}
MPMResult Nest::setAwayMode(const AWAY_MODE &awayMode)
{
MPMResult result = MPM_RESULT_INTERNAL_ERROR;
std::string awayValue;
std::string request = "{ }";
rapidjson::Document doc;
if (m_isAuthorized)
{
if (awayMode == eAWAway)
{
awayValue = NEST_AWAY_TAG;
}
else if (awayMode == eAWHome)
{
awayValue = NEST_HOME_TAG;
}
else
{
// bad request
result = MPM_RESULT_INVALID_DATA;
}
if (result != MPM_RESULT_INVALID_DATA)
{
// build the URI
std::string uri(NEST_BASE_URL);
uri += NEST_STRUCTURE_AUTH_STR;
uri += m_accessToken.accessToken;
// build the request
if (!doc.Parse<0>(request.c_str()).HasParseError())
{
Document::AllocatorType &allocator = doc.GetAllocator();
JsonHelper::setMember(doc, m_metaInfo.structId, "");
doc[m_metaInfo.structId.c_str()].SetObject();
rapidjson::Value val(awayValue.c_str(), allocator);
JsonHelper::setMember(doc, m_metaInfo.structId, NEST_AWAY_TAG, val);
// serialize the DOM to a string
request = JsonHelper::toString(doc);
CurlClient cc = CurlClient(CurlClient::CurlMethod::PUT, uri)
.addRequestHeader(CURL_HEADER_ACCEPT_JSON)
.addRequestHeader(CURL_CONTENT_TYPE_JSON)
.setRequestBody(request);
int curlCode = cc.send();
if (curlCode != MPM_RESULT_OK)
{
OIC_LOG_V(ERROR, TAG, "PUT request for set away mode failed. Error code %d", curlCode);
return MPM_RESULT_INTERNAL_ERROR;
}
result = MPM_RESULT_OK;
}
else
{
result = MPM_RESULT_JSON_ERROR;
}
}
}
else
{
result = MPM_RESULT_NOT_AUTHORIZED;
}
return result;
}
|
Return false boolean instead of enum
|
bridging: Return false boolean instead of enum
Small Fix to support g++-7.1.0
It was tested on yocto poky master on iotivity-1.3.0 (and later):
bridging/plugins/nest_plugin/nest_objects/nest.cpp: \
In member function 'bool Nest::isAuthorized()':
bridging/plugins/nest_plugin/nest_objects/nest.cpp:95:16: \
error: enum constant in boolean context [-Werror=int-in-bool-context]
Change-Id: Ib53aa7be0198cd926b6901b173001910a324633e
Signed-off-by: Philippe Coval <[email protected]>
Reviewed-on: https://gerrit.iotivity.org/gerrit/21071
Tested-by: jenkins-iotivity <[email protected]>
Reviewed-by: Dan Mihai <[email protected]>
Reviewed-by: Todd Malsbary <[email protected]>
|
C++
|
apache-2.0
|
iotivity/iotivity,iotivity/iotivity,rzr/iotivity,iotivity/iotivity,iotivity/iotivity,iotivity/iotivity,iotivity/iotivity,rzr/iotivity,iotivity/iotivity,iotivity/iotivity,rzr/iotivity,rzr/iotivity,rzr/iotivity,rzr/iotivity,rzr/iotivity
|
7fbe56ad534436871560ae52740ceee25a18beb1
|
PolyMapGeneratorTest/MapTest.cpp
|
PolyMapGeneratorTest/MapTest.cpp
|
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include "Map.h"
#include "Structure.h"
#include "Noise/noise.h"
const int WIDTH = 800;
const int HEIGHT = 600;
const int POINT_SIZE = 2;
const int LINE_SIZE = 1;
struct InfoShown
{
enum class Name
{
Elevation,
Moisture,
Biomes
};
};
InfoShown::Name VideoMode;
sf::Color DELAUNAY_COLOR = sf::Color::Black;
sf::Color VORONOI_COLOR = sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94), sf::Uint8(127));
sf::Color WATER_COLOR = sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94));
sf::Color LAND_COLOR = sf::Color(sf::Uint8(178), sf::Uint8(166), sf::Uint8(148));
sf::Color LAKE_COLOR = sf::Color(sf::Uint8(95), sf::Uint8(134), sf::Uint8(169));
sf::Color RIVER_COLOR = sf::Color(sf::Uint8(40), sf::Uint8(88), sf::Uint8(132));
const sf::Color ELEVATION_COLOR[] =
{
sf::Color(sf::Uint8(104), sf::Uint8(134), sf::Uint8(89)),
sf::Color(sf::Uint8(119), sf::Uint8(153), sf::Uint8(102)),
sf::Color(sf::Uint8(136), sf::Uint8(166), sf::Uint8(121)),
sf::Color(sf::Uint8(153), sf::Uint8(179), sf::Uint8(148)),
sf::Color(sf::Uint8(170), sf::Uint8(191), sf::Uint8(159)),
sf::Color(sf::Uint8(187), sf::Uint8(204), sf::Uint8(179)),
sf::Color(sf::Uint8(204), sf::Uint8(217), sf::Uint8(198)),
sf::Color(sf::Uint8(221), sf::Uint8(230), sf::Uint8(217)),
sf::Color(sf::Uint8(238), sf::Uint8(242), sf::Uint8(236)),
sf::Color(sf::Uint8(251), sf::Uint8(252), sf::Uint8(251))
};
const sf::Color MOISTURE_COLOR[] =
{
sf::Color(sf::Uint8(238), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(218), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(197), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(176), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(155), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(135), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(115), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(94), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(73), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(52), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(32), sf::Uint8(238), sf::Uint8(32))
};
const sf::Color BIOME_COLOR[] =
{
sf::Color(sf::Uint8(248), sf::Uint8(248), sf::Uint8(248)),
sf::Color(sf::Uint8(221), sf::Uint8(221), sf::Uint8(187)),
sf::Color(sf::Uint8(153), sf::Uint8(153), sf::Uint8(153)),
sf::Color(sf::Uint8(204), sf::Uint8(212), sf::Uint8(187)),
sf::Color(sf::Uint8(196), sf::Uint8(204), sf::Uint8(187)),
sf::Color(sf::Uint8(228), sf::Uint8(232), sf::Uint8(202)),
sf::Color(sf::Uint8(164), sf::Uint8(196), sf::Uint8(168)),
sf::Color(sf::Uint8(180), sf::Uint8(201), sf::Uint8(169)),
sf::Color(sf::Uint8(196), sf::Uint8(212), sf::Uint8(170)),
sf::Color(sf::Uint8(156), sf::Uint8(187), sf::Uint8(169)),
sf::Color(sf::Uint8(169), sf::Uint8(204), sf::Uint8(164)),
sf::Color(sf::Uint8(233), sf::Uint8(221), sf::Uint8(199)),
sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94)),
sf::Color(sf::Uint8(95), sf::Uint8(134), sf::Uint8(169)),
sf::Color(sf::Uint8(178), sf::Uint8(166), sf::Uint8(148))
};
|
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include "Map.h"
#include "Structure.h"
#include "Noise/noise.h"
#include "QuadTree.h"
#include "PoissonDiskSampling/PoissonDiskSampling.h"
const int WIDTH = 800;
const int HEIGHT = 600;
const int POINT_SIZE = 2;
const int LINE_SIZE = 1;
struct InfoShown
{
enum class Name
{
Elevation,
Moisture,
Biomes
};
};
InfoShown::Name VideoMode;
sf::Color DELAUNAY_COLOR = sf::Color::Black;
sf::Color VORONOI_COLOR = sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94), sf::Uint8(127));
sf::Color WATER_COLOR = sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94));
sf::Color LAND_COLOR = sf::Color(sf::Uint8(178), sf::Uint8(166), sf::Uint8(148));
sf::Color LAKE_COLOR = sf::Color(sf::Uint8(95), sf::Uint8(134), sf::Uint8(169));
sf::Color RIVER_COLOR = sf::Color(sf::Uint8(40), sf::Uint8(88), sf::Uint8(132));
const sf::Color ELEVATION_COLOR[] =
{
sf::Color(sf::Uint8(104), sf::Uint8(134), sf::Uint8(89)),
sf::Color(sf::Uint8(119), sf::Uint8(153), sf::Uint8(102)),
sf::Color(sf::Uint8(136), sf::Uint8(166), sf::Uint8(121)),
sf::Color(sf::Uint8(153), sf::Uint8(179), sf::Uint8(148)),
sf::Color(sf::Uint8(170), sf::Uint8(191), sf::Uint8(159)),
sf::Color(sf::Uint8(187), sf::Uint8(204), sf::Uint8(179)),
sf::Color(sf::Uint8(204), sf::Uint8(217), sf::Uint8(198)),
sf::Color(sf::Uint8(221), sf::Uint8(230), sf::Uint8(217)),
sf::Color(sf::Uint8(238), sf::Uint8(242), sf::Uint8(236)),
sf::Color(sf::Uint8(251), sf::Uint8(252), sf::Uint8(251))
};
const sf::Color MOISTURE_COLOR[] =
{
sf::Color(sf::Uint8(238), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(218), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(197), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(176), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(155), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(135), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(115), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(94), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(73), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(52), sf::Uint8(238), sf::Uint8(32)),
sf::Color(sf::Uint8(32), sf::Uint8(238), sf::Uint8(32))
};
const sf::Color BIOME_COLOR[] =
{
sf::Color(sf::Uint8(248), sf::Uint8(248), sf::Uint8(248)),
sf::Color(sf::Uint8(221), sf::Uint8(221), sf::Uint8(187)),
sf::Color(sf::Uint8(153), sf::Uint8(153), sf::Uint8(153)),
sf::Color(sf::Uint8(204), sf::Uint8(212), sf::Uint8(187)),
sf::Color(sf::Uint8(196), sf::Uint8(204), sf::Uint8(187)),
sf::Color(sf::Uint8(228), sf::Uint8(232), sf::Uint8(202)),
sf::Color(sf::Uint8(164), sf::Uint8(196), sf::Uint8(168)),
sf::Color(sf::Uint8(180), sf::Uint8(201), sf::Uint8(169)),
sf::Color(sf::Uint8(196), sf::Uint8(212), sf::Uint8(170)),
sf::Color(sf::Uint8(156), sf::Uint8(187), sf::Uint8(169)),
sf::Color(sf::Uint8(169), sf::Uint8(204), sf::Uint8(164)),
sf::Color(sf::Uint8(233), sf::Uint8(221), sf::Uint8(199)),
sf::Color(sf::Uint8(52), sf::Uint8(58), sf::Uint8(94)),
sf::Color(sf::Uint8(95), sf::Uint8(134), sf::Uint8(169)),
sf::Color(sf::Uint8(178), sf::Uint8(166), sf::Uint8(148))
};
|
Add include files
|
Add include files
|
C++
|
mit
|
utilForever/PolyMapGenerator
|
b873777a6528d62df32a430fa4b33ac5058377fc
|
include/metaverse/explorer/extensions/commands/listbalances.hpp
|
include/metaverse/explorer/extensions/commands/listbalances.hpp
|
/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ listbalances *************************/
class listbalances: public command_extension
{
public:
static const char* symbol(){ return "listbalances";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ex_online & bs ) == bs; }
const char* description() override { return "List balance details of each address of this account. defaults show non-zero unspent address."; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("ACCOUNTNAME", 1)
.add("ACCOUNTAUTH", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(auth_.name, "ACCOUNTNAME", variables, input, raw);
load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"nozero,n",
value<bool>(&option_.non_zero)->zero_tokens()->default_value(true),
"Defaults to true."
)
(
"greater_equal,g",
value<uint64_t>(&option_.greater)->default_value(0),
"Greater than ETP bits."
)
(
"lesser_equal,l",
value<uint64_t>(&option_.lesser)->default_value(0),
"Lesser than ETP bits."
)
(
"ACCOUNTNAME",
value<std::string>(&auth_.name)->required(),
BX_ACCOUNT_NAME
)
(
"ACCOUNTAUTH",
value<std::string>(&auth_.auth)->required(),
BX_ACCOUNT_AUTH
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
} argument_;
struct option
{
bool non_zero;
uint64_t greater;
uint64_t lesser;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
|
/**
* Copyright (c) 2016-2017 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
/************************ listbalances *************************/
class listbalances: public command_extension
{
public:
static const char* symbol(){ return "listbalances";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ex_online & bs ) == bs; }
const char* description() override { return "List balance details of each address of this account. defaults show non-zero unspent address."; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("ACCOUNTNAME", 1)
.add("ACCOUNTAUTH", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(auth_.name, "ACCOUNTNAME", variables, input, raw);
load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"nozero,n",
value<bool>(&option_.non_zero)->zero_tokens()->default_value(false),
"Defaults to false."
)
(
"greater_equal,g",
value<uint64_t>(&option_.greater)->default_value(0),
"Greater than ETP bits."
)
(
"lesser_equal,l",
value<uint64_t>(&option_.lesser)->default_value(0),
"Lesser than ETP bits."
)
(
"ACCOUNTNAME",
value<std::string>(&auth_.name)->required(),
BX_ACCOUNT_NAME
)
(
"ACCOUNTAUTH",
value<std::string>(&auth_.auth)->required(),
BX_ACCOUNT_AUTH
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
} argument_;
struct option
{
bool non_zero;
uint64_t greater;
uint64_t lesser;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
|
change listbalances default output
|
change listbalances default output
|
C++
|
agpl-3.0
|
the-metaverse/metaverse,mvs-org/metaverse,mvs-live/metaverse,mvs-live/metaverse,the-metaverse/metaverse,the-metaverse/metaverse,mvs-org/metaverse,mvs-org/metaverse,mvs-org/metaverse,mvs-org/metaverse,mvs-org/metaverse
|
9d071772e6d83ab96cf79cb47e5ad659eea731bb
|
apps/tests/test_zgemm.cpp
|
apps/tests/test_zgemm.cpp
|
#include <sirius.h>
void test_gemm(int M, int N, int K, int transa, mdarray<double_complex, 2>& c)
{
sirius::Timer t("test_gemm");
mdarray<double_complex, 2> a;
if (transa == 0)
{
a.set_dimensions(N, K);
a.allocate();
for (int j = 0; j < K; j++)
{
for (int i = 0; i < N; i++) a(i, j) = type_wrapper<double_complex>::random();
}
}
else
{
a.set_dimensions(K, N);
a.allocate();
for (int j = 0; j < N; j++)
{
for (int i = 0; i < K; i++) a(i, j) = type_wrapper<double_complex>::random();
}
}
mdarray<double_complex, 2> b(K, N);
for (int j = 0; j < N; j++)
{
for (int i = 0; i < K; i++) b(i, j) = type_wrapper<double_complex>::random();
}
printf("testing serial zgemm with M, N, K = %i, %i, %i, opA = %i\n", M, N, K, transa);
sirius::Timer t1("gemm_only");
blas<cpu>::gemm(transa, 0, M, N, K, a.ptr(), a.ld(), b.ptr(), b.ld(), c.ptr(), c.ld());
t1.stop();
printf("execution time (sec) : %12.6f\n", t1.value());
printf("performance (GFlops) : %12.6f\n", 8e-9 * M * N * K / t1.value());
}
#ifdef _SCALAPACK_
void test_pgemm(int M, int N, int K, int nrow, int ncol, int transa)
{
int blacs_handler = linalg<scalapack>::create_blacs_handler(MPI_COMM_WORLD);
int context = blacs_handler;
Cblacs_gridinit(&context, "C", nrow, ncol);
dmatrix<double_complex> a;
if (transa == 0)
{
a.set_dimensions(M, K, context);
}
else
{
a.set_dimensions(K, M, context);
}
a.allocate();
dmatrix<double_complex> b(K, N, context);
dmatrix<double_complex> c(M, N, context);
c.zero();
for (int ic = 0; ic < a.num_cols_local(); ic++)
{
for (int ir = 0; ir < a.num_rows_local(); ir++) a(ir, ic) = type_wrapper<double_complex>::random();
}
for (int ic = 0; ic < b.num_cols_local(); ic++)
{
for (int ir = 0; ir < b.num_rows_local(); ir++) b(ir, ic) = type_wrapper<double_complex>::random();
}
if (Platform::mpi_rank() == 0)
{
printf("testing parallel zgemm with M, N, K = %i, %i, %i, opA = %i\n", M, N, K, transa);
printf("nrow, ncol = %i, %i, bs = %i\n", nrow, ncol, linalg<scalapack>::cyclic_block_size());
}
sirius::Timer t1("gemm_only");
blas<cpu>::gemm(transa, 0, M, N, K, complex_one, a, b, complex_zero, c);
t1.stop();
if (Platform::mpi_rank() == 0)
{
printf("execution time (sec) : %12.6f\n", t1.value());
printf("performance (GFlops) : %12.6f\n", 8e-9 * M * N * K / t1.value() / nrow / ncol);
}
Cblacs_gridexit(context);
linalg<scalapack>::free_blacs_handler(blacs_handler);
}
#endif
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--M=", "{int} M");
args.register_key("--N=", "{int} N");
args.register_key("--K=", "{int} K");
args.register_key("--opA=", "{0|1|2} 0: op(A) = A, 1: op(A) = A', 2: op(A) = conjg(A')");
args.register_key("--nrow=", "{int} number of row MPI ranks");
args.register_key("--ncol=", "{int} number of column MPI ranks");
args.register_key("--bs=", "{int} cyclic block size");
args.parse_args(argn, argv);
if (argn == 1)
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
exit(0);
}
int nrow = 1;
int ncol = 1;
if (args.exist("nrow")) nrow = args.value<int>("nrow");
if (args.exist("ncol")) ncol = args.value<int>("ncol");
int M = args.value<int>("M");
int N = args.value<int>("N");
int K = args.value<int>("K");
int transa = 0;
if (args.exist("opA")) transa = args.value<int>("opA");
Platform::initialize(true);
if (nrow * ncol == 1)
{
mdarray<double_complex, 2> c(M, N);
for (int j = 0; j < N; j++)
{
for (int i = 0; i < M; i++) c(i, j) = complex_zero;
}
test_gemm(M, N, K, transa, c);
}
else
{
#ifdef _SCALAPACK_
int bs = args.value<int>("bs");
linalg<scalapack>::set_cyclic_block_size(bs);
test_pgemm(M, N, K, nrow, ncol, transa);
#else
terminate(__FILE__, __LINE__, "not compiled with ScaLAPACK support");
#endif
}
Platform::finalize();
}
|
#include <sirius.h>
void test_gemm(int M, int N, int K, int transa)
{
sirius::Timer t("test_gemm");
mdarray<double_complex, 2> a, b, c;
int imax, jmax;
if (transa == 0)
{
imax = N;
jmax = K;
}
else
{
imax = K;
jmax = N;
}
a.set_dimensions(imax, jmax);
b.set_dimensions(K, N);
c.set_dimensions(M, N);
#ifdef _GPU_
a.allocate_page_locked();
b.allocate_page_locked();
c.allocate_page_locked();
#else
a.allocate();
b.allocate();
c.allocate();
#endif
for (int j = 0; j < jmax; j++)
{
for (int i = 0; i < imax; i++) a(i, j) = type_wrapper<double_complex>::random();
}
for (int j = 0; j < N; j++)
{
for (int i = 0; i < K; i++) b(i, j) = type_wrapper<double_complex>::random();
}
c.zero();
printf("testing serial zgemm with M, N, K = %i, %i, %i, opA = %i\n", M, N, K, transa);
sirius::Timer t1("gemm_only");
blas<cpu>::gemm(transa, 0, M, N, K, a.ptr(), a.ld(), b.ptr(), b.ld(), c.ptr(), c.ld());
t1.stop();
printf("execution time (sec) : %12.6f\n", t1.value());
printf("performance (GFlops) : %12.6f\n", 8e-9 * M * N * K / t1.value());
}
#ifdef _SCALAPACK_
void test_pgemm(int M, int N, int K, int nrow, int ncol, int transa)
{
int blacs_handler = linalg<scalapack>::create_blacs_handler(MPI_COMM_WORLD);
int context = blacs_handler;
Cblacs_gridinit(&context, "C", nrow, ncol);
dmatrix<double_complex> a, b, c;
if (transa == 0)
{
a.set_dimensions(M, K, context);
}
else
{
a.set_dimensions(K, M, context);
}
b.set_dimensions(K, N, context);
c.set_dimensions(M, N, context);
#ifdef _GPU_
a.allocate_page_locked();
b.allocate_page_locked();
c.allocate_page_locked();
#else
a.allocate();
b.allocate();
c.allocate();
#endif
for (int ic = 0; ic < a.num_cols_local(); ic++)
{
for (int ir = 0; ir < a.num_rows_local(); ir++) a(ir, ic) = type_wrapper<double_complex>::random();
}
for (int ic = 0; ic < b.num_cols_local(); ic++)
{
for (int ir = 0; ir < b.num_rows_local(); ir++) b(ir, ic) = type_wrapper<double_complex>::random();
}
c.zero();
if (Platform::mpi_rank() == 0)
{
printf("testing parallel zgemm with M, N, K = %i, %i, %i, opA = %i\n", M, N, K, transa);
printf("nrow, ncol = %i, %i, bs = %i\n", nrow, ncol, linalg<scalapack>::cyclic_block_size());
}
sirius::Timer t1("gemm_only");
blas<cpu>::gemm(transa, 0, M, N, K, complex_one, a, b, complex_zero, c);
t1.stop();
if (Platform::mpi_rank() == 0)
{
printf("execution time (sec) : %12.6f\n", t1.value());
printf("performance (GFlops) : %12.6f\n", 8e-9 * M * N * K / t1.value() / nrow / ncol);
}
Cblacs_gridexit(context);
linalg<scalapack>::free_blacs_handler(blacs_handler);
}
#endif
int main(int argn, char **argv)
{
cmd_args args;
args.register_key("--M=", "{int} M");
args.register_key("--N=", "{int} N");
args.register_key("--K=", "{int} K");
args.register_key("--opA=", "{0|1|2} 0: op(A) = A, 1: op(A) = A', 2: op(A) = conjg(A')");
args.register_key("--nrow=", "{int} number of row MPI ranks");
args.register_key("--ncol=", "{int} number of column MPI ranks");
args.register_key("--bs=", "{int} cyclic block size");
args.parse_args(argn, argv);
if (argn == 1)
{
printf("Usage: %s [options]\n", argv[0]);
args.print_help();
exit(0);
}
int nrow = 1;
int ncol = 1;
if (args.exist("nrow")) nrow = args.value<int>("nrow");
if (args.exist("ncol")) ncol = args.value<int>("ncol");
int M = args.value<int>("M");
int N = args.value<int>("N");
int K = args.value<int>("K");
int transa = 0;
if (args.exist("opA")) transa = args.value<int>("opA");
Platform::initialize(true);
if (nrow * ncol == 1)
{
test_gemm(M, N, K, transa);
}
else
{
#ifdef _SCALAPACK_
int bs = args.value<int>("bs");
linalg<scalapack>::set_cyclic_block_size(bs);
test_pgemm(M, N, K, nrow, ncol, transa);
#else
terminate(__FILE__, __LINE__, "not compiled with ScaLAPACK support");
#endif
}
Platform::finalize();
}
|
update of test_zgemm
|
update of test_zgemm
|
C++
|
bsd-2-clause
|
dithillobothrium/SIRIUS,electronic-structure/sirius,electronic-structure/sirius,dithillobothrium/SIRIUS,electronic-structure/sirius,dithillobothrium/SIRIUS,toxa81/sirius,electronic-structure/sirius,electronic-structure/sirius,dithillobothrium/SIRIUS,toxa81/sirius,toxa81/sirius,electronic-structure/sirius,electronic-structure/sirius,toxa81/sirius,toxa81/sirius,toxa81/sirius
|
d564fca3d26eee0a43455810fa4bf4cf01b62947
|
arangod/Aql/Optimizer.cpp
|
arangod/Aql/Optimizer.cpp
|
////////////////////////////////////////////////////////////////////////////////
/// @brief infrastructure for query optimizer
///
/// @file arangod/Aql/Optimizer.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/Optimizer.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/OptimizerRules.h"
#include "Cluster/ServerState.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- the optimizer class
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- static initializations
// -----------------------------------------------------------------------------
triagens::basics::Mutex Optimizer::SetupLock;
////////////////////////////////////////////////////////////////////////////////
// @brief list of all rules
////////////////////////////////////////////////////////////////////////////////
std::map<int, Optimizer::Rule> Optimizer::_rules;
////////////////////////////////////////////////////////////////////////////////
// @brief lookup from rule name to rule level
////////////////////////////////////////////////////////////////////////////////
std::unordered_map<std::string, int> Optimizer::_ruleLookup;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// @brief constructor, this will initialize the rules database
////////////////////////////////////////////////////////////////////////////////
Optimizer::Optimizer (size_t maxNumberOfPlans)
: _maxNumberOfPlans(maxNumberOfPlans > 0 ? maxNumberOfPlans : DefaultMaxNumberOfPlans) {
if (_rules.empty()) {
setupRules();
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// @brief add a plan to the optimizer
////////////////////////////////////////////////////////////////////////////////
bool Optimizer::addPlan (ExecutionPlan* plan,
RuleLevel level,
bool wasModified) {
TRI_ASSERT(plan != nullptr);
_newPlans.push_back(plan, level);
if (wasModified) {
// register which rules modified / created the plan
plan->addAppliedRule(_currentRule);
plan->invalidateCost();
}
if (_newPlans.size() >= _maxNumberOfPlans) {
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
// @brief the actual optimization
////////////////////////////////////////////////////////////////////////////////
int Optimizer::createPlans (ExecutionPlan* plan,
std::vector<std::string> const& rulesSpecification) {
int res;
int leastDoneLevel = 0;
TRI_ASSERT(! _rules.empty());
int maxRuleLevel = _rules.rbegin()->first;
// which optimizer rules are disabled?
std::unordered_set<int> const&& disabledIds = getDisabledRuleIds(rulesSpecification);
// _plans contains the previous optimisation result
_plans.clear();
_plans.push_back(plan, 0);
_newPlans.clear();
while (leastDoneLevel < maxRuleLevel) {
// Find variable usage for all old plans now:
for (auto p : _plans.list) {
if (! p->varUsageComputed()) {
p->findVarUsage();
}
}
// std::cout << "Have " << _plans.size() << " plans:" << std::endl;
/*
for (auto p : _plans.list) {
p->show();
std::cout << std::endl;
}
*/
// int count = 0;
// For all current plans:
while (_plans.size() > 0) {
int level;
auto p = _plans.pop_front(level);
if (level >= maxRuleLevel) {
_newPlans.push_back(p, level); // nothing to do, just keep it
}
else { // find next rule
auto it = _rules.upper_bound(level);
TRI_ASSERT(it != _rules.end());
/*
std::cout << "Trying rule " << it->second.name << " with level "
<< it->first << " on plan " << count++
<< std::endl;
*/
level = (*it).first;
if (disabledIds.find(level) != disabledIds.end() &&
(*it).second.canBeDisabled) {
// we picked a disabled rule
level = it->first;
_newPlans.push_back(p, level); // nothing to do, just keep it
// now try next
continue;
}
_currentRule = level;
try {
res = (*it).second.func(this, p, &(it->second));
}
catch (...) {
delete p;
throw;
}
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
}
// TODO: abort early here if we found a good-enough plan
// a good-enough plan is probably every plan with costs below some
// defined threshold. this requires plan costs to be calculated here
}
_plans.steal(_newPlans);
leastDoneLevel = maxRuleLevel;
for (auto l : _plans.levelDone) {
if (l < leastDoneLevel) {
leastDoneLevel = l;
}
}
// std::cout << "Least done level is " << leastDoneLevel << std::endl;
// Stop if the result gets out of hand:
if (_plans.size() >= _maxNumberOfPlans) {
// TODO: must iterate over all REQUIRED remaining transformation rules
// because there are some rules which are required to make the query
// work in cluster mode
// rules that have their canBeDisabled flag set to false must still
// be carried out!
break;
}
}
TRI_ASSERT(_plans.size() >= 1);
estimatePlans();
sortPlans();
/*
std::cout << "Optimisation ends with " << _plans.size() << " plans."
<< std::endl;
for (auto p : _plans.list) {
p->show();
std::cout << "costing: " << p->getCost() << std::endl;
std::cout << std::endl;
}
*/
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief translate a list of rule ids into rule name
////////////////////////////////////////////////////////////////////////////////
std::vector<std::string> Optimizer::translateRules (std::vector<int> const& rules) {
std::vector<std::string> names;
for (auto r : rules) {
auto it = _rules.find(r);
if (it != _rules.end()) {
names.emplace_back((*it).second.name);
}
}
return names;
}
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief estimatePlans
////////////////////////////////////////////////////////////////////////////////
void Optimizer::estimatePlans () {
for (auto p : _plans.list) {
p->getCost();
// this value is cached in the plan, so formally this step is
// unnecessary, but for the sake of cleanliness...
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sortPlans
////////////////////////////////////////////////////////////////////////////////
void Optimizer::sortPlans () {
std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {
return a->getCost() < b->getCost();
});
}
////////////////////////////////////////////////////////////////////////////////
/// @brief look up the ids of all disabled rules
////////////////////////////////////////////////////////////////////////////////
std::unordered_set<int> Optimizer::getDisabledRuleIds (std::vector<std::string> const& names) const {
std::unordered_set<int> disabled;
// lookup ids of all disabled rules
for (auto name : names) {
if (name[0] == '-') {
// disable rule
if (name == "-all") {
// disable all rules
for (auto it : _rules) {
disabled.insert(it.first);
}
}
else {
// disable a specific rule
auto it = _ruleLookup.find(std::string(name.c_str() + 1));
if (it != _ruleLookup.end()) {
disabled.insert((*it).second);
}
}
}
else if (name[0] == '+') {
// enable rule
if (name == "+all") {
// enable all rules
disabled.clear();
}
else {
auto it = _ruleLookup.find(std::string(name.c_str() + 1));
if (it != _ruleLookup.end()) {
disabled.erase((*it).second);
}
}
}
}
return disabled;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief set up the optimizer rules once and forever
////////////////////////////////////////////////////////////////////////////////
void Optimizer::setupRules () {
MUTEX_LOCKER(SetupLock);
if (! _rules.empty()) {
// race condition... prevent duplicate registration of rules
return;
}
// List all the rules in the system here:
// lower level values mean earlier rule execution
// note that levels must be unique
//////////////////////////////////////////////////////////////////////////////
// "Pass 1": moving nodes "up" (potentially outside loops):
// please use levels between 1 and 99 here
//////////////////////////////////////////////////////////////////////////////
// move calculations up the dependency chain (to pull them out of
// inner loops etc.)
registerRule("move-calculations-up",
moveCalculationsUpRule,
moveCalculationsUpRule_pass1,
true);
// move filters up the dependency chain (to make result sets as small
// as possible as early as possible)
registerRule("move-filters-up",
moveFiltersUpRule,
moveFiltersUpRule_pass1,
true);
// remove redundant calculations
registerRule("remove-redundant-calculations",
removeRedundantCalculationsRule,
removeRedundantCalculationsRule_pass1,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 2": try to remove redundant or unnecessary nodes
/// use levels between 101 and 199 for this
//////////////////////////////////////////////////////////////////////////////
// remove filters from the query that are not necessary at all
// filters that are always true will be removed entirely
// filters that are always false will be replaced with a NoResults node
registerRule("remove-unnecessary-filters",
removeUnnecessaryFiltersRule,
removeUnnecessaryFiltersRule_pass2,
true);
// remove calculations that are never necessary
registerRule("remove-unnecessary-calculations",
removeUnnecessaryCalculationsRule,
removeUnnecessaryCalculationsRule_pass2,
true);
// remove redundant sort blocks
registerRule("remove-redundant-sorts",
removeRedundantSorts,
removeRedundantSorts_pass2,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 3": interchange EnumerateCollection nodes in all possible ways
/// this is level 500, please never let new plans from higher
/// levels go back to this or lower levels!
//////////////////////////////////////////////////////////////////////////////
registerRule("interchange-adjacent-enumerations",
interchangeAdjacentEnumerations,
interchangeAdjacentEnumerations_pass3,
true);
//////////////////////////////////////////////////////////////////////////////
// "Pass 4": moving nodes "up" (potentially outside loops) (second try):
// please use levels between 501 and 599 here
//////////////////////////////////////////////////////////////////////////////
// move calculations up the dependency chain (to pull them out of
// inner loops etc.)
registerRule("move-calculations-up-2",
moveCalculationsUpRule,
moveCalculationsUpRule_pass4,
true);
// move filters up the dependency chain (to make result sets as small
// as possible as early as possible)
registerRule("move-filters-up-2",
moveFiltersUpRule,
moveFiltersUpRule_pass4,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 5": try to remove redundant or unnecessary nodes (second try)
/// use levels between 601 and 699 for this
//////////////////////////////////////////////////////////////////////////////
// remove filters from the query that are not necessary at all
// filters that are always true will be removed entirely
// filters that are always false will be replaced with a NoResults node
registerRule("remove-unnecessary-filters-2",
removeUnnecessaryFiltersRule,
removeUnnecessaryFiltersRule_pass5,
true);
// remove calculations that are never necessary
registerRule("remove-unnecessary-calculations-2",
removeUnnecessaryCalculationsRule,
removeUnnecessaryCalculationsRule_pass5,
true);
// remove redundant sort blocks
registerRule("remove-redundant-sorts-2",
removeRedundantSorts,
removeRedundantSorts_pass5,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 6": use indexes if possible for FILTER and/or SORT nodes
/// use levels between 701 and 799 for this
//////////////////////////////////////////////////////////////////////////////
// try to find a filter after an enumerate collection and find an index . . .
registerRule("use-index-range",
useIndexRange,
useIndexRange_pass6,
true);
// try to find sort blocks which are superseeded by indexes
registerRule("use-index-for-sort",
useIndexForSort,
useIndexForSort_pass6,
true);
if (ExecutionEngine::isCoordinator()) {
// distribute operations in cluster
registerRule("scatter-in-cluster",
scatterInCluster,
scatterInCluster_pass10,
false);
registerRule("distribute-in-cluster",
distributeInCluster,
distributeInCluster_pass10,
false);
// distribute operations in cluster
registerRule("distribute-filtercalc-to-cluster",
distributeFilternCalcToCluster,
distributeFilternCalcToCluster_pass10,
false);
registerRule("distribute-sort-to-cluster",
distributeSortToCluster,
distributeSortToCluster_pass10,
true);
registerRule("remove-unnecessary-remote-scatter",
removeUnnecessaryRemoteScatter,
removeUnnecessaryRemoteScatter_pass10,
true);
registerRule("undistribute-remove-after-enum-coll",
undistributeRemoveAfterEnumColl,
undistributeRemoveAfterEnumColl_pass10,
true);
}
}
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
|
////////////////////////////////////////////////////////////////////////////////
/// @brief infrastructure for query optimizer
///
/// @file arangod/Aql/Optimizer.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Aql/Optimizer.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/OptimizerRules.h"
#include "Cluster/ServerState.h"
using namespace triagens::aql;
// -----------------------------------------------------------------------------
// --SECTION-- the optimizer class
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- static initializations
// -----------------------------------------------------------------------------
triagens::basics::Mutex Optimizer::SetupLock;
////////////////////////////////////////////////////////////////////////////////
// @brief list of all rules
////////////////////////////////////////////////////////////////////////////////
std::map<int, Optimizer::Rule> Optimizer::_rules;
////////////////////////////////////////////////////////////////////////////////
// @brief lookup from rule name to rule level
////////////////////////////////////////////////////////////////////////////////
std::unordered_map<std::string, int> Optimizer::_ruleLookup;
// -----------------------------------------------------------------------------
// --SECTION-- constructors / destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// @brief constructor, this will initialize the rules database
////////////////////////////////////////////////////////////////////////////////
Optimizer::Optimizer (size_t maxNumberOfPlans)
: _maxNumberOfPlans(maxNumberOfPlans > 0 ? maxNumberOfPlans : DefaultMaxNumberOfPlans) {
if (_rules.empty()) {
setupRules();
}
}
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// @brief add a plan to the optimizer
////////////////////////////////////////////////////////////////////////////////
bool Optimizer::addPlan (ExecutionPlan* plan,
RuleLevel level,
bool wasModified) {
TRI_ASSERT(plan != nullptr);
_newPlans.push_back(plan, level);
if (wasModified) {
// register which rules modified / created the plan
plan->addAppliedRule(_currentRule);
plan->invalidateCost();
}
if (_newPlans.size() >= _maxNumberOfPlans) {
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
// @brief the actual optimization
////////////////////////////////////////////////////////////////////////////////
int Optimizer::createPlans (ExecutionPlan* plan,
std::vector<std::string> const& rulesSpecification) {
int res;
int leastDoneLevel = 0;
TRI_ASSERT(! _rules.empty());
int maxRuleLevel = _rules.rbegin()->first;
// which optimizer rules are disabled?
std::unordered_set<int> const&& disabledIds = getDisabledRuleIds(rulesSpecification);
// _plans contains the previous optimisation result
_plans.clear();
_plans.push_back(plan, 0);
_newPlans.clear();
while (leastDoneLevel < maxRuleLevel) {
// Find variable usage for all old plans now:
for (auto p : _plans.list) {
if (! p->varUsageComputed()) {
p->findVarUsage();
}
}
// std::cout << "Have " << _plans.size() << " plans:" << std::endl;
/*
for (auto p : _plans.list) {
p->show();
std::cout << std::endl;
}
*/
// int count = 0;
// For all current plans:
while (_plans.size() > 0) {
int level;
auto p = _plans.pop_front(level);
if (level >= maxRuleLevel) {
_newPlans.push_back(p, level); // nothing to do, just keep it
}
else { // find next rule
auto it = _rules.upper_bound(level);
TRI_ASSERT(it != _rules.end());
/*
std::cout << "Trying rule " << it->second.name << " with level "
<< it->first << " on plan " << count++
<< std::endl;
*/
level = (*it).first;
if (disabledIds.find(level) != disabledIds.end() &&
(*it).second.canBeDisabled) {
// we picked a disabled rule
level = it->first;
_newPlans.push_back(p, level); // nothing to do, just keep it
// now try next
continue;
}
_currentRule = level;
try {
res = (*it).second.func(this, p, &(it->second));
}
catch (...) {
delete p;
throw;
}
if (res != TRI_ERROR_NO_ERROR) {
return res;
}
}
// TODO: abort early here if we found a good-enough plan
// a good-enough plan is probably every plan with costs below some
// defined threshold. this requires plan costs to be calculated here
}
_plans.steal(_newPlans);
leastDoneLevel = maxRuleLevel;
for (auto l : _plans.levelDone) {
if (l < leastDoneLevel) {
leastDoneLevel = l;
}
}
// std::cout << "Least done level is " << leastDoneLevel << std::endl;
// Stop if the result gets out of hand:
if (_plans.size() >= _maxNumberOfPlans) {
// TODO: must iterate over all REQUIRED remaining transformation rules
// because there are some rules which are required to make the query
// work in cluster mode
// rules that have their canBeDisabled flag set to false must still
// be carried out!
break;
}
}
TRI_ASSERT(_plans.size() >= 1);
estimatePlans();
sortPlans();
/*
std::cout << "Optimisation ends with " << _plans.size() << " plans."
<< std::endl;
for (auto p : _plans.list) {
p->show();
std::cout << "costing: " << p->getCost() << std::endl;
std::cout << std::endl;
}
*/
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief translate a list of rule ids into rule name
////////////////////////////////////////////////////////////////////////////////
std::vector<std::string> Optimizer::translateRules (std::vector<int> const& rules) {
std::vector<std::string> names;
for (auto r : rules) {
auto it = _rules.find(r);
if (it != _rules.end()) {
names.emplace_back((*it).second.name);
}
}
return names;
}
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief estimatePlans
////////////////////////////////////////////////////////////////////////////////
void Optimizer::estimatePlans () {
for (auto p : _plans.list) {
p->getCost();
// this value is cached in the plan, so formally this step is
// unnecessary, but for the sake of cleanliness...
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sortPlans
////////////////////////////////////////////////////////////////////////////////
void Optimizer::sortPlans () {
std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {
return a->getCost() < b->getCost();
});
}
////////////////////////////////////////////////////////////////////////////////
/// @brief look up the ids of all disabled rules
////////////////////////////////////////////////////////////////////////////////
std::unordered_set<int> Optimizer::getDisabledRuleIds (std::vector<std::string> const& names) const {
std::unordered_set<int> disabled;
// lookup ids of all disabled rules
for (auto name : names) {
if (name[0] == '-') {
// disable rule
if (name == "-all") {
// disable all rules
for (auto it : _rules) {
disabled.insert(it.first);
}
}
else {
// disable a specific rule
auto it = _ruleLookup.find(std::string(name.c_str() + 1));
if (it != _ruleLookup.end()) {
disabled.insert((*it).second);
}
}
}
else if (name[0] == '+') {
// enable rule
if (name == "+all") {
// enable all rules
disabled.clear();
}
else {
auto it = _ruleLookup.find(std::string(name.c_str() + 1));
if (it != _ruleLookup.end()) {
disabled.erase((*it).second);
}
}
}
}
return disabled;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief set up the optimizer rules once and forever
////////////////////////////////////////////////////////////////////////////////
void Optimizer::setupRules () {
MUTEX_LOCKER(SetupLock);
if (! _rules.empty()) {
// race condition... prevent duplicate registration of rules
return;
}
// List all the rules in the system here:
// lower level values mean earlier rule execution
// note that levels must be unique
//////////////////////////////////////////////////////////////////////////////
// "Pass 1": moving nodes "up" (potentially outside loops):
// please use levels between 1 and 99 here
//////////////////////////////////////////////////////////////////////////////
// move calculations up the dependency chain (to pull them out of
// inner loops etc.)
registerRule("move-calculations-up",
moveCalculationsUpRule,
moveCalculationsUpRule_pass1,
true);
// move filters up the dependency chain (to make result sets as small
// as possible as early as possible)
registerRule("move-filters-up",
moveFiltersUpRule,
moveFiltersUpRule_pass1,
true);
// remove redundant calculations
registerRule("remove-redundant-calculations",
removeRedundantCalculationsRule,
removeRedundantCalculationsRule_pass1,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 2": try to remove redundant or unnecessary nodes
/// use levels between 101 and 199 for this
//////////////////////////////////////////////////////////////////////////////
// remove filters from the query that are not necessary at all
// filters that are always true will be removed entirely
// filters that are always false will be replaced with a NoResults node
registerRule("remove-unnecessary-filters",
removeUnnecessaryFiltersRule,
removeUnnecessaryFiltersRule_pass2,
true);
// remove calculations that are never necessary
registerRule("remove-unnecessary-calculations",
removeUnnecessaryCalculationsRule,
removeUnnecessaryCalculationsRule_pass2,
true);
// remove redundant sort blocks
registerRule("remove-redundant-sorts",
removeRedundantSorts,
removeRedundantSorts_pass2,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 3": interchange EnumerateCollection nodes in all possible ways
/// this is level 500, please never let new plans from higher
/// levels go back to this or lower levels!
//////////////////////////////////////////////////////////////////////////////
registerRule("interchange-adjacent-enumerations",
interchangeAdjacentEnumerations,
interchangeAdjacentEnumerations_pass3,
true);
//////////////////////////////////////////////////////////////////////////////
// "Pass 4": moving nodes "up" (potentially outside loops) (second try):
// please use levels between 501 and 599 here
//////////////////////////////////////////////////////////////////////////////
// move calculations up the dependency chain (to pull them out of
// inner loops etc.)
registerRule("move-calculations-up-2",
moveCalculationsUpRule,
moveCalculationsUpRule_pass4,
true);
// move filters up the dependency chain (to make result sets as small
// as possible as early as possible)
registerRule("move-filters-up-2",
moveFiltersUpRule,
moveFiltersUpRule_pass4,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 5": try to remove redundant or unnecessary nodes (second try)
/// use levels between 601 and 699 for this
//////////////////////////////////////////////////////////////////////////////
// remove filters from the query that are not necessary at all
// filters that are always true will be removed entirely
// filters that are always false will be replaced with a NoResults node
registerRule("remove-unnecessary-filters-2",
removeUnnecessaryFiltersRule,
removeUnnecessaryFiltersRule_pass5,
true);
// remove calculations that are never necessary
registerRule("remove-unnecessary-calculations-2",
removeUnnecessaryCalculationsRule,
removeUnnecessaryCalculationsRule_pass5,
true);
// remove redundant sort blocks
registerRule("remove-redundant-sorts-2",
removeRedundantSorts,
removeRedundantSorts_pass5,
true);
//////////////////////////////////////////////////////////////////////////////
/// "Pass 6": use indexes if possible for FILTER and/or SORT nodes
/// use levels between 701 and 799 for this
//////////////////////////////////////////////////////////////////////////////
// try to find a filter after an enumerate collection and find an index . . .
registerRule("use-index-range",
useIndexRange,
useIndexRange_pass6,
true);
// try to find sort blocks which are superseeded by indexes
registerRule("use-index-for-sort",
useIndexForSort,
useIndexForSort_pass6,
true);
if (ExecutionEngine::isCoordinator()) {
// distribute operations in cluster
registerRule("scatter-in-cluster",
scatterInCluster,
scatterInCluster_pass10,
false);
registerRule("distribute-in-cluster",
distributeInCluster,
distributeInCluster_pass10,
false);
// distribute operations in cluster
registerRule("distribute-filtercalc-to-cluster",
distributeFilternCalcToCluster,
distributeFilternCalcToCluster_pass10,
true);
registerRule("distribute-sort-to-cluster",
distributeSortToCluster,
distributeSortToCluster_pass10,
true);
registerRule("remove-unnecessary-remote-scatter",
removeUnnecessaryRemoteScatter,
removeUnnecessaryRemoteScatter_pass10,
true);
registerRule("undistribute-remove-after-enum-coll",
undistributeRemoveAfterEnumColl,
undistributeRemoveAfterEnumColl_pass10,
true);
}
}
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
|
Make distribute-filtercalc-in-cluster switch-off-able.
|
Make distribute-filtercalc-in-cluster switch-off-able.
|
C++
|
apache-2.0
|
thurt/arangodb,baslr/ArangoDB,CoDEmanX/ArangoDB,baslr/ArangoDB,m0ppers/arangodb,jsteemann/arangodb,Simran-B/arangodb,thurt/arangodb,CoDEmanX/ArangoDB,graetzer/arangodb,jsteemann/arangodb,CoDEmanX/ArangoDB,m0ppers/arangodb,wiltonlazary/arangodb,m0ppers/arangodb,thurt/arangodb,CoDEmanX/ArangoDB,thurt/arangodb,joerg84/arangodb,Simran-B/arangodb,kangkot/arangodb,fceller/arangodb,thurt/arangodb,baslr/ArangoDB,joerg84/arangodb,thurt/arangodb,fceller/arangodb,graetzer/arangodb,baslr/ArangoDB,arangodb/arangodb,baslr/ArangoDB,m0ppers/arangodb,fceller/arangodb,m0ppers/arangodb,CoDEmanX/ArangoDB,graetzer/arangodb,m0ppers/arangodb,joerg84/arangodb,hkernbach/arangodb,kangkot/arangodb,graetzer/arangodb,fceller/arangodb,jsteemann/arangodb,kangkot/arangodb,graetzer/arangodb,arangodb/arangodb,kangkot/arangodb,arangodb/arangodb,hkernbach/arangodb,joerg84/arangodb,jsteemann/arangodb,baslr/ArangoDB,wiltonlazary/arangodb,m0ppers/arangodb,Simran-B/arangodb,wiltonlazary/arangodb,arangodb/arangodb,fceller/arangodb,jsteemann/arangodb,thurt/arangodb,joerg84/arangodb,hkernbach/arangodb,graetzer/arangodb,kangkot/arangodb,graetzer/arangodb,joerg84/arangodb,arangodb/arangodb,thurt/arangodb,m0ppers/arangodb,Simran-B/arangodb,arangodb/arangodb,wiltonlazary/arangodb,fceller/arangodb,kangkot/arangodb,graetzer/arangodb,graetzer/arangodb,m0ppers/arangodb,graetzer/arangodb,joerg84/arangodb,fceller/arangodb,fceller/arangodb,wiltonlazary/arangodb,jsteemann/arangodb,CoDEmanX/ArangoDB,hkernbach/arangodb,graetzer/arangodb,hkernbach/arangodb,joerg84/arangodb,baslr/ArangoDB,joerg84/arangodb,jsteemann/arangodb,CoDEmanX/ArangoDB,hkernbach/arangodb,CoDEmanX/ArangoDB,hkernbach/arangodb,hkernbach/arangodb,m0ppers/arangodb,joerg84/arangodb,thurt/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,jsteemann/arangodb,m0ppers/arangodb,baslr/ArangoDB,joerg84/arangodb,joerg84/arangodb,joerg84/arangodb,baslr/ArangoDB,m0ppers/arangodb,CoDEmanX/ArangoDB,graetzer/arangodb,hkernbach/arangodb,thurt/arangodb,fceller/arangodb,Simran-B/arangodb,Simran-B/arangodb,CoDEmanX/ArangoDB,Simran-B/arangodb,baslr/ArangoDB,Simran-B/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,jsteemann/arangodb,kangkot/arangodb,hkernbach/arangodb,baslr/ArangoDB,baslr/ArangoDB,baslr/ArangoDB,joerg84/arangodb,Simran-B/arangodb,arangodb/arangodb,graetzer/arangodb,hkernbach/arangodb,Simran-B/arangodb,kangkot/arangodb,kangkot/arangodb,hkernbach/arangodb,arangodb/arangodb,fceller/arangodb,kangkot/arangodb,m0ppers/arangodb,jsteemann/arangodb,graetzer/arangodb,wiltonlazary/arangodb
|
51c04121898fbd61105080bd622cedfe8fdbc1e5
|
Metazion/Share/Collection/Map.hpp
|
Metazion/Share/Collection/Map.hpp
|
#ifndef _MZ_SHARE_MAP_HPP_
#define _MZ_SHARE_MAP_HPP_
#include "Metazion/Share/ShareInclude.hpp"
#include "Metazion/Share/Collection/MapIterator.hpp"
#include "Metazion/Share/Collection/RBTree.hpp"
#include "Metazion/Share/Memory/HeapAllocator.hpp"
DECL_NAMESPACE_MZ_SHARE_BEGIN
template<typename KeyType
, typename ValueType
, typename CompareType
, typename AllocatorFamily = HeapAllocator<>
>
class Map {
DISALLOW_COPY_AND_ASSIGN(Map)
using Key_t = KeyType;
using Value_t = ValueType;
using Compare_t = CompareType;
using Data_t = Pair<Key_t, Value_t>;
using DataCompare_t = PairCompare<Data_t, Compare_t>;
using Node_t = RBTreeNode<Data_t>;
using Tree_t = RBTree<Node_t, DataCompare_t>;
using Allocator_t = typename AllocatorFamily::template Rebind<sizeof(Node_t)>;
public:
using Iterator_t = MapIterator<Node_t>;
using ConstIterator_t = MapConstIterator<Node_t>;
public:
Map() { m_allocator.Initialize(); }
~Map() { m_allocator.Finalize(); }
public:
void Clear() {
while (!IsEmpty()) {
}
}
bool IsEmpty() const {
return m_tree.IsEmpty();
}
int GetSize() const {
return m_tree.GetSize();
}
public:
ConstIterator_t Begin() const {
const auto node = m_tree.First();
return ConstIterator_t(node);
}
Iterator_t Begin() {
auto node = m_tree.First();
return Iterator_t(node);
}
ConstIterator_t End() const {
return ConstIterator_t();
}
Iterator_t End() {
return Iterator_t();
}
Iterator_t Insert(const Key_t& key, const Value_t& value) {
auto node = CreateNode();
ASSERT_TRUE(!IsNull(node));
node->m_value.first = key;
node->m_value.second = value;
m_tree.Insert(node);
return Iterator_t(node);
}
void Erase(Iterator_t iter) {
ASSERT_TRUE(iter != End());
m_tree.Remove(iter.Node());
DestoryNode(iter.Node());
}
void Erase(const Key_t& key) {
auto iter = Find(key);
if (iter != End()) {
Erase(iter);
}
}
Iterator_t Find(const Key_t& key) {
Data_t data;
data.first = key;
Node_t* node = m_tree.Search(data);
return Iterator_t(node);
}
private:
Node_t* CreateNode() {
auto memory = m_allocator.Alloc();
auto node = new(memory) Node_t();
return node;
}
void DestoryNode(Node_t* node) {
node->~Node_t();
m_allocator.Free(node);
}
private:
Allocator_t m_allocator;
Tree_t m_tree;
};
DECL_NAMESPACE_MZ_SHARE_END
#endif // _MZ_SHARE_MAP_HPP_
|
#ifndef _MZ_SHARE_MAP_HPP_
#define _MZ_SHARE_MAP_HPP_
#include "Metazion/Share/ShareInclude.hpp"
#include "Metazion/Share/Collection/MapIterator.hpp"
#include "Metazion/Share/Collection/RBTree.hpp"
#include "Metazion/Share/Memory/HeapAllocator.hpp"
DECL_NAMESPACE_MZ_SHARE_BEGIN
template<typename KeyType
, typename ValueType
, typename CompareType
, typename AllocatorFamily = HeapAllocator<>
>
class Map {
DISALLOW_COPY_AND_ASSIGN(Map)
using Key_t = KeyType;
using Value_t = ValueType;
using Compare_t = CompareType;
using Data_t = Pair<Key_t, Value_t>;
using DataCompare_t = PairCompare<Data_t, Compare_t>;
using Node_t = RBTreeNode<Data_t>;
using Tree_t = RBTree<Node_t, DataCompare_t>;
using Allocator_t = typename AllocatorFamily::template Rebind<sizeof(Node_t)>;
public:
using Iterator_t = MapIterator<Node_t>;
using ConstIterator_t = MapConstIterator<Node_t>;
public:
Map() { m_allocator.Initialize(); }
~Map() { m_allocator.Finalize(); }
public:
void Clear() {
while (!IsEmpty()) {
Iterator_t iter = Begin();
Erase(iter);
}
}
bool IsEmpty() const {
return m_tree.IsEmpty();
}
int GetSize() const {
return m_tree.GetSize();
}
public:
ConstIterator_t Begin() const {
const auto node = m_tree.First();
return ConstIterator_t(node);
}
Iterator_t Begin() {
auto node = m_tree.First();
return Iterator_t(node);
}
ConstIterator_t End() const {
return ConstIterator_t();
}
Iterator_t End() {
return Iterator_t();
}
Iterator_t Insert(const Key_t& key, const Value_t& value) {
auto node = CreateNode();
ASSERT_TRUE(!IsNull(node));
node->m_value.first = key;
node->m_value.second = value;
m_tree.Insert(node);
return Iterator_t(node);
}
void Erase(Iterator_t iter) {
ASSERT_TRUE(iter != End());
m_tree.Remove(iter.Node());
DestoryNode(iter.Node());
}
void Erase(const Key_t& key) {
auto iter = Find(key);
if (iter != End()) {
Erase(iter);
}
}
Iterator_t Find(const Key_t& key) {
Data_t data;
data.first = key;
Node_t* node = m_tree.Search(data);
return Iterator_t(node);
}
private:
Node_t* CreateNode() {
auto memory = m_allocator.Alloc();
auto node = new(memory) Node_t();
return node;
}
void DestoryNode(Node_t* node) {
node->~Node_t();
m_allocator.Free(node);
}
private:
Allocator_t m_allocator;
Tree_t m_tree;
};
DECL_NAMESPACE_MZ_SHARE_END
#endif // _MZ_SHARE_MAP_HPP_
|
Improve map.
|
Improve map.
|
C++
|
mit
|
Metazion/Metazion,Metazion/Metazion
|
fb0150c035284dedf63b920ae0668c8ec397ffd5
|
iree/compiler/Dialect/Shape/Conversion/ConvertShapeToShapex.cpp
|
iree/compiler/Dialect/Shape/Conversion/ConvertShapeToShapex.cpp
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Dialect/Shape/IR/ShapeDialect.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeOps.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeTypes.h"
#include "mlir/Dialect/Shape/IR/Shape.h"
#include "mlir/Dialect/Traits.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace iree_compiler {
namespace Shape {
namespace {
// This conversion is currently quite limited, such as not handling multiple
// basic blocks in general, due to doing a type conversion that the MLIR core
// conversion infra doesn't handle well.
//
// In particular, we convert `!shape.shape` to `!shapex.ranked_shape<...>`, but
// the contents of the `...` are context-dependent. Thus, one could say that
// this pass does a context-dependent type conversion.
//
// The current MLIR conversion infra doesn't handle context-dependent type
// conversions.
//
// I can see two solutions:
//
// 1. Extend the MLIR conversion infra to better support context-dependent type
// conversions. One way to do this would be for the conversion infra to convert
// blocks in RPO and use the type of the converted successor operand in a
// dominating predecessor as the type for the block argument when converting a
// block. A similar thing could be done with an RPO traversal of the callgraph.
// This algorithm wouldn't work in the presence of recursively dead cycles. And
// of course linkage boundaries cannot have a context-dependent type conversion
// (by definition).
//
// 2. Avoid needing to convert to !shapex.ranked_shape in the first place. This
// could be accomplished by generalizing !shape.shape to be able to support the
// use case of !shapex.ranked_shape. One important requirement here is that
// !shapex.ranked_shape models a partially-specified shape (hardcoded for the
// ranked case). !shape.shape could be extended to capture partially-specified
// shapes in the type, such as allowing `!shape.shape<*>` to model an unranked
// shape (which is the default; no information), `!shape.shape<?x?x5x?>` to
// model a rank-4 shape with dimension 2 being of extent 5, etc.
//
// Once we have this, we could do this lowering from generic !shape.shape to
// statically-known ranked shapes more progressively and treat it more like a
// type refinement algorithm.
//
// The main risk is that we are trying to shove too much stuff into the
// !shape.shape type. There's a risk that "progressive lowering" becomes "no
// clear boundaries" and we end up with code deep into the compiler continuously
// needing to doublecheck that the !shape.shape's at this point are in fact
// statically known to be ranked, or silently making that assumption and
// triggering assertions on verifier-valid IR. Pipelines and legalization
// targets could make these assertions not fire in practice, but it would
// be a maintenance burden.
class ConvertConstShapeOp : public OpConversionPattern<shape::ConstShapeOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ConstShapeOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
SmallVector<int64_t, 4> extents;
for (APInt extent : op.shape()) {
extents.push_back(extent.getZExtValue());
}
auto rsType = RankedShapeType::get(extents, rewriter.getContext());
rewriter.replaceOpWithNewOp<ConstRankedShapeOp>(op, rsType);
return success();
}
};
class ConvertShapeOfOp : public OpConversionPattern<shape::ShapeOfOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ShapeOfOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto tensorType = operands[0].getType().dyn_cast<RankedTensorType>();
if (!tensorType) {
return failure();
}
auto resultType =
RankedShapeType::get(tensorType.getShape(), rewriter.getContext());
rewriter.replaceOpWithNewOp<Shape::GetRankedShapeOp>(op, resultType,
operands[0]);
return success();
}
};
class ConvertSplitAtOp : public OpConversionPattern<shape::SplitAtOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::SplitAtOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
IntegerAttr indexAttr;
if (!matchPattern(op.index(), m_Constant(&indexAttr))) {
return rewriter.notifyMatchFailure(op, "requires constant `index`");
}
auto rank = operands[0].getType().cast<RankedShapeType>().getRank();
int64_t index = indexAttr.getInt();
if (index < 0) {
index += rank;
}
auto head_indices = llvm::to_vector<4>(llvm::seq<int64_t>(0, index));
auto tail_indices = llvm::to_vector<4>(llvm::seq<int64_t>(index, rank));
Value head = rewriter.create<GatherExtentsOp>(
op.getLoc(), operands[0], rewriter.getI64TensorAttr(head_indices));
Value tail = rewriter.create<GatherExtentsOp>(
op.getLoc(), operands[0], rewriter.getI64TensorAttr(tail_indices));
rewriter.replaceOp(op, {head, tail});
return success();
}
};
class ConvertBroadcastOp : public OpConversionPattern<shape::BroadcastOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::BroadcastOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
Value lhs = operands[0];
Value rhs = operands[1];
auto lhsType = lhs.getType().cast<RankedShapeType>();
auto rhsType = rhs.getType().cast<RankedShapeType>();
// Establish invariant that rank(lhs) <= rank(rhs)
if (lhsType.getRank() > rhsType.getRank()) {
std::swap(lhsType, rhsType);
std::swap(lhs, rhs);
}
SmallVector<int64_t, 6> resultShape;
OpTrait::util::getBroadcastedShape(lhsType.getAllDims(),
rhsType.getAllDims(), resultShape);
auto resultType = RankedShapeType::get(resultShape, rewriter.getContext());
auto iota = llvm::to_vector<4>(llvm::seq<int64_t>(0, rhsType.getRank()));
rewriter.replaceOpWithNewOp<RankedBroadcastShapeOp>(
op, resultType, lhs, rhs,
/*lhs_broadcast_dimensions=*/
rewriter.getI64TensorAttr(makeArrayRef(iota).drop_front(
rhsType.getRank() - lhsType.getRank())),
/*rhs_broadcast_dimensions=*/
rewriter.getI64TensorAttr(iota));
return success();
}
};
class ConvertConcatOp : public OpConversionPattern<shape::ConcatOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ConcatOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto resultRank = operands[0].getType().cast<RankedShapeType>().getRank() +
operands[1].getType().cast<RankedShapeType>().getRank();
auto indices = llvm::to_vector<4>(llvm::seq<int64_t>(0, resultRank));
rewriter.replaceOpWithNewOp<Shape::GatherExtentsOp>(
op, ValueRange({operands[0], operands[1]}),
rewriter.getI64TensorAttr(indices));
return success();
}
};
class ConvertToExtentTensorOp
: public OpConversionPattern<shape::ToExtentTensorOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ToExtentTensorOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<Shape::ToExtentTensorOp>(op, op.getType(),
operands[0]);
return success();
}
};
class ConvertShapeToShapex
: public PassWrapper<ConvertShapeToShapex, OperationPass<ModuleOp>> {
void runOnOperation() override {
ModuleOp module = getOperation();
MLIRContext *context = &getContext();
// Conversion target definition.
ConversionTarget conversionTarget(*context);
conversionTarget.addIllegalDialect<shape::ShapeDialect>();
conversionTarget.addLegalDialect<iree_compiler::ShapeDialect>();
// Patterns.
OwningRewritePatternList patterns;
patterns.insert<ConvertConstShapeOp>(context);
patterns.insert<ConvertShapeOfOp>(context);
patterns.insert<ConvertSplitAtOp>(context);
patterns.insert<ConvertBroadcastOp>(context);
patterns.insert<ConvertConcatOp>(context);
patterns.insert<ConvertToExtentTensorOp>(context);
if (failed(applyPartialConversion(module, conversionTarget, patterns))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> createConvertShapeToShapexPass() {
return std::make_unique<ConvertShapeToShapex>();
}
static PassRegistration<ConvertShapeToShapex> registration(
"convert-shape-to-shapex", "Convert `shape` dialect to `shapex` dialect");
} // namespace Shape
} // namespace iree_compiler
} // namespace mlir
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iree/compiler/Dialect/Shape/IR/ShapeDialect.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeOps.h"
#include "iree/compiler/Dialect/Shape/IR/ShapeTypes.h"
#include "mlir/Dialect/Shape/IR/Shape.h"
#include "mlir/Dialect/Traits.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace iree_compiler {
namespace Shape {
namespace {
// This conversion is currently quite limited, such as not handling multiple
// basic blocks in general, due to doing a type conversion that the MLIR core
// conversion infra doesn't handle well.
//
// In particular, we convert `!shape.shape` to `!shapex.ranked_shape<...>`, but
// the contents of the `...` are context-dependent. Thus, one could say that
// this pass does a context-dependent type conversion.
//
// The current MLIR conversion infra doesn't handle context-dependent type
// conversions.
//
// I can see two solutions:
//
// 1. Extend the MLIR conversion infra to better support context-dependent type
// conversions. One way to do this would be for the conversion infra to convert
// blocks in RPO and use the type of the converted successor operand in a
// dominating predecessor as the type for the block argument when converting a
// block. A similar thing could be done with an RPO traversal of the callgraph.
// This algorithm wouldn't work in the presence of recursively dead cycles. And
// of course linkage boundaries cannot have a context-dependent type conversion
// (by definition).
//
// 2. Avoid needing to convert to !shapex.ranked_shape in the first place. This
// could be accomplished by generalizing !shape.shape to be able to support the
// use case of !shapex.ranked_shape. One important requirement here is that
// !shapex.ranked_shape models a partially-specified shape (hardcoded for the
// ranked case). !shape.shape could be extended to capture partially-specified
// shapes in the type, such as allowing `!shape.shape<*>` to model an unranked
// shape (which is the default; no information), `!shape.shape<?x?x5x?>` to
// model a rank-4 shape with dimension 2 being of extent 5, etc.
//
// Once we have this, we could do this lowering from generic !shape.shape to
// statically-known ranked shapes more progressively and treat it more like a
// type refinement algorithm.
//
// The main risk is that we are trying to shove too much stuff into the
// !shape.shape type. There's a risk that "progressive lowering" becomes "no
// clear boundaries" and we end up with code deep into the compiler continuously
// needing to doublecheck that the !shape.shape's at this point are in fact
// statically known to be ranked, or silently making that assumption and
// triggering assertions on verifier-valid IR. Pipelines and legalization
// targets could make these assertions not fire in practice, but it would
// be a maintenance burden.
class ConvertConstShapeOp : public OpConversionPattern<shape::ConstShapeOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ConstShapeOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
SmallVector<int64_t, 4> extents;
for (APInt extent : op.shape()) {
extents.push_back(extent.getZExtValue());
}
auto rsType = RankedShapeType::get(extents, rewriter.getContext());
rewriter.replaceOpWithNewOp<ConstRankedShapeOp>(op, rsType);
return success();
}
};
class ConvertShapeOfOp : public OpConversionPattern<shape::ShapeOfOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ShapeOfOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto tensorType = operands[0].getType().dyn_cast<RankedTensorType>();
if (!tensorType) {
return failure();
}
auto resultType =
RankedShapeType::get(tensorType.getShape(), rewriter.getContext());
// TODO(jpienaar): The following needs to be re-evaluated once the patch
// train from 2020/07/23 integrates properly. This is required to make
// it forward and backwards compatible. Also, tests need to be added once
// upstream integrates (and this can be tested).
// rewriter.replaceOpWithNewOp<Shape::GetRankedShapeOp>(op, resultType,
// operands[0]);
auto getRanked = rewriter.create<Shape::GetRankedShapeOp>(
op.getLoc(), resultType, operands[0]);
// For FromExtentTensorOp users, just forward the result from GetRanked.
SmallPtrSet<Operation *, 2> toDelete;
for (auto use : op.getOperation()->getUsers()) {
if (isa<FromExtentTensorOp>(use)) {
use->replaceAllUsesWith(getRanked);
toDelete.insert(use);
}
}
for (Operation *use : toDelete) {
rewriter.eraseOp(use);
}
rewriter.replaceOp(op.getOperation(), getRanked.getResult());
return success();
}
};
class ConvertSplitAtOp : public OpConversionPattern<shape::SplitAtOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::SplitAtOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
IntegerAttr indexAttr;
if (!matchPattern(op.index(), m_Constant(&indexAttr))) {
return rewriter.notifyMatchFailure(op, "requires constant `index`");
}
auto rank = operands[0].getType().cast<RankedShapeType>().getRank();
int64_t index = indexAttr.getInt();
if (index < 0) {
index += rank;
}
auto head_indices = llvm::to_vector<4>(llvm::seq<int64_t>(0, index));
auto tail_indices = llvm::to_vector<4>(llvm::seq<int64_t>(index, rank));
Value head = rewriter.create<GatherExtentsOp>(
op.getLoc(), operands[0], rewriter.getI64TensorAttr(head_indices));
Value tail = rewriter.create<GatherExtentsOp>(
op.getLoc(), operands[0], rewriter.getI64TensorAttr(tail_indices));
rewriter.replaceOp(op, {head, tail});
return success();
}
};
class ConvertBroadcastOp : public OpConversionPattern<shape::BroadcastOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::BroadcastOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
Value lhs = operands[0];
Value rhs = operands[1];
auto lhsType = lhs.getType().cast<RankedShapeType>();
auto rhsType = rhs.getType().cast<RankedShapeType>();
// Establish invariant that rank(lhs) <= rank(rhs)
if (lhsType.getRank() > rhsType.getRank()) {
std::swap(lhsType, rhsType);
std::swap(lhs, rhs);
}
SmallVector<int64_t, 6> resultShape;
OpTrait::util::getBroadcastedShape(lhsType.getAllDims(),
rhsType.getAllDims(), resultShape);
auto resultType = RankedShapeType::get(resultShape, rewriter.getContext());
auto iota = llvm::to_vector<4>(llvm::seq<int64_t>(0, rhsType.getRank()));
rewriter.replaceOpWithNewOp<RankedBroadcastShapeOp>(
op, resultType, lhs, rhs,
/*lhs_broadcast_dimensions=*/
rewriter.getI64TensorAttr(makeArrayRef(iota).drop_front(
rhsType.getRank() - lhsType.getRank())),
/*rhs_broadcast_dimensions=*/
rewriter.getI64TensorAttr(iota));
return success();
}
};
class ConvertConcatOp : public OpConversionPattern<shape::ConcatOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ConcatOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
auto resultRank = operands[0].getType().cast<RankedShapeType>().getRank() +
operands[1].getType().cast<RankedShapeType>().getRank();
auto indices = llvm::to_vector<4>(llvm::seq<int64_t>(0, resultRank));
rewriter.replaceOpWithNewOp<Shape::GatherExtentsOp>(
op, ValueRange({operands[0], operands[1]}),
rewriter.getI64TensorAttr(indices));
return success();
}
};
class ConvertToExtentTensorOp
: public OpConversionPattern<shape::ToExtentTensorOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult matchAndRewrite(
shape::ToExtentTensorOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<Shape::ToExtentTensorOp>(op, op.getType(),
operands[0]);
return success();
}
};
class ConvertShapeToShapex
: public PassWrapper<ConvertShapeToShapex, OperationPass<ModuleOp>> {
void runOnOperation() override {
ModuleOp module = getOperation();
MLIRContext *context = &getContext();
// Conversion target definition.
ConversionTarget conversionTarget(*context);
conversionTarget.addIllegalDialect<shape::ShapeDialect>();
conversionTarget.addLegalDialect<iree_compiler::ShapeDialect>();
// Patterns.
OwningRewritePatternList patterns;
patterns.insert<ConvertConstShapeOp>(context);
patterns.insert<ConvertShapeOfOp>(context);
patterns.insert<ConvertSplitAtOp>(context);
patterns.insert<ConvertBroadcastOp>(context);
patterns.insert<ConvertConcatOp>(context);
patterns.insert<ConvertToExtentTensorOp>(context);
if (failed(applyPartialConversion(module, conversionTarget, patterns))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> createConvertShapeToShapexPass() {
return std::make_unique<ConvertShapeToShapex>();
}
static PassRegistration<ConvertShapeToShapex> registration(
"convert-shape-to-shapex", "Convert `shape` dialect to `shapex` dialect");
} // namespace Shape
} // namespace iree_compiler
} // namespace mlir
|
Handle case where shape.shape_of feeds into from_extent_tensor.
|
[shapex] Handle case where shape.shape_of feeds into from_extent_tensor.
Pre-fetching for upstream change where shape.shape_of can produce a
ranked tensor of index, rather than just a shape and post
canonicalization one has a shape.shape_of feeding into a
shapex.from_extent_tensor directly. The lowering of shape_of ti
get_ranked_shape then leads to an invalid ranked_tensor as input to
from_extent_tensor, e.g.,
%63 = "shapex.get_ranked_shape"(%55) : (tensor<?x10xf32>) -> !shapex.ranked_shape<[?,10]>
%64 = "shapex.from_extent_tensor"(%63) : (!shapex.ranked_shape<[?,10]>) -> !shapex.ranked_shape<[?,?]>
Avoid this by removing the from_extent_tensor in these cases and
propagating the value from get_ranked_shape directly.
Author: Jacques Pienaar <[email protected]>
Closes: #2667
PiperOrigin-RevId: 323194382
|
C++
|
apache-2.0
|
google/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,google/iree,iree-org/iree,iree-org/iree,google/iree,iree-org/iree,google/iree,iree-org/iree,iree-org/iree
|
93b6da21e10f82283e2bab783558c1e87eb53714
|
src/arch/mips64.cpp
|
src/arch/mips64.cpp
|
#include "arch.h"
#include <algorithm>
#include <array>
// SP + 8 points to the first argument that is passed on the stack
#define ARG0_STACK 8
namespace bpftrace {
namespace arch {
// clang-format off
static std::array<std::string, 32> registers = {
"zero",
"at",
"v0",
"v1",
"a0",
"a1",
"a2",
"a3",
"a4",
"a5",
"a6",
"a7",
"t0",
"t1",
"t2",
"t3",
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"t8",
"t9",
"k0",
"k1",
"gp",
"sp",
"fp/s8",
"ra",
};
// Alternative register names that match struct pt_regs
static std::array<std::string, 32> ptrace_registers = {
"regs[0]",
"regs[1]",
"regs[2]",
"regs[3]",
"regs[4]",
"regs[5]",
"regs[6]",
"regs[7]",
"regs[8]",
"regs[9]",
"regs[10]",
"regs[11]",
"regs[12]",
"regs[13]",
"regs[14]",
"regs[15]",
"regs[16]",
"regs[17]",
"regs[18]",
"regs[19]",
"regs[20]",
"regs[21]",
"regs[22]",
"regs[23]",
"regs[24]",
"regs[25]",
"regs[26]",
"regs[27]",
"regs[28]",
"regs[29]",
"regs[30]",
"regs[31]",
};
static std::array<std::string, 8> arg_registers = {
"a0",
"a1",
"a2",
"a3",
"a4",
"a5",
"a6",
"a7",
};
// clang-format on
int offset(std::string reg_name)
{
auto it = find(registers.begin(), registers.end(), reg_name);
if (it == registers.end())
{
// Also allow register names that match the fields in struct pt_regs.
// These appear in USDT probe arguments.
it = find(ptrace_registers.begin(), ptrace_registers.end(), reg_name);
if (it == ptrace_registers.end())
{
return -1;
}
return distance(ptrace_registers.begin(), it);
}
return distance(registers.begin(), it);
}
int max_arg()
{
return arg_registers.size() - 1;
}
int arg_offset(int arg_num)
{
return offset(arg_registers.at(arg_num));
}
#pragma GCC push_options
#pragma GCC optimize("O0")
static int *__getpc(void)
{
int *rtaddr;
__asm__ volatile("move %0, $31" : "=r"(rtaddr));
return rtaddr;
}
#pragma GCC pop_options
int pc_offset()
{
int *retAddr, pc;
retAddr = __getpc();
pc = *retAddr;
return pc;
}
int ret_offset()
{
return offset("v0");
}
int sp_offset()
{
return offset("sp");
}
int arg_stack_offset()
{
return ARG0_STACK / 8;
}
std::string name()
{
return std::string("mips64");
}
} // namespace arch
} // namespace bpftrace
|
#include "arch.h"
#include <algorithm>
#include <array>
// SP + 8 points to the first argument that is passed on the stack
#define ARG0_STACK 8
namespace bpftrace {
namespace arch {
// clang-format off
static std::array<std::string, 32> registers = {
"zero",
"at",
"v0",
"v1",
"a0",
"a1",
"a2",
"a3",
"a4",
"a5",
"a6",
"a7",
"t0",
"t1",
"t2",
"t3",
"s0",
"s1",
"s2",
"s3",
"s4",
"s5",
"s6",
"s7",
"t8",
"t9",
"k0",
"k1",
"gp",
"sp",
"fp/s8",
"ra",
};
// Alternative register names that match struct pt_regs
static std::array<std::string, 32> ptrace_registers = {
"regs[0]",
"regs[1]",
"regs[2]",
"regs[3]",
"regs[4]",
"regs[5]",
"regs[6]",
"regs[7]",
"regs[8]",
"regs[9]",
"regs[10]",
"regs[11]",
"regs[12]",
"regs[13]",
"regs[14]",
"regs[15]",
"regs[16]",
"regs[17]",
"regs[18]",
"regs[19]",
"regs[20]",
"regs[21]",
"regs[22]",
"regs[23]",
"regs[24]",
"regs[25]",
"regs[26]",
"regs[27]",
"regs[28]",
"regs[29]",
"regs[30]",
"regs[31]",
};
static std::array<std::string, 8> arg_registers = {
"a0",
"a1",
"a2",
"a3",
"a4",
"a5",
"a6",
"a7",
};
// clang-format on
int offset(std::string reg_name)
{
auto it = find(registers.begin(), registers.end(), reg_name);
if (it == registers.end())
{
// Also allow register names that match the fields in struct pt_regs.
// These appear in USDT probe arguments.
it = find(ptrace_registers.begin(), ptrace_registers.end(), reg_name);
if (it == ptrace_registers.end())
{
return -1;
}
return distance(ptrace_registers.begin(), it);
}
return distance(registers.begin(), it);
}
int max_arg()
{
return arg_registers.size() - 1;
}
int arg_offset(int arg_num)
{
return offset(arg_registers.at(arg_num));
}
#pragma GCC push_options
#pragma GCC optimize("O0")
static int *__getpc(void)
{
int *rtaddr;
__asm__ volatile("move %0, $31" : "=r"(rtaddr));
return rtaddr;
}
#pragma GCC pop_options
int pc_offset()
{
int *retAddr, pc;
retAddr = __getpc();
pc = *retAddr;
return pc;
}
int ret_offset()
{
return offset("v0");
}
int sp_offset()
{
return offset("sp");
}
int arg_stack_offset()
{
return ARG0_STACK / 8;
}
std::string name()
{
return std::string("mips64");
}
std::vector<std::string> invalid_watchpoint_modes()
{
throw std::runtime_error(
"Watchpoints are not supported on this architecture");
}
} // namespace arch
} // namespace bpftrace
|
Add invalid_watchpoint_modes function in mips
|
Add invalid_watchpoint_modes function in mips
|
C++
|
apache-2.0
|
iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace,iovisor/bpftrace
|
687f0c7dc0324192d71f2165552e81a9d4346b4a
|
hal/lib/athena/SerialHelper.cpp
|
hal/lib/athena/SerialHelper.cpp
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "SerialHelper.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <regex>
#include "HAL/Errors.h"
#include "llvm/StringRef.h"
#include "visa/visa.h"
constexpr const char* OnboardResource = "ASRL1::INSTR";
constexpr const char* MxpResource = "ASRL2::INSTR";
namespace hal {
std::string SerialHelper::m_usbNames[2]{"", ""};
priority_mutex SerialHelper::m_nameMutex;
SerialHelper::SerialHelper(int32_t resourceHandle)
: m_resourceHandle(resourceHandle) {}
std::string SerialHelper::GetSerialPortName(HAL_SerialPort port,
int32_t* status) {
if (port == HAL_SerialPort::HAL_SerialPort_Onboard) {
return OnboardResource;
} else if (port == HAL_SerialPort::HAL_SerialPort_MXP) {
return MxpResource;
}
QueryHubPaths(status);
// If paths are empty or status error, return error
if (*status != 0 || m_visaResource.empty() || m_osResource.empty() ||
m_sortedHubPath.empty()) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
// Hold lock whenever we're using the names array
std::lock_guard<priority_mutex> lock(m_nameMutex);
std::string portString = m_usbNames[port - 2];
llvm::SmallVector<int32_t, 4> indices;
// If port has not been assigned, find the one to assign
if (portString.empty()) {
for (size_t i = 0; i < 2; i++) {
// Remove all used ports
auto idx = std::find(m_sortedHubPath.begin(), m_sortedHubPath.end(),
m_usbNames[i]);
if (idx != m_sortedHubPath.end()) {
// found
m_sortedHubPath.erase(idx);
}
if (m_usbNames[i] == "") {
indices.push_back(i);
}
}
int32_t idx = -1;
for (size_t i = 0; i < indices.size(); i++) {
if (indices[i] == port - 2) {
idx = i;
break;
}
}
if (idx == -1) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
if (idx >= static_cast<int32_t>(m_sortedHubPath.size())) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
portString = m_sortedHubPath[idx].str();
m_usbNames[port - 2] = portString;
}
int visaIndex = -1;
for (size_t i = 0; i < m_sortedHubPath.size(); i++) {
if (m_sortedHubPath[i].equals(portString)) {
visaIndex = i;
break;
}
}
if (visaIndex == -1) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
// Error
} else {
return m_visaResource[visaIndex].str();
}
}
void SerialHelper::SortHubPathVector() {
m_sortedHubPath.clear();
m_sortedHubPath = m_unsortedHubPath;
std::sort(m_sortedHubPath.begin(), m_sortedHubPath.end(),
[](llvm::SmallVectorImpl<char>& lhs,
llvm::SmallVectorImpl<char>& rhs) -> int {
llvm::StringRef lhsRef(lhs.begin(), lhs.size());
llvm::StringRef rhsRef(rhs.begin(), rhs.size());
return lhsRef.compare(rhsRef);
});
}
void SerialHelper::CoiteratedSort(
llvm::SmallVectorImpl<llvm::SmallString<16>>& vec) {
llvm::SmallVector<llvm::SmallString<16>, 4> sortedVec;
for (auto& str : m_sortedHubPath) {
for (size_t i = 0; i < m_unsortedHubPath.size(); i++) {
if (llvm::StringRef{m_unsortedHubPath[i].begin(),
m_unsortedHubPath[i].size()}
.equals(llvm::StringRef{str.begin(), str.size()})) {
sortedVec.push_back(vec[i]);
break;
}
}
}
vec = sortedVec;
}
void SerialHelper::QueryHubPaths(int32_t* status) {
// VISA resource matching string
const char* str = "?*";
// Items needed for VISA
ViUInt32 retCnt = 0;
ViFindList viList = 0;
ViChar desc[VI_FIND_BUFLEN];
*status = viFindRsrc(m_resourceHandle, const_cast<char*>(str), &viList,
&retCnt, desc);
if (*status < 0) {
// Handle the bad status elsewhere
// Note let positive statii (warnings) continue
return;
}
// Status might be positive, so reset it to 0
*status = 0;
// Storage buffers for Visa calls and system exec calls
char osName[256];
char execBuffer[128];
// Regex to filter out the device name
// Will be index 1 on success
std::regex devMatch("[^\\s]+\\s+\\(\\/dev\\/([^\\s]+)\\)");
// Loop through all returned VISA objects.
// Increment the internal VISA ptr every loop
for (size_t i = 0; i < retCnt; i++, viFindNext(viList, desc)) {
// Ignore any matches to the 2 onboard ports
if (std::strcmp(OnboardResource, desc) == 0 ||
std::strcmp(MxpResource, desc) == 0) {
continue;
}
// Open the resource, grab its interface name, and close it.
ViSession vSession;
*status = viOpen(m_resourceHandle, desc, VI_NULL, VI_NULL, &vSession);
if (*status < 0) return;
*status = 0;
*status = viGetAttribute(vSession, VI_ATTR_INTF_INST_NAME, &osName);
// Ignore an error here, as we want to close the session on an error
// Use a seperate close variable so we can check
ViStatus closeStatus = viClose(vSession);
if (*status < 0) return;
if (closeStatus < 0) return;
*status = 0;
std::smatch regexMatcher;
auto regexVal =
std::regex_match(std::string(osName), regexMatcher, devMatch);
if (regexVal > 0 && regexMatcher.size() > 1) {
// Store our match string, as output was ocassionally being corrupted
// before being accessed
auto matchString = regexMatcher[1].str();
// Run find using pipe to get a list of system accessors
llvm::SmallString<128> val(
"sh -c \"find /sys/devices/soc0 | grep amba | grep usb | grep ");
val += matchString;
val += "\"";
// Pipe code found on StackOverflow
// http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix
// Using std::string because this is guarenteed to be large
std::string output = "";
std::shared_ptr<FILE> pipe(popen(val.c_str(), "r"), pclose);
// Just check the next item on a pipe failure
if (!pipe) continue;
while (!feof(pipe.get())) {
if (std::fgets(execBuffer, 128, pipe.get()) != 0) output += execBuffer;
}
if (!output.empty()) {
llvm::SmallVector<llvm::StringRef, 16> pathSplitVec;
// Split output by line, grab first line, and split it into
// individual directories
llvm::StringRef{output}.split('\n').first.split(pathSplitVec, '/', -1,
false);
// Find each individual item index
const char* usb1 = "usb1";
const char* tty = "tty";
int findusb = -1;
int findtty = -1;
int findregex = -1;
for (size_t i = 0; i < pathSplitVec.size(); i++) {
if (findusb == -1 && pathSplitVec[i].equals(usb1)) {
findusb = i;
}
if (findtty == -1 && pathSplitVec[i].equals(tty)) {
findtty = i;
}
if (findregex == -1 && pathSplitVec[i].equals(matchString)) {
findregex = i;
}
}
// Get the index for our device
int hubIndex = findtty;
if (findtty == -1) hubIndex = findregex;
int devStart = findusb + 1;
if (hubIndex < devStart) continue;
// Add our devices to our list
m_unsortedHubPath.push_back(
llvm::StringRef{pathSplitVec[hubIndex - 2]});
m_visaResource.push_back(llvm::StringRef{desc});
m_osResource.push_back(llvm::StringRef{matchString});
}
}
}
SortHubPathVector();
CoiteratedSort(m_visaResource);
CoiteratedSort(m_osResource);
}
} // namespace hal
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "SerialHelper.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <regex>
#include "HAL/Errors.h"
#include "llvm/StringRef.h"
#include "visa/visa.h"
constexpr const char* OnboardResource = "ASRL1::INSTR";
constexpr const char* MxpResource = "ASRL2::INSTR";
namespace hal {
std::string SerialHelper::m_usbNames[2]{"", ""};
priority_mutex SerialHelper::m_nameMutex;
SerialHelper::SerialHelper(int32_t resourceHandle)
: m_resourceHandle(resourceHandle) {}
std::string SerialHelper::GetSerialPortName(HAL_SerialPort port,
int32_t* status) {
if (port == HAL_SerialPort::HAL_SerialPort_Onboard) {
return OnboardResource;
} else if (port == HAL_SerialPort::HAL_SerialPort_MXP) {
return MxpResource;
}
QueryHubPaths(status);
// If paths are empty or status error, return error
if (*status != 0 || m_visaResource.empty() || m_osResource.empty() ||
m_sortedHubPath.empty()) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
// Hold lock whenever we're using the names array
std::lock_guard<priority_mutex> lock(m_nameMutex);
std::string portString = m_usbNames[port - 2];
llvm::SmallVector<int32_t, 4> indices;
// If port has not been assigned, find the one to assign
if (portString.empty()) {
for (size_t i = 0; i < 2; i++) {
// Remove all used ports
auto idx = std::find(m_sortedHubPath.begin(), m_sortedHubPath.end(),
m_usbNames[i]);
if (idx != m_sortedHubPath.end()) {
// found
m_sortedHubPath.erase(idx);
}
if (m_usbNames[i] == "") {
indices.push_back(i);
}
}
int32_t idx = -1;
for (size_t i = 0; i < indices.size(); i++) {
if (indices[i] == port - 2) {
idx = i;
break;
}
}
if (idx == -1) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
if (idx >= static_cast<int32_t>(m_sortedHubPath.size())) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
}
portString = m_sortedHubPath[idx].str();
m_usbNames[port - 2] = portString;
}
int visaIndex = -1;
for (size_t i = 0; i < m_sortedHubPath.size(); i++) {
if (m_sortedHubPath[i].equals(portString)) {
visaIndex = i;
break;
}
}
if (visaIndex == -1) {
*status = HAL_SERIAL_PORT_NOT_FOUND;
return "";
// Error
} else {
return m_visaResource[visaIndex].str();
}
}
void SerialHelper::SortHubPathVector() {
m_sortedHubPath.clear();
m_sortedHubPath = m_unsortedHubPath;
std::sort(m_sortedHubPath.begin(), m_sortedHubPath.end(),
[](const llvm::SmallVectorImpl<char>& lhs,
const llvm::SmallVectorImpl<char>& rhs) -> int {
llvm::StringRef lhsRef(lhs.begin(), lhs.size());
llvm::StringRef rhsRef(rhs.begin(), rhs.size());
return lhsRef.compare(rhsRef);
});
}
void SerialHelper::CoiteratedSort(
llvm::SmallVectorImpl<llvm::SmallString<16>>& vec) {
llvm::SmallVector<llvm::SmallString<16>, 4> sortedVec;
for (auto& str : m_sortedHubPath) {
for (size_t i = 0; i < m_unsortedHubPath.size(); i++) {
if (llvm::StringRef{m_unsortedHubPath[i].begin(),
m_unsortedHubPath[i].size()}
.equals(llvm::StringRef{str.begin(), str.size()})) {
sortedVec.push_back(vec[i]);
break;
}
}
}
vec = sortedVec;
}
void SerialHelper::QueryHubPaths(int32_t* status) {
// VISA resource matching string
const char* str = "?*";
// Items needed for VISA
ViUInt32 retCnt = 0;
ViFindList viList = 0;
ViChar desc[VI_FIND_BUFLEN];
*status = viFindRsrc(m_resourceHandle, const_cast<char*>(str), &viList,
&retCnt, desc);
if (*status < 0) {
// Handle the bad status elsewhere
// Note let positive statii (warnings) continue
return;
}
// Status might be positive, so reset it to 0
*status = 0;
// Storage buffers for Visa calls and system exec calls
char osName[256];
char execBuffer[128];
// Regex to filter out the device name
// Will be index 1 on success
std::regex devMatch("[^\\s]+\\s+\\(\\/dev\\/([^\\s]+)\\)");
// Loop through all returned VISA objects.
// Increment the internal VISA ptr every loop
for (size_t i = 0; i < retCnt; i++, viFindNext(viList, desc)) {
// Ignore any matches to the 2 onboard ports
if (std::strcmp(OnboardResource, desc) == 0 ||
std::strcmp(MxpResource, desc) == 0) {
continue;
}
// Open the resource, grab its interface name, and close it.
ViSession vSession;
*status = viOpen(m_resourceHandle, desc, VI_NULL, VI_NULL, &vSession);
if (*status < 0) return;
*status = 0;
*status = viGetAttribute(vSession, VI_ATTR_INTF_INST_NAME, &osName);
// Ignore an error here, as we want to close the session on an error
// Use a seperate close variable so we can check
ViStatus closeStatus = viClose(vSession);
if (*status < 0) return;
if (closeStatus < 0) return;
*status = 0;
std::smatch regexMatcher;
auto regexVal =
std::regex_match(std::string(osName), regexMatcher, devMatch);
if (regexVal > 0 && regexMatcher.size() > 1) {
// Store our match string, as output was ocassionally being corrupted
// before being accessed
auto matchString = regexMatcher[1].str();
// Run find using pipe to get a list of system accessors
llvm::SmallString<128> val(
"sh -c \"find /sys/devices/soc0 | grep amba | grep usb | grep ");
val += matchString;
val += "\"";
// Pipe code found on StackOverflow
// http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix
// Using std::string because this is guarenteed to be large
std::string output = "";
std::shared_ptr<FILE> pipe(popen(val.c_str(), "r"), pclose);
// Just check the next item on a pipe failure
if (!pipe) continue;
while (!feof(pipe.get())) {
if (std::fgets(execBuffer, 128, pipe.get()) != 0) output += execBuffer;
}
if (!output.empty()) {
llvm::SmallVector<llvm::StringRef, 16> pathSplitVec;
// Split output by line, grab first line, and split it into
// individual directories
llvm::StringRef{output}.split('\n').first.split(pathSplitVec, '/', -1,
false);
// Find each individual item index
const char* usb1 = "usb1";
const char* tty = "tty";
int findusb = -1;
int findtty = -1;
int findregex = -1;
for (size_t i = 0; i < pathSplitVec.size(); i++) {
if (findusb == -1 && pathSplitVec[i].equals(usb1)) {
findusb = i;
}
if (findtty == -1 && pathSplitVec[i].equals(tty)) {
findtty = i;
}
if (findregex == -1 && pathSplitVec[i].equals(matchString)) {
findregex = i;
}
}
// Get the index for our device
int hubIndex = findtty;
if (findtty == -1) hubIndex = findregex;
int devStart = findusb + 1;
if (hubIndex < devStart) continue;
// Add our devices to our list
m_unsortedHubPath.push_back(
llvm::StringRef{pathSplitVec[hubIndex - 2]});
m_visaResource.push_back(llvm::StringRef{desc});
m_osResource.push_back(llvm::StringRef{matchString});
}
}
}
SortHubPathVector();
CoiteratedSort(m_visaResource);
CoiteratedSort(m_osResource);
}
} // namespace hal
|
Use const parameters in std::sort lambda. (#364)
|
Use const parameters in std::sort lambda. (#364)
This is more correct, and non-const fails on gcc 4.8.
|
C++
|
bsd-3-clause
|
robotdotnet/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,robotdotnet/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,333fred/allwpilib,robotdotnet/allwpilib,333fred/allwpilib,333fred/allwpilib
|
bc1e4bcfa8e7d6d04c3afbd3354ed43108d6fea3
|
arch/exception_handler.cc
|
arch/exception_handler.cc
|
/* exception_handler.cc
Jeremy Barnes, 26 February 2008
Copyright (c) 2009 Jeremy Barnes. All rights reserved.
*/
#include <cxxabi.h>
#include <fstream>
#include "jml/compiler/compiler.h"
#include "jml/utils/environment.h"
#include "backtrace.h"
#include "demangle.h"
#include "exception.h"
#include "exception_hook.h"
#include "format.h"
#include "threads.h"
using namespace std;
namespace ML {
void (*exception_tracer) (void *, const std::type_info *) JML_WEAK_FN = 0;
Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true);
__thread bool trace_exceptions = false;
__thread bool trace_exceptions_initialized = false;
void set_default_trace_exceptions(bool val)
{
TRACE_EXCEPTIONS.set(val);
}
bool get_default_trace_exceptions()
{
return TRACE_EXCEPTIONS;
}
void set_trace_exceptions(bool trace)
{
//cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions
// << endl;
trace_exceptions = trace;
trace_exceptions_initialized = true;
}
bool get_trace_exceptions()
{
if (!trace_exceptions_initialized) {
//cerr << "trace_exceptions initialized to = "
// << trace_exceptions << " at " << &trace_exceptions << endl;
set_trace_exceptions(TRACE_EXCEPTIONS);
trace_exceptions_initialized = true;
}
//cerr << "get_trace_exceptions returned " << trace_exceptions
// << " at " << &trace_exceptions << endl;
return trace_exceptions;
}
static const std::exception *
to_std_exception(void* object, const std::type_info * tinfo)
{
/* Check if its a class. If not, we can't see if it's a std::exception.
The abi::__class_type_info is the base class of all types of type
info for types that are classes (of which std::exception is one).
*/
const abi::__class_type_info * ctinfo
= dynamic_cast<const abi::__class_type_info *>(tinfo);
if (!ctinfo) return 0;
/* The thing thrown was an object. Now, check if it is derived from
std::exception. */
const std::type_info * etinfo = &typeid(std::exception);
/* See if the exception could catch this. This is the mechanism
used internally by the compiler in catch {} blocks to see if
the exception matches the catch type.
In the case of success, the object will be adjusted to point to
the start of the std::exception object.
*/
void * obj_ptr = object;
bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);
if (!can_catch) return 0;
/* obj_ptr points to a std::exception; extract it and get the
exception message.
*/
return (const std::exception *)obj_ptr;
}
/** We install this handler for when an exception is thrown. */
void trace_exception(void * object, const std::type_info * tinfo)
{
//cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions()
// << " at " << &trace_exceptions << endl;
if (!get_trace_exceptions()) return;
const std::exception * exc = to_std_exception(object, tinfo);
// We don't want these exceptions to be printed out.
if (dynamic_cast<const ML::SilentException *>(exc)) return;
/* avoid allocations when std::bad_alloc is thrown */
bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);
size_t bufferSize(1024*1024);
char buffer[bufferSize];
char datetime[128];
size_t totalWritten(0), written, remaining(bufferSize);
time_t now;
time(&now);
strftime(datetime, sizeof(datetime), "%FT%H:%M:%S", localtime(&now));
const char * demangled;
char * heapDemangled;
if (noAlloc) {
heapDemangled = nullptr;
demangled = "std::bad_alloc";
}
else {
heapDemangled = char_demangle(tinfo->name());
demangled = heapDemangled;
}
auto pid = getpid();
auto tid = gettid();
written = ::snprintf(buffer, remaining,
"\n"
"--------------------------[Exception thrown]"
"---------------------------\n"
"time: %s\n"
"type: %s\n"
"pid: %d; tid: %d\n",
datetime, demangled, pid, tid);
if (heapDemangled) {
free(heapDemangled);
}
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
if (exc) {
written = snprintf(buffer + totalWritten, remaining,
"what: %s\n", exc->what());
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
}
if (noAlloc) {
goto end;
}
written = snprintf(buffer + totalWritten, remaining, "stack:\n");
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
written = backtrace(buffer + totalWritten, remaining, 3);
if (written >= remaining) {
goto end;
}
totalWritten += written;
if (totalWritten < bufferSize - 1) {
strcpy(buffer + totalWritten, "\n");
}
end:
cerr << buffer;
char const * reports = getenv("ENABLE_EXCEPTION_REPORTS");
if (!noAlloc && reports) {
std::string path = ML::format("%s/exception-report-%s-%d-%d.log",
reports, datetime, pid, tid);
std::ofstream file(path, std::ios_base::app);
if(file) {
file << getenv("_") << endl;
backtrace(file, 3);
file.close();
}
}
}
namespace {
struct Install_Handler {
Install_Handler()
{
//cerr << "installing exception tracer" << endl;
exception_tracer = trace_exception;
}
~Install_Handler()
{
if (exception_tracer == trace_exception)
exception_tracer = 0;
}
} install_handler;
} // file scope
} // namespace ML
|
/* exception_handler.cc
Jeremy Barnes, 26 February 2008
Copyright (c) 2009 Jeremy Barnes. All rights reserved.
*/
#include <cxxabi.h>
#include <cstring>
#include <fstream>
#include "jml/compiler/compiler.h"
#include "jml/utils/environment.h"
#include "backtrace.h"
#include "demangle.h"
#include "exception.h"
#include "exception_hook.h"
#include "format.h"
#include "threads.h"
using namespace std;
namespace ML {
void (*exception_tracer) (void *, const std::type_info *) JML_WEAK_FN = 0;
Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true);
__thread bool trace_exceptions = false;
__thread bool trace_exceptions_initialized = false;
void set_default_trace_exceptions(bool val)
{
TRACE_EXCEPTIONS.set(val);
}
bool get_default_trace_exceptions()
{
return TRACE_EXCEPTIONS;
}
void set_trace_exceptions(bool trace)
{
//cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions
// << endl;
trace_exceptions = trace;
trace_exceptions_initialized = true;
}
bool get_trace_exceptions()
{
if (!trace_exceptions_initialized) {
//cerr << "trace_exceptions initialized to = "
// << trace_exceptions << " at " << &trace_exceptions << endl;
set_trace_exceptions(TRACE_EXCEPTIONS);
trace_exceptions_initialized = true;
}
//cerr << "get_trace_exceptions returned " << trace_exceptions
// << " at " << &trace_exceptions << endl;
return trace_exceptions;
}
static const std::exception *
to_std_exception(void* object, const std::type_info * tinfo)
{
/* Check if its a class. If not, we can't see if it's a std::exception.
The abi::__class_type_info is the base class of all types of type
info for types that are classes (of which std::exception is one).
*/
const abi::__class_type_info * ctinfo
= dynamic_cast<const abi::__class_type_info *>(tinfo);
if (!ctinfo) return 0;
/* The thing thrown was an object. Now, check if it is derived from
std::exception. */
const std::type_info * etinfo = &typeid(std::exception);
/* See if the exception could catch this. This is the mechanism
used internally by the compiler in catch {} blocks to see if
the exception matches the catch type.
In the case of success, the object will be adjusted to point to
the start of the std::exception object.
*/
void * obj_ptr = object;
bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);
if (!can_catch) return 0;
/* obj_ptr points to a std::exception; extract it and get the
exception message.
*/
return (const std::exception *)obj_ptr;
}
/** We install this handler for when an exception is thrown. */
void trace_exception(void * object, const std::type_info * tinfo)
{
//cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions()
// << " at " << &trace_exceptions << endl;
if (!get_trace_exceptions()) return;
const std::exception * exc = to_std_exception(object, tinfo);
// We don't want these exceptions to be printed out.
if (dynamic_cast<const ML::SilentException *>(exc)) return;
/* avoid allocations when std::bad_alloc is thrown */
bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);
size_t bufferSize(1024*1024);
char buffer[bufferSize];
char datetime[128];
size_t totalWritten(0), written, remaining(bufferSize);
time_t now;
time(&now);
strftime(datetime, sizeof(datetime), "%FT%H:%M:%S", localtime(&now));
const char * demangled;
char * heapDemangled;
if (noAlloc) {
heapDemangled = nullptr;
demangled = "std::bad_alloc";
}
else {
heapDemangled = char_demangle(tinfo->name());
demangled = heapDemangled;
}
auto pid = getpid();
auto tid = gettid();
written = ::snprintf(buffer, remaining,
"\n"
"--------------------------[Exception thrown]"
"---------------------------\n"
"time: %s\n"
"type: %s\n"
"pid: %d; tid: %d\n",
datetime, demangled, pid, tid);
if (heapDemangled) {
free(heapDemangled);
}
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
if (exc) {
written = snprintf(buffer + totalWritten, remaining,
"what: %s\n", exc->what());
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
}
if (noAlloc) {
goto end;
}
written = snprintf(buffer + totalWritten, remaining, "stack:\n");
if (written >= remaining) {
goto end;
}
totalWritten += written;
remaining -= written;
written = backtrace(buffer + totalWritten, remaining, 3);
if (written >= remaining) {
goto end;
}
totalWritten += written;
if (totalWritten < bufferSize - 1) {
strcpy(buffer + totalWritten, "\n");
}
end:
cerr << buffer;
char const * reports = getenv("ENABLE_EXCEPTION_REPORTS");
if (!noAlloc && reports) {
std::string path = ML::format("%s/exception-report-%s-%d-%d.log",
reports, datetime, pid, tid);
std::ofstream file(path, std::ios_base::app);
if(file) {
file << getenv("_") << endl;
backtrace(file, 3);
file.close();
}
}
}
namespace {
struct Install_Handler {
Install_Handler()
{
//cerr << "installing exception tracer" << endl;
exception_tracer = trace_exception;
}
~Install_Handler()
{
if (exception_tracer == trace_exception)
exception_tracer = 0;
}
} install_handler;
} // file scope
} // namespace ML
|
include cstring so that strcpy is declared
|
PLAT-545: include cstring so that strcpy is declared
|
C++
|
apache-2.0
|
rtbkit/rtbkit,emmanuelleparquier/rtbkitinstall,rtbkit/rtbkit,wesley1001/rtbkit,Motrixi/rtbkit-vainilla,ksurendra/rtbkit,monoj-khatua/rtbkit,emmanuelleparquier/rtbkitinstall,ksurendra/rtbkit,OrbitScripts/rtbkit,wesley1001/rtbkit,meiry/rtbkit,pablin87/rtbkit,wesley1001/rtbkit,pablin87/rtbkit,winclap/rtbkit,pablin87/rtbkit,pswaminathan/rtbkit,emmanuelleparquier/rtbkitinstall,Motrixi/rtbkit-public,nagyistoce/StockExchange-RealTimeBidder-kit,winclap/rtbkit,ksurendra/rtbkit,pswaminathan/rtbkit,pswaminathan/rtbkit,wesley1001/rtbkit,datacratic/rtbkit,niko-lay/rtbkit,datacratic/rtbkit,OrbitScripts/rtbkit,monoj-khatua/rtbkit,ksurendra/rtbkit,Motrixi/rtbkit-vainilla,datacratic/DasDB,meiry/rtbkit,pswaminathan/rtbkit,OrbitScripts/rtbkit,meiry/rtbkit,monoj-khatua/rtbkit,nagyistoce/StockExchange-RealTimeBidder-kit,datacratic/rtbkit,meiry/rtbkit,dinomyte72/rtbkit,dinomyte72/rtbkit,dinomyte72/rtbkit,nagyistoce/StockExchange-RealTimeBidder-kit,Motrixi/rtbkit-public,datacratic/rtbkit,OrbitScripts/rtbkit,winclap/rtbkit,datacratic/DasDB,pablin87/rtbkit,datacratic/DasDB,emmanuelleparquier/rtbkitinstall,datacratic/rtbkit,Motrixi/rtbkit-vainilla,emmanuelleparquier/rtbkitinstall,pablin87/rtbkit,monoj-khatua/rtbkit,Motrixi/rtbkit-vainilla,Motrixi/rtbkit-public,niko-lay/rtbkit,pablin87/rtbkit,ksurendra/rtbkit,datacratic/DasDB,dinomyte72/rtbkit,niko-lay/rtbkit,winclap/rtbkit,OrbitScripts/rtbkit,wesley1001/rtbkit,nagyistoce/StockExchange-RealTimeBidder-kit,Motrixi/rtbkit-public,datacratic/rtbkit,OrbitScripts/rtbkit,wesley1001/rtbkit,nagyistoce/StockExchange-RealTimeBidder-kit,Motrixi/rtbkit-public,emmanuelleparquier/rtbkitinstall,dinomyte72/rtbkit,ksurendra/rtbkit,niko-lay/rtbkit,niko-lay/rtbkit,Motrixi/rtbkit-public,pswaminathan/rtbkit,Motrixi/rtbkit-vainilla,monoj-khatua/rtbkit,meiry/rtbkit,rtbkit/rtbkit,rtbkit/rtbkit,rtbkit/rtbkit,niko-lay/rtbkit,rtbkit/rtbkit,winclap/rtbkit,monoj-khatua/rtbkit,meiry/rtbkit,dinomyte72/rtbkit,nagyistoce/StockExchange-RealTimeBidder-kit,pswaminathan/rtbkit,winclap/rtbkit,datacratic/DasDB
|
609c2432e9d463dda59d5a178b0d7850a65d2e33
|
src/backenddata.cpp
|
src/backenddata.cpp
|
#include "backenddata.h"
#include "debug.h"
#include "tasks-tarsnap.h"
BackendData::BackendData()
{
}
QMap<QString, JobPtr> BackendData::jobs()
{
return _jobMap;
}
QMap<QString, ArchivePtr> BackendData::archives()
{
return _archiveMap;
}
quint64 BackendData::numArchives()
{
return static_cast<quint64>(_archiveMap.count());
}
bool BackendData::loadArchives()
{
_archiveMap.clear();
if(!global_store->initialized())
{
DEBUG << "PersistentStore was not initialized properly.";
return false;
}
QSqlQuery query = global_store->createQuery();
if(!query.prepare(QLatin1String("select name from archives")))
{
DEBUG << query.lastError().text();
return false;
}
if(!global_store->runQuery(query))
{
DEBUG << "loadArchives query failed.";
return false;
}
const int index = query.record().indexOf("name");
while(query.next())
{
ArchivePtr archive(new Archive);
archive->setName(query.value(index).toString());
archive->load();
_archiveMap[archive->name()] = archive;
}
return true;
}
QList<ArchivePtr> BackendData::findMatchingArchives(const QString &jobPrefix)
{
QList<ArchivePtr> matching;
for(const ArchivePtr &archive : _archiveMap)
{
if(archive->name().startsWith(jobPrefix + QChar('_'))
&& archive->jobRef().isEmpty())
matching << archive;
}
return matching;
}
ArchivePtr BackendData::newArchive(BackupTaskDataPtr backupTaskData,
bool truncated)
{
ArchivePtr archive(new Archive);
archive->setName(backupTaskData->name());
if(truncated)
{
archive->setName(archive->name().append(".part"));
archive->setTruncated(true);
}
archive->setCommand(backupTaskData->command());
// Lose milliseconds precision by converting to Unix timestamp and back.
// So that a subsequent comparison in getArchiveListFinished won't fail.
archive->setTimestamp(
QDateTime::fromTime_t(backupTaskData->timestamp().toTime_t()));
archive->setJobRef(backupTaskData->jobRef());
// parseArchiveStats(stdErr, true, archive);
archive->save();
backupTaskData->setArchive(archive);
_archiveMap.insert(archive->name(), archive);
for(const JobPtr &job : _jobMap)
{
if(job->objectKey() == archive->jobRef())
emit job->loadArchives();
}
return archive;
}
QList<ArchivePtr>
BackendData::setArchivesFromList(QList<struct archive_list_data> metadatas)
{
QList<ArchivePtr> newArchives;
QMap<QString, ArchivePtr> nextArchiveMap;
for(const struct archive_list_data &metadata : metadatas)
{
ArchivePtr archive =
_archiveMap.value(metadata.archiveName, ArchivePtr(new Archive));
if(!archive->objectKey().isEmpty()
&& (archive->timestamp() != metadata.timestamp))
{
// There is a different archive with the same name on the remote
archive->purge();
archive.clear();
archive = archive.create();
}
if(archive->objectKey().isEmpty())
{
// New archive
archive->setName(metadata.archiveName);
archive->setTimestamp(metadata.timestamp);
archive->setCommand(metadata.command);
// Automagically set Job ownership
for(const JobPtr &job : _jobMap)
{
if(archive->name().startsWith(job->archivePrefix()))
archive->setJobRef(job->objectKey());
}
archive->save();
newArchives.append(archive);
}
nextArchiveMap.insert(archive->name(), archive);
_archiveMap.remove(archive->name());
}
// Purge archives left in old _archiveMap (not mirrored by the remote)
for(const ArchivePtr &archive : _archiveMap)
{
archive->purge();
}
_archiveMap.clear();
_archiveMap = nextArchiveMap;
for(const JobPtr &job : _jobMap)
{
emit job->loadArchives();
}
return newArchives;
}
void BackendData::removeArchives(QList<ArchivePtr> archives)
{
for(const ArchivePtr &archive : archives)
{
_archiveMap.remove(archive->name());
archive->purge();
}
}
bool BackendData::loadJobs()
{
_jobMap.clear();
if(!global_store->initialized())
{
DEBUG << "PersistentStore was not initialized properly.";
return false;
}
QSqlQuery query = global_store->createQuery();
if(!query.prepare(QLatin1String("select name from jobs")))
{
DEBUG << query.lastError().text();
return false;
}
if(!global_store->runQuery(query))
{
DEBUG << "loadJobs query failed.";
return false;
}
const int index = query.record().indexOf("name");
while(query.next())
{
JobPtr job(new Job);
job->setName(query.value(index).toString());
connect(job.data(), &Job::loadArchives, this,
&BackendData::loadJobArchives);
job->load();
_jobMap[job->name()] = job;
}
return true;
}
void BackendData::deleteJob(JobPtr job)
{
// Clear JobRef for assigned Archives.
for(const ArchivePtr &archive : job->archives())
{
archive->setJobRef("");
archive->save();
}
job->purge();
_jobMap.remove(job->name());
}
void BackendData::loadJobArchives()
{
Job * job = qobject_cast<Job *>(sender());
QList<ArchivePtr> archives;
for(const ArchivePtr &archive : _archiveMap)
{
if(archive->jobRef() == job->objectKey())
archives << archive;
}
job->setArchives(archives);
}
void BackendData::addJob(JobPtr job)
{
_jobMap[job->name()] = job;
connect(job.data(), &Job::loadArchives, this,
&BackendData::loadJobArchives);
}
|
#include "backenddata.h"
#include "debug.h"
#include "tasks-tarsnap.h"
BackendData::BackendData()
{
}
QMap<QString, JobPtr> BackendData::jobs()
{
return _jobMap;
}
QMap<QString, ArchivePtr> BackendData::archives()
{
return _archiveMap;
}
quint64 BackendData::numArchives()
{
return static_cast<quint64>(_archiveMap.count());
}
bool BackendData::loadArchives()
{
_archiveMap.clear();
if(!global_store->initialized())
{
DEBUG << "PersistentStore was not initialized properly.";
return false;
}
QSqlQuery query = global_store->createQuery();
if(!query.prepare(QLatin1String("select name from archives")))
{
DEBUG << query.lastError().text();
return false;
}
if(!global_store->runQuery(query))
{
DEBUG << "loadArchives query failed.";
return false;
}
const int index = query.record().indexOf("name");
while(query.next())
{
ArchivePtr archive(new Archive);
archive->setName(query.value(index).toString());
archive->load();
_archiveMap[archive->name()] = archive;
}
return true;
}
QList<ArchivePtr> BackendData::findMatchingArchives(const QString &jobPrefix)
{
const QString prefix = jobPrefix + QChar('_');
QList<ArchivePtr> matching;
for(const ArchivePtr &archive : _archiveMap)
{
if(archive->name().startsWith(prefix) && archive->jobRef().isEmpty())
matching << archive;
}
return matching;
}
ArchivePtr BackendData::newArchive(BackupTaskDataPtr backupTaskData,
bool truncated)
{
ArchivePtr archive(new Archive);
archive->setName(backupTaskData->name());
if(truncated)
{
archive->setName(archive->name().append(".part"));
archive->setTruncated(true);
}
archive->setCommand(backupTaskData->command());
// Lose milliseconds precision by converting to Unix timestamp and back.
// So that a subsequent comparison in getArchiveListFinished won't fail.
archive->setTimestamp(
QDateTime::fromTime_t(backupTaskData->timestamp().toTime_t()));
archive->setJobRef(backupTaskData->jobRef());
// parseArchiveStats(stdErr, true, archive);
archive->save();
backupTaskData->setArchive(archive);
_archiveMap.insert(archive->name(), archive);
for(const JobPtr &job : _jobMap)
{
if(job->objectKey() == archive->jobRef())
emit job->loadArchives();
}
return archive;
}
QList<ArchivePtr>
BackendData::setArchivesFromList(QList<struct archive_list_data> metadatas)
{
QList<ArchivePtr> newArchives;
QMap<QString, ArchivePtr> nextArchiveMap;
for(const struct archive_list_data &metadata : metadatas)
{
ArchivePtr archive =
_archiveMap.value(metadata.archiveName, ArchivePtr(new Archive));
if(!archive->objectKey().isEmpty()
&& (archive->timestamp() != metadata.timestamp))
{
// There is a different archive with the same name on the remote
archive->purge();
archive.clear();
archive = archive.create();
}
if(archive->objectKey().isEmpty())
{
// New archive
archive->setName(metadata.archiveName);
archive->setTimestamp(metadata.timestamp);
archive->setCommand(metadata.command);
// Automagically set Job ownership
for(const JobPtr &job : _jobMap)
{
if(archive->name().startsWith(job->archivePrefix()))
archive->setJobRef(job->objectKey());
}
archive->save();
newArchives.append(archive);
}
nextArchiveMap.insert(archive->name(), archive);
_archiveMap.remove(archive->name());
}
// Purge archives left in old _archiveMap (not mirrored by the remote)
for(const ArchivePtr &archive : _archiveMap)
{
archive->purge();
}
_archiveMap.clear();
_archiveMap = nextArchiveMap;
for(const JobPtr &job : _jobMap)
{
emit job->loadArchives();
}
return newArchives;
}
void BackendData::removeArchives(QList<ArchivePtr> archives)
{
for(const ArchivePtr &archive : archives)
{
_archiveMap.remove(archive->name());
archive->purge();
}
}
bool BackendData::loadJobs()
{
_jobMap.clear();
if(!global_store->initialized())
{
DEBUG << "PersistentStore was not initialized properly.";
return false;
}
QSqlQuery query = global_store->createQuery();
if(!query.prepare(QLatin1String("select name from jobs")))
{
DEBUG << query.lastError().text();
return false;
}
if(!global_store->runQuery(query))
{
DEBUG << "loadJobs query failed.";
return false;
}
const int index = query.record().indexOf("name");
while(query.next())
{
JobPtr job(new Job);
job->setName(query.value(index).toString());
connect(job.data(), &Job::loadArchives, this,
&BackendData::loadJobArchives);
job->load();
_jobMap[job->name()] = job;
}
return true;
}
void BackendData::deleteJob(JobPtr job)
{
// Clear JobRef for assigned Archives.
for(const ArchivePtr &archive : job->archives())
{
archive->setJobRef("");
archive->save();
}
job->purge();
_jobMap.remove(job->name());
}
void BackendData::loadJobArchives()
{
Job * job = qobject_cast<Job *>(sender());
QList<ArchivePtr> archives;
for(const ArchivePtr &archive : _archiveMap)
{
if(archive->jobRef() == job->objectKey())
archives << archive;
}
job->setArchives(archives);
}
void BackendData::addJob(JobPtr job)
{
_jobMap[job->name()] = job;
connect(job.data(), &Job::loadArchives, this,
&BackendData::loadJobArchives);
}
|
simplify findMatchingArchives
|
BackendData: simplify findMatchingArchives
|
C++
|
bsd-2-clause
|
Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui
|
789f9f7f234ddbc33dd599815ded7363478ecd5e
|
plugins/node-control.cpp
|
plugins/node-control.cpp
|
// Copyright 2013 Samplecount S.L.
//
// 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 <methcla/plugins/node-control.h>
#include <methcla/plugin.hpp>
#include <cmath>
using namespace Methcla::Plugin;
// DoneAfter
class DoneAfterOptions
{
public:
DoneAfterOptions(OSCPP::Server::ArgStream args)
{
m_seconds = args.float32();
}
float m_seconds;
};
typedef NoPorts DoneAfterPorts;
class DoneAfter
{
double m_numFramesLeft;
bool m_done;
public:
DoneAfter(const World<DoneAfter>& world, const Methcla_SynthDef*, const DoneAfterOptions& options)
: m_numFramesLeft((double)options.m_seconds * world.sampleRate())
, m_done(false)
{
}
void connect(DoneAfterPorts::Port, void*)
{
}
void process(const World<DoneAfter>& world, size_t numFrames)
{
if (!m_done)
{
m_numFramesLeft -= numFrames;
if (m_numFramesLeft <= 0)
{
m_done = true;
world.synthDone(this);
}
}
}
};
StaticSynthDef<DoneAfter,DoneAfterOptions,DoneAfterPorts> kDoneAfterDef;
// LinearEnvelope
class ASREnvelopeOptions
{
public:
ASREnvelopeOptions(OSCPP::Server::ArgStream args)
{
attackTime = args.float32();
sustainTime = args.float32();
sustainLevel = args.float32();
releaseTime = args.float32();
}
float attackTime;
float sustainTime;
float sustainLevel;
float releaseTime;
};
class ASREnvelopePorts
{
public:
enum Port
{
kInput
, kOutput
};
static constexpr size_t numPorts() { return 2; }
static Methcla_PortDescriptor descriptor(Port port)
{
switch (port)
{
case kInput: return Methcla::Plugin::PortDescriptor::audioInput();
case kOutput: return Methcla::Plugin::PortDescriptor::audioOutput();
default: throw std::runtime_error("Invalid port index");
}
}
};
class ASREnvelope
{
enum State
{
kAttackPhase,
kSustainPhase,
kReleasePhase,
kDone
};
ASREnvelopeOptions m_options;
State m_state;
size_t m_numFramesLeft;
float m_slope;
float m_level;
float* m_ports[ASREnvelopePorts::numPorts()];
public:
ASREnvelope(const World<ASREnvelope>& world, const Methcla_SynthDef*, const ASREnvelopeOptions& options)
: m_options(options)
, m_state(kAttackPhase)
, m_numFramesLeft((size_t)(options.attackTime * world.sampleRate() + 0.5f))
, m_slope(m_options.sustainLevel / m_numFramesLeft)
, m_level(0.f)
{
std::fill(m_ports, m_ports + ASREnvelopePorts::numPorts(), nullptr);
}
void connect(ASREnvelopePorts::Port port, void* data)
{
m_ports[port] = static_cast<float*>(data);
}
void process(const World<ASREnvelope>& world, size_t numFrames)
{
const float* input = m_ports[ASREnvelopePorts::kInput];
float* output = m_ports[ASREnvelopePorts::kOutput];
if (m_state == kDone)
{
for (size_t k=0; k < numFrames; k++) {
output[k] = 0.f;
}
}
else
{
size_t outFrame = 0;
while (outFrame < numFrames)
{
const size_t n = std::min(numFrames - outFrame, m_numFramesLeft);
for (size_t k=0; k < n; k++)
{
output[outFrame] = input[outFrame] * m_level;
m_level += m_slope;
outFrame++;
}
m_numFramesLeft -= n;
if (m_numFramesLeft == 0)
{
if (m_state == kAttackPhase)
{
m_state = kSustainPhase;
m_numFramesLeft = m_options.sustainTime * world.sampleRate();
m_slope = 0.f;
}
else if (m_state == kSustainPhase)
{
m_state = kReleasePhase;
m_numFramesLeft = m_options.releaseTime * world.sampleRate();
m_slope = -(m_level / m_numFramesLeft);
}
else
{
m_state = kDone;
world.synthDone(this);
break;
}
}
}
for (size_t k=outFrame; k < numFrames; k++) {
output[k] = 0.f;
}
}
}
};
StaticSynthDef<ASREnvelope,ASREnvelopeOptions,ASREnvelopePorts> kASREnvelopeDef;
// ExponentialFade
class ExponentialFadeOptions
{
public:
ExponentialFadeOptions(OSCPP::Server::ArgStream args)
{
startLevel = args.float32();
endLevel = args.float32();
duration = args.float32();
}
float startLevel;
float endLevel;
float duration;
};
class ExponentialFadePorts
{
public:
enum Port
{
kInput
, kOutput
};
static constexpr size_t numPorts() { return 2; }
static Methcla_PortDescriptor descriptor(Port port)
{
switch (port)
{
case kInput: return Methcla::Plugin::PortDescriptor::audioInput();
case kOutput: return Methcla::Plugin::PortDescriptor::audioOutput();
default: throw std::runtime_error("Invalid port index");
}
}
};
class ExponentialFade
{
enum State {
kRunning,
kDone
};
State m_state;
size_t m_numFramesLeft;
float m_growth;
float m_level;
float* m_ports[ExponentialFadePorts::numPorts()];
public:
ExponentialFade(const World<ExponentialFade>& world, const Methcla_SynthDef*, const ExponentialFadeOptions& options)
: m_state(kRunning)
, m_numFramesLeft((size_t)(options.duration * world.sampleRate() + 0.5f))
, m_growth(std::pow(options.endLevel / options.startLevel, 1.0 / m_numFramesLeft))
, m_level(options.startLevel)
{
std::fill(m_ports, m_ports + ExponentialFadePorts::numPorts(), nullptr);
}
void connect(ExponentialFadePorts::Port port, void* data)
{
m_ports[port] = static_cast<float*>(data);
}
void process(const World<ExponentialFade>& world, size_t numFrames)
{
const float* input = m_ports[ExponentialFadePorts::kInput];
float* output = m_ports[ExponentialFadePorts::kOutput];
if (m_numFramesLeft == 0)
{
if (m_state == kRunning) {
m_state = kDone;
world.synthDone(this);
}
for (size_t k=0; k < numFrames; k++) {
output[k] = m_level * input[k];
}
}
else
{
const size_t n = std::min(numFrames, m_numFramesLeft);
for (size_t k=0; k < n; k++) {
output[k] = m_level * input[k];
m_level *= m_growth;
}
for (size_t k=n; k < numFrames; k++) {
output[k] = m_level * input[k];
}
m_numFramesLeft -= n;
if (m_numFramesLeft == 0) {
m_state = kDone;
world.synthDone(this);
}
}
}
};
StaticSynthDef<ExponentialFade,ExponentialFadeOptions,ExponentialFadePorts> kExponentialFade;
// Library
static const Methcla_Library library = { NULL, NULL };
METHCLA_EXPORT const Methcla_Library* methcla_plugins_node_control(const Methcla_Host* host, const char* /* bundlePath */)
{
kDoneAfterDef(host, METHCLA_PLUGINS_DONE_AFTER_URI);
kASREnvelopeDef(host, METHCLA_PLUGINS_ASR_ENVELOPE_URI);
kExponentialFade(host, METHCLA_PLUGINS_EXPONENTIAL_FADE_URI);
return &library;
}
|
// Copyright 2013 Samplecount S.L.
//
// 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 <methcla/plugins/node-control.h>
#include <methcla/plugin.hpp>
#include <cmath>
using namespace Methcla::Plugin;
// DoneAfter
class DoneAfterOptions
{
public:
DoneAfterOptions(OSCPP::Server::ArgStream args)
{
m_seconds = args.float32();
}
float m_seconds;
};
typedef NoPorts DoneAfterPorts;
class DoneAfter
{
double m_numFramesLeft;
bool m_done;
public:
DoneAfter(const World<DoneAfter>& world, const Methcla_SynthDef*, const DoneAfterOptions& options)
: m_numFramesLeft((double)options.m_seconds * world.sampleRate())
, m_done(false)
{
}
void connect(DoneAfterPorts::Port, void*)
{
}
void process(const World<DoneAfter>& world, size_t numFrames)
{
if (!m_done)
{
m_numFramesLeft -= numFrames;
if (m_numFramesLeft <= 0)
{
m_done = true;
world.synthDone(this);
}
}
}
};
static StaticSynthDef<DoneAfter,DoneAfterOptions,DoneAfterPorts> kDoneAfterDef;
// LinearEnvelope
class ASREnvelopeOptions
{
public:
ASREnvelopeOptions(OSCPP::Server::ArgStream args)
{
attackTime = args.float32();
sustainTime = args.float32();
sustainLevel = args.float32();
releaseTime = args.float32();
}
float attackTime;
float sustainTime;
float sustainLevel;
float releaseTime;
};
class ASREnvelopePorts
{
public:
enum Port
{
kInput
, kOutput
};
static constexpr size_t numPorts() { return 2; }
static Methcla_PortDescriptor descriptor(Port port)
{
switch (port)
{
case kInput: return Methcla::Plugin::PortDescriptor::audioInput();
case kOutput: return Methcla::Plugin::PortDescriptor::audioOutput();
default: throw std::runtime_error("Invalid port index");
}
}
};
class ASREnvelope
{
enum State
{
kAttackPhase,
kSustainPhase,
kReleasePhase,
kDone
};
ASREnvelopeOptions m_options;
State m_state;
size_t m_numFramesLeft;
float m_slope;
float m_level;
float* m_ports[ASREnvelopePorts::numPorts()];
public:
ASREnvelope(const World<ASREnvelope>& world, const Methcla_SynthDef*, const ASREnvelopeOptions& options)
: m_options(options)
, m_state(kAttackPhase)
, m_numFramesLeft((size_t)(options.attackTime * world.sampleRate() + 0.5f))
, m_slope(m_options.sustainLevel / m_numFramesLeft)
, m_level(0.f)
{
std::fill(m_ports, m_ports + ASREnvelopePorts::numPorts(), nullptr);
}
void connect(ASREnvelopePorts::Port port, void* data)
{
m_ports[port] = static_cast<float*>(data);
}
void process(const World<ASREnvelope>& world, size_t numFrames)
{
const float* input = m_ports[ASREnvelopePorts::kInput];
float* output = m_ports[ASREnvelopePorts::kOutput];
if (m_state == kDone)
{
for (size_t k=0; k < numFrames; k++) {
output[k] = 0.f;
}
}
else
{
size_t outFrame = 0;
while (outFrame < numFrames)
{
const size_t n = std::min(numFrames - outFrame, m_numFramesLeft);
for (size_t k=0; k < n; k++)
{
output[outFrame] = input[outFrame] * m_level;
m_level += m_slope;
outFrame++;
}
m_numFramesLeft -= n;
if (m_numFramesLeft == 0)
{
if (m_state == kAttackPhase)
{
m_state = kSustainPhase;
m_numFramesLeft = m_options.sustainTime * world.sampleRate();
m_slope = 0.f;
}
else if (m_state == kSustainPhase)
{
m_state = kReleasePhase;
m_numFramesLeft = m_options.releaseTime * world.sampleRate();
m_slope = -(m_level / m_numFramesLeft);
}
else
{
m_state = kDone;
world.synthDone(this);
break;
}
}
}
for (size_t k=outFrame; k < numFrames; k++) {
output[k] = 0.f;
}
}
}
};
static StaticSynthDef<ASREnvelope,ASREnvelopeOptions,ASREnvelopePorts> kASREnvelopeDef;
// ExponentialFade
class ExponentialFadeOptions
{
public:
ExponentialFadeOptions(OSCPP::Server::ArgStream args)
{
startLevel = args.float32();
endLevel = args.float32();
duration = args.float32();
}
float startLevel;
float endLevel;
float duration;
};
class ExponentialFadePorts
{
public:
enum Port
{
kInput
, kOutput
};
static constexpr size_t numPorts() { return 2; }
static Methcla_PortDescriptor descriptor(Port port)
{
switch (port)
{
case kInput: return Methcla::Plugin::PortDescriptor::audioInput();
case kOutput: return Methcla::Plugin::PortDescriptor::audioOutput();
default: throw std::runtime_error("Invalid port index");
}
}
};
class ExponentialFade
{
enum State {
kRunning,
kDone
};
State m_state;
size_t m_numFramesLeft;
float m_growth;
float m_level;
float* m_ports[ExponentialFadePorts::numPorts()];
public:
ExponentialFade(const World<ExponentialFade>& world, const Methcla_SynthDef*, const ExponentialFadeOptions& options)
: m_state(kRunning)
, m_numFramesLeft((size_t)(options.duration * world.sampleRate() + 0.5f))
, m_growth(std::pow(options.endLevel / options.startLevel, 1.0 / m_numFramesLeft))
, m_level(options.startLevel)
{
std::fill(m_ports, m_ports + ExponentialFadePorts::numPorts(), nullptr);
}
void connect(ExponentialFadePorts::Port port, void* data)
{
m_ports[port] = static_cast<float*>(data);
}
void process(const World<ExponentialFade>& world, size_t numFrames)
{
const float* input = m_ports[ExponentialFadePorts::kInput];
float* output = m_ports[ExponentialFadePorts::kOutput];
if (m_numFramesLeft == 0)
{
if (m_state == kRunning) {
m_state = kDone;
world.synthDone(this);
}
for (size_t k=0; k < numFrames; k++) {
output[k] = m_level * input[k];
}
}
else
{
const size_t n = std::min(numFrames, m_numFramesLeft);
for (size_t k=0; k < n; k++) {
output[k] = m_level * input[k];
m_level *= m_growth;
}
for (size_t k=n; k < numFrames; k++) {
output[k] = m_level * input[k];
}
m_numFramesLeft -= n;
if (m_numFramesLeft == 0) {
m_state = kDone;
world.synthDone(this);
}
}
}
};
static StaticSynthDef<ExponentialFade,ExponentialFadeOptions,ExponentialFadePorts> kExponentialFade;
// Library
static const Methcla_Library library = { NULL, NULL };
METHCLA_EXPORT const Methcla_Library* methcla_plugins_node_control(const Methcla_Host* host, const char* /* bundlePath */)
{
kDoneAfterDef(host, METHCLA_PLUGINS_DONE_AFTER_URI);
kASREnvelopeDef(host, METHCLA_PLUGINS_ASR_ENVELOPE_URI);
kExponentialFade(host, METHCLA_PLUGINS_EXPONENTIAL_FADE_URI);
return &library;
}
|
Make node-control synth definitions static
|
Make node-control synth definitions static
|
C++
|
apache-2.0
|
samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla
|
b1797ff8b9409155f5c7c350bc207ebc14b17141
|
dune/multiscale/fem/algorithm.cc
|
dune/multiscale/fem/algorithm.cc
|
#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "algorithm.hh"
#include <dune/multiscale/hmm/cell_problem_numbering.hh>
#include <dune/multiscale/tools/misc/outputparameter.hh>
#include <dune/multiscale/common/righthandside_assembler.hh>
#include <dune/multiscale/common/newton_rhs.hh>
#include <dune/multiscale/common/output_traits.hh>
#include <dune/multiscale/common/error_calc.hh>
#include <dune/multiscale/fem/print_info.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/fem/misc/l2norm.hh>
#include <string>
#include <fstream>
#include "fem_traits.hh"
namespace {
const std::string seperator_line =
"---------------------------------------------------------------------------------\n";
}
namespace Dune {
namespace Multiscale {
namespace FEM {
//! \TODO docme
void solve(typename CommonTraits::DiscreteFunctionType& solution,
const typename CommonTraits::DiscreteFunctionType& dirichlet_extension,
const typename CommonTraits::DiscreteFunctionSpaceType& finerDiscreteFunctionSpace,
const typename FEMTraits::EllipticOperatorType& discrete_elliptic_op) {
typename CommonTraits::LinearOperatorType system_matrix("FEM Newton stiffness matrix", finerDiscreteFunctionSpace,
finerDiscreteFunctionSpace);
typename CommonTraits::DiscreteFunctionType system_rhs("fem newton rhs", finerDiscreteFunctionSpace);
system_rhs.clear();
const auto f = Dune::Multiscale::Problem::getFirstSource();
const auto diffusion_op = Problem::getDiffusion();
const auto neumann_bc = Problem::getNeumannBC();
DSC_LOG_INFO << "Solving linear problem." << std::endl;
DSC_LOG_INFO << "Solving linear problem with standard FEM and resolution level "
<< DSC_CONFIG_GET("fem.grid_level", 4) << "." << std::endl;
DSC_LOG_INFO << "------------------------------------------------------------------------------" << std::endl;
// to assemble the computational time
Dune::Timer assembleTimer;
// assemble the stiffness matrix
discrete_elliptic_op.assemble_matrix(system_matrix);
DSC_LOG_INFO << "Time to assemble standard FEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl;
const RightHandSideAssembler rhsassembler = {};
rhsassembler.assemble(*f, *diffusion_op, dirichlet_extension, *neumann_bc, system_rhs);
// set Dirichlet Boundary to zero
boundaryTreatment(system_rhs);
const typename FEMTraits::InverseOperatorType fem_biCGStab(
system_matrix, 1e-8, 1e-8, 20000, DSC_CONFIG_GET("global.cgsolver_verbose", false),
DSC_CONFIG_GET("fem.algebraic_solver", "bcgs"), DSC_CONFIG_GET("preconditioner_type", std::string("sor")));
fem_biCGStab(system_rhs, solution);
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
DSC_LOG_INFO << "Standard FEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
}
//! the main FEM computation
void algorithm(typename CommonTraits::GridPointerType& macro_grid_pointer, const std::string filename) {
using namespace Dune;
const auto problem_data = Problem::getModelData();
print_info(*problem_data, DSC_LOG_INFO);
//! ---------------------------- grid parts ----------------------------------------------
// grid part for the global function space, required for the finite element problem
typename CommonTraits::GridPartType gridPart(*macro_grid_pointer);
//! --------------------------------------------------------------------------------------
//! ------------------------- discrete function spaces -----------------------------------
// the global-problem function space:
typename CommonTraits::DiscreteFunctionSpaceType discreteFunctionSpace(gridPart);
//! --------------------------------------------------------------------------------------
// defines the matrix A^{\epsilon} in our global problem - div ( A^{\epsilon}(\nabla u^{\epsilon} ) = f
const auto diffusion_op = Problem::getDiffusion();
// lower order term F(x, u(x), grad u(x) )
const auto lower_order_term = Problem::getLowerOrderTerm();
// Dirichlet boundary condition
const auto dirichlet_bc = Problem::getDirichletBC();
// discrete function that takes the values of the Dirichlet BC on the Dirichlet Boundary nodes
// and that is zero elsewhere
typename CommonTraits::DiscreteFunctionType dirichlet_extension("Dirichlet extension", discreteFunctionSpace);
dirichlet_extension.clear();
setDirichletValues(*dirichlet_bc, dirichlet_extension);
//! define the discrete (elliptic) operator that describes our problem
// ( effect of the discretized differential operator on a certain discrete function )
const typename FEMTraits::EllipticOperatorType discrete_elliptic_op(discreteFunctionSpace, *diffusion_op,
lower_order_term);
//! solution vector
// - By solution, we denote the "discrete solution" determined with FEM in the linear case or FEM-Newton (nonlinear
// case)
// ( if the elliptic problem is linear, the 'solution' is determined without the Newton method )
// - solution of the finite element method, where we use the Newton method to solve the non-linear system of equations
auto discrete_solution = make_df_ptr<typename CommonTraits::DiscreteFunctionType>(filename + " FEM(-Newton) Solution",
discreteFunctionSpace);
discrete_solution->clear();
if (DSC_CONFIG_GET("problem.linear", true))
solve(*discrete_solution, dirichlet_extension, discreteFunctionSpace, discrete_elliptic_op);
else
solve_nonlinear(*discrete_solution, dirichlet_extension, discreteFunctionSpace, discrete_elliptic_op,
lower_order_term, filename);
*discrete_solution += dirichlet_extension;
// write FEM solution to a file and produce a VTK output
write_discrete_function(discrete_solution, "fem");
ErrorCalculator(nullptr, discrete_solution.get()).print(DSC_LOG_INFO_0);
}
//! \TODO docme
void solve_nonlinear(typename CommonTraits::DiscreteFunctionType& solution,
const typename CommonTraits::DiscreteFunctionType& dirichlet_extension,
const typename CommonTraits::DiscreteFunctionSpaceType& finerDiscreteFunctionSpace,
const typename FEMTraits::EllipticOperatorType& discrete_elliptic_op,
const std::unique_ptr<const CommonTraits::LowerOrderTermType> &lower_order_term,
const std::string& filename)
{
typename CommonTraits::LinearOperatorType system_matrix("FEM Newton stiffness matrix", finerDiscreteFunctionSpace,
finerDiscreteFunctionSpace);
typename CommonTraits::DiscreteFunctionType system_rhs("fem newton rhs", finerDiscreteFunctionSpace);
system_rhs.clear();
const auto f = Dune::Multiscale::Problem::getFirstSource();
const auto diffusion_op = Problem::getDiffusion();
const auto neumann_bc = Problem::getNeumannBC();
DSC_LOG_INFO << "Solving non-linear problem." << std::endl;
DSC_LOG_INFO << "Solving nonlinear problem with FEM + Newton-Method. Resolution level of grid = "
<< DSC_CONFIG_GET("fem.grid_level", 4) << "." << std::endl;
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
Dune::Timer assembleTimer;
//! residual vector
// current residual
typename CommonTraits::DiscreteFunctionType residual(filename + "FEM Newton Residual", finerDiscreteFunctionSpace);
residual.clear();
typename CommonTraits::RangeType relative_newton_error_finescale = std::numeric_limits<typename CommonTraits::RangeType>::max();
typename CommonTraits::RangeType rhs_L2_norm = std::numeric_limits<typename CommonTraits::RangeType>::max();
int iteration_step = 1;
// the Newton step for the FEM reference problem (solved with Newton Method):
// L2-Norm of residual < tolerance ?
double tolerance = 1e-06;
const NewtonRightHandSide newton_rhs = {};
while (relative_newton_error_finescale > tolerance) {
// (here: solution = solution from the last iteration step)
DSC_LOG_INFO << "Newton iteration " << iteration_step << ":" << std::endl;
Dune::Timer stepAssembleTimer;
// assemble the stiffness matrix
discrete_elliptic_op.assemble_jacobian_matrix(solution, dirichlet_extension, system_matrix);
DSC_LOG_INFO << "Time to assemble FEM Newton stiffness matrix for current iteration: "
<< stepAssembleTimer.elapsed() << "s" << std::endl;
newton_rhs.assemble_for_Newton_method(*f, *diffusion_op, *lower_order_term, solution,
dirichlet_extension, *neumann_bc, system_rhs);
const Dune::Fem::L2Norm<typename CommonTraits::DiscreteFunctionType::GridPartType> l2norm(system_rhs.gridPart());
rhs_L2_norm = l2norm.norm(system_rhs);
if (rhs_L2_norm < 1e-10) {
// residual solution almost identical to zero: break
DSC_LOG_DEBUG << "Residual solution almost identical to zero. Therefore: break loop." << std::endl;
DSC_LOG_DEBUG << "(L^2-Norm of current right hand side = " << rhs_L2_norm << " < 1e-10)" << std::endl;
break;
}
// set Dirichlet Boundary to zero
boundaryTreatment(system_rhs);
const typename FEMTraits::InverseOperatorType fem_newton_biCGStab(system_matrix, 1e-8, 1e-8, 20000, true);
fem_newton_biCGStab(system_rhs, residual);
if (residual.dofsValid()) {
solution += residual;
relative_newton_error_finescale = l2norm.norm(residual);
relative_newton_error_finescale /= l2norm.norm(solution);
DSC_LOG_INFO << "Relative L2-Newton Error = " << relative_newton_error_finescale << std::endl;
// residual solution almost identical to zero: break
DSC_LOG_INFO << "Relative L2-Newton Error = " << relative_newton_error_finescale << std::endl;
if (relative_newton_error_finescale <= tolerance) {
DSC_LOG_INFO << "Since tolerance = " << tolerance << ": break loop." << std::endl;
}
residual.clear();
} else {
DSC_LOG_INFO << "WARNING! Invalid dofs in 'residual'." << std::endl;
break;
}
iteration_step += 1;
}
if (DSC_CONFIG_GET("problem.linear", true)) {
DSC_LOG_INFO << "Finite Element Problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
} else {
DSC_LOG_INFO << "Nonlinear Finite Element Problem solved with Newton Method in " << assembleTimer.elapsed()
<< "s." << std::endl << std::endl << std::endl;
}
DSC_LOG_INFO << seperator_line;
}
} // namespace FEM {
} // namespace Multiscale {
} // namespace Dune {
|
#include <config.h>
// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "algorithm.hh"
#include <dune/multiscale/hmm/cell_problem_numbering.hh>
#include <dune/multiscale/tools/misc/outputparameter.hh>
#include <dune/multiscale/common/righthandside_assembler.hh>
#include <dune/multiscale/common/newton_rhs.hh>
#include <dune/multiscale/common/output_traits.hh>
#include <dune/multiscale/common/error_calc.hh>
#include <dune/multiscale/fem/print_info.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/fem/misc/l2norm.hh>
#include <string>
#include <fstream>
#include "fem_traits.hh"
namespace {
const std::string seperator_line =
"---------------------------------------------------------------------------------\n";
}
namespace Dune {
namespace Multiscale {
namespace FEM {
//! \TODO docme
void solve(typename CommonTraits::DiscreteFunctionType& solution,
const typename CommonTraits::DiscreteFunctionType& dirichlet_extension,
const typename CommonTraits::DiscreteFunctionSpaceType& finerDiscreteFunctionSpace,
const typename FEMTraits::EllipticOperatorType& discrete_elliptic_op) {
typename CommonTraits::LinearOperatorType system_matrix("FEM Newton stiffness matrix", finerDiscreteFunctionSpace,
finerDiscreteFunctionSpace);
typename CommonTraits::DiscreteFunctionType system_rhs("fem newton rhs", finerDiscreteFunctionSpace);
system_rhs.clear();
const auto f = Dune::Multiscale::Problem::getFirstSource();
const auto diffusion_op = Problem::getDiffusion();
const auto neumann_bc = Problem::getNeumannBC();
DSC_LOG_INFO << "Solving linear problem." << std::endl;
DSC_LOG_INFO << "Solving linear problem with standard FEM and resolution level "
<< DSC_CONFIG_GET("fem.grid_level", 4) << "." << std::endl;
DSC_LOG_INFO << "------------------------------------------------------------------------------" << std::endl;
// to assemble the computational time
Dune::Timer assembleTimer;
// assemble the stiffness matrix
discrete_elliptic_op.assemble_matrix(system_matrix);
DSC_LOG_INFO << "Time to assemble standard FEM stiffness matrix: " << assembleTimer.elapsed() << "s" << std::endl;
const RightHandSideAssembler rhsassembler = {};
rhsassembler.assemble(*f, *diffusion_op, dirichlet_extension, *neumann_bc, system_rhs);
const auto boundaryInfo = Problem::getModelData()->boundaryInfo();
DirichletConstraints<typename CommonTraits::DiscreteFunctionSpaceType> constraints(*boundaryInfo, finerDiscreteFunctionSpace);
constraints.applyToOperator(system_matrix);
constraints(dirichlet_extension, system_rhs);
const typename FEMTraits::InverseOperatorType fem_biCGStab(
system_matrix, 1e-8, 1e-8, 20000, DSC_CONFIG_GET("global.cgsolver_verbose", false),
DSC_CONFIG_GET("fem.algebraic_solver", "bcgs"), DSC_CONFIG_GET("preconditioner_type", std::string("sor")));
fem_biCGStab(system_rhs, solution);
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
DSC_LOG_INFO << "Standard FEM problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
}
//! the main FEM computation
void algorithm(typename CommonTraits::GridPointerType& macro_grid_pointer, const std::string filename) {
using namespace Dune;
const auto problem_data = Problem::getModelData();
print_info(*problem_data, DSC_LOG_INFO);
//! ---------------------------- grid parts ----------------------------------------------
// grid part for the global function space, required for the finite element problem
typename CommonTraits::GridPartType gridPart(*macro_grid_pointer);
//! --------------------------------------------------------------------------------------
//! ------------------------- discrete function spaces -----------------------------------
// the global-problem function space:
typename CommonTraits::DiscreteFunctionSpaceType discreteFunctionSpace(gridPart);
//! --------------------------------------------------------------------------------------
// defines the matrix A^{\epsilon} in our global problem - div ( A^{\epsilon}(\nabla u^{\epsilon} ) = f
const auto diffusion_op = Problem::getDiffusion();
// lower order term F(x, u(x), grad u(x) )
const auto lower_order_term = Problem::getLowerOrderTerm();
// Dirichlet boundary condition
const auto dirichlet_bc = Problem::getDirichletBC();
// discrete function that takes the values of the Dirichlet BC on the Dirichlet Boundary nodes
// and that is zero elsewhere
typename CommonTraits::DiscreteFunctionType dirichlet_extension("Dirichlet extension", discreteFunctionSpace);
dirichlet_extension.clear();
setDirichletValues(*dirichlet_bc, dirichlet_extension);
//! define the discrete (elliptic) operator that describes our problem
// ( effect of the discretized differential operator on a certain discrete function )
const typename FEMTraits::EllipticOperatorType discrete_elliptic_op(discreteFunctionSpace, *diffusion_op,
lower_order_term);
//! solution vector
// - By solution, we denote the "discrete solution" determined with FEM in the linear case or FEM-Newton (nonlinear
// case)
// ( if the elliptic problem is linear, the 'solution' is determined without the Newton method )
// - solution of the finite element method, where we use the Newton method to solve the non-linear system of equations
auto discrete_solution = make_df_ptr<typename CommonTraits::DiscreteFunctionType>(filename + " FEM(-Newton) Solution",
discreteFunctionSpace);
discrete_solution->clear();
if (DSC_CONFIG_GET("problem.linear", true))
solve(*discrete_solution, dirichlet_extension, discreteFunctionSpace, discrete_elliptic_op);
else
solve_nonlinear(*discrete_solution, dirichlet_extension, discreteFunctionSpace, discrete_elliptic_op,
lower_order_term, filename);
*discrete_solution += dirichlet_extension;
// write FEM solution to a file and produce a VTK output
write_discrete_function(discrete_solution, "fem");
ErrorCalculator(nullptr, discrete_solution.get()).print(DSC_LOG_INFO_0);
}
//! \TODO docme
void solve_nonlinear(typename CommonTraits::DiscreteFunctionType& solution,
const typename CommonTraits::DiscreteFunctionType& dirichlet_extension,
const typename CommonTraits::DiscreteFunctionSpaceType& finerDiscreteFunctionSpace,
const typename FEMTraits::EllipticOperatorType& discrete_elliptic_op,
const std::unique_ptr<const CommonTraits::LowerOrderTermType> &lower_order_term,
const std::string& filename)
{
typename CommonTraits::LinearOperatorType system_matrix("FEM Newton stiffness matrix", finerDiscreteFunctionSpace,
finerDiscreteFunctionSpace);
typename CommonTraits::DiscreteFunctionType system_rhs("fem newton rhs", finerDiscreteFunctionSpace);
system_rhs.clear();
const auto f = Dune::Multiscale::Problem::getFirstSource();
const auto diffusion_op = Problem::getDiffusion();
const auto neumann_bc = Problem::getNeumannBC();
DSC_LOG_INFO << "Solving non-linear problem." << std::endl;
DSC_LOG_INFO << "Solving nonlinear problem with FEM + Newton-Method. Resolution level of grid = "
<< DSC_CONFIG_GET("fem.grid_level", 4) << "." << std::endl;
DSC_LOG_INFO << "---------------------------------------------------------------------------------" << std::endl;
Dune::Timer assembleTimer;
//! residual vector
// current residual
typename CommonTraits::DiscreteFunctionType residual(filename + "FEM Newton Residual", finerDiscreteFunctionSpace);
residual.clear();
typename CommonTraits::RangeType relative_newton_error_finescale = std::numeric_limits<typename CommonTraits::RangeType>::max();
typename CommonTraits::RangeType rhs_L2_norm = std::numeric_limits<typename CommonTraits::RangeType>::max();
int iteration_step = 1;
// the Newton step for the FEM reference problem (solved with Newton Method):
// L2-Norm of residual < tolerance ?
double tolerance = 1e-06;
const NewtonRightHandSide newton_rhs = {};
while (relative_newton_error_finescale > tolerance) {
// (here: solution = solution from the last iteration step)
DSC_LOG_INFO << "Newton iteration " << iteration_step << ":" << std::endl;
Dune::Timer stepAssembleTimer;
// assemble the stiffness matrix
discrete_elliptic_op.assemble_jacobian_matrix(solution, dirichlet_extension, system_matrix);
DSC_LOG_INFO << "Time to assemble FEM Newton stiffness matrix for current iteration: "
<< stepAssembleTimer.elapsed() << "s" << std::endl;
newton_rhs.assemble_for_Newton_method(*f, *diffusion_op, *lower_order_term, solution,
dirichlet_extension, *neumann_bc, system_rhs);
const Dune::Fem::L2Norm<typename CommonTraits::DiscreteFunctionType::GridPartType> l2norm(system_rhs.gridPart());
rhs_L2_norm = l2norm.norm(system_rhs);
if (rhs_L2_norm < 1e-10) {
// residual solution almost identical to zero: break
DSC_LOG_DEBUG << "Residual solution almost identical to zero. Therefore: break loop." << std::endl;
DSC_LOG_DEBUG << "(L^2-Norm of current right hand side = " << rhs_L2_norm << " < 1e-10)" << std::endl;
break;
}
// set Dirichlet Boundary to zero
boundaryTreatment(system_rhs);
const typename FEMTraits::InverseOperatorType fem_newton_biCGStab(system_matrix, 1e-8, 1e-8, 20000, true);
fem_newton_biCGStab(system_rhs, residual);
if (residual.dofsValid()) {
solution += residual;
relative_newton_error_finescale = l2norm.norm(residual);
relative_newton_error_finescale /= l2norm.norm(solution);
DSC_LOG_INFO << "Relative L2-Newton Error = " << relative_newton_error_finescale << std::endl;
// residual solution almost identical to zero: break
DSC_LOG_INFO << "Relative L2-Newton Error = " << relative_newton_error_finescale << std::endl;
if (relative_newton_error_finescale <= tolerance) {
DSC_LOG_INFO << "Since tolerance = " << tolerance << ": break loop." << std::endl;
}
residual.clear();
} else {
DSC_LOG_INFO << "WARNING! Invalid dofs in 'residual'." << std::endl;
break;
}
iteration_step += 1;
}
if (DSC_CONFIG_GET("problem.linear", true)) {
DSC_LOG_INFO << "Finite Element Problem solved in " << assembleTimer.elapsed() << "s." << std::endl << std::endl
<< std::endl;
} else {
DSC_LOG_INFO << "Nonlinear Finite Element Problem solved with Newton Method in " << assembleTimer.elapsed()
<< "s." << std::endl << std::endl << std::endl;
}
DSC_LOG_INFO << seperator_line;
}
} // namespace FEM {
} // namespace Multiscale {
} // namespace Dune {
|
fix dirichlet bd treatment in standalone binary
|
[fem] fix dirichlet bd treatment in standalone binary
|
C++
|
bsd-2-clause
|
wwu-numerik/DUNE-Multiscale,wwu-numerik/DUNE-Multiscale
|
c2270f23ce16a3122780b7c5b337faf36f5a2a7c
|
src/Nazara/Utility/Formats/STBSaver.cpp
|
src/Nazara/Utility/Formats/STBSaver.cpp
|
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Formats/STBLoader.hpp>
#include <stb/stb_image_write.h>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/PixelFormat.hpp>
#include <map>
#include <stdexcept>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
namespace
{
using FormatHandler = bool(*)(const Image& image, const ImageParams& parameters, Stream& stream);
std::map<String, FormatHandler> s_formatHandlers;
int ConvertToFloatFormat(Image& image)
{
switch (image.GetFormat())
{
case PixelFormatType_R32F:
return 1;
case PixelFormatType_RG32F:
return 2;
case PixelFormatType_RGB32F:
return 3;
case PixelFormatType_RGBA32F:
return 4;
default:
{
if (PixelFormat::HasAlpha(image.GetFormat()))
{
if (!image.Convert(PixelFormatType_RGBA32F))
break;
return 4;
}
else
{
if (!image.Convert(PixelFormatType_RGB32F))
break;
return 3;
}
}
}
return 0;
}
int ConvertToIntegerFormat(Image& image)
{
switch (image.GetFormat())
{
case PixelFormatType_L8:
case PixelFormatType_R8:
return 1;
case PixelFormatType_LA8:
case PixelFormatType_RG8:
return 2;
case PixelFormatType_RGB8:
return 3;
case PixelFormatType_RGBA8:
return 4;
default:
{
if (PixelFormat::HasAlpha(image.GetFormat()))
{
if (!image.Convert(PixelFormatType_RGBA8))
break;
return 4;
}
else
{
if (!image.Convert(PixelFormatType_RGB8))
break;
return 3;
}
}
}
return 0;
}
void WriteToStream(void* userdata, void* data, int size)
{
Stream* stream = static_cast<Stream*>(userdata);
if (stream->Write(data, size) != size)
throw std::runtime_error("Failed to write to stream");
}
bool FormatQuerier(const String& extension)
{
return s_formatHandlers.find(extension) != s_formatHandlers.end();
}
bool SaveToStream(const Image& image, const String& format, Stream& stream, const ImageParams& parameters)
{
NazaraUnused(parameters);
if (!image.IsValid())
{
NazaraError("Invalid image");
return false;
}
ImageType type = image.GetType();
if (type != ImageType_1D && type != ImageType_2D)
{
NazaraError("Image type 0x" + String::Number(type, 16) + " is not ");
return false;
}
auto it = s_formatHandlers.find(format);
NazaraAssert(it != s_formatHandlers.end(), "Invalid handler");
const FormatHandler& handler = it->second;
try
{
return handler(image, parameters, stream);
}
catch (const std::exception& e)
{
NazaraError(e.what());
return false;
}
}
bool SaveBMP(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_bmp_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels()))
{
NazaraError("Failed to write BMP to stream");
return false;
}
return true;
}
bool SaveHDR(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToFloatFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_hdr_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, reinterpret_cast<const float*>(tempImage.GetConstPixels())))
{
NazaraError("Failed to write HDR to stream");
return false;
}
return true;
}
bool SavePNG(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_png_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels(), 0))
{
NazaraError("Failed to write PNG to stream");
return false;
}
return true;
}
bool SaveTGA(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_tga_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels()))
{
NazaraError("Failed to write TGA to stream");
return false;
}
return true;
}
}
namespace Loaders
{
void RegisterSTBSaver()
{
s_formatHandlers["bmp"] = &SaveBMP;
s_formatHandlers["hdr"] = &SaveHDR;
s_formatHandlers["png"] = &SavePNG;
s_formatHandlers["tga"] = &SaveTGA;
ImageSaver::RegisterSaver(FormatQuerier, SaveToStream);
}
void UnregisterSTBSaver()
{
ImageSaver::UnregisterSaver(FormatQuerier, SaveToStream);
s_formatHandlers.clear();
}
}
}
|
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Formats/STBLoader.hpp>
#include <stb/stb_image_write.h>
#include <Nazara/Utility/Image.hpp>
#include <Nazara/Utility/PixelFormat.hpp>
#include <map>
#include <stdexcept>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
namespace
{
using FormatHandler = bool(*)(const Image& image, const ImageParams& parameters, Stream& stream);
std::map<String, FormatHandler> s_formatHandlers;
int ConvertToFloatFormat(Image& image)
{
switch (image.GetFormat())
{
case PixelFormatType_R32F:
return 1;
case PixelFormatType_RG32F:
return 2;
case PixelFormatType_RGB32F:
return 3;
case PixelFormatType_RGBA32F:
return 4;
default:
{
if (PixelFormat::HasAlpha(image.GetFormat()))
{
if (!image.Convert(PixelFormatType_RGBA32F))
break;
return 4;
}
else
{
if (!image.Convert(PixelFormatType_RGB32F))
break;
return 3;
}
}
}
return 0;
}
int ConvertToIntegerFormat(Image& image)
{
switch (image.GetFormat())
{
case PixelFormatType_L8:
case PixelFormatType_R8:
return 1;
case PixelFormatType_LA8:
case PixelFormatType_RG8:
return 2;
case PixelFormatType_RGB8:
return 3;
case PixelFormatType_RGBA8:
return 4;
default:
{
if (PixelFormat::HasAlpha(image.GetFormat()))
{
if (!image.Convert(PixelFormatType_RGBA8))
break;
return 4;
}
else
{
if (!image.Convert(PixelFormatType_RGB8))
break;
return 3;
}
}
}
return 0;
}
void WriteToStream(void* userdata, void* data, int size)
{
Stream* stream = static_cast<Stream*>(userdata);
if (stream->Write(data, size) != size)
throw std::runtime_error("Failed to write to stream");
}
bool FormatQuerier(const String& extension)
{
return s_formatHandlers.find(extension) != s_formatHandlers.end();
}
bool SaveToStream(const Image& image, const String& format, Stream& stream, const ImageParams& parameters)
{
NazaraUnused(parameters);
if (!image.IsValid())
{
NazaraError("Invalid image");
return false;
}
ImageType type = image.GetType();
if (type != ImageType_1D && type != ImageType_2D)
{
NazaraError("Image type 0x" + String::Number(type, 16) + " is not in a supported format");
return false;
}
auto it = s_formatHandlers.find(format);
NazaraAssert(it != s_formatHandlers.end(), "Invalid handler");
const FormatHandler& handler = it->second;
try
{
return handler(image, parameters, stream);
}
catch (const std::exception& e)
{
NazaraError(e.what());
return false;
}
}
bool SaveBMP(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_bmp_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels()))
{
NazaraError("Failed to write BMP to stream");
return false;
}
return true;
}
bool SaveHDR(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToFloatFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_hdr_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, reinterpret_cast<const float*>(tempImage.GetConstPixels())))
{
NazaraError("Failed to write HDR to stream");
return false;
}
return true;
}
bool SavePNG(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_png_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels(), 0))
{
NazaraError("Failed to write PNG to stream");
return false;
}
return true;
}
bool SaveTGA(const Image& image, const ImageParams& parameters, Stream& stream)
{
Image tempImage(image); //< We're using COW here to prevent Image copy unless required
int componentCount = ConvertToIntegerFormat(tempImage);
if (componentCount == 0)
{
NazaraError("Failed to convert image to suitable format");
return false;
}
if (!stbi_write_tga_to_func(&WriteToStream, &stream, tempImage.GetWidth(), tempImage.GetHeight(), componentCount, tempImage.GetConstPixels()))
{
NazaraError("Failed to write TGA to stream");
return false;
}
return true;
}
}
namespace Loaders
{
void RegisterSTBSaver()
{
s_formatHandlers["bmp"] = &SaveBMP;
s_formatHandlers["hdr"] = &SaveHDR;
s_formatHandlers["png"] = &SavePNG;
s_formatHandlers["tga"] = &SaveTGA;
ImageSaver::RegisterSaver(FormatQuerier, SaveToStream);
}
void UnregisterSTBSaver()
{
ImageSaver::UnregisterSaver(FormatQuerier, SaveToStream);
s_formatHandlers.clear();
}
}
}
|
Fix error message
|
Utility/STBSaver: Fix error message
Former-commit-id: 40d0d01efcce56f8cd1ba516a5f1336ac4dc2a26 [formerly 46a7331866a7a1033d8238d2f49a6100bc9e8dd6]
Former-commit-id: 52de2bb4622a3499f69fb59dc5b9f1602cbac8cb
|
C++
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
276dcc0ad86e5010268ae78efecc9f30e2139877
|
src/src/region.cc
|
src/src/region.cc
|
#include "region.h"
#include "config.h"
#include "util.h"
#include <algorithm>
using namespace std;
region::region(int32_t _lpos, int32_t _rpos, int _ltype, int _rtype, const split_interval_map *_mmap, const split_interval_map *_imap, bool _inclusive)
:lpos(_lpos), rpos(_rpos), mmap(_mmap), imap(_imap), ltype(_ltype), rtype(_rtype), inclusive(_inclusive)
{
build_join_interval_map();
smooth_join_interval_map();
build_partial_exons();
}
region::~region()
{}
int region::build_join_interval_map()
{
jmap.clear();
SIMI lit, rit;
tie(lit, rit) = locate_boundary_iterators(*mmap, lpos, rpos);
if(lit == mmap->end() || rit == mmap->end()) return 0;
SIMI it = lit;
while(true)
{
jmap += make_pair(it->first, 1);
if(it == rit) break;
it++;
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
assert(it->second == 1);
}
return 0;
}
int region::smooth_join_interval_map()
{
vector<PI32> v;
int32_t p = lpos;
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
int32_t p1 = lower(it->first);
int32_t p2 = upper(it->first);
assert(p1 >= p);
assert(p2 > p1);
if(p1 - p <= min_subregion_gap) v.push_back(PI32(p, p1));
p = p2;
}
if(p < rpos && rpos - p <= min_subregion_gap) v.push_back(PI32(p, rpos));
for(int i = 0; i < v.size(); i++)
{
jmap += make_pair(ROI(v[i].first, v[i].second), 1);
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
assert(it->second == 1);
}
return 0;
}
bool region::empty_subregion(int32_t p1, int32_t p2)
{
assert(p1 < p2);
assert(p1 >= lpos && p2 <= rpos);
//printf(" region = [%d, %d), subregion [%d, %d), length = %d\n", lpos, rpos, p1, p2, p2 - p1);
if(p2 - p1 < min_subregion_length) return true;
SIMI it1, it2;
tie(it1, it2) = locate_boundary_iterators(*mmap, p1, p2);
if(it1 == mmap->end() || it2 == mmap->end()) return true;
int32_t sum = compute_sum_overlap(*mmap, it1, it2);
double ratio = sum * 1.0 / (p2 - p1);
//printf(" region = [%d, %d), subregion [%d, %d), overlap = %.2lf\n", lpos, rpos, p1, p2, ratio);
if(ratio < min_subregion_overlap) return true;
int32_t indel = 0;
SIMI jit1 = imap->lower_bound(ROI(p1, p1 + 1));
SIMI jit2 = imap->upper_bound(ROI(p2 - 1, p2));
for(SIMI jit = jit1; jit != jit2; jit++) indel += jit->second;
//printf(" region = [%d, %d), subregion [%d, %d), indel = %d\n", lpos, rpos, p1, p2, indel);
if(indel * 1.0 * ratio / (p2 - p1) > max_indel_ratio) return true;
return false;
}
int region::build_partial_exons()
{
pexons.clear();
if(jmap.size() == 0) return 0;
//printf("size = %lu, size2 = %lu, [%d, %d), [%d, %d)\n", jmap.size(), distance(jmap.begin(), jmap.end()), lower(jmap.begin()->first), upper(jmap.begin()->first), lpos, rpos);
if(lower(jmap.begin()->first) == lpos && upper(jmap.begin()->first) == rpos)
{
partial_exon pe(lpos, rpos, ltype, rtype);
evaluate_rectangle(*mmap, pe.lpos, pe.rpos, pe.ave, pe.dev);
pexons.push_back(pe);
return 0;
}
if(inclusive == true && ltype == RIGHT_SPLICE && jmap.find(ROI(lpos, lpos + 1)) == jmap.end())
{
partial_exon pe(lpos, lpos + 1, ltype, END_BOUNDARY);
pe.ave = 1.0;
pe.dev = 1.0;
pexons.push_back(pe);
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
int32_t p1 = lower(it->first);
int32_t p2 = upper(it->first);
assert(p1 < p2);
bool b = empty_subregion(p1, p2);
//printf(" subregion [%d, %d), empty = %c\n", p1, p2, b ? 'T' : 'F');
if(inclusive == true && p1 == lpos && ltype == RIGHT_SPLICE) b = false;
if(inclusive == true && p2 == rpos && rtype == LEFT_SPLICE) b = false;
if(b == true) continue;
int lt = (p1 == lpos) ? ltype : START_BOUNDARY;
int rt = (p2 == rpos) ? rtype : END_BOUNDARY;
partial_exon pe(p1, p2, lt, rt);
evaluate_rectangle(*mmap, pe.lpos, pe.rpos, pe.ave, pe.dev);
pexons.push_back(pe);
}
if(inclusive && rtype == LEFT_SPLICE && jmap.find(ROI(rpos - 1, rpos)) == jmap.end())
{
partial_exon pe(rpos - 1, rpos, START_BOUNDARY, rtype);
pe.ave = 1.0;
pe.dev = 1.0;
pexons.push_back(pe);
}
return 0;
}
bool region::left_inclusive()
{
if(pexons.size() == 0) return false;
if(pexons[0].lpos == lpos) return true;
else return false;
}
bool region::right_inclusive()
{
if(pexons.size() == 0) return false;
if(pexons[pexons.size() - 1].rpos == rpos) return true;
else return false;
}
int region::print(int index) const
{
int32_t lc = compute_overlap(*mmap, lpos);
int32_t rc = compute_overlap(*mmap, rpos - 1);
printf("region %d: partial-exons = %lu, type = (%d, %d), pos = [%d, %d), boundary coverage = (%d, %d)\n",
index, pexons.size(), ltype, rtype, lpos, rpos, lc, rc);
/*
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
printf(" [%d, %d) -> %d\n", lower(it->first), upper(it->first), it->second);
}
*/
return 0;
}
|
#include "region.h"
#include "config.h"
#include "util.h"
#include <algorithm>
using namespace std;
region::region(int32_t _lpos, int32_t _rpos, int _ltype, int _rtype, const split_interval_map *_mmap, const split_interval_map *_imap, bool _inclusive)
:lpos(_lpos), rpos(_rpos), mmap(_mmap), imap(_imap), ltype(_ltype), rtype(_rtype), inclusive(_inclusive)
{
build_join_interval_map();
smooth_join_interval_map();
build_partial_exons();
}
region::~region()
{}
int region::build_join_interval_map()
{
jmap.clear();
SIMI lit, rit;
tie(lit, rit) = locate_boundary_iterators(*mmap, lpos, rpos);
if(lit == mmap->end() || rit == mmap->end()) return 0;
SIMI it = lit;
while(true)
{
jmap += make_pair(it->first, 1);
if(it == rit) break;
it++;
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
assert(it->second == 1);
}
return 0;
}
int region::smooth_join_interval_map()
{
vector<PI32> v;
int32_t p = lpos;
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
int32_t p1 = lower(it->first);
int32_t p2 = upper(it->first);
assert(p1 >= p);
assert(p2 > p1);
if(p1 - p <= min_subregion_gap) v.push_back(PI32(p, p1));
p = p2;
}
if(p < rpos && rpos - p <= min_subregion_gap) v.push_back(PI32(p, rpos));
for(int i = 0; i < v.size(); i++)
{
jmap += make_pair(ROI(v[i].first, v[i].second), 1);
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
assert(it->second == 1);
}
return 0;
}
bool region::empty_subregion(int32_t p1, int32_t p2)
{
assert(p1 < p2);
assert(p1 >= lpos && p2 <= rpos);
printf(" region = [%d, %d), subregion [%d, %d), length = %d\n", lpos, rpos, p1, p2, p2 - p1);
if(p2 - p1 < min_subregion_length) return true;
SIMI it1, it2;
tie(it1, it2) = locate_boundary_iterators(*mmap, p1, p2);
if(it1 == mmap->end() || it2 == mmap->end()) return true;
int32_t sum = compute_sum_overlap(*mmap, it1, it2);
double ratio = sum * 1.0 / (p2 - p1);
printf(" region = [%d, %d), subregion [%d, %d), overlap = %.2lf\n", lpos, rpos, p1, p2, ratio);
if(ratio < min_subregion_overlap) return true;
int32_t indel = 0;
SIMI jit1 = imap->lower_bound(ROI(p1, p1 + 1));
SIMI jit2 = imap->upper_bound(ROI(p2 - 1, p2));
for(SIMI jit = jit1; jit != jit2; jit++) indel += jit->second;
printf(" region = [%d, %d), subregion [%d, %d), indel = %d\n", lpos, rpos, p1, p2, indel);
if(indel * 1.0 / (p2 - p1) > max_indel_ratio) return true;
return false;
}
int region::build_partial_exons()
{
pexons.clear();
if(jmap.size() == 0) return 0;
//printf("size = %lu, size2 = %lu, [%d, %d), [%d, %d)\n", jmap.size(), distance(jmap.begin(), jmap.end()), lower(jmap.begin()->first), upper(jmap.begin()->first), lpos, rpos);
if(lower(jmap.begin()->first) == lpos && upper(jmap.begin()->first) == rpos)
{
partial_exon pe(lpos, rpos, ltype, rtype);
evaluate_rectangle(*mmap, pe.lpos, pe.rpos, pe.ave, pe.dev);
pexons.push_back(pe);
return 0;
}
if(inclusive == true && ltype == RIGHT_SPLICE && jmap.find(ROI(lpos, lpos + 1)) == jmap.end())
{
partial_exon pe(lpos, lpos + 1, ltype, END_BOUNDARY);
pe.ave = 1.0;
pe.dev = 1.0;
pexons.push_back(pe);
}
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
int32_t p1 = lower(it->first);
int32_t p2 = upper(it->first);
assert(p1 < p2);
bool b = empty_subregion(p1, p2);
printf(" subregion [%d, %d), empty = %c\n", p1, p2, b ? 'T' : 'F');
if(inclusive == true && p1 == lpos && ltype == RIGHT_SPLICE) b = false;
if(inclusive == true && p2 == rpos && rtype == LEFT_SPLICE) b = false;
if(b == true) continue;
int lt = (p1 == lpos) ? ltype : START_BOUNDARY;
int rt = (p2 == rpos) ? rtype : END_BOUNDARY;
partial_exon pe(p1, p2, lt, rt);
evaluate_rectangle(*mmap, pe.lpos, pe.rpos, pe.ave, pe.dev);
pexons.push_back(pe);
}
if(inclusive && rtype == LEFT_SPLICE && jmap.find(ROI(rpos - 1, rpos)) == jmap.end())
{
partial_exon pe(rpos - 1, rpos, START_BOUNDARY, rtype);
pe.ave = 1.0;
pe.dev = 1.0;
pexons.push_back(pe);
}
return 0;
}
bool region::left_inclusive()
{
if(pexons.size() == 0) return false;
if(pexons[0].lpos == lpos) return true;
else return false;
}
bool region::right_inclusive()
{
if(pexons.size() == 0) return false;
if(pexons[pexons.size() - 1].rpos == rpos) return true;
else return false;
}
int region::print(int index) const
{
int32_t lc = compute_overlap(*mmap, lpos);
int32_t rc = compute_overlap(*mmap, rpos - 1);
printf("region %d: partial-exons = %lu, type = (%d, %d), pos = [%d, %d), boundary coverage = (%d, %d)\n",
index, pexons.size(), ltype, rtype, lpos, rpos, lc, rc);
/*
for(JIMI it = jmap.begin(); it != jmap.end(); it++)
{
printf(" [%d, %d) -> %d\n", lower(it->first), upper(it->first), it->second);
}
*/
return 0;
}
|
fix bug in checking empty subregion
|
fix bug in checking empty subregion
|
C++
|
bsd-3-clause
|
Kingsford-Group/scallop
|
f8d202438c1202e241ed2039a34dbe1efee57239
|
src/lib/kineticmodel.cpp
|
src/lib/kineticmodel.cpp
|
/*
This file is part of the Ofi Labs X2 project.
Copyright (C) 2010 Ariya Hidayat <[email protected]>
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 <organization> 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 <COPYRIGHT HOLDER> 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 "kineticmodel.h"
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
static const int KineticModelDefaultUpdateInterval = 15; // ms
class KineticModelPrivate
{
public:
QTimer ticker;
bool released;
int duration;
QPointF position;
QPointF velocity;
QPointF deacceleration;
QTime timestamp;
QPointF lastPosition;
KineticModelPrivate();
};
KineticModelPrivate::KineticModelPrivate()
: released(false)
, duration(1403)
, position(0, 0)
, velocity(0, 0)
, deacceleration(0, 0)
, lastPosition(0, 0)
{
}
KineticModel::KineticModel(QObject *parent)
: QObject(parent)
, d_ptr(new KineticModelPrivate)
{
connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}
KineticModel::~KineticModel()
{
}
int KineticModel::duration() const
{
return d_ptr->duration;
}
void KineticModel::setDuration(int ms)
{
d_ptr->duration = ms;
}
QPointF KineticModel::position() const
{
return d_ptr->position;
}
void KineticModel::setPosition(QPointF position)
{
setPosition( position.x(), position.y() );
}
void KineticModel::setPosition(qreal posX, qreal posY)
{
d_ptr->released = false;
QPointF oldPos = d_ptr->position;
d_ptr->position.setX( posX );
d_ptr->position.setY( posY );
if (!qFuzzyCompare(posX, oldPos.x()) || !qFuzzyCompare(posY, oldPos.y()))
emit positionChanged();
update();
if (!d_ptr->ticker.isActive())
d_ptr->ticker.start();
}
int KineticModel::updateInterval() const
{
return d_ptr->ticker.interval();
}
void KineticModel::setUpdateInterval(int ms)
{
d_ptr->ticker.setInterval(ms);
}
void KineticModel::resetSpeed()
{
Q_D(KineticModel);
d->released = false;
d->ticker.stop();
d->lastPosition = d->position;
d->timestamp.start();
d->velocity = QPointF(0, 0);
}
void KineticModel::release()
{
Q_D(KineticModel);
d->released = true;
d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
if (d->deacceleration.x() < 0) {
d->deacceleration.setX( -d->deacceleration.x() );
}
if (d->deacceleration.y() < 0) {
d->deacceleration.setY( -d->deacceleration.y() );
}
if (d->deacceleration.x() > 0.5 || d->deacceleration.y() > 0.5) {
if (!d->ticker.isActive())
d->ticker.start();
update();
} else {
d->ticker.stop();
}
}
void KineticModel::update()
{
Q_D(KineticModel);
int elapsed = d->timestamp.elapsed();
// too fast gives less accuracy
if (elapsed < d->ticker.interval() / 2) {
return;
}
qreal delta = static_cast<qreal>(elapsed) / 1000.0;
if (d->released) {
d->position += d->velocity * delta;
QPointF vstep = d->deacceleration * delta;
if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
d->velocity.setX( 0 );
d->ticker.stop();
} else {
if (d->velocity.x() > 0)
d->velocity.setX( d->velocity.x() - vstep.x() );
else
d->velocity.setX( d->velocity.x() + vstep.x() );
}
if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
d->velocity.setY( 0 );
} else {
if (d->velocity.y() > 0)
d->velocity.setY( d->velocity.y() - vstep.y() );
else
d->velocity.setY( d->velocity.y() + vstep.y() );
}
emit positionChanged();
if (d->velocity.isNull()) {
emit finished();
d->ticker.stop();
}
} else {
QPointF lastSpeed = d->velocity;
QPointF currentSpeed = ( d->position - d->lastPosition ) / delta;
d->velocity = .2 * lastSpeed + .8 * currentSpeed;
d->lastPosition = d->position;
}
d->timestamp.start();
}
#include "kineticmodel.moc"
|
/*
This file is part of the Ofi Labs X2 project.
Copyright (C) 2010 Ariya Hidayat <[email protected]>
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 <organization> 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 <COPYRIGHT HOLDER> 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 "kineticmodel.h"
#include <QtCore/QTimer>
#include <QtCore/QDateTime>
static const int KineticModelDefaultUpdateInterval = 15; // ms
class KineticModelPrivate
{
public:
QTimer ticker;
bool released;
int duration;
QPointF position;
QPointF velocity;
QPointF deacceleration;
QTime timestamp;
QPointF lastPosition;
KineticModelPrivate();
};
KineticModelPrivate::KineticModelPrivate()
: released(false)
, duration(1403)
, position(0, 0)
, velocity(0, 0)
, deacceleration(0, 0)
, lastPosition(0, 0)
{
}
KineticModel::KineticModel(QObject *parent)
: QObject(parent)
, d_ptr(new KineticModelPrivate)
{
connect(&d_ptr->ticker, SIGNAL(timeout()), SLOT(update()));
d_ptr->ticker.setInterval(KineticModelDefaultUpdateInterval);
}
KineticModel::~KineticModel()
{
}
int KineticModel::duration() const
{
return d_ptr->duration;
}
void KineticModel::setDuration(int ms)
{
d_ptr->duration = ms;
}
QPointF KineticModel::position() const
{
return d_ptr->position;
}
void KineticModel::setPosition(QPointF position)
{
setPosition( position.x(), position.y() );
}
void KineticModel::setPosition(qreal posX, qreal posY)
{
d_ptr->released = false;
QPointF oldPos = d_ptr->position;
d_ptr->position.setX( posX );
d_ptr->position.setY( posY );
if (!qFuzzyCompare(posX, oldPos.x()) || !qFuzzyCompare(posY, oldPos.y()))
emit positionChanged();
update();
if (!d_ptr->ticker.isActive())
d_ptr->ticker.start();
}
int KineticModel::updateInterval() const
{
return d_ptr->ticker.interval();
}
void KineticModel::setUpdateInterval(int ms)
{
d_ptr->ticker.setInterval(ms);
}
void KineticModel::resetSpeed()
{
Q_D(KineticModel);
d->released = false;
d->ticker.stop();
d->lastPosition = d->position;
d->timestamp.start();
d->velocity = QPointF(0, 0);
}
void KineticModel::release()
{
Q_D(KineticModel);
d->released = true;
d->deacceleration = d->velocity * 1000 / ( 1 + d_ptr->duration );
if (d->deacceleration.x() < 0) {
d->deacceleration.setX( -d->deacceleration.x() );
}
if (d->deacceleration.y() < 0) {
d->deacceleration.setY( -d->deacceleration.y() );
}
if (d->deacceleration.x() > 0.0005 || d->deacceleration.y() > 0.0005) {
if (!d->ticker.isActive())
d->ticker.start();
update();
} else {
d->ticker.stop();
}
}
void KineticModel::update()
{
Q_D(KineticModel);
int elapsed = d->timestamp.elapsed();
// too fast gives less accuracy
if (elapsed < d->ticker.interval() / 2) {
return;
}
qreal delta = static_cast<qreal>(elapsed) / 1000.0;
if (d->released) {
d->position += d->velocity * delta;
QPointF vstep = d->deacceleration * delta;
if (d->velocity.x() < vstep.x() && d->velocity.x() >= -vstep.x()) {
d->velocity.setX( 0 );
d->ticker.stop();
} else {
if (d->velocity.x() > 0)
d->velocity.setX( d->velocity.x() - vstep.x() );
else
d->velocity.setX( d->velocity.x() + vstep.x() );
}
if (d->velocity.y() < vstep.y() && d->velocity.y() >= -vstep.y()) {
d->velocity.setY( 0 );
} else {
if (d->velocity.y() > 0)
d->velocity.setY( d->velocity.y() - vstep.y() );
else
d->velocity.setY( d->velocity.y() + vstep.y() );
}
emit positionChanged();
if (d->velocity.isNull()) {
emit finished();
d->ticker.stop();
}
} else {
QPointF lastSpeed = d->velocity;
QPointF currentSpeed = ( d->position - d->lastPosition ) / delta;
d->velocity = .2 * lastSpeed + .8 * currentSpeed;
d->lastPosition = d->position;
}
d->timestamp.start();
}
#include "kineticmodel.moc"
|
Fix kinetic spinning at high zoom levels.
|
Fix kinetic spinning at high zoom levels.
Geoposition differences are small at high zoom levels and
deacceleration is small as well. Use a smaller threshold to abort
kinetic spinning to have it work at higher zoom levels as well.
|
C++
|
lgpl-2.1
|
oberluz/marble,tzapzoor/marble,Earthwings/marble,quannt24/marble,quannt24/marble,tucnak/marble,rku/marble,utkuaydin/marble,adraghici/marble,utkuaydin/marble,utkuaydin/marble,David-Gil/marble-dev,Earthwings/marble,oberluz/marble,rku/marble,David-Gil/marble-dev,Earthwings/marble,adraghici/marble,David-Gil/marble-dev,Earthwings/marble,tzapzoor/marble,quannt24/marble,tucnak/marble,utkuaydin/marble,AndreiDuma/marble,tucnak/marble,probonopd/marble,AndreiDuma/marble,tucnak/marble,oberluz/marble,adraghici/marble,AndreiDuma/marble,rku/marble,David-Gil/marble-dev,AndreiDuma/marble,tzapzoor/marble,tzapzoor/marble,tucnak/marble,AndreiDuma/marble,David-Gil/marble-dev,oberluz/marble,adraghici/marble,utkuaydin/marble,quannt24/marble,adraghici/marble,utkuaydin/marble,tzapzoor/marble,rku/marble,probonopd/marble,probonopd/marble,oberluz/marble,tucnak/marble,quannt24/marble,Earthwings/marble,probonopd/marble,David-Gil/marble-dev,rku/marble,rku/marble,tzapzoor/marble,tucnak/marble,probonopd/marble,quannt24/marble,tzapzoor/marble,probonopd/marble,adraghici/marble,AndreiDuma/marble,probonopd/marble,Earthwings/marble,quannt24/marble,oberluz/marble,tzapzoor/marble
|
928cccc620f075bd768e5ba907d63b2c8abc82b2
|
src/libANGLE/Sampler.cpp
|
src/libANGLE/Sampler.cpp
|
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Sampler.cpp : Implements the Sampler class, which represents a GLES 3
// sampler object. Sampler objects store some state needed to sample textures.
#include "libANGLE/Sampler.h"
#include "libANGLE/angletypes.h"
#include "libANGLE/renderer/ImplFactory.h"
#include "libANGLE/renderer/SamplerImpl.h"
namespace gl
{
Sampler::Sampler(rx::ImplFactory *factory, GLuint id)
: mImpl(factory->createSampler()), RefCountObject(id), mSamplerState()
{
}
Sampler::~Sampler()
{
SafeDelete(mImpl);
}
void Sampler::setMinFilter(GLenum minFilter)
{
mSamplerState.minFilter = minFilter;
}
GLenum Sampler::getMinFilter() const
{
return mSamplerState.minFilter;
}
void Sampler::setMagFilter(GLenum magFilter)
{
mSamplerState.magFilter = magFilter;
}
GLenum Sampler::getMagFilter() const
{
return mSamplerState.magFilter;
}
void Sampler::setWrapS(GLenum wrapS)
{
mSamplerState.wrapS = wrapS;
}
GLenum Sampler::getWrapS() const
{
return mSamplerState.wrapS;
}
void Sampler::setWrapT(GLenum wrapT)
{
mSamplerState.wrapT = wrapT;
}
GLenum Sampler::getWrapT() const
{
return mSamplerState.wrapT;
}
void Sampler::setWrapR(GLenum wrapR)
{
mSamplerState.wrapR = wrapR;
}
GLenum Sampler::getWrapR() const
{
return mSamplerState.wrapR;
}
void Sampler::setMaxAnisotropy(float maxAnisotropy)
{
mSamplerState.maxAnisotropy = maxAnisotropy;
}
float Sampler::getMaxAnisotropy() const
{
return mSamplerState.maxAnisotropy;
}
void Sampler::setMinLod(GLfloat minLod)
{
mSamplerState.minLod = minLod;
}
GLfloat Sampler::getMinLod() const
{
return mSamplerState.minLod;
}
void Sampler::setMaxLod(GLfloat maxLod)
{
mSamplerState.maxLod = maxLod;
}
GLfloat Sampler::getMaxLod() const
{
return mSamplerState.maxLod;
}
void Sampler::setCompareMode(GLenum compareMode)
{
mSamplerState.compareMode = compareMode;
}
GLenum Sampler::getCompareMode() const
{
return mSamplerState.compareMode;
}
void Sampler::setCompareFunc(GLenum compareFunc)
{
mSamplerState.compareFunc = compareFunc;
}
GLenum Sampler::getCompareFunc() const
{
return mSamplerState.compareFunc;
}
const SamplerState &Sampler::getSamplerState() const
{
return mSamplerState;
}
const rx::SamplerImpl *Sampler::getImplementation() const
{
return mImpl;
}
rx::SamplerImpl *Sampler::getImplementation()
{
return mImpl;
}
}
|
//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Sampler.cpp : Implements the Sampler class, which represents a GLES 3
// sampler object. Sampler objects store some state needed to sample textures.
#include "libANGLE/Sampler.h"
#include "libANGLE/angletypes.h"
#include "libANGLE/renderer/ImplFactory.h"
#include "libANGLE/renderer/SamplerImpl.h"
namespace gl
{
Sampler::Sampler(rx::ImplFactory *factory, GLuint id)
: RefCountObject(id), mImpl(factory->createSampler()), mSamplerState()
{
}
Sampler::~Sampler()
{
SafeDelete(mImpl);
}
void Sampler::setMinFilter(GLenum minFilter)
{
mSamplerState.minFilter = minFilter;
}
GLenum Sampler::getMinFilter() const
{
return mSamplerState.minFilter;
}
void Sampler::setMagFilter(GLenum magFilter)
{
mSamplerState.magFilter = magFilter;
}
GLenum Sampler::getMagFilter() const
{
return mSamplerState.magFilter;
}
void Sampler::setWrapS(GLenum wrapS)
{
mSamplerState.wrapS = wrapS;
}
GLenum Sampler::getWrapS() const
{
return mSamplerState.wrapS;
}
void Sampler::setWrapT(GLenum wrapT)
{
mSamplerState.wrapT = wrapT;
}
GLenum Sampler::getWrapT() const
{
return mSamplerState.wrapT;
}
void Sampler::setWrapR(GLenum wrapR)
{
mSamplerState.wrapR = wrapR;
}
GLenum Sampler::getWrapR() const
{
return mSamplerState.wrapR;
}
void Sampler::setMaxAnisotropy(float maxAnisotropy)
{
mSamplerState.maxAnisotropy = maxAnisotropy;
}
float Sampler::getMaxAnisotropy() const
{
return mSamplerState.maxAnisotropy;
}
void Sampler::setMinLod(GLfloat minLod)
{
mSamplerState.minLod = minLod;
}
GLfloat Sampler::getMinLod() const
{
return mSamplerState.minLod;
}
void Sampler::setMaxLod(GLfloat maxLod)
{
mSamplerState.maxLod = maxLod;
}
GLfloat Sampler::getMaxLod() const
{
return mSamplerState.maxLod;
}
void Sampler::setCompareMode(GLenum compareMode)
{
mSamplerState.compareMode = compareMode;
}
GLenum Sampler::getCompareMode() const
{
return mSamplerState.compareMode;
}
void Sampler::setCompareFunc(GLenum compareFunc)
{
mSamplerState.compareFunc = compareFunc;
}
GLenum Sampler::getCompareFunc() const
{
return mSamplerState.compareFunc;
}
const SamplerState &Sampler::getSamplerState() const
{
return mSamplerState;
}
const rx::SamplerImpl *Sampler::getImplementation() const
{
return mImpl;
}
rx::SamplerImpl *Sampler::getImplementation()
{
return mImpl;
}
}
|
Fix a warning on Linux and Mac
|
Sampler.cpp: Fix a warning on Linux and Mac
BUG=
Change-Id: I58a19de9d5978aa4d65ac2ab1acd2fbd233ec6a2
Reviewed-on: https://chromium-review.googlesource.com/302463
Reviewed-by: Geoff Lang <[email protected]>
Tested-by: Geoff Lang <[email protected]>
|
C++
|
bsd-3-clause
|
mlfarrell/angle,ppy/angle,vvuk/angle,vvuk/angle,mybios/angle,mlfarrell/angle,ppy/angle,mybios/angle,mikolalysenko/angle,MSOpenTech/angle,mikolalysenko/angle,ppy/angle,ecoal95/angle,ecoal95/angle,MSOpenTech/angle,mikolalysenko/angle,domokit/waterfall,vvuk/angle,mikolalysenko/angle,MSOpenTech/angle,ecoal95/angle,domokit/waterfall,ppy/angle,MSOpenTech/angle,mlfarrell/angle,ecoal95/angle,mybios/angle,mlfarrell/angle,vvuk/angle,ecoal95/angle,mybios/angle
|
f8912c5033a73a6c2a11e54f88492bc4faf41c56
|
src/libGLESv2/Buffer.cpp
|
src/libGLESv2/Buffer.cpp
|
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Buffer.cpp: Implements the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.
#include "libGLESv2/Buffer.h"
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/IndexBuffer.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Buffer::Buffer(rx::Renderer *renderer, GLuint id) : RefCountObject(id)
{
mRenderer = renderer;
mUsage = GL_DYNAMIC_DRAW;
mBufferStorage = renderer->createBufferStorage();
mStaticVertexBuffer = NULL;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
Buffer::~Buffer()
{
delete mBufferStorage;
delete mStaticVertexBuffer;
delete mStaticIndexBuffer;
}
void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
mBufferStorage->clear();
mIndexRangeCache.clear();
mBufferStorage->setData(data, size, 0);
mUsage = usage;
invalidateStaticData();
if (usage == GL_STATIC_DRAW)
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
mBufferStorage->setData(data, size, offset);
mIndexRangeCache.invalidateRange(offset, size);
if ((mStaticVertexBuffer && mStaticVertexBuffer->getBufferSize() != 0) || (mStaticIndexBuffer && mStaticIndexBuffer->getBufferSize() != 0))
{
invalidateStaticData();
}
mUnmodifiedDataUse = 0;
}
void Buffer::copyBufferSubData(Buffer* source, GLintptr sourceOffset, GLintptr destOffset, GLsizeiptr size)
{
mBufferStorage->copyData(source->mBufferStorage, size, sourceOffset, destOffset);
if ((mStaticVertexBuffer && mStaticVertexBuffer->getBufferSize() != 0) || (mStaticIndexBuffer && mStaticIndexBuffer->getBufferSize() != 0))
{
invalidateStaticData();
}
mUnmodifiedDataUse = 0;
}
rx::BufferStorage *Buffer::getStorage() const
{
return mBufferStorage;
}
unsigned int Buffer::size() const
{
return mBufferStorage->getSize();
}
GLenum Buffer::usage() const
{
return mUsage;
}
rx::StaticVertexBufferInterface *Buffer::getStaticVertexBuffer()
{
return mStaticVertexBuffer;
}
rx::StaticIndexBufferInterface *Buffer::getStaticIndexBuffer()
{
return mStaticIndexBuffer;
}
void Buffer::invalidateStaticData()
{
delete mStaticVertexBuffer;
mStaticVertexBuffer = NULL;
delete mStaticIndexBuffer;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
// Creates static buffers if sufficient used data has been left unmodified
void Buffer::promoteStaticUsage(int dataSize)
{
if (!mStaticVertexBuffer && !mStaticIndexBuffer)
{
mUnmodifiedDataUse += dataSize;
if (mUnmodifiedDataUse > 3 * mBufferStorage->getSize())
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
}
rx::IndexRangeCache *Buffer::getIndexRangeCache()
{
return &mIndexRangeCache;
}
}
|
#include "precompiled.h"
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Buffer.cpp: Implements the gl::Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.
#include "libGLESv2/Buffer.h"
#include "libGLESv2/renderer/VertexBuffer.h"
#include "libGLESv2/renderer/IndexBuffer.h"
#include "libGLESv2/renderer/BufferStorage.h"
#include "libGLESv2/renderer/Renderer.h"
namespace gl
{
Buffer::Buffer(rx::Renderer *renderer, GLuint id) : RefCountObject(id)
{
mRenderer = renderer;
mUsage = GL_DYNAMIC_DRAW;
mBufferStorage = renderer->createBufferStorage();
mStaticVertexBuffer = NULL;
mStaticIndexBuffer = NULL;
mUnmodifiedDataUse = 0;
}
Buffer::~Buffer()
{
delete mBufferStorage;
delete mStaticVertexBuffer;
delete mStaticIndexBuffer;
}
void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
mBufferStorage->clear();
mIndexRangeCache.clear();
mBufferStorage->setData(data, size, 0);
mUsage = usage;
invalidateStaticData();
if (usage == GL_STATIC_DRAW)
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
mBufferStorage->setData(data, size, offset);
mIndexRangeCache.invalidateRange(offset, size);
invalidateStaticData();
}
void Buffer::copyBufferSubData(Buffer* source, GLintptr sourceOffset, GLintptr destOffset, GLsizeiptr size)
{
mBufferStorage->copyData(source->mBufferStorage, size, sourceOffset, destOffset);
invalidateStaticData();
}
rx::BufferStorage *Buffer::getStorage() const
{
return mBufferStorage;
}
unsigned int Buffer::size() const
{
return mBufferStorage->getSize();
}
GLenum Buffer::usage() const
{
return mUsage;
}
rx::StaticVertexBufferInterface *Buffer::getStaticVertexBuffer()
{
return mStaticVertexBuffer;
}
rx::StaticIndexBufferInterface *Buffer::getStaticIndexBuffer()
{
return mStaticIndexBuffer;
}
void Buffer::invalidateStaticData()
{
if ((mStaticVertexBuffer && mStaticVertexBuffer->getBufferSize() != 0) || (mStaticIndexBuffer && mStaticIndexBuffer->getBufferSize() != 0))
{
delete mStaticVertexBuffer;
mStaticVertexBuffer = NULL;
delete mStaticIndexBuffer;
mStaticIndexBuffer = NULL;
}
mUnmodifiedDataUse = 0;
}
// Creates static buffers if sufficient used data has been left unmodified
void Buffer::promoteStaticUsage(int dataSize)
{
if (!mStaticVertexBuffer && !mStaticIndexBuffer)
{
mUnmodifiedDataUse += dataSize;
if (mUnmodifiedDataUse > 3 * mBufferStorage->getSize())
{
mStaticVertexBuffer = new rx::StaticVertexBufferInterface(mRenderer);
mStaticIndexBuffer = new rx::StaticIndexBufferInterface(mRenderer);
}
}
}
rx::IndexRangeCache *Buffer::getIndexRangeCache()
{
return &mIndexRangeCache;
}
}
|
Refactor buffer existance check into Buffer::invalidateStaticData.
|
Refactor buffer existance check into Buffer::invalidateStaticData.
Change-Id: I28a7654d152865c236831636f00554a71784667b
Reviewed-on: https://chromium-review.googlesource.com/184394
Reviewed-by: Shannon Woods <[email protected]>
Reviewed-by: Jamie Madill <[email protected]>
Tested-by: Geoff Lang <[email protected]>
|
C++
|
bsd-3-clause
|
mrobinson/rust-angle,jgcaaprom/android_external_chromium_org_third_party_angle,ghostoy/angle,crezefire/angle,MSOpenTech/angle,nandhanurrevanth/angle,mybios/angle,ecoal95/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,android-ia/platform_external_chromium_org_third_party_angle,mybios/angle,mrobinson/rust-angle,mlfarrell/angle,mikolalysenko/angle,xin3liang/platform_external_chromium_org_third_party_angle,mikolalysenko/angle,xin3liang/platform_external_chromium_org_third_party_angle,jgcaaprom/android_external_chromium_org_third_party_angle,xin3liang/platform_external_chromium_org_third_party_angle,bsergean/angle,xin3liang/platform_external_chromium_org_third_party_angle,crezefire/angle,ecoal95/angle,bsergean/angle,vvuk/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,ghostoy/angle,crezefire/angle,MIPS/external-chromium_org-third_party-angle,MIPS/external-chromium_org-third_party-angle,domokit/waterfall,android-ia/platform_external_chromium_org_third_party_angle,ppy/angle,csa7mdm/angle,ecoal95/angle,larsbergstrom/angle,nandhanurrevanth/angle,vvuk/angle,ppy/angle,ppy/angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,MSOpenTech/angle,jgcaaprom/android_external_chromium_org_third_party_angle,mikolalysenko/angle,jgcaaprom/android_external_chromium_org_third_party_angle,geekboxzone/lollipop_external_chromium_org_third_party_angle,mlfarrell/angle,mlfarrell/angle,domokit/waterfall,larsbergstrom/angle,MSOpenTech/angle,crezefire/angle,MSOpenTech/angle,mlfarrell/angle,ecoal95/angle,mrobinson/rust-angle,vvuk/angle,nandhanurrevanth/angle,csa7mdm/angle,ghostoy/angle,nandhanurrevanth/angle,android-ia/platform_external_chromium_org_third_party_angle,bsergean/angle,mybios/angle,ecoal95/angle,mrobinson/rust-angle,MIPS/external-chromium_org-third_party-angle,mrobinson/rust-angle,csa7mdm/angle,mybios/angle,MIPS/external-chromium_org-third_party-angle,mikolalysenko/angle,larsbergstrom/angle,ppy/angle,vvuk/angle,ghostoy/angle,csa7mdm/angle,android-ia/platform_external_chromium_org_third_party_angle,bsergean/angle,larsbergstrom/angle
|
fda067edd55fa2b0ddb55da571b0713037eadccf
|
src/XalanDOM/XalanNodeListSurrogate.cpp
|
src/XalanDOM/XalanNodeListSurrogate.cpp
|
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XalanNodeListSurrogate.hpp"
#include "XalanNode.hpp"
XalanNodeListSurrogate::XalanNodeListSurrogate(const XalanNode& theNode) :
m_node(&theNode)
{
}
XalanNodeListSurrogate::XalanNodeListSurrogate(const XalanNodeListSurrogate& theSource) :
m_node(theSource.m_node)
{
}
XalanNodeListSurrogate::~XalanNodeListSurrogate()
{
}
XalanNode*
XalanNodeListSurrogate::item(unsigned int index) const
{
XalanNode* theCurrentChild = m_node->getFirstChild();
for(unsigned int i = 0; i < index && theCurrentChild != 0; ++i)
{
theCurrentChild = theCurrentChild->getNextSibling();
}
return theCurrentChild;
}
unsigned int
XalanNodeListSurrogate::getLength() const
{
unsigned int theLength = 0;
XalanNode* theCurrentChild = m_node->getFirstChild();
while(theCurrentChild != 0)
{
++theLength;
theCurrentChild = theCurrentChild->getNextSibling();
}
return theLength;
}
|
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XalanNodeListSurrogate.hpp"
#include "XalanNode.hpp"
XalanNodeListSurrogate::XalanNodeListSurrogate(const XalanNode& theNode) :
XalanNodeList(),
m_node(&theNode)
{
}
XalanNodeListSurrogate::XalanNodeListSurrogate(const XalanNodeListSurrogate& theSource) :
XalanNodeList(theSource),
m_node(theSource.m_node)
{
}
XalanNodeListSurrogate::~XalanNodeListSurrogate()
{
}
XalanNode*
XalanNodeListSurrogate::item(unsigned int index) const
{
XalanNode* theCurrentChild = m_node->getFirstChild();
for(unsigned int i = 0; i < index && theCurrentChild != 0; ++i)
{
theCurrentChild = theCurrentChild->getNextSibling();
}
return theCurrentChild;
}
unsigned int
XalanNodeListSurrogate::getLength() const
{
unsigned int theLength = 0;
XalanNode* theCurrentChild = m_node->getFirstChild();
while(theCurrentChild != 0)
{
++theLength;
theCurrentChild = theCurrentChild->getNextSibling();
}
return theLength;
}
|
Call base class copy constructor.
|
Call base class copy constructor.
|
C++
|
apache-2.0
|
apache/xalan-c,apache/xalan-c,apache/xalan-c,apache/xalan-c
|
a6272d5025f855a267fb6af4adf06c4185ccb582
|
OpenSim/Common/TRCFileAdapter.cpp
|
OpenSim/Common/TRCFileAdapter.cpp
|
#include "TRCFileAdapter.h"
#include <OpenSim/Common/IO.h>
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string _headerDelimiters{ " \t\r" };
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _headerDelimiters);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
IO::eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
IO::eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// for marker labels we do not need three columns per marker.
// remove the blank ones used in TRC due to tabbing
IO::eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
IO::eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine};
std::vector<std::string> row = nextLine();
// skip immediate blank lines between header and data.
while(row.empty() || row.at(0).empty()) {
row = nextLine();
++line_num;
}
const size_t expected{ column_labels.size() * 3 + 2 };
// An empty line during data parsing denotes end of data
while(!row.empty()) {
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
//if any component is blank, treat the location as unspecified
if ( !(row.at(c).empty() && row.at(c + 1).empty()
&& row.at(c + 2).empty()) ) {
row_vector[ind] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
}
++ind;
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
++line_num;
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
|
#include "TRCFileAdapter.h"
#include <OpenSim/Common/IO.h>
#include <fstream>
#include <iomanip>
namespace OpenSim {
const std::string _headerDelimiters{ " \t\r" };
const std::string TRCFileAdapter::_markers{"markers"};
const std::string TRCFileAdapter::_delimiterWrite{"\t"};
// Get rid of the extra \r if parsing a file with CRLF line endings.
const std::string TRCFileAdapter::_delimitersRead{"\t\r"};
const std::string TRCFileAdapter::_frameNumColumnLabel{"Frame#"};
const std::string TRCFileAdapter::_timeColumnLabel{"Time"};
const std::string TRCFileAdapter::_xLabel{"X"};
const std::string TRCFileAdapter::_yLabel{"Y"};
const std::string TRCFileAdapter::_zLabel{"Z"};
const std::string TRCFileAdapter::_numMarkersLabel{"NumMarkers"};
const std::string TRCFileAdapter::_numFramesLabel{"NumFrames"};
const unsigned TRCFileAdapter::_dataStartsAtLine{6};
const std::vector<std::string> TRCFileAdapter::_metadataKeys{"DataRate",
"CameraRate", "NumFrames", "NumMarkers", "Units", "OrigDataRate",
"OrigDataStartFrame", "OrigNumFrames"};
TRCFileAdapter*
TRCFileAdapter::clone() const {
return new TRCFileAdapter{*this};
}
TimeSeriesTableVec3
TRCFileAdapter::read(const std::string& fileName) {
auto abs_table = TRCFileAdapter{}.extendRead(fileName).at(_markers);
return static_cast<TimeSeriesTableVec3&>(*abs_table);
}
void
TRCFileAdapter::write(const TimeSeriesTableVec3& table,
const std::string& fileName) {
InputTables tables{};
tables.emplace(_markers, &table);
TRCFileAdapter{}.extendWrite(tables, fileName);
}
TRCFileAdapter::OutputTables
TRCFileAdapter::extendRead(const std::string& fileName) const {
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ifstream in_stream{fileName};
OPENSIM_THROW_IF(!in_stream.good(),
FileDoesNotExist,
fileName);
auto table = std::make_shared<TimeSeriesTableVec3>();
// Callable to get the next line in form of vector of tokens.
auto nextLine = [&] {
return getNextLine(in_stream, _delimitersRead);
};
// First line of the stream is considered the header.
std::string header{};
std::getline(in_stream, header);
auto header_tokens = tokenize(header, _headerDelimiters);
OPENSIM_THROW_IF(header_tokens.empty(),
FileIsEmpty,
fileName);
OPENSIM_THROW_IF(header_tokens.at(0) != "PathFileType",
MissingHeader);
table->updTableMetaData().setValueForKey("header", header);
// Read the line containing metadata keys.
auto keys = nextLine();
// Keys cannot be empty strings, so delete empty keys due to
// excessive use of delimiters
IO::eraseEmptyElements(keys);
OPENSIM_THROW_IF(keys.size() != _metadataKeys.size(),
IncorrectNumMetaDataKeys,
fileName,
_metadataKeys.size(),
keys.size());
for(size_t i = 0; i < keys.size(); ++i)
OPENSIM_THROW_IF(keys[i] != _metadataKeys[i],
UnexpectedMetaDataKey,
fileName,
_metadataKeys[i],
keys[i]);
// Read the line containing metadata values.
auto values = nextLine();
IO::eraseEmptyElements(values);
OPENSIM_THROW_IF(keys.size() != values.size(),
MetaDataLengthMismatch,
fileName,
keys.size(),
values.size());
// Fill up the metadata container.
for(std::size_t i = 0; i < keys.size(); ++i)
table->updTableMetaData().setValueForKey(keys[i], values[i]);
auto num_markers_expected =
std::stoul(table->
getTableMetaData().
getValueForKey(_numMarkersLabel).
template getValue<std::string>());
// Read the line containing column labels and fill up the column labels
// container.
auto column_labels = nextLine();
// For marker labels we do not need three columns per marker, and
// remove the blank elements in TRC due to uniform tabbing. For example,
// TRC files often have the following structure:
//Frame#<tab>Time<tab>marker1<tab><tab><tab>marker2<tab><tab><tab>
//<tab><tab>X1<tab>Y1<tab>Z1<tab>X2<tab>Y2<tab>Z2<tab>X3<tab>Y3<tab>Z3
IO::eraseEmptyElements(column_labels);
OPENSIM_THROW_IF(column_labels.size() != num_markers_expected + 2,
IncorrectNumColumnLabels,
fileName,
num_markers_expected + 2,
column_labels.size());
// Column 0 should be the frame number. Check and get rid of it as it is
// not used. The whole column is discarded as the data is read in.
OPENSIM_THROW_IF(column_labels[0] != _frameNumColumnLabel,
UnexpectedColumnLabel,
fileName,
_frameNumColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Column 0 (originally column 1 before removing frame number) should
// now be the time column. Check and get rid of it. The data in this
// column is maintained separately from rest of the data.
OPENSIM_THROW_IF(column_labels[0] != _timeColumnLabel,
UnexpectedColumnLabel,
fileName,
_timeColumnLabel,
column_labels[0]);
column_labels.erase(column_labels.begin());
// Read in the next line of column labels containing (Xdd, Ydd, Zdd)
// tuples where dd is a 1 or 2 digit subscript. For example --
// X1, Y1, Z1, X2, Y2, Z2, ... so on.
// Check and ignore these labels.
auto xyz_labels_found = nextLine();
// erase blank labels, e.g. due to Frame# and Time columns
IO::eraseEmptyElements(xyz_labels_found);
for(unsigned i = 1; i <= num_markers_expected; ++i) {
unsigned j = 0;
for(auto& letter : {_xLabel, _yLabel, _zLabel}) {
const unsigned ind = ((i - 1) * 3) + j++;
const std::string expected{letter + std::to_string(i)};
OPENSIM_THROW_IF(xyz_labels_found.at(ind) != expected,
UnexpectedColumnLabel,
fileName,
expected,
xyz_labels_found.at(ind));
}
}
// Read the rows one at a time and fill up the time column container and
// the data container.
std::size_t line_num{_dataStartsAtLine};
std::vector<std::string> row = nextLine();
// skip immediate blank lines between header and data.
while(row.empty() || row.at(0).empty()) {
row = nextLine();
++line_num;
}
const size_t expected{ column_labels.size() * 3 + 2 };
// An empty line during data parsing denotes end of data
while(!row.empty()) {
OPENSIM_THROW_IF(row.size() != expected,
RowLengthMismatch,
fileName,
line_num,
expected,
row.size());
// Columns 2 till the end are data.
TimeSeriesTableVec3::RowVector
row_vector{static_cast<int>(num_markers_expected),
SimTK::Vec3(SimTK::NaN)};
int ind{0};
for (std::size_t c = 2; c < column_labels.size() * 3 + 2; c += 3) {
//if any component is blank, treat the location as unspecified
if ( !(row.at(c).empty() && row.at(c + 1).empty()
&& row.at(c + 2).empty()) ) {
row_vector[ind] = SimTK::Vec3{ std::stod(row.at(c)),
std::stod(row.at(c + 1)),
std::stod(row.at(c + 2)) };
}
++ind;
}
// Column 1 is time.
table->appendRow(std::stod(row.at(1)), std::move(row_vector));
row = nextLine();
++line_num;
}
// Set the column labels of the table.
ValueArray<std::string> value_array{};
for(const auto& cl : column_labels)
value_array.upd().push_back(SimTK::Value<std::string>{cl});
TimeSeriesTableVec3::DependentsMetaData dep_metadata{};
dep_metadata.setValueArrayForKey("labels", value_array);
table->setDependentsMetaData(dep_metadata);
OutputTables output_tables{};
output_tables.emplace(_markers, table);
return output_tables;
}
void
TRCFileAdapter::extendWrite(const InputTables& absTables,
const std::string& fileName) const {
OPENSIM_THROW_IF(absTables.empty(),
NoTableFound);
const TimeSeriesTableVec3* table{};
try {
auto abs_table = absTables.at(_markers);
table = dynamic_cast<const TimeSeriesTableVec3*>(abs_table);
} catch(std::out_of_range) {
OPENSIM_THROW(KeyMissing,
_markers);
} catch(std::bad_cast&) {
OPENSIM_THROW(IncorrectTableType);
}
OPENSIM_THROW_IF(fileName.empty(),
EmptyFileName);
std::ofstream out_stream{fileName};
// First line of the stream is the header.
try {
out_stream << table->
getTableMetaData().
getValueForKey("header").
getValue<std::string>() << "\n";
} catch(KeyNotFound&) {
out_stream << "PathFileType\t4\t(X/Y/Z)\t" << fileName << "\n";
}
// Line containing metadata keys.
out_stream << _metadataKeys[0];
for(unsigned i = 1; i < _metadataKeys.size(); ++i)
out_stream << _delimiterWrite << _metadataKeys[i];
out_stream << "\n";
// Line containing metadata values.
std::string datarate;
try {
datarate = table->
getTableMetaData().
getValueForKey(_metadataKeys[0]).
getValue<std::string>();
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"DataRate");
}
out_stream << datarate << _delimiterWrite;
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[1]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[2]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumRows() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[3]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << table->getNumColumns() << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[4]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
OPENSIM_THROW(MissingMetaData,
"Units");
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[5]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << datarate << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[6]).
getValue<std::string>()
<< _delimiterWrite;
} catch(KeyNotFound&) {
out_stream << 0 << _delimiterWrite;
}
try {
out_stream << table->
getTableMetaData().
getValueForKey(_metadataKeys[7]).
getValue<std::string>();
} catch(KeyNotFound&) {
out_stream << table->getNumRows();
}
out_stream << "\n";
// Line containing column labels.
out_stream << _frameNumColumnLabel << _delimiterWrite
<< _timeColumnLabel << _delimiterWrite;
for(unsigned col = 0; col < table->getNumColumns(); ++col)
out_stream << table->
getDependentsMetaData().
getValueArrayForKey("labels")[col].
getValue<std::string>()
<< _delimiterWrite << _delimiterWrite << _delimiterWrite;
out_stream << "\n";
// Line containing xyz component labels for each marker.
out_stream << _delimiterWrite << _delimiterWrite;
for(unsigned col = 1; col <= table->getNumColumns(); ++col)
for(auto& letter : {_xLabel, _yLabel, _zLabel})
out_stream << (letter + std::to_string(col)) << _delimiterWrite;
out_stream << "\n";
// Empty line.
out_stream << "\n";
// Data rows.
for(unsigned row = 0; row < table->getNumRows(); ++row) {
constexpr auto prec = std::numeric_limits<double>::digits10 + 1;
out_stream << row + 1 << _delimiterWrite
<< std::setprecision(prec)
<< table->getIndependentColumn()[row] << _delimiterWrite;
const auto& row_r = table->getRowAtIndex(row);
for(unsigned col = 0; col < table->getNumColumns(); ++col) {
const auto& elt = row_r[col];
out_stream << std::setprecision(prec)
<< elt[0] << _delimiterWrite
<< elt[1] << _delimiterWrite
<< elt[2] << _delimiterWrite;
}
out_stream << "\n";
}
}
}
|
Add more detailed comment for parsing labels and why empty elements are common due to the TRC file structure.
|
Add more detailed comment for parsing labels and why empty elements are common due to the TRC file structure.
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
6c2c17c0598a0262e483f19c258de88c9acbe1f0
|
src/rpg_setup.cpp
|
src/rpg_setup.cpp
|
/*
* This file is part of EasyRPG.
*
* EasyRPG 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.
*
* EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include "reader_options.h"
#include "rpg_actor.h"
#include "rpg_event.h"
#include "rpg_map.h"
#include "rpg_mapinfo.h"
#include "rpg_system.h"
#include "rpg_save.h"
#include "rpg_chipset.h"
#include "rpg_parameters.h"
#include "data.h"
void RPG::SaveActor::Setup(int actor_id) {
const RPG::Actor& actor = Data::actors[actor_id - 1];
ID = actor.ID;
name = actor.name;
title = actor.title;
sprite_name = actor.character_name;
sprite_id = actor.character_index;
sprite_flags = actor.transparent ? 3 : 0;
face_name = actor.face_name;
face_id = actor.face_index;
level = actor.initial_level;
exp = 0;
hp_mod = 0;
sp_mod = 0;
attack_mod = 0;
defense_mod = 0;
spirit_mod = 0;
agility_mod = 0;
skills_size = 0;
skills.clear();
equipped.clear();
equipped.push_back(actor.initial_equipment.weapon_id);
equipped.push_back(actor.initial_equipment.shield_id);
equipped.push_back(actor.initial_equipment.armor_id);
equipped.push_back(actor.initial_equipment.helmet_id);
equipped.push_back(actor.initial_equipment.accessory_id);
current_hp = 0;
current_sp = 0;
battle_commands = actor.battle_commands;
status_size = 0;
status.clear();
changed_class = false;
class_id = actor.class_id;
row = -1;
two_weapon = actor.two_swords_style;
lock_equipment = actor.fix_equipment;
auto_battle = actor.auto_battle;
mighty_guard = actor.super_guard;
unknown_60 = -1;
}
void RPG::SaveInventory::Setup() {
party = Data::system.party;
party_size = party.size();
}
void RPG::SaveMapEvent::Setup(const RPG::Event& event) {
ID = event.ID;
position_x = event.x;
position_y = event.y;
}
void RPG::SaveMapInfo::Setup() {
position_x = 0;
position_y = 0;
lower_tiles.resize(144);
upper_tiles.resize(144);
for (int i = 0; i < 144; i++) {
lower_tiles[i] = i;
upper_tiles[i] = i;
}
}
void RPG::SaveMapInfo::Setup(const RPG::Map& map) {
chipset_id = map.chipset_id;
parallax_name = map.parallax_name;
parallax_horz = map.parallax_loop_x;
parallax_vert = map.parallax_loop_y;
parallax_horz_auto = map.parallax_auto_loop_x;
parallax_vert_auto = map.parallax_auto_loop_y;
parallax_horz_speed = map.parallax_sx;
parallax_vert_speed = map.parallax_sy;
}
void RPG::SaveMapInfo::Setup(const RPG::MapInfo& map_info) {
encounter_rate = map_info.encounter_steps;
}
void RPG::SaveSystem::Setup() {
const RPG::System& system = Data::system;
screen = 0;
frame_count = 0;
graphics_name = system.system_name;
switches_size = Data::switches.size();
switches.clear();
switches.resize(switches_size);
variables_size = Data::variables.size();
variables.clear();
variables.resize(variables_size);
face_name = "";
face_id = -1;
face_right = false;
face_flip = false;
transparent = false;
unknown_3d = -1;
title_music = system.title_music;
battle_music = system.battle_music;
battle_end_music = system.battle_end_music;
inn_music = system.inn_music;
// current_music
// unknown1_music FIXME
// unknown2_music FIXME
// stored_music
boat_music = system.boat_music;
ship_music = system.ship_music;
airship_music = system.airship_music;
gameover_music = system.gameover_music;
cursor_se = system.cursor_se;
decision_se = system.decision_se;
cancel_se = system.cancel_se;
buzzer_se = system.buzzer_se;
battle_se = system.battle_se;
escape_se = system.escape_se;
enemy_attack_se = system.enemy_attack_se;
enemy_damaged_se = system.enemy_damaged_se;
actor_damaged_se = system.actor_damaged_se;
dodge_se = system.dodge_se;
enemy_death_se = system.enemy_death_se;
item_se = system.item_se;
transition_out = system.transition_out;
transition_in = system.transition_in;
battle_start_fadeout = system.battle_start_fadeout;
battle_start_fadein = system.battle_start_fadein;
battle_end_fadeout = system.battle_end_fadeout;
battle_end_fadein = system.battle_end_fadein;
teleport_allowed = true;
escape_allowed = true;
save_allowed = true;
menu_allowed = true;
background = "";
save_count = 0;
save_slot = -1;
}
void RPG::Save::Setup() {
system.Setup();
pictures.resize(50);
for (int i = 1; i <= (int) pictures.size(); i++)
pictures[i - 1].ID = i;
actors.resize(Data::actors.size());
for (int i = 1; i <= (int) actors.size(); i++)
actors[i - 1].Setup(i);
map_info.Setup();
}
void RPG::Actor::Init() {
#if RPGMAKER == RPG2K3
final_level = 99;
exp_base = 300;
exp_inflation = 300;
#endif
parameters.Setup(final_level);
}
void RPG::MapInfo::Init() {
music.name = "(OFF)";
}
void RPG::Chipset::Init() {
terrain_data.resize(162, 1);
passable_data_lower.resize(162, 15);
passable_data_upper.resize(162, 15);
}
void RPG::Parameters::Setup(int final_level) {
maxhp.resize(final_level + 1);
maxsp.resize(final_level + 1);
attack.resize(final_level + 1);
defense.resize(final_level + 1);
spirit.resize(final_level + 1);
agility.resize(final_level + 1);
for (int i = 0; i <= final_level; i++) {
maxhp[i] = 1;
maxsp[i] = 0;
attack[i] = 1;
defense[i] = 1;
spirit[i] = 1;
agility[i] = 1;
}
}
|
/*
* This file is part of EasyRPG.
*
* EasyRPG 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.
*
* EasyRPG 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 EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include "reader_options.h"
#include "rpg_actor.h"
#include "rpg_event.h"
#include "rpg_map.h"
#include "rpg_mapinfo.h"
#include "rpg_system.h"
#include "rpg_save.h"
#include "rpg_chipset.h"
#include "rpg_parameters.h"
#include "data.h"
void RPG::SaveActor::Setup(int actor_id) {
const RPG::Actor& actor = Data::actors[actor_id - 1];
ID = actor.ID;
name = actor.name;
title = actor.title;
sprite_name = actor.character_name;
sprite_id = actor.character_index;
sprite_flags = actor.transparent ? 3 : 0;
face_name = actor.face_name;
face_id = actor.face_index;
level = actor.initial_level;
exp = 0;
hp_mod = 0;
sp_mod = 0;
attack_mod = 0;
defense_mod = 0;
spirit_mod = 0;
agility_mod = 0;
skills_size = 0;
skills.clear();
equipped.clear();
equipped.push_back(actor.initial_equipment.weapon_id);
equipped.push_back(actor.initial_equipment.shield_id);
equipped.push_back(actor.initial_equipment.armor_id);
equipped.push_back(actor.initial_equipment.helmet_id);
equipped.push_back(actor.initial_equipment.accessory_id);
current_hp = 0;
current_sp = 0;
battle_commands = actor.battle_commands;
status_size = 0;
status.clear();
changed_class = false;
class_id = actor.class_id;
row = -1;
two_weapon = actor.two_swords_style;
lock_equipment = actor.fix_equipment;
auto_battle = actor.auto_battle;
mighty_guard = actor.super_guard;
unknown_60 = -1;
}
void RPG::SaveInventory::Setup() {
party = Data::system.party;
party_size = party.size();
}
void RPG::SaveMapEvent::Setup(const RPG::Event& event) {
ID = event.ID;
position_x = event.x;
position_y = event.y;
}
void RPG::SaveMapInfo::Setup() {
position_x = 0;
position_y = 0;
lower_tiles.resize(144);
upper_tiles.resize(144);
for (int i = 0; i < 144; i++) {
lower_tiles[i] = i;
upper_tiles[i] = i;
}
}
void RPG::SaveMapInfo::Setup(const RPG::Map& map) {
chipset_id = map.chipset_id;
parallax_name = map.parallax_name;
parallax_horz = map.parallax_loop_x;
parallax_vert = map.parallax_loop_y;
parallax_horz_auto = map.parallax_auto_loop_x;
parallax_vert_auto = map.parallax_auto_loop_y;
parallax_horz_speed = map.parallax_sx;
parallax_vert_speed = map.parallax_sy;
}
void RPG::SaveMapInfo::Setup(const RPG::MapInfo& map_info) {
encounter_rate = map_info.encounter_steps;
}
void RPG::SaveSystem::Setup() {
const RPG::System& system = Data::system;
screen = 0;
frame_count = 0;
graphics_name = system.system_name;
switches_size = Data::switches.size();
switches.clear();
switches.resize(switches_size);
variables_size = Data::variables.size();
variables.clear();
variables.resize(variables_size);
face_name = "";
face_id = -1;
face_right = false;
face_flip = false;
transparent = false;
unknown_3d = -1;
title_music = system.title_music;
battle_music = system.battle_music;
battle_end_music = system.battle_end_music;
inn_music = system.inn_music;
// current_music
// unknown1_music FIXME
// unknown2_music FIXME
// stored_music
boat_music = system.boat_music;
ship_music = system.ship_music;
airship_music = system.airship_music;
gameover_music = system.gameover_music;
cursor_se = system.cursor_se;
decision_se = system.decision_se;
cancel_se = system.cancel_se;
buzzer_se = system.buzzer_se;
battle_se = system.battle_se;
escape_se = system.escape_se;
enemy_attack_se = system.enemy_attack_se;
enemy_damaged_se = system.enemy_damaged_se;
actor_damaged_se = system.actor_damaged_se;
dodge_se = system.dodge_se;
enemy_death_se = system.enemy_death_se;
item_se = system.item_se;
transition_out = system.transition_out;
transition_in = system.transition_in;
battle_start_fadeout = system.battle_start_fadeout;
battle_start_fadein = system.battle_start_fadein;
battle_end_fadeout = system.battle_end_fadeout;
battle_end_fadein = system.battle_end_fadein;
teleport_allowed = true;
escape_allowed = true;
save_allowed = true;
menu_allowed = true;
background = "";
save_count = 0;
save_slot = -1;
}
void RPG::Save::Setup() {
system.Setup();
screen = RPG::SaveScreen();
pictures.clear();
pictures.resize(50);
for (int i = 1; i <= (int)pictures.size(); i++) {
pictures[i - 1].ID = i;
}
actors.clear();
actors.resize(Data::actors.size());
for (int i = 1; i <= (int) actors.size(); i++)
actors[i - 1].Setup(i);
map_info.Setup();
}
void RPG::Actor::Init() {
#if RPGMAKER == RPG2K3
final_level = 99;
exp_base = 300;
exp_inflation = 300;
#endif
parameters.Setup(final_level);
}
void RPG::MapInfo::Init() {
music.name = "(OFF)";
}
void RPG::Chipset::Init() {
terrain_data.resize(162, 1);
passable_data_lower.resize(162, 15);
passable_data_upper.resize(162, 15);
}
void RPG::Parameters::Setup(int final_level) {
maxhp.resize(final_level + 1);
maxsp.resize(final_level + 1);
attack.resize(final_level + 1);
defense.resize(final_level + 1);
spirit.resize(final_level + 1);
agility.resize(final_level + 1);
for (int i = 0; i <= final_level; i++) {
maxhp[i] = 1;
maxsp[i] = 0;
attack[i] = 1;
defense[i] = 1;
spirit[i] = 1;
agility[i] = 1;
}
}
|
Reset more save state fields
|
Reset more save state fields
|
C++
|
mit
|
Zegeri/liblcf,Ghabry/easyrpg-liblcf,EasyRPG/liblcf,carstene1ns/easyrpg-liblcf,EasyRPG/liblcf,glynnc/liblcf,EasyRPG/liblcf,fdelapena/easyrpg-liblcf,glynnc/liblcf,Ghabry/easyrpg-liblcf,Zegeri/liblcf,carstene1ns/easyrpg-liblcf,fdelapena/easyrpg-liblcf,EasyRPG/liblcf,glynnc/liblcf,Ghabry/easyrpg-liblcf,Ghabry/easyrpg-liblcf,glynnc/liblcf,Zegeri/liblcf,fdelapena/easyrpg-liblcf,carstene1ns/easyrpg-liblcf
|
edbba0e98e31bcc8cf0f11e04baca7dfb523903c
|
src/themefile.cpp
|
src/themefile.cpp
|
/****************************************************************************
* themefile.cpp - Theme file handling
*
* Copyright (C) 2003 Hans Karlsson <[email protected]>
* Copyright (C) 2003-2004 Adam Geitgey <[email protected]>
* Copyright (c) 2004 Petri Damstn <[email protected]>
*
* This file is part of Superkaramba.
*
* Superkaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Superkaramba 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 Superkaramba; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include "themefile.h"
#include "lineparser.h"
#include <kdebug.h>
#include <kurl.h>
#include <kzip.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kio/netaccess.h>
#include <qtextstream.h>
#include <qfileinfo.h>
#include <qdom.h>
#include <qdir.h>
class ZipFile
{
public:
ZipFile(const QString& zipfile, const QString& filename) :
m_zip(0), m_file(0), m_filename(filename)
{
if(filename.isEmpty())
return;
const KArchiveDirectory* dir;
const KArchiveEntry* entry;
m_zip = new KZip(zipfile);
if(!m_zip->open(IO_ReadOnly))
{
qDebug("Unable to open '%s' for reading.", zipfile.ascii());
return;
}
dir = m_zip->directory();
if(dir == 0)
{
qDebug("Error reading directory contents of file %s", zipfile.ascii());
return;
}
entry = dir->entry(filename);
if(entry == 0 || !entry->isFile())
return;
m_file = static_cast<const KArchiveFile*>(entry);
}
virtual ~ZipFile()
{
if(m_zip)
{
m_zip->close();
delete m_zip;
}
}
QByteArray data()
{
if(m_file)
return m_file->data();
else
{
if(!m_filename.isEmpty())
qDebug("Error reading file %s from zip", m_filename.ascii());
return QByteArray();
}
}
bool exists()
{
return (m_file != 0);
}
private:
KZip* m_zip;
const KArchiveFile* m_file;
QString m_filename;
};
ThemeFile::ThemeFile(const KURL& url)
: m_stream(0)
{
if(url.isValid())
set(url);
}
ThemeFile::~ThemeFile()
{
delete m_stream;
}
bool ThemeFile::open()
{
bool result = false;
if(m_zipTheme)
{
ZipFile zf(m_file, m_theme);
m_ba = zf.data();
if(m_ba.size() > 0)
{
m_stream = new QTextStream(m_ba, IO_ReadOnly);
result = true;
}
}
else
{
m_fl.setName(m_file);
if(m_fl.open(IO_ReadOnly|IO_Translate))
{
m_stream = new QTextStream(&m_fl); // use a text stream
result = true;
}
}
return result;
}
bool ThemeFile::nextLine(LineParser& parser)
{
parser.set("");
if(m_stream)
{
QString result = m_stream->readLine();
if(result.isNull())
return false;
parser.set(result);
return true;
}
return false;
}
bool ThemeFile::close()
{
if(m_stream)
{
delete m_stream;
m_stream = 0;
m_fl.close();
m_ba.resize(0);
return true;
}
return false;
}
bool ThemeFile::isValid() const
{
return (exists() && !m_name.isEmpty() && !m_theme.isEmpty());
}
bool ThemeFile::exists() const
{
QFileInfo file(m_file);
return file.exists();
}
QPixmap ThemeFile::icon() const
{
return QPixmap(readThemeFile(m_icon));
}
bool ThemeFile::set(const KURL &url)
{
if(!url.isLocalFile())
{
QDir themeDir(locateLocal("appdata", "themes/", true));
QFileInfo localFile = themeDir.filePath(url.fileName());
if(localFile.exists())
{
if(KMessageBox::questionYesNo(kapp->activeWindow(),
i18n("%1 already exists. Do you want to overwrite it?")
.arg(localFile.filePath()))
== KMessageBox::No)
{
return false;
}
}
if(!KIO::NetAccess::file_copy(url, localFile.filePath(), -1, true,
false, kapp->mainWidget()))
{
return false;
}
m_file = localFile.filePath();
}
else
{
m_file = canonicalFile(url.path());
if(!exists())
return false;
}
QFileInfo fi(m_file);
m_name = fi.baseName();
m_theme = m_name + ".theme";
m_python = m_name;
m_id = m_name;
if(isZipFile(m_file))
{
m_path = m_file;
m_zipTheme = true;
}
else
{
m_path = fi.dirPath(true) + "/";
m_zipTheme = false;
}
parseXml();
return isValid();
}
void ThemeFile::parseXml()
{
if(!fileExists("maindata.xml"))
return;
QByteArray ba = readThemeFile("maindata.xml");
QDomDocument doc("superkaramba_theme");
doc.setContent(ba);
QDomElement element = doc.documentElement();
QDomNode n = element.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement();
if(!e.isNull())
{
if(e.tagName() == "name")
m_name = e.text();
if(e.tagName() == "themefile")
m_theme = e.text();
if(e.tagName() == "python_module")
{
m_python = e.text();
if(m_python.right(3).lower() == ".py")
m_python.remove(m_python.length() - 3, 3);
}
if(e.tagName() == "description")
m_description = e.text();
if(e.tagName() == "author")
m_author = e.text();
if(e.tagName() == "author_email")
m_authorEmail = e.text();
if(e.tagName() == "homepage")
m_homepage = e.text();
if(e.tagName() == "icon")
m_icon = e.text();
}
n = n.nextSibling();
}
}
bool ThemeFile::isThemeFile(const QString& filename) const
{
QFileInfo fileInfo(filename);
return fileInfo.isRelative();
}
bool ThemeFile::fileExists(const QString& filename) const
{
if(isThemeFile(filename))
{
if(isZipTheme())
{
ZipFile zf(m_file, filename);
return zf.exists();
}
else
return QFileInfo(path() + "/" + filename).exists();
}
else
return QFileInfo(filename).exists();
}
QByteArray ThemeFile::readThemeFile(const QString& filename) const
{
QByteArray ba;
if(isZipTheme())
{
ZipFile zf(m_file, filename);
ba = zf.data();
}
else
{
QFile file(path() + "/" + filename);
if(file.open(IO_ReadOnly))
{
ba = file.readAll();
file.close();
}
}
return ba;
}
bool ThemeFile::isZipFile(const QString& filename)
{
QFile file(filename);
if(file.open(IO_ReadOnly))
{
unsigned char buf[5];
if(file.readBlock((char*)buf, 4) == 4)
{
if(buf[0] == 'P' && buf[1] == 'K' && buf[2] == 3 && buf[3] == 4)
return true;
}
}
return false;
}
bool ThemeFile::pythonModuleExists() const
{
return (!m_python.isEmpty() && fileExists(m_python + ".py"));
}
QString ThemeFile::canonicalFile(const QString& file)
{
// Get absolute path with NO symlinks
QFileInfo fi(file);
return QDir(fi.dir().canonicalPath()).filePath(fi.fileName());
}
|
/****************************************************************************
* themefile.cpp - Theme file handling
*
* Copyright (C) 2003 Hans Karlsson <[email protected]>
* Copyright (C) 2003-2004 Adam Geitgey <[email protected]>
* Copyright (c) 2004 Petri Damstn <[email protected]>
*
* This file is part of Superkaramba.
*
* Superkaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Superkaramba 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 Superkaramba; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include "themefile.h"
#include "lineparser.h"
#include <kdebug.h>
#include <kurl.h>
#include <kzip.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kio/netaccess.h>
#include <qtextstream.h>
#include <qfileinfo.h>
#include <qdom.h>
#include <qdir.h>
class ZipFile
{
public:
ZipFile(const QString& zipfile, const QString& filename) :
m_zip(0), m_file(0), m_filename(filename)
{
if(filename.isEmpty())
return;
const KArchiveDirectory* dir;
const KArchiveEntry* entry;
m_zip = new KZip(zipfile);
if(!m_zip->open(IO_ReadOnly))
{
qDebug("Unable to open '%s' for reading.", zipfile.ascii());
return;
}
dir = m_zip->directory();
if(dir == 0)
{
qDebug("Error reading directory contents of file %s", zipfile.ascii());
return;
}
entry = dir->entry(filename);
if(entry == 0 || !entry->isFile())
return;
m_file = static_cast<const KArchiveFile*>(entry);
}
virtual ~ZipFile()
{
if(m_zip)
{
m_zip->close();
delete m_zip;
}
}
QByteArray data()
{
if(m_file)
return m_file->data();
else
{
if(!m_filename.isEmpty())
qDebug("Error reading file %s from zip", m_filename.ascii());
return QByteArray();
}
}
bool exists()
{
return (m_file != 0);
}
private:
KZip* m_zip;
const KArchiveFile* m_file;
QString m_filename;
};
ThemeFile::ThemeFile(const KURL& url)
: m_stream(0)
{
if(url.isValid())
set(url);
}
ThemeFile::~ThemeFile()
{
delete m_stream;
}
bool ThemeFile::open()
{
bool result = false;
if(m_zipTheme)
{
ZipFile zf(m_file, m_theme);
m_ba = zf.data();
if(m_ba.size() > 0)
{
m_stream = new QTextStream(m_ba, IO_ReadOnly);
result = true;
}
}
else
{
m_fl.setName(m_file);
if(m_fl.open(IO_ReadOnly|IO_Translate))
{
m_stream = new QTextStream(&m_fl); // use a text stream
result = true;
}
}
return result;
}
bool ThemeFile::nextLine(LineParser& parser)
{
parser.set("");
if(m_stream)
{
QString result = m_stream->readLine();
if(result.isNull())
return false;
parser.set(result);
return true;
}
return false;
}
bool ThemeFile::close()
{
if(m_stream)
{
delete m_stream;
m_stream = 0;
m_fl.close();
m_ba.resize(0);
return true;
}
return false;
}
bool ThemeFile::isValid() const
{
return (exists() && !m_name.isEmpty() && !m_theme.isEmpty());
}
bool ThemeFile::exists() const
{
QFileInfo file(m_file);
return file.exists();
}
QPixmap ThemeFile::icon() const
{
return QPixmap(readThemeFile(m_icon));
}
bool ThemeFile::set(const KURL &url)
{
if(!url.isLocalFile() && !url.protocol().isEmpty())
{
QDir themeDir(locateLocal("appdata", "themes/", true));
QFileInfo localFile = themeDir.filePath(url.fileName());
if(localFile.exists())
{
if(KMessageBox::questionYesNo(kapp->activeWindow(),
i18n("%1 already exists. Do you want to overwrite it?")
.arg(localFile.filePath()))
== KMessageBox::No)
{
return false;
}
}
if(!KIO::NetAccess::file_copy(url, localFile.filePath(), -1, true,
false, kapp->mainWidget()))
{
return false;
}
m_file = localFile.filePath();
}
else
{
if(url.directory().isEmpty() or url.directory() == "/")
m_file = canonicalFile(QDir::current().filePath(url.fileName()));
else
m_file = canonicalFile(url.path());
if(!exists())
return false;
}
QFileInfo fi(m_file);
m_name = fi.baseName();
m_theme = m_name + ".theme";
m_python = m_name;
m_id = m_name;
if(isZipFile(m_file))
{
m_path = m_file;
m_zipTheme = true;
}
else
{
m_path = fi.dirPath(true) + "/";
m_zipTheme = false;
}
parseXml();
return isValid();
}
void ThemeFile::parseXml()
{
if(!fileExists("maindata.xml"))
return;
QByteArray ba = readThemeFile("maindata.xml");
QDomDocument doc("superkaramba_theme");
doc.setContent(ba);
QDomElement element = doc.documentElement();
QDomNode n = element.firstChild();
while(!n.isNull())
{
QDomElement e = n.toElement();
if(!e.isNull())
{
if(e.tagName() == "name")
m_name = e.text();
if(e.tagName() == "themefile")
m_theme = e.text();
if(e.tagName() == "python_module")
{
m_python = e.text();
if(m_python.right(3).lower() == ".py")
m_python.remove(m_python.length() - 3, 3);
}
if(e.tagName() == "description")
m_description = e.text();
if(e.tagName() == "author")
m_author = e.text();
if(e.tagName() == "author_email")
m_authorEmail = e.text();
if(e.tagName() == "homepage")
m_homepage = e.text();
if(e.tagName() == "icon")
m_icon = e.text();
}
n = n.nextSibling();
}
}
bool ThemeFile::isThemeFile(const QString& filename) const
{
QFileInfo fileInfo(filename);
return fileInfo.isRelative();
}
bool ThemeFile::fileExists(const QString& filename) const
{
if(isThemeFile(filename))
{
if(isZipTheme())
{
ZipFile zf(m_file, filename);
return zf.exists();
}
else
return QFileInfo(path() + "/" + filename).exists();
}
else
return QFileInfo(filename).exists();
}
QByteArray ThemeFile::readThemeFile(const QString& filename) const
{
QByteArray ba;
if(isZipTheme())
{
ZipFile zf(m_file, filename);
ba = zf.data();
}
else
{
QFile file(path() + "/" + filename);
if(file.open(IO_ReadOnly))
{
ba = file.readAll();
file.close();
}
}
return ba;
}
bool ThemeFile::isZipFile(const QString& filename)
{
QFile file(filename);
if(file.open(IO_ReadOnly))
{
unsigned char buf[5];
if(file.readBlock((char*)buf, 4) == 4)
{
if(buf[0] == 'P' && buf[1] == 'K' && buf[2] == 3 && buf[3] == 4)
return true;
}
}
return false;
}
bool ThemeFile::pythonModuleExists() const
{
return (!m_python.isEmpty() && fileExists(m_python + ".py"));
}
QString ThemeFile::canonicalFile(const QString& file)
{
// Get absolute path with NO symlinks
QFileInfo fi(file);
return QDir(fi.dir().canonicalPath()).filePath(fi.fileName());
}
|
handle file with no path better.
|
handle file with no path better.
svn path=/trunk/kdereview/superkaramba/; revision=422017
|
C++
|
lgpl-2.1
|
KDE/superkaramba,KDE/superkaramba,KDE/superkaramba
|
bd8bbb5a9e30724684de3738faa4319a1d17f826
|
src/sdpb/main.cxx
|
src/sdpb/main.cxx
|
//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "SDP_Solver_Parameters.hxx"
#include "Block_Info.hxx"
#include "Timers.hxx"
#include <El.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
Timers
solve(const boost::filesystem::path &sdp_directory,
const boost::filesystem::path &out_file,
const boost::filesystem::path &checkpoint_in,
const boost::filesystem::path &checkpoint_out,
const Block_Info &block_info, const SDP_Solver_Parameters ¶meters);
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &block_timings_filename,
const bool &write_block_timing, const Block_Info &block_info,
const Timers &timers, const bool &debug);
int main(int argc, char **argv)
{
El::Environment env(argc, argv);
int result(0);
try
{
boost::filesystem::path sdp_directory, out_file, checkpoint_in,
checkpoint_out, param_file;
bool write_block_timing(false);
SDP_Solver_Parameters parameters;
po::options_description basic_options("Basic options");
basic_options.add_options()("help,h", "Show this helpful message.")(
"sdpDir,s",
po::value<boost::filesystem::path>(&sdp_directory)->required(),
"Directory containing preprocessed SDP data files.")(
"paramFile,p", po::value<boost::filesystem::path>(¶m_file),
"Any parameter can optionally be set via this file in key=value "
"format. Command line arguments override values in the parameter "
"file.")("outFile,o", po::value<boost::filesystem::path>(&out_file),
"The optimal solution is saved to this file in Mathematica "
"format. Defaults to sdpDir with '.out' extension.")(
"checkpointDir,c", po::value<boost::filesystem::path>(&checkpoint_out),
"Checkpoints are saved to this directory every checkpointInterval. "
"Defaults to sdpDir with '.ck' extension.")(
"initialCheckpointDir,i",
po::value<boost::filesystem::path>(&checkpoint_in),
"The initial checkpoint directory to load. Defaults to "
"checkpointDir.")(
"debug", po::value<bool>(¶meters.debug)->default_value(false),
"Write out debugging output.")(
"writeBlockTiming",
po::bool_switch(&write_block_timing)->default_value(false),
"Write per-block timing info for use when distributing "
"blocks over MPI.");
// We set default parameters using El::BigFloat("1e-10",10)
// rather than a straight double precision 1e-10 so that results
// are more reproducible at high precision. Using double
// precision defaults results in differences of about 1e-15 in
// primalObjective after one step.
po::options_description solver_params_options("Solver parameters");
solver_params_options.add_options()(
"precision", po::value<int>(¶meters.precision)->default_value(400),
"The precision, in the number of bits, for numbers in the computation. "
" This should be less than or equal to the precision used when "
"preprocessing the XML input files with 'pvm2sdp'. GMP will round "
"this up to a multiple of 32 or 64, depending on the system.")(
"checkpointInterval",
po::value<int>(¶meters.checkpoint_interval)->default_value(3600),
"Save checkpoints to checkpointDir every checkpointInterval "
"seconds.")(
"noFinalCheckpoint",
po::bool_switch(¶meters.no_final_checkpoint)->default_value(false),
"Don't save a final checkpoint after terminating (useful when "
"debugging).")(
"findPrimalFeasible",
po::bool_switch(¶meters.find_primal_feasible)->default_value(false),
"Terminate once a primal feasible solution is found.")(
"findDualFeasible",
po::bool_switch(¶meters.find_dual_feasible)->default_value(false),
"Terminate once a dual feasible solution is found.")(
"detectPrimalFeasibleJump",
po::bool_switch(¶meters.detect_primal_feasible_jump)
->default_value(false),
"Terminate if a primal-step of 1 is taken. This often indicates that "
"a "
"primal feasible solution would be found if the precision were high "
"enough. Try increasing either primalErrorThreshold or precision "
"and run from the latest checkpoint.")(
"detectDualFeasibleJump",
po::bool_switch(¶meters.detect_dual_feasible_jump)
->default_value(false),
"Terminate if a dual-step of 1 is taken. This often indicates that a "
"dual feasible solution would be found if the precision were high "
"enough. Try increasing either dualErrorThreshold or precision "
"and run from the latest checkpoint.")(
"maxIterations",
po::value<int>(¶meters.max_iterations)->default_value(500),
"Maximum number of iterations to run the solver.")(
"maxRuntime",
po::value<int>(¶meters.max_runtime)->default_value(86400),
"Maximum amount of time to run the solver in seconds.")(
"procsPerNode", po::value<int>(¶meters.procs_per_node)->required(),
"This option is **required**.\n\n"
"The number of processes that can run on a node. When running on "
"more "
"than one node, the load balancer needs to know how many processes "
"are assigned to each node. On a laptop or desktop, this would be "
"the number of physical cores on your machine, not including "
"hyperthreaded cores. For current laptops (2018), this is probably "
"2 or 4.\n\n"
"If you are using the Slurm workload manager, this should be set to "
"'$SLURM_NTASKS_PER_NODE'.")(
"dualityGapThreshold",
po::value<El::BigFloat>(¶meters.duality_gap_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for duality gap (roughly the difference in primal and dual "
"objective) at which the solution is considered "
"optimal. Corresponds to SDPA's epsilonStar.")(
"primalErrorThreshold",
po::value<El::BigFloat>(¶meters.primal_error_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for feasibility of the primal problem. Corresponds to "
"SDPA's epsilonBar.")(
"dualErrorThreshold",
po::value<El::BigFloat>(¶meters.dual_error_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for feasibility of the dual problem. Corresponds to SDPA's "
"epsilonBar.")(
"initialMatrixScalePrimal",
po::value<El::BigFloat>(¶meters.initial_matrix_scale_primal)
->default_value(El::BigFloat("1e20", 10)),
"The primal matrix X begins at initialMatrixScalePrimal times the "
"identity matrix. Corresponds to SDPA's lambdaStar.")(
"initialMatrixScaleDual",
po::value<El::BigFloat>(¶meters.initial_matrix_scale_dual)
->default_value(El::BigFloat("1e20", 10)),
"The dual matrix Y begins at initialMatrixScaleDual times the "
"identity matrix. Corresponds to SDPA's lambdaStar.")(
"feasibleCenteringParameter",
po::value<El::BigFloat>(¶meters.feasible_centering_parameter)
->default_value(El::BigFloat("0.1", 10)),
"Shrink the complementarity X Y by this factor when the primal and "
"dual "
"problems are feasible. Corresponds to SDPA's betaStar.")(
"infeasibleCenteringParameter",
po::value<El::BigFloat>(¶meters.infeasible_centering_parameter)
->default_value(El::BigFloat("0.3", 10)),
"Shrink the complementarity X Y by this factor when either the primal "
"or dual problems are infeasible. Corresponds to SDPA's betaBar.")(
"stepLengthReduction",
po::value<El::BigFloat>(¶meters.step_length_reduction)
->default_value(El::BigFloat("0.7", 10)),
"Shrink each newton step by this factor (smaller means slower, more "
"stable convergence). Corresponds to SDPA's gammaStar.")(
"maxComplementarity",
po::value<El::BigFloat>(¶meters.max_complementarity)
->default_value(El::BigFloat("1e100", 10)),
"Terminate if the complementarity mu = Tr(X Y)/dim(X) "
"exceeds this value.");
po::options_description cmd_line_options;
cmd_line_options.add(basic_options).add(solver_params_options);
po::variables_map variables_map;
try
{
po::store(po::parse_command_line(argc, argv, cmd_line_options),
variables_map);
if(variables_map.count("help"))
{
std::cout << cmd_line_options << '\n';
return 0;
}
if(variables_map.count("paramFile"))
{
param_file
= variables_map["paramFile"].as<boost::filesystem::path>();
std::ifstream ifs(param_file.string().c_str());
if(!ifs.good())
{
throw std::runtime_error("Could not open '"
+ param_file.string() + "'");
}
po::store(po::parse_config_file(ifs, solver_params_options),
variables_map);
}
po::notify(variables_map);
if(!boost::filesystem::exists(sdp_directory))
{
throw std::runtime_error("sdp directory '"
+ sdp_directory.string()
+ "' does not exist");
}
if(!boost::filesystem::is_directory(sdp_directory))
{
throw std::runtime_error("sdp directory '"
+ sdp_directory.string()
+ "' is not a directory");
}
if(!variables_map.count("outFile"))
{
out_file = sdp_directory;
if(out_file.filename() == ".")
{
out_file = out_file.parent_path();
}
out_file.replace_extension("out");
}
if(!variables_map.count("checkpointDir"))
{
checkpoint_out = sdp_directory;
if(checkpoint_out.filename() == ".")
{
checkpoint_out = checkpoint_out.parent_path();
}
checkpoint_out.replace_extension("ck");
}
if(!variables_map.count("initialCheckpointDir"))
{
checkpoint_in = checkpoint_out;
}
if(El::mpi::Rank() == 0)
{
std::ofstream ofs(out_file.string().c_str());
if(!ofs)
{
std::cerr << "Cannot write to outFile." << '\n';
return 1;
}
}
}
catch(po::error &e)
{
std::cerr << "ERROR: " << e.what() << '\n';
std::cerr << cmd_line_options << '\n';
return 1;
}
// Set the default precision of all Real numbers to that specified
// by the 'precision' parameter.
mpf_set_default_prec(parameters.precision);
El::gmp::SetPrecision(parameters.precision);
El::mpfr::SetPrecision(parameters.precision);
Block_Info block_info(sdp_directory, parameters.procs_per_node);
Timers timers(solve(sdp_directory, out_file, checkpoint_in,
checkpoint_out, block_info, parameters));
write_timing(out_file, sdp_directory, write_block_timing, block_info,
timers, parameters.debug);
}
catch(std::exception &e)
{
El::ReportException(e);
result = 1;
}
return result;
}
|
//=======================================================================
// Copyright 2014-2015 David Simmons-Duffin.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "SDP_Solver_Parameters.hxx"
#include "Block_Info.hxx"
#include "Timers.hxx"
#include <El.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
Timers
solve(const boost::filesystem::path &sdp_directory,
const boost::filesystem::path &out_file,
const boost::filesystem::path &checkpoint_in,
const boost::filesystem::path &checkpoint_out,
const Block_Info &block_info, const SDP_Solver_Parameters ¶meters);
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &block_timings_filename,
const bool &write_block_timing, const Block_Info &block_info,
const Timers &timers, const bool &debug);
int main(int argc, char **argv)
{
El::Environment env(argc, argv);
try
{
boost::filesystem::path sdp_directory, out_file, checkpoint_in,
checkpoint_out, param_file;
bool write_block_timing(false);
SDP_Solver_Parameters parameters;
po::options_description basic_options("Basic options");
basic_options.add_options()("help,h", "Show this helpful message.")(
"sdpDir,s",
po::value<boost::filesystem::path>(&sdp_directory)->required(),
"Directory containing preprocessed SDP data files.")(
"paramFile,p", po::value<boost::filesystem::path>(¶m_file),
"Any parameter can optionally be set via this file in key=value "
"format. Command line arguments override values in the parameter "
"file.")("outFile,o", po::value<boost::filesystem::path>(&out_file),
"The optimal solution is saved to this file in Mathematica "
"format. Defaults to sdpDir with '.out' extension.")(
"checkpointDir,c", po::value<boost::filesystem::path>(&checkpoint_out),
"Checkpoints are saved to this directory every checkpointInterval. "
"Defaults to sdpDir with '.ck' extension.")(
"initialCheckpointDir,i",
po::value<boost::filesystem::path>(&checkpoint_in),
"The initial checkpoint directory to load. Defaults to "
"checkpointDir.")(
"debug", po::value<bool>(¶meters.debug)->default_value(false),
"Write out debugging output.")(
"writeBlockTiming",
po::bool_switch(&write_block_timing)->default_value(false),
"Write per-block timing info for use when distributing "
"blocks over MPI.");
// We set default parameters using El::BigFloat("1e-10",10)
// rather than a straight double precision 1e-10 so that results
// are more reproducible at high precision. Using double
// precision defaults results in differences of about 1e-15 in
// primalObjective after one step.
po::options_description solver_params_options("Solver parameters");
solver_params_options.add_options()(
"precision", po::value<int>(¶meters.precision)->default_value(400),
"The precision, in the number of bits, for numbers in the "
"computation. "
" This should be less than or equal to the precision used when "
"preprocessing the XML input files with 'pvm2sdp'. GMP will round "
"this up to a multiple of 32 or 64, depending on the system.")(
"checkpointInterval",
po::value<int>(¶meters.checkpoint_interval)->default_value(3600),
"Save checkpoints to checkpointDir every checkpointInterval "
"seconds.")(
"noFinalCheckpoint",
po::bool_switch(¶meters.no_final_checkpoint)->default_value(false),
"Don't save a final checkpoint after terminating (useful when "
"debugging).")(
"findPrimalFeasible",
po::bool_switch(¶meters.find_primal_feasible)->default_value(false),
"Terminate once a primal feasible solution is found.")(
"findDualFeasible",
po::bool_switch(¶meters.find_dual_feasible)->default_value(false),
"Terminate once a dual feasible solution is found.")(
"detectPrimalFeasibleJump",
po::bool_switch(¶meters.detect_primal_feasible_jump)
->default_value(false),
"Terminate if a primal-step of 1 is taken. This often indicates that "
"a "
"primal feasible solution would be found if the precision were high "
"enough. Try increasing either primalErrorThreshold or precision "
"and run from the latest checkpoint.")(
"detectDualFeasibleJump",
po::bool_switch(¶meters.detect_dual_feasible_jump)
->default_value(false),
"Terminate if a dual-step of 1 is taken. This often indicates that a "
"dual feasible solution would be found if the precision were high "
"enough. Try increasing either dualErrorThreshold or precision "
"and run from the latest checkpoint.")(
"maxIterations",
po::value<int>(¶meters.max_iterations)->default_value(500),
"Maximum number of iterations to run the solver.")(
"maxRuntime",
po::value<int>(¶meters.max_runtime)->default_value(86400),
"Maximum amount of time to run the solver in seconds.")(
"procsPerNode", po::value<int>(¶meters.procs_per_node)->required(),
"This option is **required**.\n\n"
"The number of processes that can run on a node. When running on "
"more "
"than one node, the load balancer needs to know how many processes "
"are assigned to each node. On a laptop or desktop, this would be "
"the number of physical cores on your machine, not including "
"hyperthreaded cores. For current laptops (2018), this is probably "
"2 or 4.\n\n"
"If you are using the Slurm workload manager, this should be set to "
"'$SLURM_NTASKS_PER_NODE'.")(
"dualityGapThreshold",
po::value<El::BigFloat>(¶meters.duality_gap_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for duality gap (roughly the difference in primal and dual "
"objective) at which the solution is considered "
"optimal. Corresponds to SDPA's epsilonStar.")(
"primalErrorThreshold",
po::value<El::BigFloat>(¶meters.primal_error_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for feasibility of the primal problem. Corresponds to "
"SDPA's epsilonBar.")(
"dualErrorThreshold",
po::value<El::BigFloat>(¶meters.dual_error_threshold)
->default_value(El::BigFloat("1e-30", 10)),
"Threshold for feasibility of the dual problem. Corresponds to SDPA's "
"epsilonBar.")(
"initialMatrixScalePrimal",
po::value<El::BigFloat>(¶meters.initial_matrix_scale_primal)
->default_value(El::BigFloat("1e20", 10)),
"The primal matrix X begins at initialMatrixScalePrimal times the "
"identity matrix. Corresponds to SDPA's lambdaStar.")(
"initialMatrixScaleDual",
po::value<El::BigFloat>(¶meters.initial_matrix_scale_dual)
->default_value(El::BigFloat("1e20", 10)),
"The dual matrix Y begins at initialMatrixScaleDual times the "
"identity matrix. Corresponds to SDPA's lambdaStar.")(
"feasibleCenteringParameter",
po::value<El::BigFloat>(¶meters.feasible_centering_parameter)
->default_value(El::BigFloat("0.1", 10)),
"Shrink the complementarity X Y by this factor when the primal and "
"dual "
"problems are feasible. Corresponds to SDPA's betaStar.")(
"infeasibleCenteringParameter",
po::value<El::BigFloat>(¶meters.infeasible_centering_parameter)
->default_value(El::BigFloat("0.3", 10)),
"Shrink the complementarity X Y by this factor when either the primal "
"or dual problems are infeasible. Corresponds to SDPA's betaBar.")(
"stepLengthReduction",
po::value<El::BigFloat>(¶meters.step_length_reduction)
->default_value(El::BigFloat("0.7", 10)),
"Shrink each newton step by this factor (smaller means slower, more "
"stable convergence). Corresponds to SDPA's gammaStar.")(
"maxComplementarity",
po::value<El::BigFloat>(¶meters.max_complementarity)
->default_value(El::BigFloat("1e100", 10)),
"Terminate if the complementarity mu = Tr(X Y)/dim(X) "
"exceeds this value.");
po::options_description cmd_line_options;
cmd_line_options.add(basic_options).add(solver_params_options);
po::variables_map variables_map;
try
{
po::store(po::parse_command_line(argc, argv, cmd_line_options),
variables_map);
if(variables_map.count("help"))
{
std::cout << cmd_line_options << '\n';
return 0;
}
if(variables_map.count("paramFile"))
{
param_file
= variables_map["paramFile"].as<boost::filesystem::path>();
std::ifstream ifs(param_file.string().c_str());
if(!ifs.good())
{
throw std::runtime_error("Could not open '"
+ param_file.string() + "'");
}
po::store(po::parse_config_file(ifs, solver_params_options),
variables_map);
}
po::notify(variables_map);
if(!boost::filesystem::exists(sdp_directory))
{
throw std::runtime_error("sdp directory '"
+ sdp_directory.string()
+ "' does not exist");
}
if(!boost::filesystem::is_directory(sdp_directory))
{
throw std::runtime_error("sdp directory '"
+ sdp_directory.string()
+ "' is not a directory");
}
if(!variables_map.count("outFile"))
{
out_file = sdp_directory;
if(out_file.filename() == ".")
{
out_file = out_file.parent_path();
}
out_file.replace_extension("out");
}
if(!variables_map.count("checkpointDir"))
{
checkpoint_out = sdp_directory;
if(checkpoint_out.filename() == ".")
{
checkpoint_out = checkpoint_out.parent_path();
}
checkpoint_out.replace_extension("ck");
}
if(!variables_map.count("initialCheckpointDir"))
{
checkpoint_in = checkpoint_out;
}
if(El::mpi::Rank() == 0)
{
std::ofstream ofs(out_file.string().c_str());
if(!ofs)
{
std::cerr << "Cannot write to outFile." << '\n';
return 1;
}
}
}
catch(po::error &e)
{
std::cerr << "ERROR: " << e.what() << '\n';
std::cerr << cmd_line_options << '\n';
return 1;
}
// Set the default precision of all Real numbers to that specified
// by the 'precision' parameter.
mpf_set_default_prec(parameters.precision);
El::gmp::SetPrecision(parameters.precision);
El::mpfr::SetPrecision(parameters.precision);
Block_Info block_info(sdp_directory, parameters.procs_per_node);
Timers timers(solve(sdp_directory, out_file, checkpoint_in,
checkpoint_out, block_info, parameters));
write_timing(out_file, sdp_directory, write_block_timing, block_info,
timers, parameters.debug);
}
catch(std::exception &e)
{
El::ReportException(e);
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
catch(...)
{
El::mpi::Abort(El::mpi::COMM_WORLD, 1);
}
}
|
Abort immediately when there is an exception.
|
Abort immediately when there is an exception.
|
C++
|
mit
|
davidsd/sdpb,davidsd/sdpb,davidsd/sdpb
|
3d939dceeb78195e3ba818641a4b9285c4b07493
|
Project2-CoinChange/src/main.cpp
|
Project2-CoinChange/src/main.cpp
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/filesystem.hpp>
#include "../include/dynProgCoin.h"
#include "../include/changegreedy.h"
#include "../include/changeslow.h"
#include "../include/Helper/fileUtils.h"
void PrintHelp()
{
std::cout << "CoinCount 1.0; Copyright (C) 2015 Jen, Dale, Nathan" << std::endl;
std::cout << "Usage: CoinCount [file]" << std::endl;
std::cout << "-h --help display this help" << std::endl;
}
int main(int argc, char* argv[])
{
std::string path;
if(argc != 2)
{
std::cout << "Error! This program takes exactly 1 argument. Printing usage:" << std::endl << std::endl;
PrintHelp();
exit(1);
}
else
{
if(std::string(argv[1]) == "-h" || std::string(argv[1]) == "--help")
{
PrintHelp();
exit(0);
}
else
path = std::string(argv[1]);
}
boost::filesystem::path boostPath(path);
boost::filesystem::path boostOutPath =
boostPath.parent_path() / boost::filesystem::path(boostPath.stem() + "change" + boostPath.extension());
if(!boost::filesystem::exists(boostPath))
{
std::cout << "The file at: " << path << " could not be found." << std::endl;
exit(1);
}
std::ifstream inFile;
inFile.open(path);
if(!inFile.is_open())
{
std::cout << "The file at: " << path << " could not be opened." << std::endl;
inFile.close();
exit(1);
}
//Grab the info we need from the file
std::vector<std::vector<int>> coinLists;
std::vector<int> coinTotals;
Helper::processCoinFile(inFile, coinLists, coinTotals);
//Give back the file handle to the OS
inFile.close();
std::ofstream outStream;
outStream.open(boostOutPath.native_file_string());
if(!outStream.is_open())
{
std::cout << "Cannot open " << boostOutPath << " for writing. Check the permissions of the directory." << std::endl;
outStream.close();
exit(1);
}
outStream << "Results from the brute-force Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = changeslow(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream << "Results from the greedy Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = greedyCoin(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream << "Results from the Dynamic Programming Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = dynProgCoin(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream.close();
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/filesystem.hpp>
#include "../include/dynProgCoin.h"
#include "../include/changegreedy.h"
#include "../include/changeslow.h"
#include "../include/Helper/fileUtils.h"
void PrintHelp()
{
std::cout << "CoinCount 1.0; Copyright (C) 2015 Jen, Dale, Nathan" << std::endl;
std::cout << "Usage: CoinCount [file]" << std::endl;
std::cout << "-h --help display this help" << std::endl;
}
int main(int argc, char* argv[])
{
std::string path;
if(argc != 2)
{
std::cout << "Error! This program takes exactly 1 argument. Printing usage:" << std::endl << std::endl;
PrintHelp();
exit(1);
}
else
{
if(std::string(argv[1]) == "-h" || std::string(argv[1]) == "--help")
{
PrintHelp();
exit(0);
}
else
path = std::string(argv[1]);
}
boost::filesystem::path boostPath(path);
boost::filesystem::path boostOutPath =
boostPath.parent_path() / boost::filesystem::path(boostPath.stem().append("change").append(boostPath.extension()));
if(!boost::filesystem::exists(boostPath))
{
std::cout << "The file at: " << path << " could not be found." << std::endl;
exit(1);
}
std::ifstream inFile;
inFile.open(path);
if(!inFile.is_open())
{
std::cout << "The file at: " << path << " could not be opened." << std::endl;
inFile.close();
exit(1);
}
//Grab the info we need from the file
std::vector<std::vector<int>> coinLists;
std::vector<int> coinTotals;
Helper::processCoinFile(inFile, coinLists, coinTotals);
//Give back the file handle to the OS
inFile.close();
std::ofstream outStream;
outStream.open(boostOutPath.native_file_string());
if(!outStream.is_open())
{
std::cout << "Cannot open " << boostOutPath << " for writing. Check the permissions of the directory." << std::endl;
outStream.close();
exit(1);
}
outStream << "Results from the brute-force Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = changeslow(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream << "Results from the greedy Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = greedyCoin(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream << "Results from the Dynamic Programming Solution\n";
for(uint i = 0; i < coinLists.size(); i++)
{
std::vector<int> returnCoinCount;
int total = dynProgCoin(coinLists.at(i), coinTotals.at(i), returnCoinCount);
Helper::WriteResultsToFile(outStream, returnCoinCount, total);
}
outStream.close();
}
|
Append to path instead of using + operator
|
Append to path instead of using + operator
|
C++
|
mit
|
nathansoz/cs325-algorithms
|
58257612265e77de8b4988f70c25dec7124719f3
|
src/core/hooks.cc
|
src/core/hooks.cc
|
#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>
namespace ccspec {
namespace core {
void before(std::string entity, Hook hook) {
ExampleGroup* parent_group = groups_being_defined.top();
if (entity == "each")
parent_group->addBeforeEachHook(hook);
else
throw "no such before hook type";
}
} // namespace core
} // namespace ccspec
|
#include <string>
#include <ccspec/core/hooks.h>
#include <ccspec/core/example_group.h>
namespace ccspec {
namespace core {
void before(std::string entity, Hook hook) {
ExampleGroup* parent_group = groups_being_defined.top();
if (entity == "each" || entity == "example")
parent_group->addBeforeEachHook(hook);
else
throw "no such before hook type";
}
} // namespace core
} // namespace ccspec
|
Add "each" alias that's new in RSpec 3
|
Add "each" alias that's new in RSpec 3
|
C++
|
mit
|
tempbottle/ccspec,tempbottle/ccspec,zhangsu/ccspec,tempbottle/ccspec,zhangsu/ccspec,zhangsu/ccspec,michaelachrisco/ccspec,michaelachrisco/ccspec,michaelachrisco/ccspec
|
4a7d8cbf0c4fa6ae056fbfef929f65e6d2eee1ab
|
src/stopwatch.cxx
|
src/stopwatch.cxx
|
/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stopwatch.hxx"
#include "AllocatorPtr.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/StaticSocketAddress.hxx"
#include "net/ToString.hxx"
#include "io/Logger.hxx"
#include "util/WritableBuffer.hxx"
#include <boost/container/static_vector.hpp>
#include <chrono>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <sys/resource.h>
enum {
STOPWATCH_VERBOSE = 3,
};
struct StopwatchEvent {
const char *name;
std::chrono::steady_clock::time_point time;
explicit StopwatchEvent(const char *_name) noexcept
:name(_name), time(std::chrono::steady_clock::now()) {}
};
class Stopwatch {
AllocatorPtr alloc;
const char *const name;
boost::container::static_vector<StopwatchEvent, 16> events;
/**
* Our own resource usage, measured when the stopwatch was
* started.
*/
struct rusage self;
public:
Stopwatch(AllocatorPtr _alloc, const char *_name)
:alloc(_alloc), name(_name) {
events.emplace_back(name);
getrusage(RUSAGE_SELF, &self);
}
~Stopwatch() noexcept {
Dump();
}
void RecordEvent(const char *name) noexcept;
void Dump() const noexcept;
};
static bool stopwatch_enabled;
void
stopwatch_enable()
{
assert(!stopwatch_enabled);
stopwatch_enabled = true;
}
bool
stopwatch_is_enabled()
{
return stopwatch_enabled && CheckLogLevel(STOPWATCH_VERBOSE);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, const char *name, const char *suffix)
{
if (!stopwatch_is_enabled())
return nullptr;
if (suffix == nullptr)
name = alloc.Dup(name);
else
name = alloc.Concat(name, suffix);
constexpr size_t MAX_NAME = 96;
if (strlen(name) > MAX_NAME)
name = alloc.DupZ({name, MAX_NAME});
return alloc.New<Stopwatch>(alloc, name);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, SocketAddress address, const char *suffix)
{
char buffer[1024];
if (!stopwatch_is_enabled())
return nullptr;
const char *name = ToString(buffer, sizeof(buffer), address, "unknown");
return stopwatch_new(alloc, name, suffix);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, SocketDescriptor fd, const char *suffix)
{
if (!stopwatch_is_enabled())
return nullptr;
const auto address = fd.GetPeerAddress();
return address.IsDefined()
? stopwatch_new(alloc, address, suffix)
: stopwatch_new(alloc, "unknown", suffix);
}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
const char *name, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, name, suffix)) {}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
SocketAddress address, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, address, suffix)) {}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
SocketDescriptor fd, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, fd, suffix)) {}
void
StopwatchPtr::Destruct(Stopwatch &stopwatch) noexcept
{
stopwatch.~Stopwatch();
}
inline void
Stopwatch::RecordEvent(const char *event_name) noexcept
{
if (events.size() >= events.capacity())
/* array is full, do not record any more events */
return;
events.emplace_back(event_name);
}
void
StopwatchPtr::RecordEvent(const char *name) const noexcept
{
if (stopwatch != nullptr)
stopwatch->RecordEvent(name);
}
static constexpr long
ToLongMs(std::chrono::steady_clock::duration d)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
}
static long
timeval_diff_ms(const struct timeval *a, const struct timeval *b)
{
return (a->tv_sec - b->tv_sec) * 1000 +
(a->tv_usec - b->tv_usec) / 1000;
}
template<typename... Args>
static void
AppendFormat(WritableBuffer<char> &buffer, const char *fmt, Args&&... args)
{
int r = snprintf(buffer.data, buffer.size, fmt, args...);
if (r > 0)
buffer.skip_front(std::min(size_t(r), buffer.size - 1));
}
inline void
Stopwatch::Dump() const noexcept
{
assert(!events.empty());
if (events.size() < 2)
/* nothing was recorded (except for the initial event) */
return;
char domain[128];
snprintf(domain, sizeof(domain), "stopwatch %s", name);
char message[1024];
WritableBuffer<char> b(message, sizeof(message));
for (const auto &i : events)
AppendFormat(b, " %s=%ldms",
i.name,
ToLongMs(i.time - events.front().time));
struct rusage new_self;
getrusage(RUSAGE_SELF, &new_self);
AppendFormat(b, " (beng-proxy=%ld+%ldms)",
timeval_diff_ms(&new_self.ru_utime, &self.ru_utime),
timeval_diff_ms(&new_self.ru_stime, &self.ru_stime));
LogConcat(STOPWATCH_VERBOSE, domain, message);
}
|
/*
* Copyright 2007-2019 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stopwatch.hxx"
#include "AllocatorPtr.hxx"
#include "net/SocketDescriptor.hxx"
#include "net/StaticSocketAddress.hxx"
#include "net/ToString.hxx"
#include "io/Logger.hxx"
#include "util/LeakDetector.hxx"
#include "util/WritableBuffer.hxx"
#include <boost/container/static_vector.hpp>
#include <chrono>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <sys/resource.h>
enum {
STOPWATCH_VERBOSE = 3,
};
struct StopwatchEvent {
const char *name;
std::chrono::steady_clock::time_point time;
explicit StopwatchEvent(const char *_name) noexcept
:name(_name), time(std::chrono::steady_clock::now()) {}
};
class Stopwatch final : LeakDetector {
AllocatorPtr alloc;
const char *const name;
boost::container::static_vector<StopwatchEvent, 16> events;
/**
* Our own resource usage, measured when the stopwatch was
* started.
*/
struct rusage self;
public:
Stopwatch(AllocatorPtr _alloc, const char *_name)
:alloc(_alloc), name(_name) {
events.emplace_back(name);
getrusage(RUSAGE_SELF, &self);
}
~Stopwatch() noexcept {
Dump();
}
void RecordEvent(const char *name) noexcept;
void Dump() const noexcept;
};
static bool stopwatch_enabled;
void
stopwatch_enable()
{
assert(!stopwatch_enabled);
stopwatch_enabled = true;
}
bool
stopwatch_is_enabled()
{
return stopwatch_enabled && CheckLogLevel(STOPWATCH_VERBOSE);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, const char *name, const char *suffix)
{
if (!stopwatch_is_enabled())
return nullptr;
if (suffix == nullptr)
name = alloc.Dup(name);
else
name = alloc.Concat(name, suffix);
constexpr size_t MAX_NAME = 96;
if (strlen(name) > MAX_NAME)
name = alloc.DupZ({name, MAX_NAME});
return alloc.New<Stopwatch>(alloc, name);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, SocketAddress address, const char *suffix)
{
char buffer[1024];
if (!stopwatch_is_enabled())
return nullptr;
const char *name = ToString(buffer, sizeof(buffer), address, "unknown");
return stopwatch_new(alloc, name, suffix);
}
static Stopwatch *
stopwatch_new(AllocatorPtr alloc, SocketDescriptor fd, const char *suffix)
{
if (!stopwatch_is_enabled())
return nullptr;
const auto address = fd.GetPeerAddress();
return address.IsDefined()
? stopwatch_new(alloc, address, suffix)
: stopwatch_new(alloc, "unknown", suffix);
}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
const char *name, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, name, suffix)) {}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
SocketAddress address, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, address, suffix)) {}
StopwatchPtr::StopwatchPtr(AllocatorPtr alloc,
SocketDescriptor fd, const char *suffix) noexcept
:stopwatch(stopwatch_new(alloc, fd, suffix)) {}
void
StopwatchPtr::Destruct(Stopwatch &stopwatch) noexcept
{
stopwatch.~Stopwatch();
}
inline void
Stopwatch::RecordEvent(const char *event_name) noexcept
{
if (events.size() >= events.capacity())
/* array is full, do not record any more events */
return;
events.emplace_back(event_name);
}
void
StopwatchPtr::RecordEvent(const char *name) const noexcept
{
if (stopwatch != nullptr)
stopwatch->RecordEvent(name);
}
static constexpr long
ToLongMs(std::chrono::steady_clock::duration d)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
}
static long
timeval_diff_ms(const struct timeval *a, const struct timeval *b)
{
return (a->tv_sec - b->tv_sec) * 1000 +
(a->tv_usec - b->tv_usec) / 1000;
}
template<typename... Args>
static void
AppendFormat(WritableBuffer<char> &buffer, const char *fmt, Args&&... args)
{
int r = snprintf(buffer.data, buffer.size, fmt, args...);
if (r > 0)
buffer.skip_front(std::min(size_t(r), buffer.size - 1));
}
inline void
Stopwatch::Dump() const noexcept
{
assert(!events.empty());
if (events.size() < 2)
/* nothing was recorded (except for the initial event) */
return;
char domain[128];
snprintf(domain, sizeof(domain), "stopwatch %s", name);
char message[1024];
WritableBuffer<char> b(message, sizeof(message));
for (const auto &i : events)
AppendFormat(b, " %s=%ldms",
i.name,
ToLongMs(i.time - events.front().time));
struct rusage new_self;
getrusage(RUSAGE_SELF, &new_self);
AppendFormat(b, " (beng-proxy=%ld+%ldms)",
timeval_diff_ms(&new_self.ru_utime, &self.ru_utime),
timeval_diff_ms(&new_self.ru_stime, &self.ru_stime));
LogConcat(STOPWATCH_VERBOSE, domain, message);
}
|
use class LeakDetector
|
stopwatch: use class LeakDetector
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
ace7b92ca27c6a1da74d1d2df598106ea27cd132
|
Pcap++/src/PcapLiveDeviceList.cpp
|
Pcap++/src/PcapLiveDeviceList.cpp
|
#define LOG_MODULE PcapLogModuleLiveDevice
#include <IpUtils.h>
#include <PcapLiveDeviceList.h>
#include <Logger.h>
#include <SystemUtils.h>
#include <string.h>
#include <sstream>
#include <algorithm>
#ifdef WIN32
#include <ws2tcpip.h>
#include <iphlpapi.h>
#elif MAC_OS_X
#include <systemconfiguration/scdynamicstore.h>
#endif
namespace pcpp
{
PcapLiveDeviceList::PcapLiveDeviceList()
{
pcap_if_t* interfaceList;
char errbuf[PCAP_ERRBUF_SIZE];
int err = pcap_findalldevs(&interfaceList, errbuf);
if (err < 0)
{
LOG_ERROR("Error searching for devices: %s", errbuf);
}
pcap_if_t* currInterface = interfaceList;
while (currInterface != NULL)
{
#ifdef WIN32
PcapLiveDevice* dev = new WinPcapLiveDevice(currInterface, true, true, true);
#else //LINUX, MAC_OSX
PcapLiveDevice* dev = new PcapLiveDevice(currInterface, true, true, true);
#endif
currInterface = currInterface->next;
m_LiveDeviceList.insert(m_LiveDeviceList.end(), dev);
}
setDnsServers();
LOG_DEBUG("Freeing live device data");
pcap_freealldevs(interfaceList);
}
PcapLiveDeviceList::~PcapLiveDeviceList()
{
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
delete (*devIter);
}
}
void PcapLiveDeviceList::setDnsServers()
{
#ifdef WIN32
FIXED_INFO * fixedInfo;
ULONG ulOutBufLen;
DWORD dwRetVal;
IP_ADDR_STRING * pIPAddr;
uint8_t buf1[sizeof(FIXED_INFO)];
fixedInfo = (FIXED_INFO *) buf1;
ulOutBufLen = sizeof( FIXED_INFO );
dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen );
uint8_t buf2[ulOutBufLen];
if(ERROR_BUFFER_OVERFLOW == dwRetVal)
{
fixedInfo = (FIXED_INFO *)buf2;
}
if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0)
LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal);
else
{
m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String));
int i = 1;
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String );
pIPAddr = fixedInfo->DnsServerList.Next;
while ( pIPAddr )
{
m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String));
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String);
pIPAddr = pIPAddr -> Next;
}
}
#elif LINUX
std::string command = "nmcli dev list | grep IP4.DNS";
std::string dnsServersInfo = executeShellCommand(command);
if (dnsServersInfo == "")
{
LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output");
return;
}
std::istringstream stream(dnsServersInfo);
std::string line;
int i = 1;
while(std::getline(stream, line))
{
std::istringstream lineStream(line);
std::string headline;
std::string dnsIP;
lineStream >> headline;
lineStream >> dnsIP;
IPv4Address dnsIPAddr(dnsIP);
if (!dnsIPAddr.isValid())
continue;
if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end())
{
m_DnsServers.push_back(dnsIPAddr);
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str());
}
}
#elif MAC_OS_X
SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL);
if (dynRef == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore");
return;
}
CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS"));
if (dnsDict == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary");
CFRelease(dynRef);
return;
}
CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses"));
if (serverAddresses == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: server addresses array is null");
CFRelease(dynRef);
CFRelease(dnsDict);
return;
}
CFIndex count = CFArrayGetCount(serverAddresses);
for (CFIndex i = 0; i < count; i++)
{
CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i);
if (serverAddress == NULL)
continue;
uint8_t buf[20];
char* serverAddressCString = (char*)buf;
CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8);
m_DnsServers.push_back(IPv4Address(serverAddressCString));
LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString);
}
CFRelease(dynRef);
CFRelease(dnsDict);
#endif
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPAddress* ipAddr)
{
if (ipAddr->getType() == IPAddress::IPv4AddressType)
{
IPv4Address* ip4Addr = static_cast<IPv4Address*>(ipAddr);
return getPcapLiveDeviceByIp(*ip4Addr);
}
else //IPAddress::IPv6AddressType
{
IPv6Address* ip6Addr = static_cast<IPv6Address*>(ipAddr);
return getPcapLiveDeviceByIp(*ip6Addr);
}
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPv4Address ipAddr)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
LOG_DEBUG("Searching device '%s'. Searching all addresses...", (*devIter)->m_Name);
for(std::vector<pcap_addr_t>::iterator addrIter = (*devIter)->m_Addresses.begin(); addrIter != (*devIter)->m_Addresses.end(); addrIter++)
{
if (LoggerPP::getInstance().isDebugEnabled(PcapLogModuleLiveDevice) && addrIter->addr != NULL)
{
char addrAsString[INET6_ADDRSTRLEN];
sockaddr2string(addrIter->addr, addrAsString);
LOG_DEBUG("Searching address %s", addrAsString);
}
in_addr* currAddr = sockaddr2in_addr(addrIter->addr);
if (currAddr == NULL)
{
LOG_DEBUG("Address is NULL");
continue;
}
if (currAddr->s_addr == ipAddr.toInAddr()->s_addr)
{
LOG_DEBUG("Found matched address!");
return (*devIter);
}
}
}
return NULL;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPv6Address ip6Addr)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
LOG_DEBUG("Searching device '%s'. Searching all addresses...", (*devIter)->m_Name);
for(std::vector<pcap_addr_t>::iterator addrIter = (*devIter)->m_Addresses.begin(); addrIter != (*devIter)->m_Addresses.end(); addrIter++)
{
if (LoggerPP::getInstance().isDebugEnabled(PcapLogModuleLiveDevice) && addrIter->addr != NULL)
{
char addrAsString[INET6_ADDRSTRLEN];
sockaddr2string(addrIter->addr, addrAsString);
LOG_DEBUG("Searching address %s", addrAsString);
}
in6_addr* currAddr = sockaddr2in6_addr(addrIter->addr);
if (currAddr == NULL)
{
LOG_DEBUG("Address is NULL");
continue;
}
uint8_t* addrAsArr; size_t addrLen;
ip6Addr.copyTo(&addrAsArr, addrLen);
if (memcmp(currAddr, addrAsArr, sizeof(struct in6_addr)) == 0)
{
LOG_DEBUG("Found matched address!");
return (*devIter);
}
delete [] addrAsArr;
}
}
return NULL;
}
std::vector<IPv4Address>& PcapLiveDeviceList::getDnsServers()
{
return m_DnsServers;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(const char* ipAddrAsString)
{
std::auto_ptr<IPAddress> apAddr = IPAddress::fromString(ipAddrAsString);
if (!apAddr->isValid())
{
LOG_ERROR("IP address illegal");
return NULL;
}
PcapLiveDevice* result = PcapLiveDeviceList::getPcapLiveDeviceByIp(apAddr.get());
return result;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByName(const std::string& name)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
std::string devName((*devIter)->getName());
if (name == devName)
return (*devIter);
}
return NULL;
}
} // namespace pcpp
|
#define LOG_MODULE PcapLogModuleLiveDevice
#include <IpUtils.h>
#include <PcapLiveDeviceList.h>
#include <Logger.h>
#include <SystemUtils.h>
#include <string.h>
#include <sstream>
#include <algorithm>
#ifdef WIN32
#include <ws2tcpip.h>
#include <iphlpapi.h>
#elif MAC_OS_X
#include <systemconfiguration/scdynamicstore.h>
#endif
namespace pcpp
{
PcapLiveDeviceList::PcapLiveDeviceList()
{
pcap_if_t* interfaceList;
char errbuf[PCAP_ERRBUF_SIZE];
int err = pcap_findalldevs(&interfaceList, errbuf);
if (err < 0)
{
LOG_ERROR("Error searching for devices: %s", errbuf);
}
pcap_if_t* currInterface = interfaceList;
while (currInterface != NULL)
{
#ifdef WIN32
PcapLiveDevice* dev = new WinPcapLiveDevice(currInterface, true, true, true);
#else //LINUX, MAC_OSX
PcapLiveDevice* dev = new PcapLiveDevice(currInterface, true, true, true);
#endif
currInterface = currInterface->next;
m_LiveDeviceList.insert(m_LiveDeviceList.end(), dev);
}
setDnsServers();
LOG_DEBUG("Freeing live device data");
pcap_freealldevs(interfaceList);
}
PcapLiveDeviceList::~PcapLiveDeviceList()
{
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
delete (*devIter);
}
}
void PcapLiveDeviceList::setDnsServers()
{
#ifdef WIN32
FIXED_INFO * fixedInfo;
ULONG ulOutBufLen;
DWORD dwRetVal;
IP_ADDR_STRING * pIPAddr;
uint8_t buf1[sizeof(FIXED_INFO)];
fixedInfo = (FIXED_INFO *) buf1;
ulOutBufLen = sizeof( FIXED_INFO );
dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen );
uint8_t buf2[ulOutBufLen];
if(ERROR_BUFFER_OVERFLOW == dwRetVal)
{
fixedInfo = (FIXED_INFO *)buf2;
}
if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0)
LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal);
else
{
m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String));
int i = 1;
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String );
pIPAddr = fixedInfo->DnsServerList.Next;
while ( pIPAddr )
{
m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String));
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String);
pIPAddr = pIPAddr -> Next;
}
}
#elif LINUX
// verify that nmcli exist
std::string command = "command -v nmcli >/dev/null 2>&1 || { echo 'nmcli not installed'; }";
std::string nmcliExists = executeShellCommand(command);
if (nmcliExists != "")
{
LOG_ERROR("Error retrieving DNS server list: nmcli doesn't exist");
return;
}
// check nmcli major version (0 or 1)
command = "nmcli -v | awk -F' ' '{print $NF}' | awk -F'.' '{print $1}'";
std::string nmcliMajorVer = executeShellCommand(command);
nmcliMajorVer.erase(std::remove(nmcliMajorVer.begin(), nmcliMajorVer.end(), '\n'), nmcliMajorVer.end());
LOG_DEBUG("Found nmcli. nmcli major version is: '%s'", nmcliMajorVer.c_str());
// build nmcli command according to its major version
if (nmcliMajorVer == "0")
command = "nmcli dev list | grep IP4.DNS";
else
command = "nmcli dev show | grep IP4.DNS";
std::string dnsServersInfo = executeShellCommand(command);
if (dnsServersInfo == "")
{
LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output");
return;
}
std::istringstream stream(dnsServersInfo);
std::string line;
int i = 1;
while(std::getline(stream, line))
{
std::istringstream lineStream(line);
std::string headline;
std::string dnsIP;
lineStream >> headline;
lineStream >> dnsIP;
IPv4Address dnsIPAddr(dnsIP);
if (!dnsIPAddr.isValid())
continue;
if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end())
{
m_DnsServers.push_back(dnsIPAddr);
LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str());
}
}
#elif MAC_OS_X
SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL);
if (dynRef == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore");
return;
}
CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS"));
if (dnsDict == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary");
CFRelease(dynRef);
return;
}
CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses"));
if (serverAddresses == NULL)
{
LOG_DEBUG("Couldn't set DNS server list: server addresses array is null");
CFRelease(dynRef);
CFRelease(dnsDict);
return;
}
CFIndex count = CFArrayGetCount(serverAddresses);
for (CFIndex i = 0; i < count; i++)
{
CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i);
if (serverAddress == NULL)
continue;
uint8_t buf[20];
char* serverAddressCString = (char*)buf;
CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8);
m_DnsServers.push_back(IPv4Address(serverAddressCString));
LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString);
}
CFRelease(dynRef);
CFRelease(dnsDict);
#endif
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPAddress* ipAddr)
{
if (ipAddr->getType() == IPAddress::IPv4AddressType)
{
IPv4Address* ip4Addr = static_cast<IPv4Address*>(ipAddr);
return getPcapLiveDeviceByIp(*ip4Addr);
}
else //IPAddress::IPv6AddressType
{
IPv6Address* ip6Addr = static_cast<IPv6Address*>(ipAddr);
return getPcapLiveDeviceByIp(*ip6Addr);
}
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPv4Address ipAddr)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
LOG_DEBUG("Searching device '%s'. Searching all addresses...", (*devIter)->m_Name);
for(std::vector<pcap_addr_t>::iterator addrIter = (*devIter)->m_Addresses.begin(); addrIter != (*devIter)->m_Addresses.end(); addrIter++)
{
if (LoggerPP::getInstance().isDebugEnabled(PcapLogModuleLiveDevice) && addrIter->addr != NULL)
{
char addrAsString[INET6_ADDRSTRLEN];
sockaddr2string(addrIter->addr, addrAsString);
LOG_DEBUG("Searching address %s", addrAsString);
}
in_addr* currAddr = sockaddr2in_addr(addrIter->addr);
if (currAddr == NULL)
{
LOG_DEBUG("Address is NULL");
continue;
}
if (currAddr->s_addr == ipAddr.toInAddr()->s_addr)
{
LOG_DEBUG("Found matched address!");
return (*devIter);
}
}
}
return NULL;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(IPv6Address ip6Addr)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
LOG_DEBUG("Searching device '%s'. Searching all addresses...", (*devIter)->m_Name);
for(std::vector<pcap_addr_t>::iterator addrIter = (*devIter)->m_Addresses.begin(); addrIter != (*devIter)->m_Addresses.end(); addrIter++)
{
if (LoggerPP::getInstance().isDebugEnabled(PcapLogModuleLiveDevice) && addrIter->addr != NULL)
{
char addrAsString[INET6_ADDRSTRLEN];
sockaddr2string(addrIter->addr, addrAsString);
LOG_DEBUG("Searching address %s", addrAsString);
}
in6_addr* currAddr = sockaddr2in6_addr(addrIter->addr);
if (currAddr == NULL)
{
LOG_DEBUG("Address is NULL");
continue;
}
uint8_t* addrAsArr; size_t addrLen;
ip6Addr.copyTo(&addrAsArr, addrLen);
if (memcmp(currAddr, addrAsArr, sizeof(struct in6_addr)) == 0)
{
LOG_DEBUG("Found matched address!");
return (*devIter);
}
delete [] addrAsArr;
}
}
return NULL;
}
std::vector<IPv4Address>& PcapLiveDeviceList::getDnsServers()
{
return m_DnsServers;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByIp(const char* ipAddrAsString)
{
std::auto_ptr<IPAddress> apAddr = IPAddress::fromString(ipAddrAsString);
if (!apAddr->isValid())
{
LOG_ERROR("IP address illegal");
return NULL;
}
PcapLiveDevice* result = PcapLiveDeviceList::getPcapLiveDeviceByIp(apAddr.get());
return result;
}
PcapLiveDevice* PcapLiveDeviceList::getPcapLiveDeviceByName(const std::string& name)
{
LOG_DEBUG("Searching all live devices...");
for(std::vector<PcapLiveDevice*>::iterator devIter = m_LiveDeviceList.begin(); devIter != m_LiveDeviceList.end(); devIter++)
{
std::string devName((*devIter)->getName());
if (name == devName)
return (*devIter);
}
return NULL;
}
} // namespace pcpp
|
Fix nmcli call to get DNS list on Linux
|
Fix nmcli call to get DNS list on Linux
|
C++
|
unlicense
|
seladb/PcapPlusPlus,seladb/PcapPlusPlus,seladb/PcapPlusPlus,seladb/PcapPlusPlus
|
13a7ff6e9e96e929cf18774b83909754cf652930
|
document/src/vespa/document/serialization/vespadocumentdeserializer.cpp
|
document/src/vespa/document/serialization/vespadocumentdeserializer.cpp
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "vespadocumentdeserializer.h"
#include "annotationdeserializer.h"
#include <vespa/document/fieldvalue/annotationreferencefieldvalue.h>
#include <vespa/document/fieldvalue/arrayfieldvalue.h>
#include <vespa/document/fieldvalue/boolfieldvalue.h>
#include <vespa/document/fieldvalue/bytefieldvalue.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/fieldvalue/doublefieldvalue.h>
#include <vespa/document/fieldvalue/floatfieldvalue.h>
#include <vespa/document/fieldvalue/longfieldvalue.h>
#include <vespa/document/fieldvalue/mapfieldvalue.h>
#include <vespa/document/fieldvalue/predicatefieldvalue.h>
#include <vespa/document/fieldvalue/rawfieldvalue.h>
#include <vespa/document/fieldvalue/shortfieldvalue.h>
#include <vespa/document/fieldvalue/stringfieldvalue.h>
#include <vespa/document/fieldvalue/weightedsetfieldvalue.h>
#include <vespa/document/fieldvalue/tensorfieldvalue.h>
#include <vespa/document/fieldvalue/referencefieldvalue.h>
#include <vespa/vespalib/data/slime/binary_format.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/backtrace.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/eval/tensor/serialization/typed_binary_format.h>
#include <vespa/document/util/serializableexceptions.h>
#include <vespa/document/base/exceptions.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/document/util/bytebuffer.h>
#include <vespa/document/base/idstringexception.h>
#include <vespa/log/log.h>
LOG_SETUP(".vespadocumentdeserializer");
using std::vector;
using vespalib::Slime;
using vespalib::asciistream;
using vespalib::nbostream;
using vespalib::Memory;
using vespalib::stringref;
using vespalib::compression::CompressionConfig;
namespace document {
namespace {
template <typename Input>
uint32_t readSize(Input &input) {
return getInt1_2_4Bytes(input);
}
uint32_t
getChunkCount(uint8_t contentCode)
{
uint8_t chunks = 0;
if (contentCode & 0x02) {
++chunks;
}
if (contentCode & 0x04) {
++chunks;
}
return chunks;
}
} // namespace
void VespaDocumentDeserializer::readDocument(Document &value) {
read(value.getId());
uint8_t content_code = readValue<uint8_t>(_stream);
LOG(spam, "content_code is %u", content_code);
const DocumentType *type = readDocType(value.getType());
if (type) {
Document::verifyIdAndType(value.getId(), type);
value.setType(*type);
value.clear();
value.setLastModified(0);
}
value.setRepo(_repo.getDocumentTypeRepo());
FixedTypeRepo repo(_repo.getDocumentTypeRepo(), value.getType());
VarScope<FixedTypeRepo> repo_scope(_repo, repo);
uint32_t chunkCount = getChunkCount(content_code);
value.getFields().reset();
for (uint32_t i = 0; i < chunkCount; ++i) {
readStructNoReset(value.getFields());
}
}
void VespaDocumentDeserializer::read(FieldValue &value) {
value.accept(*this);
}
const DocumentType*
VespaDocumentDeserializer::readDocType(const DocumentType &guess)
{
stringref type_name(_stream.peek());
_stream.adjustReadPos(type_name.size() + 1);
readValue<uint16_t>(_stream); // skip version
if (guess.getName() != type_name) {
const DocumentType *type =
_repo.getDocumentTypeRepo().getDocumentType(type_name);
if (!type) {
throw DocumentTypeNotFoundException(type_name, VESPA_STRLOC);
}
return type;
}
return 0;
}
void VespaDocumentDeserializer::read(DocumentId &value) {
stringref s(_stream.peek());
value.set(s);
_stream.adjustReadPos(s.size() + 1);
}
void VespaDocumentDeserializer::read(DocumentType &value) {
const DocumentType *doc_type = readDocType(value);
if (doc_type) {
value = *doc_type;
}
}
void VespaDocumentDeserializer::read(Document &value) {
uint16_t version = readValue<uint16_t>(_stream);
VarScope<uint16_t> version_scope(_version, version);
if (version < 8 || version > 8) {
asciistream msg;
msg << "Unrecognized serialization version " << version;
throw DeserializeException(msg.str(), VESPA_STRLOC);
}
uint32_t data_size = readValue<uint32_t>(_stream);
size_t data_start_size = _stream.size();
readDocument(value);
if (data_start_size - _stream.size() != data_size) {
asciistream msg;
msg << "Length mismatch. Was "
<< data_start_size - _stream.size()
<< ", expected " << data_size << ".";
throw DeserializeException(msg.str(), VESPA_STRLOC);
}
}
void VespaDocumentDeserializer::read(AnnotationReferenceFieldValue &value) {
value.setAnnotationIndex(getInt1_2_4Bytes(_stream));
}
void VespaDocumentDeserializer::read(ArrayFieldValue &value) {
uint32_t size = readSize(_stream);
value.clear();
value.resize(size);
for (uint32_t i = 0; i < size; ++i) {
value[i].accept(*this); // Double dispatch to call the correct read()
}
}
void VespaDocumentDeserializer::read(MapFieldValue &value) {
value.clear();
uint32_t size = readSize(_stream);
value.resize(size);
for (auto & pair : value) {
pair.first->accept(*this); // Double dispatch to call the correct read()
pair.second->accept(*this); // Double dispatch to call the correct read()
}
}
namespace {
template <typename T> struct ValueType { using Type = typename T::Number; };
template <> struct ValueType<BoolFieldValue> { using Type = bool; };
template <> struct ValueType<ShortFieldValue> { using Type = uint16_t; };
template <> struct ValueType<IntFieldValue> { using Type = uint32_t; };
template <> struct ValueType<LongFieldValue> { using Type = uint64_t; };
template <> struct ValueType<RawFieldValue> { using Type = vespalib::string; };
template <typename T>
void readFieldValue(nbostream &input, T &value) {
typename ValueType<T>::Type val;
input >> val;
value.setValue(val);
}
} // namespace
void VespaDocumentDeserializer::read(BoolFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(ByteFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(DoubleFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(FloatFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(IntFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(LongFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(PredicateFieldValue &value) {
uint32_t stored_size = readValue<uint32_t>(_stream);
Memory memory(_stream.peek(), _stream.size());
std::unique_ptr<Slime> slime(new Slime);
size_t size = vespalib::slime::BinaryFormat::decode(memory, *slime);
if (size != stored_size) {
throw DeserializeException("Specified slime size don't match actual "
"slime size.", VESPA_STRLOC);
}
value = PredicateFieldValue(std::move(slime));
_stream.adjustReadPos(size);
}
namespace {
template <typename FV>
void setValue(FV &field_value, stringref val, bool use_ref) {
if (use_ref) {
field_value.setValueRef(val);
} else {
field_value.setValue(val);
}
}
} // namespace
void VespaDocumentDeserializer::read(RawFieldValue &value) {
uint32_t size = readValue<uint32_t>(_stream);
stringref val(_stream.peek(), size);
setValue(value, val, _stream.isLongLivedBuffer());
_stream.adjustReadPos(size);
}
void VespaDocumentDeserializer::read(ShortFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(StringFieldValue &value) {
uint8_t coding = readValue<uint8_t>(_stream);
size_t size = getInt1_4Bytes(_stream);
if (size == 0) {
throw DeserializeException("invalid zero string length", VESPA_STRLOC);
}
stringref val(_stream.peek(), size - 1);
_stream.adjustReadPos(size);
setValue(value, val, _stream.isLongLivedBuffer());
if (coding & 0x40) {
uint32_t serializedAnnotationsSize = readValue<uint32_t>(_stream);
value.setSpanTrees(vespalib::ConstBufferRef(_stream.peek(), serializedAnnotationsSize),
_repo, _version, _stream.isLongLivedBuffer());
_stream.adjustReadPos(serializedAnnotationsSize);
} else {
value.clearSpanTrees();
}
}
namespace {
typedef SerializableArray::EntryMap FieldInfo;
void readFieldInfo(nbostream& input, SerializableArray::EntryMap & field_info) __attribute__((noinline));
void readFieldInfo(nbostream& input, SerializableArray::EntryMap & field_info) {
size_t field_count = getInt1_4Bytes(input);
field_info.reserve(field_count);
uint32_t offset = 0;
for (size_t i = 0; i < field_count; ++i) {
const uint32_t id = getInt1_4Bytes(input);
const uint32_t size = getInt2_4_8Bytes(input);
field_info.emplace_back(id,
size, offset);
offset += size;
}
}
} // namespace
void VespaDocumentDeserializer::readStructNoReset(StructFieldValue &value) {
size_t data_size = readValue<uint32_t>(_stream);
CompressionConfig::Type compression_type = CompressionConfig::Type(readValue<uint8_t>(_stream));
SerializableArray::EntryMap field_info;
size_t uncompressed_size = 0;
if (CompressionConfig::isCompressed(compression_type)) {
uncompressed_size = getInt2_4_8Bytes(_stream);
}
readFieldInfo(_stream, field_info);
if (CompressionConfig::isCompressed(compression_type)) {
if ((compression_type != CompressionConfig::LZ4)) {
throw DeserializeException("Unsupported compression type.", VESPA_STRLOC);
} else if (data_size > _stream.size()) {
throw DeserializeException("Invalid compressed struct data.", VESPA_STRLOC);
}
}
if (data_size > 0) {
ByteBuffer buffer(_stream.isLongLivedBuffer()
? ByteBuffer(_stream.peek(), data_size)
: ByteBuffer::copyBuffer(_stream.peek(), data_size));
if (value.getFields().empty()) {
LOG(spam, "Lazy deserializing into %s with _version %u",
value.getDataType()->getName().c_str(), _version);
value.lazyDeserialize(_repo, _version, std::move(field_info),
std::move(buffer), compression_type, uncompressed_size);
} else {
LOG(debug, "Legacy dual header/body format. -> Merging.");
StructFieldValue tmp(*value.getDataType());
tmp.lazyDeserialize(_repo, _version, std::move(field_info),
std::move(buffer), compression_type, uncompressed_size);
for (const auto & entry : tmp) {
try {
FieldValue::UP decoded = tmp.getValue(entry);
value.setValue(entry, std::move(decoded));
} catch (const vespalib::Exception & e) {
LOG(warning, "Failed decoding field '%s' in legacy bodyfield -> Skipping it: %s",
entry.getName().data(), e.what());
}
}
}
_stream.adjustReadPos(data_size);
}
}
void
VespaDocumentDeserializer::read(StructFieldValue& value)
{
value.reset();
readStructNoReset(value);
}
void VespaDocumentDeserializer::read(WeightedSetFieldValue &value) {
value.clear();
readValue<uint32_t>(_stream); // skip type id
uint32_t size = readValue<uint32_t>(_stream);
value.reserve(size);
for (uint32_t i = 0; i < size; ++i) {
readValue<uint32_t>(_stream); // skip element size
FieldValue::UP child = value.createNested();
child->accept(*this); // Double dispatch to call the correct read()
uint32_t weight = readValue<uint32_t>(_stream);
value.push_back(std::move(child), weight);
}
}
void
VespaDocumentDeserializer::read(TensorFieldValue &value)
{
size_t length = _stream.getInt1_4Bytes();
if (length > _stream.size()) {
throw DeserializeException(vespalib::make_string("Stream failed size(%zu), needed(%zu) to deserialize tensor field value", _stream.size(), length),
VESPA_STRLOC);
}
std::unique_ptr<vespalib::tensor::Tensor> tensor;
if (length != 0) {
nbostream wrapStream(_stream.peek(), length);
tensor = vespalib::tensor::TypedBinaryFormat::deserialize(wrapStream);
if (wrapStream.size() != 0) {
throw DeserializeException("Leftover bytes deserializing tensor field value.", VESPA_STRLOC);
}
}
value.assignDeserialized(std::move(tensor));
_stream.adjustReadPos(length);
}
void VespaDocumentDeserializer::read(ReferenceFieldValue& value) {
const bool hasId(readValue<uint8_t>(_stream) == 1);
if (hasId) {
DocumentId id;
read(id);
value.setDeserializedDocumentId(id);
} else {
value.clearChanged();
}
}
} // document
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "vespadocumentdeserializer.h"
#include "annotationdeserializer.h"
#include <vespa/document/fieldvalue/annotationreferencefieldvalue.h>
#include <vespa/document/fieldvalue/arrayfieldvalue.h>
#include <vespa/document/fieldvalue/boolfieldvalue.h>
#include <vespa/document/fieldvalue/bytefieldvalue.h>
#include <vespa/document/fieldvalue/document.h>
#include <vespa/document/fieldvalue/doublefieldvalue.h>
#include <vespa/document/fieldvalue/floatfieldvalue.h>
#include <vespa/document/fieldvalue/longfieldvalue.h>
#include <vespa/document/fieldvalue/mapfieldvalue.h>
#include <vespa/document/fieldvalue/predicatefieldvalue.h>
#include <vespa/document/fieldvalue/rawfieldvalue.h>
#include <vespa/document/fieldvalue/shortfieldvalue.h>
#include <vespa/document/fieldvalue/stringfieldvalue.h>
#include <vespa/document/fieldvalue/weightedsetfieldvalue.h>
#include <vespa/document/fieldvalue/tensorfieldvalue.h>
#include <vespa/document/fieldvalue/referencefieldvalue.h>
#include <vespa/vespalib/data/slime/binary_format.h>
#include <vespa/vespalib/data/slime/slime.h>
#include <vespa/vespalib/stllike/asciistream.h>
#include <vespa/vespalib/util/backtrace.h>
#include <vespa/eval/tensor/tensor.h>
#include <vespa/eval/tensor/serialization/typed_binary_format.h>
#include <vespa/document/util/serializableexceptions.h>
#include <vespa/document/base/exceptions.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/document/util/bytebuffer.h>
#include <vespa/document/base/idstringexception.h>
#include <vespa/log/log.h>
LOG_SETUP(".vespadocumentdeserializer");
using std::vector;
using vespalib::Slime;
using vespalib::asciistream;
using vespalib::nbostream;
using vespalib::Memory;
using vespalib::stringref;
using vespalib::compression::CompressionConfig;
namespace document {
namespace {
template <typename Input>
uint32_t readSize(Input &input) {
return getInt1_2_4Bytes(input);
}
uint32_t
getChunkCount(uint8_t contentCode)
{
uint8_t chunks = 0;
if (contentCode & 0x02) {
++chunks;
}
if (contentCode & 0x04) {
++chunks;
}
return chunks;
}
} // namespace
void VespaDocumentDeserializer::readDocument(Document &value) {
read(value.getId());
uint8_t content_code = readValue<uint8_t>(_stream);
LOG(spam, "content_code is %u", content_code);
const DocumentType *type = readDocType(value.getType());
if (type) {
Document::verifyIdAndType(value.getId(), type);
value.setType(*type);
value.clear();
value.setLastModified(0);
}
value.setRepo(_repo.getDocumentTypeRepo());
FixedTypeRepo repo(_repo.getDocumentTypeRepo(), value.getType());
VarScope<FixedTypeRepo> repo_scope(_repo, repo);
uint32_t chunkCount = getChunkCount(content_code);
value.getFields().reset();
for (uint32_t i = 0; i < chunkCount; ++i) {
readStructNoReset(value.getFields());
}
}
void VespaDocumentDeserializer::read(FieldValue &value) {
value.accept(*this);
}
const DocumentType*
VespaDocumentDeserializer::readDocType(const DocumentType &guess)
{
stringref type_name(_stream.peek());
_stream.adjustReadPos(type_name.size() + 1);
readValue<uint16_t>(_stream); // skip version
if (guess.getName() != type_name) {
const DocumentType *type =
_repo.getDocumentTypeRepo().getDocumentType(type_name);
if (!type) {
throw DocumentTypeNotFoundException(type_name, VESPA_STRLOC);
}
return type;
}
return 0;
}
void VespaDocumentDeserializer::read(DocumentId &value) {
stringref s(_stream.peek());
value.set(s);
_stream.adjustReadPos(s.size() + 1);
}
void VespaDocumentDeserializer::read(DocumentType &value) {
const DocumentType *doc_type = readDocType(value);
if (doc_type) {
value = *doc_type;
}
}
void VespaDocumentDeserializer::read(Document &value) {
uint16_t version = readValue<uint16_t>(_stream);
VarScope<uint16_t> version_scope(_version, version);
if (version < 8 || version > 8) {
asciistream msg;
msg << "Unrecognized serialization version " << version;
throw DeserializeException(msg.str(), VESPA_STRLOC);
}
uint32_t data_size = readValue<uint32_t>(_stream);
size_t data_start_size = _stream.size();
readDocument(value);
if (data_start_size - _stream.size() != data_size) {
asciistream msg;
msg << "Length mismatch. Was "
<< data_start_size - _stream.size()
<< ", expected " << data_size << ".";
throw DeserializeException(msg.str(), VESPA_STRLOC);
}
}
void VespaDocumentDeserializer::read(AnnotationReferenceFieldValue &value) {
value.setAnnotationIndex(getInt1_2_4Bytes(_stream));
}
void VespaDocumentDeserializer::read(ArrayFieldValue &value) {
uint32_t size = readSize(_stream);
value.clear();
value.resize(size);
for (uint32_t i = 0; i < size; ++i) {
value[i].accept(*this); // Double dispatch to call the correct read()
}
}
void VespaDocumentDeserializer::read(MapFieldValue &value) {
value.clear();
uint32_t size = readSize(_stream);
value.resize(size);
for (auto & pair : value) {
pair.first->accept(*this); // Double dispatch to call the correct read()
pair.second->accept(*this); // Double dispatch to call the correct read()
}
}
namespace {
template <typename T> struct ValueType { using Type = typename T::Number; };
template <> struct ValueType<BoolFieldValue> { using Type = bool; };
template <> struct ValueType<ShortFieldValue> { using Type = uint16_t; };
template <> struct ValueType<IntFieldValue> { using Type = uint32_t; };
template <> struct ValueType<LongFieldValue> { using Type = uint64_t; };
template <> struct ValueType<RawFieldValue> { using Type = vespalib::string; };
template <typename T>
void readFieldValue(nbostream &input, T &value) {
typename ValueType<T>::Type val;
input >> val;
value.setValue(val);
}
} // namespace
void VespaDocumentDeserializer::read(BoolFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(ByteFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(DoubleFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(FloatFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(IntFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(LongFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(PredicateFieldValue &value) {
uint32_t stored_size = readValue<uint32_t>(_stream);
Memory memory(_stream.peek(), _stream.size());
std::unique_ptr<Slime> slime(new Slime);
size_t size = vespalib::slime::BinaryFormat::decode(memory, *slime);
if (size != stored_size) {
throw DeserializeException("Specified slime size don't match actual "
"slime size.", VESPA_STRLOC);
}
value = PredicateFieldValue(std::move(slime));
_stream.adjustReadPos(size);
}
namespace {
template <typename FV>
void setValue(FV &field_value, stringref val, bool use_ref) {
if (use_ref) {
field_value.setValueRef(val);
} else {
field_value.setValue(val);
}
}
} // namespace
void VespaDocumentDeserializer::read(RawFieldValue &value) {
uint32_t size = readValue<uint32_t>(_stream);
stringref val(_stream.peek(), size);
setValue(value, val, _stream.isLongLivedBuffer());
_stream.adjustReadPos(size);
}
void VespaDocumentDeserializer::read(ShortFieldValue &value) {
readFieldValue(_stream, value);
}
void VespaDocumentDeserializer::read(StringFieldValue &value) {
uint8_t coding = readValue<uint8_t>(_stream);
size_t size = getInt1_4Bytes(_stream);
if (size == 0) {
throw DeserializeException("invalid zero string length", VESPA_STRLOC);
}
stringref val(_stream.peek(), size - 1);
_stream.adjustReadPos(size);
setValue(value, val, _stream.isLongLivedBuffer());
if (coding & 0x40) {
uint32_t serializedAnnotationsSize = readValue<uint32_t>(_stream);
value.setSpanTrees(vespalib::ConstBufferRef(_stream.peek(), serializedAnnotationsSize),
_repo, _version, _stream.isLongLivedBuffer());
_stream.adjustReadPos(serializedAnnotationsSize);
} else {
value.clearSpanTrees();
}
}
namespace {
typedef SerializableArray::EntryMap FieldInfo;
void readFieldInfo(nbostream& input, SerializableArray::EntryMap & field_info) __attribute__((noinline));
void readFieldInfo(nbostream& input, SerializableArray::EntryMap & field_info) {
size_t field_count = getInt1_4Bytes(input);
field_info.reserve(field_count);
uint32_t offset = 0;
for (size_t i = 0; i < field_count; ++i) {
const uint32_t id = getInt1_4Bytes(input);
const uint32_t size = getInt2_4_8Bytes(input);
field_info.emplace_back(id, size, offset);
offset += size;
}
}
} // namespace
void VespaDocumentDeserializer::readStructNoReset(StructFieldValue &value) {
size_t data_size = readValue<uint32_t>(_stream);
CompressionConfig::Type compression_type = CompressionConfig::Type(readValue<uint8_t>(_stream));
SerializableArray::EntryMap field_info;
size_t uncompressed_size = 0;
if (CompressionConfig::isCompressed(compression_type)) {
uncompressed_size = getInt2_4_8Bytes(_stream);
}
readFieldInfo(_stream, field_info);
if (CompressionConfig::isCompressed(compression_type)) {
if ((compression_type != CompressionConfig::LZ4)) {
throw DeserializeException("Unsupported compression type.", VESPA_STRLOC);
} else if (data_size > _stream.size()) {
throw DeserializeException("Invalid compressed struct data.", VESPA_STRLOC);
}
}
if (data_size > 0) {
ByteBuffer buffer(_stream.isLongLivedBuffer()
? ByteBuffer(_stream.peek(), data_size)
: ByteBuffer::copyBuffer(_stream.peek(), data_size));
if (value.getFields().empty()) {
LOG(spam, "Lazy deserializing into %s with _version %u",
value.getDataType()->getName().c_str(), _version);
value.lazyDeserialize(_repo, _version, std::move(field_info),
std::move(buffer), compression_type, uncompressed_size);
} else {
LOG(debug, "Legacy dual header/body format. -> Merging.");
StructFieldValue tmp(*value.getDataType());
tmp.lazyDeserialize(_repo, _version, std::move(field_info),
std::move(buffer), compression_type, uncompressed_size);
for (const auto & entry : tmp) {
try {
FieldValue::UP decoded = tmp.getValue(entry);
value.setValue(entry, std::move(decoded));
} catch (const vespalib::Exception & e) {
LOG(warning, "Failed decoding field '%s' in legacy bodyfield -> Skipping it: %s",
entry.getName().data(), e.what());
}
}
}
_stream.adjustReadPos(data_size);
}
}
void
VespaDocumentDeserializer::read(StructFieldValue& value)
{
value.reset();
readStructNoReset(value);
}
void VespaDocumentDeserializer::read(WeightedSetFieldValue &value) {
value.clear();
readValue<uint32_t>(_stream); // skip type id
uint32_t size = readValue<uint32_t>(_stream);
value.reserve(size);
for (uint32_t i = 0; i < size; ++i) {
readValue<uint32_t>(_stream); // skip element size
FieldValue::UP child = value.createNested();
child->accept(*this); // Double dispatch to call the correct read()
uint32_t weight = readValue<uint32_t>(_stream);
value.push_back(std::move(child), weight);
}
}
void
VespaDocumentDeserializer::read(TensorFieldValue &value)
{
size_t length = _stream.getInt1_4Bytes();
if (length > _stream.size()) {
throw DeserializeException(vespalib::make_string("Stream failed size(%zu), needed(%zu) to deserialize tensor field value", _stream.size(), length),
VESPA_STRLOC);
}
std::unique_ptr<vespalib::tensor::Tensor> tensor;
if (length != 0) {
nbostream wrapStream(_stream.peek(), length);
tensor = vespalib::tensor::TypedBinaryFormat::deserialize(wrapStream);
if (wrapStream.size() != 0) {
throw DeserializeException("Leftover bytes deserializing tensor field value.", VESPA_STRLOC);
}
}
value.assignDeserialized(std::move(tensor));
_stream.adjustReadPos(length);
}
void VespaDocumentDeserializer::read(ReferenceFieldValue& value) {
const bool hasId(readValue<uint8_t>(_stream) == 1);
if (hasId) {
DocumentId id;
read(id);
value.setDeserializedDocumentId(id);
} else {
value.clearChanged();
}
}
} // document
|
Remove spurious line break.
|
Remove spurious line break.
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
a818ca64069354adc40985dc28fbc97157be18db
|
src/pks/deform/prescribed_deformation/prescribed_deformation.cc
|
src/pks/deform/prescribed_deformation/prescribed_deformation.cc
|
/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Markus Berndt
Interface for the Prescribed Deformation PK.
<ParameterList name="prescribed deformation">
<Parameter name="PK model" type="string" value="Prescibed Mesh Deformation"/>
<Parameter name="Deformation method" type="string" value="method name"/>
</ParameterList>
------------------------------------------------------------------------- */
#include "prescribed_deformation.hh"
#include "porosity_evaluator.hh"
namespace Amanzi {
namespace Deform {
using namespace Amanzi::AmanziMesh;
RegisteredPKFactory<PrescribedDeformation> PrescribedDeformation::reg_("prescribed deformation");
PrescribedDeformation::PrescribedDeformation(Teuchos::ParameterList& plist,
const Teuchos::RCP<TreeVector>& solution):
PKDefaultBase(plist,solution),
PKPhysicalBase(plist,solution)
{
}
// -- Setup data
void PrescribedDeformation::setup(const Teuchos::Ptr<State>& S) {
PKPhysicalBase::setup(S);
S->RequireField(key_,name_);
dependencies_.insert("cell_volume");
}
// -- Initialize owned (dependent) variables.
void PrescribedDeformation::initialize(const Teuchos::Ptr<State>& S) {
PKPhysicalBase::initialize(S);
}
// -- advance via one of a few methods
bool PrescribedDeformation::advance(double dt) {
std::cout << "ADVANCING prescribed deformation" << std:: endl;
AmanziMesh::Mesh * write_access_mesh_ = const_cast<AmanziMesh::Mesh*>(&*S_next_->GetMesh());
Teuchos::RCP<CompositeVector> cell_volume = S_next_->GetFieldData("cell_volume", "cell_volume");
Teuchos::RCP<FieldEvaluator> cveval = S_next_->GetFieldEvaluator("cell_volume");
double ss = S_next_->time();
double ss0 = S_->time();
double thickness = 0.8 + 0.2*cos( ss / (365.25*24*60*60) * 2.0*M_PI );
double thickness0 = 0.8 + 0.2*cos( ss0 / (365.25*24*60*60) * 2.0*M_PI );
double factor = thickness/thickness0;
std::cout << "factor = " << factor << std::endl;
// get space dimensions
int dim = write_access_mesh_->space_dimension();
// set the list of the new position coords
AmanziGeometry::Point_List newpos, finpos;
// move the mid point on the mesh top
Entity_ID_List nodeids;
// number of vertices
int nV = write_access_mesh_->num_entities(Amanzi::AmanziMesh::NODE,
Amanzi::AmanziMesh::OWNED);
std::cout << "number of nodes = " << nV << std::endl;
Amanzi::AmanziGeometry::Point coords, new_coords;
coords.init(dim);
new_coords.init(dim);
// search the id of the mid point on the top
for (int iV=0; iV<nV; iV++) {
// get the coords of the node
write_access_mesh_->node_get_coordinates(iV,&coords);
for ( int s=0; s<dim-1; ++s ) {
new_coords[s] = coords[s];
}
// new_coords[dim-1] = coords[dim-1] * fac;
new_coords[dim-1] = coords[dim-1] * factor;
// puch back for deform method
nodeids.push_back(iV);
newpos.push_back( new_coords );
}
std::cout << "now modifying the mesh..." << std::endl;
// compute the deformed mesh
write_access_mesh_->deform( nodeids, newpos, true, &finpos);
std::cout << "cell volume = " << write_access_mesh_->cell_volume(0) << std::endl;
// now update cell volumes
cell_volume->Scale(factor);
std::cout << "DONE" << std::endl;
}
} // namespace
} // namespace
|
/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/* -------------------------------------------------------------------------
ATS
License: see $ATS_DIR/COPYRIGHT
Author: Markus Berndt
Interface for the Prescribed Deformation PK.
<ParameterList name="prescribed deformation">
<Parameter name="PK model" type="string" value="Prescibed Mesh Deformation"/>
<Parameter name="Deformation method" type="string" value="method name"/>
</ParameterList>
------------------------------------------------------------------------- */
#include "prescribed_deformation.hh"
namespace Amanzi {
namespace Deform {
using namespace Amanzi::AmanziMesh;
RegisteredPKFactory<PrescribedDeformation> PrescribedDeformation::reg_("prescribed deformation");
PrescribedDeformation::PrescribedDeformation(Teuchos::ParameterList& plist,
const Teuchos::RCP<TreeVector>& solution):
PKDefaultBase(plist,solution),
PKPhysicalBase(plist,solution)
{
}
// -- Setup data
void PrescribedDeformation::setup(const Teuchos::Ptr<State>& S) {
PKPhysicalBase::setup(S);
}
// -- Initialize owned (dependent) variables.
void PrescribedDeformation::initialize(const Teuchos::Ptr<State>& S) {
PKPhysicalBase::initialize(S);
}
// -- advance via one of a few methods
bool PrescribedDeformation::advance(double dt) {
std::cout << "ADVANCING prescribed deformation" << std:: endl;
AmanziMesh::Mesh * write_access_mesh_ = const_cast<AmanziMesh::Mesh*>(&*S_next_->GetMesh());
Teuchos::RCP<CompositeVector> cell_volume = S_next_->GetFieldData("cell_volume", "cell_volume");
// Teuchos::RCP<FieldEvaluator> cveval = S_next_->GetFieldEvaluator("cell_volume");
double ss = S_next_->time();
double ss0 = S_->time();
double thickness = 0.8 + 0.2*cos( ss / (365.25*24*60*60) * 2.0*M_PI );
double thickness0 = 0.8 + 0.2*cos( ss0 / (365.25*24*60*60) * 2.0*M_PI );
double factor = thickness/thickness0;
std::cout << "factor = " << factor << std::endl;
// get space dimensions
int dim = write_access_mesh_->space_dimension();
// set the list of the new position coords
AmanziGeometry::Point_List newpos, finpos;
// move the mid point on the mesh top
Entity_ID_List nodeids;
// number of vertices
int nV = write_access_mesh_->num_entities(Amanzi::AmanziMesh::NODE,
Amanzi::AmanziMesh::OWNED);
std::cout << "number of nodes = " << nV << std::endl;
Amanzi::AmanziGeometry::Point coords, new_coords;
coords.init(dim);
new_coords.init(dim);
// search the id of the mid point on the top
for (int iV=0; iV<nV; iV++) {
// get the coords of the node
write_access_mesh_->node_get_coordinates(iV,&coords);
for ( int s=0; s<dim-1; ++s ) {
new_coords[s] = coords[s];
}
// new_coords[dim-1] = coords[dim-1] * fac;
new_coords[dim-1] = coords[dim-1] * factor;
// puch back for deform method
nodeids.push_back(iV);
newpos.push_back( new_coords );
}
std::cout << "now modifying the mesh..." << std::endl;
// compute the deformed mesh
write_access_mesh_->deform( nodeids, newpos, true, &finpos);
std::cout << "cell volume = " << write_access_mesh_->cell_volume(0) << std::endl;
// now update cell volumes
cell_volume->Scale(factor);
std::cout << "DONE" << std::endl;
}
} // namespace
} // namespace
|
update local repo
|
update local repo
|
C++
|
bsd-3-clause
|
amanzi/ats-dev,amanzi/ats-dev,amanzi/ats-dev
|
8f196cc752a336210e5b57966cd656e54f4e544d
|
addons/aimod/script_component.hpp
|
addons/aimod/script_component.hpp
|
#define COMPONENT aimod
#include "\z\fpa\addons\main\script_mod.hpp"
#define DEBUG_MODE_FULL
#define DISABLE_COMPILE_CACHE
// #define CBA_DEBUG_SYNCHRONOUS
// #define ENABLE_PERFORMANCE_COUNTERS
#include "\z\fpa\addons\main\script_macros.hpp"
|
#define COMPONENT aimod
#include "\z\fpa\addons\main\script_mod.hpp"
// #define DEBUG_MODE_FULL
// #define DISABLE_COMPILE_CACHE
// #define CBA_DEBUG_SYNCHRONOUS
// #define ENABLE_PERFORMANCE_COUNTERS
#include "\z\fpa\addons\main\script_macros.hpp"
|
disable debug
|
disable debug
|
C++
|
mit
|
fparma/fparma-mods,fparma/fparma-mods,fparma/fparma-mods
|
e1805adebec4053f45e201ffdd6a9b1845457906
|
src/checkpoints.cpp
|
src/checkpoints.cpp
|
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "txdb.h"
#include "main.h"
#include "uint256.h"
static const int nCheckpointSpan = 500;
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x00000068ea1bda5d79b59679d475024f8bc3344a5571a2c00bed231c7495fae6") ) // genesis
( 5000, uint256("0x000000000017501bf964656a97c4ba2657dd05b7bb52c4c17442966b11796989") )
( 10000, uint256("0x0908e603384f625dc816a16dcc98a3c8a3183c759ec5e3d1bbef642642386a33") )
( 50000, uint256("0x00000000001f1b1d5d043d65a52e53c460634275e33ef5bf308f8a362936c03e") )
( 100000, uint256("0x000000000014e8ccf418d1293e8d2dda42abcbd5a2d335d2e035b2059c5b2d78") )
( 120000, uint256("0x000000000003b1f965cefcbb3fb5eef2f19de55718e90fe35ddd752a142d6ce3") )
;
// TestNet has no checkpoints
static MapCheckpoints mapCheckpointsTestnet;
bool CheckHardened(int nHeight, const uint256& hash)
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
if (checkpoints.empty())
return 0;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
// Automatically select a suitable sync-checkpoint
const CBlockIndex* AutoSelectSyncCheckpoint()
{
const CBlockIndex *pindex = pindexBest;
// Search backward for a block within max span and maturity window
while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
pindex = pindex->pprev;
return pindex;
}
// Check against synchronized checkpoint
bool CheckSync(int nHeight)
{
const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();
if (nHeight <= pindexSync->nHeight)
return false;
return true;
}
}
|
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "txdb.h"
#include "main.h"
#include "uint256.h"
static const int nCheckpointSpan = 500;
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x00000068ea1bda5d79b59679d475024f8bc3344a5571a2c00bed231c7495fae6") ) // genesis
( 5000, uint256("0x000000000017501bf964656a97c4ba2657dd05b7bb52c4c17442966b11796989") )
( 10000, uint256("0x0908e603384f625dc816a16dcc98a3c8a3183c759ec5e3d1bbef642642386a33") )
( 50000, uint256("0x00000000001f1b1d5d043d65a52e53c460634275e33ef5bf308f8a362936c03e") )
( 100000, uint256("0x000000000014e8ccf418d1293e8d2dda42abcbd5a2d335d2e035b2059c5b2d78") )
( 120000, uint256("0x000000000003b1f965cefcbb3fb5eef2f19de55718e90fe35ddd752a142d6ce3") )
( 16000, uint256("0x000000000037142fd8382daa8236063626a4319aa6119c830843e7e212968e61") )
;
// TestNet has no checkpoints
static MapCheckpoints mapCheckpointsTestnet;
bool CheckHardened(int nHeight, const uint256& hash)
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
if (checkpoints.empty())
return 0;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
// Automatically select a suitable sync-checkpoint
const CBlockIndex* AutoSelectSyncCheckpoint()
{
const CBlockIndex *pindex = pindexBest;
// Search backward for a block within max span and maturity window
while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)
pindex = pindex->pprev;
return pindex;
}
// Check against synchronized checkpoint
bool CheckSync(int nHeight)
{
const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();
if (nHeight <= pindexSync->nHeight)
return false;
return true;
}
}
|
Add checkpoint BH 146000
|
Add checkpoint BH 146000
|
C++
|
mit
|
OC-CryptoCurrency/OC,OC-CryptoCurrency/OC,OC-CryptoCurrency/OC,OC-CryptoCurrency/OC,OC-CryptoCurrency/OC
|
c1a1d1abc810c8ff7f630453c050dd560f29b2f2
|
lib/DiscIONFS.cpp
|
lib/DiscIONFS.cpp
|
#include "nod/IDiscIO.hpp"
#include "nod/IFileIO.hpp"
#include "nod/Util.hpp"
#include "nod/aes.hpp"
#include <logvisor/logvisor.hpp>
#include <array>
namespace nod {
/*
* NFS is the image format used to distribute Wii VC games for the Wii U.
* It is an LBA format similar to WBFS but adds its own encryption layer.
* It logically stores a standard Wii disc image with partitions.
*/
class DiscIONFS : public IDiscIO {
struct DiscIONFSShared {
std::vector<std::unique_ptr<IFileIO>> files;
struct NFSHead {
uint32_t magic; // EGGS
uint32_t version;
uint32_t unknown[2]; // Signature, UUID?
uint32_t lbaRangeCount;
struct {
uint32_t startBlock;
uint32_t numBlocks;
} lbaRanges[61];
uint32_t endMagic; // SGGE
} nfsHead;
uint8_t key[16];
uint32_t calculateNumFiles() const {
uint32_t totalBlockCount = 0;
for (uint32_t i = 0; i < nfsHead.lbaRangeCount; ++i)
totalBlockCount += nfsHead.lbaRanges[i].numBlocks;
return (uint64_t(totalBlockCount) * uint64_t(0x8000) +
(uint64_t(0x200) + uint64_t(0xF9FFFFF))) / uint64_t(0xFA00000);
}
struct FBO {
uint32_t file, block, offset;
};
FBO logicalToFBO(uint64_t offset) const {
auto blockAndRemBytes = std::lldiv(offset, 0x8000); /* 32768 bytes per block */
uint32_t i, physicalBlock;
for (i = 0, physicalBlock = 0; i < nfsHead.lbaRangeCount; ++i) {
const auto& range = nfsHead.lbaRanges[i];
if (blockAndRemBytes.quot >= range.startBlock && blockAndRemBytes.quot - range.startBlock < range.numBlocks) {
blockAndRemBytes.quot = physicalBlock + (blockAndRemBytes.quot - range.startBlock);
break;
}
physicalBlock += range.numBlocks;
}
/* This offset has no physical mapping, read zeroes */
if (i == nfsHead.lbaRangeCount)
return {UINT32_MAX, UINT32_MAX, UINT32_MAX};
auto fileAndRemBlocks = std::lldiv(blockAndRemBytes.quot, 8000); /* 8000 blocks per file */
return {uint32_t(fileAndRemBlocks.quot), uint32_t(fileAndRemBlocks.rem), uint32_t(blockAndRemBytes.rem)};
}
DiscIONFSShared(SystemStringView fpin, bool& err) {
/* Validate file path format */
using SignedSize = std::make_signed<SystemString::size_type>::type;
const auto dotPos = SignedSize(fpin.rfind('.'));
const auto slashPos = SignedSize(fpin.rfind("/\\"));
if (fpin.size() <= 4 || dotPos == -1 || dotPos <= slashPos ||
fpin.compare(slashPos + 1, 4, "hif_") ||
fpin.compare(dotPos, fpin.size() - dotPos, ".nfs")) {
LogModule.report(logvisor::Error,
fmt("'{}' must begin with 'hif_' and end with '.nfs' to be accepted as an NFS image"), fpin);
err = true;
return;
}
/* Load key file */
const SystemString dir(fpin.begin(), fpin.begin() + slashPos + 1);
auto keyFile = NewFileIO(dir + "../code/htk.bin")->beginReadStream();
if (!keyFile)
keyFile = NewFileIO(dir + "htk.bin")->beginReadStream();
if (!keyFile) {
LogModule.report(logvisor::Error, fmt("Unable to open '{}../code/htk.bin' or '{}htk.bin'"), dir, dir);
err = true;
return;
}
if (keyFile->read(key, 16) != 16) {
LogModule.report(logvisor::Error, fmt("Unable to read from '{}../code/htk.bin' or '{}htk.bin'"), dir, dir);
err = true;
return;
}
/* Load header from first file */
const SystemString firstPath = fmt::format(fmt("{}hif_{:06}.nfs"), dir, 0);
files.push_back(NewFileIO(firstPath));
auto rs = files.back()->beginReadStream();
if (!rs) {
LogModule.report(logvisor::Error, fmt("'{}' does not exist"), firstPath);
err = true;
return;
}
if (rs->read(&nfsHead, 0x200) != 0x200) {
LogModule.report(logvisor::Error, fmt("Unable to read header from '{}'"), firstPath);
err = true;
return;
}
if (std::memcmp(&nfsHead.magic, "EGGS", 4)) {
LogModule.report(logvisor::Error, fmt("Invalid magic in '{}'"), firstPath);
err = true;
return;
}
nfsHead.lbaRangeCount = SBig(nfsHead.lbaRangeCount);
for (uint32_t i = 0; i < nfsHead.lbaRangeCount; ++i) {
auto& range = nfsHead.lbaRanges[i];
range.startBlock = SBig(range.startBlock);
range.numBlocks = SBig(range.numBlocks);
}
/* Ensure remaining files exist */
const uint32_t numFiles = calculateNumFiles();
files.reserve(numFiles);
for (uint32_t i = 1; i < numFiles; ++i) {
SystemString path = fmt::format(fmt("{}hif_{:06}.nfs"), dir, i);
files.push_back(NewFileIO(path));
if (!files.back()->exists()) {
LogModule.report(logvisor::Error, fmt("'{}' does not exist"), path);
err = true;
return;
}
}
}
};
std::shared_ptr<DiscIONFSShared> m_shared;
public:
DiscIONFS(SystemStringView fpin, bool& err) : m_shared(std::make_shared<DiscIONFSShared>(fpin, err)) {}
class ReadStream : public IReadStream {
friend class DiscIONFS;
std::shared_ptr<DiscIONFSShared> m_shared;
std::unique_ptr<IReadStream> m_rs;
std::unique_ptr<IAES> m_aes;
/* Physical address - all UINT32_MAX indicates logical zero block */
DiscIONFSShared::FBO m_physAddr;
/* Logical address */
uint64_t m_offset;
/* Active file stream and its offset as set in the system.
* Block is typically one ahead of the presently decrypted block. */
uint32_t m_curFile = UINT32_MAX;
uint32_t m_curBlock = UINT32_MAX;
ReadStream(std::shared_ptr<DiscIONFSShared> shared, uint64_t offset, bool& err)
: m_shared(std::move(shared)), m_aes(NewAES()),
m_physAddr({UINT32_MAX, UINT32_MAX, UINT32_MAX}), m_offset(offset) {
m_aes->setKey(m_shared->key);
setNewLogicalAddr(offset);
}
uint8_t m_encBuf[0x8000] = {};
uint8_t m_decBuf[0x8000] = {};
void setCurFile(uint32_t curFile) {
if (curFile >= m_shared->files.size()) {
LogModule.report(logvisor::Error, fmt("Out of bounds NFS file access"));
return;
}
m_curFile = curFile;
m_curBlock = UINT32_MAX;
m_rs = m_shared->files[m_curFile]->beginReadStream();
}
void setCurBlock(uint32_t curBlock) {
m_curBlock = curBlock;
m_rs->seek(m_curBlock * 0x8000 + 0x200);
}
void setNewPhysicalAddr(DiscIONFSShared::FBO physAddr) {
/* If we're just changing the offset, nothing else needs to be done */
if (m_physAddr.file == physAddr.file && m_physAddr.block == physAddr.block) {
m_physAddr.offset = physAddr.offset;
return;
}
m_physAddr = physAddr;
/* Set logical zero block */
if (m_physAddr.file == UINT32_MAX) {
memset(m_decBuf, 0, 0x8000);
return;
}
/* Make necessary file and block current with system */
if (m_physAddr.file != m_curFile)
setCurFile(m_physAddr.file);
if (m_physAddr.block != m_curBlock)
setCurBlock(m_physAddr.block);
/* Read block, handling 0x200 overlap case */
if (m_physAddr.block == 7999) {
m_rs->read(m_encBuf, 0x7E00);
setCurFile(m_curFile + 1);
m_rs->read(m_encBuf + 0x7E00, 0x200);
m_curBlock = 0;
} else {
m_rs->read(m_encBuf, 0x8000);
++m_curBlock;
}
/* Decrypt */
const uint32_t ivBuf[] = {0, 0, 0, SBig(m_physAddr.block)};
m_aes->decrypt((const uint8_t*)ivBuf, m_encBuf, m_decBuf, 0x8000);
}
void setNewLogicalAddr(uint64_t addr) {
setNewPhysicalAddr(m_shared->logicalToFBO(m_offset));
}
public:
uint64_t read(void* buf, uint64_t length) override {
uint64_t rem = length;
uint8_t* dst = (uint8_t*)buf;
/* Perform reads on block boundaries */
while (rem) {
uint64_t readSize = rem;
uint32_t blockOffset = (m_physAddr.offset == UINT32_MAX) ? 0 : m_physAddr.offset;
if (readSize + blockOffset > 0x8000)
readSize = 0x8000 - blockOffset;
memmove(dst, m_decBuf + blockOffset, readSize);
dst += readSize;
rem -= readSize;
m_offset += readSize;
setNewLogicalAddr(m_offset);
}
return dst - (uint8_t*)buf;
}
uint64_t position() const override { return m_offset; }
void seek(int64_t offset, int whence) override {
if (whence == SEEK_SET)
m_offset = offset;
else if (whence == SEEK_CUR)
m_offset += offset;
else
return;
setNewLogicalAddr(m_offset);
}
};
std::unique_ptr<IReadStream> beginReadStream(uint64_t offset) const override {
bool err = false;
auto ret = std::unique_ptr<IReadStream>(new ReadStream(m_shared, offset, err));
if (err)
return {};
return ret;
}
std::unique_ptr<IWriteStream> beginWriteStream(uint64_t offset) const override { return {}; }
bool hasWiiCrypto() const override { return false; }
};
std::unique_ptr<IDiscIO> NewDiscIONFS(SystemStringView path) {
bool err = false;
auto ret = std::make_unique<DiscIONFS>(path, err);
if (err)
return {};
return ret;
}
}
|
#include "nod/IDiscIO.hpp"
#include "nod/IFileIO.hpp"
#include "nod/Util.hpp"
#include "nod/aes.hpp"
#include <logvisor/logvisor.hpp>
#include <array>
namespace nod {
/*
* NFS is the image format used to distribute Wii VC games for the Wii U.
* It is an LBA format similar to WBFS but adds its own encryption layer.
* It logically stores a standard Wii disc image with partitions.
*/
class DiscIONFS : public IDiscIO {
struct DiscIONFSShared {
std::vector<std::unique_ptr<IFileIO>> files;
struct NFSHead {
uint32_t magic; // EGGS
uint32_t version;
uint32_t unknown[2]; // Signature, UUID?
uint32_t lbaRangeCount;
struct {
uint32_t startBlock;
uint32_t numBlocks;
} lbaRanges[61];
uint32_t endMagic; // SGGE
} nfsHead;
uint8_t key[16];
uint32_t calculateNumFiles() const {
uint32_t totalBlockCount = 0;
for (uint32_t i = 0; i < nfsHead.lbaRangeCount; ++i)
totalBlockCount += nfsHead.lbaRanges[i].numBlocks;
return (uint64_t(totalBlockCount) * uint64_t(0x8000) +
(uint64_t(0x200) + uint64_t(0xF9FFFFF))) / uint64_t(0xFA00000);
}
struct FBO {
uint32_t file, block, lblock, offset;
};
FBO logicalToFBO(uint64_t offset) const {
auto blockAndRemBytes = std::lldiv(offset, 0x8000); /* 32768 bytes per block */
uint32_t block = UINT32_MAX;
for (uint32_t i = 0, physicalBlock = 0; i < nfsHead.lbaRangeCount; ++i) {
const auto& range = nfsHead.lbaRanges[i];
if (blockAndRemBytes.quot >= range.startBlock && blockAndRemBytes.quot - range.startBlock < range.numBlocks) {
block = physicalBlock + (blockAndRemBytes.quot - range.startBlock);
break;
}
physicalBlock += range.numBlocks;
}
/* This offset has no physical mapping, read zeroes */
if (block == UINT32_MAX)
return {UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX};
auto fileAndRemBlocks = std::lldiv(block, 8000); /* 8000 blocks per file */
return {uint32_t(fileAndRemBlocks.quot), uint32_t(fileAndRemBlocks.rem),
uint32_t(blockAndRemBytes.quot), uint32_t(blockAndRemBytes.rem)};
}
DiscIONFSShared(SystemStringView fpin, bool& err) {
/* Validate file path format */
using SignedSize = std::make_signed<SystemString::size_type>::type;
const auto dotPos = SignedSize(fpin.rfind('.'));
const auto slashPos = SignedSize(fpin.rfind("/\\"));
if (fpin.size() <= 4 || dotPos == -1 || dotPos <= slashPos ||
fpin.compare(slashPos + 1, 4, "hif_") ||
fpin.compare(dotPos, fpin.size() - dotPos, ".nfs")) {
LogModule.report(logvisor::Error,
fmt("'{}' must begin with 'hif_' and end with '.nfs' to be accepted as an NFS image"), fpin);
err = true;
return;
}
/* Load key file */
const SystemString dir(fpin.begin(), fpin.begin() + slashPos + 1);
auto keyFile = NewFileIO(dir + "../code/htk.bin")->beginReadStream();
if (!keyFile)
keyFile = NewFileIO(dir + "htk.bin")->beginReadStream();
if (!keyFile) {
LogModule.report(logvisor::Error, fmt("Unable to open '{}../code/htk.bin' or '{}htk.bin'"), dir, dir);
err = true;
return;
}
if (keyFile->read(key, 16) != 16) {
LogModule.report(logvisor::Error, fmt("Unable to read from '{}../code/htk.bin' or '{}htk.bin'"), dir, dir);
err = true;
return;
}
/* Load header from first file */
const SystemString firstPath = fmt::format(fmt("{}hif_{:06}.nfs"), dir, 0);
files.push_back(NewFileIO(firstPath));
auto rs = files.back()->beginReadStream();
if (!rs) {
LogModule.report(logvisor::Error, fmt("'{}' does not exist"), firstPath);
err = true;
return;
}
if (rs->read(&nfsHead, 0x200) != 0x200) {
LogModule.report(logvisor::Error, fmt("Unable to read header from '{}'"), firstPath);
err = true;
return;
}
if (std::memcmp(&nfsHead.magic, "EGGS", 4)) {
LogModule.report(logvisor::Error, fmt("Invalid magic in '{}'"), firstPath);
err = true;
return;
}
nfsHead.lbaRangeCount = SBig(nfsHead.lbaRangeCount);
for (uint32_t i = 0; i < nfsHead.lbaRangeCount; ++i) {
auto& range = nfsHead.lbaRanges[i];
range.startBlock = SBig(range.startBlock);
range.numBlocks = SBig(range.numBlocks);
}
/* Ensure remaining files exist */
const uint32_t numFiles = calculateNumFiles();
files.reserve(numFiles);
for (uint32_t i = 1; i < numFiles; ++i) {
SystemString path = fmt::format(fmt("{}hif_{:06}.nfs"), dir, i);
files.push_back(NewFileIO(path));
if (!files.back()->exists()) {
LogModule.report(logvisor::Error, fmt("'{}' does not exist"), path);
err = true;
return;
}
}
}
};
std::shared_ptr<DiscIONFSShared> m_shared;
public:
DiscIONFS(SystemStringView fpin, bool& err) : m_shared(std::make_shared<DiscIONFSShared>(fpin, err)) {}
class ReadStream : public IReadStream {
friend class DiscIONFS;
std::shared_ptr<DiscIONFSShared> m_shared;
std::unique_ptr<IReadStream> m_rs;
std::unique_ptr<IAES> m_aes;
/* Physical address - all UINT32_MAX indicates logical zero block */
DiscIONFSShared::FBO m_physAddr;
/* Logical address */
uint64_t m_offset;
/* Active file stream and its offset as set in the system.
* Block is typically one ahead of the presently decrypted block. */
uint32_t m_curFile = UINT32_MAX;
uint32_t m_curBlock = UINT32_MAX;
ReadStream(std::shared_ptr<DiscIONFSShared> shared, uint64_t offset, bool& err)
: m_shared(std::move(shared)), m_aes(NewAES()),
m_physAddr({UINT32_MAX, UINT32_MAX, UINT32_MAX, UINT32_MAX}), m_offset(offset) {
m_aes->setKey(m_shared->key);
setNewLogicalAddr(offset);
}
uint8_t m_encBuf[0x8000] = {};
uint8_t m_decBuf[0x8000] = {};
void setCurFile(uint32_t curFile) {
if (curFile >= m_shared->files.size()) {
LogModule.report(logvisor::Error, fmt("Out of bounds NFS file access"));
return;
}
m_curFile = curFile;
m_curBlock = UINT32_MAX;
m_rs = m_shared->files[m_curFile]->beginReadStream();
}
void setCurBlock(uint32_t curBlock) {
m_curBlock = curBlock;
m_rs->seek(m_curBlock * 0x8000 + 0x200);
}
void setNewPhysicalAddr(DiscIONFSShared::FBO physAddr) {
/* If we're just changing the offset, nothing else needs to be done */
if (m_physAddr.file == physAddr.file && m_physAddr.block == physAddr.block) {
m_physAddr.offset = physAddr.offset;
return;
}
m_physAddr = physAddr;
/* Set logical zero block */
if (m_physAddr.file == UINT32_MAX) {
memset(m_decBuf, 0, 0x8000);
return;
}
/* Make necessary file and block current with system */
if (m_physAddr.file != m_curFile)
setCurFile(m_physAddr.file);
if (m_physAddr.block != m_curBlock)
setCurBlock(m_physAddr.block);
/* Read block, handling 0x200 overlap case */
if (m_physAddr.block == 7999) {
m_rs->read(m_encBuf, 0x7E00);
setCurFile(m_curFile + 1);
m_rs->read(m_encBuf + 0x7E00, 0x200);
m_curBlock = 0;
} else {
m_rs->read(m_encBuf, 0x8000);
++m_curBlock;
}
/* Decrypt */
const uint32_t ivBuf[] = {0, 0, 0, SBig(m_physAddr.lblock)};
m_aes->decrypt((const uint8_t*)ivBuf, m_encBuf, m_decBuf, 0x8000);
}
void setNewLogicalAddr(uint64_t addr) {
setNewPhysicalAddr(m_shared->logicalToFBO(m_offset));
}
public:
uint64_t read(void* buf, uint64_t length) override {
uint64_t rem = length;
uint8_t* dst = (uint8_t*)buf;
/* Perform reads on block boundaries */
while (rem) {
uint64_t readSize = rem;
uint32_t blockOffset = (m_physAddr.offset == UINT32_MAX) ? 0 : m_physAddr.offset;
if (readSize + blockOffset > 0x8000)
readSize = 0x8000 - blockOffset;
memmove(dst, m_decBuf + blockOffset, readSize);
dst += readSize;
rem -= readSize;
m_offset += readSize;
setNewLogicalAddr(m_offset);
}
return dst - (uint8_t*)buf;
}
uint64_t position() const override { return m_offset; }
void seek(int64_t offset, int whence) override {
if (whence == SEEK_SET)
m_offset = offset;
else if (whence == SEEK_CUR)
m_offset += offset;
else
return;
setNewLogicalAddr(m_offset);
}
};
std::unique_ptr<IReadStream> beginReadStream(uint64_t offset) const override {
bool err = false;
auto ret = std::unique_ptr<IReadStream>(new ReadStream(m_shared, offset, err));
if (err)
return {};
return ret;
}
std::unique_ptr<IWriteStream> beginWriteStream(uint64_t offset) const override { return {}; }
bool hasWiiCrypto() const override { return false; }
};
std::unique_ptr<IDiscIO> NewDiscIONFS(SystemStringView path) {
bool err = false;
auto ret = std::make_unique<DiscIONFS>(path, err);
if (err)
return {};
return ret;
}
}
|
Use logical block for iv
|
Use logical block for iv
|
C++
|
mit
|
RetroView/NODLib,AxioDL/NODLib,RetroView/NODLib,AxioDL/NODLib
|
c93cf48546c0954ecadda2e67cabc4dd3973f3a2
|
src/bindings/cpp/tests/test_contextual.cpp
|
src/bindings/cpp/tests/test_contextual.cpp
|
#include <contextual.hpp>
#include <gtest/gtest.h>
class MyStaticGetPolicy
{
public:
static kdb::Key get(ELEKTRA_UNUSED kdb::KeySet & ks,
ELEKTRA_UNUSED kdb::Key const& spec)
{
kdb::Key k("user/test",
KEY_VALUE, "23",
KEY_END);
return k;
}
};
TEST(test_contextual, staticGetPolicy)
{
using namespace kdb;
KeySet ks;
Context c;
ContextualValue<int, GetPolicyIs<MyStaticGetPolicy>> cv
(ks, c, Key("/test",
ckdb::KDB_O_CASCADING_NAME,
KEY_VALUE, "/test",
KEY_META, "default", "88",
KEY_END));
EXPECT_EQ(cv, 23);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
}
class MyDynamicGetPolicy
{
public:
static kdb::Key get(ELEKTRA_UNUSED kdb::KeySet & ks,
ELEKTRA_UNUSED kdb::Key const& spec)
{
return ksLookupBySpec(ks.getKeySet(), *spec);
}
};
TEST(test_contextual, dynamicGetPolicy)
{
using namespace kdb;
KeySet ks;
ks.append(Key("user/available",
KEY_VALUE, "12",
KEY_END));
Context c;
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv
(ks, c, Key("/test",
ckdb::KDB_O_CASCADING_NAME,
KEY_META, "default", "88",
KEY_META, "override/#0", "user/available",
KEY_END));
EXPECT_EQ(cv, 12);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
}
struct RootLayer : kdb::Layer
{
std::string id() const override
{
return "root";
}
std::string operator()() const override
{
return "root";
}
};
TEST(test_contextual, root)
{
using namespace kdb;
KeySet ks;
ks.append(Key("user/available",
KEY_VALUE, "12",
KEY_END));
Context c;
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv
(ks, c, Key("/",
ckdb::KDB_O_CASCADING_NAME,
KEY_META, "default", "88",
KEY_META, "override/#0", "user/available",
KEY_END));
EXPECT_EQ(cv, 12);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
c.activate<RootLayer>();
EXPECT_EQ(cv, 40);
}
|
#include <contextual.hpp>
#include <gtest/gtest.h>
class MyStaticGetPolicy
{
public:
static kdb::Key get(ELEKTRA_UNUSED kdb::KeySet & ks,
ELEKTRA_UNUSED kdb::Key const& spec)
{
kdb::Key k("user/test",
KEY_VALUE, "23",
KEY_END);
return k;
}
};
TEST(test_contextual, staticGetPolicy)
{
using namespace kdb;
KeySet ks;
Context c;
ContextualValue<int, GetPolicyIs<MyStaticGetPolicy>> cv
(ks, c, Key("/test",
ckdb::KDB_O_CASCADING_NAME,
KEY_VALUE, "/test",
KEY_META, "default", "88",
KEY_END));
EXPECT_EQ(cv, 23);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
ContextualValue<int, GetPolicyIs<MyStaticGetPolicy>> cv2(cv);
EXPECT_EQ(cv, cv2);
}
class MyDynamicGetPolicy
{
public:
static kdb::Key get(ELEKTRA_UNUSED kdb::KeySet & ks,
ELEKTRA_UNUSED kdb::Key const& spec)
{
return ksLookupBySpec(ks.getKeySet(), *spec);
}
};
TEST(test_contextual, dynamicGetPolicy)
{
using namespace kdb;
KeySet ks;
ks.append(Key("user/available",
KEY_VALUE, "12",
KEY_END));
Context c;
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv
(ks, c, Key("/test",
ckdb::KDB_O_CASCADING_NAME,
KEY_META, "default", "88",
KEY_META, "override/#0", "user/available",
KEY_END));
EXPECT_EQ(cv, 12);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv2(cv);
EXPECT_EQ(cv, cv2);
}
struct RootLayer : kdb::Layer
{
std::string id() const override
{
return "root";
}
std::string operator()() const override
{
return "root";
}
};
TEST(test_contextual, root)
{
using namespace kdb;
KeySet ks;
ks.append(Key("user/available",
KEY_VALUE, "12",
KEY_END));
Context c;
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv
(ks, c, Key("/",
ckdb::KDB_O_CASCADING_NAME,
KEY_META, "default", "88",
KEY_META, "override/#0", "user/available",
KEY_END));
EXPECT_EQ(cv, 12);
EXPECT_EQ(cv, cv);
cv = 40;
EXPECT_EQ(cv, 40);
c.activate<RootLayer>();
EXPECT_EQ(cv, 40);
ContextualValue<int, GetPolicyIs<MyDynamicGetPolicy>> cv2(cv);
EXPECT_EQ(cv, cv2);
}
class MyCV : public kdb::ContextualValue<int, kdb::GetPolicyIs<MyStaticGetPolicy>>
{
public:
MyCV(kdb::KeySet & ks_, kdb::Context & context_)
: ContextualValue<int, kdb::GetPolicyIs<MyStaticGetPolicy>>(ks_,
context_,
kdb::Key(
"/",
ckdb::KDB_O_CASCADING_NAME,
KEY_END))
{}
};
TEST(test_contextual, myCVRoot)
{
using namespace kdb;
KeySet ks;
Context c;
MyCV m(ks, c);
EXPECT_EQ(m, 23);
}
class none_t
{};
namespace kdb {
template <>
inline void Key::set(none_t)
{}
template <>
inline none_t Key::get() const
{
none_t ret;
return ret;
}
}
class MyCV2 : public kdb::ContextualValue<none_t, kdb::GetPolicyIs<MyStaticGetPolicy>>
{
public:
MyCV2(kdb::KeySet & ks_, kdb::Context & context_)
: ContextualValue<none_t, kdb::GetPolicyIs<MyStaticGetPolicy>>(ks_,
context_,
kdb::Key(
"/",
ckdb::KDB_O_CASCADING_NAME,
KEY_END)),
m_m(ks_, context_)
{}
MyCV m_m;
};
TEST(test_contextual, myCV2Root)
{
using namespace kdb;
KeySet ks;
Context c;
MyCV2 m(ks, c);
}
|
add some more tests
|
add some more tests
|
C++
|
bsd-3-clause
|
ElektraInitiative/libelektra,mpranj/libelektra,petermax2/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,mpranj/libelektra,e1528532/libelektra,mpranj/libelektra,mpranj/libelektra,BernhardDenner/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,mpranj/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,e1528532/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,mpranj/libelektra,mpranj/libelektra,BernhardDenner/libelektra,e1528532/libelektra,BernhardDenner/libelektra,e1528532/libelektra,BernhardDenner/libelektra,petermax2/libelektra,BernhardDenner/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,ElektraInitiative/libelektra
|
e9d58fa23c5a0e0889276f8d1ebf43bb63a38f2c
|
plugins/multimedia/directshow/player/directshowaudioendpointcontrol.cpp
|
plugins/multimedia/directshow/player/directshowaudioendpointcontrol.cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "directshowaudioendpointcontrol.h"
#include "directshowglobal.h"
#include "directshowplayerservice.h"
DirectShowAudioEndpointControl::DirectShowAudioEndpointControl(
DirectShowPlayerService *service, QObject *parent)
: QAudioEndpointSelector(parent)
, m_service(service)
, m_bindContext(0)
, m_deviceEnumerator(0)
{
if (CreateBindCtx(0, &m_bindContext) == S_OK) {
m_deviceEnumerator = com_new<ICreateDevEnum>(CLSID_SystemDeviceEnum);
updateEndpoints();
setActiveEndpoint(m_defaultEndpoint);
}
}
DirectShowAudioEndpointControl::~DirectShowAudioEndpointControl()
{
foreach (IMoniker *moniker, m_devices)
moniker->Release();
if (m_bindContext)
m_bindContext->Release();
if (m_deviceEnumerator)
m_deviceEnumerator->Release();
}
QList<QString> DirectShowAudioEndpointControl::availableEndpoints() const
{
return m_devices.keys();
}
QString DirectShowAudioEndpointControl::endpointDescription(const QString &name) const
{
return name.section(QLatin1Char('\\'), -1);
}
QString DirectShowAudioEndpointControl::defaultEndpoint() const
{
return m_defaultEndpoint;
}
QString DirectShowAudioEndpointControl::activeEndpoint() const
{
return m_activeEndpoint;
}
void DirectShowAudioEndpointControl::setActiveEndpoint(const QString &name)
{
if (m_activeEndpoint == name)
return;
if (IMoniker *moniker = m_devices.value(name, 0)) {
IBaseFilter *filter = 0;
if (moniker->BindToObject(
m_bindContext,
0,
__uuidof(IBaseFilter),
reinterpret_cast<void **>(&filter)) == S_OK) {
m_service->setAudioOutput(filter);
filter->Release();
}
}
}
void DirectShowAudioEndpointControl::updateEndpoints()
{
IMalloc *oleMalloc = 0;
if (m_deviceEnumerator && CoGetMalloc(1, &oleMalloc) == S_OK) {
IEnumMoniker *monikers = 0;
if (m_deviceEnumerator->CreateClassEnumerator(
CLSID_AudioRendererCategory, &monikers, 0) == S_OK) {
for (IMoniker *moniker = 0; monikers->Next(1, &moniker, 0) == S_OK; moniker->Release()) {
OLECHAR *string = 0;
if (moniker->GetDisplayName(m_bindContext, 0, &string) == S_OK) {
QString deviceId = QString::fromWCharArray(string);
oleMalloc->Free(string);
moniker->AddRef();
m_devices.insert(deviceId, moniker);
if (m_defaultEndpoint.isEmpty()
|| deviceId.endsWith(QLatin1String("Default DirectSound Device"))) {
m_defaultEndpoint = deviceId;
}
}
}
monikers->Release();
}
oleMalloc->Release();
}
}
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "directshowaudioendpointcontrol.h"
#include "directshowglobal.h"
#include "directshowplayerservice.h"
DirectShowAudioEndpointControl::DirectShowAudioEndpointControl(
DirectShowPlayerService *service, QObject *parent)
: QAudioEndpointSelector(parent)
, m_service(service)
, m_bindContext(0)
, m_deviceEnumerator(0)
{
if (CreateBindCtx(0, &m_bindContext) == S_OK) {
m_deviceEnumerator = com_new<ICreateDevEnum>(CLSID_SystemDeviceEnum);
updateEndpoints();
setActiveEndpoint(m_defaultEndpoint);
}
}
DirectShowAudioEndpointControl::~DirectShowAudioEndpointControl()
{
foreach (IMoniker *moniker, m_devices)
moniker->Release();
if (m_bindContext)
m_bindContext->Release();
if (m_deviceEnumerator)
m_deviceEnumerator->Release();
}
QList<QString> DirectShowAudioEndpointControl::availableEndpoints() const
{
return m_devices.keys();
}
QString DirectShowAudioEndpointControl::endpointDescription(const QString &name) const
{
QString description;
if (IMoniker *moniker = m_devices.value(name, 0)) {
IPropertyBag *propertyBag = 0;
if (SUCCEEDED(moniker->BindToStorage(
0, 0, IID_IPropertyBag, reinterpret_cast<void **>(&propertyBag)))) {
VARIANT name;
VariantInit(&name);
if (SUCCEEDED(propertyBag->Read(L"FriendlyName", &name, 0)))
description = QString::fromWCharArray(name.bstrVal);
VariantClear(&name);
propertyBag->Release();
}
}
return description;;
}
QString DirectShowAudioEndpointControl::defaultEndpoint() const
{
return m_defaultEndpoint;
}
QString DirectShowAudioEndpointControl::activeEndpoint() const
{
return m_activeEndpoint;
}
void DirectShowAudioEndpointControl::setActiveEndpoint(const QString &name)
{
if (m_activeEndpoint == name)
return;
if (IMoniker *moniker = m_devices.value(name, 0)) {
IBaseFilter *filter = 0;
if (moniker->BindToObject(
m_bindContext,
0,
__uuidof(IBaseFilter),
reinterpret_cast<void **>(&filter)) == S_OK) {
m_service->setAudioOutput(filter);
filter->Release();
}
}
}
void DirectShowAudioEndpointControl::updateEndpoints()
{
IMalloc *oleMalloc = 0;
if (m_deviceEnumerator && CoGetMalloc(1, &oleMalloc) == S_OK) {
IEnumMoniker *monikers = 0;
if (m_deviceEnumerator->CreateClassEnumerator(
CLSID_AudioRendererCategory, &monikers, 0) == S_OK) {
for (IMoniker *moniker = 0; monikers->Next(1, &moniker, 0) == S_OK; moniker->Release()) {
OLECHAR *string = 0;
if (moniker->GetDisplayName(m_bindContext, 0, &string) == S_OK) {
QString deviceId = QString::fromWCharArray(string);
oleMalloc->Free(string);
moniker->AddRef();
m_devices.insert(deviceId, moniker);
if (m_defaultEndpoint.isEmpty()
|| deviceId.endsWith(QLatin1String("Default DirectSound Device"))) {
m_defaultEndpoint = deviceId;
}
}
}
monikers->Release();
}
oleMalloc->Release();
}
}
|
Use the IPropertyBag to get audio device names.
|
Use the IPropertyBag to get audio device names.
This is instead of parsing the identifier, which isn't guaranteed to
have a readable name in it.
|
C++
|
lgpl-2.1
|
kaltsi/qt-mobility,tmcguire/qt-mobility,kaltsi/qt-mobility,tmcguire/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,qtproject/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,enthought/qt-mobility,tmcguire/qt-mobility,KDE/android-qt-mobility,tmcguire/qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,enthought/qt-mobility,qtproject/qt-mobility,qtproject/qt-mobility,KDE/android-qt-mobility,enthought/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility,kaltsi/qt-mobility
|
034a037a5f59ddcb08f77d4208ff9b15b7e7bea2
|
src/clang-cache.cpp
|
src/clang-cache.cpp
|
#include <client/client.h>
#include <server/server.h>
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int separator;
char** compile_argv;
separator = 0;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--") == 0) {
separator = i;
break;
}
}
compile_argv = argv + separator;
compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang";
/* Start the server and send the compile command. */
if (!clc::server::is_running())
clc::server::start();
/* Run the compiler and print error message if execvp returns. */
execvp(compile_argv[0], compile_argv);
err(EXIT_FAILURE, "%s", compile_argv[0]);
}
|
#include <client/client.h>
#include <server/server.h>
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int separator;
char** compile_argv;
separator = 0;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--") == 0) {
separator = i;
break;
} else if (strcmp(argv[i], "--start") == 0) {
clc::server::start();
return EXIT_SUCCESS;
} else if (strcmp(argv[i], "--stop") == 0) {
clc::server::stop();
return EXIT_SUCCESS;
}
}
compile_argv = argv + separator;
compile_argv[0] = separator >= 2 ? argv[separator - 1] : (char*) "clang";
/* Start the server and send the compile command. */
if (!clc::server::is_running())
clc::server::start();
/* Run the compiler and print error message if execvp returns. */
execvp(compile_argv[0], compile_argv);
err(EXIT_FAILURE, "%s", compile_argv[0]);
}
|
Add --start and --stop commands to manage the server.
|
Add --start and --stop commands to manage the server.
|
C++
|
bsd-3-clause
|
sas/clang-cache,sas/clang-cache
|
67872dde147ec11037bf17b162f34bd3b58506a1
|
src/exception.cpp
|
src/exception.cpp
|
//===------------------------ exception.cpp -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include "exception"
#if __APPLE__
#include <cxxabi.h>
using namespace __cxxabiv1;
#define HAVE_DEPENDENT_EH_ABI 1
#ifndef _LIBCPPABI_VERSION
using namespace __cxxabiapple;
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared libray. The globals holding the current terminate handler and
// current unexpected handler are in the ABI library.
#define __terminate_handler __cxxabiapple::__cxa_terminate_handler
#define __unexpected_handler __cxxabiapple::__cxa_unexpected_handler
#endif // _LIBCPPABI_VERSION
#elif defined(LIBCXXRT)
#include <cxxabi.h>
using namespace __cxxabiv1;
#define HAVE_DEPENDENT_EH_ABI 1
#else // __APPLE__
static std::terminate_handler __terminate_handler;
static std::unexpected_handler __unexpected_handler;
#endif // __APPLE__
#if !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)
// libcxxrt provides implementations of these functions itself.
std::unexpected_handler
std::set_unexpected(std::unexpected_handler func) _NOEXCEPT
{
return __sync_lock_test_and_set(&__unexpected_handler, func);
}
std::unexpected_handler
std::get_unexpected() _NOEXCEPT
{
return __sync_fetch_and_add(&__unexpected_handler, (std::unexpected_handler)0);
}
_ATTRIBUTE(noreturn)
void
std::unexpected()
{
(*std::get_unexpected())();
// unexpected handler should not return
std::terminate();
}
std::terminate_handler
std::set_terminate(std::terminate_handler func) _NOEXCEPT
{
return __sync_lock_test_and_set(&__terminate_handler, func);
}
std::terminate_handler
std::get_terminate() _NOEXCEPT
{
return __sync_fetch_and_add(&__terminate_handler, (std::terminate_handler)0);
}
_ATTRIBUTE(noreturn)
void
std::terminate() _NOEXCEPT
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
(*std::get_terminate())();
// handler should not return
::abort ();
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
// handler should not throw exception
::abort ();
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
#endif // !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)
bool std::uncaught_exception() _NOEXCEPT
{
#if __APPLE__
// on Darwin, there is a helper function so __cxa_get_globals is private
return __cxa_uncaught_exception();
#elif LIBCXXRT
__cxa_eh_globals * globals = __cxa_get_globals();
return (globals->uncaughtExceptions != 0);
#else // __APPLE__
#warning uncaught_exception not yet implemented
::abort();
#endif // __APPLE__
}
namespace std
{
#ifndef _LIBCPPABI_VERSION
exception::~exception() _NOEXCEPT
{
}
bad_exception::~bad_exception() _NOEXCEPT
{
}
const char* exception::what() const _NOEXCEPT
{
return "std::exception";
}
const char* bad_exception::what() const _NOEXCEPT
{
return "std::bad_exception";
}
#endif // _LIBCPPABI_VERSION
exception_ptr::~exception_ptr() _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_decrement_exception_refcount(__ptr_);
#else
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
: __ptr_(other.__ptr_)
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_increment_exception_refcount(__ptr_);
#else
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
if (__ptr_ != other.__ptr_)
{
__cxa_increment_exception_refcount(other.__ptr_);
__cxa_decrement_exception_refcount(__ptr_);
__ptr_ = other.__ptr_;
}
return *this;
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
nested_exception::nested_exception() _NOEXCEPT
: __ptr_(current_exception())
{
}
nested_exception::~nested_exception() _NOEXCEPT
{
}
_ATTRIBUTE(noreturn)
void
nested_exception::rethrow_nested() const
{
if (__ptr_ == nullptr)
terminate();
rethrow_exception(__ptr_);
}
} // std
std::exception_ptr std::current_exception() _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
// be nicer if there was a constructor that took a ptr, then
// this whole function would be just:
// return exception_ptr(__cxa_current_primary_exception());
std::exception_ptr ptr;
ptr.__ptr_ = __cxa_current_primary_exception();
return ptr;
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
void std::rethrow_exception(exception_ptr p)
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_rethrow_primary_exception(p.__ptr_);
// if p.__ptr_ is NULL, above returns so we terminate
terminate();
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
|
//===------------------------ exception.cpp -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include "exception"
#if __APPLE__
#include <cxxabi.h>
using namespace __cxxabiv1;
#define HAVE_DEPENDENT_EH_ABI 1
#ifndef _LIBCPPABI_VERSION
using namespace __cxxabiapple;
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared libray. The globals holding the current terminate handler and
// current unexpected handler are in the ABI library.
#define __terminate_handler __cxxabiapple::__cxa_terminate_handler
#define __unexpected_handler __cxxabiapple::__cxa_unexpected_handler
#endif // _LIBCPPABI_VERSION
#elif defined(LIBCXXRT)
#include <cxxabi.h>
using namespace __cxxabiv1;
#define HAVE_DEPENDENT_EH_ABI 1
#else // __APPLE__
static std::terminate_handler __terminate_handler;
static std::unexpected_handler __unexpected_handler;
#endif // __APPLE__
#if !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)
// libcxxrt provides implementations of these functions itself.
std::unexpected_handler
std::set_unexpected(std::unexpected_handler func) _NOEXCEPT
{
return __sync_lock_test_and_set(&__unexpected_handler, func);
}
std::unexpected_handler
std::get_unexpected() _NOEXCEPT
{
return __sync_fetch_and_add(&__unexpected_handler, (std::unexpected_handler)0);
}
_ATTRIBUTE(noreturn)
void
std::unexpected()
{
(*std::get_unexpected())();
// unexpected handler should not return
std::terminate();
}
std::terminate_handler
std::set_terminate(std::terminate_handler func) _NOEXCEPT
{
return __sync_lock_test_and_set(&__terminate_handler, func);
}
std::terminate_handler
std::get_terminate() _NOEXCEPT
{
return __sync_fetch_and_add(&__terminate_handler, (std::terminate_handler)0);
}
_ATTRIBUTE(noreturn)
void
std::terminate() _NOEXCEPT
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
(*std::get_terminate())();
// handler should not return
::abort ();
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
// handler should not throw exception
::abort ();
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
#endif // !defined(LIBCXXRT) && !defined(_LIBCPPABI_VERSION)
bool std::uncaught_exception() _NOEXCEPT
{
#if __APPLE__
// on Darwin, there is a helper function so __cxa_get_globals is private
return __cxa_uncaught_exception();
#elif LIBCXXRT
__cxa_eh_globals * globals = __cxa_get_globals();
return (globals->uncaughtExceptions != 0);
#else // __APPLE__
#warning uncaught_exception not yet implemented
::abort();
#endif // __APPLE__
}
namespace std
{
#ifndef _LIBCPPABI_VERSION
exception::~exception() _NOEXCEPT
{
}
bad_exception::~bad_exception() _NOEXCEPT
{
}
const char* exception::what() const _NOEXCEPT
{
return "std::exception";
}
const char* bad_exception::what() const _NOEXCEPT
{
return "std::bad_exception";
}
#endif // _LIBCPPABI_VERSION
exception_ptr::~exception_ptr() _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_decrement_exception_refcount(__ptr_);
#else
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
: __ptr_(other.__ptr_)
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_increment_exception_refcount(__ptr_);
#else
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
if (__ptr_ != other.__ptr_)
{
__cxa_increment_exception_refcount(other.__ptr_);
__cxa_decrement_exception_refcount(__ptr_);
__ptr_ = other.__ptr_;
}
return *this;
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
nested_exception::nested_exception() _NOEXCEPT
: __ptr_(current_exception())
{
}
nested_exception::~nested_exception() _NOEXCEPT
{
}
_ATTRIBUTE(noreturn)
void
nested_exception::rethrow_nested() const
{
if (__ptr_ == nullptr)
terminate();
rethrow_exception(__ptr_);
}
} // std
std::exception_ptr std::current_exception() _NOEXCEPT
{
#if HAVE_DEPENDENT_EH_ABI
// be nicer if there was a constructor that took a ptr, then
// this whole function would be just:
// return exception_ptr(__cxa_current_primary_exception());
std::exception_ptr ptr;
ptr.__ptr_ = __cxa_current_primary_exception();
return ptr;
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
_ATTRIBUTE(noreturn)
void std::rethrow_exception(exception_ptr p)
{
#if HAVE_DEPENDENT_EH_ABI
__cxa_rethrow_primary_exception(p.__ptr_);
// if p.__ptr_ is NULL, above returns so we terminate
terminate();
#else // __APPLE__
#warning exception_ptr not yet implemented
::abort();
#endif // __APPLE__
}
|
Make attributes on definition consistent with those on declaration.
|
Make attributes on definition consistent with those on declaration.
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@149701 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
|
19c7a1754ff520e165e32c922929201439c32662
|
src/cpp/session/modules/SessionThemes.cpp
|
src/cpp/session/modules/SessionThemes.cpp
|
/*
* SessionThemes.cpp
*
* Copyright (C) 2018 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionThemes.hpp"
#include <boost/bind.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
#include <r/RRoutines.hpp>
#include <r/RSexp.hpp>
#include <fstream>
#include <map>
#include <regex>
#include <string>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace themes {
namespace {
// A map from the name of the theme to the location of the file and a boolean representing
// whether or not the theme is dark.
typedef std::map<std::string, std::pair<std::string, bool> > ThemeMap;
void getThemesInLocation(const rstudio::core::FilePath& location, ThemeMap& themeMap)
{
using rstudio::core::FilePath;
if (location.isDirectory())
{
std::vector<FilePath> locationChildren;
location.children(&locationChildren);
for (const FilePath& themeFile: locationChildren)
{
if (themeFile.hasExtensionLowerCase(".rstheme"))
{
const std::string k_themeFileStr = themeFile.canonicalPath();
std::ifstream themeIFStream(k_themeFileStr);
std::string themeContents(
(std::istreambuf_iterator<char>(themeIFStream)),
(std::istreambuf_iterator<char>()));
themeIFStream.close();
std::smatch matches;
std::regex_search(
themeContents,
matches,
std::regex("rs-theme-name\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)"));
// If there's no name specified,use the name of the file
std::string name;
if (matches.size() < 2)
{
name = themeFile.stem();
}
else
{
// If there's at least one name specified, get the first one.
name = matches[1];
}
// Find out if the theme is dark or not.
std::regex_search(
themeContents,
matches,
std::regex("rs-theme-is-dark\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)"));
bool isDark = false;
if (matches.size() >= 2)
{
isDark = std::regex_match(
std::string(matches[1]),
std::regex("(?:1|t(?:rue)?))", std::regex_constants::icase));
}
if ((matches.size() < 2) ||
(!isDark &&
!std::regex_match(
std::string(matches[1]),
std::regex("(?:0|f(?:alse)?))", std::regex_constants::icase))))
{
// TODO: warning / logging about using default isDark value.
}
themeMap[name] = std::pair<std::string, bool>(k_themeFileStr, isDark);
}
}
}
}
/**
* @brief Gets the list of all RStudio editor themes.
*
* @return The list of all RStudio editor themes.
*/
SEXP rs_getThemes()
{
// List all files in the global location first.
// TODO: Windows
using rstudio::core::FilePath;
FilePath preInstalledPath = session::options.rResourcesPath().childPath("themes");
#ifdef _WIN32
FilePath globalPath = core::system::systemSettingsPath("RStudio\\themes", false);
FilePath localPath = core::system::userHomePath().childPath(".R\\rstudio\\themes");
#else
FilePath globalPath("/etc/rstudio/themes/");
FilePath localPath = core::system::userHomePath().childPath(".R/rstudio/themes/");
#endif
const char* k_globalPathAlt = std::getenv("RS_THEME_GLOBAL_HOME");
const char* k_localPathAlt = std::getenv("RS_THEME_LOCAL_HOME");
if (k_globalPathAlt)
{
globalPath = FilePath(k_globalPathAlt);
}
if (k_localPathAlt)
{
localPath = FilePath(k_localPathAlt);
}
// Intentionally get global themes before getting user specific themes so that user specific
// themes will override global ones.
ThemeMap themeMap;
getThemesInLocation(preInstalledPath, themeMap);
getThemesInLocation(globalPath, themeMap);
getThemesInLocation(localPath, themeMap);
// TODO: get default themes.
// Convert to an R list.
rstudio::r::sexp::Protect protect;
rstudio::r::sexp::ListBuilder themeListBuilder(&protect);
for (auto theme: themeMap)
{
rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect);
themeDetailsListBuilder.add("fileName", theme.second.first);
themeDetailsListBuilder.add("isDark", theme.second.second);
themeListBuilder.add(theme.first, themeDetailsListBuilder);
}
return rstudio::r::sexp::create(themeListBuilder, &protect);
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
RS_REGISTER_CALL_METHOD(rs_getThemes, 0);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionThemes.R"));
return initBlock.execute();
}
} // namespace themes
} // namespace modules
} // namespace session
} // namespace rstudio
|
/*
* SessionThemes.cpp
*
* Copyright (C) 2018 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionThemes.hpp"
#include <boost/bind.hpp>
#include <core/Error.hpp>
#include <core/Exec.hpp>
#include <core/FilePath.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/system/System.hpp>
#include <session/SessionModuleContext.hpp>
#include <r/RRoutines.hpp>
#include <r/RSexp.hpp>
#include <fstream>
#include <map>
#include <regex>
#include <string>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace themes {
namespace {
// A map from the name of the theme to the location of the file and a boolean representing
// whether or not the theme is dark.
typedef std::map<std::string, std::pair<std::string, bool> > ThemeMap;
void getThemesInLocation(const rstudio::core::FilePath& location, ThemeMap& themeMap)
{
using rstudio::core::FilePath;
if (location.isDirectory())
{
std::vector<FilePath> locationChildren;
location.children(&locationChildren);
for (const FilePath& themeFile: locationChildren)
{
if (themeFile.hasExtensionLowerCase(".rstheme"))
{
const std::string k_themeFileStr = themeFile.canonicalPath();
std::ifstream themeIFStream(k_themeFileStr);
std::string themeContents(
(std::istreambuf_iterator<char>(themeIFStream)),
(std::istreambuf_iterator<char>()));
themeIFStream.close();
std::smatch matches;
std::regex_search(
themeContents,
matches,
std::regex("rs-theme-name\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)"));
// If there's no name specified,use the name of the file
std::string name;
if (matches.size() < 2)
{
name = themeFile.stem();
}
else
{
// If there's at least one name specified, get the first one.
name = matches[1];
}
// Find out if the theme is dark or not.
std::regex_search(
themeContents,
matches,
std::regex("rs-theme-is-dark\\s*:\\s*([^\\*]+?)\\s*(?:\\*|$)"));
bool isDark = false;
if (matches.size() >= 2)
{
isDark = std::regex_match(
std::string(matches[1]),
std::regex("(?:1|t(?:rue)?))", std::regex_constants::icase));
}
if ((matches.size() < 2) ||
(!isDark &&
!std::regex_match(
std::string(matches[1]),
std::regex("(?:0|f(?:alse)?))", std::regex_constants::icase))))
{
// TODO: warning / logging about using default isDark value.
}
themeMap[name] = std::pair<std::string, bool>(k_themeFileStr, isDark);
}
}
}
}
void getAllThemes(ThemeMap& themeMap)
{
// Intentionally get global themes before getting user specific themes so that user specific
// themes will override global ones.
getThemesInLocation(preInstalledPath, themeMap);
getThemesInLocation(globalPath, themeMap);
getThemesInLocation(localPath, themeMap);
}
/**
* @brief Gets the list of all RStudio editor themes.
*
* @return The list of all RStudio editor themes.
*/
SEXP rs_getThemes()
{
// List all files in the global location first.
// TODO: Windows
using rstudio::core::FilePath;
FilePath preInstalledPath = session::options.rResourcesPath().childPath("themes");
#ifdef _WIN32
FilePath globalPath = core::system::systemSettingsPath("RStudio\\themes", false);
FilePath localPath = core::system::userHomePath().childPath(".R\\rstudio\\themes");
#else
FilePath globalPath("/etc/rstudio/themes/");
FilePath localPath = core::system::userHomePath().childPath(".R/rstudio/themes/");
#endif
const char* k_globalPathAlt = std::getenv("RS_THEME_GLOBAL_HOME");
const char* k_localPathAlt = std::getenv("RS_THEME_LOCAL_HOME");
if (k_globalPathAlt)
{
globalPath = FilePath(k_globalPathAlt);
}
if (k_localPathAlt)
{
localPath = FilePath(k_localPathAlt);
}
ThemeMap themeMap;
getAllThemes(themeMap);
// Convert to an R list.
rstudio::r::sexp::Protect protect;
rstudio::r::sexp::ListBuilder themeListBuilder(&protect);
for (auto theme: themeMap)
{
rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect);
themeDetailsListBuilder.add("fileName", theme.second.first);
themeDetailsListBuilder.add("isDark", theme.second.second);
themeListBuilder.add(theme.first, themeDetailsListBuilder);
}
return rstudio::r::sexp::create(themeListBuilder, &protect);
}
} // anonymous namespace
Error initialize()
{
using boost::bind;
using namespace module_context;
RS_REGISTER_CALL_METHOD(rs_getThemes, 0);
ExecBlock initBlock;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionThemes.R"));
return initBlock.execute();
}
} // namespace themes
} // namespace modules
} // namespace session
} // namespace rstudio
|
add function to get all themes in a map.
|
add function to get all themes in a map.
|
C++
|
agpl-3.0
|
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
|
0f81586771b5345b067b6f4b49010213f73b624c
|
chrome/browser/ui/views/tab_contents/tab_contents_container_views.cc
|
chrome/browser/ui/views/tab_contents/tab_contents_container_views.cc
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "views/fill_layout.h"
#if defined(OS_LINUX)
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"
#endif
// Some of this class is implemented in tab_contents_container.cc, where
// the implementation doesn't vary between a pure views approach and a
// native view host approach. See the header file for details.
////////////////////////////////////////////////////////////////////////////////
// TabContentsContainer, public:
TabContentsContainer::TabContentsContainer()
: tab_contents_(NULL) {
SetID(VIEW_ID_TAB_CONTAINER);
}
void TabContentsContainer::SetReservedContentsRect(
const gfx::Rect& reserved_rect) {
cached_reserved_rect_ = reserved_rect;
// TODO(anicolao): find out what this is supposed to be used for and ensure
// it's OK for touch.
}
void TabContentsContainer::ChangeTabContents(TabContents* contents) {
if (tab_contents_) {
views::View *v = static_cast<TabContentsViewViews*>(tab_contents_->view());
RemoveChildView(v);
tab_contents_->WasHidden();
RemoveObservers();
}
tab_contents_ = contents;
// When detaching the last tab of the browser ChangeTabContents is invoked
// with NULL. Don't attempt to do anything in that case.
if (tab_contents_) {
views::View *v = static_cast<TabContentsViewViews*>(contents->view());
AddChildView(v);
SetLayoutManager(new views::FillLayout());
Layout();
AddObservers();
}
}
void TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {
}
void TabContentsContainer::SetFastResize(bool fast_resize) {
}
void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,
RenderViewHost* new_host) {
NOTIMPLEMENTED(); // TODO(anicolao)
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/tab_contents_container.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container_gtk.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_container.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "views/fill_layout.h"
// Some of this class is implemented in tab_contents_container.cc, where
// the implementation doesn't vary between a pure views approach and a
// native view host approach. See the header file for details.
////////////////////////////////////////////////////////////////////////////////
// TabContentsContainer, public:
TabContentsContainer::TabContentsContainer()
: tab_contents_(NULL) {
SetID(VIEW_ID_TAB_CONTAINER);
}
void TabContentsContainer::SetReservedContentsRect(
const gfx::Rect& reserved_rect) {
cached_reserved_rect_ = reserved_rect;
// TODO(anicolao): find out what this is supposed to be used for and ensure
// it's OK for touch.
}
void TabContentsContainer::ChangeTabContents(TabContents* contents) {
if (tab_contents_) {
views::View *v = static_cast<TabContentsViewViews*>(tab_contents_->view());
RemoveChildView(v);
tab_contents_->WasHidden();
RemoveObservers();
}
tab_contents_ = contents;
// When detaching the last tab of the browser ChangeTabContents is invoked
// with NULL. Don't attempt to do anything in that case.
if (tab_contents_) {
views::View *v = static_cast<TabContentsViewViews*>(contents->view());
AddChildView(v);
SetLayoutManager(new views::FillLayout());
Layout();
AddObservers();
}
}
void TabContentsContainer::TabContentsFocused(TabContents* tab_contents) {
}
void TabContentsContainer::SetFastResize(bool fast_resize) {
}
void TabContentsContainer::RenderViewHostChanged(RenderViewHost* old_host,
RenderViewHost* new_host) {
NOTIMPLEMENTED(); // TODO(anicolao)
}
|
Revert 71837 - Do not include GTK file on Windows.
|
Revert 71837 - Do not include GTK file on Windows.
TEST=compiles
BUG=none
Review URL: http://codereview.chromium.org/6347008
[email protected]
Review URL: http://codereview.chromium.org/6303011
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@71839 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
a568aa2a9afcc06d8fbb7af177cfe7915c839b81
|
src/udpreplay.cpp
|
src/udpreplay.cpp
|
/*
Copyright (c) 2018 Erik Rigtorp <[email protected]>
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 <cstring>
#include <iostream>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <pcap/pcap.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
static const char usage[] =
" [-i iface] [-l] [-s speed] [-c millisec] [-r repeat] [-t ttl] pcap\n"
"\n"
" -i iface interface to send packets through\n"
" -l enable loopback\n"
" -c millisec constant milliseconds between packets\n"
" -r repeat number of times to loop data (-1 for infinite loop)\n"
" -s speed replay speed relative to pcap timestamps\n"
" -t ttl packet ttl\n"
" -b enable broadcast (SO_BROADCAST)";
int ifindex = 0;
int loopback = 0;
double speed = 1;
int interval = -1;
int repeat = 1;
int ttl = -1;
int broadcast = 0;
int opt;
while ((opt = getopt(argc, argv, "i:bls:c:r:t:")) != -1) {
switch (opt) {
case 'i':
ifindex = if_nametoindex(optarg);
if (ifindex == 0) {
std::cerr << "if_nametoindex: " << strerror(errno) << std::endl;
return 1;
}
break;
case 'l':
loopback = 1;
break;
case 's':
speed = std::stod(optarg);
if (speed < 0) {
std::cerr << "speed must be positive" << std::endl;
}
break;
case 'c':
interval = std::stoi(optarg);
if (interval <= 0) {
std::cerr << "interval must be positive integer" << std::endl;
return 1;
}
break;
case 'r':
repeat = std::stoi(optarg);
if (repeat != -1 && repeat <= 0) {
std::cerr << "repeat must be positive integer or -1" << std::endl;
return 1;
}
break;
case 't':
ttl = std::stoi(optarg);
if (ttl < 0) {
std::cerr << "ttl must be non-negative integer" << std::endl;
return 1;
}
break;
case 'b':
broadcast = 1;
break;
default:
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
}
if (optind >= argc) {
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
std::cerr << "socket: " << strerror(errno) << std::endl;
return 1;
}
if (ifindex != 0) {
ip_mreqn mreqn;
memset(&mreqn, 0, sizeof(mreqn));
mreqn.imr_ifindex = ifindex;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) ==
-1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (loopback != 0) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loopback,
sizeof(loopback)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (broadcast != 0) {
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast,
sizeof(broadcast)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (ttl != -1) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
char errbuf[PCAP_ERRBUF_SIZE];
for (int i = 0; repeat == -1 || i < repeat; i++) {
pcap_t *handle = pcap_open_offline(argv[optind], errbuf);
if (handle == nullptr) {
std::cerr << "pcap_open: " << errbuf << std::endl;
return 1;
}
pcap_pkthdr header;
const u_char *p;
timeval tv = {0, 0};
while ((p = pcap_next(handle, &header))) {
if (header.len != header.caplen) {
continue;
}
auto eth = reinterpret_cast<const ether_header *>(p);
// jump over and ignore vlan tag
if (ntohs(eth->ether_type) == ETHERTYPE_VLAN) {
p += 4;
eth = reinterpret_cast<const ether_header *>(p);
}
if (ntohs(eth->ether_type) != ETHERTYPE_IP) {
continue;
}
auto ip = reinterpret_cast<const struct ip *>(p + sizeof(ether_header));
if (ip->ip_v != 4) {
continue;
}
if (ip->ip_p != IPPROTO_UDP) {
continue;
}
auto udp = reinterpret_cast<const udphdr *>(p + sizeof(ether_header) +
ip->ip_hl * 4);
if (interval != -1) {
// Use constant packet rate
usleep(interval * 1000);
} else {
if (tv.tv_sec == 0) {
tv = header.ts;
}
timeval diff;
timersub(&header.ts, &tv, &diff);
tv = header.ts;
const double delay =
std::max(0.0, (diff.tv_sec * 1000000 + diff.tv_usec) * speed);
usleep(delay);
}
ssize_t len = ntohs(udp->uh_ulen) - 8;
const u_char *d = &p[sizeof(ether_header) + ip->ip_hl * 4 + sizeof(udphdr)];
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = udp->uh_dport;
addr.sin_addr = {ip->ip_dst};
auto n = sendto(fd, d, len, 0, reinterpret_cast<sockaddr *>(&addr),
sizeof(addr));
if (n != len) {
std::cerr << "sendto: " << strerror(errno) << std::endl;
return 1;
}
}
pcap_close(handle);
}
return 0;
}
|
/*
Copyright (c) 2019 Erik Rigtorp <[email protected]>
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 <cstring>
#include <iostream>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <pcap/pcap.h>
#include <unistd.h>
#define NANOSECONDS_PER_SECOND 1000000000L
int main(int argc, char *argv[]) {
static const char usage[] =
" [-i iface] [-l] [-s speed] [-c millisec] [-r repeat] [-t ttl] pcap\n"
"\n"
" -i iface interface to send packets through\n"
" -l enable loopback\n"
" -c millisec constant milliseconds between packets\n"
" -r repeat number of times to loop data (-1 for infinite loop)\n"
" -s speed replay speed relative to pcap timestamps\n"
" -t ttl packet ttl\n"
" -b enable broadcast (SO_BROADCAST)";
int ifindex = 0;
int loopback = 0;
double speed = 1;
int interval = -1;
int repeat = 1;
int ttl = -1;
int broadcast = 0;
int opt;
while ((opt = getopt(argc, argv, "i:bls:c:r:t:")) != -1) {
switch (opt) {
case 'i':
ifindex = if_nametoindex(optarg);
if (ifindex == 0) {
std::cerr << "if_nametoindex: " << strerror(errno) << std::endl;
return 1;
}
break;
case 'l':
loopback = 1;
break;
case 's':
speed = std::stod(optarg);
if (speed < 0) {
std::cerr << "speed must be positive" << std::endl;
}
break;
case 'c':
interval = std::stoi(optarg);
if (interval <= 0) {
std::cerr << "interval must be positive integer" << std::endl;
return 1;
}
break;
case 'r':
repeat = std::stoi(optarg);
if (repeat != -1 && repeat <= 0) {
std::cerr << "repeat must be positive integer or -1" << std::endl;
return 1;
}
break;
case 't':
ttl = std::stoi(optarg);
if (ttl < 0) {
std::cerr << "ttl must be non-negative integer" << std::endl;
return 1;
}
break;
case 'b':
broadcast = 1;
break;
default:
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
}
if (optind >= argc) {
std::cerr << "usage: " << argv[0] << usage << std::endl;
return 1;
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1) {
std::cerr << "socket: " << strerror(errno) << std::endl;
return 1;
}
if (ifindex != 0) {
ip_mreqn mreqn;
memset(&mreqn, 0, sizeof(mreqn));
mreqn.imr_ifindex = ifindex;
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, &mreqn, sizeof(mreqn)) ==
-1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (loopback != 0) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loopback,
sizeof(loopback)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (broadcast != 0) {
if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &broadcast,
sizeof(broadcast)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
if (ttl != -1) {
if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1) {
std::cerr << "setsockopt: " << strerror(errno) << std::endl;
return 1;
}
}
timespec deadline = {};
if (clock_gettime(CLOCK_MONOTONIC, &deadline) == -1) {
std::cerr << "clock_gettime: " << strerror(errno) << std::endl;
return 1;
}
for (int i = 0; repeat == -1 || i < repeat; i++) {
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle = pcap_open_offline_with_tstamp_precision(
argv[optind], PCAP_TSTAMP_PRECISION_NANO, errbuf);
if (handle == nullptr) {
std::cerr << "pcap_open: " << errbuf << std::endl;
return 1;
}
timespec start = {-1, -1};
timespec pcap_start = {-1, -1};
pcap_pkthdr header;
const u_char *p;
while ((p = pcap_next(handle, &header))) {
if (start.tv_nsec == -1) {
if (clock_gettime(CLOCK_MONOTONIC, &start) == -1) {
std::cerr << "clock_gettime: " << strerror(errno) << std::endl;
return 1;
}
pcap_start.tv_sec = header.ts.tv_sec;
pcap_start.tv_nsec =
header.ts.tv_usec; // Note PCAP_TSTAMP_PRECISION_NANO
}
if (header.len != header.caplen) {
continue;
}
auto eth = reinterpret_cast<const ether_header *>(p);
// jump over and ignore vlan tag
if (ntohs(eth->ether_type) == ETHERTYPE_VLAN) {
p += 4;
eth = reinterpret_cast<const ether_header *>(p);
}
if (ntohs(eth->ether_type) != ETHERTYPE_IP) {
continue;
}
auto ip = reinterpret_cast<const struct ip *>(p + sizeof(ether_header));
if (ip->ip_v != 4) {
continue;
}
if (ip->ip_p != IPPROTO_UDP) {
continue;
}
auto udp = reinterpret_cast<const udphdr *>(p + sizeof(ether_header) +
ip->ip_hl * 4);
if (interval != -1) {
// Use constant packet rate
deadline.tv_sec += interval / 1000L;
deadline.tv_nsec += interval * 1000000L;
} else {
// Next packet deadline = start + (packet ts - first packet ts) * speed
int64_t delta =
(header.ts.tv_sec - pcap_start.tv_sec) * NANOSECONDS_PER_SECOND +
(header.ts.tv_usec -
pcap_start.tv_nsec); // Note PCAP_TSTAMP_PRECISION_NANO
if (speed != 1.0) {
delta *= speed;
}
deadline = start;
deadline.tv_sec += delta / NANOSECONDS_PER_SECOND;
deadline.tv_nsec += delta % NANOSECONDS_PER_SECOND;
}
// Normalize timespec
if (deadline.tv_nsec > NANOSECONDS_PER_SECOND) {
deadline.tv_sec++;
deadline.tv_nsec -= NANOSECONDS_PER_SECOND;
}
timespec now = {};
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1) {
std::cerr << "clock_gettime: " << strerror(errno) << std::endl;
return 1;
}
if (deadline.tv_sec > now.tv_sec ||
(deadline.tv_sec == now.tv_sec && deadline.tv_nsec > now.tv_nsec)) {
if (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline,
nullptr) == -1) {
std::cerr << "clock_nanosleep: " << strerror(errno) << std::endl;
return 1;
}
}
ssize_t len = ntohs(udp->uh_ulen) - 8;
const u_char *d =
&p[sizeof(ether_header) + ip->ip_hl * 4 + sizeof(udphdr)];
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = udp->uh_dport;
addr.sin_addr = {ip->ip_dst};
auto n = sendto(fd, d, len, 0, reinterpret_cast<sockaddr *>(&addr),
sizeof(addr));
if (n != len) {
std::cerr << "sendto: " << strerror(errno) << std::endl;
return 1;
}
}
pcap_close(handle);
}
return 0;
}
|
Make packet timing more precise
|
Make packet timing more precise
Simplified version with proper error handling of @sobomax PR #17.
|
C++
|
mit
|
rigtorp/udpreplay
|
6d5dd8cdc641352fd7b1c9a49f658a19ccae84d1
|
src/dwi/tractography/connectomics/lut.cpp
|
src/dwi/tractography/connectomics/lut.cpp
|
/*
Copyright 2012 Brain Research Institute, Melbourne, Australia
Written by Robert Smith, 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 "dwi/tractography/connectomics/lut.h"
namespace MR {
namespace DWI {
namespace Tractography {
namespace Connectomics {
using namespace App;
const OptionGroup LookupTableOption = OptionGroup ("Options for importing information from parcellation lookup tables")
+ Option ("lut_basic", "get information from a basic lookup table consisting of index / name pairs")
+ Argument("path").type_file()
+ Option ("lut_freesurfer", "get information from a FreeSurfer lookup table (typically \"FreeSurferColorLUT.txt\")")
+ Argument("path").type_file()
+ Option ("lut_aal", "get information from the AAL lookup table (typically \"ROI_MNI_V4.txt\")")
+ Argument("path").type_file()
+ Option ("lut_itksnap", "get information from an ITK-SNAP lookup table (this includes the IIT atlas file \"LUT_GM.txt\")")
+ Argument("path").type_file();
// TODO Add more e.g. FSL
// FSL's HarvardOxford atlas has identical labels across left and right hemispheres...
void load_lookup_table (Node_map& nodes)
{
const node_t max_node_index = std::numeric_limits<node_t>::max();
Options opt = get_options ("lut_basic");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
sscanf (line.c_str(), "%u %s", &index, name);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname)));
}
}
line.clear();
}
}
Options opt = get_options ("lut_freesurfer");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open FreeSurfer lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
node_t r = 256, g = 256, b = 256, a = 255;
sscanf (line.c_str(), "%u %s %u %u %u %u", &index, name, &r, &g, &b, &a);
if (index != max_node_index) {
if (maxvalue (r, g, b) > 255)
throw Exception ("Lookup table " + opt[0][0] + " is malformed");
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname, r, g, b, a)));
}
}
line.clear();
}
}
opt = get_options ("lut_aal");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open AAL lookup table file");
std::string line;
char short_name[20], name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
sscanf (line.c_str(), "%s %s %u", short_name, name, &index);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname)));
}
}
line.clear();
}
}
opt = get_options ("lut_itksnap");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open ITK-SNAP lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
node_t r = 256, g = 256, b = 256;
float a = 1.0;
unsigned int label_vis = 0, mesh_vis = 0;
sscanf (line.c_str(), "%u %u %u %u %f %u %u %s", &index, &r, &g, &b, &a, &label_vis, &mesh_vis, name);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
std::string strname (name);
size_t first = strname.find_first_not_of ('\"');
if (first == std::string::npos)
first = 0;
size_t last = strname.find_last_not_of ('\"');
if (last == std::string::npos)
last = strname.size() - 1;
strname = strname.substr (first, last - first + 1);
VAR (index);
VAR (strname);
nodes.insert (std::make_pair (index, Node_info (strname, r, g, b, uint8_t(a*255.0))));
}
}
line.clear();
}
}
}
}
}
}
}
|
/*
Copyright 2012 Brain Research Institute, Melbourne, Australia
Written by Robert Smith, 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 "dwi/tractography/connectomics/lut.h"
namespace MR {
namespace DWI {
namespace Tractography {
namespace Connectomics {
using namespace App;
const OptionGroup LookupTableOption = OptionGroup ("Options for importing information from parcellation lookup tables")
+ Option ("lut_basic", "get information from a basic lookup table consisting of index / name pairs")
+ Argument("path").type_file()
+ Option ("lut_freesurfer", "get information from a FreeSurfer lookup table (typically \"FreeSurferColorLUT.txt\")")
+ Argument("path").type_file()
+ Option ("lut_aal", "get information from the AAL lookup table (typically \"ROI_MNI_V4.txt\")")
+ Argument("path").type_file()
+ Option ("lut_itksnap", "get information from an ITK-SNAP lookup table (this includes the IIT atlas file \"LUT_GM.txt\")")
+ Argument("path").type_file();
// TODO Add more e.g. FSL
// FSL's HarvardOxford atlas has identical labels across left and right hemispheres...
void load_lookup_table (Node_map& nodes)
{
const node_t max_node_index = std::numeric_limits<node_t>::max();
Options opt = get_options ("lut_basic");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
sscanf (line.c_str(), "%u %s", &index, name);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname)));
}
}
line.clear();
}
}
opt = get_options ("lut_freesurfer");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open FreeSurfer lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
node_t r = 256, g = 256, b = 256, a = 255;
sscanf (line.c_str(), "%u %s %u %u %u %u", &index, name, &r, &g, &b, &a);
if (index != max_node_index) {
if (maxvalue (r, g, b) > 255)
throw Exception ("Lookup table " + opt[0][0] + " is malformed");
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname, r, g, b, a)));
}
}
line.clear();
}
}
opt = get_options ("lut_aal");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open AAL lookup table file");
std::string line;
char short_name[20], name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
sscanf (line.c_str(), "%s %s %u", short_name, name, &index);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
const std::string strname (name);
nodes.insert (std::make_pair (index, Node_info (strname)));
}
}
line.clear();
}
}
opt = get_options ("lut_itksnap");
if (opt.size()) {
if (nodes.size())
throw Exception ("Cannot import lookup table information from multiple sources");
std::ifstream in_lut (opt[0][0].c_str(), std::ios_base::in);
if (!in_lut)
throw Exception ("Unable to open ITK-SNAP lookup table file");
std::string line;
char name [80];
while (std::getline (in_lut, line)) {
if (line[0] != '#' && line.size() > 1) {
node_t index = max_node_index;
node_t r = 256, g = 256, b = 256;
float a = 1.0;
unsigned int label_vis = 0, mesh_vis = 0;
sscanf (line.c_str(), "%u %u %u %u %f %u %u %s", &index, &r, &g, &b, &a, &label_vis, &mesh_vis, name);
if (index != max_node_index) {
if (nodes.find (index) != nodes.end())
throw Exception ("Lookup table " + opt[0][0] + " contains redundant entries");
std::string strname (name);
size_t first = strname.find_first_not_of ('\"');
if (first == std::string::npos)
first = 0;
size_t last = strname.find_last_not_of ('\"');
if (last == std::string::npos)
last = strname.size() - 1;
strname = strname.substr (first, last - first + 1);
VAR (index);
VAR (strname);
nodes.insert (std::make_pair (index, Node_info (strname, r, g, b, uint8_t(a*255.0))));
}
}
line.clear();
}
}
}
}
}
}
}
|
Fix code error in previous commit (revision 305)
|
Fix code error in previous commit (revision 305)
|
C++
|
mpl-2.0
|
MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3,MRtrix3/mrtrix3
|
519b9c44724c9166507cb90419f3c05265679c78
|
TerrainApps/CManager/PropDlg.cpp
|
TerrainApps/CManager/PropDlg.cpp
|
//
// Name: PropDlg.cpp
//
// Copyright (c) 2001-2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "PropDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "vtlib/vtlib.h"
#ifdef _MSC_VER
#pragma warning( disable : 4786 )
#endif
#include "PropDlg.h"
#include "vtdata/Content.h"
#include "Frame.h"
#include "TagDlg.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// PropDlg
//----------------------------------------------------------------------------
// WDR: event table for PropDlg
BEGIN_EVENT_TABLE(PropDlg,AutoPanel)
EVT_INIT_DIALOG(PropDlg::OnInitDialog)
EVT_TEXT( ID_ITEM, PropDlg::OnTextItem )
EVT_CHOICE( ID_TYPECHOICE, PropDlg::OnChoiceType )
EVT_CHOICE( ID_SUBTYPECHOICE, PropDlg::OnChoiceSubtype )
EVT_BUTTON( ID_ADDTAG, PropDlg::OnAddTag )
EVT_BUTTON( ID_REMOVETAG, PropDlg::OnRemoveTag )
EVT_BUTTON( ID_EDITTAG, PropDlg::OnTagEdit )
END_EVENT_TABLE()
PropDlg::PropDlg( wxWindow *parent, wxWindowID id,
const wxPoint &position, const wxSize& size, long style ) :
AutoPanel( parent, id, position, size, style )
{
m_bUpdating = false;
m_pCurrentItem = NULL;
PropDialogFunc( this, TRUE );
m_pTypeChoice = GetTypeChoice();
m_pSubtypeChoice = GetSubtypeChoice();
m_pTagList = GetTaglist();
AddValidator(ID_ITEM, &m_strItem);
AddValidator(ID_TYPECHOICE, &m_strType);
AddValidator(ID_SUBTYPECHOICE, &m_strSubtype);
}
// WDR: handler implementations for PropDlg
void PropDlg::OnAddTag( wxCommandEvent &event )
{
GetMainFrame()->RenderingPause();
TagDlg dlg(GetMainFrame(), -1, _T("Add New Tag"));
if (dlg.ShowModal() == wxID_OK)
{
vtTag tag;
tag.name = dlg.m_strName.mb_str();
tag.value = dlg.m_strValue.mb_str();
m_pCurrentItem->AddTag(tag);
UpdateTagList();
}
GetMainFrame()->RenderingResume();
}
void PropDlg::OnRemoveTag( wxCommandEvent &event )
{
int sel = m_pTagList->GetNextItem(-1, wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if (sel != -1)
{
int tagnum = m_pTagList->GetItemData(sel);
m_pCurrentItem->RemoveTag(tagnum);
UpdateTagList();
}
}
void PropDlg::OnTagEdit( wxCommandEvent &event )
{
GetMainFrame()->RenderingPause();
int sel = m_pTagList->GetNextItem(-1, wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if (sel != -1)
{
int tagnum = m_pTagList->GetItemData(sel);
vtTag *tag = m_pCurrentItem->GetTag(tagnum);
TagDlg dlg(GetMainFrame(), -1, _T("Edit Tag"));
dlg.m_strName = tag->name;
dlg.m_strValue = tag->value;
if (dlg.ShowModal() == wxID_OK)
{
tag->name = dlg.m_strName.mb_str();
tag->value = dlg.m_strValue.mb_str();
UpdateTagList();
}
}
GetMainFrame()->RenderingResume();
}
void PropDlg::OnInitDialog(wxInitDialogEvent& event)
{
char buf[80];
FILE *fp = fopen("itemtypes.txt", "rb");
if (fp)
{
Pair p;
while (fgets(buf, 80, fp))
{
// string EOL
if (buf[strlen(buf)-1] == 10) buf[strlen(buf)-1] = 0;
if (buf[strlen(buf)-1] == 13) buf[strlen(buf)-1] = 0;
if (buf[0] == '\t')
p.subtype = buf;
else
{
p.type = buf;
p.subtype = "";
}
m_types.push_back(p);
}
fclose(fp);
}
m_pTypeChoice->Clear();
for (unsigned int i = 0; i < m_types.size(); i++)
{
if (m_types[i].subtype == "")
m_pTypeChoice->Append(wxString2(m_types[i].type));
}
m_pTypeChoice->SetSelection(0);
UpdateSubtypes();
m_pTagList->ClearAll();
m_pTagList->SetSingleStyle(wxLC_REPORT);
m_pTagList->InsertColumn(0, _T("Tag"));
m_pTagList->SetColumnWidth(0, 100);
m_pTagList->InsertColumn(1, _T("Value"));
m_pTagList->SetColumnWidth(1, 120);
}
void PropDlg::OnChoiceType( wxCommandEvent &event )
{
UpdateFromControls();
UpdateSubtypes();
}
void PropDlg::OnChoiceSubtype( wxCommandEvent &event )
{
UpdateFromControls();
}
void PropDlg::OnTextItem( wxCommandEvent &event )
{
UpdateFromControls();
if (!m_bUpdating)
GetMainFrame()->RefreshTreeItems();
}
//////////////////////////////////////////////////////////////////////////
void PropDlg::UpdateSubtypes()
{
vtString type = m_pTypeChoice->GetStringSelection().mb_str();
m_pSubtypeChoice->Clear();
for (unsigned int i = 0; i < m_types.size(); i++)
{
if (m_types[i].type == type)
m_pSubtypeChoice->Append(wxString2(m_types[i].subtype));
}
if (m_pCurrentItem)
{
const char *subtype = m_pCurrentItem->GetValueString("subtype");
if (subtype)
m_pSubtypeChoice->SetStringSelection(wxString2(subtype));
}
}
void PropDlg::UpdateTagList()
{
m_pTagList->DeleteAllItems();
if (!m_pCurrentItem)
return;
int item;
vtTag *tag;
for (unsigned int i = 0; i < m_pCurrentItem->NumTags(); i++)
{
tag = m_pCurrentItem->GetTag(i);
if (!tag->name.Compare("type"))
continue;
if (!tag->name.Compare("subtype"))
continue;
item = m_pTagList->InsertItem(i, (wxString2) tag->name);
m_pTagList->SetItem(item, 1, (wxString2) tag->value);
m_pTagList->SetItemData(item, i);
}
}
void PropDlg::SetCurrentItem(vtItem *item)
{
if (item)
{
m_strItem = item->m_name;
const char *type = item->GetValueString("type");
if (type)
m_strType = type;
else
m_strType = _T("unknown");
const char *subtype = item->GetValueString("subtype");
if (subtype)
m_strSubtype = subtype;
else
m_strSubtype = _T("");
}
else
{
m_strItem = "";
m_strType = "unspecified";
}
m_pCurrentItem = item;
m_bUpdating = true;
TransferDataToWindow();
int sel = m_pTypeChoice->FindString(m_strType);
if (sel != -1)
m_pTypeChoice->SetSelection(sel);
else
m_pTypeChoice->SetSelection(0);
UpdateSubtypes();
UpdateTagList();
m_bUpdating = false;
}
void PropDlg::UpdateFromControls()
{
if (m_bUpdating)
return;
TransferDataFromWindow();
if (m_pCurrentItem)
{
m_pCurrentItem->m_name = m_strItem.mb_str();
m_pCurrentItem->SetValueString("type", m_strType.mb_str());
//if (m_strSubtype != _T(""))
m_pCurrentItem->SetValueString("subtype", m_strSubtype.mb_str());
}
}
|
//
// Name: PropDlg.cpp
//
// Copyright (c) 2001-2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "PropDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "vtlib/vtlib.h"
#ifdef _MSC_VER
#pragma warning( disable : 4786 )
#endif
#include "PropDlg.h"
#include "vtdata/Content.h"
#include "Frame.h"
#include "TagDlg.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// PropDlg
//----------------------------------------------------------------------------
// WDR: event table for PropDlg
BEGIN_EVENT_TABLE(PropDlg,AutoPanel)
EVT_INIT_DIALOG(PropDlg::OnInitDialog)
EVT_TEXT( ID_ITEM, PropDlg::OnTextItem )
EVT_CHOICE( ID_TYPECHOICE, PropDlg::OnChoiceType )
EVT_CHOICE( ID_SUBTYPECHOICE, PropDlg::OnChoiceSubtype )
EVT_BUTTON( ID_ADDTAG, PropDlg::OnAddTag )
EVT_BUTTON( ID_REMOVETAG, PropDlg::OnRemoveTag )
EVT_BUTTON( ID_EDITTAG, PropDlg::OnTagEdit )
END_EVENT_TABLE()
PropDlg::PropDlg( wxWindow *parent, wxWindowID id,
const wxPoint &position, const wxSize& size, long style ) :
AutoPanel( parent, id, position, size, style )
{
m_bUpdating = false;
m_pCurrentItem = NULL;
PropDialogFunc( this, TRUE );
m_pTypeChoice = GetTypeChoice();
m_pSubtypeChoice = GetSubtypeChoice();
m_pTagList = GetTaglist();
AddValidator(ID_ITEM, &m_strItem);
AddValidator(ID_TYPECHOICE, &m_strType);
AddValidator(ID_SUBTYPECHOICE, &m_strSubtype);
}
// WDR: handler implementations for PropDlg
void PropDlg::OnAddTag( wxCommandEvent &event )
{
GetMainFrame()->RenderingPause();
TagDlg dlg(GetMainFrame(), -1, _T("Add New Tag"));
if (dlg.ShowModal() == wxID_OK)
{
vtTag tag;
tag.name = dlg.m_strName.mb_str();
tag.value = dlg.m_strValue.mb_str();
m_pCurrentItem->AddTag(tag);
UpdateTagList();
}
GetMainFrame()->RenderingResume();
}
void PropDlg::OnRemoveTag( wxCommandEvent &event )
{
int sel = m_pTagList->GetNextItem(-1, wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if (sel != -1)
{
int tagnum = m_pTagList->GetItemData(sel);
m_pCurrentItem->RemoveTag(tagnum);
UpdateTagList();
}
}
void PropDlg::OnTagEdit( wxCommandEvent &event )
{
GetMainFrame()->RenderingPause();
int sel = m_pTagList->GetNextItem(-1, wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if (sel != -1)
{
int tagnum = m_pTagList->GetItemData(sel);
vtTag *tag = m_pCurrentItem->GetTag(tagnum);
TagDlg dlg(GetMainFrame(), -1, _T("Edit Tag"));
dlg.m_strName = tag->name;
dlg.m_strValue = tag->value;
if (dlg.ShowModal() == wxID_OK)
{
tag->name = dlg.m_strName.mb_str();
tag->value = dlg.m_strValue.mb_str();
UpdateTagList();
}
}
GetMainFrame()->RenderingResume();
}
void PropDlg::OnInitDialog(wxInitDialogEvent& event)
{
char buf[80];
FILE *fp = fopen("itemtypes.txt", "rb");
if (fp)
{
Pair p;
while (fgets(buf, 80, fp))
{
// string EOL
if (buf[strlen(buf)-1] == 10) buf[strlen(buf)-1] = 0;
if (buf[strlen(buf)-1] == 13) buf[strlen(buf)-1] = 0;
if (buf[0] == '\t')
p.subtype = buf+1;
else
{
p.type = buf;
p.subtype = "";
}
m_types.push_back(p);
}
fclose(fp);
}
m_pTypeChoice->Clear();
for (unsigned int i = 0; i < m_types.size(); i++)
{
if (m_types[i].subtype == "")
m_pTypeChoice->Append(wxString2(m_types[i].type));
}
m_pTypeChoice->SetSelection(0);
UpdateSubtypes();
m_pTagList->ClearAll();
m_pTagList->SetSingleStyle(wxLC_REPORT);
m_pTagList->InsertColumn(0, _T("Tag"));
m_pTagList->SetColumnWidth(0, 100);
m_pTagList->InsertColumn(1, _T("Value"));
m_pTagList->SetColumnWidth(1, 120);
}
void PropDlg::OnChoiceType( wxCommandEvent &event )
{
UpdateFromControls();
UpdateSubtypes();
}
void PropDlg::OnChoiceSubtype( wxCommandEvent &event )
{
UpdateFromControls();
}
void PropDlg::OnTextItem( wxCommandEvent &event )
{
UpdateFromControls();
if (!m_bUpdating)
GetMainFrame()->RefreshTreeItems();
}
//////////////////////////////////////////////////////////////////////////
void PropDlg::UpdateSubtypes()
{
vtString type = m_pTypeChoice->GetStringSelection().mb_str();
m_pSubtypeChoice->Clear();
for (unsigned int i = 0; i < m_types.size(); i++)
{
if (m_types[i].type == type)
m_pSubtypeChoice->Append(wxString2(m_types[i].subtype));
}
if (m_pCurrentItem)
{
const char *subtype = m_pCurrentItem->GetValueString("subtype");
if (subtype)
m_pSubtypeChoice->SetStringSelection(wxString2(subtype));
}
}
void PropDlg::UpdateTagList()
{
m_pTagList->DeleteAllItems();
if (!m_pCurrentItem)
return;
int item;
vtTag *tag;
for (unsigned int i = 0; i < m_pCurrentItem->NumTags(); i++)
{
tag = m_pCurrentItem->GetTag(i);
if (!tag->name.Compare("type"))
continue;
if (!tag->name.Compare("subtype"))
continue;
item = m_pTagList->InsertItem(i, (wxString2) tag->name);
m_pTagList->SetItem(item, 1, (wxString2) tag->value);
m_pTagList->SetItemData(item, i);
}
}
void PropDlg::SetCurrentItem(vtItem *item)
{
if (item)
{
m_strItem = item->m_name;
const char *type = item->GetValueString("type");
if (type)
m_strType = type;
else
m_strType = _T("unknown");
const char *subtype = item->GetValueString("subtype");
if (subtype)
m_strSubtype = subtype;
else
m_strSubtype = _T("");
}
else
{
m_strItem = "";
m_strType = "unspecified";
}
m_pCurrentItem = item;
m_bUpdating = true;
TransferDataToWindow();
int sel = m_pTypeChoice->FindString(m_strType);
if (sel != -1)
m_pTypeChoice->SetSelection(sel);
else
m_pTypeChoice->SetSelection(0);
UpdateSubtypes();
UpdateTagList();
m_bUpdating = false;
}
void PropDlg::UpdateFromControls()
{
if (m_bUpdating)
return;
TransferDataFromWindow();
if (m_pCurrentItem)
{
m_pCurrentItem->m_name = m_strItem.mb_str();
m_pCurrentItem->SetValueString("type", m_strType.mb_str());
//if (m_strSubtype != _T(""))
m_pCurrentItem->SetValueString("subtype", m_strSubtype.mb_str());
}
}
|
fix tab
|
fix tab
|
C++
|
mit
|
markraz/vtp,nakijun/vtp,nakijun/vtp,nakijun/vtp,seanisom/vtp,seanisom/vtp,seanisom/vtp,markraz/vtp,seanisom/vtp,nakijun/vtp,markraz/vtp,nakijun/vtp,markraz/vtp,markraz/vtp,seanisom/vtp
|
825fa2bb3f5aef49822c4a001fe5321b105d874c
|
include/libtorrent/bitfield.hpp
|
include/libtorrent/bitfield.hpp
|
/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t
namespace libtorrent
{
// The bitfiled type stores any number of bits as a bitfield
// in a heap allocated or borrowed array.
struct TORRENT_EXPORT bitfield
{
// constructs a new bitfield. The default constructor creates an empty
// bitfield. ``bits`` is the size of the bitfield (specified in bits).
// `` val`` is the value to initialize the bits to. If not specified
// all bits are initialized to 0.
//
// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
// from the specified buffer, and ``bits`` number of bits (rounded up to
// the nearest byte boundry).
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
{ rhs.m_bytes = NULL; }
#endif
// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
// taking ownership of the buffer. This is a way to avoid copying data and
// yet provide a raw buffer to functions that may operate on the bitfield
// type. It is the user's responsibility to make sure the passed-in buffer's
// life time exceeds all uses of the bitfield.
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
// hidden
~bitfield() { dealloc(); }
// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
// the nearest byte boundary.
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
// query bit at ``index``. Returns true if bit is 1, otherwise false.
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
// returns true if all bits in the bitfield are set
bool all_set() const
{
const int num_words = m_size / 32;
const int num_bytes = m_size / 8;
boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
for (int i = 0; i < num_words; ++i)
{
if (bits[i] != 0xffffffff) return false;
}
for (int i = num_words * 4; i < num_bytes; ++i)
{
if (m_bytes[i] != 0xff) return false;
}
int rest = m_size - num_bytes * 8;
boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
return false;
return true;
}
// returns the size of the bitfield in bits.
std::size_t size() const { return m_size; }
// returns true if the bitfield has zero size.
bool empty() const { return m_size == 0; }
// returns a pointer to the internal buffer of the bitfield.
char const* bytes() const { return (char*)m_bytes; }
// copy operator
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
// count the number of bits in the bitfield that are set to 1.
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
// the new bits are initialized to ``val``.
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void resize(int bits)
{
TORRENT_ASSERT(bits >= 0);
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else if (bits > 0)
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
// make the bitfield empty, of zero size.
void clear() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
|
/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t
#include <algorithm> // for min()
namespace libtorrent
{
// The bitfiled type stores any number of bits as a bitfield
// in a heap allocated or borrowed array.
struct TORRENT_EXPORT bitfield
{
// constructs a new bitfield. The default constructor creates an empty
// bitfield. ``bits`` is the size of the bitfield (specified in bits).
// `` val`` is the value to initialize the bits to. If not specified
// all bits are initialized to 0.
//
// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
// from the specified buffer, and ``bits`` number of bits (rounded up to
// the nearest byte boundry).
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
{ rhs.m_bytes = NULL; }
#endif
// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
// taking ownership of the buffer. This is a way to avoid copying data and
// yet provide a raw buffer to functions that may operate on the bitfield
// type. It is the user's responsibility to make sure the passed-in buffer's
// life time exceeds all uses of the bitfield.
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
// hidden
~bitfield() { dealloc(); }
// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
// the nearest byte boundary.
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
// query bit at ``index``. Returns true if bit is 1, otherwise false.
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
// returns true if all bits in the bitfield are set
bool all_set() const
{
const int num_words = m_size / 32;
const int num_bytes = m_size / 8;
boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
for (int i = 0; i < num_words; ++i)
{
if (bits[i] != 0xffffffff) return false;
}
for (int i = num_words * 4; i < num_bytes; ++i)
{
if (m_bytes[i] != 0xff) return false;
}
int rest = m_size - num_bytes * 8;
boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
return false;
return true;
}
// returns the size of the bitfield in bits.
std::size_t size() const { return m_size; }
// returns true if the bitfield has zero size.
bool empty() const { return m_size == 0; }
// returns a pointer to the internal buffer of the bitfield.
char const* bytes() const { return (char*)m_bytes; }
// copy operator
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
// count the number of bits in the bitfield that are set to 1.
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
// the new bits are initialized to ``val``.
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void resize(int bits)
{
TORRENT_ASSERT(bits >= 0);
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else if (bits > 0)
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
// make the bitfield empty, of zero size.
void clear() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
|
add missing include
|
add missing include
git-svn-id: 6ed3528c1be4534134272ad6dd050eeaa1f628d3@9839 f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
|
C++
|
bsd-3-clause
|
svn2github/libtorrent-trunk,svn2github/libtorrent-trunk,svn2github/libtorrent-trunk,svn2github/libtorrent-trunk
|
2f60e62f2409f2ebfc7cdfc5ee71a118cb13dabb
|
starleth_elevation_visualization/src/ElevationVisualization.cpp
|
starleth_elevation_visualization/src/ElevationVisualization.cpp
|
/*
* ElevationVisualization.cpp
*
* Created on: Nov 19, 2013
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "ElevationVisualization.hpp"
// StarlETH Navigation
#include <ElevationMapTransformations.hpp>
using namespace std;
using namespace ros;
using namespace Eigen;
namespace starleth_elevation_visualization {
ElevationVisualization::ElevationVisualization(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle)
{
ROS_INFO("StarlETH elevation visualization node started.");
readParameters();
mapSubscriber_ = nodeHandle_.subscribe(mapTopic_, 1, &ElevationVisualization::elevationMapCallback, this);
mapMarkerArrayPublisher_ = nodeHandle_.advertise<visualization_msgs::MarkerArray>("elevation_map_marker_array", 1, true);
initializeVisualization();
}
ElevationVisualization::~ElevationVisualization()
{
// TODO Auto-generated destructor stub
}
bool ElevationVisualization::readParameters()
{
nodeHandle_.param("elevation_map_topic", mapTopic_, string("/elevation_map"));
nodeHandle_.param("marker_height", markerHeight_, 0.25);
return true;
}
bool ElevationVisualization::initializeVisualization()
{
mapMarkerArrayMessage_.markers.resize((int)MarkerTypes::Count); // Could add more marker types here
auto& elevationMarker = mapMarkerArrayMessage_.markers.at((int)MarkerTypes::ElevationMap);
elevationMarker.id = (int)MarkerTypes::ElevationMap;
elevationMarker.ns = "elevation_map";
elevationMarker.lifetime = ros::Duration();
elevationMarker.type = visualization_msgs::Marker::CUBE_LIST;
elevationMarker.scale.z = markerHeight_;
elevationMarker.action = visualization_msgs::Marker::ADD;
return true;
}
void ElevationVisualization::elevationMapCallback(
const starleth_elevation_msg::ElevationMap& map)
{
if (mapMarkerArrayPublisher_.getNumSubscribers () < 1) return;
ROS_DEBUG("ElevationVisualization received an elevation map (time stamp %f) for visualization.", map.header.stamp.toSec());
if (!generateVisualization(map))
{
ROS_ERROR("ElevationVisualization: Generating visualization failed.");
return;
}
mapMarkerArrayPublisher_.publish(mapMarkerArrayMessage_);
}
bool ElevationVisualization::generateVisualization(
const starleth_elevation_msg::ElevationMap& map)
{
unsigned int nCells = map.elevation.layout.dim.at(0).stride;
ROS_DEBUG("ElevationVisualization: Elevation data has has %i cells.", nCells);
// Set marker info for elevation map
auto& elevationMarker = mapMarkerArrayMessage_.markers.at((int)MarkerTypes::ElevationMap);
elevationMarker.header = map.header;
elevationMarker.scale.x = map.resolution;
elevationMarker.scale.y = map.resolution;
// Clear points
elevationMarker.points.clear();
elevationMarker.colors.clear();
for (unsigned int i = 0; i < starleth_elevation_msg::getRows(map.elevation); ++i)
{
for (unsigned int j = 0; j < starleth_elevation_msg::getCols(map.elevation); ++j)
{
// Getting elevation value
Vector2i cellIndex(i, j);
unsigned int elevationDataIndex = starleth_elevation_msg::get1dIndexFrom2dIndex(cellIndex, map);
double elevation = map.elevation.data[elevationDataIndex];
// Do not continue for nan values
if (std::isnan(elevation))
{
continue;
}
// Getting position of cell
Vector2d position;
starleth_elevation_msg::getPositionFromIndex(position, Vector2i(i, j), map);
// Add marker point
geometry_msgs::Point point;
point.x = position.x();
point.y = position.y();
point.z = elevation;
elevationMarker.points.push_back(point);
// Add marker color
std_msgs::ColorRGBA color;
color.r = 0.0;
color.g = 0.3;
color.b = 1.0;
color.a = 1.0;
elevationMarker.colors.push_back(color);
}
}
return true;
}
} /* namespace starleth_elevation_visualization */
|
/*
* ElevationVisualization.cpp
*
* Created on: Nov 19, 2013
* Author: Péter Fankhauser
* Institute: ETH Zurich, Autonomous Systems Lab
*/
#include "ElevationVisualization.hpp"
// StarlETH Navigation
#include <ElevationMapHelpers.hpp>
using namespace std;
using namespace ros;
using namespace Eigen;
namespace starleth_elevation_visualization {
ElevationVisualization::ElevationVisualization(ros::NodeHandle& nodeHandle)
: nodeHandle_(nodeHandle)
{
ROS_INFO("StarlETH elevation visualization node started.");
readParameters();
mapSubscriber_ = nodeHandle_.subscribe(mapTopic_, 1, &ElevationVisualization::elevationMapCallback, this);
mapMarkerArrayPublisher_ = nodeHandle_.advertise<visualization_msgs::MarkerArray>("elevation_map_marker_array", 1, true);
initializeVisualization();
}
ElevationVisualization::~ElevationVisualization()
{
// TODO Auto-generated destructor stub
}
bool ElevationVisualization::readParameters()
{
nodeHandle_.param("elevation_map_topic", mapTopic_, string("/elevation_map"));
nodeHandle_.param("marker_height", markerHeight_, 0.25);
return true;
}
bool ElevationVisualization::initializeVisualization()
{
mapMarkerArrayMessage_.markers.resize((int)MarkerTypes::Count); // Could add more marker types here
auto& elevationMarker = mapMarkerArrayMessage_.markers.at((int)MarkerTypes::ElevationMap);
elevationMarker.id = (int)MarkerTypes::ElevationMap;
elevationMarker.ns = "elevation_map";
elevationMarker.lifetime = ros::Duration();
elevationMarker.type = visualization_msgs::Marker::CUBE_LIST;
elevationMarker.scale.z = markerHeight_;
elevationMarker.action = visualization_msgs::Marker::ADD;
return true;
}
void ElevationVisualization::elevationMapCallback(
const starleth_elevation_msg::ElevationMap& map)
{
if (mapMarkerArrayPublisher_.getNumSubscribers () < 1) return;
ROS_DEBUG("ElevationVisualization received an elevation map (time stamp %f) for visualization.", map.header.stamp.toSec());
if (!generateVisualization(map))
{
ROS_ERROR("ElevationVisualization: Generating visualization failed.");
return;
}
mapMarkerArrayPublisher_.publish(mapMarkerArrayMessage_);
}
bool ElevationVisualization::generateVisualization(
const starleth_elevation_msg::ElevationMap& map)
{
unsigned int nCells = map.elevation.layout.dim.at(0).stride;
ROS_DEBUG("ElevationVisualization: Elevation data has has %i cells.", nCells);
// Set marker info for elevation map
auto& elevationMarker = mapMarkerArrayMessage_.markers.at((int)MarkerTypes::ElevationMap);
elevationMarker.header = map.header;
elevationMarker.scale.x = map.resolution;
elevationMarker.scale.y = map.resolution;
// Clear points
elevationMarker.points.clear();
elevationMarker.colors.clear();
for (unsigned int i = 0; i < starleth_elevation_msg::getRows(map.elevation); ++i)
{
for (unsigned int j = 0; j < starleth_elevation_msg::getCols(map.elevation); ++j)
{
// Getting elevation value
Vector2i cellIndex(i, j);
unsigned int elevationDataIndex = starleth_elevation_msg::get1dIndexFrom2dIndex(cellIndex, map);
double elevation = map.elevation.data[elevationDataIndex];
// Do not continue for nan values
if (std::isnan(elevation))
{
continue;
}
// Getting position of cell
Vector2d position;
starleth_elevation_msg::getPositionFromIndex(position, Array2i(i, j), map);
// Add marker point
geometry_msgs::Point point;
point.x = position.x();
point.y = position.y();
point.z = elevation;
elevationMarker.points.push_back(point);
// Add marker color
std_msgs::ColorRGBA color;
color.r = 0.0;
color.g = 0.3;
color.b = 1.0;
color.a = 1.0;
elevationMarker.colors.push_back(color);
}
}
return true;
}
} /* namespace starleth_elevation_visualization */
|
Split up elevation message libraries
|
Split up elevation message libraries
|
C++
|
bsd-3-clause
|
ethz-asl/elevation_mapping,ethz-asl/elevation_mapping,wsAndy/elevation_mapping,wsAndy/elevation_mapping,chen0510566/elevation_mapping,chen0510566/elevation_mapping
|
8ad4bf9ff6113b34799a5abc02bb29ea0269c49a
|
include/minizinc/astiterator.hh
|
include/minizinc/astiterator.hh
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __MINIZINC_ASTITERATOR_HH__
#define __MINIZINC_ASTITERATOR_HH__
#include <minizinc/ast.hh>
#include <minizinc/hash.hh>
namespace MiniZinc {
/**
* \brief Bottom-up iterator for expressions
*/
template<class T>
class BottomUpIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Stack item
struct C {
/// Expression on the stack
Expression* _e;
/// Whether this expression has been visited before
bool _done;
/// If part of a generator expression, which one it is
int _gen_i;
/// Constructor
C(Expression* e) : _e(e), _done(false), _gen_i(-1) {}
/// Constructor for generator expression
C(Expression* e, int gen_i) : _e(e), _done(true), _gen_i(gen_i) {}
};
/// Push all elements of \a v onto \a stack
template<class E>
void pushVec(std::vector<C>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(C(v[i]));
}
public:
/// Constructor
BottomUpIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void bottomUp(T& t, Expression* e) {
BottomUpIterator<T>(t).run(e);
}
/**
* \brief Leaf iterator for expressions
*/
template<class T>
class TopDownIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Push all elements of \a v onto \a stack
template<class E>
static void pushVec(std::vector<Expression*>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(v[i]);
}
public:
/// Constructor
TopDownIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void topDown(T& t, Expression* e) {
TopDownIterator<T>(t).run(e);
}
/* IMPLEMENTATION */
template<class T> void
BottomUpIterator<T>::run(Expression* root) {
std::vector<C> stack;
if (_t.enter(root))
stack.push_back(C(root));
while (!stack.empty()) {
C& c = stack.back();
if (c._e==NULL) {
stack.pop_back();
continue;
}
if (c._done) {
switch (c._e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*c._e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*c._e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*c._e->template cast<SetLit>());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*c._e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*c._e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*c._e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*c._e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*c._e->template cast<ArrayLit>());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*c._e->template cast<ArrayAccess>());
break;
case Expression::E_COMP:
if (c._gen_i >= 0) {
_t.vComprehensionGenerator(*c._e->template cast<Comprehension>(), c._gen_i);
} else {
_t.vComprehension(*c._e->template cast<Comprehension>());
}
break;
case Expression::E_ITE:
_t.vITE(*c._e->template cast<ITE>());
break;
case Expression::E_BINOP:
_t.vBinOp(*c._e->template cast<BinOp>());
break;
case Expression::E_UNOP:
_t.vUnOp(*c._e->template cast<UnOp>());
break;
case Expression::E_CALL:
_t.vCall(*c._e->template cast<Call>());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*c._e->template cast<VarDecl>());
break;
case Expression::E_LET:
_t.vLet(*c._e->template cast<Let>());
break;
case Expression::E_TI:
_t.vTypeInst(*c._e->template cast<TypeInst>());
break;
case Expression::E_TIID:
_t.vTIId(*c._e->template cast<TIId>());
break;
}
_t.exit(c._e);
stack.pop_back();
} else {
c._done=true;
Expression* ce = c._e;
for (ExpressionSetIter it = ce->ann().begin(); it != ce->ann().end(); ++it) {
if (_t.enter(*it))
stack.push_back(C(*it));
}
if (_t.enter(ce)) {
switch (ce->eid()) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
break;
case Expression::E_SETLIT:
pushVec(stack, ce->template cast<SetLit>()->v());
break;
case Expression::E_ARRAYLIT:
pushVec(stack, ce->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
pushVec(stack, ce->template cast<ArrayAccess>()->idx());
stack.push_back(C(ce->template cast<ArrayAccess>()->v()));
break;
case Expression::E_COMP:
{
Comprehension* comp = ce->template cast<Comprehension>();
stack.push_back(C(comp->e()));
stack.push_back(C(comp->where()));
for (unsigned int i=comp->n_generators(); i--; ) {
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(C(comp->decl(i, j)));
}
stack.push_back(C(comp,i));
stack.push_back(C(comp->in(i)));
}
}
break;
case Expression::E_ITE:
{
ITE* ite = ce->template cast<ITE>();
stack.push_back(C(ite->e_else()));
for (int i=0; i<ite->size(); i++) {
stack.push_back(C(ite->e_if(i)));
stack.push_back(C(ite->e_then(i)));
}
}
break;
case Expression::E_BINOP:
stack.push_back(C(ce->template cast<BinOp>()->rhs()));
stack.push_back(C(ce->template cast<BinOp>()->lhs()));
break;
case Expression::E_UNOP:
stack.push_back(C(ce->template cast<UnOp>()->e()));
break;
case Expression::E_CALL:
pushVec(stack, ce->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
stack.push_back(C(ce->template cast<VarDecl>()->e()));
stack.push_back(C(ce->template cast<VarDecl>()->ti()));
break;
case Expression::E_LET:
stack.push_back(C(ce->template cast<Let>()->in()));
pushVec(stack, ce->template cast<Let>()->let());
break;
case Expression::E_TI:
stack.push_back(C(ce->template cast<TypeInst>()->domain()));
pushVec(stack,ce->template cast<TypeInst>()->ranges());
break;
}
} else {
c._e = NULL;
}
}
}
}
template<class T> void
TopDownIterator<T>::run(Expression* root) {
std::vector<Expression*> stack;
if (_t.enter(root))
stack.push_back(root);
while (!stack.empty()) {
Expression* e = stack.back();
stack.pop_back();
if (e==NULL) {
continue;
}
switch (e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*e->template cast<SetLit>());
pushVec(stack, e->template cast<SetLit>()->v());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*e->template cast<ArrayLit>());
pushVec(stack, e->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*e->template cast<ArrayAccess>());
pushVec(stack, e->template cast<ArrayAccess>()->idx());
stack.push_back(e->template cast<ArrayAccess>()->v());
break;
case Expression::E_COMP:
_t.vComprehension(*e->template cast<Comprehension>());
{
Comprehension* comp = e->template cast<Comprehension>();
stack.push_back(comp->where());
for (unsigned int i=comp->n_generators(); i--; ) {
stack.push_back(comp->in(i));
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(comp->decl(i, j));
}
}
stack.push_back(comp->e());
}
break;
case Expression::E_ITE:
_t.vITE(*e->template cast<ITE>());
{
ITE* ite = e->template cast<ITE>();
stack.push_back(ite->e_else());
for (int i=0; i<ite->size(); i++) {
stack.push_back(ite->e_if(i));
stack.push_back(ite->e_then(i));
}
}
break;
case Expression::E_BINOP:
_t.vBinOp(*e->template cast<BinOp>());
stack.push_back(e->template cast<BinOp>()->rhs());
stack.push_back(e->template cast<BinOp>()->lhs());
break;
case Expression::E_UNOP:
_t.vUnOp(*e->template cast<UnOp>());
stack.push_back(e->template cast<UnOp>()->e());
break;
case Expression::E_CALL:
_t.vCall(*e->template cast<Call>());
pushVec(stack, e->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*e->template cast<VarDecl>());
stack.push_back(e->template cast<VarDecl>()->e());
stack.push_back(e->template cast<VarDecl>()->ti());
break;
case Expression::E_LET:
_t.vLet(*e->template cast<Let>());
stack.push_back(e->template cast<Let>()->in());
pushVec(stack, e->template cast<Let>()->let());
break;
case Expression::E_TI:
_t.vTypeInst(*e->template cast<TypeInst>());
stack.push_back(e->template cast<TypeInst>()->domain());
pushVec(stack,e->template cast<TypeInst>()->ranges());
break;
case Expression::E_TIID:
_t.vTIId(*e->template cast<TIId>());
break;
}
}
}
}
#endif
|
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __MINIZINC_ASTITERATOR_HH__
#define __MINIZINC_ASTITERATOR_HH__
#include <minizinc/ast.hh>
#include <minizinc/hash.hh>
namespace MiniZinc {
/**
* \brief Bottom-up iterator for expressions
*/
template<class T>
class BottomUpIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Stack item
struct C {
/// Expression on the stack
Expression* _e;
/// Whether this expression has been visited before
bool _done;
/// If part of a generator expression, which one it is
int _gen_i;
/// Constructor
C(Expression* e) : _e(e), _done(false), _gen_i(-1) {}
/// Constructor for generator expression
C(Expression* e, int gen_i) : _e(e), _done(true), _gen_i(gen_i) {}
};
/// Push all elements of \a v onto \a stack
template<class E>
void pushVec(std::vector<C>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(C(v[i]));
}
public:
/// Constructor
BottomUpIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void bottomUp(T& t, Expression* e) {
BottomUpIterator<T>(t).run(e);
}
/**
* \brief Leaf iterator for expressions
*/
template<class T>
class TopDownIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Push all elements of \a v onto \a stack
template<class E>
static void pushVec(std::vector<Expression*>& stack, ASTExprVec<E> v) {
for (unsigned int i=0; i<v.size(); i++)
stack.push_back(v[i]);
}
public:
/// Constructor
TopDownIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* e);
};
template<class T>
void topDown(T& t, Expression* e) {
TopDownIterator<T>(t).run(e);
}
/* IMPLEMENTATION */
template<class T> void
BottomUpIterator<T>::run(Expression* root) {
std::vector<C> stack;
if (_t.enter(root))
stack.push_back(C(root));
while (!stack.empty()) {
C& c = stack.back();
if (c._e==NULL) {
stack.pop_back();
continue;
}
if (c._done) {
switch (c._e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*c._e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*c._e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*c._e->template cast<SetLit>());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*c._e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*c._e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*c._e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*c._e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*c._e->template cast<ArrayLit>());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*c._e->template cast<ArrayAccess>());
break;
case Expression::E_COMP:
if (c._gen_i >= 0) {
_t.vComprehensionGenerator(*c._e->template cast<Comprehension>(), c._gen_i);
} else {
_t.vComprehension(*c._e->template cast<Comprehension>());
}
break;
case Expression::E_ITE:
_t.vITE(*c._e->template cast<ITE>());
break;
case Expression::E_BINOP:
_t.vBinOp(*c._e->template cast<BinOp>());
break;
case Expression::E_UNOP:
_t.vUnOp(*c._e->template cast<UnOp>());
break;
case Expression::E_CALL:
_t.vCall(*c._e->template cast<Call>());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*c._e->template cast<VarDecl>());
break;
case Expression::E_LET:
_t.vLet(*c._e->template cast<Let>());
break;
case Expression::E_TI:
_t.vTypeInst(*c._e->template cast<TypeInst>());
break;
case Expression::E_TIID:
_t.vTIId(*c._e->template cast<TIId>());
break;
}
_t.exit(c._e);
stack.pop_back();
} else {
c._done=true;
Expression* ce = c._e;
for (ExpressionSetIter it = ce->ann().begin(); it != ce->ann().end(); ++it) {
if (_t.enter(*it))
stack.push_back(C(*it));
}
if (_t.enter(ce)) {
switch (ce->eid()) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
break;
case Expression::E_SETLIT:
pushVec(stack, ce->template cast<SetLit>()->v());
break;
case Expression::E_ARRAYLIT:
pushVec(stack, ce->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
pushVec(stack, ce->template cast<ArrayAccess>()->idx());
stack.push_back(C(ce->template cast<ArrayAccess>()->v()));
break;
case Expression::E_COMP:
{
Comprehension* comp = ce->template cast<Comprehension>();
stack.push_back(C(comp->e()));
stack.push_back(C(comp->where()));
for (unsigned int i=comp->n_generators(); i--; ) {
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(C(comp->decl(i, j)));
}
stack.push_back(C(comp,i));
stack.push_back(C(comp->in(i)));
}
}
break;
case Expression::E_ITE:
{
ITE* ite = ce->template cast<ITE>();
stack.push_back(C(ite->e_else()));
for (int i=0; i<ite->size(); i++) {
stack.push_back(C(ite->e_if(i)));
stack.push_back(C(ite->e_then(i)));
}
}
break;
case Expression::E_BINOP:
stack.push_back(C(ce->template cast<BinOp>()->rhs()));
stack.push_back(C(ce->template cast<BinOp>()->lhs()));
break;
case Expression::E_UNOP:
stack.push_back(C(ce->template cast<UnOp>()->e()));
break;
case Expression::E_CALL:
pushVec(stack, ce->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
stack.push_back(C(ce->template cast<VarDecl>()->e()));
stack.push_back(C(ce->template cast<VarDecl>()->ti()));
break;
case Expression::E_LET:
stack.push_back(C(ce->template cast<Let>()->in()));
pushVec(stack, ce->template cast<Let>()->let());
break;
case Expression::E_TI:
stack.push_back(C(ce->template cast<TypeInst>()->domain()));
pushVec(stack,ce->template cast<TypeInst>()->ranges());
break;
}
} else {
c._e = NULL;
}
}
}
}
template<class T> void
TopDownIterator<T>::run(Expression* root) {
std::vector<Expression*> stack;
if (_t.enter(root))
stack.push_back(root);
while (!stack.empty()) {
Expression* e = stack.back();
stack.pop_back();
if (e==NULL) {
continue;
}
if (!_t.enter(e))
continue;
switch (e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*e->template cast<SetLit>());
pushVec(stack, e->template cast<SetLit>()->v());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*e->template cast<ArrayLit>());
pushVec(stack, e->template cast<ArrayLit>()->v());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*e->template cast<ArrayAccess>());
pushVec(stack, e->template cast<ArrayAccess>()->idx());
stack.push_back(e->template cast<ArrayAccess>()->v());
break;
case Expression::E_COMP:
_t.vComprehension(*e->template cast<Comprehension>());
{
Comprehension* comp = e->template cast<Comprehension>();
stack.push_back(comp->where());
for (unsigned int i=comp->n_generators(); i--; ) {
stack.push_back(comp->in(i));
for (unsigned int j=comp->n_decls(i); j--; ) {
stack.push_back(comp->decl(i, j));
}
}
stack.push_back(comp->e());
}
break;
case Expression::E_ITE:
_t.vITE(*e->template cast<ITE>());
{
ITE* ite = e->template cast<ITE>();
stack.push_back(ite->e_else());
for (int i=0; i<ite->size(); i++) {
stack.push_back(ite->e_if(i));
stack.push_back(ite->e_then(i));
}
}
break;
case Expression::E_BINOP:
_t.vBinOp(*e->template cast<BinOp>());
stack.push_back(e->template cast<BinOp>()->rhs());
stack.push_back(e->template cast<BinOp>()->lhs());
break;
case Expression::E_UNOP:
_t.vUnOp(*e->template cast<UnOp>());
stack.push_back(e->template cast<UnOp>()->e());
break;
case Expression::E_CALL:
_t.vCall(*e->template cast<Call>());
pushVec(stack, e->template cast<Call>()->args());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*e->template cast<VarDecl>());
stack.push_back(e->template cast<VarDecl>()->e());
stack.push_back(e->template cast<VarDecl>()->ti());
break;
case Expression::E_LET:
_t.vLet(*e->template cast<Let>());
stack.push_back(e->template cast<Let>()->in());
pushVec(stack, e->template cast<Let>()->let());
break;
case Expression::E_TI:
_t.vTypeInst(*e->template cast<TypeInst>());
stack.push_back(e->template cast<TypeInst>()->domain());
pushVec(stack,e->template cast<TypeInst>()->ranges());
break;
case Expression::E_TIID:
_t.vTIId(*e->template cast<TIId>());
break;
}
}
}
}
#endif
|
Add enter method to top down iterator (was not used properly before)
|
Add enter method to top down iterator (was not used properly before)
|
C++
|
mpl-2.0
|
nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc
|
40a1fcb687e64fb153f4fd48c5a8088dc53ff4e9
|
src/upl/lexer.cpp
|
src/upl/lexer.cpp
|
//======================================================================
#include <upl/lexer.hpp>
#include <cstring>
//======================================================================
namespace UPL {
//======================================================================
Lexer::Lexer (InputStream & input, Error::Reporter & reporter)
: m_input (input)
, m_reporter (reporter)
, m_cur_tok ()
, m_has_error (false)
{
pop ();
}
//----------------------------------------------------------------------
bool Lexer::pop ()
{
bool token_popped = false;
if (m_cur_tok.is(TT::EOI))
return false;
while (consume_whitespace() || consume_comment());
if (pop_name() || pop_numeric_literal() | pop_string_literal() ||
pop_separator_or_operator())
{
token_popped = true;
}
if (!token_popped && !m_input.eoi()) {
Location location = m_input.location();
Char c = m_input.curr();
m_input.pop();
String value;
value += c;
m_cur_tok = Token(TT::Error, location, value);
token_popped = true;
}
if (!token_popped) {
m_cur_tok = Token(TT::EOI, m_input.location(), L"");
token_popped = true;
}
return token_popped;
}
//----------------------------------------------------------------------
bool Lexer::consume_whitespace()
{
bool consumed_input = false;
while (!m_input.eoi()) {
Char c = m_input.curr();
if (!IsWhitespace(c))
break;
m_input.pop();
consumed_input = true;
}
return consumed_input;
}
//----------------------------------------------------------------------
bool Lexer::consume_comment()
{
if (!IsCommentStarter(m_input.curr()))
return false;
while (!m_input.eoi()) {
Char c = m_input.curr();
if (IsNewline(c))
break;
m_input.pop();
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_name()
{
String name;
Location location;
if (!IsIdentStarter(m_input.curr()))
return false;
/* save location and read the name */
location = m_input.location();
while (!m_input.eoi() && IsIdentContinuer(m_input.curr())) {
name += m_input.curr();
m_input.pop();
}
/* check for bool literals */
if (IsFalseLiteral(name)) {
m_cur_tok = Token(TT::BoolLiteral, location, name, false);
return true;
}
else if (IsTrueLiteral(name)) {
m_cur_tok = Token(TT::BoolLiteral, location, name, true);
return true;
}
/* check for keywords */
TT keyword_token = StringToKeyword(name);
if (TT::Error != keyword_token)
{
m_cur_tok = Token(keyword_token, location, name);
return true;
}
/* otherwise it is a simple identifier */
m_cur_tok = Token(TT::Identifier, location, name);
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_numeric_literal()
{
String number;
Location location;
enum {
INTEGER_PART,
FRACTIONAL_PART_FIRST,
FRACTIONAL_PART_REST,
EXPONENT_SIGN,
EXPONENT_VALUE_FIRST,
EXPONENT_VALUE_REST,
DONE_INTEGER,
DONE_REAL,
ERROR
} state = INTEGER_PART;
if (!IsDigit(m_input.curr()))
return false;
location = m_input.location();
while (state != DONE_INTEGER && state != DONE_REAL && state != ERROR) {
char c = m_input.curr();
switch (state) {
case INTEGER_PART:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else if (c == UPL_PRIVATE__FRACTIONAL_SEP) {
number += c;
m_input.pop();
state = FRACTIONAL_PART_FIRST;
}
else {
state = DONE_INTEGER;
}
break;
case FRACTIONAL_PART_FIRST:
if (IsDigit(c)) {
number += c;
m_input.pop();
state = FRACTIONAL_PART_REST;
}
else {
state = ERROR;
}
break;
case FRACTIONAL_PART_REST:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else if (c == UPL_PRIVATE__EXPONENT_SEP) {
number += c;
m_input.pop();
state = EXPONENT_SIGN;
}
else {
state = DONE_REAL;
}
break;
case EXPONENT_SIGN:
if (c == UPL_PRIVATE__POSITIVE_SIGN ||
c == UPL_PRIVATE__NEGATIVE_SIGN) {
number += c;
m_input.pop();
}
state = EXPONENT_VALUE_FIRST;
break;
case EXPONENT_VALUE_FIRST:
if (IsDigit(c)) {
number += c;
m_input.pop();
state = EXPONENT_VALUE_REST;
}
else {
state = ERROR;
}
break;
case EXPONENT_VALUE_REST:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else {
state = DONE_REAL;
}
break;
}
}
if (state == DONE_INTEGER) {
Int value = stoll(number);
m_cur_tok = Token(TT::IntLiteral, location, number, value);
}
else if (state == DONE_REAL) {
Real value = stod(number);
m_cur_tok = Token(TT::RealLiteral, location, number, value);
}
else if (state == ERROR) {
m_cur_tok = Token(TT::Error, location, number);
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_string_literal()
{
String uncooked;
String value;
Location location;
bool escape = false;
bool error = false;
bool done = false;
if (!IsStringDelimiter(m_input.curr()))
return false;
location = m_input.location();
uncooked += m_input.curr();
m_input.pop();
while (!done && !error) {
char c = m_input.curr();
if (escape) {
value += EscapeCharacter(c);
uncooked += c;
m_input.pop();
escape = false;
}
else if (IsNewline(c) || c == 0) {
error = true;
}
else if (IsStringDelimiter(c)) {
uncooked += c;
m_input.pop();
done = true;
}
else if (IsStringEscapeCharacter(c)) {
uncooked += c;
m_input.pop();
escape = true;
}
else {
value += c;
uncooked += c;
m_input.pop();
}
}
if (error) {
m_cur_tok = Token(TT::Error, location, uncooked);
}
else {
m_cur_tok = Token(TT::StrLiteral, location, uncooked, value);
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_separator_or_operator()
{
TT token_type = TT::Empty;
Location location = m_input.location();
String uncooked;
/* detect single character separators */
switch (m_input.curr()) {
case UPL_PRIVATE__OPEN_BRACKET:
token_type = TT::OpenBracket;
break;
case UPL_PRIVATE__CLOSE_BRACKET:
token_type = TT::CloseBracket;
break;
case UPL_PRIVATE__OPEN_PAREN:
token_type = TT::OpenParen;
break;
case UPL_PRIVATE__CLOSE_PAREN:
token_type = TT::CloseParen;
break;
case UPL_PRIVATE__ARGUMENT_SEP:
token_type = TT::ArgumentSep;
break;
case UPL_PRIVATE__STATEMENT_SEP:
token_type = TT::StatementSep;
break;
}
if (token_type != TT::Empty) {
uncooked += m_input.curr();
m_input.pop();
m_cur_tok = Token(token_type, location, uncooked);
return true;
}
/* detect multi character separators and operators */
while (!m_input.eoi() &&
strchr(UPL_PRIVATE__OPERATOR_CHAR_SET, m_input.curr()) != NULL) {
uncooked += m_input.curr();
m_input.pop();
}
if (uncooked == UPL_PRIVATE__ASSIGNMENT)
token_type = TT::Assignment;
else if (uncooked == UPL_PRIVATE__RETURNS_SEP)
token_type = TT::ReturnsSep;
else if (uncooked.length() != 0)
token_type = TT::Operator;
if (token_type != TT::Empty) {
m_cur_tok = Token(token_type, location, uncooked);
return true;
}
else {
return false;
}
}
//----------------------------------------------------------------------
//======================================================================
} // namespace UPL
//======================================================================
|
//======================================================================
#include <upl/lexer.hpp>
#include <cstring>
//======================================================================
namespace UPL {
//======================================================================
Lexer::Lexer (InputStream & input, Error::Reporter & reporter)
: m_input (input)
, m_reporter (reporter)
, m_cur_tok ()
, m_has_error (false)
{
pop ();
}
//----------------------------------------------------------------------
bool Lexer::pop ()
{
bool token_popped = false;
if (m_cur_tok.is(TT::EOI))
return false;
while (consume_whitespace() || consume_comment());
if (pop_name() || pop_numeric_literal() | pop_string_literal() ||
pop_separator_or_operator())
{
token_popped = true;
}
if (!token_popped && !m_input.eoi()) {
Location location = m_input.location();
Char c = m_input.curr();
m_input.pop();
String value;
value += c;
m_cur_tok = Token(TT::Error, location, value);
token_popped = true;
}
if (!token_popped) {
m_cur_tok = Token(TT::EOI, m_input.location(), L"");
token_popped = true;
}
if (m_cur_tok.is(TT::Error))
m_has_error = true;
return token_popped;
}
//----------------------------------------------------------------------
bool Lexer::consume_whitespace()
{
bool consumed_input = false;
while (!m_input.eoi()) {
Char c = m_input.curr();
if (!IsWhitespace(c))
break;
m_input.pop();
consumed_input = true;
}
return consumed_input;
}
//----------------------------------------------------------------------
bool Lexer::consume_comment()
{
if (!IsCommentStarter(m_input.curr()))
return false;
while (!m_input.eoi()) {
Char c = m_input.curr();
if (IsNewline(c))
break;
m_input.pop();
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_name()
{
String name;
Location location;
if (!IsIdentStarter(m_input.curr()))
return false;
/* save location and read the name */
location = m_input.location();
while (!m_input.eoi() && IsIdentContinuer(m_input.curr())) {
name += m_input.curr();
m_input.pop();
}
/* check for bool literals */
if (IsFalseLiteral(name)) {
m_cur_tok = Token(TT::BoolLiteral, location, name, false);
return true;
}
else if (IsTrueLiteral(name)) {
m_cur_tok = Token(TT::BoolLiteral, location, name, true);
return true;
}
/* check for keywords */
TT keyword_token = StringToKeyword(name);
if (TT::Error != keyword_token)
{
m_cur_tok = Token(keyword_token, location, name);
return true;
}
/* otherwise it is a simple identifier */
m_cur_tok = Token(TT::Identifier, location, name);
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_numeric_literal()
{
String number;
Location location;
enum {
INTEGER_PART,
FRACTIONAL_PART_FIRST,
FRACTIONAL_PART_REST,
EXPONENT_SIGN,
EXPONENT_VALUE_FIRST,
EXPONENT_VALUE_REST,
DONE_INTEGER,
DONE_REAL,
ERROR
} state = INTEGER_PART;
if (!IsDigit(m_input.curr()))
return false;
location = m_input.location();
while (state != DONE_INTEGER && state != DONE_REAL && state != ERROR) {
char c = m_input.curr();
switch (state) {
case INTEGER_PART:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else if (c == UPL_PRIVATE__FRACTIONAL_SEP) {
number += c;
m_input.pop();
state = FRACTIONAL_PART_FIRST;
}
else {
state = DONE_INTEGER;
}
break;
case FRACTIONAL_PART_FIRST:
if (IsDigit(c)) {
number += c;
m_input.pop();
state = FRACTIONAL_PART_REST;
}
else {
state = ERROR;
}
break;
case FRACTIONAL_PART_REST:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else if (c == UPL_PRIVATE__EXPONENT_SEP) {
number += c;
m_input.pop();
state = EXPONENT_SIGN;
}
else {
state = DONE_REAL;
}
break;
case EXPONENT_SIGN:
if (c == UPL_PRIVATE__POSITIVE_SIGN ||
c == UPL_PRIVATE__NEGATIVE_SIGN) {
number += c;
m_input.pop();
}
state = EXPONENT_VALUE_FIRST;
break;
case EXPONENT_VALUE_FIRST:
if (IsDigit(c)) {
number += c;
m_input.pop();
state = EXPONENT_VALUE_REST;
}
else {
state = ERROR;
}
break;
case EXPONENT_VALUE_REST:
if (IsDigit(c)) {
number += c;
m_input.pop();
}
else {
state = DONE_REAL;
}
break;
}
}
if (state == DONE_INTEGER) {
Int value = stoll(number);
m_cur_tok = Token(TT::IntLiteral, location, number, value);
}
else if (state == DONE_REAL) {
Real value = stod(number);
m_cur_tok = Token(TT::RealLiteral, location, number, value);
}
else if (state == ERROR) {
m_cur_tok = Token(TT::Error, location, number);
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_string_literal()
{
String uncooked;
String value;
Location location;
bool escape = false;
bool error = false;
bool done = false;
if (!IsStringDelimiter(m_input.curr()))
return false;
location = m_input.location();
uncooked += m_input.curr();
m_input.pop();
while (!done && !error) {
char c = m_input.curr();
if (escape) {
value += EscapeCharacter(c);
uncooked += c;
m_input.pop();
escape = false;
}
else if (IsNewline(c) || c == 0) {
error = true;
}
else if (IsStringDelimiter(c)) {
uncooked += c;
m_input.pop();
done = true;
}
else if (IsStringEscapeCharacter(c)) {
uncooked += c;
m_input.pop();
escape = true;
}
else {
value += c;
uncooked += c;
m_input.pop();
}
}
if (error) {
m_cur_tok = Token(TT::Error, location, uncooked);
}
else {
m_cur_tok = Token(TT::StrLiteral, location, uncooked, value);
}
return true;
}
//----------------------------------------------------------------------
bool Lexer::pop_separator_or_operator()
{
TT token_type = TT::Empty;
Location location = m_input.location();
String uncooked;
/* detect single character separators */
switch (m_input.curr()) {
case UPL_PRIVATE__OPEN_BRACKET:
token_type = TT::OpenBracket;
break;
case UPL_PRIVATE__CLOSE_BRACKET:
token_type = TT::CloseBracket;
break;
case UPL_PRIVATE__OPEN_PAREN:
token_type = TT::OpenParen;
break;
case UPL_PRIVATE__CLOSE_PAREN:
token_type = TT::CloseParen;
break;
case UPL_PRIVATE__ARGUMENT_SEP:
token_type = TT::ArgumentSep;
break;
case UPL_PRIVATE__STATEMENT_SEP:
token_type = TT::StatementSep;
break;
}
if (token_type != TT::Empty) {
uncooked += m_input.curr();
m_input.pop();
m_cur_tok = Token(token_type, location, uncooked);
return true;
}
/* detect multi character separators and operators */
while (!m_input.eoi() &&
strchr(UPL_PRIVATE__OPERATOR_CHAR_SET, m_input.curr()) != NULL) {
uncooked += m_input.curr();
m_input.pop();
}
if (uncooked == UPL_PRIVATE__ASSIGNMENT)
token_type = TT::Assignment;
else if (uncooked == UPL_PRIVATE__RETURNS_SEP)
token_type = TT::ReturnsSep;
else if (uncooked.length() != 0)
token_type = TT::Operator;
if (token_type != TT::Empty) {
m_cur_tok = Token(token_type, location, uncooked);
return true;
}
else {
return false;
}
}
//----------------------------------------------------------------------
//======================================================================
} // namespace UPL
//======================================================================
|
Set Lexer::m_has_error on TT::Error.
|
Set Lexer::m_has_error on TT::Error.
|
C++
|
mit
|
declued/upl
|
dd03608d403d3d02c48b129d18d55caa9dc922f3
|
include/nomlib/math/helpers.hpp
|
include/nomlib/math/helpers.hpp
|
/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY 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.
******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP
#include <chrono>
#include <random>
#include <cmath>
#include "nomlib/config.hpp"
#include "nomlib/math/Point2.hpp"
namespace nom {
const double PI = 4.0 * atan ( 1.0 );
/// Returns a random number between the specified start and end numbers.
inline int32 rand ( int32 start, int32 end )
{
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rand_generator ( seed );
std::uniform_int_distribution<int32> distribution ( start, end );
return distribution ( rand_generator );
}
/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
inline const Point2d rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y )
{
Point2d p;
double rotated_x = 0;
double rotated_y = 0;
float translated_x = 0;
float translated_y = 0;
float center_x = pivot_x / 2.0f;
float center_y = pivot_y / 2.0f;
translated_x = x - center_x;
translated_y = y - center_y;
rotated_x = ( translated_x * cos ( -angle * PI / 180 ) - translated_y * sin ( -angle * PI / 180 ) );
rotated_y = ( translated_x * sin ( -angle * PI / 180 ) + translated_y * cos ( -angle * PI / 180 ) );
rotated_x += center_x;
rotated_y += center_y;
p.x = rotated_x;
p.y = rotated_y;
return p;
}
/// ...
inline double round ( double number )
{
return number < 0.0 ? ceil ( number - 0.5 ) : floor ( number + 0.5 );
}
} // namespace nom
#endif // include guard defined
|
/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY 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.
******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP
#include <chrono>
#include <random>
#include <cmath>
#include "nomlib/config.hpp"
#include "nomlib/math/Point2.hpp"
namespace nom {
const double PI = 4.0 * atan ( 1.0 );
/// Generate a random number
///
/// \return Random number between the specified start and end numbers.
inline int32 rand ( int32 start, int32 end )
{
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rand_generator ( seed );
std::uniform_int_distribution<int32> distribution ( start, end );
return distribution ( rand_generator );
}
/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
inline const Point2d rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y )
{
Point2d p;
double rotated_x = 0;
double rotated_y = 0;
float translated_x = 0;
float translated_y = 0;
float center_x = pivot_x / 2.0f;
float center_y = pivot_y / 2.0f;
translated_x = x - center_x;
translated_y = y - center_y;
rotated_x = ( translated_x * cos ( -angle * PI / 180 ) - translated_y * sin ( -angle * PI / 180 ) );
rotated_y = ( translated_x * sin ( -angle * PI / 180 ) + translated_y * cos ( -angle * PI / 180 ) );
rotated_x += center_x;
rotated_y += center_y;
p.x = rotated_x;
p.y = rotated_y;
return p;
}
/// Round a fractional value
///
/// \param number Number to round up or down
///
/// \return Rounded value
///
/// \note Round up when number > 0.5; round down when number < 0.5
template <typename T>
inline T round ( T number )
{
return number < 0.0 ? ceil ( number - 0.5 ) : floor ( number + 0.5 );
}
} // namespace nom
#endif // include guard defined
|
Update round func to use C++ templates
|
math/helpers: Update round func to use C++ templates
* Add documentation for round function
* Update documentation for rand function
|
C++
|
bsd-2-clause
|
i8degrees/nomlib,i8degrees/nomlib,i8degrees/nomlib,i8degrees/nomlib
|
fea16aa40d866ea1e0c2567691e9a87ee34c3b28
|
Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
|
Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
|
/*
* Copyright (C) 2012 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
namespace {
// URI label for a lazily decoded SkPixelRef.
const char labelLazyDecoded[] = "lazy";
} // namespace
bool DeferredImageDecoder::s_enabled = false;
DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder)
: m_allDataReceived(false)
, m_actualDecoder(actualDecoder)
, m_orientation(DefaultImageOrientation)
, m_repetitionCount(cAnimationNone)
{
}
DeferredImageDecoder::~DeferredImageDecoder()
{
}
PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption)
{
OwnPtr<ImageDecoder> actualDecoder = ImageDecoder::create(data, alphaOption, gammaAndColorOption);
return actualDecoder ? adoptPtr(new DeferredImageDecoder(actualDecoder.release())) : nullptr;
}
PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::createForTesting(PassOwnPtr<ImageDecoder> decoder)
{
return adoptPtr(new DeferredImageDecoder(decoder));
}
bool DeferredImageDecoder::isLazyDecoded(const SkBitmap& bitmap)
{
return bitmap.pixelRef()
&& bitmap.pixelRef()->getURI()
&& !memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded));
}
SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& bitmap, const SkISize& scaledSize, const SkIRect& scaledSubset)
{
LazyDecodingPixelRef* pixelRef = static_cast<LazyDecodingPixelRef*>(bitmap.pixelRef());
int rowBytes = 0;
rowBytes = SkBitmap::ComputeRowBytes(SkBitmap::kARGB_8888_Config, scaledSize.width());
SkBitmap resizedBitmap;
resizedBitmap.setConfig(SkBitmap::kARGB_8888_Config, scaledSubset.width(), scaledSubset.height(), rowBytes);
// FIXME: This code has the potential problem that multiple
// LazyDecodingPixelRefs are created even though they share the same
// scaled size and ImageFrameGenerator.
resizedBitmap.setPixelRef(new LazyDecodingPixelRef(pixelRef->frameGenerator(), scaledSize, pixelRef->frameIndex(), scaledSubset))->unref();
// See comments in createLazyDecodingBitmap().
resizedBitmap.setImmutable();
return resizedBitmap;
}
void DeferredImageDecoder::setEnabled(bool enabled)
{
s_enabled = enabled;
}
String DeferredImageDecoder::filenameExtension() const
{
return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension;
}
ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index)
{
prepareLazyDecodedFrames();
if (index < m_lazyDecodedFrames.size()) {
// ImageFrameGenerator has the latest known alpha state. There will
// be a performance boost if this frame is opaque.
m_lazyDecodedFrames[index]->setHasAlpha(m_frameGenerator->hasAlpha(index));
return m_lazyDecodedFrames[index].get();
}
if (m_actualDecoder)
return m_actualDecoder->frameBufferAtIndex(index);
return 0;
}
void DeferredImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
{
if (m_actualDecoder) {
m_data = data;
m_allDataReceived = allDataReceived;
m_actualDecoder->setData(data, allDataReceived);
prepareLazyDecodedFrames();
}
if (m_frameGenerator)
m_frameGenerator->setData(data, allDataReceived);
}
bool DeferredImageDecoder::isSizeAvailable()
{
// m_actualDecoder is 0 only if image decoding is deferred and that
// means image header decoded successfully and size is available.
return m_actualDecoder ? m_actualDecoder->isSizeAvailable() : true;
}
IntSize DeferredImageDecoder::size() const
{
return m_actualDecoder ? m_actualDecoder->size() : m_size;
}
IntSize DeferredImageDecoder::frameSizeAtIndex(size_t index) const
{
// FIXME: Frame size is assumed to be uniform. This might not be true for
// future supported codecs.
return m_actualDecoder ? m_actualDecoder->frameSizeAtIndex(index) : m_size;
}
size_t DeferredImageDecoder::frameCount()
{
return m_actualDecoder ? m_actualDecoder->frameCount() : m_lazyDecodedFrames.size();
}
int DeferredImageDecoder::repetitionCount() const
{
return m_actualDecoder ? m_actualDecoder->repetitionCount() : m_repetitionCount;
}
size_t DeferredImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
{
// If image decoding is deferred then frame buffer cache is managed by
// the compositor and this call is ignored.
return m_actualDecoder ? m_actualDecoder->clearCacheExceptFrame(clearExceptFrame) : 0;
}
bool DeferredImageDecoder::frameHasAlphaAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameHasAlphaAtIndex(index);
if (!m_frameGenerator->isMultiFrame())
return m_frameGenerator->hasAlpha(index);
return true;
}
bool DeferredImageDecoder::frameIsCompleteAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameIsCompleteAtIndex(index);
if (index < m_lazyDecodedFrames.size())
return m_lazyDecodedFrames[index]->status() == ImageFrame::FrameComplete;
return false;
}
float DeferredImageDecoder::frameDurationAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameDurationAtIndex(index);
if (index < m_lazyDecodedFrames.size())
return m_lazyDecodedFrames[index]->duration();
return 0;
}
unsigned DeferredImageDecoder::frameBytesAtIndex(size_t index) const
{
// If frame decoding is deferred then it is not managed by MemoryCache
// so return 0 here.
return m_frameGenerator ? 0 : m_actualDecoder->frameBytesAtIndex(index);
}
ImageOrientation DeferredImageDecoder::orientation() const
{
return m_actualDecoder ? m_actualDecoder->orientation() : m_orientation;
}
void DeferredImageDecoder::activateLazyDecoding()
{
if (m_frameGenerator)
return;
m_size = m_actualDecoder->size();
m_orientation = m_actualDecoder->orientation();
m_filenameExtension = m_actualDecoder->filenameExtension();
const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u);
m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_size.width(), m_size.height()), m_data, m_allDataReceived, !isSingleFrame);
}
void DeferredImageDecoder::prepareLazyDecodedFrames()
{
if (!s_enabled
|| !m_actualDecoder
|| !m_actualDecoder->isSizeAvailable()
|| m_actualDecoder->filenameExtension() == "ico"
|| m_actualDecoder->filenameExtension() == "gif")
return;
activateLazyDecoding();
const size_t previousSize = m_lazyDecodedFrames.size();
m_lazyDecodedFrames.resize(m_actualDecoder->frameCount());
for (size_t i = previousSize; i < m_lazyDecodedFrames.size(); ++i) {
OwnPtr<ImageFrame> frame(adoptPtr(new ImageFrame()));
frame->setSkBitmap(createLazyDecodingBitmap(i));
frame->setDuration(m_actualDecoder->frameDurationAtIndex(i));
frame->setStatus(m_actualDecoder->frameIsCompleteAtIndex(i) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
m_lazyDecodedFrames[i] = frame.release();
}
// The last lazy decoded frame created from previous call might be
// incomplete so update its state.
if (previousSize)
m_lazyDecodedFrames[previousSize - 1]->setStatus(m_actualDecoder->frameIsCompleteAtIndex(previousSize - 1) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
if (m_allDataReceived) {
m_repetitionCount = m_actualDecoder->repetitionCount();
m_actualDecoder.clear();
m_data = nullptr;
}
}
SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index)
{
SkISize fullSize = SkISize::Make(m_actualDecoder->size().width(), m_actualDecoder->size().height());
ASSERT(!fullSize.isEmpty());
SkIRect fullRect = SkIRect::MakeSize(fullSize);
// Creates a lazily decoded SkPixelRef that references the entire image without scaling.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, fullSize.width(), fullSize.height());
bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, fullSize, index, fullRect))->unref();
// Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef.
// FIXME: It would be more useful to give the actual image URI.
bitmap.pixelRef()->setURI(labelLazyDecoded);
// Inform the bitmap that we will never change the pixels. This is a performance hint
// subsystems that may try to cache this bitmap (e.g. pictures, pipes, gpu, pdf, etc.)
bitmap.setImmutable();
return bitmap;
}
bool DeferredImageDecoder::hotSpot(IntPoint& hotSpot) const
{
// TODO: Implement.
return m_actualDecoder ? m_actualDecoder->hotSpot(hotSpot) : false;
}
} // namespace WebCore
|
/*
* Copyright (C) 2012 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
namespace {
// URI label for a lazily decoded SkPixelRef.
const char labelLazyDecoded[] = "lazy";
} // namespace
bool DeferredImageDecoder::s_enabled = false;
DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder)
: m_allDataReceived(false)
, m_actualDecoder(actualDecoder)
, m_orientation(DefaultImageOrientation)
, m_repetitionCount(cAnimationNone)
{
}
DeferredImageDecoder::~DeferredImageDecoder()
{
}
PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption)
{
OwnPtr<ImageDecoder> actualDecoder = ImageDecoder::create(data, alphaOption, gammaAndColorOption);
return actualDecoder ? adoptPtr(new DeferredImageDecoder(actualDecoder.release())) : nullptr;
}
PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::createForTesting(PassOwnPtr<ImageDecoder> decoder)
{
return adoptPtr(new DeferredImageDecoder(decoder));
}
bool DeferredImageDecoder::isLazyDecoded(const SkBitmap& bitmap)
{
return bitmap.pixelRef()
&& bitmap.pixelRef()->getURI()
&& !memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded));
}
SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& bitmap, const SkISize& scaledSize, const SkIRect& scaledSubset)
{
LazyDecodingPixelRef* pixelRef = static_cast<LazyDecodingPixelRef*>(bitmap.pixelRef());
int rowBytes = 0;
rowBytes = SkBitmap::ComputeRowBytes(SkBitmap::kARGB_8888_Config, scaledSize.width());
SkBitmap resizedBitmap;
resizedBitmap.setConfig(SkBitmap::kARGB_8888_Config, scaledSubset.width(), scaledSubset.height(), rowBytes);
// FIXME: This code has the potential problem that multiple
// LazyDecodingPixelRefs are created even though they share the same
// scaled size and ImageFrameGenerator.
resizedBitmap.setPixelRef(new LazyDecodingPixelRef(pixelRef->frameGenerator(), scaledSize, pixelRef->frameIndex(), scaledSubset))->unref();
// See comments in createLazyDecodingBitmap().
resizedBitmap.setImmutable();
return resizedBitmap;
}
void DeferredImageDecoder::setEnabled(bool enabled)
{
s_enabled = enabled;
}
String DeferredImageDecoder::filenameExtension() const
{
return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension;
}
ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index)
{
prepareLazyDecodedFrames();
if (index < m_lazyDecodedFrames.size()) {
// ImageFrameGenerator has the latest known alpha state. There will
// be a performance boost if this frame is opaque.
m_lazyDecodedFrames[index]->setHasAlpha(m_frameGenerator->hasAlpha(index));
return m_lazyDecodedFrames[index].get();
}
if (m_actualDecoder)
return m_actualDecoder->frameBufferAtIndex(index);
return 0;
}
void DeferredImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
{
if (m_actualDecoder) {
m_data = data;
m_allDataReceived = allDataReceived;
m_actualDecoder->setData(data, allDataReceived);
prepareLazyDecodedFrames();
}
if (m_frameGenerator)
m_frameGenerator->setData(data, allDataReceived);
}
bool DeferredImageDecoder::isSizeAvailable()
{
// m_actualDecoder is 0 only if image decoding is deferred and that
// means image header decoded successfully and size is available.
return m_actualDecoder ? m_actualDecoder->isSizeAvailable() : true;
}
IntSize DeferredImageDecoder::size() const
{
return m_actualDecoder ? m_actualDecoder->size() : m_size;
}
IntSize DeferredImageDecoder::frameSizeAtIndex(size_t index) const
{
// FIXME: Frame size is assumed to be uniform. This might not be true for
// future supported codecs.
return m_actualDecoder ? m_actualDecoder->frameSizeAtIndex(index) : m_size;
}
size_t DeferredImageDecoder::frameCount()
{
return m_actualDecoder ? m_actualDecoder->frameCount() : m_lazyDecodedFrames.size();
}
int DeferredImageDecoder::repetitionCount() const
{
return m_actualDecoder ? m_actualDecoder->repetitionCount() : m_repetitionCount;
}
size_t DeferredImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
{
// If image decoding is deferred then frame buffer cache is managed by
// the compositor and this call is ignored.
return m_actualDecoder ? m_actualDecoder->clearCacheExceptFrame(clearExceptFrame) : 0;
}
bool DeferredImageDecoder::frameHasAlphaAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameHasAlphaAtIndex(index);
if (!m_frameGenerator->isMultiFrame())
return m_frameGenerator->hasAlpha(index);
return true;
}
bool DeferredImageDecoder::frameIsCompleteAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameIsCompleteAtIndex(index);
if (index < m_lazyDecodedFrames.size())
return m_lazyDecodedFrames[index]->status() == ImageFrame::FrameComplete;
return false;
}
float DeferredImageDecoder::frameDurationAtIndex(size_t index) const
{
if (m_actualDecoder)
return m_actualDecoder->frameDurationAtIndex(index);
if (index < m_lazyDecodedFrames.size())
return m_lazyDecodedFrames[index]->duration();
return 0;
}
unsigned DeferredImageDecoder::frameBytesAtIndex(size_t index) const
{
// If frame decoding is deferred then it is not managed by MemoryCache
// so return 0 here.
return m_frameGenerator ? 0 : m_actualDecoder->frameBytesAtIndex(index);
}
ImageOrientation DeferredImageDecoder::orientation() const
{
return m_actualDecoder ? m_actualDecoder->orientation() : m_orientation;
}
void DeferredImageDecoder::activateLazyDecoding()
{
if (m_frameGenerator)
return;
m_size = m_actualDecoder->size();
m_orientation = m_actualDecoder->orientation();
m_filenameExtension = m_actualDecoder->filenameExtension();
const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u);
m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_size.width(), m_size.height()), m_data, m_allDataReceived, !isSingleFrame);
}
void DeferredImageDecoder::prepareLazyDecodedFrames()
{
if (!s_enabled
|| !m_actualDecoder
|| !m_actualDecoder->isSizeAvailable()
|| m_actualDecoder->filenameExtension() == "ico")
return;
activateLazyDecoding();
const size_t previousSize = m_lazyDecodedFrames.size();
m_lazyDecodedFrames.resize(m_actualDecoder->frameCount());
for (size_t i = previousSize; i < m_lazyDecodedFrames.size(); ++i) {
OwnPtr<ImageFrame> frame(adoptPtr(new ImageFrame()));
frame->setSkBitmap(createLazyDecodingBitmap(i));
frame->setDuration(m_actualDecoder->frameDurationAtIndex(i));
frame->setStatus(m_actualDecoder->frameIsCompleteAtIndex(i) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
m_lazyDecodedFrames[i] = frame.release();
}
// The last lazy decoded frame created from previous call might be
// incomplete so update its state.
if (previousSize)
m_lazyDecodedFrames[previousSize - 1]->setStatus(m_actualDecoder->frameIsCompleteAtIndex(previousSize - 1) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
if (m_allDataReceived) {
m_repetitionCount = m_actualDecoder->repetitionCount();
m_actualDecoder.clear();
m_data = nullptr;
}
}
SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index)
{
SkISize fullSize = SkISize::Make(m_actualDecoder->size().width(), m_actualDecoder->size().height());
ASSERT(!fullSize.isEmpty());
SkIRect fullRect = SkIRect::MakeSize(fullSize);
// Creates a lazily decoded SkPixelRef that references the entire image without scaling.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, fullSize.width(), fullSize.height());
bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, fullSize, index, fullRect))->unref();
// Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef.
// FIXME: It would be more useful to give the actual image URI.
bitmap.pixelRef()->setURI(labelLazyDecoded);
// Inform the bitmap that we will never change the pixels. This is a performance hint
// subsystems that may try to cache this bitmap (e.g. pictures, pipes, gpu, pdf, etc.)
bitmap.setImmutable();
return bitmap;
}
bool DeferredImageDecoder::hotSpot(IntPoint& hotSpot) const
{
// TODO: Implement.
return m_actualDecoder ? m_actualDecoder->hotSpot(hotSpot) : false;
}
} // namespace WebCore
|
Enable deferred image decoding for GIF images
|
Enable deferred image decoding for GIF images
A better benchmark measurement is in the tree this feature is safe to
turn on.
BUG=259783,169377,260052
[email protected]
Review URL: https://codereview.chromium.org/20829002
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@155022 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
|
2a5bf325a8f34ada801dca661ecb174d7dc0eb3e
|
src/colorscheme.cpp
|
src/colorscheme.cpp
|
/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2016-2018 Vaclav Slavik
*
* 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 "colorscheme.h"
#include <wx/settings.h>
#ifdef __WXGTK__
#include <pango/pango.h>
#if PANGO_VERSION_CHECK(1,38,0)
#define SUPPORTS_BGALPHA
#endif
#else
#define SUPPORTS_BGALPHA
#endif
namespace
{
#ifdef __WXOSX__
inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
return wxColour([NSColor colorWithSRGBRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]);
}
inline bool IsDarkAppearance(NSAppearance *appearance)
{
if (@available(macOS 10.14, *))
{
NSAppearanceName appearanceName = [appearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
return [appearanceName isEqualToString:NSAppearanceNameDarkAqua];
}
else
{
return false;
}
}
#else
inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
return wxColour(r, g, b, int(a * wxALPHA_OPAQUE));
}
#endif
} // anonymous namespace
std::unique_ptr<ColorScheme::Data> ColorScheme::s_data;
bool ColorScheme::s_appModeDetermined = false;
ColorScheme::Mode ColorScheme::s_appMode = ColorScheme::Mode::Light;
wxColour ColorScheme::DoGet(Color color, Mode mode)
{
switch (color)
{
// Labels:
case Color::SecondaryLabel:
#ifdef __WXOSX__
return wxColour([NSColor secondaryLabelColor]);
#elif defined(__WXGTK__)
return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
#endif
// List items:
case Color::ItemID:
#ifdef __WXOSX__
return wxColour([NSColor tertiaryLabelColor]);
#else
return mode == Light ? "#a1a1a1" : wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT).ChangeLightness(50);
#endif
case Color::ItemFuzzy:
return mode == Dark ? sRGB(253, 178, 72) : sRGB(230, 134, 0);
case Color::ItemError:
return sRGB(225, 77, 49);
case Color::ItemContextFg:
return mode == Dark ? sRGB(180, 222, 254) : sRGB(70, 109, 137);
case Color::ItemContextBg:
return mode == Dark ? sRGB(67, 94, 147, 0.6) : sRGB(217, 232, 242);
case Color::ItemContextBgHighlighted:
#if defined(__WXMSW__)
return sRGB(255, 255, 255, 0.50);
#elif defined(SUPPORTS_BGALPHA)
return sRGB(255, 255, 255, 0.35);
#else
return DoGet(Color::ItemContextBg, mode);
#endif
// Tags:
case Color::TagContextFg:
return DoGet(Color::ItemContextFg, mode);
case Color::TagContextBg:
return DoGet(Color::ItemContextBg, mode);
case Color::TagSecondaryBg:
return mode == Dark ? sRGB(255, 255, 255, 0.5) : sRGB(0, 0, 0, 0.10);
case Color::TagErrorLineBg:
return sRGB(241, 134, 135);
case Color::TagWarningLineBg:
return mode == Dark ? sRGB(198, 171, 113) : sRGB(253, 235, 176);
case Color::TagErrorLineFg:
return sRGB(0, 0, 0, 0.8);
case Color::TagSecondaryFg:
case Color::TagWarningLineFg:
return sRGB(0, 0, 0, 0.9);
// Separators:
case Color::ToolbarSeparator:
return mode == Dark ? "#505050" : "#cdcdcd";
case Color::SidebarSeparator:
return mode == Dark ? *wxBLACK : "#cbcbcb";
case Color::EditingSeparator:
return mode == Dark ? sRGB(80, 80, 80) : sRGB(204, 204, 204);
case Color::EditingSubtleSeparator:
return mode == Dark ? sRGB(60, 60, 60) : sRGB(229, 229, 229);
// Backgrounds:
case Color::SidebarBackground:
return mode == Dark ? sRGB(43, 44, 47) : "#edf0f4";
case Color::EditingBackground:
#ifdef __WXOSX__
return wxColour([NSColor textBackgroundColor]);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
#endif
// Fuzzy toggle:
case Color::FuzzySwitch:
return mode == Dark ? sRGB(253, 178, 72) : sRGB(244, 143, 0);
case Color::FuzzySwitchInactive:
return mode == Dark ? sRGB(163, 163, 163) : sRGB(87, 87, 87);
// Syntax highlighting:
case Color::SyntaxLeadingWhitespaceBg:
return mode == Dark ? sRGB(75, 49, 111) : sRGB(234, 223, 247);
case Color::SyntaxEscapeFg:
return mode == Dark ? sRGB(234, 188, 244) : sRGB(162, 0, 20);
case Color::SyntaxEscapeBg:
return mode == Dark ? sRGB(90, 15, 167, 0.5) : sRGB(254, 234, 236);
case Color::SyntaxMarkup:
return mode == Dark ? sRGB(76, 156, 230) : sRGB(0, 121, 215);
case Color::SyntaxFormat:
return mode == Dark ? sRGB(250, 165, 251) : sRGB(178, 52, 197);
// Attention bar:
#ifdef __WXGTK__
// FIXME: use system colors
case Color::AttentionWarningBackground:
return sRGB(250, 173, 61);
case Color::AttentionQuestionBackground:
return sRGB(138, 173, 212);
case Color::AttentionErrorBackground:
return sRGB(237, 54, 54);
#else
case Color::AttentionWarningBackground:
return mode == Dark ? sRGB(254, 224, 132) : sRGB(254, 228, 149);
case Color::AttentionQuestionBackground:
return sRGB(199, 244, 156);
case Color::AttentionErrorBackground:
return sRGB(241, 103, 104);
#endif
// Buttons:
case Color::TranslucentButton:
return sRGB(255, 255, 255, 0.5);
case Color::Max:
return wxColour();
}
return wxColour(); // Visual C++ being silly
}
ColorScheme::Mode ColorScheme::GetAppMode()
{
if (!s_appModeDetermined)
{
#ifdef __WXOSX__
if (@available(macOS 10.14, *))
s_appMode = IsDarkAppearance(NSApp.effectiveAppearance) ? Dark : Light;
else
s_appMode = Light;
#else
auto colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
if (colBg.Red() < 0x60 && colBg.Green() < 0x60 && colBg.Blue() < 0x60)
s_appMode = Dark;
else
s_appMode = Light;
#endif
s_appModeDetermined = true;
}
return s_appMode;
}
ColorScheme::Mode ColorScheme::GetWindowMode(wxWindow *win)
{
#ifdef __WXOSX__
NSView *view = win->GetHandle();
return IsDarkAppearance(view.effectiveAppearance) ? Dark : Light;
#else
auto colBg = win->GetDefaultAttributes().colBg;
// Use dark scheme for very dark backgrounds:
if (colBg.Red() < 0x60 && colBg.Green() < 0x60 && colBg.Blue() < 0x60)
return Dark;
else
return Light;
#endif
}
wxColour ColorScheme::GetBlendedOn(Color color, wxWindow *win, Color bgColor)
{
auto bg = (bgColor != Color::Max) ? Get(bgColor, win) : win->GetBackgroundColour();
auto fg = Get(color, win);
#ifndef __WXOSX__
if (fg.Alpha() != wxALPHA_OPAQUE)
{
double alpha = fg.Alpha() / 255.0;
return wxColour(wxColour::AlphaBlend(fg.Red(), bg.Red(), alpha),
wxColour::AlphaBlend(fg.Green(), bg.Green(), alpha),
wxColour::AlphaBlend(fg.Blue(), bg.Blue(), alpha));
}
#endif
return fg;
}
void ColorScheme::CleanUp()
{
s_data.reset();
}
|
/*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2016-2018 Vaclav Slavik
*
* 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 "colorscheme.h"
#include <wx/settings.h>
#ifdef __WXGTK__
#include <pango/pango.h>
#if PANGO_VERSION_CHECK(1,38,0)
#define SUPPORTS_BGALPHA
#endif
#else
#define SUPPORTS_BGALPHA
#endif
namespace
{
#ifdef __WXOSX__
inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
return wxColour([NSColor colorWithSRGBRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]);
}
inline bool IsDarkAppearance(NSAppearance *appearance)
{
if (@available(macOS 10.14, *))
{
NSAppearanceName appearanceName = [appearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
return [appearanceName isEqualToString:NSAppearanceNameDarkAqua];
}
else
{
return false;
}
}
#else
inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
return wxColour(r, g, b, int(a * wxALPHA_OPAQUE));
}
#endif
} // anonymous namespace
std::unique_ptr<ColorScheme::Data> ColorScheme::s_data;
bool ColorScheme::s_appModeDetermined = false;
ColorScheme::Mode ColorScheme::s_appMode = ColorScheme::Mode::Light;
wxColour ColorScheme::DoGet(Color color, Mode mode)
{
switch (color)
{
// Labels:
case Color::SecondaryLabel:
#ifdef __WXOSX__
return wxColour([NSColor secondaryLabelColor]);
#elif defined(__WXGTK__)
return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
#endif
// List items:
case Color::ItemID:
#ifdef __WXOSX__
return wxColour([NSColor tertiaryLabelColor]);
#else
return mode == Light ? "#a1a1a1" : wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT).ChangeLightness(50);
#endif
case Color::ItemFuzzy:
return mode == Dark ? sRGB(253, 178, 72) : sRGB(230, 134, 0);
case Color::ItemError:
return sRGB(225, 77, 49);
case Color::ItemContextFg:
return mode == Dark ? sRGB(180, 222, 254) : sRGB(70, 109, 137);
case Color::ItemContextBg:
if (mode == Dark)
#if wxCHECK_VERSION(3,1,0)
return sRGB(67, 94, 147, 0.6);
#else // see https://github.com/vslavik/poedit/issues/524
return sRGB(67, 94, 147);
#endif
else
return sRGB(217, 232, 242);
case Color::ItemContextBgHighlighted:
#if defined(__WXMSW__)
return sRGB(255, 255, 255, 0.50);
#elif defined(SUPPORTS_BGALPHA)
return sRGB(255, 255, 255, 0.35);
#else
return DoGet(Color::ItemContextBg, mode);
#endif
// Tags:
case Color::TagContextFg:
return DoGet(Color::ItemContextFg, mode);
case Color::TagContextBg:
return DoGet(Color::ItemContextBg, mode);
case Color::TagSecondaryBg:
return mode == Dark ? sRGB(255, 255, 255, 0.5) : sRGB(0, 0, 0, 0.10);
case Color::TagErrorLineBg:
return sRGB(241, 134, 135);
case Color::TagWarningLineBg:
return mode == Dark ? sRGB(198, 171, 113) : sRGB(253, 235, 176);
case Color::TagErrorLineFg:
return sRGB(0, 0, 0, 0.8);
case Color::TagSecondaryFg:
case Color::TagWarningLineFg:
return sRGB(0, 0, 0, 0.9);
// Separators:
case Color::ToolbarSeparator:
return mode == Dark ? "#505050" : "#cdcdcd";
case Color::SidebarSeparator:
return mode == Dark ? *wxBLACK : "#cbcbcb";
case Color::EditingSeparator:
return mode == Dark ? sRGB(80, 80, 80) : sRGB(204, 204, 204);
case Color::EditingSubtleSeparator:
return mode == Dark ? sRGB(60, 60, 60) : sRGB(229, 229, 229);
// Backgrounds:
case Color::SidebarBackground:
return mode == Dark ? sRGB(43, 44, 47) : "#edf0f4";
case Color::EditingBackground:
#ifdef __WXOSX__
return wxColour([NSColor textBackgroundColor]);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
#endif
// Fuzzy toggle:
case Color::FuzzySwitch:
return mode == Dark ? sRGB(253, 178, 72) : sRGB(244, 143, 0);
case Color::FuzzySwitchInactive:
return mode == Dark ? sRGB(163, 163, 163) : sRGB(87, 87, 87);
// Syntax highlighting:
case Color::SyntaxLeadingWhitespaceBg:
return mode == Dark ? sRGB(75, 49, 111) : sRGB(234, 223, 247);
case Color::SyntaxEscapeFg:
return mode == Dark ? sRGB(234, 188, 244) : sRGB(162, 0, 20);
case Color::SyntaxEscapeBg:
return mode == Dark ? sRGB(90, 15, 167, 0.5) : sRGB(254, 234, 236);
case Color::SyntaxMarkup:
return mode == Dark ? sRGB(76, 156, 230) : sRGB(0, 121, 215);
case Color::SyntaxFormat:
return mode == Dark ? sRGB(250, 165, 251) : sRGB(178, 52, 197);
// Attention bar:
#ifdef __WXGTK__
// FIXME: use system colors
case Color::AttentionWarningBackground:
return sRGB(250, 173, 61);
case Color::AttentionQuestionBackground:
return sRGB(138, 173, 212);
case Color::AttentionErrorBackground:
return sRGB(237, 54, 54);
#else
case Color::AttentionWarningBackground:
return mode == Dark ? sRGB(254, 224, 132) : sRGB(254, 228, 149);
case Color::AttentionQuestionBackground:
return sRGB(199, 244, 156);
case Color::AttentionErrorBackground:
return sRGB(241, 103, 104);
#endif
// Buttons:
case Color::TranslucentButton:
return sRGB(255, 255, 255, 0.5);
case Color::Max:
return wxColour();
}
return wxColour(); // Visual C++ being silly
}
ColorScheme::Mode ColorScheme::GetAppMode()
{
if (!s_appModeDetermined)
{
#ifdef __WXOSX__
if (@available(macOS 10.14, *))
s_appMode = IsDarkAppearance(NSApp.effectiveAppearance) ? Dark : Light;
else
s_appMode = Light;
#else
auto colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
if (colBg.Red() < 0x60 && colBg.Green() < 0x60 && colBg.Blue() < 0x60)
s_appMode = Dark;
else
s_appMode = Light;
#endif
s_appModeDetermined = true;
}
return s_appMode;
}
ColorScheme::Mode ColorScheme::GetWindowMode(wxWindow *win)
{
#ifdef __WXOSX__
NSView *view = win->GetHandle();
return IsDarkAppearance(view.effectiveAppearance) ? Dark : Light;
#else
auto colBg = win->GetDefaultAttributes().colBg;
// Use dark scheme for very dark backgrounds:
if (colBg.Red() < 0x60 && colBg.Green() < 0x60 && colBg.Blue() < 0x60)
return Dark;
else
return Light;
#endif
}
wxColour ColorScheme::GetBlendedOn(Color color, wxWindow *win, Color bgColor)
{
auto bg = (bgColor != Color::Max) ? Get(bgColor, win) : win->GetBackgroundColour();
auto fg = Get(color, win);
#ifndef __WXOSX__
if (fg.Alpha() != wxALPHA_OPAQUE)
{
double alpha = fg.Alpha() / 255.0;
return wxColour(wxColour::AlphaBlend(fg.Red(), bg.Red(), alpha),
wxColour::AlphaBlend(fg.Green(), bg.Green(), alpha),
wxColour::AlphaBlend(fg.Blue(), bg.Blue(), alpha));
}
#endif
return fg;
}
void ColorScheme::CleanUp()
{
s_data.reset();
}
|
Fix dark mode assert with wxGTK 3.0
|
Fix dark mode assert with wxGTK 3.0
wx 3.0 didn't support alpha channel in HTML exports, so just tweak the
dark mode color to not require it. It's not worth doing complicated
fixes for the old wx version.
Fixes #524.
|
C++
|
mit
|
alexhenrie/poedit,vslavik/poedit,vslavik/poedit,c72578/poedit,PKRoma/poedit,nawawi/poedit,nawawi/poedit,PKRoma/poedit,PKRoma/poedit,nawawi/poedit,PKRoma/poedit,vslavik/poedit,vslavik/poedit,c72578/poedit,c72578/poedit,vslavik/poedit,c72578/poedit,c72578/poedit,PKRoma/poedit,alexhenrie/poedit,alexhenrie/poedit,nawawi/poedit,alexhenrie/poedit,nawawi/poedit,alexhenrie/poedit
|
eb3765949caf7801863bb72b5a934fdd553a6b2b
|
Examples/Filtering/GradientAnisotropicDiffusionImageFilter.cxx
|
Examples/Filtering/GradientAnisotropicDiffusionImageFilter.cxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {GradientAnisotropicDiffusionImageFilterOutput.png}
// ARGUMENTS: 5 0.25 3
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The \doxygen{GradientAnisotropicDiffusionImageFilter} implements an
// $N$-dimensional version of the classic Perona-Malik anisotropic diffusion
// equation for scalar-valued images \cite{Perona1990}.
//
// The conductance term for this implementation is chosen as a function of the
// gradient magnitude of the image at each point, reducing the strength of
// diffusion at edge pixels.
//
// \begin{equation}
// C(\mathbf{x}) = e^{-(\frac{\parallel \nabla U(\mathbf{x}) \parallel}{K})^2}
// \end{equation}
//
// The numerical implementation of this equation is similar to that described
// in the Perona-Malik paper \cite{Perona1990}, but uses a more robust technique
// for gradient magnitude estimation and has been generalized to $N$-dimensions.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step required to use this filter is to include its header file.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGradientAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 6 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile ";
std::cerr << "numberOfIterations timeStep conductance" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// Types should be selected based on the pixel types required for the
// input and output images. The image types are defined using the pixel
// type and the dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef float InputPixelType;
typedef float OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
// Software Guide : BeginLatex
//
// The filter type is now instantiated using both the input image and the
// output image types. The filter object is created by the \code{New()}
// method.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!instantiation}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!New()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::GradientAnisotropicDiffusionImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// Software Guide : BeginLatex
//
// The input image can be obtained from the output of another filter. Here,
// an image reader is used as source.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
// Software Guide : EndCodeSnippet
const unsigned int numberOfIterations = atoi( argv[3] );
const double timeStep = atof( argv[4] );
const double conductance = atof( argv[5] );
// Software Guide : BeginLatex
//
// This filter requires three parameters: the number of iterations to be
// performed, the time step and the conductance parameter used in the
// computation of the level set evolution. These parameters are set using
// the methods \code{SetNumberOfIterations()}, \code{SetTimeStep()} and
// \code{SetConductanceParameter()} respectively. The filter can be
// executed by invoking \code{Update()}.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!Update()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetTimeStep()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetConductanceParameter()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetNumberOfIterations()}
// \index{SetTimeStep()!itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
// \index{SetNumberOfIterations()!itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetNumberOfIterations( numberOfIterations );
filter->SetTimeStep( timeStep );
filter->SetConductanceParameter( conductance );
filter->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Typical values for the time step are $0.25$ in $2D$ images and $0.125$
// in $3D$ images. The number of iterations is typically set to $5$; more
// iterations result in further smoothing and will increase the computing
// time linearly.
//
// Software Guide : EndLatex
//
// The output of the filter is rescaled here and then sent to a writer.
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
OutputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
rescaler->SetInput( filter->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
// Software Guide : BeginLatex
//
// \begin{figure} \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice}
// \includegraphics[width=0.44\textwidth]{GradientAnisotropicDiffusionImageFilterOutput}
// \itkcaption[GradientAnisotropicDiffusionImageFilter output]{Effect of the
// GradientAnisotropicDiffusionImageFilter on a slice from a MRI Proton
// Density image of the brain.}
// \label{fig:GradientAnisotropicDiffusionImageFilterInputOutput}
// \end{figure}
//
// Figure \ref{fig:GradientAnisotropicDiffusionImageFilterInputOutput}
// illustrates the effect of this filter on a MRI proton density image of
// the brain. In this example the filter was run with a time step of $0.25$,
// and $5$ iterations. The figure shows how homogeneous regions are
// smoothed and edges are preserved.
//
// \relatedClasses
// \begin{itemize}
// \item \doxygen{BilateralImageFilter}
// \item \doxygen{CurvatureAnisotropicDiffusionImageFilter}
// \item \doxygen{CurvatureFlowImageFilter}
// \end{itemize}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {GradientAnisotropicDiffusionImageFilterOutput.png}
// ARGUMENTS: 15 0.1 3
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The \doxygen{GradientAnisotropicDiffusionImageFilter} implements an
// $N$-dimensional version of the classic Perona-Malik anisotropic diffusion
// equation for scalar-valued images \cite{Perona1990}.
//
// The conductance term for this implementation is chosen as a function of the
// gradient magnitude of the image at each point, reducing the strength of
// diffusion at edge pixels.
//
// \begin{equation}
// C(\mathbf{x}) = e^{-(\frac{\parallel \nabla U(\mathbf{x}) \parallel}{K})^2}
// \end{equation}
//
// The numerical implementation of this equation is similar to that described
// in the Perona-Malik paper \cite{Perona1990}, but uses a more robust technique
// for gradient magnitude estimation and has been generalized to $N$-dimensions.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step required to use this filter is to include its header file.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkGradientAnisotropicDiffusionImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 6 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile ";
std::cerr << "numberOfIterations timeStep conductance" << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// Types should be selected based on the pixel types required for the
// input and output images. The image types are defined using the pixel
// type and the dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef float InputPixelType;
typedef float OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
// Software Guide : BeginLatex
//
// The filter type is now instantiated using both the input image and the
// output image types. The filter object is created by the \code{New()}
// method.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!instantiation}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!New()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::GradientAnisotropicDiffusionImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// Software Guide : BeginLatex
//
// The input image can be obtained from the output of another filter. Here,
// an image reader is used as source.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
// Software Guide : EndCodeSnippet
const unsigned int numberOfIterations = atoi( argv[3] );
const double timeStep = atof( argv[4] );
const double conductance = atof( argv[5] );
// Software Guide : BeginLatex
//
// This filter requires three parameters: the number of iterations to be
// performed, the time step and the conductance parameter used in the
// computation of the level set evolution. These parameters are set using
// the methods \code{SetNumberOfIterations()}, \code{SetTimeStep()} and
// \code{SetConductanceParameter()} respectively. The filter can be
// executed by invoking \code{Update()}.
//
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!Update()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetTimeStep()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetConductanceParameter()}
// \index{itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter!SetNumberOfIterations()}
// \index{SetTimeStep()!itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
// \index{SetNumberOfIterations()!itk::Gradient\-Anisotropic\-Diffusion\-Image\-Filter}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetNumberOfIterations( numberOfIterations );
filter->SetTimeStep( timeStep );
filter->SetConductanceParameter( conductance );
filter->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Typical values for the time step are $0.25$ in $2D$ images and $0.125$
// in $3D$ images. The number of iterations is typically set to $5$; more
// iterations result in further smoothing and will increase the computing
// time linearly.
//
// Software Guide : EndLatex
//
// The output of the filter is rescaled here and then sent to a writer.
//
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
OutputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
rescaler->SetInput( filter->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
// Software Guide : BeginLatex
//
// \begin{figure} \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice}
// \includegraphics[width=0.44\textwidth]{GradientAnisotropicDiffusionImageFilterOutput}
// \itkcaption[GradientAnisotropicDiffusionImageFilter output]{Effect of the
// GradientAnisotropicDiffusionImageFilter on a slice from a MRI Proton
// Density image of the brain.}
// \label{fig:GradientAnisotropicDiffusionImageFilterInputOutput}
// \end{figure}
//
// Figure \ref{fig:GradientAnisotropicDiffusionImageFilterInputOutput}
// illustrates the effect of this filter on a MRI proton density image of
// the brain. In this example the filter was run with a time step of $0.25$,
// and $5$ iterations. The figure shows how homogeneous regions are
// smoothed and edges are preserved.
//
// \relatedClasses
// \begin{itemize}
// \item \doxygen{BilateralImageFilter}
// \item \doxygen{CurvatureAnisotropicDiffusionImageFilter}
// \item \doxygen{CurvatureFlowImageFilter}
// \end{itemize}
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
|
Address GradientAnisotropicDiffusionImageFilter example settings.
|
COMP: Address GradientAnisotropicDiffusionImageFilter example settings.
Addresses:
WARNING: In
/home/matt/src/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionImageFilter.hxx,
line 82
GradientAnisotropicDiffusionImageFilter (0x12ce520): Anisotropic diffusion
unstable time step: 0.25
Stable time step for this image must be smaller than 0.125
when building the Software Guide.
Change-Id: I6718b6a5a0b8ece222b86039596224bdc32e95b2
|
C++
|
apache-2.0
|
LucasGandel/ITK,ajjl/ITK,hendradarwin/ITK,biotrump/ITK,InsightSoftwareConsortium/ITK,jcfr/ITK,malaterre/ITK,jcfr/ITK,msmolens/ITK,InsightSoftwareConsortium/ITK,BRAINSia/ITK,atsnyder/ITK,malaterre/ITK,stnava/ITK,fbudin69500/ITK,zachary-williamson/ITK,richardbeare/ITK,jcfr/ITK,stnava/ITK,LucHermitte/ITK,jcfr/ITK,fedral/ITK,LucHermitte/ITK,blowekamp/ITK,PlutoniumHeart/ITK,InsightSoftwareConsortium/ITK,fedral/ITK,fbudin69500/ITK,hendradarwin/ITK,jmerkow/ITK,PlutoniumHeart/ITK,msmolens/ITK,biotrump/ITK,biotrump/ITK,blowekamp/ITK,BlueBrain/ITK,zachary-williamson/ITK,Kitware/ITK,ajjl/ITK,heimdali/ITK,malaterre/ITK,fedral/ITK,atsnyder/ITK,richardbeare/ITK,stnava/ITK,hendradarwin/ITK,biotrump/ITK,zachary-williamson/ITK,hjmjohnson/ITK,spinicist/ITK,PlutoniumHeart/ITK,BlueBrain/ITK,vfonov/ITK,fbudin69500/ITK,ajjl/ITK,hendradarwin/ITK,fbudin69500/ITK,heimdali/ITK,hjmjohnson/ITK,vfonov/ITK,hjmjohnson/ITK,fbudin69500/ITK,jcfr/ITK,vfonov/ITK,blowekamp/ITK,jcfr/ITK,BRAINSia/ITK,malaterre/ITK,msmolens/ITK,BlueBrain/ITK,msmolens/ITK,heimdali/ITK,vfonov/ITK,jmerkow/ITK,ajjl/ITK,hjmjohnson/ITK,blowekamp/ITK,stnava/ITK,LucHermitte/ITK,Kitware/ITK,PlutoniumHeart/ITK,atsnyder/ITK,LucHermitte/ITK,InsightSoftwareConsortium/ITK,BlueBrain/ITK,fedral/ITK,jmerkow/ITK,hendradarwin/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,jcfr/ITK,blowekamp/ITK,jmerkow/ITK,vfonov/ITK,BRAINSia/ITK,LucasGandel/ITK,jcfr/ITK,atsnyder/ITK,atsnyder/ITK,thewtex/ITK,biotrump/ITK,malaterre/ITK,vfonov/ITK,malaterre/ITK,richardbeare/ITK,stnava/ITK,LucHermitte/ITK,BRAINSia/ITK,PlutoniumHeart/ITK,LucHermitte/ITK,PlutoniumHeart/ITK,thewtex/ITK,spinicist/ITK,stnava/ITK,stnava/ITK,hendradarwin/ITK,msmolens/ITK,BlueBrain/ITK,malaterre/ITK,thewtex/ITK,spinicist/ITK,atsnyder/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,heimdali/ITK,BRAINSia/ITK,heimdali/ITK,LucasGandel/ITK,zachary-williamson/ITK,LucasGandel/ITK,jmerkow/ITK,jmerkow/ITK,blowekamp/ITK,spinicist/ITK,biotrump/ITK,biotrump/ITK,stnava/ITK,hendradarwin/ITK,BRAINSia/ITK,atsnyder/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,heimdali/ITK,heimdali/ITK,fedral/ITK,BlueBrain/ITK,jmerkow/ITK,ajjl/ITK,heimdali/ITK,hendradarwin/ITK,hjmjohnson/ITK,zachary-williamson/ITK,richardbeare/ITK,malaterre/ITK,thewtex/ITK,zachary-williamson/ITK,BRAINSia/ITK,biotrump/ITK,vfonov/ITK,jmerkow/ITK,zachary-williamson/ITK,thewtex/ITK,vfonov/ITK,fbudin69500/ITK,atsnyder/ITK,ajjl/ITK,InsightSoftwareConsortium/ITK,spinicist/ITK,zachary-williamson/ITK,blowekamp/ITK,LucHermitte/ITK,richardbeare/ITK,ajjl/ITK,fbudin69500/ITK,Kitware/ITK,thewtex/ITK,Kitware/ITK,blowekamp/ITK,malaterre/ITK,fedral/ITK,BlueBrain/ITK,hjmjohnson/ITK,msmolens/ITK,BlueBrain/ITK,spinicist/ITK,msmolens/ITK,stnava/ITK,hjmjohnson/ITK,LucasGandel/ITK,atsnyder/ITK,LucasGandel/ITK,LucHermitte/ITK,spinicist/ITK,fedral/ITK,Kitware/ITK,LucasGandel/ITK,vfonov/ITK,PlutoniumHeart/ITK,msmolens/ITK,thewtex/ITK,richardbeare/ITK,Kitware/ITK,LucasGandel/ITK,Kitware/ITK,richardbeare/ITK,spinicist/ITK,fedral/ITK,ajjl/ITK
|
9b3fc31292fb9524cc6fa1f59fcc117a405eb0ac
|
include/tmxpp/impl/to_color.hpp
|
include/tmxpp/impl/to_color.hpp
|
#ifndef TMXPP_IMPL_TO_COLOR_HPP
#define TMXPP_IMPL_TO_COLOR_HPP
#include <cstdint>
#include <ios>
#include <regex>
#include <sstream>
#include <string>
#include <string_view>
#include <tmxpp/Color.hpp>
#include <tmxpp/exceptions.hpp>
#include <tmxpp/impl/Xml.hpp>
namespace tmxpp::impl {
namespace color {
// Returns: `true` if `s` has the format of a TMX color, and `false` otherwise.
// Notes: A TMX color has the format "#AARRGGBB" or "#RRGGBB".
bool is_well_formatted(std::string_view s)
{
static const std::regex format{"#([[:xdigit:]]{2})?[[:xdigit:]]{6}",
std::regex::nosubs};
return std::regex_match(s.begin(), s.end(), format);
}
// Requires: `is_well_formatted(color)`
// Returns: The hexadecimal substring in `color`.
constexpr std::string_view hex_substr(std::string_view color) noexcept
{
return color.substr(1);
}
using Channels = std::uint_least32_t;
// Requires: `is_well_formatted(color)`
// Returns: `hex_substr(color)` as `Channels`.
// Throws: `Exception` if it could not be converted.
Channels to_channels(std::string_view color)
{
std::stringstream ss;
ss << std::noskipws << std::hex << hex_substr(color);
Channels num;
ss >> num;
if (!ss || !ss.eof())
throw Exception{"Hexadecimal " + std::string{hex_substr(color)} +
" could not be converted to Channels."};
return num;
}
// Requires: `is_well_formatted(color)`
// Returns: `true` if `color` has an alpha channel, and `false` otherwise.
constexpr bool has_alpha(std::string_view color) noexcept
{
constexpr std::string_view format_with_alpha{"#AARRGGBB"};
return color.size() == format_with_alpha.size();
}
Color to_color(std::string_view color)
{
constexpr Color::Channel default_alpha{255};
constexpr Color default_{default_alpha, 0, 0, 0};
if (color.empty())
return default_;
if (!is_well_formatted(color))
throw Exception{"Color with bad format: " + std::string{color}};
auto channels{to_channels(color)};
return {
has_alpha(color) ? static_cast<Color::Channel>(channels >> 24 & 0xFF)
: default_alpha,
static_cast<Color::Channel>(channels >> 16 & 0xFF),
static_cast<Color::Channel>(channels >> 8 & 0xFF),
static_cast<Color::Channel>(channels & 0xFF),
};
}
Color to_color(Xml::Attribute::Value value)
{
return to_color(get(value));
}
} // namespace color
using color::to_color;
} // namespace tmxpp::impl
#endif // TMXPP_IMPL_TO_COLOR_HPP
|
#ifndef TMXPP_IMPL_TO_COLOR_HPP
#define TMXPP_IMPL_TO_COLOR_HPP
#include <cstdint>
#include <ios>
#include <regex>
#include <sstream>
#include <string>
#include <string_view>
#include <tmxpp/Color.hpp>
#include <tmxpp/exceptions.hpp>
#include <tmxpp/impl/Xml.hpp>
namespace tmxpp::impl {
namespace color {
// Returns: `true` if `s` has the format of a TMX color, and `false` otherwise.
// Notes: A TMX color has the format "#AARRGGBB" or "#RRGGBB".
bool is_well_formatted(std::string_view s)
{
static const std::regex format{"#([[:xdigit:]]{2})?[[:xdigit:]]{6}",
std::regex::nosubs};
return std::regex_match(s.begin(), s.end(), format);
}
// Requires: `is_well_formatted(color)`
// Returns: The hexadecimal substring in `color`.
constexpr std::string_view hex_substr(std::string_view color) noexcept
{
return color.substr(1);
}
using Channels = std::uint_least32_t;
// Requires: `is_well_formatted(color)`
// Returns: `hex_substr(color)` as `Channels`.
// Throws: `Exception` if it could not be converted.
Channels to_channels(std::string_view color)
{
std::stringstream ss;
ss << std::noskipws << std::hex << hex_substr(color);
Channels num;
ss >> num;
if (!ss || !ss.eof())
throw Exception{"Hexadecimal " + std::string{hex_substr(color)} +
" could not be converted to Channels."};
return num;
}
// Requires: `is_well_formatted(color)`
// Returns: `true` if `color` has an alpha channel, and `false` otherwise.
constexpr bool has_alpha(std::string_view color) noexcept
{
constexpr std::string_view format_with_alpha{"#AARRGGBB"};
return color.size() == format_with_alpha.size();
}
Color to_color(std::string_view color)
{
constexpr Color::Channel default_alpha{255};
constexpr Color default_{default_alpha, 0, 0, 0};
if (color.empty())
return default_;
if (!is_well_formatted(color))
throw Exception{"Color with bad format: " + std::string{color}};
auto channels{to_channels(color)};
return {
has_alpha(color) ? static_cast<Color::Channel>((channels >> 24) & 0xFF)
: default_alpha,
static_cast<Color::Channel>((channels >> 16) & 0xFF),
static_cast<Color::Channel>((channels >> 8) & 0xFF),
static_cast<Color::Channel>(channels & 0xFF),
};
}
Color to_color(Xml::Attribute::Value value)
{
return to_color(get(value));
}
} // namespace color
using color::to_color;
} // namespace tmxpp::impl
#endif // TMXPP_IMPL_TO_COLOR_HPP
|
Add parentheses for improved readability
|
Add parentheses for improved readability
|
C++
|
unlicense
|
johelegp/tmxpp
|
d38072d64d9cf323642ca7212b8b25e340e3a985
|
base/security_unittest.cc
|
base/security_unittest.cc
|
// Copyright (c) 2013 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 <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <limits>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_POSIX)
#include <sys/mman.h>
#include <unistd.h>
#endif
#if defined(OS_WIN)
#include <new.h>
#endif
using std::nothrow;
using std::numeric_limits;
namespace {
#if defined(OS_WIN)
// This is a permitted size but exhausts memory pretty quickly.
const size_t kLargePermittedAllocation = 0x7FFFE000;
int OnNoMemory(size_t) {
_exit(1);
}
void ExhaustMemoryWithMalloc() {
for (;;) {
// Without the |volatile|, clang optimizes away the allocation.
void* volatile buf = malloc(kLargePermittedAllocation);
if (!buf)
break;
}
}
void ExhaustMemoryWithRealloc() {
size_t size = kLargePermittedAllocation;
void* buf = malloc(size);
if (!buf)
return;
for (;;) {
size += kLargePermittedAllocation;
void* new_buf = realloc(buf, size);
if (!buf)
break;
buf = new_buf;
}
}
#endif
// This function acts as a compiler optimization barrier. We use it to
// prevent the compiler from making an expression a compile-time constant.
// We also use it so that the compiler doesn't discard certain return values
// as something we don't need (see the comment with calloc below).
template <typename Type>
Type HideValueFromCompiler(volatile Type value) {
#if defined(__GNUC__)
// In a GCC compatible compiler (GCC or Clang), make this compiler barrier
// more robust than merely using "volatile".
__asm__ volatile ("" : "+r" (value));
#endif // __GNUC__
return value;
}
// Tcmalloc and Windows allocator shim support setting malloc limits.
// - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
// - ADDRESS_SANITIZER and SYZYASAN because they have their own memory allocator
// - IOS does not use tcmalloc
// - OS_MACOSX does not use tcmalloc
// - Windows allocator shim defines ALLOCATOR_SHIM
#if (!defined(NO_TCMALLOC) || defined(ALLOCATOR_SHIM)) && \
!defined(ADDRESS_SANITIZER) && !defined(OS_IOS) && !defined(OS_MACOSX) && \
!defined(SYZYASAN)
#define MALLOC_OVERFLOW_TEST(function) function
#else
#define MALLOC_OVERFLOW_TEST(function) DISABLED_##function
#endif
// TODO(jln): switch to std::numeric_limits<int>::max() when we switch to
// C++11.
const size_t kTooBigAllocSize = INT_MAX;
// Detect runtime TCMalloc bypasses.
bool IsTcMallocBypassed() {
#if defined(OS_LINUX)
// This should detect a TCMalloc bypass from Valgrind.
char* g_slice = getenv("G_SLICE");
if (g_slice && !strcmp(g_slice, "always-malloc"))
return true;
#endif
return false;
}
bool CallocDiesOnOOM() {
// The sanitizers' calloc dies on OOM instead of returning NULL.
// The wrapper function in base/process_util_linux.cc that is used when we
// compile without TCMalloc will just die on OOM instead of returning NULL.
#if defined(ADDRESS_SANITIZER) || \
defined(MEMORY_SANITIZER) || \
defined(THREAD_SANITIZER) || \
(defined(OS_LINUX) && defined(NO_TCMALLOC))
return true;
#else
return false;
#endif
}
// Fake test that allow to know the state of TCMalloc by looking at bots.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(IsTCMallocDynamicallyBypassed)) {
printf("Malloc is dynamically bypassed: %s\n",
IsTcMallocBypassed() ? "yes." : "no.");
}
// The MemoryAllocationRestrictions* tests test that we can not allocate a
// memory range that cannot be indexed via an int. This is used to mitigate
// vulnerabilities in libraries that use int instead of size_t. See
// crbug.com/169327.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsMalloc)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(malloc(kTooBigAllocSize))));
ASSERT_TRUE(!ptr);
}
}
#if defined(GTEST_HAS_DEATH_TEST) && defined(OS_WIN)
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationMallocDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
scoped_ptr<char, base::FreeDeleter> ptr;
EXPECT_DEATH(ptr.reset(static_cast<char*>(
HideValueFromCompiler(malloc(kTooBigAllocSize)))),
"");
ASSERT_TRUE(!ptr);
}
_set_new_handler(NULL);
_set_new_mode(0);
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationExhaustDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
ASSERT_DEATH(ExhaustMemoryWithMalloc(), "");
}
_set_new_handler(NULL);
_set_new_mode(0);
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryReallocationExhaustDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
ASSERT_DEATH(ExhaustMemoryWithRealloc(), "");
}
_set_new_handler(NULL);
_set_new_mode(0);
}
#endif
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsCalloc)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));
ASSERT_TRUE(!ptr);
}
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsRealloc)) {
if (!IsTcMallocBypassed()) {
char* orig_ptr = static_cast<char*>(malloc(1));
ASSERT_TRUE(orig_ptr);
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));
ASSERT_TRUE(!ptr);
// If realloc() did not succeed, we need to free orig_ptr.
free(orig_ptr);
}
}
typedef struct {
char large_array[kTooBigAllocSize];
} VeryLargeStruct;
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsNew)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<VeryLargeStruct> ptr(
HideValueFromCompiler(new (nothrow) VeryLargeStruct));
ASSERT_TRUE(!ptr);
}
}
#if defined(GTEST_HAS_DEATH_TEST) && defined(OS_WIN)
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationNewDeathTest)) {
_set_new_handler(&OnNoMemory);
{
scoped_ptr<VeryLargeStruct> ptr;
EXPECT_DEATH(
ptr.reset(HideValueFromCompiler(new (nothrow) VeryLargeStruct)), "");
ASSERT_TRUE(!ptr);
}
_set_new_handler(NULL);
}
#endif
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsNewArray)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char[]> ptr(
HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));
ASSERT_TRUE(!ptr);
}
}
// The tests bellow check for overflows in new[] and calloc().
// There are platforms where these tests are known to fail. We would like to
// be able to easily check the status on the bots, but marking tests as
// FAILS_ is too clunky.
void OverflowTestsSoftExpectTrue(bool overflow_detected) {
if (!overflow_detected) {
#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
// Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
// fail the test, but report.
printf("Platform has overflow: %s\n",
!overflow_detected ? "yes." : "no.");
#else
// Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
// aren't).
EXPECT_TRUE(overflow_detected);
#endif
}
}
#if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER) || defined(OS_MACOSX)
#define MAYBE_NewOverflow DISABLED_NewOverflow
#else
#define MAYBE_NewOverflow NewOverflow
#endif
// Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
// IOS doesn't honor nothrow, so disable the test there.
// Crashes on Windows Dbg builds, disable there as well.
// Fails on Mac 10.8 http://crbug.com/227092
TEST(SecurityTest, MAYBE_NewOverflow) {
const size_t kArraySize = 4096;
// We want something "dynamic" here, so that the compiler doesn't
// immediately reject crazy arrays.
const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
// numeric_limits are still not constexpr until we switch to C++11, so we
// use an ugly cast.
const size_t kMaxSizeT = ~static_cast<size_t>(0);
ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
{
scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
char[kDynamicArraySize2][kArraySize]);
OverflowTestsSoftExpectTrue(!array_pointer);
}
// On windows, the compiler prevents static array sizes of more than
// 0x7fffffff (error C2148).
#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
ALLOW_UNUSED_LOCAL(kDynamicArraySize);
#else
{
scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
char[kDynamicArraySize][kArraySize2]);
OverflowTestsSoftExpectTrue(!array_pointer);
}
#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
}
// Call calloc(), eventually free the memory and return whether or not
// calloc() did succeed.
bool CallocReturnsNull(size_t nmemb, size_t size) {
scoped_ptr<char, base::FreeDeleter> array_pointer(
static_cast<char*>(calloc(nmemb, size)));
// We need the call to HideValueFromCompiler(): we have seen LLVM
// optimize away the call to calloc() entirely and assume
// the pointer to not be NULL.
return HideValueFromCompiler(array_pointer.get()) == NULL;
}
// Test if calloc() can overflow.
TEST(SecurityTest, CallocOverflow) {
const size_t kArraySize = 4096;
const size_t kMaxSizeT = numeric_limits<size_t>::max();
const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
if (!CallocDiesOnOOM()) {
EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2));
EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize));
} else {
// It's also ok for calloc to just terminate the process.
#if defined(GTEST_HAS_DEATH_TEST)
EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), "");
EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), "");
#endif // GTEST_HAS_DEATH_TEST
}
}
#if defined(OS_LINUX) && defined(__x86_64__)
// Check if ptr1 and ptr2 are separated by less than size chars.
bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
reinterpret_cast<char*>(std::min(ptr1, ptr2));
return static_cast<size_t>(ptr_diff) <= size;
}
// Check if TCMalloc uses an underlying random memory allocator.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(RandomMemoryAllocations)) {
if (IsTcMallocBypassed())
return;
size_t kPageSize = 4096; // We support x86_64 only.
// Check that malloc() returns an address that is neither the kernel's
// un-hinted mmap area, nor the current brk() area. The first malloc() may
// not be at a random address because TCMalloc will first exhaust any memory
// that it has allocated early on, before starting the sophisticated
// allocators.
void* default_mmap_heap_address =
mmap(0, kPageSize, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
ASSERT_NE(default_mmap_heap_address,
static_cast<void*>(MAP_FAILED));
ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
void* brk_heap_address = sbrk(0);
ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
ASSERT_TRUE(brk_heap_address != NULL);
// 1 MB should get us past what TCMalloc pre-allocated before initializing
// the sophisticated allocators.
size_t kAllocSize = 1<<20;
scoped_ptr<char, base::FreeDeleter> ptr(
static_cast<char*>(malloc(kAllocSize)));
ASSERT_TRUE(ptr != NULL);
// If two pointers are separated by less than 512MB, they are considered
// to be in the same area.
// Our random pointer could be anywhere within 0x3fffffffffff (46bits),
// and we are checking that it's not withing 1GB (30 bits) from two
// addresses (brk and mmap heap). We have roughly one chance out of
// 2^15 to flake.
const size_t kAreaRadius = 1<<29;
bool in_default_mmap_heap = ArePointersToSameArea(
ptr.get(), default_mmap_heap_address, kAreaRadius);
EXPECT_FALSE(in_default_mmap_heap);
bool in_default_brk_heap = ArePointersToSameArea(
ptr.get(), brk_heap_address, kAreaRadius);
EXPECT_FALSE(in_default_brk_heap);
// In the implementation, we always mask our random addresses with
// kRandomMask, so we use it as an additional detection mechanism.
const uintptr_t kRandomMask = 0x3fffffffffffULL;
bool impossible_random_address =
reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
EXPECT_FALSE(impossible_random_address);
}
#endif // defined(OS_LINUX) && defined(__x86_64__)
} // namespace
|
// Copyright (c) 2013 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 <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <limits>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_POSIX)
#include <sys/mman.h>
#include <unistd.h>
#endif
#if defined(OS_WIN)
#include <new.h>
#endif
using std::nothrow;
using std::numeric_limits;
namespace {
#if defined(OS_WIN)
// This is a permitted size but exhausts memory pretty quickly.
const size_t kLargePermittedAllocation = 0x7FFFE000;
int OnNoMemory(size_t) {
_exit(1);
}
void ExhaustMemoryWithMalloc() {
for (;;) {
// Without the |volatile|, clang optimizes away the allocation.
void* volatile buf = malloc(kLargePermittedAllocation);
if (!buf)
break;
}
}
void ExhaustMemoryWithRealloc() {
size_t size = kLargePermittedAllocation;
void* buf = malloc(size);
if (!buf)
return;
for (;;) {
size += kLargePermittedAllocation;
void* new_buf = realloc(buf, size);
if (!buf)
break;
buf = new_buf;
}
}
#endif
// This function acts as a compiler optimization barrier. We use it to
// prevent the compiler from making an expression a compile-time constant.
// We also use it so that the compiler doesn't discard certain return values
// as something we don't need (see the comment with calloc below).
template <typename Type>
Type HideValueFromCompiler(volatile Type value) {
#if defined(__GNUC__)
// In a GCC compatible compiler (GCC or Clang), make this compiler barrier
// more robust than merely using "volatile".
__asm__ volatile ("" : "+r" (value));
#endif // __GNUC__
return value;
}
// Tcmalloc and Windows allocator shim support setting malloc limits.
// - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
// - ADDRESS_SANITIZER and SYZYASAN because they have their own memory allocator
// - IOS does not use tcmalloc
// - OS_MACOSX does not use tcmalloc
// - Windows allocator shim defines ALLOCATOR_SHIM
#if (!defined(NO_TCMALLOC) || defined(ALLOCATOR_SHIM)) && \
!defined(ADDRESS_SANITIZER) && !defined(OS_IOS) && !defined(OS_MACOSX) && \
!defined(SYZYASAN)
#define MALLOC_OVERFLOW_TEST(function) function
#else
#define MALLOC_OVERFLOW_TEST(function) DISABLED_##function
#endif
// TODO(jln): switch to std::numeric_limits<int>::max() when we switch to
// C++11.
const size_t kTooBigAllocSize = INT_MAX;
// Detect runtime TCMalloc bypasses.
bool IsTcMallocBypassed() {
#if defined(OS_LINUX)
// This should detect a TCMalloc bypass from Valgrind.
char* g_slice = getenv("G_SLICE");
if (g_slice && !strcmp(g_slice, "always-malloc"))
return true;
#endif
return false;
}
bool CallocDiesOnOOM() {
// The sanitizers' calloc dies on OOM instead of returning NULL.
// The wrapper function in base/process_util_linux.cc that is used when we
// compile without TCMalloc will just die on OOM instead of returning NULL.
#if defined(ADDRESS_SANITIZER) || \
defined(MEMORY_SANITIZER) || \
defined(THREAD_SANITIZER) || \
(defined(OS_LINUX) && defined(NO_TCMALLOC))
return true;
#else
return false;
#endif
}
// Fake test that allow to know the state of TCMalloc by looking at bots.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(IsTCMallocDynamicallyBypassed)) {
printf("Malloc is dynamically bypassed: %s\n",
IsTcMallocBypassed() ? "yes." : "no.");
}
// The MemoryAllocationRestrictions* tests test that we can not allocate a
// memory range that cannot be indexed via an int. This is used to mitigate
// vulnerabilities in libraries that use int instead of size_t. See
// crbug.com/169327.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsMalloc)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(malloc(kTooBigAllocSize))));
ASSERT_TRUE(!ptr);
}
}
#if defined(GTEST_HAS_DEATH_TEST) && defined(OS_WIN)
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationMallocDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
scoped_ptr<char, base::FreeDeleter> ptr;
EXPECT_DEATH(ptr.reset(static_cast<char*>(
HideValueFromCompiler(malloc(kTooBigAllocSize)))),
"");
ASSERT_TRUE(!ptr);
}
_set_new_handler(NULL);
_set_new_mode(0);
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationExhaustDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
ASSERT_DEATH(ExhaustMemoryWithMalloc(), "");
}
_set_new_handler(NULL);
_set_new_mode(0);
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryReallocationExhaustDeathTest)) {
_set_new_handler(&OnNoMemory);
_set_new_mode(1);
{
ASSERT_DEATH(ExhaustMemoryWithRealloc(), "");
}
_set_new_handler(NULL);
_set_new_mode(0);
}
#endif
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsCalloc)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));
ASSERT_TRUE(!ptr);
}
}
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsRealloc)) {
if (!IsTcMallocBypassed()) {
char* orig_ptr = static_cast<char*>(malloc(1));
ASSERT_TRUE(orig_ptr);
scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));
ASSERT_TRUE(!ptr);
// If realloc() did not succeed, we need to free orig_ptr.
free(orig_ptr);
}
}
typedef struct {
char large_array[kTooBigAllocSize];
} VeryLargeStruct;
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsNew)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<VeryLargeStruct> ptr(
HideValueFromCompiler(new (nothrow) VeryLargeStruct));
ASSERT_TRUE(!ptr);
}
}
#if defined(GTEST_HAS_DEATH_TEST) && defined(OS_WIN)
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationNewDeathTest)) {
_set_new_handler(&OnNoMemory);
{
scoped_ptr<VeryLargeStruct> ptr;
EXPECT_DEATH(
ptr.reset(HideValueFromCompiler(new (nothrow) VeryLargeStruct)), "");
ASSERT_TRUE(!ptr);
}
_set_new_handler(NULL);
}
#endif
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(MemoryAllocationRestrictionsNewArray)) {
if (!IsTcMallocBypassed()) {
scoped_ptr<char[]> ptr(
HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));
ASSERT_TRUE(!ptr);
}
}
// The tests bellow check for overflows in new[] and calloc().
// There are platforms where these tests are known to fail. We would like to
// be able to easily check the status on the bots, but marking tests as
// FAILS_ is too clunky.
void OverflowTestsSoftExpectTrue(bool overflow_detected) {
if (!overflow_detected) {
#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
// Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
// fail the test, but report.
printf("Platform has overflow: %s\n",
!overflow_detected ? "yes." : "no.");
#else
// Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
// aren't).
EXPECT_TRUE(overflow_detected);
#endif
}
}
#if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER) || defined(OS_MACOSX)
#define MAYBE_NewOverflow DISABLED_NewOverflow
#else
#define MAYBE_NewOverflow NewOverflow
#endif
// Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
// IOS doesn't honor nothrow, so disable the test there.
// Crashes on Windows Dbg builds, disable there as well.
// Fails on Mac 10.8 http://crbug.com/227092
TEST(SecurityTest, MAYBE_NewOverflow) {
const size_t kArraySize = 4096;
// We want something "dynamic" here, so that the compiler doesn't
// immediately reject crazy arrays.
const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
// numeric_limits are still not constexpr until we switch to C++11, so we
// use an ugly cast.
const size_t kMaxSizeT = ~static_cast<size_t>(0);
ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
{
scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
char[kDynamicArraySize2][kArraySize]);
OverflowTestsSoftExpectTrue(!array_pointer);
}
// On windows, the compiler prevents static array sizes of more than
// 0x7fffffff (error C2148).
#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
ALLOW_UNUSED_LOCAL(kDynamicArraySize);
#else
{
scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
char[kDynamicArraySize][kArraySize2]);
OverflowTestsSoftExpectTrue(!array_pointer);
}
#endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
}
// Call calloc(), eventually free the memory and return whether or not
// calloc() did succeed.
bool CallocReturnsNull(size_t nmemb, size_t size) {
// We need the two calls to HideValueFromCompiler(): we have seen LLVM
// optimize away the call to calloc() entirely and assume the pointer to not
// be NULL.
scoped_ptr<char, base::FreeDeleter> array_pointer(
static_cast<char*>(HideValueFromCompiler(calloc(nmemb, size))));
return HideValueFromCompiler(array_pointer.get()) == NULL;
}
// Test if calloc() can overflow.
TEST(SecurityTest, CallocOverflow) {
const size_t kArraySize = 4096;
const size_t kMaxSizeT = numeric_limits<size_t>::max();
const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
if (!CallocDiesOnOOM()) {
EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2));
EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize));
} else {
// It's also ok for calloc to just terminate the process.
#if defined(GTEST_HAS_DEATH_TEST)
EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), "");
EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), "");
#endif // GTEST_HAS_DEATH_TEST
}
}
#if defined(OS_LINUX) && defined(__x86_64__)
// Check if ptr1 and ptr2 are separated by less than size chars.
bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
reinterpret_cast<char*>(std::min(ptr1, ptr2));
return static_cast<size_t>(ptr_diff) <= size;
}
// Check if TCMalloc uses an underlying random memory allocator.
TEST(SecurityTest, MALLOC_OVERFLOW_TEST(RandomMemoryAllocations)) {
if (IsTcMallocBypassed())
return;
size_t kPageSize = 4096; // We support x86_64 only.
// Check that malloc() returns an address that is neither the kernel's
// un-hinted mmap area, nor the current brk() area. The first malloc() may
// not be at a random address because TCMalloc will first exhaust any memory
// that it has allocated early on, before starting the sophisticated
// allocators.
void* default_mmap_heap_address =
mmap(0, kPageSize, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
ASSERT_NE(default_mmap_heap_address,
static_cast<void*>(MAP_FAILED));
ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
void* brk_heap_address = sbrk(0);
ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
ASSERT_TRUE(brk_heap_address != NULL);
// 1 MB should get us past what TCMalloc pre-allocated before initializing
// the sophisticated allocators.
size_t kAllocSize = 1<<20;
scoped_ptr<char, base::FreeDeleter> ptr(
static_cast<char*>(malloc(kAllocSize)));
ASSERT_TRUE(ptr != NULL);
// If two pointers are separated by less than 512MB, they are considered
// to be in the same area.
// Our random pointer could be anywhere within 0x3fffffffffff (46bits),
// and we are checking that it's not withing 1GB (30 bits) from two
// addresses (brk and mmap heap). We have roughly one chance out of
// 2^15 to flake.
const size_t kAreaRadius = 1<<29;
bool in_default_mmap_heap = ArePointersToSameArea(
ptr.get(), default_mmap_heap_address, kAreaRadius);
EXPECT_FALSE(in_default_mmap_heap);
bool in_default_brk_heap = ArePointersToSameArea(
ptr.get(), brk_heap_address, kAreaRadius);
EXPECT_FALSE(in_default_brk_heap);
// In the implementation, we always mask our random addresses with
// kRandomMask, so we use it as an additional detection mechanism.
const uintptr_t kRandomMask = 0x3fffffffffffULL;
bool impossible_random_address =
reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
EXPECT_FALSE(impossible_random_address);
}
#endif // defined(OS_LINUX) && defined(__x86_64__)
} // namespace
|
Fix SecurityTest.CallocOverflow in -Os builds.
|
clang/win: Fix SecurityTest.CallocOverflow in -Os builds.
The additional indirection foils clang's efforts...for now.
BUG=467929
Review URL: https://codereview.chromium.org/1064713003
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#323978}
|
C++
|
bsd-3-clause
|
Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,ltilve/chromium,ltilve/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk
|
4acd8b01fd3b182af9f169040af1f95b09b0c803
|
src/cpp/session/modules/jobs/ScriptJob.cpp
|
src/cpp/session/modules/jobs/ScriptJob.cpp
|
/*
* ScriptJob.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <boost/asio.hpp>
#include <r/RExec.hpp>
#include <core/Algorithm.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#include "ScriptJob.hpp"
#include "JobsApi.hpp"
#define kProgressDelim "__"
#define kProgressStart kProgressDelim "rs_progress_0" kProgressDelim " "
#define kProgressEnd " " kProgressDelim "rs_progress_1" kProgressDelim
#define kProgressMiddle " " kProgressDelim " "
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace jobs {
namespace {
class ScriptJob : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<ScriptJob> create(
const ScriptLaunchSpec& spec,
boost::function<void()> onComplete)
{
boost::shared_ptr<ScriptJob> pJob(new ScriptJob(spec, onComplete));
pJob->start();
return pJob;
}
std::string id()
{
if (job_)
return job_->id();
return "";
}
private:
ScriptJob(const ScriptLaunchSpec& spec,
boost::function<void()> onComplete):
spec_(spec),
completed_(false),
onComplete_(onComplete)
{
}
void start()
{
Error error;
// add the job -- currently idle until we get some content from it
job_ = addJob(spec_.path().filename(), "", "", 0, JobIdle, false);
std::string importRdata = "NULL";
std::string exportRdata = "NULL";
if (spec_.importEnv())
{
// create temporary file to save/load the data
FilePath::tempFilePath(&import_);
importRdata = "'" + string_utils::utf8ToSystem(import_.absolutePath()) + "'";
// prepare the environment for the script by exporting the current env
setJobStatus(job_, "Preparing environment");
r::exec::RFunction save("save.image");
save.addParam("file", import_.absolutePath());
save.addParam("safe", false); // no need to write a temp file
error = save.call();
if (error)
{
job_->addOutput("Error importing environment: " + error.summary() + "\n", true);
}
// clear status in preparation for execution
setJobStatus(job_, "");
}
if (!spec_.exportEnv().empty())
{
// if exporting, create a file to host the exported values
FilePath::tempFilePath(&export_);
exportRdata = "'" + string_utils::utf8ToSystem(export_.absolutePath()) + "'";
}
// form the command to send to R
std::string cmd = "source('" +
string_utils::utf8ToSystem(
string_utils::singleQuotedStrEscape(
session::options().modulesRSourcePath()
.complete("SourceWithProgress.R").absolutePath())) +
"'); sourceWithProgress(script = '" +
string_utils::utf8ToSystem(
string_utils::singleQuotedStrEscape(spec_.path().absolutePath())) + "', "
"encoding = '" + spec_.encoding() + "', "
"con = stdout(), "
"importRdata = " + importRdata + ", "
"exportRdata = " + exportRdata + ");";
core::system::Options environment;
async_r::AsyncRProcess::start(cmd.c_str(), environment, spec_.workingDir(),
async_r::R_PROCESS_NO_RDATA);
}
void onStdout(const std::string& output)
{
// split into lines
std::vector<std::string> lines = core::algorithm::split(output, "\n");
// examine each line and look for progress markers; for performance we do this using
// piecewise string indexing rather than regular expressions
for (size_t i = 0; i < lines.size(); i++)
{
std::string line = lines.at(i);
// initialize string positions (where we found the progress marker)
size_t start = std::string::npos,
middle = std::string::npos,
end = std::string::npos;
// look for the start of the progress marker
start = line.find(kProgressStart);
if (start != std::string::npos)
{
// ... and for the middle ...
middle = line.find(kProgressMiddle,
start + std::strlen(kProgressStart));
if (middle != std::string::npos)
{
// ... and finally the end.
size_t end = line.find(kProgressEnd, middle + std::strlen(kProgressMiddle));
if (end != std::string::npos)
{
// we found all three, so split up the string accordingly.
size_t begin = start + std::strlen(kProgressStart);
std::string cat = line.substr(begin, middle - begin);
size_t mid = middle + std::strlen(kProgressMiddle);
std::string arg = line.substr(mid, end - mid);
// invoke the progress handler with our discoveries
onProgress(cat, arg);
}
}
}
if (job_)
{
std::string output;
if (start != std::string::npos)
{
// emit the output that occurred before the start marker
output = line.substr(0, start);
}
if (end != std::string::npos)
{
// emit the output that occurred after the end marker
output.append(line.substr(end + std::strlen(kProgressEnd)));
}
if (start == std::string::npos && end == std::string::npos)
{
// no progress markers were found; just emit the whole line
output.append(line);
}
if (!output.empty())
{
// if this isn't the final line in the set, add a newline
if (i < lines.size() - 1)
{
output.append("\n");
}
job_->addOutput(output, false);
}
}
}
}
void onStderr(const std::string& output)
{
if (job_)
job_->addOutput(output, true);
}
void onCompleted(int exitStatus)
{
Error error;
r::sexp::Protect protect;
// export results if requested
if (!spec_.exportEnv().empty() && export_.exists())
{
setJobStatus(job_, "Loading results");
r::exec::RFunction load("load");
load.addParam("file", export_.absolutePath());
if (spec_.exportEnv() == "R_GlobalEnv")
{
// user requested that results be loaded into the global environment
load.addParam("envir", R_GlobalEnv);
}
else
{
// user requested a named local environment
SEXP localEnv = R_NilValue;
error = r::exec::evaluateString(
"`" + spec_.exportEnv() + "` <- new.env(parent = emptyenv())",
&localEnv, &protect);
load.addParam("envir", localEnv);
}
if (!error)
{
error = load.call();
}
if (error)
{
job_->addOutput("Error loading results: " + error.summary() + "\n", true);
}
else
{
// act as though the user had just invoked load() at the R console; this will cause the
// environment monitor to pick up the new values, if any
module_context::events().onDetectChanges(module_context::ChangeSourceREPL);
}
setJobStatus(job_, "");
}
// mark job state
if (job_)
setJobState(job_, exitStatus == 0 && completed_ ? JobSucceeded : JobFailed);
// clean up temporary files, if we used them
import_.removeIfExists();
export_.removeIfExists();
// run caller-provided completion function
onComplete_();
}
void onProgress(const std::string& cat, const std::string& argument)
{
// process argument according to category
if (cat == "count")
{
// record job as started
int count = safe_convert::stringTo<int>(argument, 0);
job_->setProgressMax(count);
// set state to running
setJobState(job_, JobRunning);
}
else if (cat == "statement" && job_)
{
int statement = safe_convert::stringTo<int>(argument, 0);
setJobProgress(job_, statement);
}
else if (cat == "completed")
{
completed_ = true;
// clear the progress text
setJobStatus(job_, "");
}
else if (cat == "section" && job_)
{
setJobStatus(job_, argument);
}
}
boost::shared_ptr<Job> job_;
ScriptLaunchSpec spec_;
bool completed_;
FilePath import_;
FilePath export_;
boost::function<void()> onComplete_;
};
std::vector<boost::shared_ptr<ScriptJob> > s_scripts;
} // anonymous namespace
ScriptLaunchSpec::ScriptLaunchSpec(
const core::FilePath& path,
const std::string& encoding,
const core::FilePath& workingDir,
bool importEnv,
const std::string& exportEnv):
path_(path),
encoding_(encoding),
workingDir_(workingDir),
importEnv_(importEnv),
exportEnv_(exportEnv)
{
}
FilePath ScriptLaunchSpec::path()
{
return path_;
}
FilePath ScriptLaunchSpec::workingDir()
{
return workingDir_;
}
std::string ScriptLaunchSpec::exportEnv()
{
return exportEnv_;
}
bool ScriptLaunchSpec::importEnv()
{
return importEnv_;
}
std::string ScriptLaunchSpec::encoding()
{
return encoding_;
}
Error startScriptJob(const ScriptLaunchSpec& spec)
{
boost::shared_ptr<ScriptJob> job = ScriptJob::create(spec,
[&]()
{
// remove the script from the list of those running
s_scripts.erase(std::remove(s_scripts.begin(), s_scripts.end(), job), s_scripts.end());
});
s_scripts.push_back(job);
return Success();
}
} // namespace jobs
} // namespace modules
} // namespace session
} // namespace rstudio
|
/*
* ScriptJob.cpp
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <boost/asio.hpp>
#include <r/RExec.hpp>
#include <core/Algorithm.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncRProcess.hpp>
#include "ScriptJob.hpp"
#include "JobsApi.hpp"
#define kProgressDelim "__"
#define kProgressStart kProgressDelim "rs_progress_0" kProgressDelim " "
#define kProgressEnd " " kProgressDelim "rs_progress_1" kProgressDelim
#define kProgressMiddle " " kProgressDelim " "
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace jobs {
namespace {
class ScriptJob : public async_r::AsyncRProcess
{
public:
static boost::shared_ptr<ScriptJob> create(
const ScriptLaunchSpec& spec,
boost::function<void()> onComplete)
{
boost::shared_ptr<ScriptJob> pJob(new ScriptJob(spec, onComplete));
pJob->start();
return pJob;
}
std::string id()
{
if (job_)
return job_->id();
return "";
}
private:
ScriptJob(const ScriptLaunchSpec& spec,
boost::function<void()> onComplete):
spec_(spec),
completed_(false),
onComplete_(onComplete)
{
}
void start()
{
Error error;
// add the job -- currently idle until we get some content from it
job_ = addJob(spec_.path().filename(), "", "", 0, JobIdle, false);
std::string importRdata = "NULL";
std::string exportRdata = "NULL";
if (spec_.importEnv())
{
// create temporary file to save/load the data
FilePath::tempFilePath(&import_);
importRdata = "'" + string_utils::utf8ToSystem(import_.absolutePath()) + "'";
// prepare the environment for the script by exporting the current env
setJobStatus(job_, "Preparing environment");
r::exec::RFunction save("save.image");
save.addParam("file", string_utils::utf8ToSystem(import_.absolutePath()));
save.addParam("safe", false); // no need to write a temp file
error = save.call();
if (error)
{
job_->addOutput("Error importing environment: " + error.summary() + "\n", true);
}
// clear status in preparation for execution
setJobStatus(job_, "");
}
if (!spec_.exportEnv().empty())
{
// if exporting, create a file to host the exported values
FilePath::tempFilePath(&export_);
exportRdata = "'" + string_utils::utf8ToSystem(export_.absolutePath()) + "'";
}
// form the command to send to R
std::string cmd = "source('" +
string_utils::utf8ToSystem(
string_utils::singleQuotedStrEscape(
session::options().modulesRSourcePath()
.complete("SourceWithProgress.R").absolutePath())) +
"'); sourceWithProgress(script = '" +
string_utils::utf8ToSystem(
string_utils::singleQuotedStrEscape(spec_.path().absolutePath())) + "', "
"encoding = '" + spec_.encoding() + "', "
"con = stdout(), "
"importRdata = " + importRdata + ", "
"exportRdata = " + exportRdata + ");";
core::system::Options environment;
async_r::AsyncRProcess::start(cmd.c_str(), environment, spec_.workingDir(),
async_r::R_PROCESS_NO_RDATA);
}
void onStdout(const std::string& output)
{
// split into lines
std::vector<std::string> lines = core::algorithm::split(output, "\n");
// examine each line and look for progress markers; for performance we do this using
// piecewise string indexing rather than regular expressions
for (size_t i = 0; i < lines.size(); i++)
{
std::string line = lines.at(i);
// initialize string positions (where we found the progress marker)
size_t start = std::string::npos,
middle = std::string::npos,
end = std::string::npos;
// look for the start of the progress marker
start = line.find(kProgressStart);
if (start != std::string::npos)
{
// ... and for the middle ...
middle = line.find(kProgressMiddle,
start + std::strlen(kProgressStart));
if (middle != std::string::npos)
{
// ... and finally the end.
size_t end = line.find(kProgressEnd, middle + std::strlen(kProgressMiddle));
if (end != std::string::npos)
{
// we found all three, so split up the string accordingly.
size_t begin = start + std::strlen(kProgressStart);
std::string cat = line.substr(begin, middle - begin);
size_t mid = middle + std::strlen(kProgressMiddle);
std::string arg = line.substr(mid, end - mid);
// invoke the progress handler with our discoveries
onProgress(cat, arg);
}
}
}
if (job_)
{
std::string output;
if (start != std::string::npos)
{
// emit the output that occurred before the start marker
output = line.substr(0, start);
}
if (end != std::string::npos)
{
// emit the output that occurred after the end marker
output.append(line.substr(end + std::strlen(kProgressEnd)));
}
if (start == std::string::npos && end == std::string::npos)
{
// no progress markers were found; just emit the whole line
output.append(line);
}
if (!output.empty())
{
// if this isn't the final line in the set, add a newline
if (i < lines.size() - 1)
{
output.append("\n");
}
job_->addOutput(output, false);
}
}
}
}
void onStderr(const std::string& output)
{
if (job_)
job_->addOutput(output, true);
}
void onCompleted(int exitStatus)
{
Error error;
r::sexp::Protect protect;
// export results if requested
if (!spec_.exportEnv().empty() && export_.exists())
{
setJobStatus(job_, "Loading results");
r::exec::RFunction load("load");
load.addParam("file", string_utils::utf8ToSystem(export_.absolutePath()));
if (spec_.exportEnv() == "R_GlobalEnv")
{
// user requested that results be loaded into the global environment
load.addParam("envir", R_GlobalEnv);
}
else
{
// user requested a named local environment
SEXP localEnv = R_NilValue;
error = r::exec::evaluateString(
"`" + spec_.exportEnv() + "` <- new.env(parent = emptyenv())",
&localEnv, &protect);
load.addParam("envir", localEnv);
}
if (!error)
{
error = load.call();
}
if (error)
{
job_->addOutput("Error loading results: " + error.summary() + "\n", true);
}
else
{
// act as though the user had just invoked load() at the R console; this will cause the
// environment monitor to pick up the new values, if any
module_context::events().onDetectChanges(module_context::ChangeSourceREPL);
}
setJobStatus(job_, "");
}
// mark job state
if (job_)
setJobState(job_, exitStatus == 0 && completed_ ? JobSucceeded : JobFailed);
// clean up temporary files, if we used them
import_.removeIfExists();
export_.removeIfExists();
// run caller-provided completion function
onComplete_();
}
void onProgress(const std::string& cat, const std::string& argument)
{
// process argument according to category
if (cat == "count")
{
// record job as started
int count = safe_convert::stringTo<int>(argument, 0);
job_->setProgressMax(count);
// set state to running
setJobState(job_, JobRunning);
}
else if (cat == "statement" && job_)
{
int statement = safe_convert::stringTo<int>(argument, 0);
setJobProgress(job_, statement);
}
else if (cat == "completed")
{
completed_ = true;
// clear the progress text
setJobStatus(job_, "");
}
else if (cat == "section" && job_)
{
setJobStatus(job_, argument);
}
}
boost::shared_ptr<Job> job_;
ScriptLaunchSpec spec_;
bool completed_;
FilePath import_;
FilePath export_;
boost::function<void()> onComplete_;
};
std::vector<boost::shared_ptr<ScriptJob> > s_scripts;
} // anonymous namespace
ScriptLaunchSpec::ScriptLaunchSpec(
const core::FilePath& path,
const std::string& encoding,
const core::FilePath& workingDir,
bool importEnv,
const std::string& exportEnv):
path_(path),
encoding_(encoding),
workingDir_(workingDir),
importEnv_(importEnv),
exportEnv_(exportEnv)
{
}
FilePath ScriptLaunchSpec::path()
{
return path_;
}
FilePath ScriptLaunchSpec::workingDir()
{
return workingDir_;
}
std::string ScriptLaunchSpec::exportEnv()
{
return exportEnv_;
}
bool ScriptLaunchSpec::importEnv()
{
return importEnv_;
}
std::string ScriptLaunchSpec::encoding()
{
return encoding_;
}
Error startScriptJob(const ScriptLaunchSpec& spec)
{
boost::shared_ptr<ScriptJob> job = ScriptJob::create(spec,
[&]()
{
// remove the script from the list of those running
s_scripts.erase(std::remove(s_scripts.begin(), s_scripts.end(), job), s_scripts.end());
});
s_scripts.push_back(job);
return Success();
}
} // namespace jobs
} // namespace modules
} // namespace session
} // namespace rstudio
|
convert file paths to system encoding
|
convert file paths to system encoding
|
C++
|
agpl-3.0
|
JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio
|
e4ae37f992f617f04d4e24160196ed3aa401962d
|
content/browser/device_sensors/device_inertial_sensor_browsertest.cc
|
content/browser/device_sensors/device_inertial_sensor_browsertest.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "content/browser/device_sensors/data_fetcher_shared_memory.h"
#include "content/browser/device_sensors/device_inertial_sensor_service.h"
#include "content/common/device_sensors/device_light_hardware_buffer.h"
#include "content/common/device_sensors/device_motion_hardware_buffer.h"
#include "content/common/device_sensors/device_orientation_hardware_buffer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_javascript_dialog_manager.h"
namespace content {
namespace {
class FakeDataFetcher : public DataFetcherSharedMemory {
public:
FakeDataFetcher()
: started_orientation_(false, false),
stopped_orientation_(false, false),
started_motion_(false, false),
stopped_motion_(false, false),
started_light_(false, false),
stopped_light_(false, false),
sensor_data_available_(true) {}
~FakeDataFetcher() override {}
bool Start(ConsumerType consumer_type, void* buffer) override {
EXPECT_TRUE(buffer);
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
{
DeviceMotionHardwareBuffer* motion_buffer =
static_cast<DeviceMotionHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateMotion(motion_buffer);
SetMotionBufferReady(motion_buffer);
started_motion_.Signal();
}
break;
case CONSUMER_TYPE_ORIENTATION:
{
DeviceOrientationHardwareBuffer* orientation_buffer =
static_cast<DeviceOrientationHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateOrientation(orientation_buffer);
SetOrientationBufferReady(orientation_buffer);
started_orientation_.Signal();
}
break;
case CONSUMER_TYPE_LIGHT:
{
DeviceLightHardwareBuffer* light_buffer =
static_cast<DeviceLightHardwareBuffer*>(buffer);
UpdateLight(light_buffer,
sensor_data_available_
? 100
: std::numeric_limits<double>::infinity());
started_light_.Signal();
}
break;
default:
return false;
}
return true;
}
bool Stop(ConsumerType consumer_type) override {
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
stopped_motion_.Signal();
break;
case CONSUMER_TYPE_ORIENTATION:
stopped_orientation_.Signal();
break;
case CONSUMER_TYPE_LIGHT:
stopped_light_.Signal();
break;
default:
return false;
}
return true;
}
void Fetch(unsigned consumer_bitmask) override {
FAIL() << "fetch should not be called";
}
FetcherType GetType() const override { return FETCHER_TYPE_DEFAULT; }
void SetSensorDataAvailable(bool available) {
sensor_data_available_ = available;
}
void SetMotionBufferReady(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void SetOrientationBufferReady(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateMotion(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.accelerationX = 1;
buffer->data.hasAccelerationX = true;
buffer->data.accelerationY = 2;
buffer->data.hasAccelerationY = true;
buffer->data.accelerationZ = 3;
buffer->data.hasAccelerationZ = true;
buffer->data.accelerationIncludingGravityX = 4;
buffer->data.hasAccelerationIncludingGravityX = true;
buffer->data.accelerationIncludingGravityY = 5;
buffer->data.hasAccelerationIncludingGravityY = true;
buffer->data.accelerationIncludingGravityZ = 6;
buffer->data.hasAccelerationIncludingGravityZ = true;
buffer->data.rotationRateAlpha = 7;
buffer->data.hasRotationRateAlpha = true;
buffer->data.rotationRateBeta = 8;
buffer->data.hasRotationRateBeta = true;
buffer->data.rotationRateGamma = 9;
buffer->data.hasRotationRateGamma = true;
buffer->data.interval = 100;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateOrientation(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.alpha = 1;
buffer->data.hasAlpha = true;
buffer->data.beta = 2;
buffer->data.hasBeta = true;
buffer->data.gamma = 3;
buffer->data.hasGamma = true;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateLight(DeviceLightHardwareBuffer* buffer, double lux) {
buffer->seqlock.WriteBegin();
buffer->data.value = lux;
buffer->seqlock.WriteEnd();
}
base::WaitableEvent started_orientation_;
base::WaitableEvent stopped_orientation_;
base::WaitableEvent started_motion_;
base::WaitableEvent stopped_motion_;
base::WaitableEvent started_light_;
base::WaitableEvent stopped_light_;
bool sensor_data_available_;
private:
DISALLOW_COPY_AND_ASSIGN(FakeDataFetcher);
};
class DeviceInertialSensorBrowserTest : public ContentBrowserTest {
public:
DeviceInertialSensorBrowserTest()
: fetcher_(nullptr), io_loop_finished_event_(false, false) {}
void SetUpOnMainThread() override {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceInertialSensorBrowserTest::SetUpOnIOThread, this));
io_loop_finished_event_.Wait();
}
void SetUpOnIOThread() {
fetcher_ = new FakeDataFetcher();
DeviceInertialSensorService::GetInstance()->
SetDataFetcherForTesting(fetcher_);
io_loop_finished_event_.Signal();
}
void DelayAndQuit(base::TimeDelta delay) {
base::PlatformThread::Sleep(delay);
base::MessageLoop::current()->QuitWhenIdle();
}
void WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta delay) {
ShellJavaScriptDialogManager* dialog_manager =
static_cast<ShellJavaScriptDialogManager*>(
shell()->GetJavaScriptDialogManager(shell()->web_contents()));
scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner();
dialog_manager->set_dialog_request_callback(
base::Bind(&DeviceInertialSensorBrowserTest::DelayAndQuit, this,
delay));
runner->Run();
}
FakeDataFetcher* fetcher_;
private:
base::WaitableEvent io_loop_finished_event_;
};
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, OrientationTest) {
// The test page will register an event handler for orientation events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_orientation_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, LightTest) {
// The test page will register an event handler for light events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_light_test.html");
// TODO(riju): remove command line args when the feature goes stable.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, MotionTest) {
// The test page will register an event handler for motion events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_motion_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
}
// crbug/416406. The test is flaky.
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
DISABLED_LightOneOffInfintyTest) {
// The test page will register an event handler for light events,
// expects to get an event with value equal to Infinity. This tests that the
// one-off infinity event still propagates to window after the alert is
// dismissed and the callback is invoked which navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
// TODO(riju): remove command line args when the feature goes stable.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_light_infinity_test.html");
shell()->LoadURL(test_url);
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID)
#define MAYBE_OrientationNullTestWithAlert DISABLED_OrientationNullTestWithAlert
#else
#define MAYBE_OrientationNullTestWithAlert OrientationNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_OrientationNullTestWithAlert) {
// The test page will register an event handler for orientation events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url = GetTestUrl("device_sensors",
"device_orientation_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaking in the android try bot. See http://crbug.com/360578.
#if defined(OS_ANDROID) || defined(OS_WIN)
#define MAYBE_MotionNullTestWithAlert DISABLED_MotionNullTestWithAlert
#else
#define MAYBE_MotionNullTestWithAlert MotionNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_MotionNullTestWithAlert) {
// The test page will register an event handler for motion events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_motion_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
} // namespace
} // namespace content
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
#include "content/browser/device_sensors/data_fetcher_shared_memory.h"
#include "content/browser/device_sensors/device_inertial_sensor_service.h"
#include "content/common/device_sensors/device_light_hardware_buffer.h"
#include "content/common/device_sensors/device_motion_hardware_buffer.h"
#include "content/common/device_sensors/device_orientation_hardware_buffer.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/content_browser_test.h"
#include "content/public/test/content_browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "content/shell/browser/shell.h"
#include "content/shell/browser/shell_javascript_dialog_manager.h"
namespace content {
namespace {
class FakeDataFetcher : public DataFetcherSharedMemory {
public:
FakeDataFetcher()
: started_orientation_(false, false),
stopped_orientation_(false, false),
started_motion_(false, false),
stopped_motion_(false, false),
started_light_(false, false),
stopped_light_(false, false),
sensor_data_available_(true) {}
~FakeDataFetcher() override {}
bool Start(ConsumerType consumer_type, void* buffer) override {
EXPECT_TRUE(buffer);
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
{
DeviceMotionHardwareBuffer* motion_buffer =
static_cast<DeviceMotionHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateMotion(motion_buffer);
SetMotionBufferReady(motion_buffer);
started_motion_.Signal();
}
break;
case CONSUMER_TYPE_ORIENTATION:
{
DeviceOrientationHardwareBuffer* orientation_buffer =
static_cast<DeviceOrientationHardwareBuffer*>(buffer);
if (sensor_data_available_)
UpdateOrientation(orientation_buffer);
SetOrientationBufferReady(orientation_buffer);
started_orientation_.Signal();
}
break;
case CONSUMER_TYPE_LIGHT:
{
DeviceLightHardwareBuffer* light_buffer =
static_cast<DeviceLightHardwareBuffer*>(buffer);
UpdateLight(light_buffer,
sensor_data_available_
? 100
: std::numeric_limits<double>::infinity());
started_light_.Signal();
}
break;
default:
return false;
}
return true;
}
bool Stop(ConsumerType consumer_type) override {
switch (consumer_type) {
case CONSUMER_TYPE_MOTION:
stopped_motion_.Signal();
break;
case CONSUMER_TYPE_ORIENTATION:
stopped_orientation_.Signal();
break;
case CONSUMER_TYPE_LIGHT:
stopped_light_.Signal();
break;
default:
return false;
}
return true;
}
void Fetch(unsigned consumer_bitmask) override {
FAIL() << "fetch should not be called";
}
FetcherType GetType() const override { return FETCHER_TYPE_DEFAULT; }
void SetSensorDataAvailable(bool available) {
sensor_data_available_ = available;
}
void SetMotionBufferReady(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void SetOrientationBufferReady(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateMotion(DeviceMotionHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.accelerationX = 1;
buffer->data.hasAccelerationX = true;
buffer->data.accelerationY = 2;
buffer->data.hasAccelerationY = true;
buffer->data.accelerationZ = 3;
buffer->data.hasAccelerationZ = true;
buffer->data.accelerationIncludingGravityX = 4;
buffer->data.hasAccelerationIncludingGravityX = true;
buffer->data.accelerationIncludingGravityY = 5;
buffer->data.hasAccelerationIncludingGravityY = true;
buffer->data.accelerationIncludingGravityZ = 6;
buffer->data.hasAccelerationIncludingGravityZ = true;
buffer->data.rotationRateAlpha = 7;
buffer->data.hasRotationRateAlpha = true;
buffer->data.rotationRateBeta = 8;
buffer->data.hasRotationRateBeta = true;
buffer->data.rotationRateGamma = 9;
buffer->data.hasRotationRateGamma = true;
buffer->data.interval = 100;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateOrientation(DeviceOrientationHardwareBuffer* buffer) {
buffer->seqlock.WriteBegin();
buffer->data.alpha = 1;
buffer->data.hasAlpha = true;
buffer->data.beta = 2;
buffer->data.hasBeta = true;
buffer->data.gamma = 3;
buffer->data.hasGamma = true;
buffer->data.allAvailableSensorsAreActive = true;
buffer->seqlock.WriteEnd();
}
void UpdateLight(DeviceLightHardwareBuffer* buffer, double lux) {
buffer->seqlock.WriteBegin();
buffer->data.value = lux;
buffer->seqlock.WriteEnd();
}
base::WaitableEvent started_orientation_;
base::WaitableEvent stopped_orientation_;
base::WaitableEvent started_motion_;
base::WaitableEvent stopped_motion_;
base::WaitableEvent started_light_;
base::WaitableEvent stopped_light_;
bool sensor_data_available_;
private:
DISALLOW_COPY_AND_ASSIGN(FakeDataFetcher);
};
class DeviceInertialSensorBrowserTest : public ContentBrowserTest {
public:
DeviceInertialSensorBrowserTest()
: fetcher_(nullptr), io_loop_finished_event_(false, false) {}
void SetUpOnMainThread() override {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceInertialSensorBrowserTest::SetUpOnIOThread, this));
io_loop_finished_event_.Wait();
}
void SetUpOnIOThread() {
fetcher_ = new FakeDataFetcher();
DeviceInertialSensorService::GetInstance()->
SetDataFetcherForTesting(fetcher_);
io_loop_finished_event_.Signal();
}
void DelayAndQuit(base::TimeDelta delay) {
base::PlatformThread::Sleep(delay);
base::MessageLoop::current()->QuitWhenIdle();
}
void WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta delay) {
ShellJavaScriptDialogManager* dialog_manager =
static_cast<ShellJavaScriptDialogManager*>(
shell()->GetJavaScriptDialogManager(shell()->web_contents()));
scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner();
dialog_manager->set_dialog_request_callback(
base::Bind(&DeviceInertialSensorBrowserTest::DelayAndQuit, this,
delay));
runner->Run();
}
FakeDataFetcher* fetcher_;
private:
base::WaitableEvent io_loop_finished_event_;
};
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, OrientationTest) {
// The test page will register an event handler for orientation events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_orientation_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, LightTest) {
// The test page will register an event handler for light events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_light_test.html");
// TODO(riju): remove command line args when the feature goes stable.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
}
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest, MotionTest) {
// The test page will register an event handler for motion events,
// expects to get an event with fake values, then removes the event
// handler and navigates to #pass.
GURL test_url = GetTestUrl("device_sensors", "device_motion_test.html");
NavigateToURLBlockUntilNavigationsComplete(shell(), test_url, 2);
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
}
// crbug/416406. The test is flaky.
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
DISABLED_LightOneOffInfintyTest) {
// The test page will register an event handler for light events,
// expects to get an event with value equal to Infinity. This tests that the
// one-off infinity event still propagates to window after the alert is
// dismissed and the callback is invoked which navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
// TODO(riju): remove command line args when the feature goes stable.
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableExperimentalWebPlatformFeatures);
}
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_light_infinity_test.html");
shell()->LoadURL(test_url);
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_light_.Wait();
fetcher_->stopped_light_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaky. See http://crbug.com/360578.
#if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_OrientationNullTestWithAlert DISABLED_OrientationNullTestWithAlert
#else
#define MAYBE_OrientationNullTestWithAlert OrientationNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_OrientationNullTestWithAlert) {
// The test page will register an event handler for orientation events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url = GetTestUrl("device_sensors",
"device_orientation_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_orientation_.Wait();
fetcher_->stopped_orientation_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
// Flaky. See http://crbug.com/360578.
#if defined(OS_ANDROID) || defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_MotionNullTestWithAlert DISABLED_MotionNullTestWithAlert
#else
#define MAYBE_MotionNullTestWithAlert MotionNullTestWithAlert
#endif
IN_PROC_BROWSER_TEST_F(DeviceInertialSensorBrowserTest,
MAYBE_MotionNullTestWithAlert) {
// The test page will register an event handler for motion events,
// expects to get an event with null values. The test raises a modal alert
// dialog with a delay to test that the one-off null-event still propagates
// to window after the alert is dismissed and the callback is invoked which
// navigates to #pass.
fetcher_->SetSensorDataAvailable(false);
TestNavigationObserver same_tab_observer(shell()->web_contents(), 2);
GURL test_url =
GetTestUrl("device_sensors", "device_motion_null_test_with_alert.html");
shell()->LoadURL(test_url);
// TODO(timvolodine): investigate if it is possible to test this without
// delay, crbug.com/360044.
WaitForAlertDialogAndQuitAfterDelay(base::TimeDelta::FromMilliseconds(1000));
fetcher_->started_motion_.Wait();
fetcher_->stopped_motion_.Wait();
same_tab_observer.Wait();
EXPECT_EQ("pass", shell()->web_contents()->GetLastCommittedURL().ref());
}
} // namespace
} // namespace content
|
Disable DeviceInertialSensorBrowserTest.OrientationNullTestWithAlert and DeviceIntertialSensorBrowserTest.MotionNullTestWithAlert
|
Disable DeviceInertialSensorBrowserTest.OrientationNullTestWithAlert
and DeviceIntertialSensorBrowserTest.MotionNullTestWithAlert
TBR=timvolodine
BUG=360578
Review URL: https://codereview.chromium.org/893123007
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#315687}
|
C++
|
bsd-3-clause
|
chuan9/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Chilledheart/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
|
538c9ca8406b12d3db0b16fdfe29871c486ece2d
|
GVRf/Framework/jni/objects/textures/compressed_texture_jni.cpp
|
GVRf/Framework/jni/objects/textures/compressed_texture_jni.cpp
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* 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.
*/
/***************************************************************************
* JNI
***************************************************************************/
#include "compressed_texture.h"
#include "util/gvr_jni.h"
namespace gvr {
extern "C" {
JNIEXPORT jlong JNICALL
// Note that "asynchronous_textures" becomes "asynchronous_1textures"
Java_org_gearvrf_asynchronous_NativeCompressedTexture_normalConstructor(JNIEnv * env,
jobject obj, jint target, jint internalFormat,
jint width, jint height, jint imageSize, jbyteArray bytes, jint dataOffset,
jintArray jtexture_parameters);
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_1textures_NativeCompressedTexture_mipmappedConstructor(JNIEnv * env,
jobject obj, jint target);
}
;
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_NativeCompressedTexture_normalConstructor(JNIEnv * env,
jobject obj, jint target, jint internalFormat,
jint width, jint height, jint imageSize, jbyteArray bytes, jint dataOffset,
jintArray jtexture_parameters) {
jint* texture_parameters = env->GetIntArrayElements(jtexture_parameters,0);
jbyte* data = env->GetByteArrayElements(bytes, 0);
CompressedTexture* texture =
new CompressedTexture(target, internalFormat, width, height, imageSize,
(const char*)data, dataOffset, texture_parameters);
env->ReleaseByteArrayElements(bytes, data, 0);
env->ReleaseIntArrayElements(jtexture_parameters, texture_parameters, 0);
return reinterpret_cast<jlong>(texture);
}
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_1textures_NativeCompressedTexture_mipmappedConstructor(JNIEnv * env,
jobject obj, jint target) {
return reinterpret_cast<jlong>(new CompressedTexture(target));
}
}
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* 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.
*/
/***************************************************************************
* JNI
***************************************************************************/
#include "compressed_texture.h"
#include "util/gvr_jni.h"
namespace gvr {
extern "C" {
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_NativeCompressedTexture_normalConstructor(JNIEnv * env,
jobject obj, jint target, jint internalFormat,
jint width, jint height, jint imageSize, jbyteArray bytes, jint dataOffset,
jintArray jtexture_parameters);
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_NativeCompressedTexture_mipmappedConstructor(JNIEnv * env,
jobject obj, jint target);
}
;
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_NativeCompressedTexture_normalConstructor(JNIEnv * env,
jobject obj, jint target, jint internalFormat,
jint width, jint height, jint imageSize, jbyteArray bytes, jint dataOffset,
jintArray jtexture_parameters) {
jint* texture_parameters = env->GetIntArrayElements(jtexture_parameters,0);
jbyte* data = env->GetByteArrayElements(bytes, 0);
CompressedTexture* texture =
new CompressedTexture(target, internalFormat, width, height, imageSize,
(const char*)data, dataOffset, texture_parameters);
env->ReleaseByteArrayElements(bytes, data, 0);
env->ReleaseIntArrayElements(jtexture_parameters, texture_parameters, 0);
return reinterpret_cast<jlong>(texture);
}
JNIEXPORT jlong JNICALL
Java_org_gearvrf_asynchronous_NativeCompressedTexture_mipmappedConstructor(JNIEnv * env,
jobject obj, jint target) {
return reinterpret_cast<jlong>(new CompressedTexture(target));
}
}
|
Fix for issue #230 native mipmappedConstructor not found.
|
Fix for issue #230 native mipmappedConstructor not found.
Fix for issue #230 native mipmappedConstructor not found.
|
C++
|
apache-2.0
|
dattanand/GearVRf,douglasalipio/GearVRf,chenchao1407/GearVRf,aglne/GearVRf,bsmr-android/GearVRf,phi-lira/GearVRf,mwitchwilliams/GearVRf,ragner/GearVRf,thomasflynn/GearVRf,mingsong/GearVRf,thomasflynn/GearVRf,chenchao1407/GearVRf,rodrigodzf/GearVRf,rongguodong/GearVRf,ragner/GearVRf,roshanch/GearVRf,luxiaoming/GearVRf,douglasalipio/GearVRf,rongguodong/GearVRf,rodrigodzf/GearVRf,gaurav-mcl/GearVRf,douglasalipio/GearVRf,parthmehta209/GearVRf,rongguodong/GearVRf,chenchao1407/GearVRf,phi-lira/GearVRf,ragner/GearVRf,dattanand/GearVRf,ragner/GearVRf,Samsung/GearVRf,NolaDonato/GearVRf,thomasflynn/GearVRf,NolaDonato/GearVRf,luxiaoming/GearVRf,thomasflynn/GearVRf,bsmr-android/GearVRf,gaurav-mcl/GearVRf,dattanand/GearVRf,xcaostagit/GearVRf,roshanch/GearVRf,douglasalipio/GearVRf,lassehe/GearVRf,danke-sra/GearVRf,rongguodong/GearVRf,aglne/GearVRf,rodrigodzf/GearVRf,gaurav-mcl/GearVRf,xcaostagit/GearVRf,nathan-almeida/GearVRf,Samsung/GearVRf,mwitchwilliams/GearVRf,parthmehta209/GearVRf,parthmehta209/GearVRf,roshanch/GearVRf,rahul27/GearVRf,rahul27/GearVRf,douglasalipio/GearVRf,thomasflynn/GearVRf,mingsong/GearVRf,chenchao1407/GearVRf,luxiaoming/GearVRf,rongguodong/GearVRf,danke-sra/GearVRf,mwitchwilliams/GearVRf,dattanand/GearVRf,gaurav-mcl/GearVRf,mingsong/GearVRf,gaurav-mcl/GearVRf,nathan-almeida/GearVRf,aglne/GearVRf,nathan-almeida/GearVRf,rongguodong/GearVRf,xcaostagit/GearVRf,rongguodong/GearVRf,phi-lira/GearVRf,Samsung/GearVRf,aglne/GearVRf,parthmehta209/GearVRf,thomasflynn/GearVRf,lassehe/GearVRf,luxiaoming/GearVRf,mingsong/GearVRf,roshanch/GearVRf,phi-lira/GearVRf,aglne/GearVRf,gaurav-mcl/GearVRf,nathan-almeida/GearVRf,nathan-almeida/GearVRf,rahul27/GearVRf,chenchao1407/GearVRf,aglne/GearVRf,danke-sra/GearVRf,bsmr-android/GearVRf,bsmr-android/GearVRf,rodrigodzf/GearVRf,mwitchwilliams/GearVRf,mingsong/GearVRf,rahul27/GearVRf,NolaDonato/GearVRf,danke-sra/GearVRf,xcaostagit/GearVRf,xcaostagit/GearVRf,phi-lira/GearVRf,chenchao1407/GearVRf,aglne/GearVRf,rahul27/GearVRf,douglasalipio/GearVRf,dattanand/GearVRf,lassehe/GearVRf,Samsung/GearVRf,nathan-almeida/GearVRf,aglne/GearVRf,NolaDonato/GearVRf,phi-lira/GearVRf,bsmr-android/GearVRf,dattanand/GearVRf,chenchao1407/GearVRf,rodrigodzf/GearVRf,luxiaoming/GearVRf,thomasflynn/GearVRf,NolaDonato/GearVRf,luxiaoming/GearVRf,rongguodong/GearVRf,Samsung/GearVRf,rahul27/GearVRf,rodrigodzf/GearVRf,danke-sra/GearVRf,luxiaoming/GearVRf,NolaDonato/GearVRf,lassehe/GearVRf,dattanand/GearVRf,nathan-almeida/GearVRf,Samsung/GearVRf,nathan-almeida/GearVRf,ragner/GearVRf,phi-lira/GearVRf,lassehe/GearVRf,Samsung/GearVRf,rodrigodzf/GearVRf,bsmr-android/GearVRf,parthmehta209/GearVRf,gaurav-mcl/GearVRf,rodrigodzf/GearVRf,NolaDonato/GearVRf,roshanch/GearVRf,ragner/GearVRf,chenchao1407/GearVRf,mingsong/GearVRf,gaurav-mcl/GearVRf,danke-sra/GearVRf,xcaostagit/GearVRf,mwitchwilliams/GearVRf,luxiaoming/GearVRf
|
5a89ed3bd5f2434f6dd6d1fe21c21fe79108f1ed
|
source/thewizardplusplus/wizard_parser/parser/repetition_parser.cpp
|
source/thewizardplusplus/wizard_parser/parser/repetition_parser.cpp
|
#include "repetition_parser.hpp"
#include "ast_node.hpp"
#include <memory>
namespace thewizardplusplus::wizard_parser::parser {
repetition_parser::repetition_parser(
const rule_parser::pointer& parser,
const std::size_t& minimal_number,
const std::size_t& maximal_number
):
parser{parser},
minimal_number{minimal_number},
maximal_number{maximal_number}
{}
parsing_result repetition_parser::parse(const lexer::token_span& tokens) const {
const auto [ast, counter] = parse_and_count(tokens);
return counter < minimal_number || counter > maximal_number
? parsing_result{{}, tokens}
: ast;
}
repetition_parser::counted_result repetition_parser::parse_and_count(
const lexer::token_span& tokens,
const std::size_t& counter
) const {
const auto type = (+ast_node_type::sequence)._to_string();
const auto ast = parser->parse(tokens);
if (!ast.node) {
return {{ast_node{type, {}, {}, lexer::get_offset(tokens)}, tokens}, counter};
}
const auto next_counter = counter + 1;
const auto [rest_ast, rest_counter] = parse_and_count(
ast.rest_tokens,
next_counter
);
if (!rest_ast.node) {
return {{ast_node{type, {}, {*ast.node}}, ast.rest_tokens}, next_counter};
}
return {
{ast_node{type, {}, {*ast.node, *rest_ast.node}}, rest_ast.rest_tokens},
rest_counter
};
}
namespace operators {
rule_parser::pointer operator-(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 0, 1);
}
rule_parser::pointer operator*(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 0);
}
rule_parser::pointer operator+(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 1);
}
}
}
|
#include "repetition_parser.hpp"
#include "ast_node.hpp"
#include <memory>
namespace thewizardplusplus::wizard_parser::parser {
repetition_parser::repetition_parser(
const rule_parser::pointer& parser,
const std::size_t& minimal_number,
const std::size_t& maximal_number
):
parser{parser},
minimal_number{minimal_number},
maximal_number{maximal_number}
{}
parsing_result repetition_parser::parse(const lexer::token_span& tokens) const {
const auto [ast, counter] = parse_and_count(tokens);
return counter >= minimal_number ? ast : parsing_result{{}, tokens};
}
repetition_parser::counted_result repetition_parser::parse_and_count(
const lexer::token_span& tokens,
const std::size_t& counter
) const {
const auto type = (+ast_node_type::sequence)._to_string();
const auto ast = parser->parse(tokens);
if (counter >= maximal_number || !ast.node) {
return {{ast_node{type, {}, {}, lexer::get_offset(tokens)}, tokens}, counter};
}
const auto [rest_ast, rest_counter] = parse_and_count(
ast.rest_tokens,
counter+1
);
return {
{ast_node{type, {}, {*ast.node, *rest_ast.node}}, rest_ast.rest_tokens},
rest_counter
};
}
namespace operators {
rule_parser::pointer operator-(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 0, 1);
}
rule_parser::pointer operator*(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 0);
}
rule_parser::pointer operator+(const rule_parser::pointer& parser) {
return std::make_shared<repetition_parser>(parser, 1);
}
}
}
|
Fix logic of the `parser::repetition_parser::parse_and_count()` method
|
Fix logic of the `parser::repetition_parser::parse_and_count()` method
|
C++
|
mit
|
thewizardplusplus/wizard-parser,thewizardplusplus/wizard-parser
|
5333d4b93dc1aa0a23b5ca52d6888ad53d7699ba
|
about_dialog.cpp
|
about_dialog.cpp
|
/*
* about_dialog.cpp
* PHD Guiding
*
* Created by Sylvain Girard.
* Copyright (c) 2013 Sylvain Girard.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>
BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()
AboutDialog::AboutDialog()
: wxDialog(pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME),
wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
SetBackgroundColour(*wxWHITE);
wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
#include "icons/phd2_64.png.h"
wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));
wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);
wxFileSystem::AddHandler(new wxMemoryFSHandler);
wxMemoryFSHandler::AddFile("about.html", wxString::Format(
"<html><body>"
"<font size=\"5\">"
"<b>%s %s</b></font><br>"
"<table CELLPADDING=0 cellspacing=10><tr><td>"
"<a href=\"https://openphdguiding.org\">PHD2 home - openphdguiding.org</a> "
"</td><td>"
"<a href=\"https://github.com/OpenPHDGuiding\">Source code on GitHub</a>"
"</td></tr></table>"
"<font size=\"2\">"
"Project maintainers<br>"
"<table CELLPADDING=0 cellspacing=10>"
"<tr>"
"<td>Andy Galasso</td>"
"<td>Bruce Waddington</td>"
"</tr>"
"</table>"
"<br>"
"Past maintainers<br>"
"<table CELLPADDING=0 cellspacing=10>"
"<tr>"
"<td>Craig Stark</td>"
"<td>Bret McKee</td>"
"</tr>"
"</table>"
"<br>"
"Credits<br>"
"<table CELLPADDING=0 cellspacing=7>"
"<tr>"
"<td>Bernhard Reutner-Fischer </td>"
"<td>Stefan Elste</td>"
"<td>Geoffrey Hausheer </td>"
"<td>Jared Wellman</td>"
"</tr>"
"<tr>"
"<td>John Wainwright</td>"
"<td>Sylvain Girard</td>"
"<td>Max Chen</td>"
"<td>Carsten Przygoda</td>"
"</tr>"
"<tr>"
"<td>Hans Lambermont</td>"
"<td>David Ault</td>"
"<td>Markus Wieczorek</td>"
"<td>Linkage</td>"
"</tr>"
"<tr>"
"<td>Robin Glover</td>"
"<td>Patrick Chevalley</td>"
"<td>Scott Edwards</td>"
"<td>Eiji Kaneshige</td>"
"</tr>"
"<tr>"
"<td>Konstantin Menshikoff </td>"
"<td>Jakub Bartas</td>"
"<td>Javier R</td>"
"<td>Oleh Malyi</td>"
"</tr>"
"<tr>"
"<td>Tsung-Chi Wu</td>"
"<td>Raffi Enficiaud</td>"
"<td>Sabin Fota</td>"
"<td>Dylan O'Donnell</td>"
"</tr>"
"<tr>"
"<td>Katsuhiro Kojima</td>"
"<td>Simon Taylor</td>"
"<td>Hallgeir Holien</td>"
"<td>Laurent Schmitz</td>"
"</tr>"
"<tr>"
"<td>Atushi Sakauchi</td>"
"<td>Giorgio Mazzacurati </td>"
"<td>Günter Scholz</td>"
"<td>Ray Gralak</td>"
"</tr>"
"<tr>"
"<td>Khalefa Algadi</td>"
"<td>David C. Partridge</td>"
"<td>Matteo Ghellere</td>"
"<td>norma</td>"
"</tr>"
"<tr>"
"<td>Edgar D. Klenske</td>"
"<td>Bernhard Schölkopf</td>"
"<td>Philipp Hennig</td>"
"<td>Stephan Wenninger</td>"
"</tr>"
"<tr>"
"<td>Wagner Trindade</td>"
"<td>Cyril Richard</td>"
"<td>Mattia Verga</td>"
"<td>Iván Zabala</td>"
"</tr>"
"<tr>"
"<td>Ken Self</td>"
"<td>Alex Helms</td>"
"<td>Randy Pufahl</td>"
"<td>Jasem Mutlaq</td>"
"</tr>"
"<tr>"
"<td>Thomas Stibor</td>"
"<td>Ludovic Pollet</td>"
"<td>Paweł Pleskaczyński</td>"
"<td>nabePla</td>"
"</tr>"
"<tr>"
"<td>Philip Peake</td>"
"<td>Manuel Rosales</td>"
"<td>Marcel Greter</td>"
"<td>Miquel Recacha</td>"
"</tr>"
"<tr>"
"<td>Mario Nicotra</td>"
"<td>Gerry Roberts</td>"
"<td></td>"
"<td></td>"
"</tr>"
"</table><br>"
"<br>"
"<br>"
"Copyright 2006-2013 Craig Stark<br>"
"Copyright 2009 Geoffrey Hausheer<br>"
"Copyright 2012-2013 Bret McKee<br>"
"Copyright 2013 Sylvain Girard<br>"
"Copyright 2013-2021 Andy Galasso<br>"
"Copyright 2013-2021 Bruce Waddington<br>"
"Copyright 2014 Hans Lambermont<br>"
"Copyright 2014 Robin Glover<br>"
"Copyright 2014-2017 Max Planck Society<br>"
"Copyright 2017 Ken Self<br>"
"Copyright 2019 Jasem Mutlaq<br>"
"<br>"
"<br>"
"The Predictive PEC guide algorithm is based on<br>"
"<a href=\"http://dx.doi.org/10.1109/TCST.2015.2420629\">Gaussian Process Based Predictive Control<br>for Periodic Error Correction</a>"
"</font>"
"</body></html>", APPNAME, FULLVER));
wxHtmlWindow *pHtml;
pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(580, 500), wxHW_SCROLLBAR_AUTO);
pHtml->SetBorders(0);
pHtml->LoadPage("memory:about.html");
pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());
pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));
wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
SetSizerAndFit(pTopLevelSizer);
}
AboutDialog::~AboutDialog(void)
{
wxMemoryFSHandler::RemoveFile("about.html");
}
void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
|
/*
* about_dialog.cpp
* PHD Guiding
*
* Created by Sylvain Girard.
* Copyright (c) 2013 Sylvain Girard.
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "phd.h"
#include "about_dialog.h"
#include <wx/fs_mem.h>
#include <wx/html/htmlwin.h>
BEGIN_EVENT_TABLE(AboutDialog, wxDialog)
EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)
END_EVENT_TABLE()
AboutDialog::AboutDialog()
: wxDialog(pFrame, wxID_ANY, wxString::Format(_("About %s"), APPNAME),
wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)
{
SetBackgroundColour(*wxWHITE);
wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);
#include "icons/phd2_64.png.h"
wxBitmap phd2(wxBITMAP_PNG_FROM_DATA(phd2_64));
wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, phd2);
wxFileSystem::AddHandler(new wxMemoryFSHandler);
wxMemoryFSHandler::AddFile("about.html", wxString::Format(
"<html><body>"
"<font size=\"5\">"
"<b>%s %s</b></font><br>"
"<table CELLPADDING=0 cellspacing=10><tr><td>"
"<a href=\"https://openphdguiding.org\">PHD2 home - openphdguiding.org</a> "
"</td><td>"
"<a href=\"https://github.com/OpenPHDGuiding\">Source code on GitHub</a>"
"</td></tr></table>"
"<font size=\"2\">"
"Project maintainers<br>"
"<table CELLPADDING=0 cellspacing=10>"
"<tr>"
"<td>Andy Galasso</td>"
"<td>Bruce Waddington</td>"
"</tr>"
"</table>"
"<br>"
"Past maintainers<br>"
"<table CELLPADDING=0 cellspacing=10>"
"<tr>"
"<td>Craig Stark</td>"
"<td>Bret McKee</td>"
"</tr>"
"</table>"
"<br>"
"Credits<br>"
"<table CELLPADDING=0 cellspacing=7>"
"<tr>"
"<td>Bernhard Reutner-Fischer </td>"
"<td>Stefan Elste</td>"
"<td>Geoffrey Hausheer </td>"
"<td>Jared Wellman</td>"
"</tr>"
"<tr>"
"<td>John Wainwright</td>"
"<td>Sylvain Girard</td>"
"<td>Max Chen</td>"
"<td>Carsten Przygoda</td>"
"</tr>"
"<tr>"
"<td>Hans Lambermont</td>"
"<td>David Ault</td>"
"<td>Markus Wieczorek</td>"
"<td>Linkage</td>"
"</tr>"
"<tr>"
"<td>Robin Glover</td>"
"<td>Patrick Chevalley</td>"
"<td>Scott Edwards</td>"
"<td>Eiji Kaneshige</td>"
"</tr>"
"<tr>"
"<td>Konstantin Menshikoff </td>"
"<td>Jakub Bartas</td>"
"<td>Javier R</td>"
"<td>Oleh Malyi</td>"
"</tr>"
"<tr>"
"<td>Tsung-Chi Wu</td>"
"<td>Raffi Enficiaud</td>"
"<td>Sabin Fota</td>"
"<td>Dylan O'Donnell</td>"
"</tr>"
"<tr>"
"<td>Katsuhiro Kojima</td>"
"<td>Simon Taylor</td>"
"<td>Hallgeir Holien</td>"
"<td>Laurent Schmitz</td>"
"</tr>"
"<tr>"
"<td>Atushi Sakauchi</td>"
"<td>Giorgio Mazzacurati </td>"
"<td>Günter Scholz</td>"
"<td>Ray Gralak</td>"
"</tr>"
"<tr>"
"<td>Khalefa Algadi</td>"
"<td>David C. Partridge</td>"
"<td>Matteo Ghellere</td>"
"<td>norma</td>"
"</tr>"
"<tr>"
"<td>Edgar D. Klenske</td>"
"<td>Bernhard Schölkopf</td>"
"<td>Philipp Hennig</td>"
"<td>Stephan Wenninger</td>"
"</tr>"
"<tr>"
"<td>Wagner Trindade</td>"
"<td>Cyril Richard</td>"
"<td>Mattia Verga</td>"
"<td>Iván Zabala</td>"
"</tr>"
"<tr>"
"<td>Ken Self</td>"
"<td>Alex Helms</td>"
"<td>Randy Pufahl</td>"
"<td>Jasem Mutlaq</td>"
"</tr>"
"<tr>"
"<td>Thomas Stibor</td>"
"<td>Ludovic Pollet</td>"
"<td>Paweł Pleskaczyński</td>"
"<td>nabePla</td>"
"</tr>"
"<tr>"
"<td>Philip Peake</td>"
"<td>Manuel Rosales</td>"
"<td>Marcel Greter</td>"
"<td>Miquel Recacha</td>"
"</tr>"
"<tr>"
"<td>Mario Nicotra</td>"
"<td>Gerry Roberts</td>"
"<td>Anthony Hinsinger</td>"
"<td></td>"
"</tr>"
"</table><br>"
"<br>"
"<br>"
"Copyright 2006-2013 Craig Stark<br>"
"Copyright 2009 Geoffrey Hausheer<br>"
"Copyright 2012-2013 Bret McKee<br>"
"Copyright 2013 Sylvain Girard<br>"
"Copyright 2013-2021 Andy Galasso<br>"
"Copyright 2013-2021 Bruce Waddington<br>"
"Copyright 2014 Hans Lambermont<br>"
"Copyright 2014 Robin Glover<br>"
"Copyright 2014-2017 Max Planck Society<br>"
"Copyright 2017 Ken Self<br>"
"Copyright 2019 Jasem Mutlaq<br>"
"<br>"
"<br>"
"The Predictive PEC guide algorithm is based on<br>"
"<a href=\"http://dx.doi.org/10.1109/TCST.2015.2420629\">Gaussian Process Based Predictive Control<br>for Periodic Error Correction</a>"
"</font>"
"</body></html>", APPNAME, FULLVER));
wxHtmlWindow *pHtml;
pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(580, 500), wxHW_SCROLLBAR_AUTO);
pHtml->SetBorders(0);
pHtml->LoadPage("memory:about.html");
pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());
pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));
pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));
wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);
pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());
SetSizerAndFit(pTopLevelSizer);
}
AboutDialog::~AboutDialog(void)
{
wxMemoryFSHandler::RemoveFile("about.html");
}
void AboutDialog::OnLink(wxHtmlLinkEvent & event)
{
wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());
}
|
add Anthony to About dialog
|
add Anthony to About dialog
|
C++
|
bsd-3-clause
|
OpenPHDGuiding/phd2,OpenPHDGuiding/phd2,OpenPHDGuiding/phd2,OpenPHDGuiding/phd2,OpenPHDGuiding/phd2,OpenPHDGuiding/phd2
|
c46ba5323632a48f96b39435d8aab57d55076f00
|
sipXmediaLib/src/test/mp/MpMMTimerTest.cpp
|
sipXmediaLib/src/test/mp/MpMMTimerTest.cpp
|
//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>
#include <mp/MpMMTimer.h>
#include <os/OsDateTime.h>
#include <os/OsSysLog.h>
#include <os/OsNotification.h>
#include <os/OsTask.h>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mp/MpMMTimerWnt.h>
#endif
// Forward Decl's
class MpMMTimerTest;
class TimerNotification : public OsNotification
{
public:
TimerNotification(MpMMTimerTest* pMMTimerTest);
virtual ~TimerNotification() {}
OsStatus signal(const intptr_t eventData);
private:
MpMMTimerTest* mpMMTimerTest;
};
/**
* Unittest for MpMMTimer and its successors
*/
class MpMMTimerTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(MpMMTimerTest);
CPPUNIT_TEST(testGetResolution);
CPPUNIT_TEST(testPeriodRange);
CPPUNIT_TEST(testLinearTimer);
CPPUNIT_TEST(testNotificationTimer);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
mpPerfCounts = NULL;
mPerfCountsSz = 0;
mCurNPerfCounts = 0;
}
void tearDown()
{
if(mpPerfCounts != NULL)
{
delete[] mpPerfCounts;
}
mpPerfCounts = NULL;
mPerfCountsSz = 0;
mCurNPerfCounts = 0;
}
#ifdef WIN32
double initializeWin32PerfMeasurementTools()
{
// Initialize performance counting measurement tools
LARGE_INTEGER perfFreqPerSec;
CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0);
//printf("Performance frequency is %I64d ticks per sec\n",
// perfFreqPerSec.QuadPart);
// Convert it to per usec instead of per sec.
double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0);
//printf("Performance frequency is %f ticks per usec\n",
// perfFreqPerUSec);
return perfFreqPerUSec;
}
#endif
void checkDeltasAgainstThresholds(long deltas[], unsigned nDeltas,
unsigned targetDelta, // <-- was periodUSecs
long lowerThresh, long upperThresh)
{
CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!",
nDeltas > 0);
printf("Timing values in microseconds, CSV: \n");
long valOutsideThreshs = targetDelta; // initialize to exactly what we want.
unsigned i;
for(i = 0; i < nDeltas; i++)
{
// Print output in CSV format, for easy graphing.
printf("%ld", deltas[i]);
printf((i < nDeltas-1) ? ", " : "\n");
// Check if we're outside some reasonable thresholds.
if(i > 0 && // don't include the first value in our tests - it's always high.
valOutsideThreshs == targetDelta) // Only check if we haven't already gone outside threshold.
{
if(deltas[i]-(long)targetDelta < lowerThresh ||
deltas[i]-(long)targetDelta > upperThresh)
{
valOutsideThreshs = deltas[i];
}
}
}
// Assert when single value outside error range specified above.
char errStrBuf[256];
snprintf(errStrBuf, 256,
"Single timer value %ld falls outside threshold of %ld to %ld us",
valOutsideThreshs, lowerThresh, upperThresh);
CPPUNIT_ASSERT_MESSAGE(errStrBuf,
(valOutsideThreshs-(long)targetDelta >= lowerThresh &&
valOutsideThreshs-(long)targetDelta <= upperThresh));
}
void checkMeanAgainstThresholds(long start, long stop, unsigned nDeltas,
unsigned targetDelta, // <-- was periodUSecs
long lowerMeanThresh, long upperMeanThresh)
{
CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!",
nDeltas > 0);
double meanAvg = 0;
meanAvg = (stop-start)/(double)nDeltas;
printf("Mean: %.2f us\n", meanAvg);
// Assert when mean is outside error range specified above.
char errStrBuf[256];
snprintf(errStrBuf, 256,
"Mean timer value %ld falls outside threshold of %ld to %ld us",
meanAvg, lowerMeanThresh, upperMeanThresh);
CPPUNIT_ASSERT_MESSAGE(errStrBuf,
(meanAvg-(long)targetDelta >= lowerMeanThresh &&
meanAvg-(long)targetDelta <= upperMeanThresh));
}
void testGetResolution()
{
// Test getting the resolution, and get it..
unsigned resolution;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getResolution(resolution));
printf("Minimum timer resolution is %d usecs\n", resolution);
}
void testPeriodRange()
{
// Test the period range static method..
unsigned unusedMin = 0;
unsigned unusedMax = 0;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
MpMMTimer::getPeriodRange(&unusedMin, &unusedMax));
}
void testLinearTimer()
{
// Set the below variables and preprocessor defines to tweak this test.
// TLT_LOOP_COUNT defines the number of timer fire repetitions to do
// (set this to an even value),
// and periodUSecs defines how long to wait in each one.
# define TLT_LOOP_CNT 500
unsigned periodUSecs = 10000;
long lowerThresh = -3000; // Assert when outside an error range
long lowerMeanThresh = -50; // specified below.
long upperThresh = 3000; // One for single values
long upperMeanThresh = 50; // One for mean values
MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear);
pMMTimer = &mmTimerWnt;
double perfFreqPerUSec = initializeWin32PerfMeasurementTools();
LARGE_INTEGER perfCount[TLT_LOOP_CNT];
#else
// Right now MMTimers are only implemented for win32.
// as other platforms are implemented, change this.
printf("MMTimer not implemented for this platform. Test disabled.\n");
return;
#endif
// Initialize the timer.
printf("Firing every %d usecs\n", periodUSecs);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));
// Perform the timing measurements.
int i;
for(i = 0; i < TLT_LOOP_CNT; i++)
{
#ifdef WIN32
CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0);
#endif
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick());
}
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
// Determine delta times from individual time measurements..
long deltas[TLT_LOOP_CNT-1];
for(i = 0; i < TLT_LOOP_CNT-1; i++)
{
deltas[i] =
#ifdef WIN32
(long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) -
__int64(perfCount[i].QuadPart / perfFreqPerUSec));
#else
0;
#endif
}
checkDeltasAgainstThresholds(deltas, TLT_LOOP_CNT-1,
periodUSecs,
lowerThresh, upperThresh);
checkMeanAgainstThresholds((long)(perfCount[0].QuadPart / perfFreqPerUSec),
(long)(perfCount[TLT_LOOP_CNT-1].QuadPart / perfFreqPerUSec),
TLT_LOOP_CNT-1,
periodUSecs,
lowerMeanThresh, upperMeanThresh);
}
void notificationTimerRecordTick()
{
#ifdef WIN32
int x;
x = mPerfCountsSz;
CPPUNIT_ASSERT(mpPerfCounts != NULL);
CPPUNIT_ASSERT(mPerfCountsSz > 0);
// Collect measurements while we have space left.
if(mCurNPerfCounts < mPerfCountsSz)
{
CPPUNIT_ASSERT(QueryPerformanceCounter(&mpPerfCounts[mCurNPerfCounts++]) > 0);
}
#else
// Nothing is currently done on other platforms, as none are implemented
// on other platforms
#endif
}
void testNotificationTimer()
{
// Set the below variables and preprocessor defines to tweak this test.
// mPerfCountsSz defines the number of timer fire repetitions to do
// (set this to an even value),
// and periodUSecs defines how long to wait in each one.
mPerfCountsSz = 500;
unsigned periodUSecs = 10000;
long lowerThresh = -3000; // Assert when outside an error range
long lowerMeanThresh = -50; // specified below.
long upperThresh = 3000; // One for single values
long upperMeanThresh = 50; // One for mean values
TimerNotification timerNotification(this);
MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
MpMMTimerWnt mmTimerWnt(MpMMTimer::Notification);
pMMTimer = &mmTimerWnt;
double perfFreqPerUSec = initializeWin32PerfMeasurementTools();
mpPerfCounts = new LARGE_INTEGER[mPerfCountsSz];
#else
// Right now MMTimers are only implemented for win32.
// as other platforms are implemented, change this.
printf("MMTimer not implemented for this platform. Test disabled.\n");
return;
#endif
// Set the notification..
pMMTimer->setNotification(&timerNotification);
// Initialize the timer.
printf("Firing every %d usecs\n", periodUSecs);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));
// Wait for the callbacks to perform the timing measurements.
OsTask::delay(periodUSecs*mPerfCountsSz/1000 + 50);
// The callbacks should be done by now, so if they aren't,
// then bitch.
//We should have a current count of the actual size of the perf buffer.
CPPUNIT_ASSERT_EQUAL(mPerfCountsSz, mCurNPerfCounts);
// Clear the OsNotification, as it doesn't need to be continuing to notify.
pMMTimer->setNotification(NULL);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
// Determine delta times from individual time measurements..
long* pDeltas = new long[mPerfCountsSz-1];
unsigned i;
for(i = 0; i < mPerfCountsSz-1; i = i++)
{
pDeltas[i] =
#ifdef WIN32
(long)(__int64(mpPerfCounts[i+1].QuadPart / perfFreqPerUSec) -
__int64(mpPerfCounts[i].QuadPart / perfFreqPerUSec));
#else
0;
#endif
}
checkDeltasAgainstThresholds(pDeltas, mPerfCountsSz-1,
periodUSecs,
lowerThresh, upperThresh);
checkMeanAgainstThresholds((long)(mpPerfCounts[0].QuadPart / perfFreqPerUSec),
(long)(mpPerfCounts[mPerfCountsSz-1].QuadPart / perfFreqPerUSec),
mPerfCountsSz-1,
periodUSecs,
lowerMeanThresh, upperMeanThresh);
// Cleanup!
delete[] pDeltas;
pDeltas = NULL;
delete[] mpPerfCounts;
mpPerfCounts = NULL;
mCurNPerfCounts = 0;
mPerfCountsSz = 0;
}
protected:
#ifdef WIN32
LARGE_INTEGER* mpPerfCounts;
unsigned mPerfCountsSz;
unsigned mCurNPerfCounts;
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest);
// Implementation of TimerNotification methods.
TimerNotification::TimerNotification(MpMMTimerTest* pMMTimerTest)
: mpMMTimerTest(pMMTimerTest)
{
CPPUNIT_ASSERT(pMMTimerTest != NULL);
}
OsStatus TimerNotification::signal(const intptr_t eventData)
{
mpMMTimerTest->notificationTimerRecordTick();
return OS_SUCCESS;
}
|
//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <sipxunit/TestUtilities.h>
#include <mp/MpMMTimer.h>
#include <os/OsDateTime.h>
#include <os/OsSysLog.h>
#include <os/OsNotification.h>
#include <os/OsTask.h>
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mp/MpMMTimerWnt.h>
#endif
// Forward Decl's
class MpMMTimerTest;
class TimerNotification : public OsNotification
{
public:
TimerNotification(MpMMTimerTest* pMMTimerTest);
virtual ~TimerNotification() {}
OsStatus signal(const intptr_t eventData);
private:
MpMMTimerTest* mpMMTimerTest;
};
/**
* Unittest for MpMMTimer and its successors
*/
class MpMMTimerTest : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(MpMMTimerTest);
CPPUNIT_TEST(testGetResolution);
CPPUNIT_TEST(testPeriodRange);
CPPUNIT_TEST(testLinearTimer);
CPPUNIT_TEST(testNotificationTimer);
CPPUNIT_TEST_SUITE_END();
public:
void setUp()
{
mpPerfCounts = NULL;
mPerfCountsSz = 0;
mCurNPerfCounts = 0;
}
void tearDown()
{
if(mpPerfCounts != NULL)
{
delete[] mpPerfCounts;
}
mpPerfCounts = NULL;
mPerfCountsSz = 0;
mCurNPerfCounts = 0;
}
#ifdef WIN32
double initializeWin32PerfMeasurementTools()
{
// Initialize performance counting measurement tools
LARGE_INTEGER perfFreqPerSec;
CPPUNIT_ASSERT(QueryPerformanceFrequency(&perfFreqPerSec) > 0);
//printf("Performance frequency is %I64d ticks per sec\n",
// perfFreqPerSec.QuadPart);
// Convert it to per usec instead of per sec.
double perfFreqPerUSec = double(perfFreqPerSec.QuadPart) / double(1000000.0);
//printf("Performance frequency is %f ticks per usec\n",
// perfFreqPerUSec);
return perfFreqPerUSec;
}
#endif
void checkDeltasAgainstThresholds(long deltas[], long absDeltas[], unsigned nDeltas,
unsigned targetDelta, // <-- was periodUSecs
long lowerThresh, long upperThresh)
{
CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!",
nDeltas > 0);
printf("Timing values in microseconds, CSV: \n");
long valOutsideThreshs = targetDelta; // initialize to exactly what we want.
unsigned i;
for(i = 0; i < nDeltas; i++)
{
// Print output in CSV format, for easy graphing.
printf("%ld\t%ld", deltas[i], absDeltas[i]);
printf((i < nDeltas-1) ? "\n" : "\n\n"); // done this way for easy change to comma CSV
// Check if we're outside some reasonable thresholds.
if(i > 0 && // don't include the first value in our tests - it's always high.
valOutsideThreshs == targetDelta) // Only check if we haven't already gone outside threshold.
{
if(deltas[i]-(long)targetDelta < lowerThresh ||
deltas[i]-(long)targetDelta > upperThresh)
{
valOutsideThreshs = deltas[i];
}
}
}
// Assert when single value outside error range specified above.
char errStrBuf[256];
snprintf(errStrBuf, 256,
"Single timer value %ld falls outside threshold of %ld to %ld us",
valOutsideThreshs, lowerThresh, upperThresh);
CPPUNIT_ASSERT_MESSAGE(errStrBuf,
(valOutsideThreshs-(long)targetDelta >= lowerThresh &&
valOutsideThreshs-(long)targetDelta <= upperThresh));
}
void checkMeanAgainstThresholds(int64_t start, int64_t stop, unsigned nDeltas,
unsigned targetDelta, // <-- was periodUSecs
long lowerMeanThresh, long upperMeanThresh)
{
CPPUNIT_ASSERT_MESSAGE("Timer didn't fire or deltas were not collected!",
nDeltas > 0);
double meanAvg = 0;
meanAvg = (stop-start)/(double)nDeltas;
printf("Mean: %.2f us\n", meanAvg);
// Assert when mean is outside error range specified above.
char errStrBuf[256];
snprintf(errStrBuf, 256,
"Mean timer value %.2f falls outside threshold of %ld to %ld us",
meanAvg, lowerMeanThresh, upperMeanThresh);
CPPUNIT_ASSERT_MESSAGE(errStrBuf,
(meanAvg-(long)targetDelta >= lowerMeanThresh &&
meanAvg-(long)targetDelta <= upperMeanThresh));
}
void testGetResolution()
{
// Test getting the resolution, and get it..
unsigned resolution;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, MpMMTimer::getResolution(resolution));
printf("Minimum timer resolution is %d usecs\n", resolution);
}
void testPeriodRange()
{
// Test the period range static method..
unsigned unusedMin = 0;
unsigned unusedMax = 0;
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS,
MpMMTimer::getPeriodRange(&unusedMin, &unusedMax));
}
void testLinearTimer()
{
// Set the below variables and preprocessor defines to tweak this test.
// TLT_LOOP_COUNT defines the number of timer fire repetitions to do
// (set this to an even value),
// and periodUSecs defines how long to wait in each one.
# define TLT_LOOP_CNT 2000
unsigned periodUSecs = 10000;
long lowerThresh = -(long)periodUSecs+1; // Assert when outside an error range
long lowerMeanThresh = -50; // specified below.
long upperThresh = periodUSecs*2-1; // One for single values
long upperMeanThresh = 50; // One for mean values
MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
MpMMTimerWnt mmTimerWnt(MpMMTimer::Linear);
pMMTimer = &mmTimerWnt;
double perfFreqPerUSec = initializeWin32PerfMeasurementTools();
LARGE_INTEGER perfCount[TLT_LOOP_CNT];
#else
// Right now MMTimers are only implemented for win32.
// as other platforms are implemented, change this.
printf("MMTimer not implemented for this platform. Test disabled.\n");
return;
#endif
// Initialize the timer.
printf("Firing every %d usecs\n", periodUSecs);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));
// Perform the timing measurements.
int i;
for(i = 0; i < TLT_LOOP_CNT; i++)
{
#ifdef WIN32
CPPUNIT_ASSERT(QueryPerformanceCounter(&perfCount[i]) > 0);
#endif
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->waitForNextTick());
}
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
// Determine delta times from individual time measurements..
long deltas[TLT_LOOP_CNT-1];
long absDeltas[TLT_LOOP_CNT-1];
for(i = 0; i < TLT_LOOP_CNT-1; i++)
{
#ifdef WIN32
deltas[i] =
(long)(__int64(perfCount[i+1].QuadPart / perfFreqPerUSec) -
__int64(perfCount[i].QuadPart / perfFreqPerUSec));
absDeltas[i] =
(long)((int64_t)((perfCount[i+1].QuadPart-perfCount[0].QuadPart) / perfFreqPerUSec) -
(int64_t)(periodUSecs)*i+1);
#else
deltas[i] = 0;
absDeltas[i] = 0;
#endif
}
checkDeltasAgainstThresholds(deltas, absDeltas, TLT_LOOP_CNT-1,
periodUSecs,
lowerThresh, upperThresh);
checkMeanAgainstThresholds((int64_t)(perfCount[0].QuadPart / perfFreqPerUSec),
(int64_t)(perfCount[TLT_LOOP_CNT-1].QuadPart / perfFreqPerUSec),
TLT_LOOP_CNT-1,
periodUSecs,
lowerMeanThresh, upperMeanThresh);
}
void notificationTimerRecordTick()
{
#ifdef WIN32
int x;
x = mPerfCountsSz;
CPPUNIT_ASSERT(mpPerfCounts != NULL);
CPPUNIT_ASSERT(mPerfCountsSz > 0);
// Collect measurements while we have space left.
if(mCurNPerfCounts < mPerfCountsSz)
{
CPPUNIT_ASSERT(QueryPerformanceCounter(&mpPerfCounts[mCurNPerfCounts++]) > 0);
}
#else
// Nothing is currently done on other platforms, as none are implemented
// on other platforms
#endif
}
void testNotificationTimer()
{
// Set the below variables and preprocessor defines to tweak this test.
// mPerfCountsSz defines the number of timer fire repetitions to do
// (set this to an even value),
// and periodUSecs defines how long to wait in each one.
mPerfCountsSz = 2000;
unsigned periodUSecs = 10000;
long lowerThresh = -(long)periodUSecs+1; // Assert when outside an error range
long lowerMeanThresh = -50; // specified below.
long upperThresh = periodUSecs*2-1; // One for single values
long upperMeanThresh = 50; // One for mean values
TimerNotification timerNotification(this);
MpMMTimer* pMMTimer = NULL;
#ifdef WIN32
MpMMTimerWnt mmTimerWnt(MpMMTimer::Notification);
pMMTimer = &mmTimerWnt;
double perfFreqPerUSec = initializeWin32PerfMeasurementTools();
mpPerfCounts = new LARGE_INTEGER[mPerfCountsSz];
#else
// Right now MMTimers are only implemented for win32.
// as other platforms are implemented, change this.
printf("MMTimer not implemented for this platform. Test disabled.\n");
return;
#endif
// Set the notification..
pMMTimer->setNotification(&timerNotification);
// Initialize the timer.
printf("Firing every %d usecs\n", periodUSecs);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->run(periodUSecs));
// Wait for the callbacks to perform the timing measurements.
OsTask::delay(periodUSecs*mPerfCountsSz/1000 + 50);
// The callbacks should be done by now, so if they aren't,
// then bitch.
//We should have a current count of the actual size of the perf buffer.
CPPUNIT_ASSERT_EQUAL(mPerfCountsSz, mCurNPerfCounts);
// Clear the OsNotification, as it doesn't need to be continuing to notify.
pMMTimer->setNotification(NULL);
CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pMMTimer->stop());
// Determine delta times from individual time measurements..
long* pDeltas = new long[mPerfCountsSz-1];
long* pAbsDeltas = new long[mPerfCountsSz-1];
unsigned i;
for(i = 0; i < mPerfCountsSz-1; i = i++)
{
#ifdef WIN32
pDeltas[i] =
(long)(__int64(mpPerfCounts[i+1].QuadPart / perfFreqPerUSec) -
__int64(mpPerfCounts[i].QuadPart / perfFreqPerUSec));
pAbsDeltas[i] =
(long)((int64_t)((mpPerfCounts[i+1].QuadPart-mpPerfCounts[0].QuadPart) / perfFreqPerUSec) -
(int64_t)(periodUSecs)*i+1);
#else
pDeltas[i] = 0;
pAbsDeltas[i] = 0;
#endif
}
checkDeltasAgainstThresholds(pDeltas, pAbsDeltas, mPerfCountsSz-1,
periodUSecs,
lowerThresh, upperThresh);
checkMeanAgainstThresholds((int64_t)(mpPerfCounts[0].QuadPart / perfFreqPerUSec),
(int64_t)(mpPerfCounts[mPerfCountsSz-1].QuadPart / perfFreqPerUSec),
mPerfCountsSz-1,
periodUSecs,
lowerMeanThresh, upperMeanThresh);
// Cleanup!
delete[] pDeltas;
pDeltas = NULL;
delete[] pAbsDeltas;
pAbsDeltas = NULL;
delete[] mpPerfCounts;
mpPerfCounts = NULL;
mCurNPerfCounts = 0;
mPerfCountsSz = 0;
}
protected:
#ifdef WIN32
LARGE_INTEGER* mpPerfCounts;
unsigned mPerfCountsSz;
unsigned mCurNPerfCounts;
#endif
};
CPPUNIT_TEST_SUITE_REGISTRATION(MpMMTimerTest);
// Implementation of TimerNotification methods.
TimerNotification::TimerNotification(MpMMTimerTest* pMMTimerTest)
: mpMMTimerTest(pMMTimerTest)
{
CPPUNIT_ASSERT(pMMTimerTest != NULL);
}
OsStatus TimerNotification::signal(const intptr_t eventData)
{
mpMMTimerTest->notificationTimerRecordTick();
return OS_SUCCESS;
}
|
Add another statistic - absDelta - a running delta since the beginning of the series calculated from current value to beginning. Effectively shows hiccups (double-hits) that occur on some systems (mine) when using Linear mode timer on windows.
|
Add another statistic - absDelta - a running delta since the beginning of the series calculated from current value to beginning. Effectively shows hiccups (double-hits) that occur on some systems (mine) when using Linear mode timer on windows.
Significantly widen the acceptable threshold for single values, as the mean is more interesting and useful.
checkMeanAgainstThresholds took start and end values that were in types not big enough to hold them - updated to use int64_t.
git-svn-id: 5274dacc98e2a95d0b0452670772bfdffe61ca90@9857 a612230a-c5fa-0310-af8b-88eea846685b
|
C++
|
lgpl-2.1
|
sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror,sipXtapi/sipXtapi-svn-mirror
|
914fdd377ed5e9dcdce2eace2e3ba08e4fc6dade
|
src/vast/index.cc
|
src/vast/index.cc
|
#include "vast/index.h"
#include <ze/type/regex.h>
#include "vast/logger.h"
#include "vast/fs/operations.h"
#include "vast/fs/fstream.h"
#include "vast/expression.h"
namespace vast {
namespace detail {
/// Picks the relevant subsets of the query expression and forwards them to
/// the index.
class picker : public expr::const_visitor
{
public:
/// Constructs a picker with an index actor.
picker(index::meta const& m, std::vector<ze::uuid>& ids)
: meta_(m)
, ids_(ids)
{
}
virtual void visit(expr::node const&)
{
assert(! "should never happen");
}
virtual void visit(expr::extractor const&)
{
assert(! "should never happen");
}
virtual void visit(expr::timestamp_extractor const&)
{
assert(rhs_.which() == ze::timepoint_type);
assert(op_ != nullptr);
switch (op_->type())
{
default:
assert(! "invalid time extractor operator");
break;
case expr::equal:
for (auto& i : meta_.ranges)
if (rhs_ >= i.first.first && rhs_ <= i.first.second)
ids_.push_back(i.second);
break;
case expr::not_equal:
for (auto& i : meta_.ranges)
if (rhs_ < i.first.first || rhs_ > i.first.second)
ids_.push_back(i.second);
break;
case expr::less:
for (auto& i : meta_.ranges)
if (rhs_ > i.first.first)
ids_.push_back(i.second);
break;
case expr::less_equal:
for (auto& i : meta_.ranges)
if (rhs_ >= i.first.first)
ids_.push_back(i.second);
break;
case expr::greater:
for (auto& i : meta_.ranges)
if (rhs_ < i.first.second)
ids_.push_back(i.second);
break;
case expr::greater_equal:
for (auto& i : meta_.ranges)
if (rhs_ <= i.first.second)
ids_.push_back(i.second);
break;
}
}
virtual void visit(expr::name_extractor const& node)
{
assert(rhs_.which() == ze::string_type || rhs_.which() == ze::regex_type);
assert(op_ != nullptr);
for (auto& i : meta_.names)
if (op_->test(i.first, rhs_))
ids_.push_back(i.second);
}
virtual void visit(expr::id_extractor const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::offset_extractor const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::exists const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::n_ary_operator const& n_ary)
{
assert(! "should never happen");
}
virtual void visit(expr::conjunction const& conj)
{
std::vector<ze::uuid> ids;
// The first intersection operand has a free shot.
auto i = conj.operands().begin();
picker p(meta_, ids);
(*i)->accept(p);
std::sort(ids.begin(), ids.end());
for (++i; i != conj.operands().end(); ++i)
{
std::vector<ze::uuid> result;
picker p(meta_, result);
(*i)->accept(p);
std::sort(result.begin(), result.end());
std::vector<ze::uuid> intersection;
std::set_intersection(ids.begin(), ids.end(),
result.begin(), result.end(),
std::back_inserter(intersection));
intersection.swap(ids);
}
ids_.swap(ids);
}
virtual void visit(expr::disjunction const& disj)
{
std::vector<ze::uuid> ids;
for (auto& operand : disj.operands())
{
std::vector<ze::uuid> result;
picker p(meta_, result);
operand->accept(p);
std::sort(result.begin(), result.end());
std::vector<ze::uuid> unification;
std::set_union(ids.begin(), ids.end(),
result.begin(), result.end(),
std::back_inserter(unification));
unification.swap(ids);
}
ids_.swap(ids);
}
virtual void visit(expr::relational_operator const& op)
{
assert(op_ == nullptr);
assert(rhs_ == ze::invalid);
assert(op.operands().size() == 2);
op_ = &op;
op.operands()[1]->accept(*this);
op.operands()[0]->accept(*this);
op_ = nullptr;
rhs_ = ze::invalid;
}
virtual void visit(expr::constant const& c)
{
assert(c.ready());
rhs_ = c.result();
}
private:
expr::relational_operator const* op_ = nullptr;
ze::value rhs_ = ze::invalid;
index::meta const& meta_;
std::vector<ze::uuid>& ids_;
};
} // namespace detail
index::index(cppa::actor_ptr archive, std::string directory)
: dir_(std::move(directory))
, archive_(archive)
{
using namespace cppa;
chaining(false);
init_state = (
on(atom("load")) >> [=]
{
LOG(verbose, index) << "spawning index @" << id();
if (! fs::exists(dir_))
{
LOG(info, index)
<< "index @" << id() << " creates new directory " << dir_;
fs::mkdir(dir_);
}
assert(fs::exists(dir_));
fs::each_file_entry(
dir_,
[&](fs::path const& p)
{
fs::ifstream file(p, std::ios::binary | std::ios::in);
ze::serialization::stream_iarchive ia(file);
segment::header hdr;
ia >> hdr;
build(hdr);
});
},
on(atom("hit"), atom("all")) >> [=]
{
if (ids_.empty())
{
reply(atom("miss"));
return;
}
reply(atom("hit"), ids_);
},
on(atom("hit"), arg_match) >> [=](expression const& expr)
{
if (ids_.empty())
{
reply(atom("miss"));
return;
}
std::vector<ze::uuid> ids;
detail::picker picker(meta_, ids);
expr.accept(picker);
if (ids.empty())
reply(atom("miss"));
else
reply(atom("hit"), std::move(ids));
},
on(atom("build"), arg_match) >> [=](segment const& s)
{
process(s);
},
on(atom("shutdown")) >> [=]()
{
quit();
LOG(verbose, index) << "index @" << id() << " terminated";
});
}
void index::process(segment const& s)
{
write(s);
build(s.head());
}
void index::write(segment const& s)
{
auto path = fs::path(dir_) / s.id().to_string();
fs::ofstream file(path, std::ios::binary | std::ios::out);
ze::serialization::stream_oarchive oa(file);
oa << s.head();
LOG(verbose, index)
<< "index @" << id() << " wrote segment header to " << path;
}
void index::build(segment::header const& hdr)
{
LOG(verbose, index) << "index @" << id()
<< " builds in-memory indexes for segment " << hdr.id;
assert(ids_.count(hdr.id) == 0);
ids_.insert(hdr.id);
// TODO: Remove as soon as newer GCC versions have adopted r181022.
#ifdef __clang__
for (auto& event : hdr.event_names)
meta_.names.emplace(event, hdr.id);
#else
for (auto& event : hdr.event_names)
meta_.names.insert({event, hdr.id});
#endif
meta_.ranges.insert({{hdr.start, hdr.end}, hdr.id});
}
} // namespace vast
|
#include "vast/index.h"
#include <ze/type/regex.h>
#include "vast/logger.h"
#include "vast/fs/operations.h"
#include "vast/fs/fstream.h"
#include "vast/expression.h"
namespace vast {
namespace detail {
/// Visits an expression and hits the meta index.
class hitter : public expr::const_visitor
{
public:
/// Constructs a hitter with an index actor.
hitter(index::meta const& m, std::vector<ze::uuid>& ids)
: meta_(m)
, ids_(ids)
{
}
virtual void visit(expr::node const&)
{
assert(! "should never happen");
}
virtual void visit(expr::extractor const&)
{
assert(! "should never happen");
}
virtual void visit(expr::timestamp_extractor const&)
{
assert(rhs_.which() == ze::timepoint_type);
assert(op_ != nullptr);
switch (op_->type())
{
default:
assert(! "invalid time extractor operator");
break;
case expr::equal:
for (auto& i : meta_.ranges)
if (rhs_ >= i.first.first && rhs_ <= i.first.second)
ids_.push_back(i.second);
break;
case expr::not_equal:
for (auto& i : meta_.ranges)
if (rhs_ < i.first.first || rhs_ > i.first.second)
ids_.push_back(i.second);
break;
case expr::less:
for (auto& i : meta_.ranges)
if (rhs_ > i.first.first)
ids_.push_back(i.second);
break;
case expr::less_equal:
for (auto& i : meta_.ranges)
if (rhs_ >= i.first.first)
ids_.push_back(i.second);
break;
case expr::greater:
for (auto& i : meta_.ranges)
if (rhs_ < i.first.second)
ids_.push_back(i.second);
break;
case expr::greater_equal:
for (auto& i : meta_.ranges)
if (rhs_ <= i.first.second)
ids_.push_back(i.second);
break;
}
}
virtual void visit(expr::name_extractor const& node)
{
assert(rhs_.which() == ze::string_type || rhs_.which() == ze::regex_type);
assert(op_ != nullptr);
for (auto& i : meta_.names)
if (op_->test(i.first, rhs_))
ids_.push_back(i.second);
}
virtual void visit(expr::id_extractor const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::offset_extractor const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::exists const&)
{
/* Do exactly nothing. */
}
virtual void visit(expr::n_ary_operator const& n_ary)
{
assert(! "should never happen");
}
virtual void visit(expr::conjunction const& conj)
{
std::vector<ze::uuid> ids;
// The first intersection operand has a free shot.
auto i = conj.operands().begin();
hitter p(meta_, ids);
(*i)->accept(p);
std::sort(ids.begin(), ids.end());
for (++i; i != conj.operands().end(); ++i)
{
std::vector<ze::uuid> result;
hitter p(meta_, result);
(*i)->accept(p);
std::sort(result.begin(), result.end());
std::vector<ze::uuid> intersection;
std::set_intersection(ids.begin(), ids.end(),
result.begin(), result.end(),
std::back_inserter(intersection));
intersection.swap(ids);
}
ids_.swap(ids);
}
virtual void visit(expr::disjunction const& disj)
{
std::vector<ze::uuid> ids;
for (auto& operand : disj.operands())
{
std::vector<ze::uuid> result;
hitter p(meta_, result);
operand->accept(p);
std::sort(result.begin(), result.end());
std::vector<ze::uuid> unification;
std::set_union(ids.begin(), ids.end(),
result.begin(), result.end(),
std::back_inserter(unification));
unification.swap(ids);
}
ids_.swap(ids);
}
virtual void visit(expr::relational_operator const& op)
{
assert(op_ == nullptr);
assert(rhs_ == ze::invalid);
assert(op.operands().size() == 2);
op_ = &op;
op.operands()[1]->accept(*this);
op.operands()[0]->accept(*this);
op_ = nullptr;
rhs_ = ze::invalid;
}
virtual void visit(expr::constant const& c)
{
assert(c.ready());
rhs_ = c.result();
}
private:
expr::relational_operator const* op_ = nullptr;
ze::value rhs_ = ze::invalid;
index::meta const& meta_;
std::vector<ze::uuid>& ids_;
};
} // namespace detail
index::index(cppa::actor_ptr archive, std::string directory)
: dir_(std::move(directory))
, archive_(archive)
{
using namespace cppa;
chaining(false);
init_state = (
on(atom("load")) >> [=]
{
LOG(verbose, index) << "spawning index @" << id();
if (! fs::exists(dir_))
{
LOG(info, index)
<< "index @" << id() << " creates new directory " << dir_;
fs::mkdir(dir_);
}
assert(fs::exists(dir_));
fs::each_file_entry(
dir_,
[&](fs::path const& p)
{
fs::ifstream file(p, std::ios::binary | std::ios::in);
ze::serialization::stream_iarchive ia(file);
segment::header hdr;
ia >> hdr;
build(hdr);
});
},
on(atom("hit"), atom("all")) >> [=]
{
if (ids_.empty())
{
reply(atom("miss"));
return;
}
reply(atom("hit"), ids_);
},
on(atom("hit"), arg_match) >> [=](expression const& expr)
{
if (ids_.empty())
{
reply(atom("miss"));
return;
}
std::vector<ze::uuid> ids;
detail::hitter hitter(meta_, ids);
expr.accept(hitter);
if (ids.empty())
reply(atom("miss"));
else
reply(atom("hit"), std::move(ids));
},
on(atom("build"), arg_match) >> [=](segment const& s)
{
process(s);
},
on(atom("shutdown")) >> [=]()
{
quit();
LOG(verbose, index) << "index @" << id() << " terminated";
});
}
void index::process(segment const& s)
{
write(s);
build(s.head());
}
void index::write(segment const& s)
{
auto path = fs::path(dir_) / s.id().to_string();
fs::ofstream file(path, std::ios::binary | std::ios::out);
ze::serialization::stream_oarchive oa(file);
oa << s.head();
LOG(verbose, index)
<< "index @" << id() << " wrote segment header to " << path;
}
void index::build(segment::header const& hdr)
{
LOG(verbose, index) << "index @" << id()
<< " builds in-memory indexes for segment " << hdr.id;
assert(ids_.count(hdr.id) == 0);
ids_.insert(hdr.id);
// TODO: Remove as soon as newer GCC versions have adopted r181022.
#ifdef __clang__
for (auto& event : hdr.event_names)
meta_.names.emplace(event, hdr.id);
#else
for (auto& event : hdr.event_names)
meta_.names.insert({event, hdr.id});
#endif
meta_.ranges.insert({{hdr.start, hdr.end}, hdr.id});
}
} // namespace vast
|
Rename picker to hitter.
|
Rename picker to hitter.
|
C++
|
bsd-3-clause
|
pmos69/vast,vast-io/vast,mavam/vast,vast-io/vast,pmos69/vast,vast-io/vast,mavam/vast,pmos69/vast,vast-io/vast,mavam/vast,pmos69/vast,vast-io/vast,mavam/vast
|
218fd83ff5ddf11846db24e7f6b3475c72df4aa9
|
src/net/ws/websocket.cpp
|
src/net/ws/websocket.cpp
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 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 <net/ws/websocket.hpp>
#include <kernel/os.hpp>
#include <util/base64.hpp>
#include <util/sha1.hpp>
#include <cstdint>
#include <net/ws/connector.hpp>
namespace net {
static inline std::string
encode_hash(const std::string& key)
{
static const std::string GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
static SHA1 sha;
sha.update(key);
sha.update(GUID);
return base64::encode(sha.as_raw());
}
const char* WebSocket::to_string(op_code code)
{
switch (code) {
case op_code::CONTINUE:
return "Continuation frame";
case op_code::TEXT:
return "Text frame";
case op_code::BINARY:
return "Binary frame";
case op_code::CLOSE:
return "Connection close";
case op_code::PING:
return "Ping";
case op_code::PONG:
return "Pong";
default:
return "Reserved (unspecified)";
}
}
WebSocket_ptr WebSocket::upgrade(http::Request& req, http::Response_writer& writer)
{
// validate handshake
auto view = req.header().value("Sec-WebSocket-Version");
if (view == nullptr || view != "13") {
writer.write_header(http::Bad_Request);
return nullptr;
}
auto key = req.header().value("Sec-WebSocket-Key");
if (key == nullptr || key.size() < 16) {
writer.write_header(http::Bad_Request);
return nullptr;
}
// create handshake response
auto& header = writer.header();
header.set_field(http::header::Connection, "Upgrade");
header.set_field(http::header::Upgrade, "WebSocket");
header.set_field("Sec-WebSocket-Accept", encode_hash(key.to_string()));
writer.write_header(http::Switching_Protocols);
auto stream = writer.connection().release();
// discard streams which can be FIN-WAIT-1
if (stream->is_connected()) {
// for now, only accept fully connected streams
return std::make_unique<WebSocket>(std::move(stream), false);
}
return nullptr;
}
WebSocket_ptr WebSocket::upgrade(http::Error err, http::Response& res, http::Connection& conn, const std::string& key)
{
if (err or res.status_code() != http::Switching_Protocols)
{
return nullptr;
}
else
{
/// validate response
auto hash = res.header().value("Sec-WebSocket-Accept");
if (hash.empty() or hash != encode_hash(key))
{
return nullptr;
}
/// create open websocket
auto stream = conn.release();
assert(stream->is_connected());
// create client websocket and call callback
return std::make_unique<WebSocket>(std::move(stream), true);
}
}
std::vector<char> WebSocket::generate_key()
{
std::vector<char> key(16);
uint16_t v;
for (size_t i = 0; i < key.size(); i += sizeof(v))
{
v = rand() & 0xffff;
memcpy(&key[i], &v, sizeof(v));
}
return key;
}
http::Server::Request_handler WebSocket::create_request_handler(
Connect_handler on_connect, Accept_handler on_accept)
{
auto handler = http::Server::Request_handler::make_packed(
[
on_connect{std::move(on_connect)},
on_accept{std::move(on_accept)}
]
(http::Request_ptr req, http::Response_writer_ptr writer)
{
if (on_accept)
{
const bool accepted = on_accept(writer->connection().peer(),
req->header().value("Origin").to_string());
if (not accepted)
{
writer->write_header(http::Unauthorized);
on_connect(nullptr);
return;
}
}
auto ws = WebSocket::upgrade(*req, *writer);
on_connect(std::move(ws));
});
return handler;
}
http::Client::Response_handler WebSocket::create_response_handler(
Connect_handler on_connect, std::string key)
{
auto handler = http::Client::Response_handler::make_packed(
[
on_connect{std::move(on_connect)},
key{std::move(key)}
]
(http::Error err, http::Response_ptr res, http::Connection& conn)
{
auto ws = WebSocket::upgrade(err, *res, conn, key);
on_connect(std::move(ws));
});
return handler;
}
void WebSocket::connect(
http::Client& client,
uri::URI remote,
Connect_handler callback)
{
// doesn't have to be extremely random, just random
std::string key = base64::encode(generate_key());
http::Header_set ws_headers {
{"Host", remote.to_string()},
{"Connection", "Upgrade" },
{"Upgrade", "WebSocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key }
};
// send HTTP request
client.get(remote, ws_headers,
WS_client_connector::create_response_handler(std::move(callback), std::move(key)));
}
void WebSocket::read_data(net::tcp::buffer_t buf, size_t len)
{
// silently ignore data from reset connection
if (this->stream == nullptr) return;
// parse message
if (message != nullptr)
{
try {
message->add(reinterpret_cast<char*>(buf.get()), len);
}
catch(const WS_error& err)
{
failure(err.what());
on_read(nullptr);
return;
}
}
// create new message
else
{
// parse header
if (len < sizeof(ws_header)) {
failure("read_data: Header was too short");
return;
}
ws_header& hdr = *reinterpret_cast<ws_header*>(buf.get());
// TODO: Add configuration for this, hardcoded max msgs of 5MB for now
if (hdr.data_length() > (1024 * 1024 * 5)) {
failure("read: Maximum message size exceeded (5MB)");
return;
}
/*
printf("Code: %hhu (%s) (final=%d)\n",
hdr.opcode(), opcode_string(hdr.opcode()), hdr.is_final());
printf("Mask: %d len=%u\n", hdr.is_masked(), hdr.mask_length());
printf("Payload: len=%u dataofs=%u\n",
hdr.data_length(), hdr.data_offset());
*/
/// unmask data (if masked)
if (hdr.is_masked()) {
if (clientside == true) {
failure("Read masked message from server");
return;
}
} else if (clientside == false) {
failure("Read unmasked message from client");
return;
}
try
{
message = std::make_unique<Message>(reinterpret_cast<char*>(buf.get()), len);
}
catch(const WS_error& err)
{
failure(err.what());
on_read(nullptr);
return;
}
}
if(message->is_complete())
{
message->unmask();
const auto& hdr = message->header();
switch (hdr.opcode()) {
case op_code::TEXT:
case op_code::BINARY:
/// .. call on_read
if (on_read) {
on_read(std::move(message));
}
break;
case op_code::CLOSE:
// they are angry with us :(
if (hdr.data_length() >= 2) {
// provide reason to user
uint16_t reason = *(uint16_t*) message->data();
if (this->on_close)
this->on_close(__builtin_bswap16(reason));
}
else {
if (this->on_close) this->on_close(1000);
}
// close it down
this->close();
break;
case op_code::PING:
write_opcode(op_code::PONG, hdr.data(), hdr.data_length());
break;
case op_code::PONG:
break;
default:
printf("Unknown opcode: %u\n", static_cast<unsigned>(hdr.opcode()));
break;
}
message.reset();
}
}
static size_t make_header(char* dest, size_t len, op_code code, bool client)
{
new (dest) ws_header;
auto& hdr = *(ws_header*) dest;
hdr.bits = 0;
hdr.set_final();
hdr.set_payload(len);
hdr.set_opcode(code);
if (client) {
hdr.set_masked(OS::cycles_since_boot() & 0xffffffff);
}
// header size + data offset
return sizeof(ws_header) + hdr.data_offset();
}
void WebSocket::write(const char* buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
Expects(code == op_code::TEXT or code == op_code::BINARY
&& "Write currently only supports TEXT or BINARY");
// allocate header and data at the same time
auto buf = net::tcp::buffer_t(new uint8_t[WS_HEADER_MAXLEN + len]);
// fill header
int header_len = make_header((char*) buf.get(), len, code, clientside);
// get data offset & fill in data into buffer
char* data_ptr = (char*) buf.get() + header_len;
memcpy(data_ptr, buffer, len);
// for client-side we have to mask the data
if (clientside)
{
// mask data to server
auto& hdr = *(ws_header*) buf.get();
assert(hdr.is_masked());
hdr.masking_algorithm();
}
/// send everything as shared buffer
this->stream->write(buf, header_len + len);
}
void WebSocket::write(net::tcp::buffer_t buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
if (UNLIKELY(clientside == true)) {
failure("write: Client-side does not support sending shared buffers");
return;
}
Expects(code == op_code::TEXT or code == op_code::BINARY
&& "Write currently only supports TEXT or BINARY");
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, len, code, false);
assert(header_len < WS_HEADER_MAXLEN);
this->stream->write(header, header_len);
/// write shared buffer
this->stream->write(buffer, len);
}
bool WebSocket::write_opcode(op_code code, const char* buffer, size_t datalen)
{
if (UNLIKELY(stream == nullptr || stream->is_writable() == false)) {
return false;
}
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, datalen, code, clientside);
this->stream->write(header, header_len);
/// write buffer (if present)
if (buffer != nullptr && datalen > 0)
this->stream->write(buffer, datalen);
return true;
}
void WebSocket::tcp_closed()
{
if (this->on_close != nullptr) this->on_close(1000);
this->reset();
}
WebSocket::WebSocket(net::Stream_ptr stream_ptr, bool client)
: stream(std::move(stream_ptr)), clientside(client)
{
assert(stream != nullptr);
this->stream->on_read(16384, {this, &WebSocket::read_data});
this->stream->on_close({this, &WebSocket::tcp_closed});
}
WebSocket::WebSocket(WebSocket&& other)
{
other.on_close = std::move(on_close);
other.on_error = std::move(on_error);
other.on_read = std::move(on_read);
other.stream = std::move(stream);
other.clientside = clientside;
}
WebSocket::~WebSocket()
{
if (stream != nullptr && stream->is_connected())
this->close();
}
void WebSocket::close()
{
/// send CLOSE message
if (this->stream->is_writable())
this->write_opcode(op_code::CLOSE, nullptr, 0);
/// close and unset socket
this->stream->close();
this->reset();
}
void WebSocket::reset()
{
this->on_close = nullptr;
this->on_error = nullptr;
this->on_read = nullptr;
stream->reset_callbacks();
stream->close();
stream = nullptr;
}
void WebSocket::failure(const std::string& reason)
{
if (stream != nullptr) stream->close();
if (this->on_error) on_error(reason);
}
const char* WebSocket::status_code(uint16_t code)
{
switch (code) {
case 1000:
return "Closed";
case 1001:
return "Going away";
case 1002:
return "Protocol error";
case 1003:
return "Cannot accept data";
case 1004:
return "Reserved";
case 1005:
return "Status code not present";
case 1006:
return "Connection closed abnormally";
case 1007:
return "Non UTF-8 data received";
case 1008:
return "Message violated policy";
case 1009:
return "Message too big";
case 1010:
return "Missing extension";
case 1011:
return "Internal server error";
case 1015:
return "TLS handshake failure";
default:
return "Unknown status code";
}
}
} // net
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2016-2017 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 <net/ws/websocket.hpp>
#include <kernel/os.hpp>
#include <util/base64.hpp>
#include <util/sha1.hpp>
#include <cstdint>
#include <net/ws/connector.hpp>
namespace net {
static inline std::string
encode_hash(const std::string& key)
{
static const std::string GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
SHA1 sha;
sha.update(key);
sha.update(GUID);
return base64::encode(sha.as_raw());
}
const char* WebSocket::to_string(op_code code)
{
switch (code) {
case op_code::CONTINUE:
return "Continuation frame";
case op_code::TEXT:
return "Text frame";
case op_code::BINARY:
return "Binary frame";
case op_code::CLOSE:
return "Connection close";
case op_code::PING:
return "Ping";
case op_code::PONG:
return "Pong";
default:
return "Reserved (unspecified)";
}
}
WebSocket_ptr WebSocket::upgrade(http::Request& req, http::Response_writer& writer)
{
// validate handshake
auto view = req.header().value("Sec-WebSocket-Version");
if (view == nullptr || view != "13") {
writer.write_header(http::Bad_Request);
return nullptr;
}
auto key = req.header().value("Sec-WebSocket-Key");
if (key == nullptr || key.size() < 16) {
writer.write_header(http::Bad_Request);
return nullptr;
}
// create handshake response
auto& header = writer.header();
header.set_field(http::header::Connection, "Upgrade");
header.set_field(http::header::Upgrade, "WebSocket");
header.set_field("Sec-WebSocket-Accept", encode_hash(key.to_string()));
writer.write_header(http::Switching_Protocols);
auto stream = writer.connection().release();
// discard streams which can be FIN-WAIT-1
if (stream->is_connected()) {
// for now, only accept fully connected streams
return std::make_unique<WebSocket>(std::move(stream), false);
}
return nullptr;
}
WebSocket_ptr WebSocket::upgrade(http::Error err, http::Response& res, http::Connection& conn, const std::string& key)
{
if (err or res.status_code() != http::Switching_Protocols)
{
return nullptr;
}
else
{
/// validate response
auto hash = res.header().value("Sec-WebSocket-Accept");
if (hash.empty() or hash != encode_hash(key))
{
return nullptr;
}
/// create open websocket
auto stream = conn.release();
assert(stream->is_connected());
// create client websocket and call callback
return std::make_unique<WebSocket>(std::move(stream), true);
}
}
std::vector<char> WebSocket::generate_key()
{
std::vector<char> key(16);
uint16_t v;
for (size_t i = 0; i < key.size(); i += sizeof(v))
{
v = rand() & 0xffff;
memcpy(&key[i], &v, sizeof(v));
}
return key;
}
http::Server::Request_handler WebSocket::create_request_handler(
Connect_handler on_connect, Accept_handler on_accept)
{
auto handler = http::Server::Request_handler::make_packed(
[
on_connect{std::move(on_connect)},
on_accept{std::move(on_accept)}
]
(http::Request_ptr req, http::Response_writer_ptr writer)
{
if (on_accept)
{
const bool accepted = on_accept(writer->connection().peer(),
req->header().value("Origin").to_string());
if (not accepted)
{
writer->write_header(http::Unauthorized);
on_connect(nullptr);
return;
}
}
auto ws = WebSocket::upgrade(*req, *writer);
on_connect(std::move(ws));
});
return handler;
}
http::Client::Response_handler WebSocket::create_response_handler(
Connect_handler on_connect, std::string key)
{
auto handler = http::Client::Response_handler::make_packed(
[
on_connect{std::move(on_connect)},
key{std::move(key)}
]
(http::Error err, http::Response_ptr res, http::Connection& conn)
{
auto ws = WebSocket::upgrade(err, *res, conn, key);
on_connect(std::move(ws));
});
return handler;
}
void WebSocket::connect(
http::Client& client,
uri::URI remote,
Connect_handler callback)
{
// doesn't have to be extremely random, just random
std::string key = base64::encode(generate_key());
http::Header_set ws_headers {
{"Host", remote.to_string()},
{"Connection", "Upgrade" },
{"Upgrade", "WebSocket"},
{"Sec-WebSocket-Version", "13"},
{"Sec-WebSocket-Key", key }
};
// send HTTP request
client.get(remote, ws_headers,
WS_client_connector::create_response_handler(std::move(callback), std::move(key)));
}
void WebSocket::read_data(net::tcp::buffer_t buf, size_t len)
{
// silently ignore data from reset connection
if (this->stream == nullptr) return;
// parse message
if (message != nullptr)
{
try {
message->add(reinterpret_cast<char*>(buf.get()), len);
}
catch(const WS_error& err)
{
failure(err.what());
on_read(nullptr);
return;
}
}
// create new message
else
{
// parse header
if (len < sizeof(ws_header)) {
failure("read_data: Header was too short");
return;
}
ws_header& hdr = *reinterpret_cast<ws_header*>(buf.get());
// TODO: Add configuration for this, hardcoded max msgs of 5MB for now
if (hdr.data_length() > (1024 * 1024 * 5)) {
failure("read: Maximum message size exceeded (5MB)");
return;
}
/*
printf("Code: %hhu (%s) (final=%d)\n",
hdr.opcode(), opcode_string(hdr.opcode()), hdr.is_final());
printf("Mask: %d len=%u\n", hdr.is_masked(), hdr.mask_length());
printf("Payload: len=%u dataofs=%u\n",
hdr.data_length(), hdr.data_offset());
*/
/// unmask data (if masked)
if (hdr.is_masked()) {
if (clientside == true) {
failure("Read masked message from server");
return;
}
} else if (clientside == false) {
failure("Read unmasked message from client");
return;
}
try
{
message = std::make_unique<Message>(reinterpret_cast<char*>(buf.get()), len);
}
catch(const WS_error& err)
{
failure(err.what());
on_read(nullptr);
return;
}
}
if(message->is_complete())
{
message->unmask();
const auto& hdr = message->header();
switch (hdr.opcode()) {
case op_code::TEXT:
case op_code::BINARY:
/// .. call on_read
if (on_read) {
on_read(std::move(message));
}
break;
case op_code::CLOSE:
// they are angry with us :(
if (hdr.data_length() >= 2) {
// provide reason to user
uint16_t reason = *(uint16_t*) message->data();
if (this->on_close)
this->on_close(__builtin_bswap16(reason));
}
else {
if (this->on_close) this->on_close(1000);
}
// close it down
this->close();
break;
case op_code::PING:
write_opcode(op_code::PONG, hdr.data(), hdr.data_length());
break;
case op_code::PONG:
break;
default:
printf("Unknown opcode: %hhu\n", hdr.opcode());
break;
}
message.reset();
}
}
static size_t make_header(char* dest, size_t len, op_code code, bool client)
{
new (dest) ws_header;
auto& hdr = *(ws_header*) dest;
hdr.bits = 0;
hdr.set_final();
hdr.set_payload(len);
hdr.set_opcode(code);
if (client) {
hdr.set_masked(OS::cycles_since_boot() & 0xffffffff);
}
// header size + data offset
return sizeof(ws_header) + hdr.data_offset();
}
void WebSocket::write(const char* buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
Expects(code == op_code::TEXT or code == op_code::BINARY
&& "Write currently only supports TEXT or BINARY");
// allocate header and data at the same time
auto buf = net::tcp::buffer_t(new uint8_t[WS_HEADER_MAXLEN + len]);
// fill header
int header_len = make_header((char*) buf.get(), len, code, clientside);
// get data offset & fill in data into buffer
char* data_ptr = (char*) buf.get() + header_len;
memcpy(data_ptr, buffer, len);
// for client-side we have to mask the data
if (clientside)
{
// mask data to server
auto& hdr = *(ws_header*) buf.get();
assert(hdr.is_masked());
hdr.masking_algorithm();
}
/// send everything as shared buffer
this->stream->write(buf, header_len + len);
}
void WebSocket::write(net::tcp::buffer_t buffer, size_t len, op_code code)
{
if (UNLIKELY(this->stream == nullptr)) {
failure("write: Already closed");
return;
}
if (UNLIKELY(this->stream->is_writable() == false)) {
failure("write: Connection not writable");
return;
}
if (UNLIKELY(clientside == true)) {
failure("write: Client-side does not support sending shared buffers");
return;
}
Expects(code == op_code::TEXT or code == op_code::BINARY
&& "Write currently only supports TEXT or BINARY");
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, len, code, false);
assert(header_len < WS_HEADER_MAXLEN);
this->stream->write(header, header_len);
/// write shared buffer
this->stream->write(buffer, len);
}
bool WebSocket::write_opcode(op_code code, const char* buffer, size_t datalen)
{
if (UNLIKELY(stream == nullptr || stream->is_writable() == false)) {
return false;
}
/// write header
char header[WS_HEADER_MAXLEN];
int header_len = make_header(header, datalen, code, clientside);
this->stream->write(header, header_len);
/// write buffer (if present)
if (buffer != nullptr && datalen > 0)
this->stream->write(buffer, datalen);
return true;
}
void WebSocket::tcp_closed()
{
if (this->on_close != nullptr) this->on_close(1000);
this->reset();
}
WebSocket::WebSocket(net::Stream_ptr stream_ptr, bool client)
: stream(std::move(stream_ptr)), clientside(client)
{
assert(stream != nullptr);
this->stream->on_read(16384, {this, &WebSocket::read_data});
this->stream->on_close({this, &WebSocket::tcp_closed});
}
WebSocket::WebSocket(WebSocket&& other)
{
other.on_close = std::move(on_close);
other.on_error = std::move(on_error);
other.on_read = std::move(on_read);
other.stream = std::move(stream);
other.clientside = clientside;
}
WebSocket::~WebSocket()
{
if (stream != nullptr && stream->is_connected())
this->close();
}
void WebSocket::close()
{
/// send CLOSE message
if (this->stream->is_writable())
this->write_opcode(op_code::CLOSE, nullptr, 0);
/// close and unset socket
this->stream->close();
this->reset();
}
void WebSocket::reset()
{
this->on_close = nullptr;
this->on_error = nullptr;
this->on_read = nullptr;
stream->reset_callbacks();
stream->close();
stream = nullptr;
}
void WebSocket::failure(const std::string& reason)
{
if (stream != nullptr) stream->close();
if (this->on_error) on_error(reason);
}
const char* WebSocket::status_code(uint16_t code)
{
switch (code) {
case 1000:
return "Closed";
case 1001:
return "Going away";
case 1002:
return "Protocol error";
case 1003:
return "Cannot accept data";
case 1004:
return "Reserved";
case 1005:
return "Status code not present";
case 1006:
return "Connection closed abnormally";
case 1007:
return "Non UTF-8 data received";
case 1008:
return "Message violated policy";
case 1009:
return "Message too big";
case 1010:
return "Missing extension";
case 1011:
return "Internal server error";
case 1015:
return "TLS handshake failure";
default:
return "Unknown status code";
}
}
} // net
|
Make SHA1 object stack allocated
|
net: Make SHA1 object stack allocated
|
C++
|
apache-2.0
|
ingve/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,ingve/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,alfred-bratterud/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,ingve/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS
|
e7649d4c5b505ab1caeab1167f0422d4dcf4ba2b
|
part/render/katelayoutcache.cpp
|
part/render/katelayoutcache.cpp
|
/* This file is part of the KDE libraries
Copyright (C) 2005 Hamish Rodda <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "katelayoutcache.h"
#include <QtCore/QMutex>
#include "katerenderer.h"
#include "kateview.h"
#include "katedocument.h"
#include "kateedit.h"
#include <kdebug.h>
static bool enableLayoutCache = false;
KateLayoutCache::KateLayoutCache(KateRenderer* renderer, QObject* parent)
: QObject(parent)
, m_renderer(renderer)
, m_startPos(-1,-1)
, m_viewWidth(0)
, m_wrap(false)
{
Q_ASSERT(m_renderer);
connect(m_renderer->doc()->history(), SIGNAL(editDone(KateEditInfo*)), SLOT(slotEditDone(KateEditInfo*)));
}
void KateLayoutCache::updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount, int viewLinesScrolled)
{
//kDebug() << startPos << " nvlc " << newViewLineCount << " vls " << viewLinesScrolled;
int oldViewLineCount = m_textLayouts.count();
if (newViewLineCount == -1)
newViewLineCount = oldViewLineCount;
enableLayoutCache = true;
int realLine = m_renderer->doc()->getRealLine(startPos.line());
int _viewLine = 0;
if (wrap()) {
// TODO check these assumptions are ok... probably they don't give much speedup anyway?
if (startPos == m_startPos && m_textLayouts.count()) {
_viewLine = m_textLayouts.first().viewLine();
} else if (viewLinesScrolled > 0 && viewLinesScrolled < m_textLayouts.count()) {
_viewLine = m_textLayouts[viewLinesScrolled].viewLine();
} else {
KateLineLayoutPtr l = line(realLine);
if (l) {
Q_ASSERT(l->isValid());
Q_ASSERT(l->length() >= startPos.column() || m_renderer->view()->wrapCursor());
for (; _viewLine < l->viewLineCount(); ++_viewLine) {
const KateTextLayout& t = l->viewLine(_viewLine);
if (t.startCol() >= startPos.column() || _viewLine == l->viewLineCount() - 1)
goto foundViewLine;
}
// FIXME FIXME need to calculate past-end-of-line position here...
Q_ASSERT(false);
foundViewLine:
Q_ASSERT(true);
}
}
}
m_startPos = startPos;
// Move the text layouts if we've just scrolled...
if (viewLinesScrolled != 0) {
// loop backwards if we've just scrolled up...
bool forwards = viewLinesScrolled >= 0 ? true : false;
for (int z = forwards ? 0 : m_textLayouts.count() - 1; forwards ? (z < m_textLayouts.count()) : (z >= 0); forwards ? z++ : z--) {
int oldZ = z + viewLinesScrolled;
if (oldZ >= 0 && oldZ < m_textLayouts.count())
m_textLayouts[z] = m_textLayouts[oldZ];
}
}
// Resize functionality
if (newViewLineCount > oldViewLineCount) {
m_textLayouts.reserve(newViewLineCount);
} else if (newViewLineCount < oldViewLineCount) {
/* FIXME reintroduce... check we're not missing any
int lastLine = m_textLayouts[newSize - 1].line();
for (int i = oldSize; i < newSize; i++) {
const KateTextLayout& layout = m_textLayouts[i];
if (layout.line() > lastLine && !layout.viewLine())
layout.kateLineLayout()->layout()->setCacheEnabled(false);
}*/
m_textLayouts.resize(newViewLineCount);
}
KateLineLayoutPtr l = line(realLine);
for (int i = 0; i < newViewLineCount; ++i) {
if (!l) {
if (i < m_textLayouts.count())
m_textLayouts[i] = KateTextLayout::invalid();
else
m_textLayouts.append(KateTextLayout::invalid());
continue;
}
Q_ASSERT(l->isValid());
Q_ASSERT(_viewLine < l->viewLineCount());
if (i < m_textLayouts.count()) {
//if (m_textLayouts[i].line() != realLine || m_textLayouts[i].viewLine() != _viewLine || !m_textLayouts[i].isValid())
m_textLayouts[i] = l->viewLine(_viewLine);
} else {
m_textLayouts.append(l->viewLine(_viewLine));
}
//kDebug() << "Laid out line " << realLine << " (" << l << "), viewLine " << _viewLine << " (" << m_textLayouts[i].kateLineLayout().data() << ")";
//m_textLayouts[i].debugOutput();
_viewLine++;
if (_viewLine > l->viewLineCount() - 1) {
int virtualLine = l->virtualLine() + 1;
realLine = m_renderer->doc()->getRealLine(virtualLine);
_viewLine = 0;
l = line(realLine, virtualLine);
}
}
enableLayoutCache = false;
}
KateLineLayoutPtr KateLayoutCache::line( int realLine, int virtualLine ) const
{
if (m_lineLayouts.contains(realLine)) {
KateLineLayoutPtr l = m_lineLayouts[realLine];
if (virtualLine != -1)
l->setVirtualLine(virtualLine);
if (!l->isValid())
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
else if (l->isLayoutDirty())
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
Q_ASSERT(l->isValid() && !l->isLayoutDirty());
return l;
}
if (realLine < 0 || realLine >= m_renderer->doc()->lines())
return KateLineLayoutPtr();
KateLineLayoutPtr l(new KateLineLayout(m_renderer->doc()));
l->setLine(realLine, virtualLine);
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
Q_ASSERT(l->isValid());
m_lineLayouts.insert(realLine, l);
return l;
}
KateLineLayoutPtr KateLayoutCache::line( const KTextEditor::Cursor & realCursor ) const
{
return line(realCursor.line());
}
KateTextLayout KateLayoutCache::textLayout( const KTextEditor::Cursor & realCursor ) const
{
/*if (realCursor >= viewCacheStart() && (realCursor < viewCacheEnd() || realCursor == viewCacheEnd() && !m_textLayouts.last().wrap()))
foreach (const KateTextLayout& l, m_textLayouts)
if (l.line() == realCursor.line() && (l.endCol() < realCursor.column() || !l.wrap()))
return l;*/
return line(realCursor.line())->viewLine(viewLine(realCursor));
}
KateTextLayout KateLayoutCache::textLayout( uint realLine, int _viewLine ) const
{
/*if (m_textLayouts.count() && (realLine >= m_textLayouts.first().line() && _viewLine >= m_textLayouts.first().viewLine()) &&
(realLine <= m_textLayouts.last().line() && _viewLine <= m_textLayouts.first().viewLine()))
foreach (const KateTextLayout& l, m_textLayouts)
if (l.line() == realLine && l.viewLine() == _viewLine)
return const_cast<KateTextLayout&>(l);*/
return line(realLine)->viewLine(_viewLine);
}
KateTextLayout & KateLayoutCache::viewLine( int _viewLine ) const
{
Q_ASSERT(_viewLine >= 0 && _viewLine < m_textLayouts.count());
return m_textLayouts[_viewLine];
}
int KateLayoutCache::viewCacheLineCount( ) const
{
return m_textLayouts.count();
}
KTextEditor::Cursor KateLayoutCache::viewCacheStart( ) const
{
return m_textLayouts.count() ? m_textLayouts.first().start() : KTextEditor::Cursor();
}
KTextEditor::Cursor KateLayoutCache::viewCacheEnd( ) const
{
return m_textLayouts.count() ? m_textLayouts.last().end() : KTextEditor::Cursor();
}
int KateLayoutCache::viewWidth( ) const
{
return m_viewWidth;
}
/**
* This returns the view line upon which realCursor is situated.
* The view line is the number of lines in the view from the first line
* The supplied cursor should be in real lines.
*/
int KateLayoutCache::viewLine(const KTextEditor::Cursor& realCursor) const
{
if (realCursor.column() == 0) return 0;
KateLineLayoutPtr thisLine = line(realCursor.line());
for (int i = 0; i < thisLine->viewLineCount(); ++i) {
const KateTextLayout& l = thisLine->viewLine(i);
if (realCursor.column() >= l.startCol() && realCursor.column() < l.endCol())
return i;
}
return thisLine->viewLineCount() - 1;
}
int KateLayoutCache::displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible) const
{
KTextEditor::Cursor work = viewCacheStart();
work.setLine(m_renderer->doc()->getVirtualLine(work.line()));
int limit = m_textLayouts.count();
// Efficient non-word-wrapped path
if (!m_renderer->view()->dynWordWrap()) {
int ret = virtualCursor.line() - work.line();
if (limitToVisible && (ret < 0 || ret > limit))
return -1;
else
return ret;
}
if (work == virtualCursor) {
return 0;
}
int ret = -(int)viewLine(work);
bool forwards = (work < virtualCursor) ? true : false;
// FIXME switch to using ranges? faster?
if (forwards) {
while (work.line() != virtualCursor.line()) {
ret += viewLineCount(m_renderer->doc()->getRealLine(work.line()));
work.setLine(work.line() + 1);
if (limitToVisible && ret > limit)
return -1;
}
} else {
while (work.line() != virtualCursor.line()) {
work.setLine(work.line() - 1);
ret -= viewLineCount(m_renderer->doc()->getRealLine(work.line()));
if (limitToVisible && ret < 0)
return -1;
}
}
// final difference
KTextEditor::Cursor realCursor = virtualCursor;
realCursor.setLine(m_renderer->doc()->getRealLine(realCursor.line()));
if (realCursor.column() == -1) realCursor.setColumn(m_renderer->doc()->lineLength(realCursor.line()));
ret += viewLine(realCursor);
if (limitToVisible && (ret < 0 || ret > limit))
return -1;
return ret;
}
int KateLayoutCache::lastViewLine(int realLine) const
{
if (!m_renderer->view()->dynWordWrap()) return 0;
KateLineLayoutPtr l = line(realLine);
Q_ASSERT(l);
return l->viewLineCount() - 1;
}
int KateLayoutCache::viewLineCount(int realLine) const
{
return lastViewLine(realLine) + 1;
}
void KateLayoutCache::viewCacheDebugOutput( ) const
{
kDebug() << "Printing values for " << m_textLayouts.count() << " lines:";
if (m_textLayouts.count())
foreach (const KateTextLayout& t, m_textLayouts)
if (t.isValid())
t.debugOutput();
else
kDebug() << "Line Invalid.";
}
void KateLayoutCache::slotEditDone(KateEditInfo* edit)
{
int fromLine = edit->oldRange().start().line();
int toLine = edit->oldRange().end().line();
int shiftAmount = edit->translate().line();
if (shiftAmount) {
QMap<int, KateLineLayoutPtr> oldMap = m_lineLayouts;
m_lineLayouts.clear();
QMapIterator<int, KateLineLayoutPtr> it = oldMap;
while (it.hasNext()) {
it.next();
if (it.key() > toLine) {
KateLineLayoutPtr layout = it.value();
layout->setLine(layout->line() + shiftAmount);
m_lineLayouts.insert(it.key() + shiftAmount, layout);
} else if (it.key() < fromLine) {
m_lineLayouts.insert(it.key(), it.value());
} else {
//gets deleted when oldMap goes but invalidate it just in case
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
}
} else {
for (int i = fromLine; i <= toLine; ++i)
if (m_lineLayouts.contains(i)) {
const_cast<KateLineLayoutPtr&>(m_lineLayouts[i])->setLayoutDirty();
m_lineLayouts.remove(i);
}
}
}
void KateLayoutCache::clear( )
{
m_textLayouts.clear();
m_lineLayouts.clear();
m_startPos = KTextEditor::Cursor(-1,-1);
}
void KateLayoutCache::setViewWidth( int width )
{
bool wider = width > m_viewWidth;
m_viewWidth = width;
m_lineLayouts.clear();
m_startPos = KTextEditor::Cursor(-1,-1);
// Only get rid of layouts that we have to
if (wider) {
QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts;
while (it.hasNext()) {
it.next();
if (it.value()->viewLineCount() > 1)
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
} else {
QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts;
while (it.hasNext()) {
it.next();
if (it.value()->viewLineCount() > 1 || it.value()->width() > m_viewWidth)
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
}
}
bool KateLayoutCache::wrap( ) const
{
return m_wrap;
}
void KateLayoutCache::setWrap( bool wrap )
{
m_wrap = wrap;
clear();
}
void KateLayoutCache::relayoutLines( int startRealLine, int endRealLine )
{
for (int i = startRealLine; i <= endRealLine; ++i)
if (m_lineLayouts.contains(i))
m_lineLayouts[i]->setLayoutDirty();
}
#include "katelayoutcache.moc"
|
/* This file is part of the KDE libraries
Copyright (C) 2005 Hamish Rodda <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "katelayoutcache.h"
#include <QtCore/QMutex>
#include "katerenderer.h"
#include "kateview.h"
#include "katedocument.h"
#include "kateedit.h"
#include <kdebug.h>
static bool enableLayoutCache = false;
KateLayoutCache::KateLayoutCache(KateRenderer* renderer, QObject* parent)
: QObject(parent)
, m_renderer(renderer)
, m_startPos(-1,-1)
, m_viewWidth(0)
, m_wrap(false)
{
Q_ASSERT(m_renderer);
connect(m_renderer->doc()->history(), SIGNAL(editDone(KateEditInfo*)), SLOT(slotEditDone(KateEditInfo*)));
}
void KateLayoutCache::updateViewCache(const KTextEditor::Cursor& startPos, int newViewLineCount, int viewLinesScrolled)
{
//kDebug() << startPos << " nvlc " << newViewLineCount << " vls " << viewLinesScrolled;
int oldViewLineCount = m_textLayouts.count();
if (newViewLineCount == -1)
newViewLineCount = oldViewLineCount;
enableLayoutCache = true;
int realLine = m_renderer->doc()->getRealLine(startPos.line());
int _viewLine = 0;
if (wrap()) {
// TODO check these assumptions are ok... probably they don't give much speedup anyway?
if (startPos == m_startPos && m_textLayouts.count()) {
_viewLine = m_textLayouts.first().viewLine();
} else if (viewLinesScrolled > 0 && viewLinesScrolled < m_textLayouts.count()) {
_viewLine = m_textLayouts[viewLinesScrolled].viewLine();
} else {
KateLineLayoutPtr l = line(realLine);
if (l) {
Q_ASSERT(l->isValid());
Q_ASSERT(l->length() >= startPos.column() || m_renderer->view()->wrapCursor());
for (; _viewLine < l->viewLineCount(); ++_viewLine) {
const KateTextLayout& t = l->viewLine(_viewLine);
if (t.startCol() >= startPos.column() || _viewLine == l->viewLineCount() - 1)
goto foundViewLine;
}
// FIXME FIXME need to calculate past-end-of-line position here...
Q_ASSERT(false);
foundViewLine:
Q_ASSERT(true);
}
}
}
m_startPos = startPos;
// Move the text layouts if we've just scrolled...
if (viewLinesScrolled != 0) {
// loop backwards if we've just scrolled up...
bool forwards = viewLinesScrolled >= 0 ? true : false;
for (int z = forwards ? 0 : m_textLayouts.count() - 1; forwards ? (z < m_textLayouts.count()) : (z >= 0); forwards ? z++ : z--) {
int oldZ = z + viewLinesScrolled;
if (oldZ >= 0 && oldZ < m_textLayouts.count())
m_textLayouts[z] = m_textLayouts[oldZ];
}
}
// Resize functionality
if (newViewLineCount > oldViewLineCount) {
m_textLayouts.reserve(newViewLineCount);
} else if (newViewLineCount < oldViewLineCount) {
/* FIXME reintroduce... check we're not missing any
int lastLine = m_textLayouts[newSize - 1].line();
for (int i = oldSize; i < newSize; i++) {
const KateTextLayout& layout = m_textLayouts[i];
if (layout.line() > lastLine && !layout.viewLine())
layout.kateLineLayout()->layout()->setCacheEnabled(false);
}*/
m_textLayouts.resize(newViewLineCount);
}
KateLineLayoutPtr l = line(realLine);
for (int i = 0; i < newViewLineCount; ++i) {
if (!l) {
if (i < m_textLayouts.count())
m_textLayouts[i] = KateTextLayout::invalid();
else
m_textLayouts.append(KateTextLayout::invalid());
continue;
}
Q_ASSERT(l->isValid());
Q_ASSERT(_viewLine < l->viewLineCount());
if (i < m_textLayouts.count()) {
bool dirty = false;
if (m_textLayouts[i].line() != realLine || m_textLayouts[i].viewLine() != _viewLine || !m_textLayouts[i].isValid())
dirty = true;
m_textLayouts[i] = l->viewLine(_viewLine);
if (dirty)
m_textLayouts[i].setDirty(true);
} else {
m_textLayouts.append(l->viewLine(_viewLine));
}
//kDebug() << "Laid out line " << realLine << " (" << l << "), viewLine " << _viewLine << " (" << m_textLayouts[i].kateLineLayout().data() << ")";
//m_textLayouts[i].debugOutput();
_viewLine++;
if (_viewLine > l->viewLineCount() - 1) {
int virtualLine = l->virtualLine() + 1;
realLine = m_renderer->doc()->getRealLine(virtualLine);
_viewLine = 0;
l = line(realLine, virtualLine);
}
}
enableLayoutCache = false;
}
KateLineLayoutPtr KateLayoutCache::line( int realLine, int virtualLine ) const
{
if (m_lineLayouts.contains(realLine)) {
KateLineLayoutPtr l = m_lineLayouts[realLine];
if (virtualLine != -1)
l->setVirtualLine(virtualLine);
if (!l->isValid())
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
else if (l->isLayoutDirty())
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
Q_ASSERT(l->isValid() && !l->isLayoutDirty());
return l;
}
if (realLine < 0 || realLine >= m_renderer->doc()->lines())
return KateLineLayoutPtr();
KateLineLayoutPtr l(new KateLineLayout(m_renderer->doc()));
l->setLine(realLine, virtualLine);
m_renderer->layoutLine(l, wrap() ? m_viewWidth : -1, enableLayoutCache);
Q_ASSERT(l->isValid());
m_lineLayouts.insert(realLine, l);
return l;
}
KateLineLayoutPtr KateLayoutCache::line( const KTextEditor::Cursor & realCursor ) const
{
return line(realCursor.line());
}
KateTextLayout KateLayoutCache::textLayout( const KTextEditor::Cursor & realCursor ) const
{
/*if (realCursor >= viewCacheStart() && (realCursor < viewCacheEnd() || realCursor == viewCacheEnd() && !m_textLayouts.last().wrap()))
foreach (const KateTextLayout& l, m_textLayouts)
if (l.line() == realCursor.line() && (l.endCol() < realCursor.column() || !l.wrap()))
return l;*/
return line(realCursor.line())->viewLine(viewLine(realCursor));
}
KateTextLayout KateLayoutCache::textLayout( uint realLine, int _viewLine ) const
{
/*if (m_textLayouts.count() && (realLine >= m_textLayouts.first().line() && _viewLine >= m_textLayouts.first().viewLine()) &&
(realLine <= m_textLayouts.last().line() && _viewLine <= m_textLayouts.first().viewLine()))
foreach (const KateTextLayout& l, m_textLayouts)
if (l.line() == realLine && l.viewLine() == _viewLine)
return const_cast<KateTextLayout&>(l);*/
return line(realLine)->viewLine(_viewLine);
}
KateTextLayout & KateLayoutCache::viewLine( int _viewLine ) const
{
Q_ASSERT(_viewLine >= 0 && _viewLine < m_textLayouts.count());
return m_textLayouts[_viewLine];
}
int KateLayoutCache::viewCacheLineCount( ) const
{
return m_textLayouts.count();
}
KTextEditor::Cursor KateLayoutCache::viewCacheStart( ) const
{
return m_textLayouts.count() ? m_textLayouts.first().start() : KTextEditor::Cursor();
}
KTextEditor::Cursor KateLayoutCache::viewCacheEnd( ) const
{
return m_textLayouts.count() ? m_textLayouts.last().end() : KTextEditor::Cursor();
}
int KateLayoutCache::viewWidth( ) const
{
return m_viewWidth;
}
/**
* This returns the view line upon which realCursor is situated.
* The view line is the number of lines in the view from the first line
* The supplied cursor should be in real lines.
*/
int KateLayoutCache::viewLine(const KTextEditor::Cursor& realCursor) const
{
if (realCursor.column() == 0) return 0;
KateLineLayoutPtr thisLine = line(realCursor.line());
for (int i = 0; i < thisLine->viewLineCount(); ++i) {
const KateTextLayout& l = thisLine->viewLine(i);
if (realCursor.column() >= l.startCol() && realCursor.column() < l.endCol())
return i;
}
return thisLine->viewLineCount() - 1;
}
int KateLayoutCache::displayViewLine(const KTextEditor::Cursor& virtualCursor, bool limitToVisible) const
{
KTextEditor::Cursor work = viewCacheStart();
work.setLine(m_renderer->doc()->getVirtualLine(work.line()));
int limit = m_textLayouts.count();
// Efficient non-word-wrapped path
if (!m_renderer->view()->dynWordWrap()) {
int ret = virtualCursor.line() - work.line();
if (limitToVisible && (ret < 0 || ret > limit))
return -1;
else
return ret;
}
if (work == virtualCursor) {
return 0;
}
int ret = -(int)viewLine(work);
bool forwards = (work < virtualCursor) ? true : false;
// FIXME switch to using ranges? faster?
if (forwards) {
while (work.line() != virtualCursor.line()) {
ret += viewLineCount(m_renderer->doc()->getRealLine(work.line()));
work.setLine(work.line() + 1);
if (limitToVisible && ret > limit)
return -1;
}
} else {
while (work.line() != virtualCursor.line()) {
work.setLine(work.line() - 1);
ret -= viewLineCount(m_renderer->doc()->getRealLine(work.line()));
if (limitToVisible && ret < 0)
return -1;
}
}
// final difference
KTextEditor::Cursor realCursor = virtualCursor;
realCursor.setLine(m_renderer->doc()->getRealLine(realCursor.line()));
if (realCursor.column() == -1) realCursor.setColumn(m_renderer->doc()->lineLength(realCursor.line()));
ret += viewLine(realCursor);
if (limitToVisible && (ret < 0 || ret > limit))
return -1;
return ret;
}
int KateLayoutCache::lastViewLine(int realLine) const
{
if (!m_renderer->view()->dynWordWrap()) return 0;
KateLineLayoutPtr l = line(realLine);
Q_ASSERT(l);
return l->viewLineCount() - 1;
}
int KateLayoutCache::viewLineCount(int realLine) const
{
return lastViewLine(realLine) + 1;
}
void KateLayoutCache::viewCacheDebugOutput( ) const
{
kDebug() << "Printing values for " << m_textLayouts.count() << " lines:";
if (m_textLayouts.count())
foreach (const KateTextLayout& t, m_textLayouts)
if (t.isValid())
t.debugOutput();
else
kDebug() << "Line Invalid.";
}
void KateLayoutCache::slotEditDone(KateEditInfo* edit)
{
int fromLine = edit->oldRange().start().line();
int toLine = edit->oldRange().end().line();
int shiftAmount = edit->translate().line();
if (shiftAmount) {
QMap<int, KateLineLayoutPtr> oldMap = m_lineLayouts;
m_lineLayouts.clear();
QMapIterator<int, KateLineLayoutPtr> it = oldMap;
while (it.hasNext()) {
it.next();
if (it.key() > toLine) {
KateLineLayoutPtr layout = it.value();
layout->setLine(layout->line() + shiftAmount);
m_lineLayouts.insert(it.key() + shiftAmount, layout);
} else if (it.key() < fromLine) {
m_lineLayouts.insert(it.key(), it.value());
} else {
//gets deleted when oldMap goes but invalidate it just in case
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
}
} else {
for (int i = fromLine; i <= toLine; ++i)
if (m_lineLayouts.contains(i)) {
const_cast<KateLineLayoutPtr&>(m_lineLayouts[i])->setLayoutDirty();
m_lineLayouts.remove(i);
}
}
}
void KateLayoutCache::clear( )
{
m_textLayouts.clear();
m_lineLayouts.clear();
m_startPos = KTextEditor::Cursor(-1,-1);
}
void KateLayoutCache::setViewWidth( int width )
{
bool wider = width > m_viewWidth;
m_viewWidth = width;
m_lineLayouts.clear();
m_startPos = KTextEditor::Cursor(-1,-1);
// Only get rid of layouts that we have to
if (wider) {
QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts;
while (it.hasNext()) {
it.next();
if (it.value()->viewLineCount() > 1)
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
} else {
QMapIterator<int, KateLineLayoutPtr> it = m_lineLayouts;
while (it.hasNext()) {
it.next();
if (it.value()->viewLineCount() > 1 || it.value()->width() > m_viewWidth)
const_cast<KateLineLayoutPtr&>(it.value())->invalidateLayout();
}
}
}
bool KateLayoutCache::wrap( ) const
{
return m_wrap;
}
void KateLayoutCache::setWrap( bool wrap )
{
m_wrap = wrap;
clear();
}
void KateLayoutCache::relayoutLines( int startRealLine, int endRealLine )
{
for (int i = startRealLine; i <= endRealLine; ++i)
if (m_lineLayouts.contains(i))
m_lineLayouts[i]->setLayoutDirty();
}
#include "katelayoutcache.moc"
|
Fix bug where edits to multi-viewline lines lead to not properly updating the view
|
Fix bug where edits to multi-viewline lines lead to not properly updating the view
svn path=/trunk/KDE/kdelibs/kate/; revision=730638
|
C++
|
lgpl-2.1
|
hlamer/kate,hlamer/kate,jfmcarreira/kate,hlamer/kate,DickJ/kate,DickJ/kate,hlamer/kate,hlamer/kate,cmacq2/kate,hlamer/kate,DickJ/kate,sandsmark/kate,jfmcarreira/kate,hlamer/kate,hlamer/kate,hlamer/kate,sandsmark/kate,sandsmark/kate,cmacq2/kate,jfmcarreira/kate,hlamer/kate,sandsmark/kate,cmacq2/kate,DickJ/kate
|
78f3782e8359dbc84fc9193d793e09956f2ce20a
|
chrome/browser/printing/printing_message_filter.cc
|
chrome/browser/printing/printing_message_filter.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 "chrome/browser/printing/printing_message_filter.h"
#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#if defined(OS_CHROMEOS)
#include <fcntl.h>
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#else
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#endif
namespace {
#if defined(OS_CHROMEOS)
typedef std::map<int, FilePath> SequenceToPathMap;
struct PrintingSequencePathMap {
SequenceToPathMap map;
int sequence;
};
// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
g_printing_file_descriptor_map(base::LINKER_INITIALIZED);
#endif
void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
ViewMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->printable_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->margin_top = settings.page_setup_device_units().content_area().x();
params->margin_left = settings.page_setup_device_units().content_area().y();
params->dpi = settings.dpi();
// Currently hardcoded at 1.25. See PrintSettings' constructor.
params->min_shrink = settings.min_shrink;
// Currently hardcoded at 2.0. See PrintSettings' constructor.
params->max_shrink = settings.max_shrink;
// Currently hardcoded at 72dpi. See PrintSettings' constructor.
params->desired_dpi = settings.desired_dpi;
// Always use an invalid cookie.
params->document_cookie = 0;
params->selection_only = settings.selection_only;
params->supports_alpha_blend = settings.supports_alpha_blend();
}
} // namespace
PrintingMessageFilter::PrintingMessageFilter()
: print_job_manager_(g_browser_process->print_job_manager()) {
#if defined(OS_CHROMEOS)
cloud_print_enabled_ = true;
#else
cloud_print_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableCloudPrint);
#endif
}
PrintingMessageFilter::~PrintingMessageFilter() {
}
void PrintingMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
if (message.type() == ViewHostMsg_AllocateTempFileForPrinting::ID ||
message.type() == ViewHostMsg_TempFileForPrintingWritten::ID) {
*thread = BrowserThread::FILE;
}
#endif
}
bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(ViewHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ViewHostMsg_AllocateTempFileForPrinting,
OnAllocateTempFileForPrinting)
IPC_MESSAGE_HANDLER(ViewHostMsg_TempFileForPrintingWritten,
OnTempFileForPrintingWritten)
#endif
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetDefaultPrintSettings,
OnGetDefaultPrintSettings)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_ScriptedPrint, OnScriptedPrint)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_UpdatePrintSettings,
OnUpdatePrintSettings)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
base::SharedMemoryHandle renderer_handle,
base::SharedMemoryHandle* browser_handle) {
// Duplicate the handle in this process right now so the memory is kept alive
// (even if it is not mapped)
base::SharedMemory shared_buf(renderer_handle, true, peer_handle());
shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif
#if defined(OS_CHROMEOS)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
base::FileDescriptor* temp_file_fd, int* sequence_number) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
temp_file_fd->fd = *sequence_number = -1;
temp_file_fd->auto_close = false;
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
*sequence_number = g_printing_file_descriptor_map.Get().sequence++;
FilePath path;
if (file_util::CreateTemporaryFile(&path)) {
int fd = open(path.value().c_str(), O_WRONLY);
if (fd >= 0) {
SequenceToPathMap::iterator it = map->find(*sequence_number);
if (it != map->end()) {
NOTREACHED() << "Sequence number already in use. seq=" <<
*sequence_number;
} else {
(*map)[*sequence_number] = path;
temp_file_fd->fd = fd;
temp_file_fd->auto_close = true;
}
}
}
}
void PrintingMessageFilter::OnTempFileForPrintingWritten(int sequence_number) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
SequenceToPathMap::iterator it = map->find(sequence_number);
if (it == map->end()) {
NOTREACHED() << "Got a sequence that we didn't pass to the "
"renderer: " << sequence_number;
return;
}
if (cloud_print_enabled_)
PrintDialogCloud::CreatePrintDialogForPdf(it->second, string16(), true);
else
NOTIMPLEMENTED();
// Erase the entry in the map.
map->erase(it);
}
#endif // defined(OS_CHROMEOS)
void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query;
if (!print_job_manager_->printing_enabled()) {
// Reply with NULL query.
OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
return;
}
print_job_manager_->PopPrinterQuery(0, &printer_query);
if (!printer_query.get()) {
printer_query = new printing::PrinterQuery;
}
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
printer_query,
reply_msg);
// Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved.
printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
NULL,
0,
false,
true,
task);
}
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
ViewMsg_Print_Params params;
if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);
params.document_cookie = printer_query->cookie();
}
ViewHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If printing was enabled.
if (printer_query.get()) {
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi()) {
print_job_manager_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
}
void PrintingMessageFilter::OnScriptedPrint(
const ViewHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg) {
gfx::NativeView host_view =
gfx::NativeViewFromIdInBrowser(params.host_window_id);
scoped_refptr<printing::PrinterQuery> printer_query;
print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);
if (!printer_query.get()) {
printer_query = new printing::PrinterQuery;
}
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnScriptedPrintReply,
printer_query,
params.routing_id,
reply_msg);
printer_query->GetSettings(printing::PrinterQuery::ASK_USER,
host_view,
params.expected_pages_count,
params.has_selection,
params.use_overlays,
task);
}
void PrintingMessageFilter::OnScriptedPrintReply(
scoped_refptr<printing::PrinterQuery> printer_query,
int routing_id,
IPC::Message* reply_msg) {
ViewMsg_PrintPages_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK ||
!printer_query->settings().dpi()) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);
params.params.document_cookie = printer_query->cookie();
params.pages =
printing::PageRange::GetPages(printer_query->settings().ranges);
}
ViewHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (params.params.dpi && params.params.document_cookie) {
print_job_manager_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
void PrintingMessageFilter::OnUpdatePrintSettings(
int document_cookie, const DictionaryValue& job_settings,
IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query;
print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);
if (printer_query.get()) {
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnUpdatePrintSettingsReply,
printer_query,
reply_msg);
printer_query->SetSettings(job_settings, task);
}
}
void PrintingMessageFilter::OnUpdatePrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
ViewMsg_Print_Params params;
if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);
params.document_cookie = printer_query->cookie();
}
ViewHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If printing was enabled.
if (printer_query.get()) {
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi()) {
print_job_manager_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
}
|
// 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/printing/printing_message_filter.h"
#include "base/process_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/render_messages_params.h"
#if defined(OS_CHROMEOS)
#include <fcntl.h>
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#else
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#endif
namespace {
#if defined(OS_CHROMEOS)
typedef std::map<int, FilePath> SequenceToPathMap;
struct PrintingSequencePathMap {
SequenceToPathMap map;
int sequence;
};
// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
g_printing_file_descriptor_map(base::LINKER_INITIALIZED);
#endif
void RenderParamsFromPrintSettings(const printing::PrintSettings& settings,
ViewMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->printable_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->margin_top = settings.page_setup_device_units().content_area().x();
params->margin_left = settings.page_setup_device_units().content_area().y();
params->dpi = settings.dpi();
// Currently hardcoded at 1.25. See PrintSettings' constructor.
params->min_shrink = settings.min_shrink;
// Currently hardcoded at 2.0. See PrintSettings' constructor.
params->max_shrink = settings.max_shrink;
// Currently hardcoded at 72dpi. See PrintSettings' constructor.
params->desired_dpi = settings.desired_dpi;
// Always use an invalid cookie.
params->document_cookie = 0;
params->selection_only = settings.selection_only;
params->supports_alpha_blend = settings.supports_alpha_blend();
}
} // namespace
PrintingMessageFilter::PrintingMessageFilter()
: print_job_manager_(g_browser_process->print_job_manager()) {
#if defined(OS_CHROMEOS)
cloud_print_enabled_ = true;
#else
cloud_print_enabled_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableCloudPrint);
#endif
}
PrintingMessageFilter::~PrintingMessageFilter() {
}
void PrintingMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
if (message.type() == ViewHostMsg_AllocateTempFileForPrinting::ID ||
message.type() == ViewHostMsg_TempFileForPrintingWritten::ID) {
*thread = BrowserThread::FILE;
}
#endif
}
bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(PrintingMessageFilter, message, *message_was_ok)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(ViewHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ViewHostMsg_AllocateTempFileForPrinting,
OnAllocateTempFileForPrinting)
IPC_MESSAGE_HANDLER(ViewHostMsg_TempFileForPrintingWritten,
OnTempFileForPrintingWritten)
#endif
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetDefaultPrintSettings,
OnGetDefaultPrintSettings)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_ScriptedPrint, OnScriptedPrint)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_UpdatePrintSettings,
OnUpdatePrintSettings)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
#if defined(OS_WIN)
void PrintingMessageFilter::OnDuplicateSection(
base::SharedMemoryHandle renderer_handle,
base::SharedMemoryHandle* browser_handle) {
// Duplicate the handle in this process right now so the memory is kept alive
// (even if it is not mapped)
base::SharedMemory shared_buf(renderer_handle, true, peer_handle());
shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle);
}
#endif
#if defined(OS_CHROMEOS)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
base::FileDescriptor* temp_file_fd, int* sequence_number) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
temp_file_fd->fd = *sequence_number = -1;
temp_file_fd->auto_close = false;
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
*sequence_number = g_printing_file_descriptor_map.Get().sequence++;
FilePath path;
if (file_util::CreateTemporaryFile(&path)) {
int fd = open(path.value().c_str(), O_WRONLY);
if (fd >= 0) {
SequenceToPathMap::iterator it = map->find(*sequence_number);
if (it != map->end()) {
NOTREACHED() << "Sequence number already in use. seq=" <<
*sequence_number;
} else {
(*map)[*sequence_number] = path;
temp_file_fd->fd = fd;
temp_file_fd->auto_close = true;
}
}
}
}
void PrintingMessageFilter::OnTempFileForPrintingWritten(int sequence_number) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
SequenceToPathMap::iterator it = map->find(sequence_number);
if (it == map->end()) {
NOTREACHED() << "Got a sequence that we didn't pass to the "
"renderer: " << sequence_number;
return;
}
if (cloud_print_enabled_)
PrintDialogCloud::CreatePrintDialogForPdf(it->second, string16(), true);
else
NOTIMPLEMENTED();
// Erase the entry in the map.
map->erase(it);
}
#endif // defined(OS_CHROMEOS)
void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query;
if (!print_job_manager_->printing_enabled()) {
// Reply with NULL query.
OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
return;
}
print_job_manager_->PopPrinterQuery(0, &printer_query);
if (!printer_query.get()) {
printer_query = new printing::PrinterQuery;
}
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
printer_query,
reply_msg);
// Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved.
printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
NULL,
0,
false,
true,
task);
}
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
ViewMsg_Print_Params params;
if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);
params.document_cookie = printer_query->cookie();
}
ViewHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If printing was enabled.
if (printer_query.get()) {
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi()) {
print_job_manager_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
}
void PrintingMessageFilter::OnScriptedPrint(
const ViewHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg) {
gfx::NativeView host_view =
gfx::NativeViewFromIdInBrowser(params.host_window_id);
scoped_refptr<printing::PrinterQuery> printer_query;
print_job_manager_->PopPrinterQuery(params.cookie, &printer_query);
if (!printer_query.get()) {
printer_query = new printing::PrinterQuery;
}
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnScriptedPrintReply,
printer_query,
params.routing_id,
reply_msg);
printer_query->GetSettings(printing::PrinterQuery::ASK_USER,
host_view,
params.expected_pages_count,
params.has_selection,
params.use_overlays,
task);
}
void PrintingMessageFilter::OnScriptedPrintReply(
scoped_refptr<printing::PrinterQuery> printer_query,
int routing_id,
IPC::Message* reply_msg) {
ViewMsg_PrintPages_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK ||
!printer_query->settings().dpi()) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params);
params.params.document_cookie = printer_query->cookie();
params.pages =
printing::PageRange::GetPages(printer_query->settings().ranges);
}
ViewHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
Send(reply_msg);
if (params.params.dpi && params.params.document_cookie) {
print_job_manager_->QueuePrinterQuery(printer_query.get());
} else {
printer_query->StopWorker();
}
}
void PrintingMessageFilter::OnUpdatePrintSettings(
int document_cookie, const DictionaryValue& job_settings,
IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query;
print_job_manager_->PopPrinterQuery(document_cookie, &printer_query);
if (printer_query.get()) {
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnUpdatePrintSettingsReply,
printer_query,
reply_msg);
printer_query->SetSettings(job_settings, task);
}
}
void PrintingMessageFilter::OnUpdatePrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg) {
ViewMsg_Print_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK) {
memset(¶ms, 0, sizeof(params));
} else {
RenderParamsFromPrintSettings(printer_query->settings(), ¶ms);
params.document_cookie = printer_query->cookie();
}
ViewHostMsg_UpdatePrintSettings::WriteReplyParams(reply_msg, params);
Send(reply_msg);
// If user hasn't cancelled.
if (printer_query->cookie() && printer_query->settings().dpi())
print_job_manager_->QueuePrinterQuery(printer_query.get());
else
printer_query->StopWorker();
}
|
Remove a check for a condition that's always true.
|
Printing: Remove a check for a condition that's always true.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/6626068
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@77318 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
3360a988d9ed9547baaf6bd04cf8933656b136c8
|
source/board/STM32/STM32F4/32F429IDISCOVERY/32F429IDISCOVERY-lowLevelInitialization.cpp
|
source/board/STM32/STM32F4/32F429IDISCOVERY/32F429IDISCOVERY-lowLevelInitialization.cpp
|
/**
* \file
* \brief board::lowLevelInitialization() implementation for 32F429IDISCOVERY
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/board/lowLevelInitialization.hpp"
namespace distortos
{
namespace board
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
}
} // namespace board
} // namespace distortos
|
/**
* \file
* \brief board::lowLevelInitialization() implementation for 32F429IDISCOVERY
*
* \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/board/lowLevelInitialization.hpp"
#include "distortos/chip/CMSIS-proxy.h"
namespace distortos
{
namespace board
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void lowLevelInitialization()
{
RCC->AHB1ENR |=
#ifdef CONFIG_BOARD_LEDS_ENABLE
RCC_AHB1ENR_GPIOGEN |
#endif // def CONFIG_BOARD_LEDS_ENABLE
0;
}
} // namespace board
} // namespace distortos
|
enable LEDs' GPIO for 32F429IDISCOVERY
|
board: enable LEDs' GPIO for 32F429IDISCOVERY
Enable GPIOG in RCC in board::lowLevelInitialization() if LED's are
enabled.
|
C++
|
mpl-2.0
|
CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos
|
4751bab76779ea94bac1a1c3fc88aa5d47d2242b
|
src/iterators/sliding_window_iterator.hpp
|
src/iterators/sliding_window_iterator.hpp
|
/**
* @file many2one_iterator.hpp
* @ingroup interators
* @author Patrick Flick <[email protected]>
* @brief Implements the many2one iterator.
*
* Copyright (c) TODO
*
* TODO add Licence
*/
#ifndef BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP
#define BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP
#include <iterator>
#include <iterators/iterator_tools.hpp>
#include <iterators/iterator_utils.hpp>
namespace bliss
{
namespace iterator
{
template<typename BaseIterator, typename Window>
class sliding_window_iterator : public std::iterator<
// 1) iterator type tag: at most forward, but if the base iterator is less,
// then inherit from it
typename iterator_tags<BaseIterator>::inherit_forward,
// 2) value type = return type of the getValue function in the Window class
typename std::remove_reference<decltype(std::declval<Window>().getValue())>::type,
// 3) difference_type = same as base iterator
typename std::iterator_traits<BaseIterator>::difference_type>
{
protected:
// the base iterator traits
typedef std::iterator_traits<BaseIterator> base_traits;
/// This type
typedef sliding_window_iterator type;
protected:
/**********************
* Member variables *
**********************/
// input iterators, _base is used for comparison and represents the current
// position, while _next reads ahead in order to fill the sliding window.
BaseIterator _base;
BaseIterator _next;
// the window
Window _window;
/// The std::iterator_traits of this iterator
typedef std::iterator_traits<type> traits;
public:
/**********************************
* Typedefs for iterator traits *
**********************************/
/// The iterator category of this iterator
typedef typename traits::iterator_category iterator_category;
/// The value type of this iterator
typedef typename traits::value_type value_type;
/// The difference type of this iterator
typedef typename traits::difference_type difference_type;
/// The reference type of a value of this iterator
typedef typename traits::reference reference_type;
/// The pointer type of a value of this iterator
typedef typename traits::pointer pointer_type;
/**********************
* Member accessors *
**********************/
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
BaseIterator& getBaseIterator()
{
return _base;
}
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
const BaseIterator& getBaseIterator() const
{
return _base;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
Window& getWindow()
{
return _window;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
const Window& getWindow() const
{
return _window;
}
/*****************
* Comparators *
*****************/
/**
* @brief Returns whether this and the given iterator point to the same
* positon.
*
* @return Whether this and the given iterator point to the same position.
*/
inline bool operator==(const sliding_window_iterator& rhs) const
{
return _base == rhs._base;
}
/**
* @brief Returns whether this and the given iterator are different.
*
* @return Whether this and the given iterator are different.
*/
inline bool operator!=(const sliding_window_iterator& rhs) const
{
return _base != rhs._base;
}
public:
/******************
* Constructors *
******************/
/**
* @brief Constructor, taking the base iterator and the many2one
* functor.
*
* @param base_iter The base iterator that is wrapped via this iterator.
* @param window The sliding window structure
*/
sliding_window_iterator(const BaseIterator& base_iter, const Window& window)
: _base(base_iter), _next(base_iter), _window(window)
{
}
/**
* @brief Returns the value at the current iterator position.
*
* This returns the buffered value of the current sliding window position.
*
* @return The value at the current position.
*/
inline value_type operator*()
{
// in case the current element has not been read yet: do so now
if (this->_base == this->_next)
{
// add the current element to the sliding window, this iterates the _next
// pointer by one
this->_window.next(this->_next);
}
// the result was already computed and stored in the functor
return this->_window.getValue();
}
/**
* @brief Pre-increment operator.
*
* Advances this iterator by one position.
*
* @return A reference to this.
*/
type& operator++()
{
// if we have not read the current element (thus iterating one postion
// ahead with _next), then do it now (this happens of operator*() is not
// called)
if (this->_base == this->_next)
{
// slide the window, inserting the current element and iterating ahead
// with _next
this->_window.next(this->_next);
}
// set both iterators to the same position
this->_base = this->_next;
// return a reference to this
return *this;
}
/**
* @brief Post-increment operator.
*
* Advances this iterator by one position, but returns the old iterator state.
*
* @return A copy to the non-incremented iterator.
*/
type operator++(int)
{
// create a copy
type tmp(*this);
this->operator++();
return tmp;
}
};
template<typename BaseIterator, typename Window>
class many2one_sliding_window_iterator : public std::iterator<
// 1) iterator type tag: at most forward, but if the base iterator is less,
// then inherit from it
typename iterator_tags<BaseIterator>::inherit_forward,
// 2) value type = return type of the getValue function in the Window class
typename std::remove_reference<decltype(std::declval<Window>().getValue())>::type,
// 3) difference_type = same as base iterator
typename std::iterator_traits<BaseIterator>::difference_type>
{
protected:
// the base iterator traits
typedef std::iterator_traits<BaseIterator> base_traits;
/// This type
typedef many2one_sliding_window_iterator type;
/// The std::iterator_traits of this iterator
typedef std::iterator_traits<type> traits;
public:
/**********************************
* Typedefs for iterator traits *
**********************************/
/// The iterator category of this iterator
typedef typename traits::iterator_category iterator_category;
/// The value type of this iterator
typedef typename traits::value_type value_type;
/// The difference type of this iterator
typedef typename traits::difference_type difference_type;
/// The reference type of a value of this iterator
typedef typename traits::reference reference_type;
/// The pointer type of a value of this iterator
typedef typename traits::pointer pointer_type;
protected:
/**********************
* Member variables *
**********************/
// input iterators, _base is used for comparison and represents the current
// position, while _next reads ahead in order to fill the sliding window.
BaseIterator _base;
BaseIterator _next;
// the offsets in each word (many2one)
difference_type _base_offset;
difference_type _next_offset;
// the window
Window _window;
public:
/**********************
* Member accessors *
**********************/
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
BaseIterator& getBaseIterator()
{
return _base;
}
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
const BaseIterator& getBaseIterator() const
{
return _base;
}
/**
* @brief Returns the current offset within the current iterator position.
*
* @return the current offset.
*/
difference_type getOffset() const
{
return _base_offset;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
Window& getWindow()
{
return _window;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
const Window& getWindow() const
{
return _window;
}
/*****************
* Comparators *
*****************/
/**
* @brief Returns whether this and the given iterator point to the same
* positon.
*
* @return Whether this and the given iterator point to the same position.
*/
inline bool operator==(const many2one_sliding_window_iterator& rhs) const
{
return _base == rhs._base && _base_offset == rhs._base_offset;
}
/**
* @brief Returns whether this and the given iterator are different.
*
* @return Whether this and the given iterator are different.
*/
inline bool operator!=(const many2one_sliding_window_iterator& rhs) const
{
return !this->operator==(rhs);
}
public:
/******************
* Constructors *
******************/
/**
* @brief Constructor, taking the base iterator and the many2one
* functor.
*
* @param base_iter The base iterator that is wrapped via this iterator.
* @param window The sliding window structure
*/
many2one_sliding_window_iterator(const BaseIterator& base_iter, const Window& window)
: _base(base_iter), _next(base_iter),
_base_offset(0), _next_offset(0), _window(window)
{
}
/**
* @brief Returns the value at the current iterator position.
*
* This returns the buffered value of the current sliding window position.
*
* @return The value at the current position.
*/
inline value_type operator*()
{
// in case the current element has not been read yet: do so now
if (this->_base == this->_next && this->_base_offset == this->_next_offset)
{
// add the current element to the sliding window, this sets the next
// and offset pointers to the next readable element/offset
this->_window.next(this->_next, this->_next_offset);
}
// the result was already computed and stored in the functor
return this->_window.getValue();
}
/**
* @brief Pre-increment operator.
*
* Advances this iterator by one position.
*
* @return A reference to this.
*/
type& operator++()
{
// if we have not read the current element (thus iterating one postion
// ahead with _next), then do it now (this happens of operator*() is not
// called)
if (this->_base == this->_next && this->_base_offset == this->_next_offset)
{
// add the current element to the sliding window, this sets the next
// and offset pointers to the next readable element/offset
this->_window.next(this->_next, this->_next_offset);
}
// set both iterators to the same position
this->_base = this->_next;
this->_base_offset = this->_next_offset;
// return a reference to this
return *this;
}
/**
* @brief Post-increment operator.
*
* Advances this iterator by one position, but returns the old iterator state.
*
* @return A copy to the non-incremented iterator.
*/
type operator++(int)
{
// create a copy
type tmp(*this);
this->operator++();
return tmp;
}
};
} // iterator
} // bliss
#endif /* BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP */
|
/**
* @file many2one_iterator.hpp
* @ingroup interators
* @author Patrick Flick <[email protected]>
* @brief Implements the many2one iterator.
*
* Copyright (c) TODO
*
* TODO add Licence
*/
#ifndef BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP
#define BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP
#include <iterator>
#include <iterators/iterator_tools.hpp>
#include <iterators/iterator_utils.hpp>
namespace bliss
{
namespace iterator
{
template<typename BaseIterator, typename Window>
class sliding_window_iterator : public std::iterator<
// 1) iterator type tag: at most forward, but if the base iterator is less,
// then inherit from it
typename iterator_tags<BaseIterator>::inherit_forward,
// 2) value type = return type of the getValue function in the Window class
typename std::remove_reference<decltype(std::declval<Window>().getValue())>::type,
// 3) difference_type = same as base iterator
typename std::iterator_traits<BaseIterator>::difference_type>
{
protected:
// the base iterator traits
typedef std::iterator_traits<BaseIterator> base_traits;
/// This type
typedef sliding_window_iterator type;
protected:
/**********************
* Member variables *
**********************/
// input iterators, _base is used for comparison and represents the current
// position, while _next reads ahead in order to fill the sliding window.
BaseIterator _base;
BaseIterator _next;
// the window
Window _window;
/// The std::iterator_traits of this iterator
typedef std::iterator_traits<type> traits;
public:
/**********************************
* Typedefs for iterator traits *
**********************************/
/// The iterator category of this iterator
typedef typename traits::iterator_category iterator_category;
/// The value type of this iterator
typedef typename traits::value_type value_type;
/// The difference type of this iterator
typedef typename traits::difference_type difference_type;
/// The reference type of a value of this iterator
typedef typename traits::reference reference_type;
/// The pointer type of a value of this iterator
typedef typename traits::pointer pointer_type;
/**********************
* Member accessors *
**********************/
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
BaseIterator& getBaseIterator()
{
return _base;
}
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
const BaseIterator& getBaseIterator() const
{
return _base;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
Window& getWindow()
{
return _window;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
const Window& getWindow() const
{
return _window;
}
/*****************
* Comparators *
*****************/
/**
* @brief Returns whether this and the given iterator point to the same
* positon.
*
* @return Whether this and the given iterator point to the same position.
*/
inline bool operator==(const sliding_window_iterator& rhs) const
{
return _base == rhs._base;
}
/**
* @brief Returns whether this and the given iterator are different.
*
* @return Whether this and the given iterator are different.
*/
inline bool operator!=(const sliding_window_iterator& rhs) const
{
return _base != rhs._base;
}
public:
/******************
* Constructors *
******************/
/**
* @brief Constructor, taking the base iterator and the many2one
* functor.
*
* @param base_iter The base iterator that is wrapped via this iterator.
* @param window The sliding window structure
*/
sliding_window_iterator(const BaseIterator& base_iter, const Window& window)
: _base(base_iter), _next(base_iter), _window(window)
{
}
/**
* @brief Returns the value at the current iterator position.
*
* This returns the buffered value of the current sliding window position.
*
* @return The value at the current position.
*/
inline value_type operator*()
{
// in case the current element has not been read yet: do so now
if (this->_base == this->_next)
{
// add the current element to the sliding window, this iterates the _next
// pointer by one
this->_window.next(this->_next);
}
// the result was already computed and stored in the functor
return this->_window.getValue();
}
/**
* @brief Pre-increment operator.
*
* Advances this iterator by one position.
*
* @return A reference to this.
*/
type& operator++()
{
// if we have not read the current element (thus iterating one postion
// ahead with _next), then do it now (this happens of operator*() is not
// called)
if (this->_base == this->_next)
{
// slide the window, inserting the current element and iterating ahead
// with _next
this->_window.next(this->_next);
}
// set both iterators to the same position
this->_base = this->_next;
// return a reference to this
return *this;
}
/**
* @brief Post-increment operator.
*
* Advances this iterator by one position, but returns the old iterator state.
*
* @return A copy to the non-incremented iterator.
*/
type operator++(int)
{
// create a copy
type tmp(*this);
this->operator++();
return tmp;
}
};
template<typename BaseIterator, typename Window>
class one2many_sliding_window_iterator : public std::iterator<
// 1) iterator type tag: at most forward, but if the base iterator is less,
// then inherit from it
typename iterator_tags<BaseIterator>::inherit_forward,
// 2) value type = return type of the getValue function in the Window class
typename std::remove_reference<decltype(std::declval<Window>().getValue())>::type,
// 3) difference_type = same as base iterator
typename std::iterator_traits<BaseIterator>::difference_type>
{
protected:
// the base iterator traits
typedef std::iterator_traits<BaseIterator> base_traits;
/// This type
typedef one2many_sliding_window_iterator type;
/// The std::iterator_traits of this iterator
typedef std::iterator_traits<type> traits;
public:
/**********************************
* Typedefs for iterator traits *
**********************************/
/// The iterator category of this iterator
typedef typename traits::iterator_category iterator_category;
/// The value type of this iterator
typedef typename traits::value_type value_type;
/// The difference type of this iterator
typedef typename traits::difference_type difference_type;
/// The reference type of a value of this iterator
typedef typename traits::reference reference_type;
/// The pointer type of a value of this iterator
typedef typename traits::pointer pointer_type;
protected:
/**********************
* Member variables *
**********************/
// input iterators, _base is used for comparison and represents the current
// position, while _next reads ahead in order to fill the sliding window.
BaseIterator _base;
BaseIterator _next;
// the offsets in each word (many2one)
difference_type _base_offset;
difference_type _next_offset;
// the window
Window _window;
public:
/**********************
* Member accessors *
**********************/
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
BaseIterator& getBaseIterator()
{
return _base;
}
/**
* @brief Returns the current base iterator.
*
* @return The current base iterator.
*/
const BaseIterator& getBaseIterator() const
{
return _base;
}
/**
* @brief Returns the current offset within the current iterator position.
*
* @return the current offset.
*/
difference_type getOffset() const
{
return _base_offset;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
Window& getWindow()
{
return _window;
}
/**
* @brief Returns a reference to the current window structure.
*
* @return The current sliding window structure.
*/
const Window& getWindow() const
{
return _window;
}
/*****************
* Comparators *
*****************/
/**
* @brief Returns whether this and the given iterator point to the same
* positon.
*
* @return Whether this and the given iterator point to the same position.
*/
inline bool operator==(const one2many_sliding_window_iterator& rhs) const
{
return _base == rhs._base && _base_offset == rhs._base_offset;
}
/**
* @brief Returns whether this and the given iterator are different.
*
* @return Whether this and the given iterator are different.
*/
inline bool operator!=(const one2many_sliding_window_iterator& rhs) const
{
return !this->operator==(rhs);
}
public:
/******************
* Constructors *
******************/
// TODO: more constructors and integrate kmer generation into this
/**
* @brief Constructor, taking the base iterator and the many2one
* functor.
*
* @param base_iter The base iterator that is wrapped via this iterator.
* @param window The sliding window structure
*/
one2many_sliding_window_iterator(const BaseIterator& base_iter, const Window& window)
: _base(base_iter), _next(base_iter),
_base_offset(0), _next_offset(0), _window(window)
{
}
/**
* @brief Returns the value at the current iterator position.
*
* This returns the buffered value of the current sliding window position.
*
* @return The value at the current position.
*/
inline value_type operator*()
{
// in case the current element has not been read yet: do so now
if (this->_base == this->_next && this->_base_offset == this->_next_offset)
{
// add the current element to the sliding window, this sets the next
// and offset pointers to the next readable element/offset
this->_window.next(this->_next, this->_next_offset);
}
// the result was already computed and stored in the functor
return this->_window.getValue();
}
/**
* @brief Pre-increment operator.
*
* Advances this iterator by one position.
*
* @return A reference to this.
*/
type& operator++()
{
// if we have not read the current element (thus iterating one postion
// ahead with _next), then do it now (this happens of operator*() is not
// called)
if (this->_base == this->_next && this->_base_offset == this->_next_offset)
{
// add the current element to the sliding window, this sets the next
// and offset pointers to the next readable element/offset
this->_window.next(this->_next, this->_next_offset);
}
// set both iterators to the same position
this->_base = this->_next;
this->_base_offset = this->_next_offset;
// return a reference to this
return *this;
}
/**
* @brief Post-increment operator.
*
* Advances this iterator by one position, but returns the old iterator state.
*
* @return A copy to the non-incremented iterator.
*/
type operator++(int)
{
// create a copy
type tmp(*this);
this->operator++();
return tmp;
}
};
} // iterator
} // bliss
#endif /* BLISS_ITERATORS_SLIDING_WINDOW_ITERATOR_HPP */
|
fix naming
|
fix naming
|
C++
|
apache-2.0
|
ParBLiSS/kmerind,ParBLiSS/kmerind,ParBLiSS/kmerind,ParBLiSS/kmerind,ParBLiSS/kmerind,ParBLiSS/kmerind
|
99be5d235ed0dc14d6ccbf18dea94508c8aa0c5a
|
src/core/system.cpp
|
src/core/system.cpp
|
/*
** Buggy-Mushroom's Spore Game Library
** Copyright (C) 2008, Buggy-Mushroom Studio
**
** Core system functions
*/
#include "bsgl_impl.h"
#define _KEY_BUF_SIZE 256
int nRef = 0;
BSGL_Impl* pBSGL = 0;
static bool bInit = false;
BSGL* CALL bsglCreate(int ver) {
if( BSGL_VERSION == ver ) {
return (BSGL*)BSGL_Impl::_Interface_Get();
} else {
return 0;
}
}
BSGL_Impl* BSGL_Impl::_Interface_Get() {
if( 0 == pBSGL ) {
pBSGL = new BSGL_Impl();
}
++nRef;
return pBSGL;
}
void CALL BSGL_Impl::Release() {
--nRef;
if( 0 == nRef) {
delete pBSGL;
pBSGL = 0;
}
}
bool CALL BSGL_Impl::System_Initiate() {
System_Log("BSGL Started...\n");
System_Log("BSGL version: %X.%X", BSGL_VERSION>>8, BSGL_VERSION&0xFF);
System_Log("Application: %s\n", szTitle);
_LoadConfig("config.xml");
if( !_GfxInit() ) {
_PostError("Can't initialize OpenGL.");
System_Shutdown();
return false;
}
fTime = 0.0f;
bInit = true;
SDL_WM_SetCaption(szTitle, NULL);
return true;
}
void CALL BSGL_Impl::System_Shutdown() {
System_Log("\nFinishing...");
_GfxDone();
System_Log("The End.");
}
bool CALL BSGL_Impl::System_Start() {
SDL_Event event;
bool done = false;
float time = SDL_GetTicks() / 1000.0f;
float old_time = time;
float old_logic_time = time;
float old_render_time = time;
float time4fps = time;
float logic_dt = 0.0f;
float render_dt = 0.0f;
unsigned int fps = 0;
while( !done ) {
while ( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_ACTIVEEVENT:
if( SDL_APPMOUSEFOCUS == event.active.state ) {
break;
}
if( 0 == event.active.gain ) {
bActive = false;
} else if( 1 == event.active.gain ) {
bActive = true;
}
break;
case SDL_QUIT:
done = true;
break;
default:
break;
}
}
time = SDL_GetTicks() / 1000.0f;
float _t = time - old_time;
old_time = time;
fTime += _t;
if( !bActive ) {
old_logic_time += _t;
old_render_time += _t;
SDL_Delay(1);
continue;
}
if( ( 0 == nLFPS )
|| ( (time-old_logic_time) >= (1.0f/nLFPS) ) ) {
fDeltaTime = logic_dt;
if( fpLogicFunc != 0 ) {
if( fpLogicFunc() ) {
break;
}
}
//fLogicDeltaTime
logic_dt = ( time - old_logic_time );
if( nLFPS != 0 ) {
old_logic_time += (1.0f/nLFPS);
}else {
old_logic_time = time;
}
}
if( ( 0 == nRFPS )
|| ( (time-old_render_time) >= (1.0f/nRFPS) ) ) {
fDeltaTime = render_dt;
if( fpRenderFunc != 0 ) {
if( fpRenderFunc() ) {
break;
}
++fps;
}
glFlush();
SDL_GL_SwapBuffers();
//fRenderDeltaTime
render_dt = ( time - old_render_time );
if( nRFPS != 0 ) {
old_render_time += (1.0f/nRFPS);
}else {
old_render_time = time;
}
}
if( time-time4fps >= 1.0f ) {
//System_Log("fps: %u\ntime: %f", fps, Timer_GetTime());
nFPS = fps;
fps = 0;
time4fps += 1.0f;
}
SDL_Delay(1);
}
return true;
}
void CALL BSGL_Impl::System_SetStateBool(bsglBoolState state, bool value) {
switch( state ) {
case BSGL_WINDOWED:
bWindowed = value;
break;
default:
break;
}
}
void CALL BSGL_Impl::System_SetStateFunc(bsglFuncState state, bsglCallback value) {
switch( state ) {
case BSGL_LOGICFUNC:
fpLogicFunc = value;
break;
case BSGL_RENDERFUNC:
fpRenderFunc = value;
break;
//case BSGL_INPUTFUNC:
// procInputFunc = value;
// break;
default:
break;
}
}
void CALL BSGL_Impl::System_SetStateInt(bsglIntState state, int value) {
switch( state ) {
case BSGL_SCREENWIDTH:
nScreenWidth = value;
break;
case BSGL_SCREENHEIGHT:
nScreenHeight = value;
break;
case BSGL_NUMOFLFPS:
nLFPS = value;
break;
case BSGL_NUMOFRFPS:
nRFPS = value;
break;
case BSGL_POLYMODE:
nPolyMode = value;
break;
default:
break;
}
}
int CALL BSGL_Impl::System_GetStateInt(bsglIntState state) {
switch( state ) {
case BSGL_SCREENWIDTH:
return nScreenWidth;
break;
case BSGL_SCREENHEIGHT:
return nScreenHeight;
break;
case BSGL_NUMOFLFPS:
return nLFPS;
break;
case BSGL_NUMOFRFPS:
return nRFPS;
break;
case BSGL_POLYMODE:
return nPolyMode;
break;
default:
break;
}
return 0;
}
void CALL BSGL_Impl::System_SetStateString(bsglStringState state, const char* value) {
switch( state ) {SDL_GL_SwapBuffers();
case BSGL_TITLE:
if( value != 0 ) {
strcpy(szTitle, value);
}else {
szTitle[0] = (char)0;
}
break;
case BSGL_CFGFILE:
if( value != 0 ) {
strcpy(szCfgFile, value);
}else {
szCfgFile[0] = (char)0;
}
break;
case BSGL_LOGFILE:
if( value != 0 ) {
FILE* fp;
strcpy(szLogFile, value);
fp = fopen(szLogFile, "w");
if( 0 == fp ) {
szLogFile[0] = (char)0;
}else {
fclose(fp);
}
}else {
szLogFile[0] = (char)0;
}
break;
default:
break;
}
}
char* CALL BSGL_Impl::System_GetErrorMessage() {
return szError;
}
void CALL BSGL_Impl::System_Log(const char *szFormat, ...) {
FILE* fp = 0;
va_list vl;
if(!szLogFile[0]) {
return;
}
fp = fopen(szLogFile, "a");
if( 0 == fp ) {
return;
}
va_start(vl, szFormat);
vfprintf(fp, szFormat, vl);
vfprintf(stdout, szFormat, vl);
va_end(vl);
fprintf(fp, "\n");
fprintf(stdout, "\n");
fclose(fp);
}
BSGL_Impl::BSGL_Impl() {
bWindowed = false;
nScreenWidth = 800;
nScreenHeight = 600;
nScreenBPP = 32;
szTitle[0] = (char)0;
szError[0] = (char)0;
szLogFile[0] = (char)0;
bActive = true;
nLFPS = 60;
nRFPS = 0;
fpLogicFunc = 0;
fpRenderFunc = 0;
fTime = 0.0f;
fDeltaTime = 0.0f;
nFPS = 0;
nPolyMode = 0;
this->_key_buf = new unsigned int[_KEY_BUF_SIZE];
memset(_key_buf, 0, _KEY_BUF_SIZE*sizeof(unsigned int));
}
void CALL BSGL_Impl::_LoadConfig(char const* filename) {
if( !filename[0] ) {
return;
}
System_SetStateString(BSGL_CFGFILE, filename);
bool windowed = Config_GetInt("Screen", "Windowed", bWindowed?1:0)==1 ? true : false;
System_SetStateBool(BSGL_WINDOWED, windowed);
int width = Config_GetInt("Screen", "Width", nScreenWidth);
int height = Config_GetInt("Screen", "Height", nScreenHeight);
System_SetStateInt(BSGL_SCREENWIDTH, width);
System_SetStateInt(BSGL_SCREENHEIGHT, height);
int logic_fps = Config_GetInt("FPS", "Logic", nLFPS);
int render_fps = Config_GetInt("FPS", "Render", nRFPS);
System_SetStateInt(BSGL_NUMOFLFPS, logic_fps);
System_SetStateInt(BSGL_NUMOFRFPS, render_fps);
char title[512];
strcpy(title, Config_GetString("Window", "Title", szTitle[0]?szTitle:"BSGL GAME"));
System_SetStateString(BSGL_TITLE, title);
}
void BSGL_Impl::_PostError(const char* error, ...) {
va_list vl;
char _error[256];
va_start(vl, error);
vsprintf(_error, error, vl);
va_end(vl);
System_Log("Error: %s", _error);
strcpy(szError, _error);
}
|
/*
** Buggy-Mushroom's Spore Game Library
** Copyright (C) 2008, Buggy-Mushroom Studio
**
** Core system functions
*/
#include "bsgl_impl.h"
#define _KEY_BUF_SIZE 256
int nRef = 0;
BSGL_Impl* pBSGL = 0;
static bool bInit = false;
BSGL* CALL bsglCreate(int ver) {
if( BSGL_VERSION == ver ) {
return (BSGL*)BSGL_Impl::_Interface_Get();
} else {
return 0;
}
}
BSGL_Impl* BSGL_Impl::_Interface_Get() {
if( 0 == pBSGL ) {
pBSGL = new BSGL_Impl();
}
++nRef;
return pBSGL;
}
void CALL BSGL_Impl::Release() {
--nRef;
if( 0 == nRef) {
delete pBSGL;
pBSGL = 0;
}
}
bool CALL BSGL_Impl::System_Initiate() {
System_Log("BSGL Started...\n");
System_Log("BSGL version: %X.%X", BSGL_VERSION>>8, BSGL_VERSION&0xFF);
System_Log("Application: %s\n", szTitle);
_LoadConfig("config.xml");
if( !_GfxInit() ) {
_PostError("Can't initialize OpenGL.");
System_Shutdown();
return false;
}
fTime = 0.0f;
bInit = true;
SDL_WM_SetCaption(szTitle, NULL);
return true;
}
void CALL BSGL_Impl::System_Shutdown() {
System_Log("\nFinishing...");
_GfxDone();
System_Log("The End.");
}
bool CALL BSGL_Impl::System_Start() {
SDL_Event event;
bool done = false;
float time = SDL_GetTicks() / 1000.0f;
float old_time = time;
float old_logic_time = time;
float old_render_time = time;
float time4fps = time;
float logic_dt = 0.0f;
float render_dt = 0.0f;
unsigned int fps = 0;
while( !done ) {
while ( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_ACTIVEEVENT:
if( SDL_APPMOUSEFOCUS == event.active.state ) {
break;
}
if( 0 == event.active.gain ) {
bActive = false;
} else if( 1 == event.active.gain ) {
bActive = true;
}
break;
case SDL_QUIT:
done = true;
break;
default:
break;
}
}
time = SDL_GetTicks() / 1000.0f;
float _t = time - old_time;
old_time = time;
fTime += _t;
if( !bActive ) {
old_logic_time += _t;
old_render_time += _t;
SDL_Delay(1);
continue;
}
if( ( 0 == nLFPS )
|| ( (time-old_logic_time) >= (1.0f/nLFPS) ) ) {
fDeltaTime = logic_dt;
if( fpLogicFunc != 0 ) {
if( fpLogicFunc() ) {
break;
}
}
//fLogicDeltaTime
logic_dt = ( time - old_logic_time );
if( nLFPS != 0 ) {
old_logic_time += (1.0f/nLFPS);
}else {
old_logic_time = time;
}
}
if( ( 0 == nRFPS )
|| ( (time-old_render_time) >= (1.0f/nRFPS) ) ) {
fDeltaTime = render_dt;
if( fpRenderFunc != 0 ) {
if( fpRenderFunc() ) {
break;
}
++fps;
}
glFlush();
SDL_GL_SwapBuffers();
//fRenderDeltaTime
render_dt = ( time - old_render_time );
if( nRFPS != 0 ) {
old_render_time += (1.0f/nRFPS);
}else {
old_render_time = time;
}
}
if( time-time4fps >= 1.0f ) {
//System_Log("fps: %u\ntime: %f", fps, Timer_GetTime());
nFPS = fps;
fps = 0;
time4fps += 1.0f;
}
SDL_Delay(1);
}
return true;
}
void CALL BSGL_Impl::System_SetStateBool(bsglBoolState state, bool value) {
switch( state ) {
case BSGL_WINDOWED:
bWindowed = value;
break;
default:
break;
}
}
void CALL BSGL_Impl::System_SetStateFunc(bsglFuncState state, bsglCallback value) {
switch( state ) {
case BSGL_LOGICFUNC:
fpLogicFunc = value;
break;
case BSGL_RENDERFUNC:
fpRenderFunc = value;
break;
//case BSGL_INPUTFUNC:
// procInputFunc = value;
// break;
default:
break;
}
}
void CALL BSGL_Impl::System_SetStateInt(bsglIntState state, int value) {
switch( state ) {
case BSGL_SCREENWIDTH:
nScreenWidth = value;
break;
case BSGL_SCREENHEIGHT:
nScreenHeight = value;
break;
case BSGL_NUMOFLFPS:
nLFPS = value;
break;
case BSGL_NUMOFRFPS:
nRFPS = value;
break;
case BSGL_POLYMODE:
nPolyMode = value;
break;
default:
break;
}
}
int CALL BSGL_Impl::System_GetStateInt(bsglIntState state) {
switch( state ) {
case BSGL_SCREENWIDTH:
return nScreenWidth;
break;
case BSGL_SCREENHEIGHT:
return nScreenHeight;
break;
case BSGL_NUMOFLFPS:
return nLFPS;
break;
case BSGL_NUMOFRFPS:
return nRFPS;
break;
case BSGL_POLYMODE:
return nPolyMode;
break;
default:
break;
}
return 0;
}
void CALL BSGL_Impl::System_SetStateString(bsglStringState state, const char* value) {
switch( state ) {SDL_GL_SwapBuffers();
case BSGL_TITLE:
if( value != 0 ) {
strcpy(szTitle, value);
}else {
szTitle[0] = (char)0;
}
break;
case BSGL_CFGFILE:
if( value != 0 ) {
strcpy(szCfgFile, value);
}else {
szCfgFile[0] = (char)0;
}
break;
case BSGL_LOGFILE:
if( value != 0 ) {
FILE* fp;
strcpy(szLogFile, value);
fp = fopen(szLogFile, "w");
if( 0 == fp ) {
szLogFile[0] = (char)0;
}else {
fclose(fp);
}
}else {
szLogFile[0] = (char)0;
}
break;
default:
break;
}
}
char* CALL BSGL_Impl::System_GetErrorMessage() {
return szError;
}
void CALL BSGL_Impl::System_Log(const char *szFormat, ...) {
FILE* fp = 0;
va_list vl;
if(!szLogFile[0]) {
return;
}
fp = fopen(szLogFile, "a");
if( 0 == fp ) {
return;
}
va_start(vl, szFormat);
vfprintf(fp, szFormat, vl);
va_end(vl);
va_start(vl, szFormat);
vfprintf(stdout, szFormat, vl);
va_end(vl);
fprintf(fp, "\n");
fprintf(stdout, "\n");
fclose(fp);
}
BSGL_Impl::BSGL_Impl() {
bWindowed = false;
nScreenWidth = 800;
nScreenHeight = 600;
nScreenBPP = 32;
szTitle[0] = (char)0;
szError[0] = (char)0;
szLogFile[0] = (char)0;
bActive = true;
nLFPS = 60;
nRFPS = 0;
fpLogicFunc = 0;
fpRenderFunc = 0;
fTime = 0.0f;
fDeltaTime = 0.0f;
nFPS = 0;
nPolyMode = 0;
this->_key_buf = new unsigned int[_KEY_BUF_SIZE];
memset(_key_buf, 0, _KEY_BUF_SIZE*sizeof(unsigned int));
}
void CALL BSGL_Impl::_LoadConfig(char const* filename) {
if( !filename[0] ) {
return;
}
System_SetStateString(BSGL_CFGFILE, filename);
bool windowed = Config_GetInt("Screen", "Windowed", bWindowed?1:0)==1 ? true : false;
System_SetStateBool(BSGL_WINDOWED, windowed);
int width = Config_GetInt("Screen", "Width", nScreenWidth);
int height = Config_GetInt("Screen", "Height", nScreenHeight);
System_SetStateInt(BSGL_SCREENWIDTH, width);
System_SetStateInt(BSGL_SCREENHEIGHT, height);
int logic_fps = Config_GetInt("FPS", "Logic", nLFPS);
int render_fps = Config_GetInt("FPS", "Render", nRFPS);
System_SetStateInt(BSGL_NUMOFLFPS, logic_fps);
System_SetStateInt(BSGL_NUMOFRFPS, render_fps);
char title[512];
strcpy(title, Config_GetString("Window", "Title", szTitle[0]?szTitle:"BSGL GAME"));
System_SetStateString(BSGL_TITLE, title);
}
void BSGL_Impl::_PostError(const char* error, ...) {
va_list vl;
char _error[256];
va_start(vl, error);
vsprintf(_error, error, vl);
va_end(vl);
System_Log("Error: %s", _error);
strcpy(szError, _error);
}
|
fix a bug about System_Log
|
fix a bug about System_Log
|
C++
|
mit
|
yozefx/bsgl,yozefx/bsgl,funcman/bsgl
|
a45cf0e1c3e3b9b70f4c58cd6735d3d66ffd445a
|
src/crashdetect.cpp
|
src/crashdetect.cpp
|
// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY 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 <cassert>
#include <cstdarg>
#include <map>
#include <stack>
#include <string>
#include "amxdebuginfo.h"
#include "amxpathfinder.h"
#include "amxstacktrace.h"
#include "amxutils.h"
#include "compiler.h"
#include "configreader.h"
#include "crashdetect.h"
#include "fileutils.h"
#include "logprintf.h"
#include "os.h"
#include "stacktrace.h"
#include "amx/amx.h"
#include "amx/amxaux.h" // for amx_StrError()
#define AMX_EXEC_GDK (-10)
static const char *kLogMessagePrefix = "[debug] ";
static const char *kServerConfig = "server.cfg";
bool crashdetect::errorCaught_ = false;
std::stack<crashdetect::NPCall> crashdetect::npCalls_;
ConfigReader crashdetect::serverCfg(kServerConfig);
crashdetect::InstanceMap crashdetect::instances_;
// static
crashdetect *crashdetect::GetInstance(AMX *amx) {
InstanceMap::const_iterator iterator = instances_.find(amx);
if (iterator == instances_.end()) {
crashdetect *c = new crashdetect(amx);
instances_.insert(std::make_pair(amx, c));
return c;
}
return iterator->second;
}
// static
void crashdetect::DestroyInstance(AMX *amx) {
instances_.erase(amx);
}
// static
void crashdetect::SystemException(void *context) {
if (!npCalls_.empty()) {
AMX *amx = npCalls_.top().amx();
GetInstance(amx)->HandleCrash();
} else {
logprintf("Server crashed due to an unknown error");
}
PrintSystemBacktrace(context);
}
// static
void crashdetect::SystemInterrupt() {
if (!npCalls_.empty()) {
AMX *amx = npCalls_.top().amx();
GetInstance(amx)->HandleInterrupt();
} else {
logprintf("Server recieved an interrupt signal");
}
PrintSystemBacktrace();
}
// static
void crashdetect::DieOrContinue() {
if (serverCfg.GetOption("die_on_error", false)) {
logprintf("Aborting...");
std::exit(EXIT_FAILURE);
}
}
crashdetect::crashdetect(AMX *amx)
: amx_(amx)
, amxhdr_(reinterpret_cast<AMX_HEADER*>(amx->base))
{
AMXPathFinder pathFinder;
pathFinder.AddSearchPath("gamemodes");
pathFinder.AddSearchPath("filterscripts");
// Read a list of additional search paths from AMX_PATH.
const char *AMX_PATH = getenv("AMX_PATH");
if (AMX_PATH != 0) {
std::string var(AMX_PATH);
std::string path;
std::string::size_type begin = 0;
while (begin < var.length()) {
std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin);
if (end == std::string::npos) {
end = var.length();
}
path.assign(var.begin() + begin, var.begin() + end);
if (!path.empty()) {
pathFinder.AddSearchPath(path);
}
begin = end + 1;
}
}
amxPath_ = pathFinder.FindAMX(amx);
amxName_ = fileutils::GetFileName(amxPath_);
if (!amxPath_.empty()) {
uint16_t flags;
amx_Flags(amx_, &flags);
if ((flags & AMX_FLAG_DEBUG) != 0) {
debugInfo_.Load(amxPath_);
}
}
amx_->sysreq_d = 0;
prevCallback_ = amx_->callback;
}
int crashdetect::HandleAmxCallback(cell index, cell *result, cell *params) {
npCalls_.push(NPCall(NPCall::NATIVE, amx_, index, amx_->frm, amx_->cip));
int retcode = prevCallback_(amx_, index, result, params);
npCalls_.pop();
return retcode;
}
int crashdetect::HandleAmxExec(cell *retval, int index) {
npCalls_.push(NPCall(NPCall::PUBLIC, amx_, index, amx_->frm, amx_->cip));
int retcode = ::amx_Exec(amx_, retval, index);
if (retcode != AMX_ERR_NONE && !errorCaught_) {
amx_Error(amx_, index, retcode);
} else {
errorCaught_ = false;
}
npCalls_.pop();
return retcode;
}
int crashdetect::HandleAmxRelease(cell amx_addr, void *releaser) {
if (amx_addr < amx_->hlw || amx_addr >= amx_->stk) {
HandleReleaseError(amx_addr, releaser);
}
return amx_Release(amx_, amx_addr);
}
void crashdetect::HandleRuntimeError(int index, int error) {
crashdetect::errorCaught_ = true;
if (error == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
error = AMX_ERR_NONE;
return;
}
logprintf("Run time error %d: \"%s\"", error, aux_StrError(error));
switch (error) {
case AMX_ERR_BOUNDS: {
cell bound = *(reinterpret_cast<cell*>(amx_->cip + amx_->base + amxhdr_->cod + sizeof(cell)));
cell index = amx_->pri;
if (index < 0) {
logprintf(" Accessing element at negative index %d", index);
} else {
logprintf(" Accessing element at index %d past array upper bound %d", index, bound);
}
break;
}
case AMX_ERR_NOTFOUND: {
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + amxhdr_->natives);
int numNatives = 0;
amx_NumNatives(amx_, &numNatives);
for (int i = 0; i < numNatives; ++i) {
if (natives[i].address == 0) {
char *name = reinterpret_cast<char*>(natives[i].nameofs + amx_->base);
logprintf(" %s", name);
}
}
break;
}
case AMX_ERR_STACKERR:
logprintf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_->stk, amx_->hea);
break;
case AMX_ERR_STACKLOW:
logprintf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_->stk, amx_->stp);
break;
case AMX_ERR_HEAPLOW:
logprintf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_->hea, amx_->hlw);
break;
case AMX_ERR_INVINSTR: {
cell opcode = *(reinterpret_cast<cell*>(amx_->cip + amx_->base + amxhdr_->cod));
logprintf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_->cip);
break;
}
}
if (error != AMX_ERR_NOTFOUND &&
error != AMX_ERR_INDEX &&
error != AMX_ERR_CALLBACK &&
error != AMX_ERR_INIT)
{
PrintAmxBacktrace();
}
std::string command = serverCfg.GetOption("run_on_error", std::string());
if (!command.empty()) {
std::system(command.c_str());
}
DieOrContinue();
}
void crashdetect::HandleCrash() {
logprintf("Server crashed while executing %s", amxName_.c_str());
PrintAmxBacktrace();
}
void crashdetect::HandleInterrupt() {
logprintf("Server recieved interrupt signal while executing %s", amxName_.c_str());
PrintAmxBacktrace();
}
void crashdetect::HandleReleaseError(cell address, void *releaser) {
std::string plugin = fileutils::GetFileName(os::GetModulePath(releaser));
if (plugin.empty()) {
plugin.assign("<unknown>");
}
logprintf("Bad heap release detected:");
logprintf(" %s [%08x] releases memory at %08x which is out of heap", plugin.c_str(), releaser, address);
PrintSystemBacktrace();
}
// static
void crashdetect::PrintAmxBacktrace() {
if (npCalls_.empty()) {
return;
}
logprintf("AMX backtrace:");
std::stack<NPCall> npCallStack = npCalls_;
cell frm = npCallStack.top().amx()->frm;
cell cip = npCallStack.top().amx()->cip;
int level = 0;
while (!npCallStack.empty()) {
NPCall call = npCallStack.top();
if (call.amx() != npCallStack.top().amx()) {
assert(level != 0);
break;
}
if (call.type() == NPCall::NATIVE) {
AMX_NATIVE address = amxutils::GetNativeAddress(call.amx(), call.index());
if (address != 0) {
std::string module = fileutils::GetFileName(os::GetModulePath((void*)address));
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
const char *name = amxutils::GetNativeName(call.amx(), call.index());
if (name != 0) {
logprintf("#%d native %s () [%08x]%s", level++, name, address, from.c_str());
}
}
} else if (call.type() == NPCall::PUBLIC) {
AMXDebugInfo &debugInfo = instances_[call.amx()]->debugInfo_;
amxutils::PushStack(call.amx(), cip); // push return address
amxutils::PushStack(call.amx(), frm); // push frame pointer
frm = call.amx()->stk;
AMXStackTrace trace(call.amx(), debugInfo, frm);
std::deque<AMXStackFrame> frames = trace.GetFrames();
frm = amxutils::PopStack(call.amx()); // pop frame pointer
cip = amxutils::PopStack(call.amx()); // pop return address
if (frames.empty()) {
ucell epAddr = amxutils::GetPublicAddress(call.amx(), call.index());
frames.push_front(AMXStackFrame(call.amx(), frm, 0, epAddr, debugInfo));
} else {
if (!debugInfo.IsLoaded()) {
AMXStackFrame &bottom = frames.back();
bottom = AMXStackFrame(call.amx(),
bottom.GetFrameAddress(),
bottom.GetReturnAddress(),
amxutils::GetPublicAddress(call.amx(), call.index()),
debugInfo);
}
}
std::string &amxName = instances_[call.amx()]->amxName_;
for (size_t i = 0; i < frames.size(); i++) {
std::string from = " from " + amxName;
if (amxName.empty() || debugInfo.IsLoaded()) {
from.clear();
}
logprintf("#%d %s%s", level++, frames[i].GetString().c_str(), from.c_str());
}
frm = call.frm();
cip = call.cip();
}
npCallStack.pop();
}
}
// static
void crashdetect::PrintSystemBacktrace(void *context) {
logprintf("System backtrace:");
int level = 0;
StackTrace trace(0, 0, context);
std::deque<StackFrame> frames = trace.GetFrames();
for (std::deque<StackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator) {
const StackFrame &frame = *iterator;
std::string module = os::GetModulePath(frame.GetReturnAddress());
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
logprintf("#%d %s%s", level++, frame.GetString().c_str(), from.c_str());
}
}
// static
void crashdetect::logprintf(const char *format, ...) {
std::va_list args;
va_start(args, format);
std::string prefixed_format;
prefixed_format.append(kLogMessagePrefix);
prefixed_format.append(format);
::vlogprintf(prefixed_format.c_str(), args);
va_end(args);
}
|
// Copyright (c) 2011-2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY 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 <cassert>
#include <cstdarg>
#include <map>
#include <stack>
#include <string>
#include "amxdebuginfo.h"
#include "amxpathfinder.h"
#include "amxstacktrace.h"
#include "amxutils.h"
#include "compiler.h"
#include "configreader.h"
#include "crashdetect.h"
#include "fileutils.h"
#include "logprintf.h"
#include "os.h"
#include "stacktrace.h"
#include "amx/amx.h"
#include "amx/amxaux.h" // for amx_StrError()
#define AMX_EXEC_GDK (-10)
static const char *kLogMessagePrefix = "[debug] ";
static const char *kServerConfig = "server.cfg";
bool crashdetect::errorCaught_ = false;
std::stack<crashdetect::NPCall> crashdetect::npCalls_;
ConfigReader crashdetect::serverCfg(kServerConfig);
crashdetect::InstanceMap crashdetect::instances_;
// static
crashdetect *crashdetect::GetInstance(AMX *amx) {
InstanceMap::const_iterator iterator = instances_.find(amx);
if (iterator == instances_.end()) {
crashdetect *c = new crashdetect(amx);
instances_.insert(std::make_pair(amx, c));
return c;
}
return iterator->second;
}
// static
void crashdetect::DestroyInstance(AMX *amx) {
instances_.erase(amx);
}
// static
void crashdetect::SystemException(void *context) {
if (!npCalls_.empty()) {
AMX *amx = npCalls_.top().amx();
GetInstance(amx)->HandleCrash();
} else {
logprintf("Server crashed due to an unknown error");
}
PrintSystemBacktrace(context);
}
// static
void crashdetect::SystemInterrupt() {
if (!npCalls_.empty()) {
AMX *amx = npCalls_.top().amx();
GetInstance(amx)->HandleInterrupt();
} else {
logprintf("Server recieved an interrupt signal");
}
PrintSystemBacktrace();
}
// static
void crashdetect::DieOrContinue() {
if (serverCfg.GetOption("die_on_error", false)) {
logprintf("Aborting...");
std::exit(EXIT_FAILURE);
}
}
crashdetect::crashdetect(AMX *amx)
: amx_(amx)
, amxhdr_(reinterpret_cast<AMX_HEADER*>(amx->base))
{
AMXPathFinder pathFinder;
pathFinder.AddSearchPath("gamemodes");
pathFinder.AddSearchPath("filterscripts");
// Read a list of additional search paths from AMX_PATH.
const char *AMX_PATH = getenv("AMX_PATH");
if (AMX_PATH != 0) {
std::string var(AMX_PATH);
std::string path;
std::string::size_type begin = 0;
while (begin < var.length()) {
std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin);
if (end == std::string::npos) {
end = var.length();
}
path.assign(var.begin() + begin, var.begin() + end);
if (!path.empty()) {
pathFinder.AddSearchPath(path);
}
begin = end + 1;
}
}
amxPath_ = pathFinder.FindAMX(amx);
amxName_ = fileutils::GetFileName(amxPath_);
if (!amxPath_.empty()) {
uint16_t flags;
amx_Flags(amx_, &flags);
if ((flags & AMX_FLAG_DEBUG) != 0) {
debugInfo_.Load(amxPath_);
}
}
amx_->sysreq_d = 0;
prevCallback_ = amx_->callback;
}
int crashdetect::HandleAmxCallback(cell index, cell *result, cell *params) {
npCalls_.push(NPCall(NPCall::NATIVE, amx_, index, amx_->frm, amx_->cip));
int retcode = prevCallback_(amx_, index, result, params);
npCalls_.pop();
return retcode;
}
int crashdetect::HandleAmxExec(cell *retval, int index) {
npCalls_.push(NPCall(NPCall::PUBLIC, amx_, index, amx_->frm, amx_->cip));
int retcode = ::amx_Exec(amx_, retval, index);
if (retcode != AMX_ERR_NONE && !errorCaught_) {
amx_Error(amx_, index, retcode);
} else {
errorCaught_ = false;
}
npCalls_.pop();
return retcode;
}
int crashdetect::HandleAmxRelease(cell amx_addr, void *releaser) {
if (amx_addr < amx_->hlw || amx_addr >= amx_->stk) {
HandleReleaseError(amx_addr, releaser);
}
return amx_Release(amx_, amx_addr);
}
void crashdetect::HandleRuntimeError(int index, int error) {
crashdetect::errorCaught_ = true;
if (error == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
error = AMX_ERR_NONE;
return;
}
logprintf("Run time error %d: \"%s\"", error, aux_StrError(error));
switch (error) {
case AMX_ERR_BOUNDS: {
cell bound = *(reinterpret_cast<cell*>(amx_->cip + amx_->base + amxhdr_->cod + sizeof(cell)));
cell index = amx_->pri;
if (index < 0) {
logprintf(" Accessing element at negative index %d", index);
} else {
logprintf(" Accessing element at index %d past array upper bound %d", index, bound);
}
break;
}
case AMX_ERR_NOTFOUND: {
AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + amxhdr_->natives);
int numNatives = 0;
amx_NumNatives(amx_, &numNatives);
for (int i = 0; i < numNatives; ++i) {
if (natives[i].address == 0) {
char *name = reinterpret_cast<char*>(natives[i].nameofs + amx_->base);
logprintf(" %s", name);
}
}
break;
}
case AMX_ERR_STACKERR:
logprintf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_->stk, amx_->hea);
break;
case AMX_ERR_STACKLOW:
logprintf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_->stk, amx_->stp);
break;
case AMX_ERR_HEAPLOW:
logprintf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_->hea, amx_->hlw);
break;
case AMX_ERR_INVINSTR: {
cell opcode = *(reinterpret_cast<cell*>(amx_->cip + amx_->base + amxhdr_->cod));
logprintf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_->cip);
break;
}
}
if (error != AMX_ERR_NOTFOUND &&
error != AMX_ERR_INDEX &&
error != AMX_ERR_CALLBACK &&
error != AMX_ERR_INIT)
{
PrintAmxBacktrace();
}
std::string command = serverCfg.GetOption("run_on_error", std::string());
if (!command.empty()) {
std::system(command.c_str());
}
DieOrContinue();
}
void crashdetect::HandleCrash() {
logprintf("Server crashed while executing %s", amxName_.c_str());
PrintAmxBacktrace();
}
void crashdetect::HandleInterrupt() {
logprintf("Server recieved interrupt signal while executing %s", amxName_.c_str());
PrintAmxBacktrace();
}
void crashdetect::HandleReleaseError(cell address, void *releaser) {
std::string plugin = fileutils::GetFileName(os::GetModulePath(releaser));
if (plugin.empty()) {
plugin.assign("<unknown>");
}
logprintf("Bad heap release detected:");
logprintf(" %s [%08x] releases memory at %08x which is out of heap", plugin.c_str(), releaser, address);
PrintSystemBacktrace();
}
// static
void crashdetect::PrintAmxBacktrace() {
if (npCalls_.empty()) {
return;
}
std::stack<NPCall> npCallStack = npCalls_;
cell frm = npCallStack.top().amx()->frm;
cell cip = npCallStack.top().amx()->cip;
int level = 0;
if (cip == 0) {
return;
}
logprintf("AMX backtrace:");
while (!npCallStack.empty() && cip != 0) {
NPCall call = npCallStack.top();
if (call.amx() != npCallStack.top().amx()) {
assert(level != 0);
break;
}
if (call.type() == NPCall::NATIVE) {
AMX_NATIVE address = amxutils::GetNativeAddress(call.amx(), call.index());
if (address != 0) {
std::string module = fileutils::GetFileName(os::GetModulePath((void*)address));
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
const char *name = amxutils::GetNativeName(call.amx(), call.index());
if (name != 0) {
logprintf("#%d native %s () [%08x]%s", level++, name, address, from.c_str());
}
}
} else if (call.type() == NPCall::PUBLIC) {
AMXDebugInfo &debugInfo = instances_[call.amx()]->debugInfo_;
amxutils::PushStack(call.amx(), cip); // push return address
amxutils::PushStack(call.amx(), frm); // push frame pointer
frm = call.amx()->stk;
AMXStackTrace trace(call.amx(), debugInfo, frm);
std::deque<AMXStackFrame> frames = trace.GetFrames();
frm = amxutils::PopStack(call.amx()); // pop frame pointer
cip = amxutils::PopStack(call.amx()); // pop return address
if (frames.empty()) {
ucell epAddr = amxutils::GetPublicAddress(call.amx(), call.index());
frames.push_front(AMXStackFrame(call.amx(), frm, 0, epAddr, debugInfo));
} else {
if (!debugInfo.IsLoaded()) {
AMXStackFrame &bottom = frames.back();
bottom = AMXStackFrame(call.amx(),
bottom.GetFrameAddress(),
bottom.GetReturnAddress(),
amxutils::GetPublicAddress(call.amx(), call.index()),
debugInfo);
}
}
std::string &amxName = instances_[call.amx()]->amxName_;
for (size_t i = 0; i < frames.size(); i++) {
std::string from = " from " + amxName;
if (amxName.empty() || debugInfo.IsLoaded()) {
from.clear();
}
logprintf("#%d %s%s", level++, frames[i].GetString().c_str(), from.c_str());
}
frm = call.frm();
cip = call.cip();
}
npCallStack.pop();
}
}
// static
void crashdetect::PrintSystemBacktrace(void *context) {
logprintf("System backtrace:");
int level = 0;
StackTrace trace(0, 0, context);
std::deque<StackFrame> frames = trace.GetFrames();
for (std::deque<StackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator) {
const StackFrame &frame = *iterator;
std::string module = os::GetModulePath(frame.GetReturnAddress());
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
logprintf("#%d %s%s", level++, frame.GetString().c_str(), from.c_str());
}
}
// static
void crashdetect::logprintf(const char *format, ...) {
std::va_list args;
va_start(args, format);
std::string prefixed_format;
prefixed_format.append(kLogMessagePrefix);
prefixed_format.append(format);
::vlogprintf(prefixed_format.c_str(), args);
va_end(args);
}
|
Make PrintAmxBacktrace() print nothing if CIP == 0
|
Make PrintAmxBacktrace() print nothing if CIP == 0
|
C++
|
bsd-2-clause
|
Zeex/samp-plugin-crashdetect,Zeex/samp-plugin-crashdetect,Zeex/samp-plugin-crashdetect
|
7b28ff494b94598f4d1c3fbc27bffe7c62d3f148
|
src/crashdetect.cpp
|
src/crashdetect.cpp
|
// Copyright (c) 2011-2013 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY 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 <cassert>
#include <cstdarg>
#include <cstdlib>
#include <list>
#include <map>
#include <stack>
#include <string>
#include <amx/amx.h>
#include <amx/amxaux.h>
#include "amxdebuginfo.h"
#include "amxerror.h"
#include "amxpathfinder.h"
#include "amxscript.h"
#include "amxstacktrace.h"
#include "compiler.h"
#include "configreader.h"
#include "crashdetect.h"
#include "fileutils.h"
#include "logprintf.h"
#include "npcall.h"
#include "os.h"
#include "stacktrace.h"
#define AMX_EXEC_GDK (-10)
static const int kOpBounds = 121;
static const int kOpSysreqC = 123;
bool CrashDetect::error_detected_ = false;
std::stack<NPCall*> CrashDetect::np_calls_;;
// static
void CrashDetect::OnException(void *context) {
if (!np_calls_.empty()) {
CrashDetect::Get(np_calls_.top()->amx())->HandleException();
} else {
Printf("Server crashed due to an unknown error");
}
PrintSystemBacktrace(context);
}
// static
void CrashDetect::OnInterrupt(void *context) {
if (!np_calls_.empty()) {
CrashDetect::Get(np_calls_.top()->amx())->HandleInterrupt();
} else {
Printf("Server received interrupt signal");
}
PrintSystemBacktrace(context);
}
// static
void CrashDetect::PrintAmxBacktrace() {
if (np_calls_.empty()) {
return;
}
AMXScript topAmx = np_calls_.top()->amx();
cell frm = topAmx.GetFrm();
cell cip = topAmx.GetCip();
int level = 0;
if (cip == 0) {
return;
}
Printf("AMX backtrace:");
std::stack<NPCall*> np_calls = np_calls_;
while (!np_calls.empty() && cip != 0) {
const NPCall *call = np_calls.top();
AMXScript amx = call->amx();
// We don't trace calls across AMX bounds i.e. outside of top-level
// function's AMX instance.
if (amx != topAmx) {
assert(level != 0);
break;
}
if (call->IsNative()) {
AMX_NATIVE address = reinterpret_cast<AMX_NATIVE>(amx.GetNativeAddr(call->index()));
if (address != 0) {
std::string module = fileutils::GetFileName(os::GetModulePathFromAddr((void*)address));
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
const char *name = amx.GetNativeName(call->index());
if (name != 0) {
Printf("#%d native %s () [%08x]%s", level++, name, address, from.c_str());
}
}
} else if (call->IsPublic()) {
AMXDebugInfo &debug_info = CrashDetect::Get(amx)->debug_info_;
amx.PushStack(cip); // push return address
amx.PushStack(frm); // push frame pointer
std::list<AMXStackFrame> frames;
{
AMXStackTrace trace(amx, amx.GetStk(), &debug_info);
do {
AMXStackFrame frame = trace.GetFrame();
if (frame) {
frames.push_back(frame);
} else {
break;
}
} while (trace.Next());
}
frm = amx.PopStack(); // pop frame pointer
cip = amx.PopStack(); // pop return address
if (frames.empty()) {
ucell ep_addr = amx.GetPublicAddr(call->index());
frames.push_front(AMXStackFrame(amx, frm, 0, ep_addr, &debug_info));
} else {
if (!debug_info.IsLoaded()) {
AMXStackFrame &bottom = frames.back();
bottom = AMXStackFrame(amx,
bottom.GetFrameAddr(),
bottom.GetRetAddr(),
amx.GetPublicAddr(call->index()),
&debug_info);
}
}
std::string &amx_name = CrashDetect::Get(amx)->amx_name_;
for (std::list<AMXStackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator)
{
std::string from = " from " + amx_name;
if (amx_name.empty() || debug_info.IsLoaded()) {
from.clear();
}
Printf("#%d %s%s", level++, iterator->AsString().c_str(), from.c_str());
}
frm = call->frm();
cip = call->cip();
}
np_calls.pop();
}
}
// static
void CrashDetect::PrintSystemBacktrace(void *context) {
Printf("System backtrace:");
int level = 0;
StackTrace trace(context);
std::deque<StackFrame> frames = trace.GetFrames();
for (std::deque<StackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator) {
const StackFrame &frame = *iterator;
std::string module = os::GetModulePathFromAddr(frame.GetRetAddr());
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
Printf("#%d %s%s", level++, frame.AsString().c_str(), from.c_str());
}
}
// static
void CrashDetect::Printf(const char *format, ...) {
std::va_list va;
va_start(va, format);
std::string new_format;
new_format.append("[debug] ");
new_format.append(format);
vlogprintf(new_format.c_str(), va);
va_end(va);
}
CrashDetect::CrashDetect(AMX *amx)
: AMXService<CrashDetect>(amx)
, amx_(amx)
, prev_callback_(0)
, die_on_error_(false)
, run_on_error_("")
{
ConfigReader server_cfg("server.cfg");
die_on_error_ = server_cfg.GetOption("die_on_error", false);
run_on_error_ = server_cfg.GetOption("run_on_error", std::string());
}
int CrashDetect::Load() {
AMXPathFinder pathFinder;
pathFinder.AddSearchPath("gamemodes");
pathFinder.AddSearchPath("filterscripts");
// Read a list of additional search paths from AMX_PATH.
const char *AMX_PATH = getenv("AMX_PATH");
if (AMX_PATH != 0) {
std::string var(AMX_PATH);
std::string path;
std::string::size_type begin = 0;
while (begin < var.length()) {
std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin);
if (end == std::string::npos) {
end = var.length();
}
path.assign(var.begin() + begin, var.begin() + end);
if (!path.empty()) {
pathFinder.AddSearchPath(path);
}
begin = end + 1;
}
}
amx_path_ = pathFinder.FindAMX(this->amx());
amx_name_ = fileutils::GetFileName(amx_path_);
if (!amx_path_.empty() && AMXDebugInfo::IsPresent(this->amx())) {
debug_info_.Load(amx_path_);
}
amx_.DisableSysreqD();
prev_callback_ = amx_.GetCallback();
return AMX_ERR_NONE;
}
int CrashDetect::Unload() {
return AMX_ERR_NONE;
}
int CrashDetect::DoAmxCallback(cell index, cell *result, cell *params) {
NPCall call = NPCall::Native(amx(), index);
np_calls_.push(&call);
int error = prev_callback_(amx(), index, result, params);
np_calls_.pop();
return error;
}
int CrashDetect::DoAmxExec(cell *retval, int index) {
NPCall call = NPCall::Public(amx(), index);
np_calls_.push(&call);
int error = ::amx_Exec(amx(), retval, index);
if (error != AMX_ERR_NONE && !error_detected_) {
HandleExecError(index, error);
} else {
error_detected_ = false;
}
np_calls_.pop();
return error;
}
void CrashDetect::HandleExecError(int index, const AMXError &error) {
CrashDetect::error_detected_ = true;
if (error.code() == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
return;
}
PrintError(error);
if (error.code() != AMX_ERR_NOTFOUND &&
error.code() != AMX_ERR_INDEX &&
error.code() != AMX_ERR_CALLBACK &&
error.code() != AMX_ERR_INIT)
{
PrintAmxBacktrace();
}
if (!run_on_error_.empty()) {
std::system(run_on_error_.c_str());
}
DieOrContinue();
}
void CrashDetect::HandleException() {
Printf("Server crashed while executing %s", amx_name_.c_str());
PrintAmxBacktrace();
}
void CrashDetect::HandleInterrupt() {
Printf("Server received interrupt signal while executing %s", amx_name_.c_str());
PrintAmxBacktrace();
}
void CrashDetect::PrintError(const AMXError &error) const {
Printf("Run time error %d: \"%s\"", error.code(), error.GetString());
switch (error.code()) {
case AMX_ERR_BOUNDS: {
const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip());
cell opcode = *ip;
if (opcode == kOpBounds) {
cell bound = *(ip + 1);
cell index = amx_.GetPri();
if (index < 0) {
Printf(" Accessing element at negative index %d", index);
} else {
Printf(" Accessing element at index %d past array upper bound %d", index, bound);
}
}
break;
}
case AMX_ERR_NOTFOUND: {
const AMX_FUNCSTUBNT *natives = amx_.GetNatives();
int num_natives = amx_.GetNumNatives();
for (int i = 0; i < num_natives; ++i) {
if (natives[i].address == 0) {
Printf(" %s", amx_.GetName(natives[i].nameofs));
}
}
break;
}
case AMX_ERR_STACKERR:
Printf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_.GetStk(), amx_.GetHea());
break;
case AMX_ERR_STACKLOW:
Printf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_.GetStk(), amx_.GetStp());
break;
case AMX_ERR_HEAPLOW:
Printf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_.GetHea(), amx_.GetHlw());
break;
case AMX_ERR_INVINSTR: {
cell opcode = *(reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()));
Printf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_.GetCip());
break;
}
case AMX_ERR_NATIVE: {
const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip());
cell opcode = *(ip - 2);
if (opcode == kOpSysreqC) {
cell index = *(ip - 1);
Printf(" %s", amx_.GetNativeName(index));
}
break;
}
}
}
void CrashDetect::DieOrContinue() {
if (die_on_error_) {
Printf("Aborting...");
std::exit(EXIT_FAILURE);
}
}
|
// Copyright (c) 2011-2013 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY 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 <cassert>
#include <cstdarg>
#include <cstdlib>
#include <list>
#include <map>
#include <stack>
#include <string>
#include <amx/amx.h>
#include <amx/amxaux.h>
#include "amxdebuginfo.h"
#include "amxerror.h"
#include "amxpathfinder.h"
#include "amxscript.h"
#include "amxstacktrace.h"
#include "compiler.h"
#include "configreader.h"
#include "crashdetect.h"
#include "fileutils.h"
#include "logprintf.h"
#include "npcall.h"
#include "os.h"
#include "stacktrace.h"
#define AMX_EXEC_GDK (-10)
static const int kOpBounds = 121;
static const int kOpSysreqC = 123;
std::stack<NPCall*> CrashDetect::np_calls_;
bool CrashDetect::error_detected_ = false;
// static
void CrashDetect::OnException(void *context) {
if (!np_calls_.empty()) {
CrashDetect::Get(np_calls_.top()->amx())->HandleException();
} else {
Printf("Server crashed due to an unknown error");
}
PrintSystemBacktrace(context);
}
// static
void CrashDetect::OnInterrupt(void *context) {
if (!np_calls_.empty()) {
CrashDetect::Get(np_calls_.top()->amx())->HandleInterrupt();
} else {
Printf("Server received interrupt signal");
}
PrintSystemBacktrace(context);
}
// static
void CrashDetect::PrintAmxBacktrace() {
if (np_calls_.empty()) {
return;
}
AMXScript topAmx = np_calls_.top()->amx();
cell frm = topAmx.GetFrm();
cell cip = topAmx.GetCip();
int level = 0;
if (cip == 0) {
return;
}
Printf("AMX backtrace:");
std::stack<NPCall*> np_calls = np_calls_;
while (!np_calls.empty() && cip != 0) {
const NPCall *call = np_calls.top();
AMXScript amx = call->amx();
// We don't trace calls across AMX bounds i.e. outside of top-level
// function's AMX instance.
if (amx != topAmx) {
assert(level != 0);
break;
}
if (call->IsNative()) {
AMX_NATIVE address = reinterpret_cast<AMX_NATIVE>(amx.GetNativeAddr(call->index()));
if (address != 0) {
std::string module = fileutils::GetFileName(os::GetModulePathFromAddr((void*)address));
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
const char *name = amx.GetNativeName(call->index());
if (name != 0) {
Printf("#%d native %s () [%08x]%s", level++, name, address, from.c_str());
}
}
} else if (call->IsPublic()) {
AMXDebugInfo &debug_info = CrashDetect::Get(amx)->debug_info_;
amx.PushStack(cip); // push return address
amx.PushStack(frm); // push frame pointer
std::list<AMXStackFrame> frames;
{
AMXStackTrace trace(amx, amx.GetStk(), &debug_info);
do {
AMXStackFrame frame = trace.GetFrame();
if (frame) {
frames.push_back(frame);
} else {
break;
}
} while (trace.Next());
}
frm = amx.PopStack(); // pop frame pointer
cip = amx.PopStack(); // pop return address
if (frames.empty()) {
ucell ep_addr = amx.GetPublicAddr(call->index());
frames.push_front(AMXStackFrame(amx, frm, 0, ep_addr, &debug_info));
} else {
if (!debug_info.IsLoaded()) {
AMXStackFrame &bottom = frames.back();
bottom = AMXStackFrame(amx,
bottom.GetFrameAddr(),
bottom.GetRetAddr(),
amx.GetPublicAddr(call->index()),
&debug_info);
}
}
std::string &amx_name = CrashDetect::Get(amx)->amx_name_;
for (std::list<AMXStackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator)
{
std::string from = " from " + amx_name;
if (amx_name.empty() || debug_info.IsLoaded()) {
from.clear();
}
Printf("#%d %s%s", level++, iterator->AsString().c_str(), from.c_str());
}
frm = call->frm();
cip = call->cip();
}
np_calls.pop();
}
}
// static
void CrashDetect::PrintSystemBacktrace(void *context) {
Printf("System backtrace:");
int level = 0;
StackTrace trace(context);
std::deque<StackFrame> frames = trace.GetFrames();
for (std::deque<StackFrame>::const_iterator iterator = frames.begin();
iterator != frames.end(); ++iterator) {
const StackFrame &frame = *iterator;
std::string module = os::GetModulePathFromAddr(frame.GetRetAddr());
std::string from = " from " + module;
if (module.empty()) {
from.clear();
}
Printf("#%d %s%s", level++, frame.AsString().c_str(), from.c_str());
}
}
// static
void CrashDetect::Printf(const char *format, ...) {
std::va_list va;
va_start(va, format);
std::string new_format;
new_format.append("[debug] ");
new_format.append(format);
vlogprintf(new_format.c_str(), va);
va_end(va);
}
CrashDetect::CrashDetect(AMX *amx)
: AMXService<CrashDetect>(amx)
, amx_(amx)
, prev_callback_(0)
, die_on_error_(false)
, run_on_error_("")
{
ConfigReader server_cfg("server.cfg");
die_on_error_ = server_cfg.GetOption("die_on_error", false);
run_on_error_ = server_cfg.GetOption("run_on_error", std::string());
}
int CrashDetect::Load() {
AMXPathFinder pathFinder;
pathFinder.AddSearchPath("gamemodes");
pathFinder.AddSearchPath("filterscripts");
// Read a list of additional search paths from AMX_PATH.
const char *AMX_PATH = getenv("AMX_PATH");
if (AMX_PATH != 0) {
std::string var(AMX_PATH);
std::string path;
std::string::size_type begin = 0;
while (begin < var.length()) {
std::string::size_type end = var.find(fileutils::kNativePathListSepChar, begin);
if (end == std::string::npos) {
end = var.length();
}
path.assign(var.begin() + begin, var.begin() + end);
if (!path.empty()) {
pathFinder.AddSearchPath(path);
}
begin = end + 1;
}
}
amx_path_ = pathFinder.FindAMX(this->amx());
amx_name_ = fileutils::GetFileName(amx_path_);
if (!amx_path_.empty() && AMXDebugInfo::IsPresent(this->amx())) {
debug_info_.Load(amx_path_);
}
amx_.DisableSysreqD();
prev_callback_ = amx_.GetCallback();
return AMX_ERR_NONE;
}
int CrashDetect::Unload() {
return AMX_ERR_NONE;
}
int CrashDetect::DoAmxCallback(cell index, cell *result, cell *params) {
NPCall call = NPCall::Native(amx(), index);
np_calls_.push(&call);
int error = prev_callback_(amx(), index, result, params);
np_calls_.pop();
return error;
}
int CrashDetect::DoAmxExec(cell *retval, int index) {
NPCall call = NPCall::Public(amx(), index);
np_calls_.push(&call);
int error = ::amx_Exec(amx(), retval, index);
if (error != AMX_ERR_NONE && !error_detected_) {
HandleExecError(index, error);
} else {
error_detected_ = false;
}
np_calls_.pop();
return error;
}
void CrashDetect::HandleExecError(int index, const AMXError &error) {
CrashDetect::error_detected_ = true;
if (error.code() == AMX_ERR_INDEX && index == AMX_EXEC_GDK) {
return;
}
PrintError(error);
if (error.code() != AMX_ERR_NOTFOUND &&
error.code() != AMX_ERR_INDEX &&
error.code() != AMX_ERR_CALLBACK &&
error.code() != AMX_ERR_INIT)
{
PrintAmxBacktrace();
}
if (!run_on_error_.empty()) {
std::system(run_on_error_.c_str());
}
DieOrContinue();
}
void CrashDetect::HandleException() {
Printf("Server crashed while executing %s", amx_name_.c_str());
PrintAmxBacktrace();
}
void CrashDetect::HandleInterrupt() {
Printf("Server received interrupt signal while executing %s", amx_name_.c_str());
PrintAmxBacktrace();
}
void CrashDetect::PrintError(const AMXError &error) const {
Printf("Run time error %d: \"%s\"", error.code(), error.GetString());
switch (error.code()) {
case AMX_ERR_BOUNDS: {
const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip());
cell opcode = *ip;
if (opcode == kOpBounds) {
cell bound = *(ip + 1);
cell index = amx_.GetPri();
if (index < 0) {
Printf(" Accessing element at negative index %d", index);
} else {
Printf(" Accessing element at index %d past array upper bound %d", index, bound);
}
}
break;
}
case AMX_ERR_NOTFOUND: {
const AMX_FUNCSTUBNT *natives = amx_.GetNatives();
int num_natives = amx_.GetNumNatives();
for (int i = 0; i < num_natives; ++i) {
if (natives[i].address == 0) {
Printf(" %s", amx_.GetName(natives[i].nameofs));
}
}
break;
}
case AMX_ERR_STACKERR:
Printf(" Stack pointer (STK) is 0x%X, heap pointer (HEA) is 0x%X", amx_.GetStk(), amx_.GetHea());
break;
case AMX_ERR_STACKLOW:
Printf(" Stack pointer (STK) is 0x%X, stack top (STP) is 0x%X", amx_.GetStk(), amx_.GetStp());
break;
case AMX_ERR_HEAPLOW:
Printf(" Heap pointer (HEA) is 0x%X, heap bottom (HLW) is 0x%X", amx_.GetHea(), amx_.GetHlw());
break;
case AMX_ERR_INVINSTR: {
cell opcode = *(reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip()));
Printf(" Unknown opcode 0x%x at address 0x%08X", opcode , amx_.GetCip());
break;
}
case AMX_ERR_NATIVE: {
const cell *ip = reinterpret_cast<const cell*>(amx_.GetCode() + amx_.GetCip());
cell opcode = *(ip - 2);
if (opcode == kOpSysreqC) {
cell index = *(ip - 1);
Printf(" %s", amx_.GetNativeName(index));
}
break;
}
}
}
void CrashDetect::DieOrContinue() {
if (die_on_error_) {
Printf("Aborting...");
std::exit(EXIT_FAILURE);
}
}
|
Remove extra colon
|
Remove extra colon
|
C++
|
bsd-2-clause
|
Zeex/samp-plugin-crashdetect,Zeex/samp-plugin-crashdetect,Zeex/samp-plugin-crashdetect
|
9482846c35566fd2d151c2b6fa9fb891a86de8d9
|
src/watchdogd.hpp
|
src/watchdogd.hpp
|
#ifndef WATCHDOGD_H
#define WATCHDOGD_H
#define _XOPEN_SOURCE 700
#define _FILE_OFFSET_BITS 64
#define PREFER_PORTABLE_SNPRINTF
#define HAVE_SNPRINTF
#include <atomic>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <clocale>
#include <config.h>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <libconfig.h>
#include <libgen.h>
#include <oping.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <syslog.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <zlib.h>
#include "snprintf.hpp"
#include "watchdog.hpp"
#include "linux.hpp"
#include "watchdog.hpp"
#ifndef NSIG
#if defined(_NSIG)
#define NSIG _NSIG /* For BSD/SysV */
#elif defined(_SIGMAX)
#define NSIG (_SIGMAX + 1) /* For QNX */
#elif defined(SIGMAX)
#define NSIG (SIGMAX + 1) /* For djgpp */
#else
#define NSIG 64 /* Use a reasonable default value */
#endif
#endif
#include "list.hpp"
#if defined __cplusplus
#define restrict
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
#define SOFTBOOT 0x1
#define SYNC 0x2
#define USEPIDFILE 0x4
#define ENABLEPING 0x8
#define KEXEC 0x10
#define DAEMONIZE 0x20
#define ENABLEPIDCHECKER 0x40
#define FORCE 0x80
#define NOACTION 0x100
#define REALTIME 0x200
#define VERBOSE 0x400
#define IDENTIFY 0x800
#define BUSYBOXDEVOPTCOMPAT 0x1000
#define LOGLVLSETCMDLN 0x2000
#define SCRIPTFAILED 0x1
#define FORKFAILED 0x2
#define OUTOFMEMORY 0x4
#define LOADAVGTOOHIGH 0x8
#define UNKNOWNPIDFILERROR 0x10
#define PIDFILERROR 0x20
#define PINGFAILED 0x40
#define NETWORKDOWN 0x80
//TODO: Split this struct into an options struct(values read in from config file) and a runtime struct.
struct cfgoptions {
cfgoptions() {
};
config_t cfg = {0};
double maxLoadFifteen = 0.0;
double maxLoadOne = 0.0;
double maxLoadFive = 0.0;
double retryLimit = 0.0;
const config_setting_t *ipAddresses = NULL;
const config_setting_t *networkInterfaces = NULL;
pingobj_t *pingObj = NULL;
const config_setting_t *pidFiles = NULL;
const char *devicepath = NULL;
const char *pidfileName = NULL;
const char *testexepath = "/etc/watchdog.d";
const char *exepathname = NULL;
const char *testexepathname = NULL;
const char *confile = "/etc/watchdogd.conf";
unsigned long options = 0;
const char *logTarget = NULL;
const char *logUpto = NULL;
time_t sleeptime = -1;
unsigned long minfreepages = 0;
const char *randomSeedPath = NULL;
int testBinTimeout = 60;
int repairBinTimeout = 60;
int sigtermDelay = 0;
int priority;
int watchdogTimeout = -1;
int testExeReturnValue = 0;
long loopExit = -1;
int allocatableMemory = 0;
volatile std::atomic_uint error = {0};
bool haveConfigFile = false;
};
struct ProcessList {
struct list head;
};
typedef struct ProcessList ProcessList;
struct spawnattr_t {
char *workingDirectory;
const char *repairFilePathname;
char *execStart;
char *user;
char *group;
int timeout;
int nice;
mode_t umask;
bool noNewPrivileges;
bool hasUmask;
};
struct repaircmd_t {
spawnattr_t * spawnattr;
char retString[32];
struct list entry;
const char *path;
int ret;
std::atomic_bool mode;
};
struct dbusinfo
{
cfgoptions **config;
Watchdog **wdt;
pid_t childPid;
int fd;
};
struct identinfo {
char name[128];
char deviceName[128];
char daemonVersion[8];
long unsigned flags;
long timeout;
long firmwareVersion;
};
struct dev {
char name[64];
unsigned long minor;
unsigned long major;
};
extern ProcessList processes;
enum logTarget_t {
INVALID_LOG_TARGET,
STANDARD_ERROR,
SYSTEM_LOG,
FILE_APPEND,
FILE_NEW,
};
#endif
|
#ifndef WATCHDOGD_H
#define WATCHDOGD_H
#define _XOPEN_SOURCE 700
#define _FILE_OFFSET_BITS 64
#define PREFER_PORTABLE_SNPRINTF
#define HAVE_SNPRINTF
#include <atomic>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cinttypes>
#include <climits>
#include <clocale>
#include <config.h>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <grp.h>
#include <libconfig.h>
#include <libgen.h>
#include <oping.h>
#include <pthread.h>
#include <pwd.h>
#include <sched.h>
#include <syslog.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <zlib.h>
#include "snprintf.hpp"
#include "watchdog.hpp"
#include "linux.hpp"
#include "watchdog.hpp"
#ifndef NSIG
#if defined(_NSIG)
#define NSIG _NSIG /* For BSD/SysV */
#elif defined(_SIGMAX)
#define NSIG (_SIGMAX + 1) /* For QNX */
#elif defined(SIGMAX)
#define NSIG (SIGMAX + 1) /* For djgpp */
#else
#define NSIG 64 /* Use a reasonable default value */
#endif
#endif
#include "list.hpp"
#if defined __cplusplus
#define restrict
#endif
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
#define SOFTBOOT 0x1
#define SYNC 0x2
#define USEPIDFILE 0x4
#define ENABLEPING 0x8
#define KEXEC 0x10
#define DAEMONIZE 0x20
#define ENABLEPIDCHECKER 0x40
#define FORCE 0x80
#define NOACTION 0x100
#define REALTIME 0x200
#define VERBOSE 0x400
#define IDENTIFY 0x800
#define BUSYBOXDEVOPTCOMPAT 0x1000
#define LOGLVLSETCMDLN 0x2000
#define SCRIPTFAILED 0x1
#define FORKFAILED 0x2
#define OUTOFMEMORY 0x4
#define LOADAVGTOOHIGH 0x8
#define UNKNOWNPIDFILERROR 0x10
#define PIDFILERROR 0x20
#define PINGFAILED 0x40
#define NETWORKDOWN 0x80
//TODO: Split this struct into an options struct(values read in from config file) and a runtime struct.
struct cfgoptions {
cfgoptions() {
};
config_t cfg = {0};
double maxLoadFifteen = 0.0;
double maxLoadOne = 0.0;
double maxLoadFive = 0.0;
double retryLimit = 0.0;
const config_setting_t *ipAddresses = NULL;
const config_setting_t *networkInterfaces = NULL;
pingobj_t *pingObj = NULL;
const config_setting_t *pidFiles = NULL;
const char *devicepath = NULL;
const char *pidfileName = NULL;
const char *testexepath = "/etc/watchdog.d";
const char *exepathname = NULL;
const char *testexepathname = NULL;
const char *confile = "/etc/watchdogd.conf";
unsigned long options = 0;
const char *logTarget = NULL;
const char *logUpto = NULL;
time_t sleeptime = -1;
unsigned long minfreepages = 0;
const char *randomSeedPath = NULL;
int testBinTimeout = 60;
int repairBinTimeout = 60;
int sigtermDelay = 0;
int priority;
int watchdogTimeout = -1;
int testExeReturnValue = 0;
long loopExit = -1;
int allocatableMemory = 0;
volatile std::atomic_uint error = {0};
bool haveConfigFile = false;
};
struct ProcessList {
struct list head;
};
typedef struct ProcessList ProcessList;
struct spawnattr_t {
char *workingDirectory;
const char *repairFilePathname;
char *execStart;
char *user;
char *group;
int timeout;
int nice;
mode_t umask;
bool noNewPrivileges;
bool hasUmask;
};
struct repaircmd_t {
spawnattr_t * spawnattr;
const char *path;
char retString[8];
struct list entry;
int ret;
std::atomic_bool mode;
};
struct dbusinfo
{
cfgoptions **config;
Watchdog **wdt;
pid_t childPid;
int fd;
};
struct identinfo {
char name[128];
char deviceName[128];
char daemonVersion[8];
long unsigned flags;
long timeout;
long firmwareVersion;
};
struct dev {
char name[64];
unsigned long minor;
unsigned long major;
};
extern ProcessList processes;
enum logTarget_t {
INVALID_LOG_TARGET,
STANDARD_ERROR,
SYSTEM_LOG,
FILE_APPEND,
FILE_NEW,
};
#endif
|
reduce memory usage
|
reduce memory usage
|
C++
|
apache-2.0
|
clockley/watchdogd,clockley/watchdogd
|
0ac7725e11d573a3bfad0ea4f5632ca6c0b38318
|
engine/components/other/spherecollision/spherecollisioncomponent.cpp
|
engine/components/other/spherecollision/spherecollisioncomponent.cpp
|
/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "spherecollisioncomponent.h"
#include "gameobject.h"
#include "game.h"
#include "scene.h"
#include <core/debughelper.h>
REGISTER_OBJECTTYPE( GluonEngine, SphereCollisionComponent )
using namespace GluonEngine;
class SphereCollisionComponent::SphereCollisionComponentPrivate
{
public:
SphereCollisionComponentPrivate() :
collisionGroup( 0 ),
radius( 1.0f ),
collides( 0 )
{
}
int collisionGroup;
float radius;
GameObject* collides;
int componentType;
const char* typeName;
QVector<Component*> collisionComponents;
};
SphereCollisionComponent::SphereCollisionComponent( QObject* parent )
: Component( parent )
, d( new SphereCollisionComponentPrivate )
{
d->componentType = qMetaTypeId<GluonEngine::SphereCollisionComponent*>();
d->typeName = staticMetaObject.className();
}
SphereCollisionComponent::~SphereCollisionComponent()
{
delete d;
}
QString SphereCollisionComponent::category() const
{
return QString( "Physics" );
}
void SphereCollisionComponent::start()
{
d->collisionComponents = gameObject()->parentGameObject()->findComponentsInChildrenByType( d->componentType ).toVector();
foreach( Component * component, d->collisionComponents )
{
connect( component, SIGNAL( destroyed( QObject* ) ), SLOT( componentDestroyed( QObject* ) ) );
static_cast<SphereCollisionComponent*>( component )->addComponent( this );
}
}
void SphereCollisionComponent::update( int elapsedMilliseconds )
{
Q_UNUSED( elapsedMilliseconds )
d->collides = 0;
//Our position
QVector3D position = gameObject()->position();
//Eliminate the Z-axis
position.setZ( 0 );
//Our radius, squared
float radius = d->radius * d->radius;
//Walk through the list
const int componentCount = d->collisionComponents.count();
Component** data = d->collisionComponents.data();
for( int i = 0; i < componentCount; ++i )
{
Component* component = data[i];
//Intentional pointer-to-pointer comparison. Way faster compared to string comparison.
if( component->metaObject()->className() != d->typeName )
continue;
SphereCollisionComponent* sphere = static_cast< SphereCollisionComponent* >( component );
if( sphere && sphere != this )
{
//See if we are in the same group
if( sphere->collisionGroup() == d->collisionGroup )
{
//Get the object's position
QVector3D otherPosition = component->gameObject()->position();
//Eliminate the Z axis
position.setZ( 0 );
//Get the object's radius
float otherRadius = sphere->radius();
//Calculate the distance between our position and theirs
//Note that this is the squared distance to avoid a costly squareroot op
float dist = ( otherPosition - position ).lengthSquared();
//If the distance between the two positions is smaller then the radius, we
//have a collision.
if( dist < ( otherRadius + radius ) )
{
d->collides = component->gameObject();
}
}
}
}
}
void SphereCollisionComponent::stop()
{
}
int SphereCollisionComponent::collisionGroup() const
{
return d->collisionGroup;
}
float SphereCollisionComponent::radius() const
{
return d->radius;
}
bool SphereCollisionComponent::isColliding() const
{
return d->collides != 0;
}
QObject* SphereCollisionComponent::collidesWith() const
{
return d->collides;
}
void SphereCollisionComponent::setCollisionGroup( int group )
{
d->collisionGroup = group;
}
void SphereCollisionComponent::setRadius( float radius )
{
d->radius = radius;
}
void SphereCollisionComponent::componentDestroyed( QObject* obj )
{
if( !obj )
return;
Component* comp = static_cast<Component*>( obj );
if( d->collisionComponents.contains( comp ) )
d->collisionComponents.remove( d->collisionComponents.indexOf( comp ) );
}
void SphereCollisionComponent::addComponent( SphereCollisionComponent* comp )
{
if( comp )
{
if( !d->collisionComponents.contains( comp ) )
{
d->collisionComponents.append( comp );
connect( comp, SIGNAL( destroyed( QObject* ) ), this, SLOT( componentDestroyed( QObject* ) ) );
}
}
}
Q_EXPORT_PLUGIN2( gluon_component_spherecollision, GluonEngine::SphereCollisionComponent )
#include "spherecollisioncomponent.moc"
|
/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "spherecollisioncomponent.h"
#include "gameobject.h"
#include "game.h"
#include "scene.h"
#include <core/debughelper.h>
REGISTER_OBJECTTYPE( GluonEngine, SphereCollisionComponent )
using namespace GluonEngine;
class SphereCollisionComponent::SphereCollisionComponentPrivate
{
public:
SphereCollisionComponentPrivate() :
collisionGroup( 0 ),
radius( 1.0f ),
collides( 0 )
{
}
int collisionGroup;
float radius;
GameObject* collides;
int componentType;
const char* typeName;
QVector<Component*> collisionComponents;
};
SphereCollisionComponent::SphereCollisionComponent( QObject* parent )
: Component( parent )
, d( new SphereCollisionComponentPrivate )
{
d->componentType = qMetaTypeId<GluonEngine::SphereCollisionComponent*>();
}
SphereCollisionComponent::~SphereCollisionComponent()
{
delete d;
}
QString SphereCollisionComponent::category() const
{
return QString( "Physics" );
}
void SphereCollisionComponent::start()
{
d->collisionComponents = gameObject()->scene()->sceneContents()->findComponentsInChildrenByType( d->componentType ).toVector();
foreach( Component * component, d->collisionComponents )
{
connect( component, SIGNAL( destroyed( QObject* ) ), SLOT( componentDestroyed( QObject* ) ) );
static_cast<SphereCollisionComponent*>( component )->addComponent( this );
}
}
void SphereCollisionComponent::update( int elapsedMilliseconds )
{
Q_UNUSED( elapsedMilliseconds )
d->collides = 0;
//Our position
QVector3D position = gameObject()->position();
//Eliminate the Z-axis
position.setZ( 0 );
//Our radius, squared
float radius = d->radius * d->radius;
//Walk through the list
const int componentCount = d->collisionComponents.count();
Component** data = d->collisionComponents.data();
for( int i = 0; i < componentCount; ++i )
{
SphereCollisionComponent* sphere = qobject_cast< SphereCollisionComponent* >( data[i] );
if( sphere && sphere != this )
{
//See if we are in the same group
if( sphere->collisionGroup() == d->collisionGroup )
{
//Get the object's position
QVector3D otherPosition = component->gameObject()->position();
//Eliminate the Z axis
position.setZ( 0 );
//Get the object's radius
float otherRadius = sphere->radius();
//Calculate the distance between our position and theirs
//Note that this is the squared distance to avoid a costly squareroot op
float dist = ( otherPosition - position ).lengthSquared();
//If the distance between the two positions is smaller then the radius, we
//have a collision.
if( dist < ( otherRadius + radius ) )
{
d->collides = component->gameObject();
}
}
}
}
}
void SphereCollisionComponent::stop()
{
}
int SphereCollisionComponent::collisionGroup() const
{
return d->collisionGroup;
}
float SphereCollisionComponent::radius() const
{
return d->radius;
}
bool SphereCollisionComponent::isColliding() const
{
return d->collides != 0;
}
QObject* SphereCollisionComponent::collidesWith() const
{
return d->collides;
}
void SphereCollisionComponent::setCollisionGroup( int group )
{
d->collisionGroup = group;
}
void SphereCollisionComponent::setRadius( float radius )
{
d->radius = radius;
}
void SphereCollisionComponent::componentDestroyed( QObject* obj )
{
if( !obj )
return;
Component* comp = static_cast<Component*>( obj );
if( d->collisionComponents.contains( comp ) )
d->collisionComponents.remove( d->collisionComponents.indexOf( comp ) );
}
void SphereCollisionComponent::addComponent( SphereCollisionComponent* comp )
{
if( comp )
{
if( !d->collisionComponents.contains( comp ) )
{
d->collisionComponents.append( comp );
connect( comp, SIGNAL( destroyed( QObject* ) ), this, SLOT( componentDestroyed( QObject* ) ) );
}
}
}
Q_EXPORT_PLUGIN2( gluon_component_spherecollision, GluonEngine::SphereCollisionComponent )
#include "spherecollisioncomponent.moc"
|
Use the proper types in SphereCollisionComponent.
|
Engine: Use the proper types in SphereCollisionComponent.
|
C++
|
lgpl-2.1
|
KDE/gluon,pranavrc/example-gluon,pranavrc/example-gluon,pranavrc/example-gluon,KDE/gluon,KDE/gluon,pranavrc/example-gluon,KDE/gluon
|
b82b226cc9924dc927017ce0b926d26054a0300d
|
src/System.cpp
|
src/System.cpp
|
#include "nil.h"
#include "nilUtil.h"
#include "nilLogitech.h"
namespace Nil {
System::System( HINSTANCE instance, HWND window, const Cooperation coop,
SystemListener* listener ): mCooperation( coop ),
mWindow( window ), mInstance( instance ), mDirectInput( nullptr ),
mMonitor( nullptr ), mIDPool( 0 ), mInitializing( true ),
mHIDManager( nullptr ), mLogitechGKeys( nullptr ), mLogitechLEDs( nullptr ),
mListener( listener ), mMouseIndexPool( 0 ), mKeyboardIndexPool( 0 ),
mControllerIndexPool( 0 ), mXInput( nullptr )
{
assert( mListener );
// Validate the passes window handle
if ( !IsWindow( mWindow ) )
NIL_EXCEPT( "Window handle is invalid" );
mLogitechGKeys = new Logitech::GKeySDK();
mLogitechLEDs = new Logitech::LedSDK();
mXInput = new XInput();
if ( mXInput->initialize() != ExternalModule::Initialization_OK )
NIL_EXCEPT( "Loading XInput failed" );
// Create DirectInput instance
auto hr = DirectInput8Create( mInstance, DIRECTINPUT_VERSION,
IID_IDirectInput8W, (LPVOID*)&mDirectInput, NULL );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not instantiate DirectInput 8" );
// Initialize our event monitor
mMonitor = new EventMonitor( mInstance, mCooperation );
// Initialize our HID manager
mHIDManager = new HIDManager();
// Register the HID manager and ourselves as PnP event listeners
mMonitor->registerPnPListener( mHIDManager );
mMonitor->registerPnPListener( this );
// Register ourselves as a raw event listener
mMonitor->registerRawListener( this );
// Fetch initial devices
initializeDevices();
refreshDevices();
// Update the monitor once, to receive initial Raw devices
mMonitor->update();
mInitializing = false;
}
DeviceID System::getNextID()
{
return mIDPool++;
}
void System::onPnPPlug( const GUID& deviceClass, const wideString& devicePath )
{
// Refresh all currently connected devices,
// since IDirectInput8::FindDevice doesn't do jack shit
refreshDevices();
}
void System::onPnPUnplug( const GUID& deviceClass, const wideString& devicePath )
{
// Refresh all currently connected devices,
// since IDirectInput8::FindDevice doesn't do jack shit
refreshDevices();
}
void System::onRawArrival( HANDLE handle )
{
UINT pathLength = 0;
if ( GetRawInputDeviceInfoW( handle, RIDI_DEVICENAME, NULL, &pathLength ) )
NIL_EXCEPT_WINAPI( "GetRawInputDeviceInfoW failed" );
wideString rawPath( pathLength, '\0' );
GetRawInputDeviceInfoW( handle, RIDI_DEVICENAME, &rawPath[0], &pathLength );
rawPath.resize( rawPath.length() - 1 );
for ( auto device : mDevices )
{
if ( device->getHandler() != Device::Handler_RawInput )
continue;
auto rawDevice = static_cast<RawInputDevice*>( device );
if ( !_wcsicmp( rawDevice->getRawPath().c_str(), rawPath.c_str() ) )
{
deviceConnect( rawDevice );
return;
}
}
auto device = new RawInputDevice( this, getNextID(), handle, rawPath );
if ( isInitializing() )
device->setStatus( Device::Status_Connected );
else
deviceConnect( device );
mDevices.push_back( device );
}
void System::onRawMouseInput( HANDLE handle,
const RAWMOUSE& input, const bool sinked )
{
if ( mInitializing || !handle )
return;
auto it = mMouseMapping.find( handle );
if ( it != mMouseMapping.end() )
it->second->onRawInput( input );
}
void System::onRawKeyboardInput( HANDLE handle,
const RAWKEYBOARD& input, const bool sinked )
{
if ( mInitializing || !handle )
return;
auto it = mKeyboardMapping.find( handle );
if ( it != mKeyboardMapping.end() )
it->second->onRawInput( input );
}
void System::onRawRemoval( HANDLE handle )
{
for ( auto device : mDevices )
{
if ( device->getHandler() != Device::Handler_RawInput )
continue;
auto rawDevice = static_cast<RawInputDevice*>( device );
if ( rawDevice->getRawHandle() == handle )
{
deviceDisconnect( rawDevice );
return;
}
}
}
void System::mapMouse( HANDLE handle, RawInputMouse* mouse )
{
mMouseMapping[handle] = mouse;
}
void System::unmapMouse( HANDLE handle )
{
mMouseMapping.erase( handle );
}
void System::mapKeyboard( HANDLE handle, RawInputKeyboard* keyboard )
{
mKeyboardMapping[handle] = keyboard;
}
void System::unmapKeyboard( HANDLE handle )
{
mKeyboardMapping.erase( handle );
}
void System::initializeDevices()
{
mXInputIDs.resize( XUSER_MAX_COUNT );
for ( int i = 0; i < XUSER_MAX_COUNT; i++ )
{
mXInputIDs[i] = getNextID();
auto device = new XInputDevice( this, mXInputIDs[i], i );
mDevices.push_back( device );
}
}
void System::refreshDevices()
{
identifyXInputDevices();
for ( Device* device : mDevices )
if ( device->getHandler() == Device::Handler_DirectInput )
{
device->saveStatus();
device->setStatus( Device::Status_Pending );
}
auto hr = mDirectInput->EnumDevices( DI8DEVCLASS_GAMECTRL,
diDeviceEnumCallback, this, DIEDFL_ATTACHEDONLY );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not enumerate DirectInput devices!" );
for ( Device* device : mDevices )
if ( device->getHandler() == Device::Handler_DirectInput
&& device->getSavedStatus() == Device::Status_Connected
&& device->getStatus() == Device::Status_Pending )
deviceDisconnect( device );
XINPUT_STATE state;
for ( Device* device : mDevices )
{
if ( device->getHandler() == Device::Handler_XInput )
{
auto xDevice = static_cast<XInputDevice*>( device );
auto status = mXInput->mFunctions.pfnXInputGetState( xDevice->getXInputID(), &state );
if ( status == ERROR_DEVICE_NOT_CONNECTED )
{
if ( xDevice->getStatus() == Device::Status_Connected )
deviceDisconnect( xDevice );
else if ( xDevice->getStatus() == Device::Status_Pending )
xDevice->setStatus( Device::Status_Disconnected );
}
else if ( status == ERROR_SUCCESS )
{
if ( xDevice->getStatus() == Device::Status_Disconnected )
deviceConnect( xDevice );
else if ( xDevice->getStatus() == Device::Status_Pending )
xDevice->setStatus( Device::Status_Connected );
}
else
NIL_EXCEPT( "XInputGetState failed" );
}
}
}
BOOL CALLBACK System::diDeviceEnumCallback( LPCDIDEVICEINSTANCEW instance,
LPVOID referer )
{
auto system = reinterpret_cast<System*>( referer );
for ( auto identifier : system->mXInputDeviceIDs )
if ( instance->guidProduct.Data1 == identifier )
return DIENUM_CONTINUE;
for ( auto device : system->mDevices )
{
if ( device->getHandler() != Device::Handler_DirectInput )
continue;
auto diDevice = static_cast<DirectInputDevice*>( device );
if ( diDevice->getInstanceID() == instance->guidInstance )
{
if ( device->getSavedStatus() == Device::Status_Disconnected )
system->deviceConnect( device );
else
device->setStatus( Device::Status_Connected );
return DIENUM_CONTINUE;
}
}
Device* device = new DirectInputDevice( system, system->getNextID(), instance );
if ( system->isInitializing() )
device->setStatus( Device::Status_Connected );
else
system->deviceConnect( device );
system->mDevices.push_back( device );
return DIENUM_CONTINUE;
}
void System::deviceConnect( Device* device )
{
device->onConnect();
mListener->onDeviceConnected( device );
}
void System::deviceDisconnect( Device* device )
{
device->onDisconnect();
mListener->onDeviceDisconnected( device );
}
void System::mouseEnabled( Device* device, Mouse* instance )
{
mListener->onMouseEnabled( device, instance );
}
void System::mouseDisabled( Device* device, Mouse* instance )
{
mListener->onMouseDisabled( device, instance );
}
void System::keyboardEnabled( Device* device, Keyboard* instance )
{
mListener->onKeyboardEnabled( device, instance );
}
void System::keyboardDisabled( Device* device, Keyboard* instance )
{
mListener->onKeyboardDisabled( device, instance );
}
void System::controllerEnabled( Device* device, Controller* instance )
{
mListener->onControllerEnabled( device, instance );
}
void System::controllerDisabled( Device* device, Controller* instance )
{
mListener->onControllerDisabled( device, instance );
}
void System::identifyXInputDevices()
{
mXInputDeviceIDs.clear();
for ( auto hidRecord : mHIDManager->getRecords() )
if ( hidRecord->isXInput() )
mXInputDeviceIDs.push_back( hidRecord->getIdentifier() );
}
DeviceList& System::getDevices()
{
return mDevices;
}
const bool System::isInitializing() const
{
return mInitializing;
}
int System::getNextMouseIndex()
{
return ++mMouseIndexPool;
}
int System::getNextKeyboardIndex()
{
return ++mKeyboardIndexPool;
}
int System::getNextControllerIndex()
{
return ++mControllerIndexPool;
}
void System::update()
{
// Run PnP & raw events if there are any
mMonitor->update();
// Make sure that we disconnect failed devices,
// and update the rest
for ( Device* device : mDevices )
if ( device->isDisconnectFlagged() )
deviceDisconnect( device );
else
device->update();
// Run queued G-key events if using the SDK
if ( mLogitechGKeys->isInitialized() )
mLogitechGKeys->update();
}
Logitech::GKeySDK* System::getLogitechGKeys()
{
return mLogitechGKeys;
}
Logitech::LedSDK* System::getLogitechLEDs()
{
return mLogitechLEDs;
}
XInput* System::getXInput()
{
return mXInput;
}
System::~System()
{
for ( Device* device : mDevices )
delete device;
SAFE_DELETE( mHIDManager );
SAFE_DELETE( mMonitor );
SAFE_RELEASE( mDirectInput );
SAFE_DELETE( mLogitechLEDs );
SAFE_DELETE( mLogitechGKeys );
}
}
|
#include "nil.h"
#include "nilUtil.h"
#include "nilLogitech.h"
namespace Nil {
System::System( HINSTANCE instance, HWND window, const Cooperation coop,
SystemListener* listener ): mCooperation( coop ),
mWindow( window ), mInstance( instance ), mDirectInput( nullptr ),
mMonitor( nullptr ), mIDPool( 0 ), mInitializing( true ),
mHIDManager( nullptr ), mLogitechGKeys( nullptr ), mLogitechLEDs( nullptr ),
mListener( listener ), mMouseIndexPool( 0 ), mKeyboardIndexPool( 0 ),
mControllerIndexPool( 0 ), mXInput( nullptr )
{
assert( mListener );
// Validate the passes window handle
if ( !IsWindow( mWindow ) )
NIL_EXCEPT( "Window handle is invalid" );
mLogitechGKeys = new Logitech::GKeySDK();
mLogitechLEDs = new Logitech::LedSDK();
mXInput = new XInput();
if ( mXInput->initialize() != ExternalModule::Initialization_OK )
NIL_EXCEPT( "Loading XInput failed" );
// Create DirectInput instance
auto hr = DirectInput8Create( mInstance, DIRECTINPUT_VERSION,
IID_IDirectInput8W, (LPVOID*)&mDirectInput, NULL );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not instantiate DirectInput 8" );
// Initialize our event monitor
mMonitor = new EventMonitor( mInstance, mCooperation );
// Initialize our HID manager
mHIDManager = new HIDManager();
// Register the HID manager and ourselves as PnP event listeners
mMonitor->registerPnPListener( mHIDManager );
mMonitor->registerPnPListener( this );
// Register ourselves as a raw event listener
mMonitor->registerRawListener( this );
// Fetch initial devices
initializeDevices();
refreshDevices();
// Update the monitor once, to receive initial Raw devices
mMonitor->update();
mInitializing = false;
}
DeviceID System::getNextID()
{
return mIDPool++;
}
void System::onPnPPlug( const GUID& deviceClass, const wideString& devicePath )
{
// Refresh all currently connected devices,
// since IDirectInput8::FindDevice doesn't do jack shit
refreshDevices();
}
void System::onPnPUnplug( const GUID& deviceClass, const wideString& devicePath )
{
// Refresh all currently connected devices,
// since IDirectInput8::FindDevice doesn't do jack shit
refreshDevices();
}
void System::onRawArrival( HANDLE handle )
{
UINT pathLength = 0;
if ( GetRawInputDeviceInfoW( handle, RIDI_DEVICENAME, NULL, &pathLength ) )
NIL_EXCEPT_WINAPI( "GetRawInputDeviceInfoW failed" );
wideString rawPath( pathLength, '\0' );
GetRawInputDeviceInfoW( handle, RIDI_DEVICENAME, &rawPath[0], &pathLength );
rawPath.resize( rawPath.length() - 1 );
for ( auto device : mDevices )
{
if ( device->getHandler() != Device::Handler_RawInput )
continue;
auto rawDevice = static_cast<RawInputDevice*>( device );
if ( !_wcsicmp( rawDevice->getRawPath().c_str(), rawPath.c_str() ) )
{
deviceConnect( rawDevice );
return;
}
}
auto device = new RawInputDevice( this, getNextID(), handle, rawPath );
if ( isInitializing() )
device->setStatus( Device::Status_Connected );
else
deviceConnect( device );
mDevices.push_back( device );
}
void System::onRawMouseInput( HANDLE handle,
const RAWMOUSE& input, const bool sinked )
{
if ( mInitializing || !handle )
return;
auto it = mMouseMapping.find( handle );
if ( it != mMouseMapping.end() )
it->second->onRawInput( input );
}
void System::onRawKeyboardInput( HANDLE handle,
const RAWKEYBOARD& input, const bool sinked )
{
if ( mInitializing || !handle )
return;
auto it = mKeyboardMapping.find( handle );
if ( it != mKeyboardMapping.end() )
it->second->onRawInput( input );
}
void System::onRawRemoval( HANDLE handle )
{
for ( auto device : mDevices )
{
if ( device->getHandler() != Device::Handler_RawInput )
continue;
auto rawDevice = static_cast<RawInputDevice*>( device );
if ( rawDevice->getRawHandle() == handle )
{
deviceDisconnect( rawDevice );
return;
}
}
}
void System::mapMouse( HANDLE handle, RawInputMouse* mouse )
{
mMouseMapping[handle] = mouse;
}
void System::unmapMouse( HANDLE handle )
{
mMouseMapping.erase( handle );
}
void System::mapKeyboard( HANDLE handle, RawInputKeyboard* keyboard )
{
mKeyboardMapping[handle] = keyboard;
}
void System::unmapKeyboard( HANDLE handle )
{
mKeyboardMapping.erase( handle );
}
void System::initializeDevices()
{
mXInputIDs.resize( XUSER_MAX_COUNT );
for ( int i = 0; i < XUSER_MAX_COUNT; i++ )
{
mXInputIDs[i] = getNextID();
auto device = new XInputDevice( this, mXInputIDs[i], i );
mDevices.push_back( device );
}
}
void System::refreshDevices()
{
identifyXInputDevices();
for ( Device* device : mDevices )
if ( device->getHandler() == Device::Handler_DirectInput )
{
device->saveStatus();
device->setStatus( Device::Status_Pending );
}
auto hr = mDirectInput->EnumDevices( DI8DEVCLASS_GAMECTRL,
diDeviceEnumCallback, this, DIEDFL_ATTACHEDONLY );
if ( FAILED( hr ) )
NIL_EXCEPT_DINPUT( hr, "Could not enumerate DirectInput devices!" );
for ( Device* device : mDevices )
if ( device->getHandler() == Device::Handler_DirectInput
&& device->getSavedStatus() == Device::Status_Connected
&& device->getStatus() == Device::Status_Pending )
deviceDisconnect( device );
XINPUT_STATE state;
for ( Device* device : mDevices )
{
if ( device->getHandler() == Device::Handler_XInput )
{
auto xDevice = static_cast<XInputDevice*>( device );
auto status = mXInput->mFunctions.pfnXInputGetState( xDevice->getXInputID(), &state );
if ( status == ERROR_DEVICE_NOT_CONNECTED )
{
if ( xDevice->getStatus() == Device::Status_Connected )
deviceDisconnect( xDevice );
else if ( xDevice->getStatus() == Device::Status_Pending )
xDevice->setStatus( Device::Status_Disconnected );
}
else if ( status == ERROR_SUCCESS )
{
if ( xDevice->getStatus() == Device::Status_Disconnected )
deviceConnect( xDevice );
else if ( xDevice->getStatus() == Device::Status_Pending )
xDevice->setStatus( Device::Status_Connected );
}
else
NIL_EXCEPT( "XInputGetState failed" );
}
}
}
BOOL CALLBACK System::diDeviceEnumCallback( LPCDIDEVICEINSTANCEW instance,
LPVOID referer )
{
auto system = reinterpret_cast<System*>( referer );
for ( auto identifier : system->mXInputDeviceIDs )
if ( instance->guidProduct.Data1 == identifier )
return DIENUM_CONTINUE;
for ( auto device : system->mDevices )
{
if ( device->getHandler() != Device::Handler_DirectInput )
continue;
auto diDevice = static_cast<DirectInputDevice*>( device );
if ( diDevice->getInstanceID() == instance->guidInstance )
{
if ( device->getSavedStatus() == Device::Status_Disconnected )
system->deviceConnect( device );
else
device->setStatus( Device::Status_Connected );
return DIENUM_CONTINUE;
}
}
Device* device = new DirectInputDevice( system, system->getNextID(), instance );
if ( system->isInitializing() )
device->setStatus( Device::Status_Connected );
else
system->deviceConnect( device );
system->mDevices.push_back( device );
return DIENUM_CONTINUE;
}
void System::deviceConnect( Device* device )
{
device->onConnect();
mListener->onDeviceConnected( device );
}
void System::deviceDisconnect( Device* device )
{
device->onDisconnect();
mListener->onDeviceDisconnected( device );
}
void System::mouseEnabled( Device* device, Mouse* instance )
{
mListener->onMouseEnabled( device, instance );
}
void System::mouseDisabled( Device* device, Mouse* instance )
{
mListener->onMouseDisabled( device, instance );
}
void System::keyboardEnabled( Device* device, Keyboard* instance )
{
mListener->onKeyboardEnabled( device, instance );
}
void System::keyboardDisabled( Device* device, Keyboard* instance )
{
mListener->onKeyboardDisabled( device, instance );
}
void System::controllerEnabled( Device* device, Controller* instance )
{
mListener->onControllerEnabled( device, instance );
}
void System::controllerDisabled( Device* device, Controller* instance )
{
mListener->onControllerDisabled( device, instance );
}
void System::identifyXInputDevices()
{
mXInputDeviceIDs.clear();
for ( auto hidRecord : mHIDManager->getRecords() )
if ( hidRecord->isXInput() )
mXInputDeviceIDs.push_back( hidRecord->getIdentifier() );
}
DeviceList& System::getDevices()
{
return mDevices;
}
const bool System::isInitializing() const
{
return mInitializing;
}
int System::getNextMouseIndex()
{
return ++mMouseIndexPool;
}
int System::getNextKeyboardIndex()
{
return ++mKeyboardIndexPool;
}
int System::getNextControllerIndex()
{
return ++mControllerIndexPool;
}
void System::update()
{
// Run PnP & raw events if there are any
mMonitor->update();
// Make sure that we disconnect failed devices,
// and update the rest
for ( Device* device : mDevices )
if ( device->isDisconnectFlagged() )
deviceDisconnect( device );
else
device->update();
// Run queued G-key events if using the SDK
if ( mLogitechGKeys->isInitialized() )
mLogitechGKeys->update();
}
Logitech::GKeySDK* System::getLogitechGKeys()
{
return mLogitechGKeys;
}
Logitech::LedSDK* System::getLogitechLEDs()
{
return mLogitechLEDs;
}
XInput* System::getXInput()
{
return mXInput;
}
System::~System()
{
for ( Device* device : mDevices )
delete device;
SAFE_DELETE( mHIDManager );
SAFE_DELETE( mMonitor );
SAFE_RELEASE( mDirectInput );
SAFE_DELETE( mLogitechLEDs );
SAFE_DELETE( mLogitechGKeys );
SAFE_DELETE( mXInput );
}
}
|
Fix a bug where the XInput ExternalModule wasn't being freed by System
|
Fix a bug where the XInput ExternalModule wasn't being freed by System
|
C++
|
mit
|
noorus/nil,noorus/nil
|
c921d47c1704836c3dabae5abb16fdd1ce9ba018
|
src/hip_event.cpp
|
src/hip_event.cpp
|
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hip_runtime.h"
#include "hcc_detail/hip_hcc.h"
#include "hcc_detail/trace_helper.h"
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Events
//---
hipError_t ihipEventCreate(hipEvent_t* event, unsigned flags)
{
hipError_t e = hipSuccess;
// TODO - support hipEventDefault, hipEventBlockingSync, hipEventDisableTiming
if (flags == 0) {
ihipEvent_t *eh = event->_handle = new ihipEvent_t();
eh->_state = hipEventStatusCreated;
eh->_stream = NULL;
eh->_flags = flags;
eh->_timestamp = 0;
eh->_copy_seq_id = 0;
} else {
e = hipErrorInvalidValue;
}
return e;
}
/**
* @warning : flags must be 0.
*/
hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags)
{
HIP_INIT_API(event, flags);
return ihipLogStatus(ihipEventCreate(event, flags));
}
hipError_t hipEventCreate(hipEvent_t* event)
{
HIP_INIT_API(event);
return ihipLogStatus(ihipEventCreate(event, 0));
}
//---
hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
if (eh && eh->_state != hipEventStatusUnitialized) {
eh->_stream = stream;
if (stream == NULL) {
// If stream == NULL, wait on all queues.
// This matches behavior described in CUDA 7 RT APIs, which say that "This function uses standard default stream semantics".
// TODO-HCC fix this - is CUDA this conservative or still uses device timestamps?
// TODO-HCC can we use barrier or event marker to implement better solution?
ihipDevice_t *device = ihipGetTlsDefaultDevice();
device->locked_syncDefaultStream(true);
eh->_timestamp = hc::get_system_ticks();
eh->_state = hipEventStatusRecorded;
return ihipLogStatus(hipSuccess);
} else {
eh->_state = hipEventStatusRecording;
// Clear timestamps
eh->_timestamp = 0;
eh->_marker = stream->_av.create_marker();
eh->_copy_seq_id = stream->locked_lastCopySeqId();
return ihipLogStatus(hipSuccess);
}
} else {
return ihipLogStatus(hipErrorInvalidResourceHandle);
}
}
//---
hipError_t hipEventDestroy(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
event._handle->_state = hipEventStatusUnitialized;
delete event._handle;
event._handle = NULL;
// TODO - examine return additional error codes
return ihipLogStatus(hipSuccess);
}
//---
hipError_t hipEventSynchronize(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
if (eh) {
if (eh->_state == hipEventStatusUnitialized) {
return ihipLogStatus(hipErrorInvalidResourceHandle);
} else if (eh->_state == hipEventStatusCreated ) {
// Created but not actually recorded on any device:
return ihipLogStatus(hipSuccess);
} else if (eh->_stream == NULL) {
ihipDevice_t *device = ihipGetTlsDefaultDevice();
device->locked_syncDefaultStream(true);
return ihipLogStatus(hipSuccess);
} else {
#if __hcc_workweek__ >= 16033
eh->_marker.wait((eh->_flags & hipEventBlockingSync) ? hc::hcWaitModeBlocked : hc::hcWaitModeActive);
#else
eh->_marker.wait();
#endif
eh->_stream->locked_reclaimSignals(eh->_copy_seq_id);
return ihipLogStatus(hipSuccess);
}
} else {
return ihipLogStatus(hipErrorInvalidResourceHandle);
}
}
//---
hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *start_eh = start._handle;
ihipEvent_t *stop_eh = stop._handle;
ihipSetTs(start);
ihipSetTs(stop);
hipError_t status = hipSuccess;
*ms = 0.0f;
if (start_eh && stop_eh) {
if ((start_eh->_state == hipEventStatusRecorded) && (stop_eh->_state == hipEventStatusRecorded)) {
// Common case, we have good information for both events.
int64_t tickDiff = (stop_eh->_timestamp - start_eh->_timestamp);
// TODO-move this to a variable saved with each agent.
uint64_t freqHz;
hsa_system_get_info(HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY, &freqHz);
if (freqHz) {
*ms = ((double)(tickDiff) / (double)(freqHz)) * 1000.0f;
status = hipSuccess;
} else {
* ms = 0.0f;
status = hipErrorInvalidValue;
}
} else if ((start_eh->_state == hipEventStatusRecording) ||
(stop_eh->_state == hipEventStatusRecording)) {
status = hipErrorNotReady;
} else if ((start_eh->_state == hipEventStatusUnitialized) ||
(stop_eh->_state == hipEventStatusUnitialized)) {
status = hipErrorInvalidResourceHandle;
}
}
return ihipLogStatus(status);
}
//---
hipError_t hipEventQuery(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
// TODO-stream - need to read state of signal here: The event may have become ready after recording..
// TODO-HCC - use get_hsa_signal here.
if (eh->_state == hipEventStatusRecording) {
return ihipLogStatus(hipErrorNotReady);
} else {
return ihipLogStatus(hipSuccess);
}
}
|
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR
IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hip_runtime.h"
#include "hcc_detail/hip_hcc.h"
#include "hcc_detail/trace_helper.h"
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Events
//---
hipError_t ihipEventCreate(hipEvent_t* event, unsigned flags)
{
hipError_t e = hipSuccess;
// TODO - support hipEventDefault, hipEventBlockingSync, hipEventDisableTiming
if (flags == 0) {
ihipEvent_t *eh = event->_handle = new ihipEvent_t();
eh->_state = hipEventStatusCreated;
eh->_stream = NULL;
eh->_flags = flags;
eh->_timestamp = 0;
eh->_copy_seq_id = 0;
} else {
e = hipErrorInvalidValue;
}
return e;
}
/**
* @warning : flags must be 0.
*/
hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags)
{
HIP_INIT_API(event, flags);
return ihipLogStatus(ihipEventCreate(event, flags));
}
hipError_t hipEventCreate(hipEvent_t* event)
{
HIP_INIT_API(event);
return ihipLogStatus(ihipEventCreate(event, 0));
}
//---
hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
if (eh && eh->_state != hipEventStatusUnitialized) {
eh->_stream = stream;
if (stream == NULL) {
// If stream == NULL, wait on all queues.
// TODO-HCC fix this - is this conservative or still uses device timestamps?
// TODO-HCC can we use barrier or event marker to implement better solution?
ihipDevice_t *device = ihipGetTlsDefaultDevice();
device->locked_syncDefaultStream(true);
eh->_timestamp = hc::get_system_ticks();
eh->_state = hipEventStatusRecorded;
return ihipLogStatus(hipSuccess);
} else {
eh->_state = hipEventStatusRecording;
// Clear timestamps
eh->_timestamp = 0;
eh->_marker = stream->_av.create_marker();
eh->_copy_seq_id = stream->locked_lastCopySeqId();
return ihipLogStatus(hipSuccess);
}
} else {
return ihipLogStatus(hipErrorInvalidResourceHandle);
}
}
//---
hipError_t hipEventDestroy(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
event._handle->_state = hipEventStatusUnitialized;
delete event._handle;
event._handle = NULL;
// TODO - examine return additional error codes
return ihipLogStatus(hipSuccess);
}
//---
hipError_t hipEventSynchronize(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
if (eh) {
if (eh->_state == hipEventStatusUnitialized) {
return ihipLogStatus(hipErrorInvalidResourceHandle);
} else if (eh->_state == hipEventStatusCreated ) {
// Created but not actually recorded on any device:
return ihipLogStatus(hipSuccess);
} else if (eh->_stream == NULL) {
ihipDevice_t *device = ihipGetTlsDefaultDevice();
device->locked_syncDefaultStream(true);
return ihipLogStatus(hipSuccess);
} else {
#if __hcc_workweek__ >= 16033
eh->_marker.wait((eh->_flags & hipEventBlockingSync) ? hc::hcWaitModeBlocked : hc::hcWaitModeActive);
#else
eh->_marker.wait();
#endif
eh->_stream->locked_reclaimSignals(eh->_copy_seq_id);
return ihipLogStatus(hipSuccess);
}
} else {
return ihipLogStatus(hipErrorInvalidResourceHandle);
}
}
//---
hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *start_eh = start._handle;
ihipEvent_t *stop_eh = stop._handle;
ihipSetTs(start);
ihipSetTs(stop);
hipError_t status = hipSuccess;
*ms = 0.0f;
if (start_eh && stop_eh) {
if ((start_eh->_state == hipEventStatusRecorded) && (stop_eh->_state == hipEventStatusRecorded)) {
// Common case, we have good information for both events.
int64_t tickDiff = (stop_eh->_timestamp - start_eh->_timestamp);
// TODO-move this to a variable saved with each agent.
uint64_t freqHz;
hsa_system_get_info(HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY, &freqHz);
if (freqHz) {
*ms = ((double)(tickDiff) / (double)(freqHz)) * 1000.0f;
status = hipSuccess;
} else {
* ms = 0.0f;
status = hipErrorInvalidValue;
}
} else if ((start_eh->_state == hipEventStatusRecording) ||
(stop_eh->_state == hipEventStatusRecording)) {
status = hipErrorNotReady;
} else if ((start_eh->_state == hipEventStatusUnitialized) ||
(stop_eh->_state == hipEventStatusUnitialized)) {
status = hipErrorInvalidResourceHandle;
}
}
return ihipLogStatus(status);
}
//---
hipError_t hipEventQuery(hipEvent_t event)
{
std::call_once(hip_initialized, ihipInit);
ihipEvent_t *eh = event._handle;
// TODO-stream - need to read state of signal here: The event may have become ready after recording..
// TODO-HCC - use get_hsa_signal here.
if (eh->_state == hipEventStatusRecording) {
return ihipLogStatus(hipErrorNotReady);
} else {
return ihipLogStatus(hipSuccess);
}
}
|
comment change
|
comment change
|
C++
|
mit
|
ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP
|
d3447d791683e2dfdb04189da95454a1e3abc331
|
src/httpclient.cc
|
src/httpclient.cc
|
#include "httpclient.h"
#include "logger.h"
/*****************************************************************************/
/**
* \par Description:
* A writeback handler for the curl library. I handles writing response
* data from curl into a string.
* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
*
*/
static size_t writeString(void* contents, size_t size, size_t nmemb,
void* userp) {
// append the writeback data to the provided string
(static_cast<std::string*>(userp))->append((char*)contents, size * nmemb);
// return size of written data
return size * nmemb;
}
static size_t writeFile(void* contents, size_t size, size_t nmemb, FILE* fp) {
size_t written = fwrite(contents, size, nmemb, fp);
return written;
}
HttpClient::HttpClient() {
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
// let curl use our write function
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeString);
if (loggerGetSeverity() <= LVL_debug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
}
}
HttpClient::~HttpClient() { curl_easy_cleanup(curl); }
bool HttpClient::authenticate(const AuthConfig& conf) {
CURL* curl_auth = curl_easy_duphandle(curl);
std::string auth_url = conf.server + "/token";
curl_easy_setopt(curl_auth, CURLOPT_URL, auth_url.c_str());
// let curl put the username and password using HTTP basic authentication
curl_easy_setopt(curl_auth, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
curl_easy_setopt(curl_auth, CURLOPT_POSTFIELDS,
"grant_type=client_credentials");
// compose username and password
std::string auth_header = conf.client_id + ":" + conf.client_secret;
// forward username and password to curl
curl_easy_setopt(curl_auth, CURLOPT_USERPWD, auth_header.c_str());
LOGGER_LOG(LVL_debug,
"servercon - requesting token from server: " << conf.server);
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&response);
CURLcode result = curl_easy_perform(curl_auth);
curl_easy_cleanup(curl_auth);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "authentication curl error: "
<< result << " with server: " << conf.server
<< "and auth header: " << auth_header)
return false;
}
Json::Reader reader;
Json::Value json;
reader.parse(response, json);
token = json["access_token"].asString();
token_type = json["token_type"].asString();
std::string header = "Authorization: Bearer " + token;
curl_slist* headers = NULL;
headers = curl_slist_append(headers, header.c_str());
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
return true;
}
Json::Value HttpClient::get(const std::string& url) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
return perform(curl);
}
Json::Value HttpClient::post(const std::string& url, const std::string& data) {
CURL* curl_post = curl_easy_duphandle(curl);
curl_easy_setopt(curl_post, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_post, CURLOPT_POSTFIELDS, data.c_str());
Json::Value result = perform(curl_post);
curl_easy_cleanup(curl_post);
return result;
}
Json::Value HttpClient::perform(CURL* curl_handler) {
Json::Value json;
std::string response;
curl_easy_setopt(curl_handler, CURLOPT_WRITEDATA, (void*)&response);
CURLcode result = curl_easy_perform(curl);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl error: " << result);
return json;
}
long http_code = 0;
curl_easy_getinfo(curl_handler, CURLINFO_RESPONSE_CODE, &http_code);
Json::Reader reader;
reader.parse(response, json);
return json;
}
bool HttpClient::download(const std::string& url, const std::string& filename) {
CURL* curl_redirect = curl_easy_duphandle(curl);
curl_easy_setopt(curl_redirect, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_redirect, CURLOPT_FOLLOWLOCATION, 1L);
unsigned char* redirect_url =
new unsigned char[1000]; /**< buffer for redirect link */
curl_easy_perform(curl_redirect);
CURLcode result =
curl_easy_getinfo(curl_redirect, CURLINFO_EFFECTIVE_URL, &redirect_url);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl redirect error: " << result
<< " with url: " << url);
return false;
}
CURL* curl_download = curl_easy_init();
curl_easy_setopt(curl_download, CURLOPT_WRITEFUNCTION, writeFile);
FILE* fp = fopen(filename.c_str(), "w");
curl_easy_setopt(curl_download, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl_download, CURLOPT_URL, redirect_url);
result = curl_easy_perform(curl_download);
curl_easy_cleanup(curl_download);
delete redirect_url;
fclose(fp);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl download error: " << result);
return false;
}
return true;
}
|
#include "httpclient.h"
#include "logger.h"
/*****************************************************************************/
/**
* \par Description:
* A writeback handler for the curl library. I handles writing response
* data from curl into a string.
* https://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
*
*/
static size_t writeString(void* contents, size_t size, size_t nmemb,
void* userp) {
// append the writeback data to the provided string
(static_cast<std::string*>(userp))->append((char*)contents, size * nmemb);
// return size of written data
return size * nmemb;
}
static size_t writeFile(void* contents, size_t size, size_t nmemb, FILE* fp) {
size_t written = fwrite(contents, size, nmemb, fp);
return written;
}
HttpClient::HttpClient() {
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
// let curl use our write function
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeString);
if (loggerGetSeverity() <= LVL_debug) {
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
}
}
HttpClient::~HttpClient() { curl_easy_cleanup(curl); }
bool HttpClient::authenticate(const AuthConfig& conf) {
CURL* curl_auth = curl_easy_duphandle(curl);
std::string auth_url = conf.server + "/token";
curl_easy_setopt(curl_auth, CURLOPT_URL, auth_url.c_str());
// let curl put the username and password using HTTP basic authentication
curl_easy_setopt(curl_auth, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
curl_easy_setopt(curl_auth, CURLOPT_POSTFIELDS,
"grant_type=client_credentials");
// compose username and password
std::string auth_header = conf.client_id + ":" + conf.client_secret;
// forward username and password to curl
curl_easy_setopt(curl_auth, CURLOPT_USERPWD, auth_header.c_str());
LOGGER_LOG(LVL_debug,
"servercon - requesting token from server: " << conf.server);
std::string response;
curl_easy_setopt(curl_auth, CURLOPT_WRITEDATA, (void*)&response);
CURLcode result = curl_easy_perform(curl_auth);
curl_easy_cleanup(curl_auth);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "authentication curl error: "
<< result << " with server: " << conf.server
<< "and auth header: " << auth_header)
return false;
}
Json::Reader reader;
Json::Value json;
reader.parse(response, json);
token = json["access_token"].asString();
token_type = json["token_type"].asString();
std::string header = "Authorization: Bearer " + token;
curl_slist* headers = NULL;
headers = curl_slist_append(headers, header.c_str());
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
return true;
}
Json::Value HttpClient::get(const std::string& url) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
return perform(curl);
}
Json::Value HttpClient::post(const std::string& url, const std::string& data) {
CURL* curl_post = curl_easy_duphandle(curl);
curl_easy_setopt(curl_post, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_post, CURLOPT_POSTFIELDS, data.c_str());
Json::Value result = perform(curl_post);
curl_easy_cleanup(curl_post);
return result;
}
Json::Value HttpClient::perform(CURL* curl_handler) {
Json::Value json;
std::string response;
curl_easy_setopt(curl_handler, CURLOPT_WRITEDATA, (void*)&response);
CURLcode result = curl_easy_perform(curl);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl error: " << result);
return json;
}
long http_code = 0;
curl_easy_getinfo(curl_handler, CURLINFO_RESPONSE_CODE, &http_code);
Json::Reader reader;
reader.parse(response, json);
return json;
}
bool HttpClient::download(const std::string& url, const std::string& filename) {
CURL* curl_redirect = curl_easy_duphandle(curl);
curl_easy_setopt(curl_redirect, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl_redirect, CURLOPT_FOLLOWLOCATION, 1L);
unsigned char* redirect_url =
new unsigned char[1000]; /**< buffer for redirect link */
curl_easy_perform(curl_redirect);
CURLcode result =
curl_easy_getinfo(curl_redirect, CURLINFO_EFFECTIVE_URL, &redirect_url);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl redirect error: " << result
<< " with url: " << url);
return false;
}
CURL* curl_download = curl_easy_init();
curl_easy_setopt(curl_download, CURLOPT_WRITEFUNCTION, writeFile);
FILE* fp = fopen(filename.c_str(), "w");
curl_easy_setopt(curl_download, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl_download, CURLOPT_URL, redirect_url);
result = curl_easy_perform(curl_download);
curl_easy_cleanup(curl_download);
delete redirect_url;
fclose(fp);
if (result != CURLE_OK) {
LOGGER_LOG(LVL_error, "curl download error: " << result);
return false;
}
return true;
}
|
Attach CURLOPT_WRITEDATA to correct curl handle
|
Attach CURLOPT_WRITEDATA to correct curl handle
|
C++
|
mpl-2.0
|
advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/aktualizr,advancedtelematic/sota_client_cpp,advancedtelematic/sota_client_cpp,advancedtelematic/aktualizr
|
a54993897668439bee71d47b5ed0004b6f5f3f31
|
src/UITask.cpp
|
src/UITask.cpp
|
#include "Common.h"
#include "UITask.h"
#include "WinUtil.h"
// TODO(kjk): can I avoid this struct wrapper?
struct UITask {
UITask(const std::function<void()> f) : f(f) {}
const std::function<void()> f;
};
namespace uitask {
static HWND gTaskDispatchHwnd = NULL;
#define WM_EXECUTE_TASK (WM_USER + 1)
static LRESULT CALLBACK WndProcTaskDispatch(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
UITask *task;
if (WM_EXECUTE_TASK == msg) {
task = (UITask *)lParam;
task->f();
delete task;
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void Initialize() {
const WCHAR *uiTaskClassName = L"UITask_Wnd_Class";
const WCHAR *uiTaskWindowName = L"UITask Dispatch Window";
WNDCLASSEX wcex;
FillWndClassEx(wcex, uiTaskClassName, WndProcTaskDispatch);
RegisterClassEx(&wcex);
CrashIf(gTaskDispatchHwnd);
gTaskDispatchHwnd = CreateWindow(uiTaskClassName, uiTaskWindowName, WS_OVERLAPPED, 0, 0, 0, 0,
HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
}
void DrainQueue() {
CrashIf(!gTaskDispatchHwnd);
MSG msg;
while (PeekMessage(&msg, gTaskDispatchHwnd, WM_EXECUTE_TASK, WM_EXECUTE_TASK, PM_REMOVE)) {
DispatchMessage(&msg);
}
}
void Destroy() {
DrainQueue();
DestroyWindow(gTaskDispatchHwnd);
gTaskDispatchHwnd = NULL;
}
void Post(const std::function<void()> &f) {
auto task = new UITask(f);
// task->f = f;
PostMessage(gTaskDispatchHwnd, WM_EXECUTE_TASK, 0, (LPARAM)task);
}
}
|
#include "Common.h"
#include "UITask.h"
#include "WinUtil.h"
// TODO(kjk): can I avoid this struct wrapper?
struct UITask {
UITask(const std::function<void()> f) : f(f) {}
const std::function<void()> f;
};
namespace uitask {
static HWND gTaskDispatchHwnd = NULL;
#define WM_EXECUTE_TASK (WM_USER + 1)
static LRESULT CALLBACK WndProcTaskDispatch(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
UITask *task;
if (WM_EXECUTE_TASK == msg) {
task = (UITask *)lParam;
task->f();
delete task;
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
void Initialize() {
const WCHAR *uiTaskClassName = L"UITask_Wnd_Class";
const WCHAR *uiTaskWindowName = L"UITask Dispatch Window";
WNDCLASSEX wcex;
FillWndClassEx(wcex, uiTaskClassName, WndProcTaskDispatch);
RegisterClassEx(&wcex);
CrashIf(gTaskDispatchHwnd);
gTaskDispatchHwnd = CreateWindow(uiTaskClassName, uiTaskWindowName, WS_OVERLAPPED, 0, 0, 0, 0,
HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
}
void DrainQueue() {
CrashIf(!gTaskDispatchHwnd);
MSG msg;
while (PeekMessage(&msg, gTaskDispatchHwnd, WM_EXECUTE_TASK, WM_EXECUTE_TASK, PM_REMOVE)) {
DispatchMessage(&msg);
}
}
void Destroy() {
DrainQueue();
DestroyWindow(gTaskDispatchHwnd);
gTaskDispatchHwnd = NULL;
}
void Post(const std::function<void()> &f) {
auto task = new UITask(f);
PostMessage(gTaskDispatchHwnd, WM_EXECUTE_TASK, 0, (LPARAM)task);
}
}
|
remove comment
|
remove comment
|
C++
|
bsd-3-clause
|
vehar/velociraptor8,vehar/velociraptor8,vehar/velociraptor8,vehar/velociraptor8,vehar/velociraptor8,vehar/velociraptor8
|
75daf34f0156b0c8e4d6a90d3ac32f53c34a125a
|
examples/fractal.cpp
|
examples/fractal.cpp
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is an example application that uses Marl to parallize the calculation of
// a Julia fractal.
#include <marl/defer.h>
#include <marl/scheduler.h>
#include <marl/thread.h>
#include <marl/waitgroup.h>
#include <fstream>
#include <math.h>
#include <stdint.h>
// A color formed from a red, green and blue component.
template <typename T>
struct Color
{
T r, g, b;
inline Color<T>& operator += (const Color<T>& rhs)
{
r += rhs.r; g += rhs.g; b += rhs.b;
return *this;
}
inline Color<T>& operator /= (T rhs)
{
r /= rhs; g /= rhs; b /= rhs;
return *this;
}
};
// colorize returns a 'rainbow-color' for the scalar v.
inline Color<float> colorize(float v)
{
constexpr float PI = 3.141592653589793f;
constexpr float PI_2_THIRDS = 2.0f * PI / 3.0f;
return Color<float>{
0.5f + 0.5f * cosf(v + 0 * PI_2_THIRDS),
0.5f + 0.5f * cosf(v + 1 * PI_2_THIRDS),
0.5f + 0.5f * cosf(v + 2 * PI_2_THIRDS),
};
}
// lerp returns the linear interpolation between min and max using the weight x.
inline float lerp(float x, float min, float max)
{
return min + x * (max - min);
}
// julia calculates the Julia-set fractal value for the given coordinate and
// constant. See https://en.wikipedia.org/wiki/Julia_set for more information.
Color<float> julia(float x, float y, float cx, float cy)
{
int iteration = 0;
for (int i = 0; i < 1000; i++)
{
if (x * x + y * y > 4)
{
return colorize(sqrt(i));
}
auto xtemp = x * x - y * y;
y = 2 * x * y + cy;
x = xtemp + cx;
}
return {};
}
// writeBMP writes the given image as a bitmap to the given file, returning
// true on success and false on error.
bool writeBMP(const Color<uint8_t>* texels, int width, int height, const char* path)
{
auto file = fopen(path, "wb");
if (!file)
{
fprintf(stderr, "Could not open file '%s'\n", path);
return false;
}
defer(fclose(file));
bool ok = true;
auto put4 = [&](uint32_t val) { ok = ok && fwrite(&val, 1, 4, file) == 4; };
auto put2 = [&](uint16_t val) { ok = ok && fwrite(&val, 1, 2, file) == 2; };
auto put1 = [&](uint8_t val) { ok = ok && fwrite(&val, 1, 1, file) == 1; };
const uint32_t padding = -(3 * width) & 3U; // in bytes
const uint32_t stride = 3 * width + padding; // in bytes
const uint32_t offset = 54;
const uint32_t size = offset + stride * height * 3;
// Bitmap file header
put1('B'); // header field
put1('M');
put4(offset + stride * height * 3); // size in bytes
put4(0); // reserved
put4(offset);
// BITMAPINFOHEADER
put4(40); // size of header in bytes
put4(width); // width in pixels
put4(height); // height in pixels
put2(1); // number of color planes
put2(24); // bits per pixel
put4(0); // compression scheme (none)
put4(0); // size
put4(72); // horizontal resolution
put4(72); // vertical resolution
put4(0); // color pallete size
put4(0); // 'important colors' count
for (int y = height - 1; y >= 0; y--)
{
for (int x = 0; x < width; x++)
{
auto &texel = texels[x + y * width];
put1(texel.b);
put1(texel.g);
put1(texel.r);
}
for (int i = 0; i < padding; i++)
{
put1(0);
}
}
return ok;
}
// Constants used for rendering the fractal.
constexpr uint32_t imageWidth = 2048;
constexpr uint32_t imageHeight = 2048;
constexpr int samplesPerPixel = 8;
constexpr float windowMinX = -0.5f;
constexpr float windowMaxX = +0.5f;
constexpr float windowMinY = -0.5f;
constexpr float windowMaxY = +0.5f;
constexpr float cx = -0.8f;
constexpr float cy = 0.156f;
int main(int argc, const char** argv)
{
// Create a marl scheduler using the full number of logical cpus.
// Bind this scheduler to the main thread so we can call marl::schedule()
marl::Scheduler scheduler;
scheduler.setWorkerThreadCount(marl::Thread::numLogicalCPUs());
scheduler.bind();
defer(scheduler.unbind()); // unbind before destructing the scheduler.
// Allocate the image.
auto pixels = new Color<uint8_t>[imageWidth * imageHeight];
defer(delete [] pixels); // free memory before returning.
// Create a wait group that will be used to synchronize the tasks.
// The wait group is constructed with an initial count of imageHeight as
// there will be a total of imageHeight tasks.
marl::WaitGroup wg(imageHeight);
// For each line of the image...
for (int y = 0; y < imageHeight; y++) {
// Schedule a task to calculate the image for this line.
// These may run concurrently across hardware threads.
marl::schedule([=] {
// Before this task returns, decrement the wait group counter.
// This is used to indicate that the task is done.
defer(wg.done());
for (int x = 0; x < imageWidth; x++) {
// Calculate the fractal pixel color.
Color<float> color = {};
for (int sample = 0; sample < samplesPerPixel; sample++)
{
auto fx = float(x) + (rand() / float(RAND_MAX));
auto fy = float(y) + (rand() / float(RAND_MAX));
auto dx = float(fx) / float(imageWidth);
auto dy = float(fy) / float(imageHeight);
color += julia(lerp(dx, windowMinX, windowMaxX), lerp(dy, windowMinY, windowMaxY), cx, cy);
}
color /= samplesPerPixel;
pixels[x + y * imageWidth] = {
static_cast<uint8_t>(color.r * 255),
static_cast<uint8_t>(color.g * 255),
static_cast<uint8_t>(color.b * 255)
};
}
});
}
// Wait until all image lines have been calculated.
wg.wait();
// Write the image to "fractal.bmp".
if (!writeBMP(pixels, imageWidth, imageHeight, "fractal.bmp")) { return 1; }
// All done.
return 0;
}
|
// Copyright 2019 The Marl 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This is an example application that uses Marl to parallize the calculation of
// a Julia fractal.
#include <marl/defer.h>
#include <marl/scheduler.h>
#include <marl/thread.h>
#include <marl/waitgroup.h>
#include <fstream>
#include <math.h>
#include <stdint.h>
// A color formed from a red, green and blue component.
template <typename T>
struct Color
{
T r, g, b;
inline Color<T>& operator += (const Color<T>& rhs)
{
r += rhs.r; g += rhs.g; b += rhs.b;
return *this;
}
inline Color<T>& operator /= (T rhs)
{
r /= rhs; g /= rhs; b /= rhs;
return *this;
}
};
// colorize returns a 'rainbow-color' for the scalar v.
inline Color<float> colorize(float v)
{
constexpr float PI = 3.141592653589793f;
constexpr float PI_2_THIRDS = 2.0f * PI / 3.0f;
return Color<float>{
0.5f + 0.5f * cosf(v + 0 * PI_2_THIRDS),
0.5f + 0.5f * cosf(v + 1 * PI_2_THIRDS),
0.5f + 0.5f * cosf(v + 2 * PI_2_THIRDS),
};
}
// lerp returns the linear interpolation between min and max using the weight x.
inline float lerp(float x, float min, float max)
{
return min + x * (max - min);
}
// julia calculates the Julia-set fractal value for the given coordinate and
// constant. See https://en.wikipedia.org/wiki/Julia_set for more information.
Color<float> julia(float x, float y, float cx, float cy)
{
int iteration = 0;
for (int i = 0; i < 1000; i++)
{
if (x * x + y * y > 4)
{
return colorize(sqrt(i));
}
auto xtemp = x * x - y * y;
y = 2 * x * y + cy;
x = xtemp + cx;
}
return {};
}
// writeBMP writes the given image as a bitmap to the given file, returning
// true on success and false on error.
bool writeBMP(const Color<uint8_t>* texels, int width, int height, const char* path)
{
auto file = fopen(path, "wb");
if (!file)
{
fprintf(stderr, "Could not open file '%s'\n", path);
return false;
}
defer(fclose(file));
bool ok = true;
auto put4 = [&](uint32_t val) { ok = ok && fwrite(&val, 1, 4, file) == 4; };
auto put2 = [&](uint16_t val) { ok = ok && fwrite(&val, 1, 2, file) == 2; };
auto put1 = [&](uint8_t val) { ok = ok && fwrite(&val, 1, 1, file) == 1; };
const uint32_t padding = -(3 * width) & 3U; // in bytes
const uint32_t stride = 3 * width + padding; // in bytes
const uint32_t offset = 54;
const uint32_t size = offset + stride * height * 3;
// Bitmap file header
put1('B'); // header field
put1('M');
put4(offset + stride * height * 3); // size in bytes
put4(0); // reserved
put4(offset);
// BITMAPINFOHEADER
put4(40); // size of header in bytes
put4(width); // width in pixels
put4(height); // height in pixels
put2(1); // number of color planes
put2(24); // bits per pixel
put4(0); // compression scheme (none)
put4(0); // size
put4(72); // horizontal resolution
put4(72); // vertical resolution
put4(0); // color pallete size
put4(0); // 'important colors' count
for (int y = height - 1; y >= 0; y--)
{
for (int x = 0; x < width; x++)
{
auto &texel = texels[x + y * width];
put1(texel.b);
put1(texel.g);
put1(texel.r);
}
for (int i = 0; i < padding; i++)
{
put1(0);
}
}
return ok;
}
// Constants used for rendering the fractal.
constexpr uint32_t imageWidth = 2048;
constexpr uint32_t imageHeight = 2048;
constexpr int samplesPerPixel = 8;
constexpr float windowMinX = -0.5f;
constexpr float windowMaxX = +0.5f;
constexpr float windowMinY = -0.5f;
constexpr float windowMaxY = +0.5f;
constexpr float cx = -0.8f;
constexpr float cy = 0.156f;
int main(int argc, const char** argv)
{
// Create a marl scheduler using the full number of logical cpus.
// Bind this scheduler to the main thread so we can call marl::schedule()
marl::Scheduler scheduler;
scheduler.setWorkerThreadCount(marl::Thread::numLogicalCPUs());
scheduler.bind();
defer(scheduler.unbind()); // unbind before destructing the scheduler.
// Allocate the image.
auto pixels = new Color<uint8_t>[imageWidth * imageHeight];
defer(delete [] pixels); // free memory before returning.
// Create a wait group that will be used to synchronize the tasks.
// The wait group is constructed with an initial count of imageHeight as
// there will be a total of imageHeight tasks.
marl::WaitGroup wg(imageHeight);
// For each line of the image...
for (int y = 0; y < imageHeight; y++) {
// Schedule a task to calculate the image for this line.
// These may run concurrently across hardware threads.
marl::schedule([=] {
// Before this task returns, decrement the wait group counter.
// This is used to indicate that the task is done.
defer(wg.done());
for (int x = 0; x < imageWidth; x++) {
// Calculate the fractal pixel color.
Color<float> color = {};
for (int sample = 0; sample < samplesPerPixel; sample++)
{
auto fx = float(x) + (rand() / float(RAND_MAX));
auto fy = float(y) + (rand() / float(RAND_MAX));
auto dx = float(fx) / float(imageWidth);
auto dy = float(fy) / float(imageHeight);
color += julia(lerp(dx, windowMinX, windowMaxX), lerp(dy, windowMinY, windowMaxY), cx, cy);
}
color /= samplesPerPixel;
pixels[x + y * imageWidth] = {
static_cast<uint8_t>(color.r * 255),
static_cast<uint8_t>(color.g * 255),
static_cast<uint8_t>(color.b * 255)
};
}
});
}
// Wait until all image lines have been calculated.
wg.wait();
// Write the image to "fractal.bmp".
if (!writeBMP(pixels, imageWidth, imageHeight, "fractal.bmp")) { return 1; }
// All done.
return 0;
}
|
Update license on fractal.cpp
|
Update license on fractal.cpp
This license header was stale.
|
C++
|
apache-2.0
|
google/marl,google/marl,google/marl,google/marl
|
eab334d955352a1990ead02418ef4bdd7e69b606
|
src/error_logger.cc
|
src/error_logger.cc
|
/*
Copyright (c) 2017-2018 Tuukka Norri
This code is licensed under MIT license (see LICENSE for details).
*/
#include <experimental/optional>
#include <vcf2multialign/error_logger.hh>
#ifdef __GNUC__
# if __GNUC__ < 7
// XXX Hack.
namespace std {
using std::experimental::optional;
using std::experimental::nullopt;
}
# endif
#endif
namespace lb = libbio;
namespace v2m = vcf2multialign;
namespace {
void log(
std::ostream &output_stream,
char const *reason,
std::size_t const line_1,
std::optional <std::size_t> line_2 = std::nullopt,
std::optional <std::size_t> ref_pos = std::nullopt,
std::optional <std::size_t> alt_idx = std::nullopt,
std::optional <lb::sv_type> svt = std::nullopt,
std::optional <std::size_t> sample_no = std::nullopt,
std::optional <std::size_t> chr_idx = std::nullopt,
std::optional <std::size_t> handled_with_alt = std::nullopt,
std::optional <std::size_t> total_with_alt = std::nullopt,
std::optional <std::size_t> handled_with_any_alt = std::nullopt,
std::optional <std::size_t> total_with_any_alt = std::nullopt
)
{
output_stream << line_1 << '\t';
if (line_2) output_stream << *line_2;
output_stream << '\t';
if (ref_pos) output_stream << *ref_pos;
output_stream << '\t';
if (alt_idx) output_stream << *alt_idx;
output_stream << '\t';
if (svt) output_stream << to_string(*svt);
output_stream << '\t';
if (sample_no) output_stream << *sample_no;
output_stream << '\t';
if (chr_idx) output_stream << *chr_idx;
output_stream << '\t';
if (handled_with_alt) output_stream << *handled_with_alt;
output_stream << '\t';
if (total_with_alt) output_stream << *total_with_alt;
output_stream << '\t';
if (handled_with_any_alt) output_stream << *handled_with_any_alt;
output_stream << '\t';
if (total_with_any_alt) output_stream << *total_with_any_alt;
output_stream << '\t';
if (reason) output_stream << reason;
output_stream << "\n";
}
}
namespace vcf2multialign {
void error_logger::write_header()
{
if (is_logging_errors())
{
m_output_stream
<< "VARIANT_1_LINE\t"
<< "VARIANT_2_LINE\t"
<< "REF_POS\t"
<< "ALT_IDX\t"
<< "SV_TYPE\t"
<< "SAMPLE\t"
<< "CHR\t"
<< "HANDLED_WITH_ALT\t"
<< "TOTAL_WITH_ALT\t"
<< "HANDLED_WITH_ANY_ALT\t"
<< "TOTAL_WITH_ANY_ALT\t"
<< "REASON\n";
}
}
void error_logger::log_no_supported_alts(std::size_t const line)
{
if (is_logging_errors())
{
char const *reason("No supported ALTs");
log(m_output_stream, reason, line);
}
}
void error_logger::log_skipped_structural_variant(std::size_t const line, std::size_t const alt_idx, lb::sv_type const svt)
{
if (is_logging_errors())
{
char const *reason("Skipped structural variant");
log(m_output_stream, reason, line, std::nullopt, std::nullopt, alt_idx, svt);
}
}
void error_logger::log_invalid_alt_seq(std::size_t const line, std::size_t const alt_idx, std::string const &alt)
{
if (is_logging_errors())
{
char const *reason("Unexpected character in ALT");
log(m_output_stream, reason, line, std::nullopt, std::nullopt, alt_idx);
}
}
void error_logger::log_conflicting_variants(std::size_t const line_1, std::size_t const line_2)
{
if (is_logging_errors())
{
char const *reason("Conflicting variants");
log(m_output_stream, reason, line_1, line_2);
}
}
void error_logger::log_ref_mismatch(std::size_t const lineno, std::size_t const diff_pos)
{
if (is_logging_errors())
{
char const *reason("REF does not match the reference sequence (output anyway using the reference)");
log(m_output_stream, reason, lineno, std::nullopt, diff_pos);
}
}
void error_logger::log_overlapping_alternative(
std::size_t const lineno,
std::size_t const sample_no,
std::size_t const chr_idx,
sample_count const &alt_counts,
sample_count const &non_ref_total_counts
)
{
char const *reason("Overlapping alternative");
log(
m_output_stream,
reason,
lineno,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
sample_no,
chr_idx,
alt_counts.handled_count,
alt_counts.total_count,
non_ref_total_counts.handled_count,
non_ref_total_counts.total_count
);
}
}
|
/*
Copyright (c) 2017-2018 Tuukka Norri
This code is licensed under MIT license (see LICENSE for details).
*/
#if __has_include(<optional>)
# include <optional>
#else
# include <experimental/optional>
// XXX Hack.
namespace std {
using std::experimental::optional;
using std::experimental::nullopt;
}
#endif
#include <vcf2multialign/error_logger.hh>
namespace lb = libbio;
namespace v2m = vcf2multialign;
namespace {
void log(
std::ostream &output_stream,
char const *reason,
std::size_t const line_1,
std::optional <std::size_t> line_2 = std::nullopt,
std::optional <std::size_t> ref_pos = std::nullopt,
std::optional <std::size_t> alt_idx = std::nullopt,
std::optional <lb::sv_type> svt = std::nullopt,
std::optional <std::size_t> sample_no = std::nullopt,
std::optional <std::size_t> chr_idx = std::nullopt,
std::optional <std::size_t> handled_with_alt = std::nullopt,
std::optional <std::size_t> total_with_alt = std::nullopt,
std::optional <std::size_t> handled_with_any_alt = std::nullopt,
std::optional <std::size_t> total_with_any_alt = std::nullopt
)
{
output_stream << line_1 << '\t';
if (line_2) output_stream << *line_2;
output_stream << '\t';
if (ref_pos) output_stream << *ref_pos;
output_stream << '\t';
if (alt_idx) output_stream << *alt_idx;
output_stream << '\t';
if (svt) output_stream << to_string(*svt);
output_stream << '\t';
if (sample_no) output_stream << *sample_no;
output_stream << '\t';
if (chr_idx) output_stream << *chr_idx;
output_stream << '\t';
if (handled_with_alt) output_stream << *handled_with_alt;
output_stream << '\t';
if (total_with_alt) output_stream << *total_with_alt;
output_stream << '\t';
if (handled_with_any_alt) output_stream << *handled_with_any_alt;
output_stream << '\t';
if (total_with_any_alt) output_stream << *total_with_any_alt;
output_stream << '\t';
if (reason) output_stream << reason;
output_stream << "\n";
}
}
namespace vcf2multialign {
void error_logger::write_header()
{
if (is_logging_errors())
{
m_output_stream
<< "VARIANT_1_LINE\t"
<< "VARIANT_2_LINE\t"
<< "REF_POS\t"
<< "ALT_IDX\t"
<< "SV_TYPE\t"
<< "SAMPLE\t"
<< "CHR\t"
<< "HANDLED_WITH_ALT\t"
<< "TOTAL_WITH_ALT\t"
<< "HANDLED_WITH_ANY_ALT\t"
<< "TOTAL_WITH_ANY_ALT\t"
<< "REASON\n";
}
}
void error_logger::log_no_supported_alts(std::size_t const line)
{
if (is_logging_errors())
{
char const *reason("No supported ALTs");
log(m_output_stream, reason, line);
}
}
void error_logger::log_skipped_structural_variant(std::size_t const line, std::size_t const alt_idx, lb::sv_type const svt)
{
if (is_logging_errors())
{
char const *reason("Skipped structural variant");
log(m_output_stream, reason, line, std::nullopt, std::nullopt, alt_idx, svt);
}
}
void error_logger::log_invalid_alt_seq(std::size_t const line, std::size_t const alt_idx, std::string const &alt)
{
if (is_logging_errors())
{
char const *reason("Unexpected character in ALT");
log(m_output_stream, reason, line, std::nullopt, std::nullopt, alt_idx);
}
}
void error_logger::log_conflicting_variants(std::size_t const line_1, std::size_t const line_2)
{
if (is_logging_errors())
{
char const *reason("Conflicting variants");
log(m_output_stream, reason, line_1, line_2);
}
}
void error_logger::log_ref_mismatch(std::size_t const lineno, std::size_t const diff_pos)
{
if (is_logging_errors())
{
char const *reason("REF does not match the reference sequence (output anyway using the reference)");
log(m_output_stream, reason, lineno, std::nullopt, diff_pos);
}
}
void error_logger::log_overlapping_alternative(
std::size_t const lineno,
std::size_t const sample_no,
std::size_t const chr_idx,
sample_count const &alt_counts,
sample_count const &non_ref_total_counts
)
{
char const *reason("Overlapping alternative");
log(
m_output_stream,
reason,
lineno,
std::nullopt,
std::nullopt,
std::nullopt,
std::nullopt,
sample_no,
chr_idx,
alt_counts.handled_count,
alt_counts.total_count,
non_ref_total_counts.handled_count,
non_ref_total_counts.total_count
);
}
}
|
Add a header check
|
Add a header check
|
C++
|
mit
|
tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign,tsnorri/vcf2multialign
|
822e4e9435110ef102a0c900849bb81ade48d635
|
src/factor_graph.cc
|
src/factor_graph.cc
|
#include "factor_graph.h"
#include "binary_format.h"
#include "factor.h"
#include <iostream>
#include <algorithm>
#include <thread>
#include <unistd.h>
namespace dd {
FactorGraphDescriptor::FactorGraphDescriptor()
: FactorGraphDescriptor(0, 0, 0, 0) {}
FactorGraphDescriptor::FactorGraphDescriptor(size_t n_var, size_t n_fac,
size_t n_wgt, size_t n_edg)
: num_variables(n_var),
num_factors(n_fac),
num_edges(n_edg),
num_weights(n_wgt),
num_values(0),
num_variables_evidence(0),
num_variables_query(0) {}
std::ostream &operator<<(std::ostream &stream,
const FactorGraphDescriptor &size) {
stream << "#V=" << size.num_variables;
if (size.num_variables_query + size.num_variables_evidence > 0) {
stream << "(";
stream << "#Vqry=" << size.num_variables_query;
stream << " ";
stream << "#Vevd=" << size.num_variables_evidence;
stream << ")";
}
stream << " "
<< "#F=" << size.num_factors;
stream << " "
<< "#W=" << size.num_weights;
stream << " "
<< "#E=" << size.num_edges;
stream << " "
<< "#Val=" << size.num_values;
return stream;
}
FactorGraph::FactorGraph(const FactorGraphDescriptor &capacity)
: capacity(capacity),
size(),
// fast alloc: 0 sec for a 270M-factor graph
weights(fast_alloc_no_init<Weight>(capacity.num_weights)),
factors(fast_alloc_no_init<Factor>(capacity.num_factors)),
vifs(fast_alloc_no_init<FactorToVariable>(capacity.num_edges)),
variables(fast_alloc_no_init<Variable>(capacity.num_variables)),
factor_index(fast_alloc_no_init<size_t>(capacity.num_edges)),
values(fast_alloc_no_init<VariableToFactor>(capacity.num_values))
// slow alloc: 55 sec for a 270M-factor graph
// weights(new Weight[capacity.num_weights]),
// factors(new Factor[capacity.num_factors]),
// vifs(new FactorToVariable[capacity.num_edges]),
// variables(new Variable[capacity.num_variables]),
// factor_index(new size_t[capacity.num_edges]),
// values(new VariableToFactor[capacity.num_values])
{
for (size_t i = 0; i < capacity.num_variables; ++i) {
// make sure the pointers are null after the fast mem allocation
// NOTE: if we introduce more pointers in the data structures, add here.
// see also ~FactorGraph()
variables[i].domain_map.release();
variables[i].adjacent_factors.release();
}
}
FactorGraph::~FactorGraph() {
// manually free pointers in array elements before dirty-free the arrays
for (size_t i = 0; i < capacity.num_variables; ++i) {
variables[i].domain_map.reset();
variables[i].adjacent_factors.reset();
}
fast_alloc_free(weights.release());
fast_alloc_free(factors.release());
fast_alloc_free(vifs.release());
fast_alloc_free(variables.release());
fast_alloc_free(factor_index.release());
fast_alloc_free(values.release());
}
void FactorGraph::construct_index() {
size_t total = size.num_variables;
// large graph, multi thread
// 6 sec instead of 30 sec for a 270M-factor graph
std::vector<std::tuple<size_t, size_t, size_t, size_t>> params;
size_t cores = sysconf(_SC_NPROCESSORS_CONF);
size_t increment = total / cores;
size_t milestone = 0;
size_t num_values = 0, num_factors = 0;
for (size_t i = 0; i < size.num_variables; ++i) {
if (i == milestone) {
milestone += increment;
if (milestone > total) {
milestone = total;
}
params.push_back(std::make_tuple(i, milestone, num_values, num_factors));
}
num_values += variables[i].internal_cardinality();
if (variables[i].adjacent_factors) {
num_factors += variables[i].adjacent_factors->size();
}
}
size.num_values = capacity.num_values = num_values;
values.reset(fast_alloc_no_init<VariableToFactor>(num_values));
// small graph, single thread
if (total < 10000) {
construct_index_part(0, total, 0, 0);
return;
}
std::vector<std::thread> threads;
for (const auto &tup : params) {
threads.push_back(std::thread(&FactorGraph::construct_index_part, this,
std::get<0>(tup), std::get<1>(tup),
std::get<2>(tup), std::get<3>(tup)));
}
for (auto &t : threads) t.join();
threads.clear();
}
void FactorGraph::construct_index_part(size_t v_start, size_t v_end,
size_t val_base, size_t fac_base) {
size_t value_index_base = val_base, factor_index_base = fac_base;
std::vector<size_t> value_list;
std::vector<double> truthiness_list;
// For each variable, sort and uniq adjacent factors by value.
// We deallocate "domain_map" and "adjacent_factors".
for (size_t i = v_start; i < v_end; ++i) {
Variable &v = variables[i];
v.var_val_base = value_index_base;
v.total_truthiness = 0;
if (v.is_boolean()) {
// NOTE: we don't support truthiness for boolean vars
values[value_index_base] =
VariableToFactor(Variable::BOOLEAN_DENSE_VALUE, 0, 0, 0);
++value_index_base;
} else {
if (v.domain_map) {
// explicitly listed domain values; recover the list from map.
value_list.assign(v.cardinality, Variable::INVALID_VALUE);
truthiness_list.assign(v.cardinality, 0);
for (const auto &item : *v.domain_map) {
value_list.at(item.second.index) = item.first;
truthiness_list.at(item.second.index) = item.second.truthiness;
v.total_truthiness += item.second.truthiness;
}
for (size_t j = 0; j < v.cardinality; ++j) {
values[value_index_base] =
VariableToFactor(value_list[j], truthiness_list[j], 0, 0);
++value_index_base;
}
v.domain_map.reset(); // reclaim memory
} else {
// implicit [0...(cardinality-1)] domain values
// TODO: this branch should be deprecated; i.e., require domains for all
// categorical vars
for (size_t j = 0; j < v.cardinality; ++j) {
values[value_index_base] = VariableToFactor(j, 0, 0, 0);
++value_index_base;
}
}
}
if (v.adjacent_factors) {
// sort by <value, fid>
std::sort(v.adjacent_factors->begin(), v.adjacent_factors->end());
size_t value_dense = Variable::INVALID_VALUE;
size_t last_factor_id = Factor::INVALID_ID;
for (const auto &item : *v.adjacent_factors) {
if (item.value_dense != value_dense) {
value_dense = item.value_dense;
assert(value_dense < v.cardinality);
values[v.var_val_base + value_dense].factor_index_base =
factor_index_base;
} else if (item.factor_id == last_factor_id) {
continue; // dedupe
}
factor_index[factor_index_base] = item.factor_id;
++factor_index_base;
++values[v.var_val_base + value_dense].factor_index_length;
last_factor_id = item.factor_id;
}
v.adjacent_factors.reset(); // reclaim memory
}
}
}
void FactorGraph::safety_check() {
// check if any space is wasted
assert(capacity.num_variables == size.num_variables);
assert(capacity.num_factors == size.num_factors);
assert(capacity.num_edges == size.num_edges);
assert(capacity.num_weights == size.num_weights);
// check whether variables, factors, and weights are stored
// in the order of their id
for (size_t i = 0; i < size.num_variables; ++i) {
assert(this->variables[i].id == i);
}
for (size_t i = 0; i < size.num_factors; ++i) {
assert(this->factors[i].id == i);
}
for (size_t i = 0; i < size.num_weights; ++i) {
assert(this->weights[i].id == i);
}
}
FactorGraph::FactorGraph(const FactorGraph &other)
: FactorGraph(other.capacity) {
size = other.size;
// fast copy: 3 sec for a 270M-factor graph
parallel_copy<Weight>(other.weights, weights, size.num_weights);
parallel_copy<Factor>(other.factors, factors, size.num_factors);
parallel_copy<FactorToVariable>(other.vifs, vifs, size.num_edges);
parallel_copy<Variable>(other.variables, variables, size.num_variables);
parallel_copy<size_t>(other.factor_index, factor_index, size.num_edges);
parallel_copy<VariableToFactor>(other.values, values, size.num_values);
// slow copy: 18 sec for a 270M-factor graph
// COPY_ARRAY_UNIQUE_PTR_MEMBER(variables, size.num_variables);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(factors, size.num_factors);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(factor_index, size.num_edges);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(vifs, size.num_edges);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(weights, size.num_weights);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(values, size.num_values);
}
// Inline by defined here; accessible only from current file.
inline void FactorGraph::sgd_on_factor(size_t factor_id, double stepsize,
size_t vid, size_t evidence_value,
InferenceResult &infrs) {
const Factor &factor = factors[factor_id];
if (infrs.weights_isfixed[factor.weight_id]) {
return;
}
// stochastic gradient ascent
// decrement weight with stepsize * gradient of weight
// gradient of weight = E[f] - E[f|D], where D is evidence variables,
// f is the factor function, E[] is expectation. Expectation is
// calculated using a sample of the variable.
double pot_evid = factor.potential(vifs.get(), infrs.assignments_evid.get(),
vid, evidence_value);
double pot_free = factor.potential(vifs.get(), infrs.assignments_free.get());
double gradient = pot_free - pot_evid;
infrs.update_weight(factor.weight_id, stepsize, gradient);
}
void FactorGraph::sgd_on_variable(const Variable &variable,
InferenceResult &infrs, double stepsize,
bool is_noise_aware) {
if (variable.is_boolean()) {
// boolean: for each factor {learn}
// NOTE: boolean vars do not support truthiness / noise-aware learning
const VariableToFactor &vv = values[variable.var_val_base];
for (size_t j = 0; j < vv.factor_index_length; ++j) {
size_t factor_id = factor_index[vv.factor_index_base + j];
sgd_on_factor(factor_id, stepsize, variable.id, variable.assignment_dense,
infrs);
}
} else {
// categorical: for each evidence value { for each factor {learn} }
size_t proposal = infrs.assignments_free[variable.id];
for (size_t val = 0; val < variable.internal_cardinality(); ++val) {
// skip non-evidence values
if (!is_noise_aware && val != variable.assignment_dense) continue;
const VariableToFactor &ev = values[variable.var_val_base + val];
if (is_noise_aware && is_linear_zero(ev.truthiness)) continue;
double truthiness = is_noise_aware ? ev.truthiness : 1;
// run SGD on all factors "activated" by this evidence value
for (size_t j = 0; j < ev.factor_index_length; ++j) {
size_t factor_id = factor_index[ev.factor_index_base + j];
sgd_on_factor(factor_id, stepsize * truthiness, variable.id, val,
infrs);
}
// run SGD on all factors "activated" by proposal value
// NOTE: Current ddlog inference rule syntax implies that this list
// of factors would overlap the above list only if the factor
// connects tuple [var=val] and tuple [var=proposal], which sensible
// ddlog inference rules would never generate.
// Hence we assume that there is no overlap.
// This may change in the future as we introduce fancier factor
// types.
// skip if we have just processed the same list of factors
// NOTE: not skipping before the first loop because ... assignments_evid!
if (val == proposal) continue;
const VariableToFactor &pv = values[variable.var_val_base + proposal];
for (size_t j = 0; j < pv.factor_index_length; ++j) {
size_t factor_id = factor_index[pv.factor_index_base + j];
sgd_on_factor(factor_id, stepsize * truthiness, variable.id, val,
infrs);
}
} // end for
}
}
} // namespace dd
|
#include "factor_graph.h"
#include "binary_format.h"
#include "factor.h"
#include <iostream>
#include <algorithm>
#include <thread>
#include <unistd.h>
namespace dd {
FactorGraphDescriptor::FactorGraphDescriptor()
: FactorGraphDescriptor(0, 0, 0, 0) {}
FactorGraphDescriptor::FactorGraphDescriptor(size_t n_var, size_t n_fac,
size_t n_wgt, size_t n_edg)
: num_variables(n_var),
num_factors(n_fac),
num_edges(n_edg),
num_weights(n_wgt),
num_values(0),
num_variables_evidence(0),
num_variables_query(0) {}
std::ostream &operator<<(std::ostream &stream,
const FactorGraphDescriptor &size) {
stream << "#V=" << size.num_variables;
if (size.num_variables_query + size.num_variables_evidence > 0) {
stream << "(";
stream << "#Vqry=" << size.num_variables_query;
stream << " ";
stream << "#Vevd=" << size.num_variables_evidence;
stream << ")";
}
stream << " "
<< "#F=" << size.num_factors;
stream << " "
<< "#W=" << size.num_weights;
stream << " "
<< "#E=" << size.num_edges;
stream << " "
<< "#Val=" << size.num_values;
return stream;
}
FactorGraph::FactorGraph(const FactorGraphDescriptor &capacity)
: capacity(capacity),
size(),
// fast alloc: 0 sec for a 270M-factor graph
weights(fast_alloc_no_init<Weight>(capacity.num_weights)),
factors(fast_alloc_no_init<Factor>(capacity.num_factors)),
vifs(fast_alloc_no_init<FactorToVariable>(capacity.num_edges)),
variables(fast_alloc_no_init<Variable>(capacity.num_variables)),
factor_index(fast_alloc_no_init<size_t>(capacity.num_edges)),
values(fast_alloc_no_init<VariableToFactor>(capacity.num_values))
// slow alloc: 55 sec for a 270M-factor graph
// weights(new Weight[capacity.num_weights]),
// factors(new Factor[capacity.num_factors]),
// vifs(new FactorToVariable[capacity.num_edges]),
// variables(new Variable[capacity.num_variables]),
// factor_index(new size_t[capacity.num_edges]),
// values(new VariableToFactor[capacity.num_values])
{
for (size_t i = 0; i < capacity.num_variables; ++i) {
// make sure the pointers are null after the fast mem allocation
// NOTE: if we introduce more pointers in the data structures, add here.
// see also ~FactorGraph()
variables[i].domain_map.release();
variables[i].adjacent_factors.release();
}
}
FactorGraph::~FactorGraph() {
// manually free pointers in array elements before dirty-free the arrays
for (size_t i = 0; i < capacity.num_variables; ++i) {
variables[i].domain_map.reset();
variables[i].adjacent_factors.reset();
}
fast_alloc_free(weights.release());
fast_alloc_free(factors.release());
fast_alloc_free(vifs.release());
fast_alloc_free(variables.release());
fast_alloc_free(factor_index.release());
fast_alloc_free(values.release());
}
// Construct index using multiple threads
// 6 sec instead of 30 sec for a 270M-factor graph
// std::vector<std::tuple<size_t, size_t, size_t, size_t>> params;
void FactorGraph::construct_index() {
size_t total = size.num_variables;
size_t cores = sysconf(_SC_NPROCESSORS_CONF);
size_t increment = total / cores;
// small graph, single thread
if (total < 1000) {
increment = total;
}
size_t milestone = 0;
size_t num_values = 0, num_factors = 0;
std::vector<std::function<void()>> tasks;
for (size_t i = 0; i < size.num_variables; ++i) {
if (i == milestone) {
milestone += increment;
if (milestone > total) {
milestone = total;
}
tasks.push_back([this, i, milestone, num_values, num_factors]() {
construct_index_part(i, milestone, num_values, num_factors);
});
}
num_values += variables[i].internal_cardinality();
if (variables[i].adjacent_factors) {
num_factors += variables[i].adjacent_factors->size();
}
}
size.num_values = capacity.num_values = num_values;
values.reset(fast_alloc_no_init<VariableToFactor>(num_values));
std::vector<std::thread> threads;
for (const auto &task : tasks) {
threads.push_back(std::thread(task));
}
for (auto &t : threads) t.join();
threads.clear();
}
void FactorGraph::construct_index_part(size_t v_start, size_t v_end,
size_t val_base, size_t fac_base) {
size_t value_index_base = val_base, factor_index_base = fac_base;
std::vector<size_t> value_list;
std::vector<double> truthiness_list;
// For each variable, sort and uniq adjacent factors by value.
// We deallocate "domain_map" and "adjacent_factors".
for (size_t i = v_start; i < v_end; ++i) {
Variable &v = variables[i];
v.var_val_base = value_index_base;
v.total_truthiness = 0;
if (v.is_boolean()) {
// NOTE: we don't support truthiness for boolean vars
values[value_index_base] =
VariableToFactor(Variable::BOOLEAN_DENSE_VALUE, 0, 0, 0);
++value_index_base;
} else {
if (v.domain_map) {
// explicitly listed domain values; recover the list from map.
value_list.assign(v.cardinality, Variable::INVALID_VALUE);
truthiness_list.assign(v.cardinality, 0);
for (const auto &item : *v.domain_map) {
value_list.at(item.second.index) = item.first;
truthiness_list.at(item.second.index) = item.second.truthiness;
v.total_truthiness += item.second.truthiness;
}
for (size_t j = 0; j < v.cardinality; ++j) {
values[value_index_base] =
VariableToFactor(value_list[j], truthiness_list[j], 0, 0);
++value_index_base;
}
v.domain_map.reset(); // reclaim memory
} else {
// implicit [0...(cardinality-1)] domain values
// TODO: this branch should be deprecated; i.e., require domains for all
// categorical vars
for (size_t j = 0; j < v.cardinality; ++j) {
values[value_index_base] = VariableToFactor(j, 0, 0, 0);
++value_index_base;
}
}
}
if (v.adjacent_factors) {
// sort by <value, fid>
std::sort(v.adjacent_factors->begin(), v.adjacent_factors->end());
size_t value_dense = Variable::INVALID_VALUE;
size_t last_factor_id = Factor::INVALID_ID;
for (const auto &item : *v.adjacent_factors) {
if (item.value_dense != value_dense) {
value_dense = item.value_dense;
assert(value_dense < v.cardinality);
values[v.var_val_base + value_dense].factor_index_base =
factor_index_base;
} else if (item.factor_id == last_factor_id) {
continue; // dedupe
}
factor_index[factor_index_base] = item.factor_id;
++factor_index_base;
++values[v.var_val_base + value_dense].factor_index_length;
last_factor_id = item.factor_id;
}
v.adjacent_factors.reset(); // reclaim memory
}
}
}
void FactorGraph::safety_check() {
// check if any space is wasted
assert(capacity.num_variables == size.num_variables);
assert(capacity.num_factors == size.num_factors);
assert(capacity.num_edges == size.num_edges);
assert(capacity.num_weights == size.num_weights);
// check whether variables, factors, and weights are stored
// in the order of their id
for (size_t i = 0; i < size.num_variables; ++i) {
assert(this->variables[i].id == i);
}
for (size_t i = 0; i < size.num_factors; ++i) {
assert(this->factors[i].id == i);
}
for (size_t i = 0; i < size.num_weights; ++i) {
assert(this->weights[i].id == i);
}
}
FactorGraph::FactorGraph(const FactorGraph &other)
: FactorGraph(other.capacity) {
size = other.size;
// fast copy: 3 sec for a 270M-factor graph
parallel_copy<Weight>(other.weights, weights, size.num_weights);
parallel_copy<Factor>(other.factors, factors, size.num_factors);
parallel_copy<FactorToVariable>(other.vifs, vifs, size.num_edges);
parallel_copy<Variable>(other.variables, variables, size.num_variables);
parallel_copy<size_t>(other.factor_index, factor_index, size.num_edges);
parallel_copy<VariableToFactor>(other.values, values, size.num_values);
// slow copy: 18 sec for a 270M-factor graph
// COPY_ARRAY_UNIQUE_PTR_MEMBER(variables, size.num_variables);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(factors, size.num_factors);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(factor_index, size.num_edges);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(vifs, size.num_edges);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(weights, size.num_weights);
// COPY_ARRAY_UNIQUE_PTR_MEMBER(values, size.num_values);
}
// Inline by defined here; accessible only from current file.
inline void FactorGraph::sgd_on_factor(size_t factor_id, double stepsize,
size_t vid, size_t evidence_value,
InferenceResult &infrs) {
const Factor &factor = factors[factor_id];
if (infrs.weights_isfixed[factor.weight_id]) {
return;
}
// stochastic gradient ascent
// decrement weight with stepsize * gradient of weight
// gradient of weight = E[f] - E[f|D], where D is evidence variables,
// f is the factor function, E[] is expectation. Expectation is
// calculated using a sample of the variable.
double pot_evid = factor.potential(vifs.get(), infrs.assignments_evid.get(),
vid, evidence_value);
double pot_free = factor.potential(vifs.get(), infrs.assignments_free.get());
double gradient = pot_free - pot_evid;
infrs.update_weight(factor.weight_id, stepsize, gradient);
}
void FactorGraph::sgd_on_variable(const Variable &variable,
InferenceResult &infrs, double stepsize,
bool is_noise_aware) {
if (variable.is_boolean()) {
// boolean: for each factor {learn}
// NOTE: boolean vars do not support truthiness / noise-aware learning
const VariableToFactor &vv = values[variable.var_val_base];
for (size_t j = 0; j < vv.factor_index_length; ++j) {
size_t factor_id = factor_index[vv.factor_index_base + j];
sgd_on_factor(factor_id, stepsize, variable.id, variable.assignment_dense,
infrs);
}
} else {
// categorical: for each evidence value { for each factor {learn} }
size_t proposal = infrs.assignments_free[variable.id];
for (size_t val = 0; val < variable.internal_cardinality(); ++val) {
// skip non-evidence values
if (!is_noise_aware && val != variable.assignment_dense) continue;
const VariableToFactor &ev = values[variable.var_val_base + val];
if (is_noise_aware && is_linear_zero(ev.truthiness)) continue;
double truthiness = is_noise_aware ? ev.truthiness : 1;
// run SGD on all factors "activated" by this evidence value
for (size_t j = 0; j < ev.factor_index_length; ++j) {
size_t factor_id = factor_index[ev.factor_index_base + j];
sgd_on_factor(factor_id, stepsize * truthiness, variable.id, val,
infrs);
}
// run SGD on all factors "activated" by proposal value
// NOTE: Current ddlog inference rule syntax implies that this list
// of factors would overlap the above list only if the factor
// connects tuple [var=val] and tuple [var=proposal], which sensible
// ddlog inference rules would never generate.
// Hence we assume that there is no overlap.
// This may change in the future as we introduce fancier factor
// types.
// skip if we have just processed the same list of factors
// NOTE: not skipping before the first loop because ... assignments_evid!
if (val == proposal) continue;
const VariableToFactor &pv = values[variable.var_val_base + proposal];
for (size_t j = 0; j < pv.factor_index_length; ++j) {
size_t factor_id = factor_index[pv.factor_index_base + j];
sgd_on_factor(factor_id, stepsize * truthiness, variable.id, val,
infrs);
}
} // end for
}
}
} // namespace dd
|
fix anon func
|
fix anon func
|
C++
|
apache-2.0
|
HazyResearch/sampler,HazyResearch/sampler,HazyResearch/deepdive,HazyResearch/deepdive,HazyResearch/sampler,HazyResearch/deepdive,HazyResearch/deepdive
|
8f7dfdab804f0096e236771d1e0994f6bfe743a3
|
src/fastqreader.cpp
|
src/fastqreader.cpp
|
#include "fastqreader.h"
#include "util.h"
#include <string.h>
FastqReader::FastqReader(string filename, bool hasQuality){
mFilename = filename;
mZipFile = NULL;
mZipped = false;
mHasQuality = hasQuality;
init();
}
FastqReader::~FastqReader(){
close();
}
void FastqReader::init(){
if (isZipFastq(mFilename)){
mZipFile = gzopen(mFilename.c_str(), "r");
// increase the gzip buffer size to increse
gzbuffer(mZipFile, 1024*1024);
mZipped = true;
Read* r = read();
//test if it has quality line or not (fastq/fasta)
if (r->mQuality[0] == '@')
mHasQuality = false;
delete r;
gzrewind(mZipFile);
}
else if (isFastq(mFilename)){
mFile.open(mFilename.c_str(), ifstream::in);
mZipped = false;
} else {
cerr << "ERROR: the input file should be fastq (.fq, .fastq) or gzipped fastq (.fq.gz, .fastq.gz)" << endl;
exit(-1);
}
}
bool FastqReader::getLine(char* line, int maxLine){
bool status = true;
if(mZipped)
status = gzgets(mZipFile, line, maxLine);
else {
mFile.getline(line, maxLine);
status = !mFile.fail();
}
// trim \n, \r or \r\n in the tail
int readed = strlen(line);
if(readed >=2 ){
if(line[readed-1] == '\n' || line[readed-1] == '\r'){
line[readed-1] = '\0';
if(line[readed-2] == '\r')
line[readed-2] = '\0';
}
}
return status;
}
Read* FastqReader::read(){
const int maxLine = 1000;
char line[maxLine];
if (mZipped){
if (mZipFile == NULL)
return NULL;
}
if(!getLine(line, maxLine))return NULL;
string name(line);
if (!getLine(line, maxLine))return NULL;
string sequence(line);
if (!getLine(line, maxLine))return NULL;
string strand(line);
if (mHasQuality){
if (!getLine(line, maxLine))return NULL;
string quality(line);
Read* read = new Read(name, sequence, strand, quality);
return read;
}
else {
Read* read = new Read(name, sequence, strand);
return read;
}
return NULL;
}
void FastqReader::close(){
if (mZipped){
if (mZipFile){
gzclose(mZipFile);
mZipFile = NULL;
}
}
else {
if (mFile.is_open()){
mFile.close();
}
}
}
bool FastqReader::isZipFastq(string filename) {
if (ends_with(filename, ".fastq.gz"))
return true;
else if (ends_with(filename, ".fq.gz"))
return true;
else if (ends_with(filename, ".fasta.gz"))
return true;
else if (ends_with(filename, ".fa.gz"))
return true;
else
return false;
}
bool FastqReader::isFastq(string filename) {
if (ends_with(filename, ".fastq"))
return true;
else if (ends_with(filename, ".fq"))
return true;
else if (ends_with(filename, ".fasta"))
return true;
else if (ends_with(filename, ".fa"))
return true;
else
return false;
}
bool FastqReader::isZipped(){
return mZipped;
}
bool FastqReader::test(){
FastqReader reader1("testdata/R1.fq");
FastqReader reader2("testdata/R1.fq.gz");
Read* r1 = NULL;
Read* r2 = NULL;
while(true){
r1=reader1.read();
r2=reader2.read();
if(r1 == NULL || r2 == NULL)
break;
if(r1->mSeq.mStr != r2->mSeq.mStr){
return false;
}
delete r1;
delete r2;
}
return true;
}
FastqReaderPair::FastqReaderPair(FastqReader* left, FastqReader* right){
mLeft = left;
mRight = right;
}
FastqReaderPair::FastqReaderPair(string leftName, string rightName){
mLeft = new FastqReader(leftName);
mRight = new FastqReader(rightName);
}
FastqReaderPair::~FastqReaderPair(){
if(mLeft){
delete mLeft;
mLeft = NULL;
}
if(mRight){
delete mRight;
mRight = NULL;
}
}
ReadPair* FastqReaderPair::read(){
Read* l = mLeft->read();
Read* r = mRight->read();
if(!l || !r){
return NULL;
} else {
return new ReadPair(l, r);
}
}
|
#include "fastqreader.h"
#include "util.h"
#include <string.h>
FastqReader::FastqReader(string filename, bool hasQuality){
mFilename = filename;
mZipFile = NULL;
mZipped = false;
mHasQuality = hasQuality;
init();
}
FastqReader::~FastqReader(){
close();
}
void FastqReader::init(){
if (isZipFastq(mFilename)){
mZipFile = gzopen(mFilename.c_str(), "r");
mZipped = true;
Read* r = read();
//test if it has quality line or not (fastq/fasta)
if (r->mQuality[0] == '@')
mHasQuality = false;
delete r;
gzrewind(mZipFile);
}
else if (isFastq(mFilename)){
mFile.open(mFilename.c_str(), ifstream::in);
mZipped = false;
} else {
cerr << "ERROR: the input file should be fastq (.fq, .fastq) or gzipped fastq (.fq.gz, .fastq.gz)" << endl;
exit(-1);
}
}
bool FastqReader::getLine(char* line, int maxLine){
bool status = true;
if(mZipped)
status = gzgets(mZipFile, line, maxLine);
else {
mFile.getline(line, maxLine);
status = !mFile.fail();
}
// trim \n, \r or \r\n in the tail
int readed = strlen(line);
if(readed >=2 ){
if(line[readed-1] == '\n' || line[readed-1] == '\r'){
line[readed-1] = '\0';
if(line[readed-2] == '\r')
line[readed-2] = '\0';
}
}
return status;
}
Read* FastqReader::read(){
const int maxLine = 1000;
char line[maxLine];
if (mZipped){
if (mZipFile == NULL)
return NULL;
}
if(!getLine(line, maxLine))return NULL;
string name(line);
if (!getLine(line, maxLine))return NULL;
string sequence(line);
if (!getLine(line, maxLine))return NULL;
string strand(line);
if (mHasQuality){
if (!getLine(line, maxLine))return NULL;
string quality(line);
Read* read = new Read(name, sequence, strand, quality);
return read;
}
else {
Read* read = new Read(name, sequence, strand);
return read;
}
return NULL;
}
void FastqReader::close(){
if (mZipped){
if (mZipFile){
gzclose(mZipFile);
mZipFile = NULL;
}
}
else {
if (mFile.is_open()){
mFile.close();
}
}
}
bool FastqReader::isZipFastq(string filename) {
if (ends_with(filename, ".fastq.gz"))
return true;
else if (ends_with(filename, ".fq.gz"))
return true;
else if (ends_with(filename, ".fasta.gz"))
return true;
else if (ends_with(filename, ".fa.gz"))
return true;
else
return false;
}
bool FastqReader::isFastq(string filename) {
if (ends_with(filename, ".fastq"))
return true;
else if (ends_with(filename, ".fq"))
return true;
else if (ends_with(filename, ".fasta"))
return true;
else if (ends_with(filename, ".fa"))
return true;
else
return false;
}
bool FastqReader::isZipped(){
return mZipped;
}
bool FastqReader::test(){
FastqReader reader1("testdata/R1.fq");
FastqReader reader2("testdata/R1.fq.gz");
Read* r1 = NULL;
Read* r2 = NULL;
while(true){
r1=reader1.read();
r2=reader2.read();
if(r1 == NULL || r2 == NULL)
break;
if(r1->mSeq.mStr != r2->mSeq.mStr){
return false;
}
delete r1;
delete r2;
}
return true;
}
FastqReaderPair::FastqReaderPair(FastqReader* left, FastqReader* right){
mLeft = left;
mRight = right;
}
FastqReaderPair::FastqReaderPair(string leftName, string rightName){
mLeft = new FastqReader(leftName);
mRight = new FastqReader(rightName);
}
FastqReaderPair::~FastqReaderPair(){
if(mLeft){
delete mLeft;
mLeft = NULL;
}
if(mRight){
delete mRight;
mRight = NULL;
}
}
ReadPair* FastqReaderPair::read(){
Read* l = mLeft->read();
Read* r = mRight->read();
if(!l || !r){
return NULL;
} else {
return new ReadPair(l, r);
}
}
|
remove gzbuffer since it is not compatible with old zlib
|
remove gzbuffer since it is not compatible with old zlib
|
C++
|
mit
|
OpenGene/MutScan,OpenGene/MutScan
|
795b5d54b29acffa469b69e15a619d162900fa54
|
Modules/Wrappers/CommandLine/src/otbWrapperCommandLineParser.cxx
|
Modules/Wrappers/CommandLine/src/otbWrapperCommandLineParser.cxx
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperCommandLineParser.h"
#include "otbWrapperApplicationRegistry.h"
#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
#include <string>
#include <iostream>
namespace otb
{
namespace Wrapper
{
CommandLineParser::CommandLineParser()
{
}
CommandLineParser::~CommandLineParser()
{
}
std::string
CommandLineParser::GetPathsAsString(const std::vector<std::string> & vexp )
{
std::string res;
std::vector<std::string> pathList;
if (this->GetPaths(pathList,vexp) == OK)
{
std::vector<std::string>::iterator it;
for (it=pathList.begin(); it!=pathList.end(); ++it)
{
if (!res.empty())
{
res.append(" ");
}
res.append(*it);
}
}
return res;
}
std::string
CommandLineParser::GetPathsAsString( const std::string & exp )
{
std::string res;
// The first element must be the module path, non " -" allowed.
// The module path list element are the strings between the first
// element and the next key (ie. " -" string).
std::string tempModPath = exp;
if( exp.find(" -") != std::string::npos)
{
tempModPath = exp.substr( 0, exp.find(" -"));
}
// Get everything after the module path
if( tempModPath.find(" ") != std::string::npos)
{
res = tempModPath.substr( tempModPath.find(" ")+1, tempModPath.size());
}
// Suppress possible multi space at the beginning of the string
while (res.size()>0 && res[0]==' ')
{
res.erase(0, 1);
}
return res;
}
CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::vector<std::string> & exp )
{
if (exp.empty())
{
return NOMODULEPATH;
}
// The first element must be the module name, non " -" allowed.
// The module path list elements are the strings between the first
// element and the first key (ie. string which begins with "-").
std::vector<std::string>::const_iterator it = exp.begin();
++it; // first element is module name
std::string tmpPath;
while (it != exp.end())
{
tmpPath = *it;
// If this is the first key : exit loop
if (tmpPath[0]=='-')
{
break;
}
// Add path to result
std::string fullPath = itksys::SystemTools::CollapseFullPath(tmpPath);
if( !itksys::SystemTools::FileIsDirectory(fullPath) )
{
std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
return INVALIDMODULEPATH;
}
paths.push_back(fullPath);
++it;
}
if (paths.empty())
{
return NOMODULEPATH;
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::string & exp )
{
std::string pathsList = this->GetPathsAsString( exp );
if( pathsList.size() == 0 )
{
return NOMODULEPATH;
}
std::string tempModPath = pathsList;
// remove other key in the string if there's any
if( pathsList.find(" -") != std::string::npos)
{
tempModPath = pathsList.substr( 0, pathsList.find(" -"));
}
if( tempModPath.size() > 0 )
{
std::vector<itksys::String> pathAttribut = itksys::SystemTools::SplitString(tempModPath.substr(0, tempModPath.size()), ' ', false);
// Remove " " string element
for(unsigned int i=0; i<pathAttribut.size(); i++)
{
// Suppress possible multi space at the beginning of the string
while (pathAttribut[i].size()>1 && pathAttribut[i][0]==' ')
{
pathAttribut[i].erase(0, 1);
}
std::string fullPath = itksys::SystemTools::CollapseFullPath(pathAttribut[i]);
if( !itksys::SystemTools::FileIsDirectory(fullPath) )
{
std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
return INVALIDMODULEPATH;
}
paths.push_back(fullPath);
}
}
else
{
return NOMODULEPATH;
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::vector<std::string> & exp )
{
if (exp.empty())
{
return NOMODULENAME;
}
itksys::RegularExpression reg;
reg.compile("([^0-9a-zA-Z])");
// The first element must be the module path, non " -" allowed.
if( exp[0][0] == '-')
{
return NOMODULENAME;
}
// It must contain only alphanumerical character
if(reg.find(exp[0]))
{
return INVALIDMODULENAME;
}
else
{
modName = exp[0];
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::string & exp )
{
std::vector<itksys::String> spaceSplitExp = itksys::SystemTools::SplitString(exp, ' ', false);
// if the chain is " module", SplitString will return: [ ], [module]
for(unsigned int i=0; i<spaceSplitExp.size(); i++)
{
if( spaceSplitExp[i] == " ")
{
spaceSplitExp.erase(spaceSplitExp.begin()+i);
i--;
}
}
// The SplitString keep the separator in the string.
// If exists a space a the beginning of the string, it will be interpreted...
// We have to delete it
if( spaceSplitExp[0][0] == ' ' )
{
spaceSplitExp[0].erase(spaceSplitExp[0].begin());
}
itksys::RegularExpression reg;
reg.compile("([^0-9a-zA-Z])");
// The first element must be the module path, non " -" allowed.
if( spaceSplitExp[0].substr(0, 2) == " -" || spaceSplitExp.size() == 0 )
{
return NOMODULENAME;
}
// It must contain only alphanumerical character
if(reg.find(spaceSplitExp[0]))
{
return INVALIDMODULENAME;
}
else
{
modName = spaceSplitExp[0];
}
return OK;
}
std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::vector<std::string> & exp )
{
std::vector<std::string> res;
if (!this->IsAttributExists(key,exp))
return res;
bool foundKey=false;
std::vector<std::string>::const_iterator it = exp.begin();
while(it!=exp.end() )
{
if (foundKey)
{
if (it->find("-") == 0)
{
std::string tmpKey = it->substr(1,std::string::npos);
if (this->IsAValidKey(tmpKey))
{
break;
}
else
{
res.push_back(*it);
}
}
else
res.push_back(*it);
}
else
{
if (it->compare(key) == 0)
{
foundKey=true;
}
}
++it;
}
return res;
}
std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::string & exp )
{
std::vector<std::string> res;
std::string keySpaced = key;
keySpaced.append(" ");
std::size_t found = std::string(exp).find(keySpaced);
if( found == std::string::npos )
{
return res;
}
std::string expFromKey = std::string(exp).substr(found+key.size()+1, std::string(exp).size());
if( expFromKey.size() == 0 )
{
return res;
}
std::string tempModKey = expFromKey;
// remove other key in the string if there's any
bool stop = false;
std::size_t curPos = expFromKey.find(" -");
std::size_t curPosOld = 0;
while ( !stop && curPos != std::string::npos )
{
std::string tmp = expFromKey.substr(curPosOld, curPos);
if( tmp.find(" ") != std::string::npos)
{
tmp = tmp.substr(0, tmp.find(" "));
}
if( this->IsAValidKey(tmp) )
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
else
{
if( curPosOld>1 )
{
if( expFromKey[curPos] != '-' )
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
}
else
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
}
curPosOld = curPos;
curPos = expFromKey.find(" -", curPos);
if(curPos!=std::string::npos)
curPos += 2;
}
// Only if the key has values associated
if( tempModKey.size() > 0 )
{
std::vector<itksys::String> spaceSplit = itksys::SystemTools::SplitString(tempModKey.substr(0, tempModKey.size()), ' ', false);
// Remove " " string element
for(unsigned int i=0; i<spaceSplit.size(); i++)
{
if( spaceSplit[i] == " ")
{
spaceSplit.erase(spaceSplit.begin()+i);
i--;
}
}
// Remove space at the beginning of the string and cast into std::vector<std::string>
for(unsigned int i=0; i<spaceSplit.size(); i++)
{
while( spaceSplit[i].size()>0 && spaceSplit[i][0] == ' ' )
{
spaceSplit[i] = spaceSplit[i].substr(1, spaceSplit[i].size());
}
res.push_back(spaceSplit[i]);
}
}
return res;
}
std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::vector<std::string> & exp )
{
std::string res("");
std::vector<std::string> values = this->GetAttribut( key, exp );
if( values.size() == 0 )
{
return "";
}
else if( values.size() == 1 && values[0] == " " )
{
return "";
}
for( unsigned int i=0; i<values.size(); i++)
{
if( i<values.size()-1 )
{
res.append(values[i]);
res.append(" ");
}
else
{
res.append(values[i]);
}
}
return res;
}
std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::string & exp )
{
std::string res("");
std::vector<std::string> values = this->GetAttribut( key, exp );
if( values.size() == 0 )
{
return "";
}
else if( values.size() == 1 && values[0] == " " )
{
return "";
}
for( unsigned int i=0; i<values.size(); i++)
{
if( i<values.size()-1 )
{
res.append(values[i]);
res.append(" ");
}
else
{
res.append(values[i]);
}
}
return res;
}
bool
CommandLineParser::IsAttributExists( const std::string key, const std::string & exp )
{
std::string keySpaced = key;
std::string expSpaced = exp;
// Add space to avoid troubles with key which starts by another one : -out and -outmax for example
keySpaced.append(" ");
expSpaced.append(" ");
std::size_t found = expSpaced.find(keySpaced);
return (found != std::string::npos);
}
bool
CommandLineParser::IsAttributExists( const std::string key, const std::vector<std::string> & exp )
{
for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
{
if (it->compare(key) == 0)
return true;
}
return false;
}
std::vector<std::string>
CommandLineParser::GetKeyList( const std::vector<std::string> & exp )
{
std::vector<std::string> keyList;
for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
{
if (it->find("-") == 0)
{
// Remove first character ('-')
std::string key = it->substr(1,std::string::npos);
if (this->IsAValidKey(key))
{
keyList.push_back(key);
}
}
}
return keyList;
}
std::vector<std::string>
CommandLineParser::GetKeyList( const std::string & exp )
{
std::vector<std::string> keyList;
std::string cutExp(exp);
std::size_t found = exp.find(" -");
while( found != std::string::npos )
{
// Suppress everything before the key
cutExp = cutExp.substr(found+2, exp.size());
// Search the end of the key (a space)
std::size_t foundSpace = cutExp.find(" ");
std::string tmpKey = cutExp;
if( foundSpace != std::string::npos )
{
tmpKey = cutExp.substr(0, foundSpace);
}
if( this->IsAValidKey(tmpKey) )
{
keyList.push_back( tmpKey );
}
// Search the next key (ie. " -")
found = cutExp.find(" -");
}
return keyList;
}
bool
CommandLineParser::IsAValidKey( const std::string & foundKey )
{
bool res = false;
std::string tmp = foundKey;
// make sure the tested key ends with a dot.
// the starting dash should be already removed
tmp.append(".");
// To be a key, the string must be a series of groups separated by dots so that :
// - each group has at least one character
// - each group contains only alphanumeric characters (and lowercase)
// - there is at least one group
// The following regular expression says just that
itksys::RegularExpression reg;
reg.compile("^([a-z0-9]+\\.)+$");
if( reg.find(tmp) )
{
res = true;
}
// a second test is performed to detect negative numbers (even in
// scientific notation). Any key that matches the search pattern for a
// number is considered not valid.
itksys::RegularExpression regNum;
regNum.compile("^([0-9]+(\\.[0-9]*)?([eE][+-]?[0-9]+)?)$");
if( regNum.find(foundKey) )
{
res = false;
}
return res;
}
}
}
|
/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperCommandLineParser.h"
#include "otbWrapperApplicationRegistry.h"
#include <itksys/SystemTools.hxx>
#include <itksys/RegularExpression.hxx>
#include <string>
#include <iostream>
namespace otb
{
namespace Wrapper
{
CommandLineParser::CommandLineParser()
{
}
CommandLineParser::~CommandLineParser()
{
}
std::string
CommandLineParser::GetPathsAsString(const std::vector<std::string> & vexp )
{
std::string res;
std::vector<std::string> pathList;
if (this->GetPaths(pathList,vexp) == OK)
{
std::vector<std::string>::iterator it;
for (it=pathList.begin(); it!=pathList.end(); ++it)
{
if (!res.empty())
{
res.append(" ");
}
res.append(*it);
}
}
return res;
}
std::string
CommandLineParser::GetPathsAsString( const std::string & exp )
{
std::string res;
// The first element must be the module path, non " -" allowed.
// The module path list element are the strings between the first
// element and the next key (ie. " -" string).
std::string tempModPath = exp;
if( exp.find(" -") != std::string::npos)
{
tempModPath = exp.substr( 0, exp.find(" -"));
}
// Get everything after the module path
if( tempModPath.find(" ") != std::string::npos)
{
res = tempModPath.substr( tempModPath.find(" ")+1, tempModPath.size());
}
// Suppress possible multi space at the beginning of the string
while (res.size()>0 && res[0]==' ')
{
res.erase(0, 1);
}
return res;
}
CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::vector<std::string> & exp )
{
if (exp.empty())
{
return NOMODULEPATH;
}
// The first element must be the module name, non " -" allowed.
// The module path list elements are the strings between the first
// element and the first key (ie. string which begins with "-").
std::vector<std::string>::const_iterator it = exp.begin();
++it; // first element is module name
std::string tmpPath;
while (it != exp.end())
{
tmpPath = *it;
// If this is the first key : exit loop
if (tmpPath[0]=='-')
{
break;
}
// Add path to result
std::string fullPath = itksys::SystemTools::CollapseFullPath(tmpPath);
if( !itksys::SystemTools::FileIsDirectory(fullPath) )
{
std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
return INVALIDMODULEPATH;
}
paths.push_back(fullPath);
++it;
}
if (paths.empty())
{
return NOMODULEPATH;
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetPaths( std::vector<std::string> & paths, const std::string & exp )
{
std::string pathsList = this->GetPathsAsString( exp );
if( pathsList.size() == 0 )
{
return NOMODULEPATH;
}
std::string tempModPath = pathsList;
// remove other key in the string if there's any
if( pathsList.find(" -") != std::string::npos)
{
tempModPath = pathsList.substr( 0, pathsList.find(" -"));
}
if( tempModPath.size() > 0 )
{
std::vector<itksys::String> pathAttribut = itksys::SystemTools::SplitString(tempModPath, ' ', false);
// Remove " " string element
for(unsigned int i=0; i<pathAttribut.size(); i++)
{
// Suppress possible multi space at the beginning of the string
while (pathAttribut[i].size()>1 && pathAttribut[i][0]==' ')
{
pathAttribut[i].erase(0, 1);
}
std::string fullPath = itksys::SystemTools::CollapseFullPath(pathAttribut[i]);
if( !itksys::SystemTools::FileIsDirectory(fullPath) )
{
std::cerr<<"Invalid module path: "<<fullPath<<std::endl;
return INVALIDMODULEPATH;
}
paths.push_back(fullPath);
}
}
else
{
return NOMODULEPATH;
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::vector<std::string> & exp )
{
if (exp.empty())
{
return NOMODULENAME;
}
itksys::RegularExpression reg;
reg.compile("([^0-9a-zA-Z])");
// The first element must be the module path, non " -" allowed.
if( exp[0][0] == '-')
{
return NOMODULENAME;
}
// It must contain only alphanumerical character
if(reg.find(exp[0]))
{
return INVALIDMODULENAME;
}
else
{
modName = exp[0];
}
return OK;
}
CommandLineParser::ParseResultType
CommandLineParser::GetModuleName( std::string & modName, const std::string & exp )
{
std::vector<itksys::String> spaceSplitExp = itksys::SystemTools::SplitString(exp, ' ', false);
// if the chain is " module", SplitString will return: [ ], [module]
for(unsigned int i=0; i<spaceSplitExp.size(); i++)
{
if( spaceSplitExp[i] == " ")
{
spaceSplitExp.erase(spaceSplitExp.begin()+i);
i--;
}
}
// The SplitString keep the separator in the string.
// If exists a space a the beginning of the string, it will be interpreted...
// We have to delete it
if( spaceSplitExp[0][0] == ' ' )
{
spaceSplitExp[0].erase(spaceSplitExp[0].begin());
}
itksys::RegularExpression reg;
reg.compile("([^0-9a-zA-Z])");
// The first element must be the module path, non " -" allowed.
if( spaceSplitExp[0].substr(0, 2) == " -" || spaceSplitExp.size() == 0 )
{
return NOMODULENAME;
}
// It must contain only alphanumerical character
if(reg.find(spaceSplitExp[0]))
{
return INVALIDMODULENAME;
}
else
{
modName = spaceSplitExp[0];
}
return OK;
}
std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::vector<std::string> & exp )
{
std::vector<std::string> res;
if (!this->IsAttributExists(key,exp))
return res;
bool foundKey=false;
std::vector<std::string>::const_iterator it = exp.begin();
while(it!=exp.end() )
{
if (foundKey)
{
if (it->find("-") == 0)
{
std::string tmpKey = it->substr(1,std::string::npos);
if (this->IsAValidKey(tmpKey))
{
break;
}
else
{
res.push_back(*it);
}
}
else
res.push_back(*it);
}
else
{
if (it->compare(key) == 0)
{
foundKey=true;
}
}
++it;
}
return res;
}
std::vector<std::string>
CommandLineParser::GetAttribut( const std::string & key, const std::string & exp )
{
std::vector<std::string> res;
std::string keySpaced = key;
keySpaced.append(" ");
std::size_t found = std::string(exp).find(keySpaced);
if( found == std::string::npos )
{
return res;
}
std::string expFromKey = std::string(exp).substr(found+key.size()+1, std::string(exp).size());
if( expFromKey.size() == 0 )
{
return res;
}
std::string tempModKey = expFromKey;
// remove other key in the string if there's any
bool stop = false;
std::size_t curPos = expFromKey.find(" -");
std::size_t curPosOld = 0;
while ( !stop && curPos != std::string::npos )
{
std::string tmp = expFromKey.substr(curPosOld, curPos);
if( tmp.find(" ") != std::string::npos)
{
tmp = tmp.substr(0, tmp.find(" "));
}
if( this->IsAValidKey(tmp) )
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
else
{
if( curPosOld>1 )
{
if( expFromKey[curPos] != '-' )
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
}
else
{
tempModKey = expFromKey.substr(0, curPos);
stop = true;
}
}
curPosOld = curPos;
curPos = expFromKey.find(" -", curPos);
if(curPos!=std::string::npos)
curPos += 2;
}
// Only if the key has values associated
if( tempModKey.size() > 0 )
{
std::vector<itksys::String> spaceSplit = itksys::SystemTools::SplitString(tempModKey.substr(0, tempModKey.size()), ' ', false);
// Remove " " string element
for(unsigned int i=0; i<spaceSplit.size(); i++)
{
if( spaceSplit[i] == " ")
{
spaceSplit.erase(spaceSplit.begin()+i);
i--;
}
}
// Remove space at the beginning of the string and cast into std::vector<std::string>
for(unsigned int i=0; i<spaceSplit.size(); i++)
{
while( spaceSplit[i].size()>0 && spaceSplit[i][0] == ' ' )
{
spaceSplit[i] = spaceSplit[i].substr(1, spaceSplit[i].size());
}
res.push_back(spaceSplit[i]);
}
}
return res;
}
std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::vector<std::string> & exp )
{
std::string res("");
std::vector<std::string> values = this->GetAttribut( key, exp );
if( values.size() == 0 )
{
return "";
}
else if( values.size() == 1 && values[0] == " " )
{
return "";
}
for( unsigned int i=0; i<values.size(); i++)
{
if( i<values.size()-1 )
{
res.append(values[i]);
res.append(" ");
}
else
{
res.append(values[i]);
}
}
return res;
}
std::string
CommandLineParser::GetAttributAsString( const std::string & key, const std::string & exp )
{
std::string res("");
std::vector<std::string> values = this->GetAttribut( key, exp );
if( values.size() == 0 )
{
return "";
}
else if( values.size() == 1 && values[0] == " " )
{
return "";
}
for( unsigned int i=0; i<values.size(); i++)
{
if( i<values.size()-1 )
{
res.append(values[i]);
res.append(" ");
}
else
{
res.append(values[i]);
}
}
return res;
}
bool
CommandLineParser::IsAttributExists( const std::string key, const std::string & exp )
{
std::string keySpaced = key;
std::string expSpaced = exp;
// Add space to avoid troubles with key which starts by another one : -out and -outmax for example
keySpaced.append(" ");
expSpaced.append(" ");
std::size_t found = expSpaced.find(keySpaced);
return (found != std::string::npos);
}
bool
CommandLineParser::IsAttributExists( const std::string key, const std::vector<std::string> & exp )
{
for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
{
if (it->compare(key) == 0)
return true;
}
return false;
}
std::vector<std::string>
CommandLineParser::GetKeyList( const std::vector<std::string> & exp )
{
std::vector<std::string> keyList;
for (std::vector<std::string>::const_iterator it = exp.begin(); it != exp.end(); ++it)
{
if (it->find("-") == 0)
{
// Remove first character ('-')
std::string key = it->substr(1,std::string::npos);
if (this->IsAValidKey(key))
{
keyList.push_back(key);
}
}
}
return keyList;
}
std::vector<std::string>
CommandLineParser::GetKeyList( const std::string & exp )
{
std::vector<std::string> keyList;
std::string cutExp(exp);
std::size_t found = exp.find(" -");
while( found != std::string::npos )
{
// Suppress everything before the key
cutExp = cutExp.substr(found+2, exp.size());
// Search the end of the key (a space)
std::size_t foundSpace = cutExp.find(" ");
std::string tmpKey = cutExp;
if( foundSpace != std::string::npos )
{
tmpKey = cutExp.substr(0, foundSpace);
}
if( this->IsAValidKey(tmpKey) )
{
keyList.push_back( tmpKey );
}
// Search the next key (ie. " -")
found = cutExp.find(" -");
}
return keyList;
}
bool
CommandLineParser::IsAValidKey( const std::string & foundKey )
{
bool res = false;
std::string tmp = foundKey;
// make sure the tested key ends with a dot.
// the starting dash should be already removed
tmp.append(".");
// To be a key, the string must be a series of groups separated by dots so that :
// - each group has at least one character
// - each group contains only alphanumeric characters (and lowercase)
// - there is at least one group
// The following regular expression says just that
itksys::RegularExpression reg;
reg.compile("^([a-z0-9]+\\.)+$");
if( reg.find(tmp) )
{
res = true;
}
// a second test is performed to detect negative numbers (even in
// scientific notation). Any key that matches the search pattern for a
// number is considered not valid.
itksys::RegularExpression regNum;
regNum.compile("^([0-9]+(\\.[0-9]*)?([eE][+-]?[0-9]+)?)$");
if( regNum.find(foundKey) )
{
res = false;
}
return res;
}
}
}
|
remove useless substr
|
BUG: remove useless substr
|
C++
|
apache-2.0
|
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
|
a4a82b769c8a11aef3936f29d2986edd2fe315f9
|
src/gear/speller.cc
|
src/gear/speller.cc
|
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-27 GONG Chen <[email protected]>
//
#include <rime/candidate.h>
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/key_table.h>
#include <rime/menu.h>
#include <rime/schema.h>
#include <rime/gear/speller.h>
static const char kRimeAlphabet[] = "zyxwvutsrqponmlkjihgfedcba";
namespace rime {
static bool is_auto_selectable(const shared_ptr<Candidate>& cand,
const std::string& input,
const std::string& delimiters) {
return cand->end() == input.length() && // reaches end of input
cand->type() == "table" && // is table entry
input.find_first_of(delimiters, cand->start()) == std::string::npos;
// no delimiters
}
Speller::Speller(Engine *engine) : Processor(engine),
alphabet_(kRimeAlphabet),
max_code_length_(0),
auto_select_(false),
auto_select_unique_candidate_(false) {
Config *config = engine->schema()->config();
if (config) {
config->GetString("speller/alphabet", &alphabet_);
config->GetString("speller/delimiter", &delimiter_);
config->GetString("speller/initials", &initials_);
config->GetInt("speller/max_code_length", &max_code_length_);
config->GetBool("speller/auto_select", &auto_select_);
if (!config->GetBool("speller/auto_select_unique_candidate",
&auto_select_unique_candidate_)) {
auto_select_unique_candidate_ = auto_select_;
}
}
if (initials_.empty()) initials_ = alphabet_;
}
Processor::Result Speller::ProcessKeyEvent(
const KeyEvent &key_event) {
if (key_event.release() || key_event.ctrl() || key_event.alt() ||
key_event.keycode() == XK_space)
return kNoop;
int ch = key_event.keycode();
if (ch <= 0x20 || ch >= 0x7f) // not a valid key for spelling
return kNoop;
Context *ctx = engine_->context();
if (ctx->IsComposing()) {
bool is_letter = alphabet_.find(ch) != std::string::npos;
bool is_delimiter = delimiter_.find(ch) != std::string::npos;
if (!is_letter && !is_delimiter)
return kNoop;
if (is_letter && // a letter may cause auto-select
max_code_length_ > 0 && // at a fixed code length
ctx->HasMenu()) {
const Segment& seg(ctx->composition()->back());
const shared_ptr<Candidate> cand = seg.GetSelectedCandidate();
if (cand) {
int code_length = static_cast<int>(cand->end() - cand->start());
if (code_length == max_code_length_ && // exceeds max code length
is_auto_selectable(cand, ctx->input(), delimiter_)) {
ctx->ConfirmCurrentSelection();
}
}
}
}
else {
if (initials_.find(ch) == std::string::npos)
return kNoop;
}
Segment previous_segment;
if (auto_select_ && ctx->HasMenu()) {
previous_segment = ctx->composition()->back();
}
DLOG(INFO) << "add to input: '" << (char)ch << "', " << key_event.repr();
ctx->PushInput(key_event.keycode());
ctx->ConfirmPreviousSelection(); // so that next BackSpace won't revert
// previous selection
if (auto_select_unique_candidate_ && ctx->HasMenu()) {
const Segment& seg(ctx->composition()->back());
bool unique_candidate = seg.menu->Prepare(2) == 1;
if (unique_candidate &&
is_auto_selectable(seg.GetSelectedCandidate(),
ctx->input(), delimiter_)) {
DLOG(INFO) << "auto-select unique candidate.";
ctx->ConfirmCurrentSelection();
}
}
if (auto_select_ && !ctx->HasMenu() && previous_segment.menu) {
if (is_auto_selectable(previous_segment.GetSelectedCandidate(),
ctx->input().substr(0, previous_segment.end),
delimiter_)) {
DLOG(INFO) << "auto-select previous word";
ctx->composition()->pop_back();
ctx->composition()->push_back(previous_segment);
ctx->ConfirmCurrentSelection();
}
}
return kAccepted;
}
} // namespace rime
|
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-10-27 GONG Chen <[email protected]>
//
#include <rime/candidate.h>
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/key_table.h>
#include <rime/menu.h>
#include <rime/schema.h>
#include <rime/gear/speller.h>
static const char kRimeAlphabet[] = "zyxwvutsrqponmlkjihgfedcba";
namespace rime {
static bool is_auto_selectable(const shared_ptr<Candidate>& cand,
const std::string& input,
const std::string& delimiters) {
return cand->end() == input.length() && // reaches end of input
cand->type() == "table" && // is table entry
input.find_first_of(delimiters, cand->start()) == std::string::npos;
// no delimiters
}
Speller::Speller(Engine *engine) : Processor(engine),
alphabet_(kRimeAlphabet),
max_code_length_(0),
auto_select_(false),
auto_select_unique_candidate_(false) {
Config *config = engine->schema()->config();
if (config) {
config->GetString("speller/alphabet", &alphabet_);
config->GetString("speller/delimiter", &delimiter_);
config->GetString("speller/initials", &initials_);
config->GetInt("speller/max_code_length", &max_code_length_);
config->GetBool("speller/auto_select", &auto_select_);
if (!config->GetBool("speller/auto_select_unique_candidate",
&auto_select_unique_candidate_)) {
auto_select_unique_candidate_ = auto_select_;
}
}
if (initials_.empty()) initials_ = alphabet_;
}
Processor::Result Speller::ProcessKeyEvent(
const KeyEvent &key_event) {
if (key_event.release() || key_event.ctrl() || key_event.alt() ||
key_event.keycode() == XK_space)
return kNoop;
int ch = key_event.keycode();
if (ch <= 0x20 || ch >= 0x7f) // not a valid key for spelling
return kNoop;
Context *ctx = engine_->context();
if (ctx->IsComposing()) {
bool is_letter = alphabet_.find(ch) != std::string::npos;
bool is_delimiter = delimiter_.find(ch) != std::string::npos;
if (!is_letter && !is_delimiter)
return kNoop;
if (is_letter && // a letter may cause auto-select
max_code_length_ > 0 && // at a fixed code length
ctx->HasMenu()) {
const Segment& seg(ctx->composition()->back());
const shared_ptr<Candidate> cand = seg.GetSelectedCandidate();
if (cand) {
int code_length = static_cast<int>(cand->end() - cand->start());
if (code_length == max_code_length_ && // exceeds max code length
is_auto_selectable(cand, ctx->input(), delimiter_)) {
ctx->ConfirmCurrentSelection();
}
}
}
}
else {
if (initials_.find(ch) == std::string::npos)
return kNoop;
}
Segment previous_segment;
if (auto_select_ && ctx->HasMenu()) {
previous_segment = ctx->composition()->back();
}
DLOG(INFO) << "add to input: '" << (char)ch << "', " << key_event.repr();
ctx->PushInput(key_event.keycode());
ctx->ConfirmPreviousSelection(); // so that next BackSpace won't revert
// previous selection
if (auto_select_unique_candidate_ && ctx->HasMenu()) {
const Segment& seg(ctx->composition()->back());
bool unique_candidate = seg.menu->Prepare(2) == 1;
if (unique_candidate &&
is_auto_selectable(seg.GetSelectedCandidate(),
ctx->input(), delimiter_)) {
DLOG(INFO) << "auto-select unique candidate.";
ctx->ConfirmCurrentSelection();
return kAccepted;
}
}
if (auto_select_ && !ctx->HasMenu() && previous_segment.menu) {
if (is_auto_selectable(previous_segment.GetSelectedCandidate(),
ctx->input().substr(0, previous_segment.end),
delimiter_)) {
DLOG(INFO) << "auto-select previous word";
ctx->composition()->pop_back();
ctx->composition()->push_back(previous_segment);
ctx->ConfirmCurrentSelection();
return kAccepted;
}
}
return kAccepted;
}
} // namespace rime
|
enable auto-committing unique candidate in fluency_editor.
|
speller: enable auto-committing unique candidate in fluency_editor.
|
C++
|
bsd-3-clause
|
jakwings/librime,jakwings/librime,rwduzhao/librime,bygloam/librime,rime/librime,rime/librime,kionz/librime,Prcuvu/librime,rwduzhao/librime,rime/librime,rwduzhao/librime,Prcuvu/librime,kionz/librime,kionz/librime,Prcuvu/librime,Prcuvu/librime,rime/librime,j717273419/librime,bygloam/librime,jakwings/librime,j717273419/librime,j717273419/librime,kionz/librime,bygloam/librime,Prcuvu/librime
|
8d8847521e9a077d1c317c622dd76d7e8087d3bd
|
samplecode/TransitionView.cpp
|
samplecode/TransitionView.cpp
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
extern bool is_overview(SkView* view);
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
static bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+500, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
// FIXME: this should go in a header
SkView* create_transition(SkView* prev, SkView* next, int direction);
SkView* create_transition(SkView* prev, SkView* next, int direction) {
return SkNEW_ARGS(TransitionView, (prev, next, direction));
};
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkTime.h"
#include "SkInterpolator.h"
extern bool is_overview(SkView* view);
static const char gIsTransitionQuery[] = "is-transition";
static const char gReplaceTransitionEvt[] = "replace-transition-view";
static bool is_transition(SkView* view) {
SkEvent isTransition(gIsTransitionQuery);
return view->doQuery(&isTransition);
}
class TransitionView : public SampleView {
enum {
// kDurationMS = 500
kDurationMS = 1
};
public:
TransitionView(SkView* prev, SkView* next, int direction) : fInterp(4, 2){
fAnimationDirection = (Direction)(1 << (direction % 8));
fPrev = prev;
fPrev->setClipToBounds(false);
fPrev->setVisibleP(true);
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//Not calling unref because fPrev is assumed to have been created, so
//this will result in a transfer of ownership
this->attachChildToBack(fPrev);
fNext = next;
fNext->setClipToBounds(true);
fNext->setVisibleP(true);
(void)SampleView::SetUsePipe(fNext, SkOSMenu::kOffState);
//Calling unref because next is a newly created view and TransitionView
//is now the sole owner of fNext
this->attachChildToFront(fNext)->unref();
fDone = false;
//SkDebugf("--created transition\n");
}
~TransitionView(){
//SkDebugf("--deleted transition\n");
}
virtual void requestMenu(SkOSMenu* menu) {
if (SampleView::IsSampleView(fNext))
((SampleView*)fNext)->requestMenu(menu);
}
protected:
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString title;
if (SampleCode::RequestTitle(fNext, &title)) {
SampleCode::TitleR(evt, title.c_str());
return true;
}
return false;
}
if (evt->isType(gIsTransitionQuery)) {
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual bool onEvent(const SkEvent& evt) {
if (evt.isType(gReplaceTransitionEvt)) {
fPrev->detachFromParent();
fPrev = (SkView*)SkEventSink::FindSink(evt.getFast32());
(void)SampleView::SetUsePipe(fPrev, SkOSMenu::kOffState);
//attach the new fPrev and call unref to balance the ref in onDraw
this->attachChildToBack(fPrev)->unref();
this->inval(NULL);
return true;
}
if (evt.isType("transition-done")) {
fNext->setLoc(0, 0);
fNext->setClipToBounds(false);
SkEvent* evt = new SkEvent(gReplaceTransitionEvt,
this->getParent()->getSinkID());
evt->setFast32(fNext->getSinkID());
//increate ref count of fNext so it survives detachAllChildren
fNext->ref();
this->detachAllChildren();
evt->post();
return true;
}
return this->INHERITED::onEvent(evt);
}
virtual void onDrawBackground(SkCanvas* canvas) {}
virtual void onDrawContent(SkCanvas* canvas) {
if (fDone)
return;
if (is_overview(fNext) || is_overview(fPrev)) {
fPipeState = SkOSMenu::kOffState;
}
SkScalar values[4];
SkInterpolator::Result result = fInterp.timeToValues(SkTime::GetMSecs(), values);
//SkDebugf("transition %x %d pipe:%d\n", this, result, fUsePipe);
//SkDebugf("%f %f %f %f %d\n", values[0], values[1], values[2], values[3], result);
if (SkInterpolator::kNormal_Result == result) {
fPrev->setLocX(values[kPrevX]);
fPrev->setLocY(values[kPrevY]);
fNext->setLocX(values[kNextX]);
fNext->setLocY(values[kNextY]);
this->inval(NULL);
}
else {
(new SkEvent("transition-done", this->getSinkID()))->post();
fDone = true;
}
}
virtual void onSizeChange() {
this->INHERITED::onSizeChange();
fNext->setSize(this->width(), this->height());
fPrev->setSize(this->width(), this->height());
SkScalar lr = 0, ud = 0;
if (fAnimationDirection & (kLeftDirection|kULDirection|kDLDirection))
lr = this->width();
if (fAnimationDirection & (kRightDirection|kURDirection|kDRDirection))
lr = -this->width();
if (fAnimationDirection & (kUpDirection|kULDirection|kURDirection))
ud = this->height();
if (fAnimationDirection & (kDownDirection|kDLDirection|kDRDirection))
ud = -this->height();
fBegin[kPrevX] = fBegin[kPrevY] = 0;
fBegin[kNextX] = lr;
fBegin[kNextY] = ud;
fNext->setLocX(lr);
fNext->setLocY(ud);
if (is_transition(fPrev))
lr = ud = 0;
fEnd[kPrevX] = -lr;
fEnd[kPrevY] = -ud;
fEnd[kNextX] = fEnd[kNextY] = 0;
SkScalar blend[] = { SkFloatToScalar(0.8f), SkFloatToScalar(0.0f),
SkFloatToScalar(0.0f), SK_Scalar1 };
fInterp.setKeyFrame(0, SkTime::GetMSecs(), fBegin, blend);
fInterp.setKeyFrame(1, SkTime::GetMSecs()+kDurationMS, fEnd, blend);
}
private:
enum {
kPrevX = 0,
kPrevY = 1,
kNextX = 2,
kNextY = 3
};
SkView* fPrev;
SkView* fNext;
bool fDone;
SkInterpolator fInterp;
enum Direction{
kUpDirection = 1,
kURDirection = 1 << 1,
kRightDirection = 1 << 2,
kDRDirection = 1 << 3,
kDownDirection = 1 << 4,
kDLDirection = 1 << 5,
kLeftDirection = 1 << 6,
kULDirection = 1 << 7
};
Direction fAnimationDirection;
SkScalar fBegin[4];
SkScalar fEnd[4];
typedef SampleView INHERITED;
};
// FIXME: this should go in a header
SkView* create_transition(SkView* prev, SkView* next, int direction);
SkView* create_transition(SkView* prev, SkView* next, int direction) {
return SkNEW_ARGS(TransitionView, (prev, next, direction));
};
|
change duration of transition animation to 1, effectively removing it (for now)
|
change duration of transition animation to 1, effectively removing it (for now)
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@5450 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
AsteroidOS/android_external_skia,amyvmiwei/skia,MinimalOS/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,BrokenROM/external_skia,google/skia,MinimalOS/android_external_skia,ench0/external_skia,geekboxzone/lollipop_external_skia,YUPlayGodDev/platform_external_skia,MinimalOS/external_skia,larsbergstrom/skia,sombree/android_external_skia,zhaochengw/platform_external_skia,akiss77/skia,CyanogenMod/android_external_chromium_org_third_party_skia,ench0/external_skia,zhaochengw/platform_external_skia,ominux/skia,ctiao/platform-external-skia,vanish87/skia,SlimSaber/android_external_skia,YUPlayGodDev/platform_external_skia,jtg-gg/skia,FusionSP/android_external_skia,mydongistiny/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,invisiblek/android_external_skia,Khaon/android_external_skia,AOSPU/external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,nfxosp/platform_external_skia,vvuk/skia,android-ia/platform_external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,Infinitive-OS/platform_external_skia,FusionSP/android_external_skia,ench0/external_skia,sudosurootdev/external_skia,Infusion-OS/android_external_skia,chenlian2015/skia_from_google,F-AOSP/platform_external_skia,sigysmund/platform_external_skia,GladeRom/android_external_skia,F-AOSP/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,sombree/android_external_skia,TeslaProject/external_skia,AOSPU/external_chromium_org_third_party_skia,MonkeyZZZZ/platform_external_skia,nox/skia,TeamEOS/external_chromium_org_third_party_skia,aospo/platform_external_skia,MonkeyZZZZ/platform_external_skia,VRToxin-AOSP/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,noselhq/skia,MinimalOS/external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,SlimSaber/android_external_skia,YUPlayGodDev/platform_external_skia,FusionSP/android_external_skia,chenlian2015/skia_from_google,Hybrid-Rom/external_skia,MinimalOS/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,UBERMALLOW/external_skia,PAC-ROM/android_external_skia,android-ia/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MarshedOut/android_external_skia,sudosurootdev/external_skia,PAC-ROM/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,nfxosp/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,Hybrid-Rom/external_skia,F-AOSP/platform_external_skia,todotodoo/skia,qrealka/skia-hc,Plain-Andy/android_platform_external_skia,geekboxzone/mmallow_external_skia,timduru/platform-external-skia,OptiPop/external_skia,boulzordev/android_external_skia,ominux/skia,Euphoria-OS-Legacy/android_external_skia,mmatyas/skia,android-ia/platform_external_chromium_org_third_party_skia,samuelig/skia,MIPS/external-chromium_org-third_party-skia,TeslaProject/external_skia,zhaochengw/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,xin3liang/platform_external_chromium_org_third_party_skia,Igalia/skia,AOSPB/external_skia,Fusion-Rom/android_external_skia,Omegaphora/external_skia,mydongistiny/android_external_skia,zhaochengw/platform_external_skia,vvuk/skia,Hybrid-Rom/external_skia,Khaon/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamExodus/external_skia,F-AOSP/platform_external_skia,pcwalton/skia,RadonX-ROM/external_skia,sigysmund/platform_external_skia,SlimSaber/android_external_skia,Khaon/android_external_skia,google/skia,ominux/skia,shahrzadmn/skia,VRToxin-AOSP/android_external_skia,sudosurootdev/external_skia,MinimalOS/android_external_skia,vvuk/skia,TeamBliss-LP/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,AOSPA-L/android_external_skia,Euphoria-OS-Legacy/android_external_skia,RadonX-ROM/external_skia,SlimSaber/android_external_skia,PAC-ROM/android_external_skia,TeamExodus/external_skia,TeslaOS/android_external_skia,Pure-Aosp/android_external_skia,TeamEOS/external_skia,mmatyas/skia,InfinitiveOS/external_skia,sigysmund/platform_external_skia,MinimalOS-AOSP/platform_external_skia,Asteroid-Project/android_external_skia,Hikari-no-Tenshi/android_external_skia,wildermason/external_skia,MarshedOut/android_external_skia,boulzordev/android_external_skia,Samsung/skia,Tesla-Redux/android_external_skia,AOSPA-L/android_external_skia,nvoron23/skia,amyvmiwei/skia,Tesla-Redux/android_external_skia,FusionSP/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,tmpvar/skia.cc,vanish87/skia,Asteroid-Project/android_external_skia,nox/skia,akiss77/skia,AsteroidOS/android_external_skia,invisiblek/android_external_skia,PAC-ROM/android_external_skia,NamelessRom/android_external_skia,mozilla-b2g/external_skia,TeamEOS/external_skia,MinimalOS/android_external_skia,byterom/android_external_skia,AOSP-YU/platform_external_skia,amyvmiwei/skia,SlimSaber/android_external_skia,FusionSP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,Purity-Lollipop/platform_external_skia,DesolationStaging/android_external_skia,InfinitiveOS/external_skia,OptiPop/external_skia,shahrzadmn/skia,rubenvb/skia,HalCanary/skia-hc,PAC-ROM/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,MinimalOS-AOSP/platform_external_skia,VRToxin-AOSP/android_external_skia,TeamTwisted/external_skia,akiss77/skia,nvoron23/skia,AOSPA-L/android_external_skia,MIPS/external-chromium_org-third_party-skia,jtg-gg/skia,TeslaProject/external_skia,aospo/platform_external_skia,amyvmiwei/skia,HalCanary/skia-hc,TeamEOS/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,ench0/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,Igalia/skia,vanish87/skia,F-AOSP/platform_external_skia,VentureROM-L/android_external_skia,AOSPU/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,YUPlayGodDev/platform_external_skia,FusionSP/android_external_skia,timduru/platform-external-skia,Android-AOSP/external_skia,aosp-mirror/platform_external_skia,jtg-gg/skia,sudosurootdev/external_skia,AOSPU/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,AndroidOpenDevelopment/android_external_skia,Hikari-no-Tenshi/android_external_skia,OptiPop/external_skia,android-ia/platform_external_skia,sombree/android_external_skia,nox/skia,pcwalton/skia,nox/skia,android-ia/platform_external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,OneRom/external_skia,MIPS/external-chromium_org-third_party-skia,HalCanary/skia-hc,Tesla-Redux/android_external_skia,Infinitive-OS/platform_external_skia,ench0/external_skia,HalCanary/skia-hc,AndroidOpenDevelopment/android_external_skia,temasek/android_external_skia,MinimalOS/external_skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,todotodoo/skia,invisiblek/android_external_skia,scroggo/skia,Plain-Andy/android_platform_external_skia,AOSPA-L/android_external_skia,AndroidOpenDevelopment/android_external_skia,MIPS/external-chromium_org-third_party-skia,ctiao/platform-external-skia,nvoron23/skia,FusionSP/android_external_skia,w3nd1go/android_external_skia,TeamExodus/external_skia,TeslaOS/android_external_skia,Plain-Andy/android_platform_external_skia,xzzz9097/android_external_skia,PAC-ROM/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,MinimalOS/external_chromium_org_third_party_skia,mydongistiny/external_chromium_org_third_party_skia,ench0/external_chromium_org_third_party_skia,TeslaOS/android_external_skia,OneRom/external_skia,tmpvar/skia.cc,wildermason/external_skia,qrealka/skia-hc,NamelessRom/android_external_skia,vanish87/skia,android-ia/platform_external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,ominux/skia,noselhq/skia,chenlian2015/skia_from_google,geekboxzone/lollipop_external_chromium_org_third_party_skia,nox/skia,xzzz9097/android_external_skia,DesolationStaging/android_external_skia,VentureROM-L/android_external_skia,aosp-mirror/platform_external_skia,Android-AOSP/external_skia,geekboxzone/mmallow_external_skia,vvuk/skia,OneRom/external_skia,Pure-Aosp/android_external_skia,MinimalOS/android_external_skia,Euphoria-OS-Legacy/android_external_skia,samuelig/skia,temasek/android_external_skia,shahrzadmn/skia,vvuk/skia,Infinitive-OS/platform_external_skia,codeaurora-unoffical/platform-external-skia,larsbergstrom/skia,nvoron23/skia,NamelessRom/android_external_skia,timduru/platform-external-skia,TeamEOS/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,MarshedOut/android_external_skia,MarshedOut/android_external_skia,Android-AOSP/external_skia,Euphoria-OS-Legacy/android_external_skia,MarshedOut/android_external_skia,DesolationStaging/android_external_skia,Infusion-OS/android_external_skia,Infinitive-OS/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,Omegaphora/external_skia,sigysmund/platform_external_skia,MarshedOut/android_external_skia,OptiPop/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,w3nd1go/android_external_skia,Pure-Aosp/android_external_skia,codeaurora-unoffical/platform-external-skia,AOSPA-L/android_external_skia,Pure-Aosp/android_external_skia,houst0nn/external_skia,boulzordev/android_external_skia,TeamTwisted/external_skia,suyouxin/android_external_skia,HalCanary/skia-hc,mmatyas/skia,HalCanary/skia-hc,MinimalOS/android_external_skia,Jichao/skia,android-ia/platform_external_chromium_org_third_party_skia,Euphoria-OS-Legacy/android_external_skia,tmpvar/skia.cc,Igalia/skia,nox/skia,invisiblek/android_external_skia,UBERMALLOW/external_skia,RadonX-ROM/external_skia,fire855/android_external_skia,akiss77/skia,tmpvar/skia.cc,boulzordev/android_external_skia,tmpvar/skia.cc,AOSP-YU/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,sigysmund/platform_external_skia,qrealka/skia-hc,google/skia,DiamondLovesYou/skia-sys,fire855/android_external_skia,Igalia/skia,vvuk/skia,AOSP-YU/platform_external_skia,timduru/platform-external-skia,Jichao/skia,mmatyas/skia,Samsung/skia,Euphoria-OS-Legacy/android_external_skia,chenlian2015/skia_from_google,MarshedOut/android_external_skia,mmatyas/skia,akiss77/skia,ench0/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,TeamExodus/external_skia,temasek/android_external_skia,mmatyas/skia,Fusion-Rom/android_external_skia,geekboxzone/mmallow_external_skia,Android-AOSP/external_skia,fire855/android_external_skia,BrokenROM/external_skia,BrokenROM/external_skia,HalCanary/skia-hc,Asteroid-Project/android_external_skia,AOSP-YU/platform_external_skia,w3nd1go/android_external_skia,qrealka/skia-hc,geekboxzone/mmallow_external_skia,ench0/external_chromium_org_third_party_skia,ench0/external_skia,fire855/android_external_skia,qrealka/skia-hc,nvoron23/skia,MyAOSP/external_chromium_org_third_party_skia,timduru/platform-external-skia,MyAOSP/external_chromium_org_third_party_skia,noselhq/skia,TeamTwisted/external_skia,NamelessRom/android_external_skia,NamelessRom/android_external_skia,suyouxin/android_external_skia,pcwalton/skia,InfinitiveOS/external_skia,w3nd1go/android_external_skia,vvuk/skia,Infusion-OS/android_external_skia,Pure-Aosp/android_external_skia,TeamBliss-LP/android_external_skia,MinimalOS-AOSP/platform_external_skia,w3nd1go/android_external_skia,scroggo/skia,MinimalOS-AOSP/platform_external_skia,byterom/android_external_skia,codeaurora-unoffical/platform-external-skia,Tesla-Redux/android_external_skia,MinimalOS/external_skia,suyouxin/android_external_skia,pcwalton/skia,GladeRom/android_external_skia,pcwalton/skia,fire855/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,temasek/android_external_skia,TeamExodus/external_skia,temasek/android_external_skia,pacerom/external_skia,nvoron23/skia,ench0/external_skia,Jichao/skia,rubenvb/skia,Fusion-Rom/android_external_skia,aospo/platform_external_skia,vanish87/skia,timduru/platform-external-skia,VRToxin-AOSP/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,pcwalton/skia,pacerom/external_skia,MonkeyZZZZ/platform_external_skia,ench0/external_skia,amyvmiwei/skia,DARKPOP/external_chromium_org_third_party_skia,shahrzadmn/skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,Omegaphora/external_skia,AOSPU/external_chromium_org_third_party_skia,rubenvb/skia,boulzordev/android_external_skia,geekboxzone/mmallow_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_skia,Tesla-Redux/android_external_skia,scroggo/skia,qrealka/skia-hc,android-ia/platform_external_skia,scroggo/skia,ominux/skia,rubenvb/skia,ctiao/platform-external-skia,mozilla-b2g/external_skia,MyAOSP/external_chromium_org_third_party_skia,FusionSP/external_chromium_org_third_party_skia,TeslaProject/external_skia,sombree/android_external_skia,larsbergstrom/skia,nfxosp/platform_external_skia,larsbergstrom/skia,Plain-Andy/android_platform_external_skia,Omegaphora/external_skia,sudosurootdev/external_skia,Fusion-Rom/android_external_skia,geekboxzone/lollipop_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,InfinitiveOS/external_skia,OneRom/external_skia,rubenvb/skia,Omegaphora/external_chromium_org_third_party_skia,AOSPB/external_skia,mydongistiny/android_external_skia,MinimalOS/android_external_skia,TeamEOS/external_skia,FusionSP/external_chromium_org_third_party_skia,wildermason/external_skia,android-ia/platform_external_skia,Hikari-no-Tenshi/android_external_skia,F-AOSP/platform_external_skia,Infusion-OS/android_external_skia,HealthyHoney/temasek_SKIA,sudosurootdev/external_skia,mydongistiny/android_external_skia,BrokenROM/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,larsbergstrom/skia,nvoron23/skia,Fusion-Rom/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,geekboxzone/mmallow_external_skia,TeslaOS/android_external_skia,MinimalOS-AOSP/platform_external_skia,TeamEOS/external_skia,spezi77/android_external_skia,samuelig/skia,Khaon/android_external_skia,scroggo/skia,xin3liang/platform_external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,Omegaphora/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,houst0nn/external_skia,suyouxin/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,TeslaProject/external_skia,HalCanary/skia-hc,MinimalOS/external_skia,DesolationStaging/android_external_skia,samuelig/skia,xin3liang/platform_external_chromium_org_third_party_skia,Omegaphora/external_skia,FusionSP/android_external_skia,AsteroidOS/android_external_skia,VentureROM-L/android_external_skia,MIPS/external-chromium_org-third_party-skia,VRToxin-AOSP/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,MinimalOS-AOSP/platform_external_skia,TeamExodus/external_skia,HealthyHoney/temasek_SKIA,samuelig/skia,zhaochengw/platform_external_skia,pcwalton/skia,Hikari-no-Tenshi/android_external_skia,VRToxin-AOSP/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,sigysmund/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,BrokenROM/external_skia,noselhq/skia,akiss77/skia,OneRom/external_skia,OneRom/external_skia,Jichao/skia,vanish87/skia,mydongistiny/android_external_skia,GladeRom/android_external_skia,OptiPop/external_skia,mydongistiny/external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,wildermason/external_skia,F-AOSP/platform_external_skia,Samsung/skia,geekboxzone/lollipop_external_skia,todotodoo/skia,todotodoo/skia,suyouxin/android_external_skia,GladeRom/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,ench0/external_chromium_org_third_party_skia,MonkeyZZZZ/platform_external_skia,xzzz9097/android_external_skia,AOSPA-L/android_external_skia,wildermason/external_skia,MIPS/external-chromium_org-third_party-skia,TeamEOS/external_skia,mozilla-b2g/external_skia,Fusion-Rom/android_external_skia,vanish87/skia,pacerom/external_skia,houst0nn/external_skia,Purity-Lollipop/platform_external_skia,rubenvb/skia,Purity-Lollipop/platform_external_skia,Khaon/android_external_skia,larsbergstrom/skia,InfinitiveOS/external_skia,sombree/android_external_skia,shahrzadmn/skia,Purity-Lollipop/platform_external_skia,shahrzadmn/skia,MinimalOS/external_chromium_org_third_party_skia,ominux/skia,DiamondLovesYou/skia-sys,AOSPB/external_skia,spezi77/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,Jichao/skia,codeaurora-unoffical/platform-external-skia,HealthyHoney/temasek_SKIA,ctiao/platform-external-skia,MonkeyZZZZ/platform_external_skia,invisiblek/android_external_skia,google/skia,Omegaphora/external_chromium_org_third_party_skia,aospo/platform_external_skia,TeamBliss-LP/android_external_skia,Samsung/skia,CyanogenMod/android_external_chromium_org_third_party_skia,TeamEOS/external_skia,todotodoo/skia,AOSPU/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,spezi77/android_external_skia,Android-AOSP/external_skia,xin3liang/platform_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,TeamBliss-LP/android_external_skia,w3nd1go/android_external_skia,vvuk/skia,codeaurora-unoffical/platform-external-skia,aosp-mirror/platform_external_skia,pacerom/external_skia,Fusion-Rom/external_chromium_org_third_party_skia,SlimSaber/android_external_skia,byterom/android_external_skia,DesolationStaging/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,aospo/platform_external_skia,larsbergstrom/skia,todotodoo/skia,DesolationStaging/android_external_skia,nfxosp/platform_external_skia,xzzz9097/android_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,noselhq/skia,nox/skia,Android-AOSP/external_skia,Samsung/skia,TeslaProject/external_skia,Hybrid-Rom/external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,scroggo/skia,boulzordev/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,Igalia/skia,sigysmund/platform_external_skia,Omegaphora/external_skia,Euphoria-OS-Legacy/android_external_skia,Fusion-Rom/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,byterom/android_external_skia,boulzordev/android_external_skia,houst0nn/external_skia,larsbergstrom/skia,geekboxzone/mmallow_external_skia,amyvmiwei/skia,sudosurootdev/external_skia,OptiPop/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,SlimSaber/android_external_skia,HalCanary/skia-hc,PAC-ROM/android_external_skia,MinimalOS-AOSP/platform_external_skia,PAC-ROM/android_external_skia,Khaon/android_external_skia,vvuk/skia,DiamondLovesYou/skia-sys,DARKPOP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,temasek/android_external_skia,rubenvb/skia,todotodoo/skia,Infinitive-OS/platform_external_skia,TeamTwisted/external_skia,samuelig/skia,geekboxzone/lollipop_external_skia,mydongistiny/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,google/skia,OneRom/external_skia,AOSPA-L/android_external_skia,TeamTwisted/external_skia,xzzz9097/android_external_skia,Omegaphora/external_skia,Asteroid-Project/android_external_skia,invisiblek/android_external_skia,AndroidOpenDevelopment/android_external_skia,GladeRom/android_external_skia,MyAOSP/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,temasek/android_external_skia,spezi77/android_external_skia,VRToxin-AOSP/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,GladeRom/android_external_skia,AOSP-YU/platform_external_skia,TeamTwisted/external_skia,BrokenROM/external_skia,vanish87/skia,MinimalOS/android_external_chromium_org_third_party_skia,AsteroidOS/android_external_skia,shahrzadmn/skia,google/skia,noselhq/skia,BrokenROM/external_skia,OptiPop/external_skia,TeamBliss-LP/android_external_skia,Hikari-no-Tenshi/android_external_skia,NamelessRom/android_external_skia,VentureROM-L/android_external_skia,OptiPop/external_skia,TeamExodus/external_skia,Hikari-no-Tenshi/android_external_skia,mozilla-b2g/external_skia,OptiPop/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,pcwalton/skia,qrealka/skia-hc,android-ia/platform_external_skia,nfxosp/platform_external_skia,Jichao/skia,Omegaphora/external_chromium_org_third_party_skia,amyvmiwei/skia,Fusion-Rom/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,google/skia,nfxosp/platform_external_skia,nfxosp/platform_external_skia,VentureROM-L/android_external_skia,Plain-Andy/android_platform_external_skia,mmatyas/skia,OptiPop/external_skia,Android-AOSP/external_skia,TeamTwisted/external_skia,tmpvar/skia.cc,pacerom/external_skia,google/skia,YUPlayGodDev/platform_external_skia,mydongistiny/android_external_skia,Khaon/android_external_skia,RadonX-ROM/external_skia,MarshedOut/android_external_skia,mydongistiny/android_external_skia,MIPS/external-chromium_org-third_party-skia,scroggo/skia,rubenvb/skia,suyouxin/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,houst0nn/external_skia,OneRom/external_skia,Pure-Aosp/android_external_skia,houst0nn/external_skia,GladeRom/android_external_skia,samuelig/skia,fire855/android_external_skia,TeslaOS/android_external_skia,noselhq/skia,MonkeyZZZZ/platform_external_skia,android-ia/platform_external_skia,Infusion-OS/android_external_skia,Fusion-Rom/android_external_skia,AOSPB/external_skia,PAC-ROM/android_external_skia,nox/skia,ctiao/platform-external-skia,geekboxzone/lollipop_external_skia,aosp-mirror/platform_external_skia,temasek/android_external_skia,Pure-Aosp/android_external_skia,codeaurora-unoffical/platform-external-skia,qrealka/skia-hc,MonkeyZZZZ/platform_external_skia,google/skia,android-ia/platform_external_skia,Infinitive-OS/platform_external_skia,HealthyHoney/temasek_SKIA,F-AOSP/platform_external_skia,Fusion-Rom/android_external_skia,TeslaProject/external_skia,vanish87/skia,OptiPop/external_chromium_org_third_party_skia,wildermason/external_skia,Infusion-OS/android_external_skia,UBERMALLOW/external_skia,GladeRom/android_external_skia,Samsung/skia,MonkeyZZZZ/platform_external_skia,HealthyHoney/temasek_SKIA,xin3liang/platform_external_chromium_org_third_party_skia,byterom/android_external_skia,AsteroidOS/android_external_skia,chenlian2015/skia_from_google,MinimalOS-AOSP/platform_external_skia,byterom/android_external_skia,w3nd1go/android_external_skia,rubenvb/skia,byterom/android_external_skia,jtg-gg/skia,nox/skia,Jichao/skia,zhaochengw/platform_external_skia,HealthyHoney/temasek_SKIA,TeamEOS/external_chromium_org_third_party_skia,w3nd1go/android_external_skia,MarshedOut/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,chenlian2015/skia_from_google,HealthyHoney/temasek_SKIA,pcwalton/skia,sombree/android_external_skia,VRToxin-AOSP/android_external_skia,aospo/platform_external_skia,nfxosp/platform_external_skia,InfinitiveOS/external_skia,ench0/external_skia,OptiPop/external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,boulzordev/android_external_skia,AndroidOpenDevelopment/android_external_skia,boulzordev/android_external_skia,RadonX-ROM/external_skia,tmpvar/skia.cc,Igalia/skia,AOSPB/external_skia,AOSPB/external_skia,NamelessRom/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,TeamEOS/external_chromium_org_third_party_skia,sudosurootdev/external_skia,MinimalOS-AOSP/platform_external_skia,houst0nn/external_skia,DiamondLovesYou/skia-sys,VentureROM-L/android_external_skia,sombree/android_external_skia,geekboxzone/mmallow_external_skia,ench0/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,invisiblek/android_external_skia,TeslaOS/android_external_skia,mozilla-b2g/external_skia,ctiao/platform-external-skia,akiss77/skia,RadonX-ROM/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,TeslaProject/external_skia,Jichao/skia,TeamTwisted/external_skia,akiss77/skia,Infinitive-OS/platform_external_skia,Samsung/skia,geekboxzone/lollipop_external_skia,Infinitive-OS/platform_external_skia,Pure-Aosp/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,suyouxin/android_external_skia,pacerom/external_skia,TeamEOS/external_skia,OneRom/external_skia,android-ia/platform_external_skia,MinimalOS/external_skia,YUPlayGodDev/platform_external_skia,jtg-gg/skia,Asteroid-Project/android_external_skia,HalCanary/skia-hc,AsteroidOS/android_external_skia,Hybrid-Rom/external_skia,ominux/skia,sombree/android_external_skia,fire855/android_external_skia,FusionSP/external_chromium_org_third_party_skia,VentureROM-L/android_external_skia,Asteroid-Project/android_external_skia,ench0/external_chromium_org_third_party_skia,todotodoo/skia,Omegaphora/external_chromium_org_third_party_skia,TeamExodus/external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,NamelessRom/android_external_skia,geekboxzone/mmallow_external_skia,noselhq/skia,akiss77/skia,mmatyas/skia,byterom/android_external_skia,YUPlayGodDev/platform_external_skia,mozilla-b2g/external_skia,chenlian2015/skia_from_google,mydongistiny/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,Infusion-OS/android_external_skia,xzzz9097/android_external_skia,Tesla-Redux/android_external_skia,tmpvar/skia.cc,wildermason/external_skia,scroggo/skia,aospo/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,fire855/android_external_skia,mmatyas/skia,mydongistiny/external_chromium_org_third_party_skia,UBERMALLOW/external_skia,Omegaphora/external_skia,ench0/external_chromium_org_third_party_skia,MinimalOS/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,pacerom/external_skia,codeaurora-unoffical/platform-external-skia,wildermason/external_skia,AOSPB/external_skia,larsbergstrom/skia,YUPlayGodDev/platform_external_skia,YUPlayGodDev/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,AOSPB/external_skia,ctiao/platform-external-skia,TeamBliss-LP/android_external_skia,noselhq/skia,Igalia/skia,UBERMALLOW/external_skia,amyvmiwei/skia,timduru/platform-external-skia,SlimSaber/android_external_skia,Infinitive-OS/platform_external_skia,MinimalOS/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Purity-Lollipop/platform_external_skia,Purity-Lollipop/platform_external_skia,nvoron23/skia,MinimalOS/external_skia,Igalia/skia,AOSPB/external_skia,Infusion-OS/android_external_skia,MIPS/external-chromium_org-third_party-skia,Samsung/skia,jtg-gg/skia,xzzz9097/android_external_skia,AOSP-YU/platform_external_skia,jtg-gg/skia,Khaon/android_external_skia,ominux/skia,DiamondLovesYou/skia-sys,AsteroidOS/android_external_skia,Jichao/skia,zhaochengw/platform_external_skia,TeamExodus/external_skia,Hybrid-Rom/external_skia,TeamTwisted/external_skia,zhaochengw/platform_external_skia,MyAOSP/external_chromium_org_third_party_skia,invisiblek/android_external_skia,TeslaOS/android_external_skia,aospo/platform_external_skia,ominux/skia,BrokenROM/external_skia,samuelig/skia,nvoron23/skia,spezi77/android_external_skia,HealthyHoney/temasek_SKIA,shahrzadmn/skia,xin3liang/platform_external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,Asteroid-Project/android_external_skia,spezi77/android_external_skia,aosp-mirror/platform_external_skia,VRToxin-AOSP/android_external_skia,VentureROM-L/android_external_skia,MinimalOS/external_skia,mydongistiny/external_chromium_org_third_party_skia,sigysmund/platform_external_skia,AOSPA-L/android_external_skia,todotodoo/skia,MonkeyZZZZ/platform_external_skia,shahrzadmn/skia,xzzz9097/android_external_skia,codeaurora-unoffical/platform-external-skia
|
7cb42a738e746a7b7304c87059f824c62daab34e
|
src/guido/guido.cpp
|
src/guido/guido.cpp
|
/*
MusicXML Library
Copyright (C) Grame 2006-2013
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
[email protected]
*/
#include <sstream>
#include "guido.h"
using namespace std;
namespace MusicXML2
{
//______________________________________________________________________________
Sguidoparam guidoparam::create(string value, bool quote)
{ guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; }
Sguidoparam guidoparam::create(long value, bool quote)
{ guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; }
Sguidoelement guidoelement::create(string name, string sep)
{ guidoelement * o = new guidoelement(name, sep); assert(o!=0); return o; }
Sguidonote guidonote::create(unsigned short voice) {
guidonotestatus * status = guidonotestatus::get(voice);
guidonote * o = new guidonote (voice,"", status->fOctave, status->fDur, "");
assert(o!=0);
return o;
}
Sguidonote guidonote::create(unsigned short voice, string name, char oct, guidonoteduration& dur, string acc)
{ guidonote * o = new guidonote (voice, name, oct, dur, acc); assert(o!=0); return o; }
Sguidoseq guidoseq::create() { guidoseq* o = new guidoseq(); assert(o!=0); return o;}
Sguidochord guidochord::create() { guidochord* o = new guidochord(); assert(o!=0); return o;}
Sguidotag guidotag::create(string name) { guidotag* o = new guidotag(name); assert(o!=0); return o;}
Sguidotag guidotag::create(string name, string sep) { guidotag* o = new guidotag(name, sep); assert(o!=0); return o;}
//______________________________________________________________________________
guidonotestatus* guidonotestatus::fInstances[kMaxInstances] = { 0 };
guidonotestatus* guidonotestatus::get (unsigned short voice)
{
if (voice < kMaxInstances) {
if (!fInstances[voice])
fInstances[voice] = new guidonotestatus;
return fInstances[voice];
}
return 0;
}
void guidonotestatus::resetall ()
{
for (int i=0; i<kMaxInstances; i++) {
if (fInstances[i]) fInstances[i]->reset();
}
}
void guidonotestatus::freeall ()
{
for (int i=0; i<kMaxInstances; i++) {
delete fInstances[i];
fInstances[i] = 0;
}
}
//______________________________________________________________________________
void guidoparam::set (string value, bool quote)
{
fValue = value;
fQuote = quote;
}
//______________________________________________________________________________
void guidoparam::set (long value, bool quote)
{
stringstream s;
s << value;
s >> fValue;
fQuote = quote;
}
//______________________________________________________________________________
long guidoelement::add (Sguidoelement& elt) {
fElements.push_back(elt);
return fElements.size()-1;
}
long guidoelement::add (Sguidoparam& param) {
fParams.push_back(param);
return fParams.size()-1;
}
long guidoelement::add (Sguidoparam param) {
fParams.push_back(param);
return fParams.size()-1;
}
static string add_escape(const char* str)
{
string out;
while (*str) {
if (*str == '"') out += '\\';
out += *str++;
}
return out;
}
//______________________________________________________________________________
// print the optional parameters section
void guidoelement::printparams(ostream& os) const
{
if (!fParams.empty()) {
os << "<";
vector<Sguidoparam>::const_iterator param;
for (param = fParams.begin(); param != fParams.end(); ) {
if ((*param)->quote())
os << "\"" << add_escape((*param)->get().c_str()) << "\"";
else
os << (*param)->get();
if (++param != fParams.end())
os << ", ";
}
os << ">";
}
}
//______________________________________________________________________________
// print a chord
// note that a score is a chord of sequences
void guidochord::print(ostream& os) const
{
os << fStartList;
int n = countNotes();
std::string seqsep = "";
for (auto e: fElements) {
// checking for elements separator
// sequences (i.e. score) are handled as chords
// that's why there are special cases for seq
//const char* sep = ((e->isNote() || (!e->isSeq() && e->countNotes())) && --n) ? ", " : " ";
std::string sep = ((e->isNote() || (!e->isSeq() && e->countNotes())) && --n) ? ", " : " ";
/// Handle the special cases:
/// - If we are in a chord and e is a note, and next event is TieEnd, then the separater is " " and "," should be applied after TieEnd!
Sguidoelement next_e, pre_e;
bool nextExist = getNext(e, next_e);
bool preExist = getPrev(e, pre_e);
if ((e->isNote())&& nextExist && (next_e->getName().find("tieEnd") != std::string::npos) ) {
sep = " ";
}
if ((e->getName().find("tieEnd") != std::string::npos) && (preExist) && (pre_e->isNote()) && nextExist) {
sep = ", ";
}
os << seqsep << e << sep;
if (e->isSeq()) seqsep = ", \n";
}
os << fEndList;
}
//______________________________________________________________________________
void guidoelement::print(ostream& os) const
{
os << fName;
printparams (os);
// print the enclosed elements
if (!fElements.empty()) {
os << fStartList;
string sep = " ";
for (auto e: fElements) {
os << sep << e;
}
os << fEndList << endl;
}
}
//______________________________________________________________________________
ostream& operator<< (ostream& os, const Sguidoelement& elt)
{
elt->print(os);
return os;
}
//______________________________________________________________________________
void guidonote::set (unsigned short voice, string name, char octave, guidonoteduration& dur, string acc)
{
guidonotestatus * status = guidonotestatus::get(voice);
stringstream s;
long dots = dur.fDots;
fNote = name;
fAccidental = acc;
fOctave = octave;
fDuration = dur;
s << name;
// octave is ignored in case of rests
if (name[0] != '_') {
if (!acc.empty())
s << acc;
if (name != "empty") {
if (!status)
s << (int)octave;
else if (status->fOctave != octave) {
s << (int)octave;
status->fOctave = octave;
}
}
}
//// AC Note 20/02/2017: Not generating Durations, causes problems on multi-voice scores with Pickup measures!
//if (!status || (*status != dur)) {
if (dur.fNum != 1) {
s << "*" << (int)dur.fNum;
}
s << "/" << (int)dur.fDenom;
if (status) *status = dur;
//}
while (dots-- > 0)
s << ".";
s >> fName;
}
//______________________________________________________________________________
guidoelement::guidoelement(string name, string sep) : fName(name), fSep(sep) {}
guidoelement::~guidoelement() {}
int guidoelement::countNotes () const {
int count = 0;
for (auto e: fElements) {
if (e->isNote()) count++;
else count += e->countNotes();
}
return count;
}
//______________________________________________________________________________
guidoparam::guidoparam(string value, bool quote) : fValue(value), fQuote(quote) {}
guidoparam::guidoparam(long value, bool quote) { set(value, quote); }
guidoparam::~guidoparam () {}
//______________________________________________________________________________
guidonote::guidonote(unsigned short voice, string name, char octave,
guidonoteduration& dur, string acc)
: guidoelement(""), fDuration(1,4) { set(voice, name, octave, dur, acc); }
guidonote::~guidonote() {}
//______________________________________________________________________________
guidoseq::guidoseq() : guidoelement("") { fStartList="["; fEndList=" ]"; }
guidoseq::~guidoseq() {}
//______________________________________________________________________________
guidochord::guidochord () : guidoelement("", ", ")
{ fStartList="{"; fEndList=" }"; }
guidochord::~guidochord() {}
//______________________________________________________________________________
guidotag::guidotag(string name) : guidoelement("\\"+name)
{ fStartList="("; fEndList=")"; }
guidotag::guidotag(string name, string sep) : guidoelement("\\"+name,sep)
{ fStartList="("; fEndList=")"; }
guidotag::~guidotag() {}
}
|
/*
MusicXML Library
Copyright (C) Grame 2006-2013
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
[email protected]
*/
#include <sstream>
#include "guido.h"
using namespace std;
namespace MusicXML2
{
//______________________________________________________________________________
Sguidoparam guidoparam::create(string value, bool quote)
{ guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; }
Sguidoparam guidoparam::create(long value, bool quote)
{ guidoparam * o = new guidoparam(value, quote); assert(o!=0); return o; }
Sguidoelement guidoelement::create(string name, string sep)
{ guidoelement * o = new guidoelement(name, sep); assert(o!=0); return o; }
Sguidonote guidonote::create(unsigned short voice) {
guidonotestatus * status = guidonotestatus::get(voice);
guidonote * o = new guidonote (voice,"", status->fOctave, status->fDur, "");
assert(o!=0);
return o;
}
Sguidonote guidonote::create(unsigned short voice, string name, char oct, guidonoteduration& dur, string acc)
{ guidonote * o = new guidonote (voice, name, oct, dur, acc); assert(o!=0); return o; }
Sguidoseq guidoseq::create() { guidoseq* o = new guidoseq(); assert(o!=0); return o;}
Sguidochord guidochord::create() { guidochord* o = new guidochord(); assert(o!=0); return o;}
Sguidotag guidotag::create(string name) { guidotag* o = new guidotag(name); assert(o!=0); return o;}
Sguidotag guidotag::create(string name, string sep) { guidotag* o = new guidotag(name, sep); assert(o!=0); return o;}
//______________________________________________________________________________
guidonotestatus* guidonotestatus::fInstances[kMaxInstances] = { 0 };
guidonotestatus* guidonotestatus::get (unsigned short voice)
{
if (voice < kMaxInstances) {
if (!fInstances[voice])
fInstances[voice] = new guidonotestatus;
return fInstances[voice];
}
return 0;
}
void guidonotestatus::resetall ()
{
for (int i=0; i<kMaxInstances; i++) {
if (fInstances[i]) fInstances[i]->reset();
}
}
void guidonotestatus::freeall ()
{
for (int i=0; i<kMaxInstances; i++) {
delete fInstances[i];
fInstances[i] = 0;
}
}
//______________________________________________________________________________
void guidoparam::set (string value, bool quote)
{
fValue = value;
fQuote = quote;
}
//______________________________________________________________________________
void guidoparam::set (long value, bool quote)
{
stringstream s;
s << value;
s >> fValue;
fQuote = quote;
}
//______________________________________________________________________________
long guidoelement::add (Sguidoelement& elt) {
fElements.push_back(elt);
return fElements.size()-1;
}
long guidoelement::add (Sguidoparam& param) {
fParams.push_back(param);
return fParams.size()-1;
}
long guidoelement::add (Sguidoparam param) {
fParams.push_back(param);
return fParams.size()-1;
}
static string add_escape(const char* str)
{
string out;
while (*str) {
if (*str == '"') out += '\\';
out += *str++;
}
return out;
}
//______________________________________________________________________________
// print the optional parameters section
void guidoelement::printparams(ostream& os) const
{
if (!fParams.empty()) {
os << "<";
vector<Sguidoparam>::const_iterator param;
for (param = fParams.begin(); param != fParams.end(); ) {
if ((*param)->quote())
os << "\"" << add_escape((*param)->get().c_str()) << "\"";
else
os << (*param)->get();
if (++param != fParams.end())
os << ", ";
}
os << ">";
}
}
//______________________________________________________________________________
// print a chord
// note that a score is a chord of sequences
void guidochord::print(ostream& os) const
{
os << fStartList;
int n = countNotes();
const char* seqsep = "";
for (auto e: fElements) {
// checking for elements separator
// sequences (i.e. score) are handled as chords
// that's why there are special cases for seq
const char* sep = ((e->isNote() || (!e->isSeq() && e->countNotes())) && --n) ? ", " : " ";
/// Handle the special cases:
/// - If we are in a chord and e is a note, and next event is TieEnd, then the separater is " " and "," should be applied after TieEnd!
Sguidoelement next_e, pre_e;
bool nextExist = getNext(e, next_e);
bool preExist = getPrev(e, pre_e);
if ((e->isNote())&& nextExist && (next_e->getName().find("tieEnd") != std::string::npos) ) {
sep = " ";
}
if ((e->getName().find("tieEnd") != std::string::npos) && (preExist) && (pre_e->isNote()) && nextExist) {
sep = ", ";
}
os << seqsep << e << sep;
if (e->isSeq()) seqsep = ", \n";
}
os << fEndList;
}
//______________________________________________________________________________
void guidoelement::print(ostream& os) const
{
os << fName;
printparams (os);
// print the enclosed elements
if (!fElements.empty()) {
os << fStartList;
string sep = " ";
for (auto e: fElements) {
os << sep << e;
}
os << fEndList << endl;
}
}
//______________________________________________________________________________
ostream& operator<< (ostream& os, const Sguidoelement& elt)
{
elt->print(os);
return os;
}
//______________________________________________________________________________
void guidonote::set (unsigned short voice, string name, char octave, guidonoteduration& dur, string acc)
{
guidonotestatus * status = guidonotestatus::get(voice);
stringstream s;
long dots = dur.fDots;
fNote = name;
fAccidental = acc;
fOctave = octave;
fDuration = dur;
s << name;
// octave is ignored in case of rests
if (name[0] != '_') {
if (!acc.empty())
s << acc;
if (name != "empty") {
if (!status)
s << (int)octave;
else if (status->fOctave != octave) {
s << (int)octave;
status->fOctave = octave;
}
}
}
//// AC Note 20/02/2017: Not generating Durations, causes problems on multi-voice scores with Pickup measures!
//if (!status || (*status != dur)) {
if (dur.fNum != 1) {
s << "*" << (int)dur.fNum;
}
s << "/" << (int)dur.fDenom;
if (status) *status = dur;
//}
while (dots-- > 0)
s << ".";
s >> fName;
}
//______________________________________________________________________________
guidoelement::guidoelement(string name, string sep) : fName(name), fSep(sep) {}
guidoelement::~guidoelement() {}
int guidoelement::countNotes () const {
int count = 0;
for (auto e: fElements) {
if (e->isNote()) count++;
else count += e->countNotes();
}
return count;
}
//______________________________________________________________________________
guidoparam::guidoparam(string value, bool quote) : fValue(value), fQuote(quote) {}
guidoparam::guidoparam(long value, bool quote) { set(value, quote); }
guidoparam::~guidoparam () {}
//______________________________________________________________________________
guidonote::guidonote(unsigned short voice, string name, char octave,
guidonoteduration& dur, string acc)
: guidoelement(""), fDuration(1,4) { set(voice, name, octave, dur, acc); }
guidonote::~guidonote() {}
//______________________________________________________________________________
guidoseq::guidoseq() : guidoelement("") { fStartList="["; fEndList=" ]"; }
guidoseq::~guidoseq() {}
//______________________________________________________________________________
guidochord::guidochord () : guidoelement("", ", ")
{ fStartList="{"; fEndList=" }"; }
guidochord::~guidochord() {}
//______________________________________________________________________________
guidotag::guidotag(string name) : guidoelement("\\"+name)
{ fStartList="("; fEndList=")"; }
guidotag::guidotag(string name, string sep) : guidoelement("\\"+name,sep)
{ fStartList="("; fEndList=")"; }
guidotag::~guidotag() {}
}
|
Revert back to const char* as before
|
Revert back to const char* as before
|
C++
|
mpl-2.0
|
grame-cncm/libmusicxml,grame-cncm/libmusicxml,grame-cncm/libmusicxml,grame-cncm/libmusicxml,grame-cncm/libmusicxml,grame-cncm/libmusicxml
|
74319fd8e983a09c1167c0932c34d300cf24d920
|
src/hp34970hack.cpp
|
src/hp34970hack.cpp
|
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/select.h>
#include <unistd.h>
#include <QtCore>
#include <stdexcept>
#include "hp34970hack.h"
// set DC voltage
// SENS:VOLT:DC ()
// 'SENS:VOLT:DC:RANG'+qs+', (@'+IntToStr(chan)+')';
// SENS:VOLT:DC:NPLC'+qs+', (@'+IntToStr(chan)+')'
/*
procedure THall.ResBtnClick(Sender: TObject);
var s:string;
kod:integer;
cur,volp,voln,Ra,Rb,Rs,pomr,t:double;
begin
ResBtn.Enabled:=false; HallBtn.Enabled:=false;
OpenChannel('209,210');
// Convert'+#13+'Current to Number
s:=EditCurr.Text; val(s,cur,kod);
// Convert'+#13+'Thickness to Number
s:=EditT.Text; val(s,t,kod);
t:=t/10;
cur:=cur/1000; str(cur:5:3,s);
{ --- Measure R_a --- }
SetCurrent(s);
CloseChannel('201,202'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=-ReadValue(101);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=-ReadValue(101);
ApplyCurrent(False);
OpenChannel('201');
Ra:=(volp-voln)/2/cur*t; str(Ra:7:5,s);
EditRa.Text:=s;
{ --- Measure R_b --- }
str(cur:6:4,s);
SetCurrent(s);
CloseChannel('203,205'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(102);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(102);
ApplyCurrent(False);
OpenChannel('202,203,205');
Rb:=(volp-voln)/2/cur*t; str(Rb:7:5,s);
EditRb.Text:=s;
{ --- Calculate R_s --- }
Rs:=SolveRs(Ra,Rb,kod); //(Ra+Rb)/2; kod:=0;
if not(kod=0) then ShowMessage('Failed on Calculating Rs');
str(Rs:7:5,s);
EditRs.Text:=s;
{ --- Measure Field --- }
CloseChannel('209,210');
SetCurrent('0.001'); KPausa(300);
ApplyCurrent(true);
KPausa(500);
pomr:=ReadValue(114)*1000;
pomr:=-30.588+sqrt(934.773+0.392163*pomr);
ApplyCurrent(false);
str(pomr:4:2,s);
EditB.Text:=s;
ResBtn.Enabled:=true; HallBtn.Enabled:=true;
end;
procedure THall.HallBtnClick(Sender: TObject);
var s:string;
kod:integer;
cur,volp,voln,Ra,Rb,Rs,pomr,t:double;
begin
ResBtn.Enabled:=false; HallBtn.Enabled:=false;
OpenChannel('209,210');
// Convert'+#13+'Current to Number
s:=EditCurr.Text; val(s,cur,kod);
// Convert'+#13+'Thickness to Number
s:=EditT.Text; val(s,t,kod);
t:=t/10;
cur:=cur/1000; str(cur:6:4,s);
{ --- Measure R_b --- }
SetCurrent(s);
CloseChannel('202,204'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(104);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(104);
ApplyCurrent(False);
OpenChannel('202,204');
Rb:=(volp-voln)/2/cur*t;
s:=Format('%6.3e',[Rb]);
Delete(s,Length(s)-2,2);
EditVb.Text:=s;
{ --- Measure R_a --- }
str(cur:6:4,s);
SetCurrent(s);
CloseChannel('201,203,206'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(103);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(103);
ApplyCurrent(False);
OpenChannel('201,203,206');
Ra:=(volp-voln)/2/cur*t;
s:=Format('%6.3e',[Ra]);
Delete(s,Length(s)-2,2);
EditVa.Text:=s;
{ --- Measure Field --- }
CloseChannel('209,210');
SetCurrent('0.001'); KPausa(300);
ApplyCurrent(true);
KPausa(500);
pomr:=ReadValue(114)*1000;
pomr:=-30.588+sqrt(934.773+0.392163*pomr);
ApplyCurrent(false);
str(pomr:4:2,s);
EditB.Text:=s;
{ --- Calculate V/B/I --- }
Rs:=Ra/pomr*10000;
s:=Format('%6.3e',[Rs]);
Delete(s,Length(s)-2,2);
EditUB.Text:=s;
ResBtn.Enabled:=true; HallBtn.Enabled:=true;
end;
*/
HP34970hack::Sense_t HP34970hack::SenseVolt = "CONF:VOLT";
HP34970hack::Sense_t HP34970hack::SenseRes = "CONF:RES";
HP34970hack::HP34970hack() :
QSerial()
{
memset(HP34903ClosedChannels, 0, sizeof(HP34903ClosedChannels));
}
HP34970hack::~HP34970hack()
{
close();
}
void HP34970hack::close()
{
QSerial::close();
}
QString HP34970hack::formatCmd(const QString &cmd, const Channels_t &channels)
{
if (!channels.size()) {
return cmd;
}
QStringList ch;
foreach(int channel, channels) {
ch.append(QVariant(channel).toString());
}
QString format("%1 (@%2)");
return format.arg(cmd).arg(ch.join(","));
}
void HP34970hack::init()
{
sendCmd("INIT", 2000000);
}
bool HP34970hack::open(const QString &port)
{
const long timeout = (10l * 1000000l) / 9600l;
close();
if (!QSerial::open(port, QSerial::Baude9600, 300000, timeout))
return false;
write("\n");
sendCmd("*RST;*CLS", 500000);
sendCmd("SYST:REM");
return true;
}
QStringList HP34970hack::read()
{
QString s;
QStringList data;
s = sendQuery("READ?");
data = s.split(",", QString::SkipEmptyParts);
for (QStringList::iterator idata(data.begin()); idata != data.end(); ++idata) {
*idata = idata->trimmed();
}
return data;
}
void HP34970hack::sendCmd(const QString &cmd, long timeout)
{
QString s;
s = sendQuery(cmd, timeout);
if (!s.isEmpty())
throw new std::runtime_error("P34970hack::cmd response not empty.");
}
void HP34970hack::sendCmd(const QString &cmd, const Channels_t &channels, long timeout)
{
QString s;
s = sendQuery(cmd, channels, timeout);
if (!s.isEmpty())
throw new std::runtime_error("P34970hack::cmd response not empty.");
}
QString HP34970hack::sendQuery(const QString &cmd, long timeout)
{
QString _cmd(cmd + ";*OPC?\n");
write(_cmd);
QString result(readLine(1024, timeout).trimmed());
if (result == "1")
return QString();
if (result.endsWith(";1"))
return result.left(result.size() - 2);
throw new std::runtime_error("P34970hack::sendQuery failed read response.");
}
QString HP34970hack::sendQuery(const QString &cmd, const Channels_t &channels, long timeout)
{
QString _cmd(formatCmd(cmd, channels));
return sendQuery(_cmd, timeout);
}
void HP34970hack::setRoute(Channels_t closeChannels, int offs)
{
Channels_t openChannels;
Channels_t _closeChannels_;
// channel = x + 1 + offs;
++offs;
for (int x(0); x <= 19; ++x) {
bool c(HP34903ClosedChannels[x]);
Channel_t channel = x + offs;
bool cw(closeChannels.count(channel));
if (c && !cw) {
openChannels.append(channel);
} else
if (!c && cw) {
_closeChannels_.append(channel);
}
}
if(!openChannels.isEmpty())
sendCmd("ROUT:OPEN", openChannels);
if (!closeChannels.isEmpty())
sendCmd("ROUT:CLOS", _closeChannels_);
}
void HP34970hack::setScan(Channels_t channels)
{
QString cmd("ROUT:SCAN");
cmd = formatCmd(cmd, channels).append(";:INIT");
sendCmd(cmd);
}
void HP34970hack::setSense(Sense_t sense, Channels_t channels)
{
sendCmd(sense, channels);
}
void HP34970hack::setup()
{
Channels_t channels;
channels << 101 << 102 << 103 << 104 << 114;
setSense(SenseVolt, channels);
init();
}
|
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/select.h>
#include <unistd.h>
#include <QtCore>
#include <stdexcept>
#include "hp34970hack.h"
// set DC voltage
// SENS:VOLT:DC ()
// 'SENS:VOLT:DC:RANG'+qs+', (@'+IntToStr(chan)+')';
// SENS:VOLT:DC:NPLC'+qs+', (@'+IntToStr(chan)+')'
/*
procedure THall.ResBtnClick(Sender: TObject);
var s:string;
kod:integer;
cur,volp,voln,Ra,Rb,Rs,pomr,t:double;
begin
ResBtn.Enabled:=false; HallBtn.Enabled:=false;
OpenChannel('209,210');
// Convert'+#13+'Current to Number
s:=EditCurr.Text; val(s,cur,kod);
// Convert'+#13+'Thickness to Number
s:=EditT.Text; val(s,t,kod);
t:=t/10;
cur:=cur/1000; str(cur:5:3,s);
{ --- Measure R_a --- }
SetCurrent(s);
CloseChannel('201,202'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=-ReadValue(101);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=-ReadValue(101);
ApplyCurrent(False);
OpenChannel('201');
Ra:=(volp-voln)/2/cur*t; str(Ra:7:5,s);
EditRa.Text:=s;
{ --- Measure R_b --- }
str(cur:6:4,s);
SetCurrent(s);
CloseChannel('203,205'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(102);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(102);
ApplyCurrent(False);
OpenChannel('202,203,205');
Rb:=(volp-voln)/2/cur*t; str(Rb:7:5,s);
EditRb.Text:=s;
{ --- Calculate R_s --- }
Rs:=SolveRs(Ra,Rb,kod); //(Ra+Rb)/2; kod:=0;
if not(kod=0) then ShowMessage('Failed on Calculating Rs');
str(Rs:7:5,s);
EditRs.Text:=s;
{ --- Measure Field --- }
CloseChannel('209,210');
SetCurrent('0.001'); KPausa(300);
ApplyCurrent(true);
KPausa(500);
pomr:=ReadValue(114)*1000;
pomr:=-30.588+sqrt(934.773+0.392163*pomr);
ApplyCurrent(false);
str(pomr:4:2,s);
EditB.Text:=s;
ResBtn.Enabled:=true; HallBtn.Enabled:=true;
end;
procedure THall.HallBtnClick(Sender: TObject);
var s:string;
kod:integer;
cur,volp,voln,Ra,Rb,Rs,pomr,t:double;
begin
ResBtn.Enabled:=false; HallBtn.Enabled:=false;
OpenChannel('209,210');
// Convert'+#13+'Current to Number
s:=EditCurr.Text; val(s,cur,kod);
// Convert'+#13+'Thickness to Number
s:=EditT.Text; val(s,t,kod);
t:=t/10;
cur:=cur/1000; str(cur:6:4,s);
{ --- Measure R_b --- }
SetCurrent(s);
CloseChannel('202,204'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(104);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(104);
ApplyCurrent(False);
OpenChannel('202,204');
Rb:=(volp-voln)/2/cur*t;
s:=Format('%6.3e',[Rb]);
Delete(s,Length(s)-2,2);
EditVb.Text:=s;
{ --- Measure R_a --- }
str(cur:6:4,s);
SetCurrent(s);
CloseChannel('201,203,206'); KPausa(300);
ApplyCurrent(True);
KPausa(500);
volp:=ReadValue(103);
ApplyCurrent(False);
str(-cur:6:4,s);
SetCurrent(s); KPausa(300);
ApplyCurrent(True);
KPausa(500);
voln:=ReadValue(103);
ApplyCurrent(False);
OpenChannel('201,203,206');
Ra:=(volp-voln)/2/cur*t;
s:=Format('%6.3e',[Ra]);
Delete(s,Length(s)-2,2);
EditVa.Text:=s;
{ --- Measure Field --- }
CloseChannel('209,210');
SetCurrent('0.001'); KPausa(300);
ApplyCurrent(true);
KPausa(500);
pomr:=ReadValue(114)*1000;
pomr:=-30.588+sqrt(934.773+0.392163*pomr);
ApplyCurrent(false);
str(pomr:4:2,s);
EditB.Text:=s;
{ --- Calculate V/B/I --- }
Rs:=Ra/pomr*10000;
s:=Format('%6.3e',[Rs]);
Delete(s,Length(s)-2,2);
EditUB.Text:=s;
ResBtn.Enabled:=true; HallBtn.Enabled:=true;
end;
*/
HP34970hack::Sense_t HP34970hack::SenseVolt = "CONF:VOLT";
HP34970hack::Sense_t HP34970hack::SenseRes = "CONF:RES";
HP34970hack::HP34970hack() :
QSerial()
{
memset(HP34903ClosedChannels, 0, sizeof(HP34903ClosedChannels));
}
HP34970hack::~HP34970hack()
{
close();
}
void HP34970hack::close()
{
QSerial::close();
}
QString HP34970hack::formatCmd(const QString &cmd, const Channels_t &channels)
{
if (!channels.size()) {
return cmd;
}
QStringList ch;
foreach(int channel, channels) {
ch.append(QVariant(channel).toString());
}
QString format("%1 (@%2)");
return format.arg(cmd).arg(ch.join(","));
}
void HP34970hack::init()
{
sendCmd("INIT", 2000000);
}
bool HP34970hack::open(const QString &port)
{
const long timeout = (10l * 1000000l) / 9600l;
close();
if (!QSerial::open(port, QSerial::Baude9600, 300000, timeout))
return false;
write("\n");
sendCmd("*RST;*CLS", 500000);
sendCmd("SYST:REM");
return true;
}
QStringList HP34970hack::read()
{
QString s;
QStringList data;
s = sendQuery("READ?");
data = s.split(",", QString::SkipEmptyParts);
for (QStringList::iterator idata(data.begin()); idata != data.end(); ++idata) {
*idata = idata->trimmed();
}
return data;
}
void HP34970hack::sendCmd(const QString &cmd, long timeout)
{
QString s;
s = sendQuery(cmd, timeout);
if (!s.isEmpty())
throw new std::runtime_error("P34970hack::cmd response not empty.");
}
void HP34970hack::sendCmd(const QString &cmd, const Channels_t &channels, long timeout)
{
QString s;
s = sendQuery(cmd, channels, timeout);
if (!s.isEmpty())
throw new std::runtime_error("P34970hack::cmd response not empty.");
}
QString HP34970hack::sendQuery(const QString &cmd, long timeout)
{
QString _cmd(cmd + ";*OPC?\n");
write(_cmd);
QString result(readLine(1024, timeout).trimmed());
if (result == "1")
return QString();
if (result.endsWith(";1"))
return result.left(result.size() - 2);
throw new std::runtime_error("P34970hack::sendQuery failed read response.");
}
QString HP34970hack::sendQuery(const QString &cmd, const Channels_t &channels, long timeout)
{
QString _cmd(formatCmd(cmd, channels));
return sendQuery(_cmd, timeout);
}
void HP34970hack::setRoute(Channels_t closeChannels, int offs)
{
Channels_t openChannels;
Channels_t _closeChannels_;
// channel = x + 1 + offs;
++offs;
for (int x(0); x <= 19; ++x) {
bool c(HP34903ClosedChannels[x]);
Channel_t channel = x + offs;
bool cw(closeChannels.count(channel));
if (c && !cw) {
openChannels.append(channel);
HP34903ClosedChannels[x] = false;
} else
if (!c && cw) {
_closeChannels_.append(channel);
HP34903ClosedChannels[x] = true;
}
}
if(!openChannels.isEmpty())
sendCmd("ROUT:OPEN", openChannels);
if (!closeChannels.isEmpty())
sendCmd("ROUT:CLOS", _closeChannels_);
}
void HP34970hack::setScan(Channels_t channels)
{
QString cmd("ROUT:SCAN");
cmd = formatCmd(cmd, channels).append(";:INIT");
sendCmd(cmd);
}
void HP34970hack::setSense(Sense_t sense, Channels_t channels)
{
sendCmd(sense, channels);
}
void HP34970hack::setup()
{
Channels_t channels;
channels << 101 << 102 << 103 << 104 << 114;
setSense(SenseVolt, channels);
init();
}
|
fix open/close channel chace for agilent
|
fix open/close channel chace for agilent
|
C++
|
apache-2.0
|
pinkavaj/hall
|
076fceb62de3b90954e667111af9c78013178c73
|
src/mlpack/methods/kmeans/kmeans_main.cpp
|
src/mlpack/methods/kmeans/kmeans_main.cpp
|
/**
* @file kmeans_main.cpp
* @author Ryan Curtin
*
* Executable for running K-Means.
*/
#include <mlpack/core.hpp>
#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"
#include "elkan_kmeans.hpp"
#include "hamerly_kmeans.hpp"
#include "pelleg_moore_kmeans.hpp"
#include "dtnn_kmeans.hpp"
#include "dual_tree_kmeans.hpp"
using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;
// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
"on the given dataset, storing the learned cluster assignments either as "
"a column of labels in the file containing the input dataset or in a "
"separate file. Empty clusters are not allowed by default; when a cluster "
"becomes empty, the point furthest from the centroid of the cluster with "
"maximum variance is taken to fill that cluster."
"\n\n"
"Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
" k-means clustering\", 1998) can be used to select initial points by "
"specifying the --refined_start (-r) option. This approach works by taking"
" random samples of the dataset; to specify the number of samples, the "
"--samples parameter is used, and to specify the percentage of the dataset "
"to be used in each sample, the --percentage parameter is used (it should "
"be a value between 0.0 and 1.0)."
"\n\n"
"There are several options available for the algorithm used for each Lloyd "
"iteration, specified with the --algorithm (-a) option. The standard O(kN)"
" approach can be used ('naive'). Other options include the Pelleg-Moore "
"tree-based algorithm ('pelleg-moore'), Elkan's triangle-inequality based "
"algorithm ('elkan'), and Hamerly's modification to Elkan's algorithm "
"('hamerly')."
"\n\n"
"As of October 2014, the --overclustering option has been removed. If you "
"want this support back, let us know -- file a bug at "
"http://www.mlpack.org/trac/ or get in touch through another means.");
// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find (0 autodetects from "
"initial centroids).", "c");
// Output options.
PARAM_FLAG("in_place", "If specified, a column containing the learned cluster "
"assignments will be added to the input dataset file. In this case, "
"--outputFile is overridden.", "P");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
"o", "");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
" be written to the given file.", "C", "");
// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
"terminates.", "m", 1000);
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_STRING("initial_centroids", "Start with the specified initial centroids.",
"I", "");
// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
"and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
"when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
" sampling (use when --refined_start is specified).", "p", 0.02);
PARAM_STRING("algorithm", "Algorithm to use for the Lloyd iteration ('naive', "
"'pelleg-moore', 'elkan', 'hamerly', or 'dtnn').", "a", "naive");
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(const InitialPartitionPolicy& ipp);
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(const InitialPartitionPolicy& ipp);
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(const InitialPartitionPolicy& ipp);
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
// Initialize random seed.
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Now, start building the KMeans type that we'll be using. Start with the
// initial partition policy. The call to FindEmptyClusterPolicy<> results in
// a call to RunKMeans<> and the algorithm is completed.
if (CLI::HasParam("refined_start"))
{
const int samplings = CLI::GetParam<int>("samplings");
const double percentage = CLI::GetParam<double>("percentage");
if (samplings < 0)
Log::Fatal << "Number of samplings (" << samplings << ") must be "
<< "greater than 0!" << endl;
if (percentage <= 0.0 || percentage > 1.0)
Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
<< "greater than 0.0 and less than or equal to 1.0!" << endl;
FindEmptyClusterPolicy<RefinedStart>(RefinedStart(samplings, percentage));
}
else
{
FindEmptyClusterPolicy<RandomPartition>(RandomPartition());
}
}
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(const InitialPartitionPolicy& ipp)
{
if (CLI::HasParam("allow_empty_clusters"))
FindLloydStepType<InitialPartitionPolicy, AllowEmptyClusters>(ipp);
else
FindLloydStepType<InitialPartitionPolicy, MaxVarianceNewCluster>(ipp);
}
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(const InitialPartitionPolicy& ipp)
{
const string algorithm = CLI::GetParam<string>("algorithm");
if (algorithm == "elkan")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, ElkanKMeans>(ipp);
else if (algorithm == "hamerly")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, HamerlyKMeans>(ipp);
else if (algorithm == "pelleg-moore")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
PellegMooreKMeans>(ipp);
else if (algorithm == "dtnn")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
DefaultDTNNKMeans>(ipp);
else if (algorithm == "dtnn-covertree")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
CoverTreeDTNNKMeans>(ipp);
else if (algorithm == "dualtree")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
DefaultDualTreeKMeans>(ipp);
else if (algorithm == "naive")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, NaiveKMeans>(ipp);
else
Log::Fatal << "Unknown algorithm: '" << algorithm << "'. Supported options"
<< " are 'naive', 'pelleg-moore', 'elkan', and 'hamerly'." << endl;
}
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(const InitialPartitionPolicy& ipp)
{
// Now, do validation of input options.
const string inputFile = CLI::GetParam<string>("inputFile");
int clusters = CLI::GetParam<int>("clusters");
if (clusters < 0)
{
Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
<< "Must be greater than or equal to 0." << endl;
}
else if (clusters == 0 && CLI::HasParam("initial_centroids"))
{
Log::Info << "Detecting number of clusters automatically from input "
<< "centroids." << endl;
}
else if (clusters == 0)
{
Log::Fatal << "Number of clusters requested is 0, and no initial centroids "
<< "provided!" << endl;
}
const int maxIterations = CLI::GetParam<int>("max_iterations");
if (maxIterations < 0)
{
Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
")! Must be greater than or equal to 0." << endl;
}
// Make sure we have an output file if we're not doing the work in-place.
if (!CLI::HasParam("in_place") && !CLI::HasParam("output_file") &&
!CLI::HasParam("centroid_file"))
{
Log::Warn << "--output_file, --in_place, and --centroid_file are not set; "
<< "no results will be saved." << std::endl;
}
// Load our dataset.
arma::mat dataset;
data::Load(inputFile, dataset, true); // Fatal upon failure.
arma::mat centroids;
const bool initialCentroidGuess = CLI::HasParam("initial_centroids");
// Load initial centroids if the user asked for it.
if (initialCentroidGuess)
{
string initialCentroidsFile = CLI::GetParam<string>("initial_centroids");
data::Load(initialCentroidsFile, centroids, true);
if (clusters == 0)
clusters = centroids.n_cols;
if (CLI::HasParam("refined_start"))
Log::Warn << "Initial centroids are specified, but will be ignored "
<< "because --refined_start is also specified!" << endl;
else
Log::Info << "Using initial centroid guesses from '" <<
initialCentroidsFile << "'." << endl;
}
Timer::Start("clustering");
KMeans<metric::EuclideanDistance,
InitialPartitionPolicy,
EmptyClusterPolicy,
LloydStepType> kmeans(maxIterations, metric::EuclideanDistance(), ipp);
if (CLI::HasParam("output_file") || CLI::HasParam("in_place"))
{
// We need to get the assignments.
arma::Col<size_t> assignments;
kmeans.Cluster(dataset, clusters, assignments, centroids,
false, initialCentroidGuess);
Timer::Stop("clustering");
// Now figure out what to do with our results.
if (CLI::HasParam("in_place"))
{
// Add the column of assignments to the dataset; but we have to convert
// them to type double first.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Save the dataset.
data::Save(inputFile, dataset);
}
else
{
if (CLI::HasParam("labels_only"))
{
// Save only the labels.
string outputFile = CLI::GetParam<string>("output_file");
arma::Mat<size_t> output = trans(assignments);
data::Save(outputFile, output);
}
else
{
// Convert the assignments to doubles.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Now save, in the different file.
string outputFile = CLI::GetParam<string>("output_file");
data::Save(outputFile, dataset);
}
}
}
else
{
// Just save the centroids.
kmeans.Cluster(dataset, clusters, centroids, initialCentroidGuess);
Timer::Stop("clustering");
}
// Should we write the centroids to a file?
if (CLI::HasParam("centroid_file"))
data::Save(CLI::GetParam<std::string>("centroid_file"), centroids);
}
|
/**
* @file kmeans_main.cpp
* @author Ryan Curtin
*
* Executable for running K-Means.
*/
#include <mlpack/core.hpp>
#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "refined_start.hpp"
#include "elkan_kmeans.hpp"
#include "hamerly_kmeans.hpp"
#include "pelleg_moore_kmeans.hpp"
#include "dtnn_kmeans.hpp"
#include "dual_tree_kmeans.hpp"
using namespace mlpack;
using namespace mlpack::kmeans;
using namespace std;
// Define parameters for the executable.
PROGRAM_INFO("K-Means Clustering", "This program performs K-Means clustering "
"on the given dataset, storing the learned cluster assignments either as "
"a column of labels in the file containing the input dataset or in a "
"separate file. Empty clusters are not allowed by default; when a cluster "
"becomes empty, the point furthest from the centroid of the cluster with "
"maximum variance is taken to fill that cluster."
"\n\n"
"Optionally, the Bradley and Fayyad approach (\"Refining initial points for"
" k-means clustering\", 1998) can be used to select initial points by "
"specifying the --refined_start (-r) option. This approach works by taking"
" random samples of the dataset; to specify the number of samples, the "
"--samples parameter is used, and to specify the percentage of the dataset "
"to be used in each sample, the --percentage parameter is used (it should "
"be a value between 0.0 and 1.0)."
"\n\n"
"There are several options available for the algorithm used for each Lloyd "
"iteration, specified with the --algorithm (-a) option. The standard O(kN)"
" approach can be used ('naive'). Other options include the Pelleg-Moore "
"tree-based algorithm ('pelleg-moore'), Elkan's triangle-inequality based "
"algorithm ('elkan'), and Hamerly's modification to Elkan's algorithm "
"('hamerly')."
"\n\n"
"As of October 2014, the --overclustering option has been removed. If you "
"want this support back, let us know -- file a bug at "
"https://github.com/mlpack/mlpack/ or get in touch through another means.");
// Required options.
PARAM_STRING_REQ("inputFile", "Input dataset to perform clustering on.", "i");
PARAM_INT_REQ("clusters", "Number of clusters to find (0 autodetects from "
"initial centroids).", "c");
// Output options.
PARAM_FLAG("in_place", "If specified, a column containing the learned cluster "
"assignments will be added to the input dataset file. In this case, "
"--outputFile is overridden.", "P");
PARAM_STRING("output_file", "File to write output labels or labeled data to.",
"o", "");
PARAM_STRING("centroid_file", "If specified, the centroids of each cluster will"
" be written to the given file.", "C", "");
// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be created.", "e");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_INT("max_iterations", "Maximum number of iterations before K-Means "
"terminates.", "m", 1000);
PARAM_INT("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_STRING("initial_centroids", "Start with the specified initial centroids.",
"I", "");
// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
"and Fayyad to choose initial points.", "r");
PARAM_INT("samplings", "Number of samplings to perform for refined start (use "
"when --refined_start is specified).", "S", 100);
PARAM_DOUBLE("percentage", "Percentage of dataset to use for each refined start"
" sampling (use when --refined_start is specified).", "p", 0.02);
PARAM_STRING("algorithm", "Algorithm to use for the Lloyd iteration ('naive', "
"'pelleg-moore', 'elkan', 'hamerly', or 'dtnn').", "a", "naive");
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(const InitialPartitionPolicy& ipp);
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(const InitialPartitionPolicy& ipp);
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(const InitialPartitionPolicy& ipp);
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
// Initialize random seed.
if (CLI::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// Now, start building the KMeans type that we'll be using. Start with the
// initial partition policy. The call to FindEmptyClusterPolicy<> results in
// a call to RunKMeans<> and the algorithm is completed.
if (CLI::HasParam("refined_start"))
{
const int samplings = CLI::GetParam<int>("samplings");
const double percentage = CLI::GetParam<double>("percentage");
if (samplings < 0)
Log::Fatal << "Number of samplings (" << samplings << ") must be "
<< "greater than 0!" << endl;
if (percentage <= 0.0 || percentage > 1.0)
Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
<< "greater than 0.0 and less than or equal to 1.0!" << endl;
FindEmptyClusterPolicy<RefinedStart>(RefinedStart(samplings, percentage));
}
else
{
FindEmptyClusterPolicy<RandomPartition>(RandomPartition());
}
}
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(const InitialPartitionPolicy& ipp)
{
if (CLI::HasParam("allow_empty_clusters"))
FindLloydStepType<InitialPartitionPolicy, AllowEmptyClusters>(ipp);
else
FindLloydStepType<InitialPartitionPolicy, MaxVarianceNewCluster>(ipp);
}
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(const InitialPartitionPolicy& ipp)
{
const string algorithm = CLI::GetParam<string>("algorithm");
if (algorithm == "elkan")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, ElkanKMeans>(ipp);
else if (algorithm == "hamerly")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, HamerlyKMeans>(ipp);
else if (algorithm == "pelleg-moore")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
PellegMooreKMeans>(ipp);
else if (algorithm == "dtnn")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
DefaultDTNNKMeans>(ipp);
else if (algorithm == "dtnn-covertree")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
CoverTreeDTNNKMeans>(ipp);
else if (algorithm == "dualtree")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
DefaultDualTreeKMeans>(ipp);
else if (algorithm == "naive")
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, NaiveKMeans>(ipp);
else
Log::Fatal << "Unknown algorithm: '" << algorithm << "'. Supported options"
<< " are 'naive', 'pelleg-moore', 'elkan', and 'hamerly'." << endl;
}
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(const InitialPartitionPolicy& ipp)
{
// Now, do validation of input options.
const string inputFile = CLI::GetParam<string>("inputFile");
int clusters = CLI::GetParam<int>("clusters");
if (clusters < 0)
{
Log::Fatal << "Invalid number of clusters requested (" << clusters << ")! "
<< "Must be greater than or equal to 0." << endl;
}
else if (clusters == 0 && CLI::HasParam("initial_centroids"))
{
Log::Info << "Detecting number of clusters automatically from input "
<< "centroids." << endl;
}
else if (clusters == 0)
{
Log::Fatal << "Number of clusters requested is 0, and no initial centroids "
<< "provided!" << endl;
}
const int maxIterations = CLI::GetParam<int>("max_iterations");
if (maxIterations < 0)
{
Log::Fatal << "Invalid value for maximum iterations (" << maxIterations <<
")! Must be greater than or equal to 0." << endl;
}
// Make sure we have an output file if we're not doing the work in-place.
if (!CLI::HasParam("in_place") && !CLI::HasParam("output_file") &&
!CLI::HasParam("centroid_file"))
{
Log::Warn << "--output_file, --in_place, and --centroid_file are not set; "
<< "no results will be saved." << std::endl;
}
// Load our dataset.
arma::mat dataset;
data::Load(inputFile, dataset, true); // Fatal upon failure.
arma::mat centroids;
const bool initialCentroidGuess = CLI::HasParam("initial_centroids");
// Load initial centroids if the user asked for it.
if (initialCentroidGuess)
{
string initialCentroidsFile = CLI::GetParam<string>("initial_centroids");
data::Load(initialCentroidsFile, centroids, true);
if (clusters == 0)
clusters = centroids.n_cols;
if (CLI::HasParam("refined_start"))
Log::Warn << "Initial centroids are specified, but will be ignored "
<< "because --refined_start is also specified!" << endl;
else
Log::Info << "Using initial centroid guesses from '" <<
initialCentroidsFile << "'." << endl;
}
Timer::Start("clustering");
KMeans<metric::EuclideanDistance,
InitialPartitionPolicy,
EmptyClusterPolicy,
LloydStepType> kmeans(maxIterations, metric::EuclideanDistance(), ipp);
if (CLI::HasParam("output_file") || CLI::HasParam("in_place"))
{
// We need to get the assignments.
arma::Col<size_t> assignments;
kmeans.Cluster(dataset, clusters, assignments, centroids,
false, initialCentroidGuess);
Timer::Stop("clustering");
// Now figure out what to do with our results.
if (CLI::HasParam("in_place"))
{
// Add the column of assignments to the dataset; but we have to convert
// them to type double first.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Save the dataset.
data::Save(inputFile, dataset);
}
else
{
if (CLI::HasParam("labels_only"))
{
// Save only the labels.
string outputFile = CLI::GetParam<string>("output_file");
arma::Mat<size_t> output = trans(assignments);
data::Save(outputFile, output);
}
else
{
// Convert the assignments to doubles.
arma::vec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; i++)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, trans(converted));
// Now save, in the different file.
string outputFile = CLI::GetParam<string>("output_file");
data::Save(outputFile, dataset);
}
}
}
else
{
// Just save the centroids.
kmeans.Cluster(dataset, clusters, centroids, initialCentroidGuess);
Timer::Stop("clustering");
}
// Should we write the centroids to a file?
if (CLI::HasParam("centroid_file"))
data::Save(CLI::GetParam<std::string>("centroid_file"), centroids);
}
|
Update reference to Github.
|
Update reference to Github.
|
C++
|
bsd-3-clause
|
trungda/mlpack,trungda/mlpack,minhpqn/mlpack,bmswgnp/mlpack,ersanliqiao/mlpack,theranger/mlpack,ajjl/mlpack,theranger/mlpack,ranjan1990/mlpack,darcyliu/mlpack,ajjl/mlpack,minhpqn/mlpack,trungda/mlpack,lezorich/mlpack,stereomatchingkiss/mlpack,ranjan1990/mlpack,bmswgnp/mlpack,BookChan/mlpack,darcyliu/mlpack,thirdwing/mlpack,darcyliu/mlpack,palashahuja/mlpack,chenmoshushi/mlpack,erubboli/mlpack,ajjl/mlpack,BookChan/mlpack,Azizou/mlpack,ersanliqiao/mlpack,ranjan1990/mlpack,theranger/mlpack,thirdwing/mlpack,palashahuja/mlpack,chenmoshushi/mlpack,ersanliqiao/mlpack,thirdwing/mlpack,datachand/mlpack,datachand/mlpack,erubboli/mlpack,lezorich/mlpack,bmswgnp/mlpack,BookChan/mlpack,stereomatchingkiss/mlpack,chenmoshushi/mlpack,minhpqn/mlpack,lezorich/mlpack,datachand/mlpack,Azizou/mlpack,erubboli/mlpack,stereomatchingkiss/mlpack,palashahuja/mlpack,Azizou/mlpack
|
56f8bb84ab1f6677cbe184539640f1d8154a8830
|
src/primitives/block.cpp
|
src/primitives/block.cpp
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
// SYSCOIN setauxpow and remove gethash (moved to pureheader.cpp)
void CBlockHeader::SetAuxpow (CAuxPow* apow)
{
if (apow)
{
auxpow.reset(apow);
nVersion.SetAuxpow(true);
} else
{
auxpow.reset();
nVersion.SetAuxpow(false);
}
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion.GetFullVersion(),
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "crypto/common.h"
// SYSCOIN setauxpow and remove gethash (moved to pureheader.cpp)
void CBlockHeader::SetAuxpow (CAuxPow* apow)
{
if (apow)
{
auxpow.reset(apow);
nVersion.SetAuxpow(true);
} else
{
auxpow.reset();
nVersion.SetAuxpow(false);
}
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
|
Revert "block cpp"
|
Revert "block cpp"
This reverts commit 7482afc62b44cd8b4f9317a6ef287c304c8b6f91.
|
C++
|
mit
|
syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin
|
9a60eb3d0d50334d21131f7528215b1e6c42c74b
|
src/qt/savingsdialog.cpp
|
src/qt/savingsdialog.cpp
|
#include "savingsdialog.h"
#include "ui_savingsdialog.h"
#include "walletmodel.h"
#include "base58.h"
#include "addressbookpage.h"
#include "init.h"
#include <QLineEdit>
AutoSavingsDialog::AutoSavingsDialog(QWidget *parent) :
QWidget(parent),
ui(new Ui::AutoSavingsDialog),
model(0)
{
ui->setupUi(this);
ui->label_2->setFocus();
// turn off custom change address in fluttershare --ofeefee
ui->savingsChangeAddressEdit->setVisible(false);
ui->changeAddressBookButton->setVisible(false);
}
AutoSavingsDialog::~AutoSavingsDialog()
{
delete ui;
}
void AutoSavingsDialog::setModel(WalletModel *model)
{
this->model = model;
CBitcoinAddress strAddress;
CBitcoinAddress strChangeAddress;
int nPer;
int64 nMin;
int64 nMax;
model->getAutoSavings(nPer, strAddress, strChangeAddress, nMin, nMax);
if (strAddress.IsValid() && nPer > 0 )
{
ui->savingsAddressEdit->setText(strAddress.ToString().c_str());
ui->savingsPercentEdit->setText(QString::number(nPer));
if (strChangeAddress.IsValid())
ui->savingsChangeAddressEdit->setText(strChangeAddress.ToString().c_str());
if (nMin > 0 && nMin != MIN_TX_FEE)
ui->savingsMinEdit->setText(QString::number(nMin/COIN));
if (nMax > 0 && nMax != MAX_MONEY)
ui->savingsMaxEdit->setText(QString::number(nMax/COIN));
ui->message->setStyleSheet("QLabel { color: green; }");
ui->message->setText(tr("You are now saving to: ") + strAddress.ToString().c_str() + tr("."));
}
}
void AutoSavingsDialog::setAddress(const QString &address)
{
setAddress(address, ui->savingsAddressEdit);
}
void AutoSavingsDialog::setAddress(const QString &address, QLineEdit *addrEdit)
{
addrEdit->setText(address);
addrEdit->setFocus();
}
void AutoSavingsDialog::on_addressBookButton_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
setAddress(dlg.getReturnValue(), ui->savingsAddressEdit);
}
}
void AutoSavingsDialog::on_changeAddressBookButton_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
setAddress(dlg.getReturnValue(), ui->savingsChangeAddressEdit);
}
}
void AutoSavingsDialog::on_enableButton_clicked()
{
if(model->getEncryptionStatus() == WalletModel::Locked)
{
ui->message->setStyleSheet("QLabel { color: black; }");
ui->message->setText(tr("Please unlock wallet before starting auto savings."));
return;
}
bool fValidConversion = false;
int64 nMinAmount = MIN_TXOUT_AMOUNT;
int64 nMaxAmount = MAX_MONEY;
CBitcoinAddress changeAddress = "";
CBitcoinAddress address = ui->savingsAddressEdit->text().toStdString();
if (!address.IsValid())
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered address: ") + ui->savingsAddressEdit->text() + tr(" is invalid."));
ui->savingsAddressEdit->setFocus();
return;
}
int nSavingsPercent = ui->savingsPercentEdit->text().toInt(&fValidConversion, 10);
if (!fValidConversion || nSavingsPercent > 50 || nSavingsPercent <= 0)
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Please Enter 1 - 50 for percent."));
ui->savingsPercentEdit->setFocus();
return;
}
if (!ui->savingsMinEdit->text().isEmpty())
{
nMinAmount = ui->savingsMinEdit->text().toDouble(&fValidConversion) * COIN;
if(!fValidConversion || nMinAmount <= MIN_TXOUT_AMOUNT || nMinAmount >= MAX_MONEY )
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Min Amount out of Range, please re-enter."));
ui->savingsMinEdit->setFocus();
return;
}
}
if (!ui->savingsMaxEdit->text().isEmpty())
{
nMaxAmount = ui->savingsMaxEdit->text().toDouble(&fValidConversion) * COIN;
if(!fValidConversion || nMaxAmount <= MIN_TXOUT_AMOUNT || nMaxAmount >= MAX_MONEY )
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Max Amount out of Range, please re-enter."));
ui->savingsMaxEdit->setFocus();
return;
}
}
if (nMinAmount >= nMaxAmount)
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Min Amount > Max Amount, please re-enter."));
ui->savingsMinEdit->setFocus();
return;
}
if (!ui->savingsChangeAddressEdit->text().isEmpty())
{
changeAddress = ui->savingsChangeAddressEdit->text().toStdString();
if (!changeAddress.IsValid())
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered change address:\n") + ui->savingsChangeAddressEdit->text() + tr(" is invalid.\nPlease check the address and try again."));
ui->savingsChangeAddressEdit->setFocus();
return;
}
else if (!model->isMine(changeAddress))
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered change address:\n") + ui->savingsChangeAddressEdit->text() + tr(" is not owned.\nPlease check the address and try again."));
ui->savingsChangeAddressEdit->setFocus();
return;
}
}
model->setAutoSavings(true, nSavingsPercent, address, changeAddress, nMinAmount, nMaxAmount);
ui->message->setStyleSheet("QLabel { color: green; }");
ui->message->setText(tr("You are now saving to: ") + QString(address.ToString().c_str()) + tr("."));
return;
}
void AutoSavingsDialog::on_disableButton_clicked()
{
int nSavingsPercent = 0;
CBitcoinAddress address = "";
CBitcoinAddress changeAddress = "";
int64 nMinAmount = MIN_TXOUT_AMOUNT;
int64 nMaxAmount = MAX_MONEY;
model->setAutoSavings(false, nSavingsPercent, address, changeAddress, nMinAmount, nMaxAmount);
ui->savingsAddressEdit->clear();
ui->savingsMaxEdit->clear();
ui->savingsMinEdit->clear();
ui->savingsPercentEdit->clear();
ui->message->setStyleSheet("QLabel { color: black; }");
ui->message->setText(tr("Auto Savings is now off"));
return;
}
void AutoSavingsDialog::on_pushButton_copy_clicked()
{
ui->savingsAddressEdit->setText("FShqpDupfZKaw6zkDyqYhZop3P86NRZiet");
}
|
#include "savingsdialog.h"
#include "ui_savingsdialog.h"
#include "walletmodel.h"
#include "base58.h"
#include "addressbookpage.h"
#include "init.h"
#include <QLineEdit>
AutoSavingsDialog::AutoSavingsDialog(QWidget *parent) :
QWidget(parent),
ui(new Ui::AutoSavingsDialog),
model(0)
{
ui->setupUi(this);
ui->label_2->setFocus();
// turn off custom change address in fluttershare --ofeefee
ui->savingsChangeAddressEdit->setVisible(false);
ui->changeAddressBookButton->setVisible(false);
}
AutoSavingsDialog::~AutoSavingsDialog()
{
delete ui;
}
void AutoSavingsDialog::setModel(WalletModel *model)
{
this->model = model;
CBitcoinAddress strAddress;
CBitcoinAddress strChangeAddress;
int nPer;
int64 nMin;
int64 nMax;
model->getAutoSavings(nPer, strAddress, strChangeAddress, nMin, nMax);
if (strAddress.IsValid() && nPer > 0 )
{
ui->savingsAddressEdit->setText(strAddress.ToString().c_str());
ui->savingsPercentEdit->setText(QString::number(nPer));
if (strChangeAddress.IsValid())
ui->savingsChangeAddressEdit->setText(strChangeAddress.ToString().c_str());
if (nMin > 0 && nMin != MIN_TX_FEE)
ui->savingsMinEdit->setText(QString::number(nMin/COIN));
if (nMax > 0 && nMax != MAX_MONEY)
ui->savingsMaxEdit->setText(QString::number(nMax/COIN));
ui->message->setStyleSheet("QLabel { color: green; }");
ui->message->setText(tr("You are now sending to: ") + strAddress.ToString().c_str() + tr("."));
}
}
void AutoSavingsDialog::setAddress(const QString &address)
{
setAddress(address, ui->savingsAddressEdit);
}
void AutoSavingsDialog::setAddress(const QString &address, QLineEdit *addrEdit)
{
addrEdit->setText(address);
addrEdit->setFocus();
}
void AutoSavingsDialog::on_addressBookButton_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
setAddress(dlg.getReturnValue(), ui->savingsAddressEdit);
}
}
void AutoSavingsDialog::on_changeAddressBookButton_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
setAddress(dlg.getReturnValue(), ui->savingsChangeAddressEdit);
}
}
void AutoSavingsDialog::on_enableButton_clicked()
{
if(model->getEncryptionStatus() == WalletModel::Locked)
{
ui->message->setStyleSheet("QLabel { color: black; }");
ui->message->setText(tr("Please unlock wallet before starting auto savings."));
return;
}
bool fValidConversion = false;
int64 nMinAmount = MIN_TXOUT_AMOUNT;
int64 nMaxAmount = MAX_MONEY;
CBitcoinAddress changeAddress = "";
CBitcoinAddress address = ui->savingsAddressEdit->text().toStdString();
if (!address.IsValid())
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered address: ") + ui->savingsAddressEdit->text() + tr(" is invalid."));
ui->savingsAddressEdit->setFocus();
return;
}
int nSavingsPercent = ui->savingsPercentEdit->text().toInt(&fValidConversion, 10);
if (!fValidConversion || nSavingsPercent > 50 || nSavingsPercent <= 0)
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Please Enter 1 - 50 for percent."));
ui->savingsPercentEdit->setFocus();
return;
}
if (!ui->savingsMinEdit->text().isEmpty())
{
nMinAmount = ui->savingsMinEdit->text().toDouble(&fValidConversion) * COIN;
if(!fValidConversion || nMinAmount <= MIN_TXOUT_AMOUNT || nMinAmount >= MAX_MONEY )
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Min Amount out of Range, please re-enter."));
ui->savingsMinEdit->setFocus();
return;
}
}
if (!ui->savingsMaxEdit->text().isEmpty())
{
nMaxAmount = ui->savingsMaxEdit->text().toDouble(&fValidConversion) * COIN;
if(!fValidConversion || nMaxAmount <= MIN_TXOUT_AMOUNT || nMaxAmount >= MAX_MONEY )
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Max Amount out of Range, please re-enter."));
ui->savingsMaxEdit->setFocus();
return;
}
}
if (nMinAmount >= nMaxAmount)
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("Min Amount > Max Amount, please re-enter."));
ui->savingsMinEdit->setFocus();
return;
}
if (!ui->savingsChangeAddressEdit->text().isEmpty())
{
changeAddress = ui->savingsChangeAddressEdit->text().toStdString();
if (!changeAddress.IsValid())
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered change address:\n") + ui->savingsChangeAddressEdit->text() + tr(" is invalid.\nPlease check the address and try again."));
ui->savingsChangeAddressEdit->setFocus();
return;
}
else if (!model->isMine(changeAddress))
{
ui->message->setStyleSheet("QLabel { color: red; }");
ui->message->setText(tr("The entered change address:\n") + ui->savingsChangeAddressEdit->text() + tr(" is not owned.\nPlease check the address and try again."));
ui->savingsChangeAddressEdit->setFocus();
return;
}
}
model->setAutoSavings(true, nSavingsPercent, address, changeAddress, nMinAmount, nMaxAmount);
ui->message->setStyleSheet("QLabel { color: green; }");
ui->message->setText(tr("You are now sending to: ") + QString(address.ToString().c_str()) + tr("."));
return;
}
void AutoSavingsDialog::on_disableButton_clicked()
{
int nSavingsPercent = 0;
CBitcoinAddress address = "";
CBitcoinAddress changeAddress = "";
int64 nMinAmount = MIN_TXOUT_AMOUNT;
int64 nMaxAmount = MAX_MONEY;
model->setAutoSavings(false, nSavingsPercent, address, changeAddress, nMinAmount, nMaxAmount);
ui->savingsAddressEdit->clear();
ui->savingsMaxEdit->clear();
ui->savingsMinEdit->clear();
ui->savingsPercentEdit->clear();
ui->message->setStyleSheet("QLabel { color: black; }");
ui->message->setText(tr("FlutterShare is now off"));
return;
}
void AutoSavingsDialog::on_pushButton_copy_clicked()
{
ui->savingsAddressEdit->setText("FShqpDupfZKaw6zkDyqYhZop3P86NRZiet");
}
|
update labels
|
update labels
|
C++
|
mit
|
kizeren/fluttercoin,kizeren/fluttercoin,kizeren/fluttercoin,ofeefee/fluttercoin,ofeefee/fluttercoin,ofeefee/fluttercoin,kizeren/fluttercoin,kizeren/fluttercoin,ofeefee/fluttercoin,ofeefee/fluttercoin
|
3cdef2f5ec3c25d1ac08c27e8d023e4e429d7eb4
|
cpp/tests/unit-tests/CapabilitiesRegistrarTest.cpp
|
cpp/tests/unit-tests/CapabilitiesRegistrarTest.cpp
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include <limits>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/CapabilitiesRegistrar.h"
#include "joynr/IMessageSender.h"
#include "joynr/MessagingQos.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/types/DiscoveryEntryWithMetaInfo.h"
#include "joynr/types/DiscoveryQos.h"
#include "joynr/types/Version.h"
#include "tests/mock/MockDiscovery.h"
#include "tests/mock/MockDispatcher.h"
#include "tests/mock/MockProvider.h"
#include "tests/mock/MockMessageRouter.h"
#include "tests/mock/MockParticipantIdStorage.h"
#include "tests/mock/MockMessageSender.h"
using ::testing::DoAll;
using ::testing::InvokeArgument;
using ::testing::Mock;
using ::testing::Return;
using ::testing::Eq;
using ::testing::_;
using ::testing::Property;
using namespace joynr;
class CapabilitiesRegistrarTest : public ::testing::Test {
public:
CapabilitiesRegistrarTest() :
mockDispatcher(),
dispatcherAddress(),
mockParticipantIdStorage(new MockParticipantIdStorage()),
mockDiscovery(std::make_shared<MockDiscovery>()),
capabilitiesRegistrar(nullptr),
mockProvider(new MockProvider()),
domain("testDomain"),
expectedParticipantId("testParticipantId"),
enablePersistency(true),
singleThreadedIOService(std::make_shared<SingleThreadedIOService>()),
mockMessageRouter(new MockMessageRouter(singleThreadedIOService->getIOService())),
expectedProviderVersion(mockProvider->MAJOR_VERSION, mockProvider->MINOR_VERSION),
mockMessageSender(std::make_shared<MockMessageSender>()),
pubManager(std::make_shared<PublicationManager>(singleThreadedIOService->getIOService(), mockMessageSender, enablePersistency))
{
singleThreadedIOService->start();
}
~CapabilitiesRegistrarTest()
{
delete capabilitiesRegistrar;
pubManager->shutdown();
singleThreadedIOService->stop();
pubManager.reset();
mockMessageSender.reset();
}
void SetUp(){
std::vector<std::shared_ptr<IDispatcher>> dispatcherList;
mockDispatcher = std::make_shared<MockDispatcher>();
dispatcherList.push_back(mockDispatcher);
const std::string globalAddress = "testGlobalAddressString";
capabilitiesRegistrar = new CapabilitiesRegistrar(
dispatcherList,
mockDiscovery,
mockParticipantIdStorage,
dispatcherAddress,
mockMessageRouter,
std::numeric_limits<std::int64_t>::max(),
pubManager,
globalAddress
);
}
protected:
DISALLOW_COPY_AND_ASSIGN(CapabilitiesRegistrarTest);
std::shared_ptr<MockDispatcher> mockDispatcher;
std::shared_ptr<const joynr::system::RoutingTypes::Address> dispatcherAddress;
std::shared_ptr<MockParticipantIdStorage> mockParticipantIdStorage;
std::shared_ptr<MockDiscovery> mockDiscovery;
CapabilitiesRegistrar* capabilitiesRegistrar;
std::shared_ptr<MockProvider> mockProvider;
std::string domain;
std::string expectedParticipantId;
const bool enablePersistency;
std::shared_ptr<SingleThreadedIOService> singleThreadedIOService;
std::shared_ptr<MockMessageRouter> mockMessageRouter;
const types::Version expectedProviderVersion;
std::shared_ptr<IMessageSender> mockMessageSender;
std::shared_ptr<PublicationManager> pubManager;
};
TEST_F(CapabilitiesRegistrarTest, add){
types::ProviderQos testQos;
testQos.setPriority(100);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos)),
Property(&joynr::types::DiscoveryEntry::getProviderVersion, Eq(expectedProviderVersion))
),
_,
_,
_,
_
)
).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, checkVisibilityOfGlobalAndLocalProviders){
types::ProviderQos testQos;
testQos.setScope(types::ProviderScope::GLOBAL);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(2)
.WillRepeatedly(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
_,
_,
_,
_,
_
)
).Times(2).WillRepeatedly(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
ON_CALL(*mockMessageRouter, addNextHop(_,_,_,_,_,_,_,_)).WillByDefault(InvokeArgument<6>());
bool expectedIsGloballyVisible = true;
EXPECT_CALL(*mockMessageRouter, addNextHop(Eq(expectedParticipantId),Eq(dispatcherAddress),Eq(expectedIsGloballyVisible),_,_,_,_,_));
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
Mock::VerifyAndClearExpectations(mockMessageRouter.get());
testQos.setScope(types::ProviderScope::LOCAL);
expectedIsGloballyVisible = false;
EXPECT_CALL(*mockMessageRouter, addNextHop(Eq(expectedParticipantId),Eq(dispatcherAddress),Eq(expectedIsGloballyVisible),_,_,_,_,_));
Future<void> future1;
auto onSuccess1 = [&future1]() { future1.onSuccess(); };
auto onError1 = [&future1](const exceptions::JoynrRuntimeException& exception) {
future1.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess1, onError1);
future1.get();
}
TEST_F(CapabilitiesRegistrarTest, removeWithDomainAndProviderObject){
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
EXPECT_CALL(*mockDispatcher, removeRequestCaller(expectedParticipantId))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(*mockDiscovery, removeAsyncMock(
expectedParticipantId,
_,
_,
_
))
.Times(1)
.WillOnce(
DoAll(InvokeArgument<1>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->removeAsync(domain, mockProvider, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, removeWithParticipantId){
EXPECT_CALL(*mockDispatcher, removeRequestCaller(expectedParticipantId))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(*mockDiscovery, removeAsyncMock(
expectedParticipantId,
_,
_,
_
))
.Times(1)
.WillOnce(
DoAll(InvokeArgument<1>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->removeAsync(expectedParticipantId, onSuccess, onError);
future.get();
}
TEST_F(CapabilitiesRegistrarTest, registerMultipleDispatchersAndRegisterCapability){
auto mockDispatcher1 = std::make_shared<MockDispatcher>();
auto mockDispatcher2 = std::make_shared<MockDispatcher>();
types::ProviderQos testQos;
testQos.setPriority(100);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos))
),
_,
_,
_,
_
)
).Times(1).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
EXPECT_CALL(*mockDispatcher1, addRequestCaller(expectedParticipantId,_))
.Times(1);
EXPECT_CALL(*mockDispatcher2, addRequestCaller(expectedParticipantId,_))
.Times(1);
capabilitiesRegistrar->addDispatcher(mockDispatcher1);
capabilitiesRegistrar->addDispatcher(mockDispatcher2);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, removeDispatcher){
auto mockDispatcher1 = std::make_shared<MockDispatcher>();
auto mockDispatcher2 = std::make_shared<MockDispatcher>();
types::ProviderQos testQos;
testQos.setPriority(100);
capabilitiesRegistrar->addDispatcher(mockDispatcher1);
capabilitiesRegistrar->addDispatcher(mockDispatcher2);
capabilitiesRegistrar->removeDispatcher(mockDispatcher1);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos))
),
_,
_,
_,
_
)
).Times(1).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
//mockDispatcher1 should not be used as it was removed
EXPECT_CALL(*mockDispatcher1, addRequestCaller(expectedParticipantId,_))
.Times(0);
EXPECT_CALL(*mockDispatcher2, addRequestCaller(expectedParticipantId,_))
.Times(1);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include <limits>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/CapabilitiesRegistrar.h"
#include "joynr/IMessageSender.h"
#include "joynr/MessagingQos.h"
#include "joynr/PrivateCopyAssign.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/types/DiscoveryEntryWithMetaInfo.h"
#include "joynr/types/DiscoveryQos.h"
#include "joynr/types/Version.h"
#include "tests/mock/MockDiscovery.h"
#include "tests/mock/MockDispatcher.h"
#include "tests/mock/MockProvider.h"
#include "tests/mock/MockMessageRouter.h"
#include "tests/mock/MockParticipantIdStorage.h"
#include "tests/mock/MockMessageSender.h"
using ::testing::DoAll;
using ::testing::InvokeArgument;
using ::testing::Mock;
using ::testing::Return;
using ::testing::Eq;
using ::testing::_;
using ::testing::Property;
using namespace joynr;
class CapabilitiesRegistrarTest : public ::testing::Test {
public:
CapabilitiesRegistrarTest() :
mockDispatcher(),
dispatcherAddress(),
mockParticipantIdStorage(std::make_shared<MockParticipantIdStorage>()),
mockDiscovery(std::make_shared<MockDiscovery>()),
capabilitiesRegistrar(nullptr),
mockProvider(std::make_shared<MockProvider>()),
domain("testDomain"),
expectedParticipantId("testParticipantId"),
enablePersistency(true),
singleThreadedIOService(std::make_shared<SingleThreadedIOService>()),
mockMessageRouter(std::make_shared< MockMessageRouter>(singleThreadedIOService->getIOService())),
expectedProviderVersion(mockProvider->MAJOR_VERSION, mockProvider->MINOR_VERSION),
mockMessageSender(std::make_shared<MockMessageSender>()),
pubManager(std::make_shared<PublicationManager>(singleThreadedIOService->getIOService(), mockMessageSender, enablePersistency))
{
singleThreadedIOService->start();
}
~CapabilitiesRegistrarTest()
{
delete capabilitiesRegistrar;
pubManager->shutdown();
singleThreadedIOService->stop();
pubManager.reset();
mockMessageSender.reset();
}
void SetUp(){
std::vector<std::shared_ptr<IDispatcher>> dispatcherList;
mockDispatcher = std::make_shared<MockDispatcher>();
dispatcherList.push_back(mockDispatcher);
const std::string globalAddress = "testGlobalAddressString";
capabilitiesRegistrar = new CapabilitiesRegistrar(
dispatcherList,
mockDiscovery,
mockParticipantIdStorage,
dispatcherAddress,
mockMessageRouter,
std::numeric_limits<std::int64_t>::max(),
pubManager,
globalAddress
);
}
protected:
DISALLOW_COPY_AND_ASSIGN(CapabilitiesRegistrarTest);
std::shared_ptr<MockDispatcher> mockDispatcher;
std::shared_ptr<const joynr::system::RoutingTypes::Address> dispatcherAddress;
std::shared_ptr<MockParticipantIdStorage> mockParticipantIdStorage;
std::shared_ptr<MockDiscovery> mockDiscovery;
CapabilitiesRegistrar* capabilitiesRegistrar;
std::shared_ptr<MockProvider> mockProvider;
std::string domain;
std::string expectedParticipantId;
const bool enablePersistency;
std::shared_ptr<SingleThreadedIOService> singleThreadedIOService;
std::shared_ptr<MockMessageRouter> mockMessageRouter;
const types::Version expectedProviderVersion;
std::shared_ptr<IMessageSender> mockMessageSender;
std::shared_ptr<PublicationManager> pubManager;
};
TEST_F(CapabilitiesRegistrarTest, add){
types::ProviderQos testQos;
testQos.setPriority(100);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos)),
Property(&joynr::types::DiscoveryEntry::getProviderVersion, Eq(expectedProviderVersion))
),
_,
_,
_,
_
)
).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, checkVisibilityOfGlobalAndLocalProviders){
types::ProviderQos testQos;
testQos.setScope(types::ProviderScope::GLOBAL);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(2)
.WillRepeatedly(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
_,
_,
_,
_,
_
)
).Times(2).WillRepeatedly(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
ON_CALL(*mockMessageRouter, addNextHop(_,_,_,_,_,_,_,_)).WillByDefault(InvokeArgument<6>());
bool expectedIsGloballyVisible = true;
EXPECT_CALL(*mockMessageRouter, addNextHop(Eq(expectedParticipantId),Eq(dispatcherAddress),Eq(expectedIsGloballyVisible),_,_,_,_,_));
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
Mock::VerifyAndClearExpectations(mockMessageRouter.get());
testQos.setScope(types::ProviderScope::LOCAL);
expectedIsGloballyVisible = false;
EXPECT_CALL(*mockMessageRouter, addNextHop(Eq(expectedParticipantId),Eq(dispatcherAddress),Eq(expectedIsGloballyVisible),_,_,_,_,_));
Future<void> future1;
auto onSuccess1 = [&future1]() { future1.onSuccess(); };
auto onError1 = [&future1](const exceptions::JoynrRuntimeException& exception) {
future1.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess1, onError1);
future1.get();
}
TEST_F(CapabilitiesRegistrarTest, removeWithDomainAndProviderObject){
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
EXPECT_CALL(*mockDispatcher, removeRequestCaller(expectedParticipantId))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(*mockDiscovery, removeAsyncMock(
expectedParticipantId,
_,
_,
_
))
.Times(1)
.WillOnce(
DoAll(InvokeArgument<1>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->removeAsync(domain, mockProvider, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, removeWithParticipantId){
EXPECT_CALL(*mockDispatcher, removeRequestCaller(expectedParticipantId))
.Times(1);
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(*mockDiscovery, removeAsyncMock(
expectedParticipantId,
_,
_,
_
))
.Times(1)
.WillOnce(
DoAll(InvokeArgument<1>(),
Return(mockFuture)
)
);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
capabilitiesRegistrar->removeAsync(expectedParticipantId, onSuccess, onError);
future.get();
}
TEST_F(CapabilitiesRegistrarTest, registerMultipleDispatchersAndRegisterCapability){
auto mockDispatcher1 = std::make_shared<MockDispatcher>();
auto mockDispatcher2 = std::make_shared<MockDispatcher>();
types::ProviderQos testQos;
testQos.setPriority(100);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos))
),
_,
_,
_,
_
)
).Times(1).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
EXPECT_CALL(*mockDispatcher1, addRequestCaller(expectedParticipantId,_))
.Times(1);
EXPECT_CALL(*mockDispatcher2, addRequestCaller(expectedParticipantId,_))
.Times(1);
capabilitiesRegistrar->addDispatcher(mockDispatcher1);
capabilitiesRegistrar->addDispatcher(mockDispatcher2);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
TEST_F(CapabilitiesRegistrarTest, removeDispatcher){
auto mockDispatcher1 = std::make_shared<MockDispatcher>();
auto mockDispatcher2 = std::make_shared<MockDispatcher>();
types::ProviderQos testQos;
testQos.setPriority(100);
capabilitiesRegistrar->addDispatcher(mockDispatcher1);
capabilitiesRegistrar->addDispatcher(mockDispatcher2);
capabilitiesRegistrar->removeDispatcher(mockDispatcher1);
EXPECT_CALL(*mockParticipantIdStorage, getProviderParticipantId(
domain,
MockProvider::INTERFACE_NAME()
))
.Times(1)
.WillOnce(Return(expectedParticipantId));
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(
*mockDiscovery,
addAsyncMock(
AllOf(
Property(&joynr::types::DiscoveryEntry::getDomain, Eq(domain)),
Property(&joynr::types::DiscoveryEntry::getInterfaceName, Eq(MockProvider::INTERFACE_NAME())),
Property(&joynr::types::DiscoveryEntry::getParticipantId, Eq(expectedParticipantId)),
Property(&joynr::types::DiscoveryEntry::getQos, Eq(testQos))
),
_,
_,
_,
_
)
).Times(1).WillOnce(
DoAll(InvokeArgument<2>(),
Return(mockFuture)
)
);
EXPECT_CALL(*mockDispatcher, addRequestCaller(expectedParticipantId,_))
.Times(1);
//mockDispatcher1 should not be used as it was removed
EXPECT_CALL(*mockDispatcher1, addRequestCaller(expectedParticipantId,_))
.Times(0);
EXPECT_CALL(*mockDispatcher2, addRequestCaller(expectedParticipantId,_))
.Times(1);
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
std::string participantId = capabilitiesRegistrar->addAsync(domain, mockProvider, testQos, onSuccess, onError);
future.get();
EXPECT_EQ(expectedParticipantId, participantId);
}
|
use std::make_shared instead of new in CapabilitiesRegistrarTest
|
[C++] use std::make_shared instead of new in CapabilitiesRegistrarTest
Change-Id: If43305cb112fb34acfaf803edacdf2c2f6d11ba4
|
C++
|
apache-2.0
|
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
|
cb1fefc0b94e0693e3b5c5151bf75d1bb16a3bed
|
src/media/plugins/music/lastfmprovider.cpp
|
src/media/plugins/music/lastfmprovider.cpp
|
#include "lastfmprovider.h"
#define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__
LastFMProvider::LastFMProvider(QSqlDatabase db, QObject *parent) :
QObject(parent),
m_reply(0),
m_db(db)
{
m_networkAccessManager = new QNetworkAccessManager(this);
m_query = new QSqlQuery(m_db);
m_query->setForwardOnly(true);
m_query->exec("SELECT id, artist, title, album, track FROM music WHERE thumbnail IS NULL");
connect(this, SIGNAL(replyFinished()), this, SLOT(requestNext()));
emit replyFinished();
}
void LastFMProvider::handleTitleReply()
{
qDebug() << "handle TITLE reply";
QXmlStreamReader reader(m_reply);
bool trackTagFound = false;
bool albumTagFound = false;
bool albumTitleTagFound = false;
while (reader.readNext() && !reader.isEndDocument()) {
if (reader.isStartElement() && reader.name() == "track") {
trackTagFound = true;
}
if (trackTagFound && reader.isStartElement() && reader.name() == "album") {
albumTagFound = true;
m_currentTrack = reader.attributes().value("position").toString().toInt();
}
if (albumTagFound && !albumTitleTagFound && reader.isStartElement() && reader.name() == "title") {
albumTitleTagFound = true;
if (reader.readNext() && reader.isCharacters())
m_currentAlbum = reader.text().toString();
}
if (albumTagFound && reader.isStartElement() && reader.name() == "image" && reader.attributes().value("size") == "large") {
if (reader.readNext() && reader.isCharacters())
m_currentThumbnail = reader.text().toString();
}
}
m_reply->deleteLater();
m_reply = 0;
// if thumbnail still empty try to get artist info
if (m_currentThumbnail.isEmpty()) {
requestArtistInformation();
} else {
updateDatabase();
emit replyFinished();
}
}
void LastFMProvider::handleArtistReply()
{
qDebug() << "handle ARTIST reply";
QXmlStreamReader reader(m_reply);
bool artistTagFound = false;
while (reader.readNext() && !reader.isEndDocument()) {
qDebug() << reader.name();
if (reader.name() == "artist") {
qDebug() << "============== artist found";
artistTagFound = true;
}
if (artistTagFound && reader.name() == "image" && reader.attributes().value("size") == "large") {
qDebug() << "==============";
if (reader.readNext() && reader.isCharacters())
m_currentThumbnail = reader.text().toString();
break;
}
}
DEBUG << "artist query result" << m_currentThumbnail;
updateDatabase();
m_reply->deleteLater();
m_reply = 0;
emit replyFinished();
}
void LastFMProvider::requestNext()
{
if (m_query->next()) {
m_currentId = m_query->value(0).toString();
m_currentArtist = m_query->value(1).toString();
m_currentTitle = m_query->value(2).toString();
m_currentAlbum = m_query->value(3).toString();
m_currentTrack = m_query->value(4).toInt();
DEBUG << "empty thumbnail for" << m_currentId << m_currentArtist << m_currentTitle;
// first try to get full title information
requestTitleInformation();
} else {
emit allRequestsFinished();
}
}
void LastFMProvider::handleError(QNetworkReply::NetworkError code)
{
qWarning() << "cannot fetch lastFM data" << m_reply->errorString();
m_reply->deleteLater();
m_reply = 0;
emit replyFinished();
}
void LastFMProvider::updateDatabase()
{
DEBUG << "metadata from lastfm:" << m_currentId << m_currentAlbum << m_currentTrack << m_currentThumbnail;
QSqlQuery query(m_db);
if (!query.prepare("UPDATE music SET thumbnail=:thumbnail WHERE id=:id")) {
qWarning() << query.lastError().text();
}
query.bindValue(":thumbnail", m_currentThumbnail);
query.bindValue(":id", m_currentId);
if (!query.exec())
qWarning() << query.lastError().text();
}
void LastFMProvider::requestTitleInformation()
{
static const QString apiUri = QString::fromLatin1("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=e7e3601ddce49a72b56c758d29af4a3f&");
QString requestString = apiUri + "artist=" + m_currentArtist + "&track=" + m_currentTitle;
DEBUG << "TITLE query" << requestString;
// execute request to lastFM
m_reply = m_networkAccessManager->get(QNetworkRequest(QUrl(requestString)));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(handleTitleReply()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
}
void LastFMProvider::requestArtistInformation()
{
static const QString apiUri = QString::fromLatin1("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=e7e3601ddce49a72b56c758d29af4a3f&");
QString requestString = apiUri + "artist=" + m_currentArtist;
DEBUG << "ARTIST query" << requestString;
// execute request to lastFM
m_reply = m_networkAccessManager->get(QNetworkRequest(QUrl(requestString)));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(handleArtistReply()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
}
|
#include "lastfmprovider.h"
#define DEBUG if (0) qDebug() << __PRETTY_FUNCTION__
LastFMProvider::LastFMProvider(QSqlDatabase db, QObject *parent) :
QObject(parent),
m_reply(0),
m_db(db)
{
m_networkAccessManager = new QNetworkAccessManager(this);
m_query = new QSqlQuery(m_db);
m_query->setForwardOnly(true);
m_query->exec("SELECT id, artist, title, album, track FROM music WHERE thumbnail IS NULL");
connect(this, SIGNAL(replyFinished()), this, SLOT(requestNext()));
emit replyFinished();
}
void LastFMProvider::handleTitleReply()
{
DEBUG << "handle TITLE reply";
QXmlStreamReader reader(m_reply);
bool trackTagFound = false;
bool albumTagFound = false;
bool albumTitleTagFound = false;
while (reader.readNext() && !reader.isEndDocument()) {
if (reader.isStartElement() && reader.name() == "track") {
trackTagFound = true;
}
if (trackTagFound && reader.isStartElement() && reader.name() == "album") {
albumTagFound = true;
m_currentTrack = reader.attributes().value("position").toString().toInt();
}
if (albumTagFound && !albumTitleTagFound && reader.isStartElement() && reader.name() == "title") {
albumTitleTagFound = true;
if (reader.readNext() && reader.isCharacters())
m_currentAlbum = reader.text().toString();
}
if (albumTagFound && reader.isStartElement() && reader.name() == "image" && reader.attributes().value("size") == "large") {
if (reader.readNext() && reader.isCharacters())
m_currentThumbnail = reader.text().toString();
}
}
m_reply->deleteLater();
m_reply = 0;
// if thumbnail still empty try to get artist info
if (m_currentThumbnail.isEmpty()) {
requestArtistInformation();
} else {
updateDatabase();
emit replyFinished();
}
}
void LastFMProvider::handleArtistReply()
{
DEBUG << "handle ARTIST reply";
QXmlStreamReader reader(m_reply);
bool artistTagFound = false;
while (reader.readNext() && !reader.isEndDocument()) {
if (reader.name() == "artist") {
artistTagFound = true;
}
if (artistTagFound && reader.name() == "image" && reader.attributes().value("size") == "large") {
if (reader.readNext() && reader.isCharacters())
m_currentThumbnail = reader.text().toString();
break;
}
}
DEBUG << "artist query result" << m_currentThumbnail;
updateDatabase();
m_reply->deleteLater();
m_reply = 0;
emit replyFinished();
}
void LastFMProvider::requestNext()
{
if (m_query->next()) {
m_currentId = m_query->value(0).toString();
m_currentArtist = m_query->value(1).toString();
m_currentTitle = m_query->value(2).toString();
m_currentAlbum = m_query->value(3).toString();
m_currentTrack = m_query->value(4).toInt();
DEBUG << "empty thumbnail for" << m_currentId << m_currentArtist << m_currentTitle;
// first try to get full title information
requestTitleInformation();
} else {
emit allRequestsFinished();
}
}
void LastFMProvider::handleError(QNetworkReply::NetworkError code)
{
qWarning() << "cannot fetch lastFM data" << m_reply->errorString();
m_reply->deleteLater();
m_reply = 0;
emit replyFinished();
}
void LastFMProvider::updateDatabase()
{
DEBUG << "metadata from lastfm:" << m_currentId << m_currentAlbum << m_currentTrack << m_currentThumbnail;
QSqlQuery query(m_db);
if (!query.prepare("UPDATE music SET thumbnail=:thumbnail WHERE id=:id")) {
qWarning() << query.lastError().text();
}
query.bindValue(":thumbnail", m_currentThumbnail);
query.bindValue(":id", m_currentId);
if (!query.exec())
qWarning() << query.lastError().text();
}
void LastFMProvider::requestTitleInformation()
{
static const QString apiUri = QString::fromLatin1("http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=e7e3601ddce49a72b56c758d29af4a3f&");
QString requestString = apiUri + "artist=" + m_currentArtist + "&track=" + m_currentTitle;
DEBUG << "TITLE query" << requestString;
// execute request to lastFM
m_reply = m_networkAccessManager->get(QNetworkRequest(QUrl(requestString)));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(handleTitleReply()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
}
void LastFMProvider::requestArtistInformation()
{
static const QString apiUri = QString::fromLatin1("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=e7e3601ddce49a72b56c758d29af4a3f&");
QString requestString = apiUri + "artist=" + m_currentArtist;
DEBUG << "ARTIST query" << requestString;
// execute request to lastFM
m_reply = m_networkAccessManager->get(QNetworkRequest(QUrl(requestString)));
connect(m_reply, SIGNAL(readyRead()), this, SLOT(handleArtistReply()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)));
}
|
remove debug output
|
remove debug output
|
C++
|
bsd-3-clause
|
qtmediahub/sasquatch,qtmediahub/sasquatch,qtmediahub/sasquatch
|
179fcdefe75ad9425bdea8281ea44aaffb4e763b
|
src/ngraph/runtime/reference/avg_pool.hpp
|
src/ngraph/runtime/reference/avg_pool.hpp
|
//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <cmath>
#include <numeric>
#include <vector>
#include "ngraph/axis_vector.hpp"
#include "ngraph/coordinate_transform.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
namespace runtime
{
namespace reference
{
template <typename T>
void avg_pool_backprop(const T* delta,
T* out,
const Shape& delta_shape,
const Shape& out_shape,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
bool include_padding_in_avg_computation)
{
CoordinateTransform out_transform(out_shape);
for (const Coordinate& out_coord : out_transform)
{
out[out_transform.index(out_coord)] = 0;
}
CoordinateTransform delta_transform(delta_shape);
for (const Coordinate& delta_coord : delta_transform)
{
size_t img_index = delta_coord[0];
size_t channel = delta_coord[1];
size_t n_image_dimensions = out_shape.size() - 2;
Coordinate source_window_transform_start(2 + n_image_dimensions);
Coordinate source_window_transform_end(2 + n_image_dimensions);
Strides source_window_transform_source_strides(2 + n_image_dimensions, 1);
AxisVector source_window_transform_source_axis_order(2 + n_image_dimensions);
CoordinateDiff source_window_transform_padding_below(2 + n_image_dimensions);
CoordinateDiff source_window_transform_padding_above(2 + n_image_dimensions);
source_window_transform_start[0] = img_index;
source_window_transform_end[0] = img_index + 1;
source_window_transform_start[1] = channel;
source_window_transform_end[1] = channel + 1;
source_window_transform_padding_below[0] = 0;
source_window_transform_padding_below[1] = 0;
source_window_transform_padding_above[0] = 0;
source_window_transform_padding_above[1] = 0;
for (size_t i = 2; i < n_image_dimensions + 2; i++)
{
size_t window_shape_this_dim = window_shape[i - 2];
size_t movement_stride = window_movement_strides[i - 2];
source_window_transform_start[i] = movement_stride * delta_coord[i];
source_window_transform_end[i] =
source_window_transform_start[i] + window_shape_this_dim;
source_window_transform_padding_below[i] = padding_below[i - 2];
source_window_transform_padding_above[i] = padding_above[i - 2];
}
std::iota(begin(source_window_transform_source_axis_order),
end(source_window_transform_source_axis_order),
0);
CoordinateTransform source_window_transform(
out_shape,
source_window_transform_start,
source_window_transform_end,
source_window_transform_source_strides,
source_window_transform_source_axis_order,
source_window_transform_padding_below,
source_window_transform_padding_above);
size_t num_elements_in_window = 0;
for (const Coordinate& source_window_coord : source_window_transform)
{
if (source_window_transform.has_source_coordinate(source_window_coord) ||
include_padding_in_avg_computation)
{
num_elements_in_window++;
}
}
for (const Coordinate& source_window_coord : source_window_transform)
{
if (source_window_transform.has_source_coordinate(source_window_coord))
{
size_t out_index = source_window_transform.index(source_window_coord);
out[out_index] +=
delta[delta_transform.index(delta_coord)] / num_elements_in_window;
}
}
}
}
template <typename T>
void avg_pool(const T* arg,
T* out,
const Shape& arg_shape,
const Shape& out_shape,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
bool include_padding_in_avg_computation)
{
// At the outermost level we will walk over every output coordinate O.
CoordinateTransform output_transform(out_shape);
for (const Coordinate& out_coord : output_transform)
{
// Our output coordinate O will have the form:
//
// (N,chan,i_1,...,i_n)
size_t batch_index = out_coord[0];
size_t channel = out_coord[1];
// For the input data we need to iterate the coordinate:
//
// I:
//
// over the range (noninclusive on the right):
//
// (N,chan,s_1*i_1,s_2*i_2,...,s_n*i_n) ->
//
// (N+1,chan+1,s_1*i_1 + window_shape_1,...,s_n*i_n + window_shape_n)
//
// with unit stride.
//
// We iterate this over the *padded* data, so below we will need to check for coordinates that fall in the padding area.
size_t n_spatial_dimensions = arg_shape.size() - 2;
Coordinate input_batch_transform_start(2 + n_spatial_dimensions);
Coordinate input_batch_transform_end(2 + n_spatial_dimensions);
Strides input_batch_transform_source_strides(2 + n_spatial_dimensions, 1);
AxisVector input_batch_transform_source_axis_order(2 + n_spatial_dimensions);
CoordinateDiff input_batch_transform_padding_below(2 + n_spatial_dimensions);
CoordinateDiff input_batch_transform_padding_above(2 + n_spatial_dimensions);
input_batch_transform_start[0] = batch_index;
input_batch_transform_end[0] = batch_index + 1;
input_batch_transform_start[1] = channel;
input_batch_transform_end[1] = channel + 1;
input_batch_transform_padding_below[0] = 0;
input_batch_transform_padding_below[1] = 0;
input_batch_transform_padding_above[0] = 0;
input_batch_transform_padding_above[1] = 0;
for (size_t i = 2; i < n_spatial_dimensions + 2; i++)
{
size_t window_shape_this_dim = window_shape[i - 2];
size_t movement_stride = window_movement_strides[i - 2];
input_batch_transform_start[i] = movement_stride * out_coord[i];
input_batch_transform_end[i] =
input_batch_transform_start[i] + window_shape_this_dim;
input_batch_transform_padding_below[i] = padding_below[i - 2];
input_batch_transform_padding_above[i] = padding_above[i - 2];
}
for (size_t i = 0; i < arg_shape.size(); i++)
{
input_batch_transform_source_axis_order[i] = i;
}
CoordinateTransform input_batch_transform(
arg_shape,
input_batch_transform_start,
input_batch_transform_end,
input_batch_transform_source_strides,
input_batch_transform_source_axis_order,
input_batch_transform_padding_below,
input_batch_transform_padding_above);
// As we go, we compute the sum value:
//
// output[O] := output[O] + arg[I]
//
// and the number of elements:
//
// n_elements := n_elements + 1
T result = 0;
size_t n_elements = 0;
for (const Coordinate& input_batch_coord : input_batch_transform)
{
bool in_bounds =
input_batch_transform.has_source_coordinate(input_batch_coord);
if (in_bounds || include_padding_in_avg_computation)
{
T v =
in_bounds ? arg[input_batch_transform.index(input_batch_coord)] : 0;
result += v;
n_elements++;
}
}
if (n_elements == 0)
{
throw std::runtime_error("AvgPool elements == 0, must be non-zero");
}
out[output_transform.index(out_coord)] = result / n_elements;
}
}
}
}
}
|
//*****************************************************************************
// Copyright 2017-2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <cmath>
#include <numeric>
#include <stdexcept>
#include <vector>
#include "ngraph/axis_vector.hpp"
#include "ngraph/coordinate_transform.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
namespace runtime
{
namespace reference
{
template <typename T>
void avg_pool_backprop(const T* delta,
T* out,
const Shape& delta_shape,
const Shape& out_shape,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
bool include_padding_in_avg_computation)
{
CoordinateTransform out_transform(out_shape);
for (const Coordinate& out_coord : out_transform)
{
out[out_transform.index(out_coord)] = 0;
}
CoordinateTransform delta_transform(delta_shape);
for (const Coordinate& delta_coord : delta_transform)
{
size_t img_index = delta_coord[0];
size_t channel = delta_coord[1];
size_t n_image_dimensions = out_shape.size() - 2;
Coordinate source_window_transform_start(2 + n_image_dimensions);
Coordinate source_window_transform_end(2 + n_image_dimensions);
Strides source_window_transform_source_strides(2 + n_image_dimensions, 1);
AxisVector source_window_transform_source_axis_order(2 + n_image_dimensions);
CoordinateDiff source_window_transform_padding_below(2 + n_image_dimensions);
CoordinateDiff source_window_transform_padding_above(2 + n_image_dimensions);
source_window_transform_start[0] = img_index;
source_window_transform_end[0] = img_index + 1;
source_window_transform_start[1] = channel;
source_window_transform_end[1] = channel + 1;
source_window_transform_padding_below[0] = 0;
source_window_transform_padding_below[1] = 0;
source_window_transform_padding_above[0] = 0;
source_window_transform_padding_above[1] = 0;
for (size_t i = 2; i < n_image_dimensions + 2; i++)
{
size_t window_shape_this_dim = window_shape[i - 2];
size_t movement_stride = window_movement_strides[i - 2];
source_window_transform_start[i] = movement_stride * delta_coord[i];
source_window_transform_end[i] =
source_window_transform_start[i] + window_shape_this_dim;
source_window_transform_padding_below[i] = padding_below[i - 2];
source_window_transform_padding_above[i] = padding_above[i - 2];
}
std::iota(begin(source_window_transform_source_axis_order),
end(source_window_transform_source_axis_order),
0);
CoordinateTransform source_window_transform(
out_shape,
source_window_transform_start,
source_window_transform_end,
source_window_transform_source_strides,
source_window_transform_source_axis_order,
source_window_transform_padding_below,
source_window_transform_padding_above);
size_t num_elements_in_window = 0;
for (const Coordinate& source_window_coord : source_window_transform)
{
if (source_window_transform.has_source_coordinate(source_window_coord) ||
include_padding_in_avg_computation)
{
num_elements_in_window++;
}
}
for (const Coordinate& source_window_coord : source_window_transform)
{
if (source_window_transform.has_source_coordinate(source_window_coord))
{
size_t out_index = source_window_transform.index(source_window_coord);
out[out_index] +=
delta[delta_transform.index(delta_coord)] / num_elements_in_window;
}
}
}
}
template <typename T>
void avg_pool(const T* arg,
T* out,
const Shape& arg_shape,
const Shape& out_shape,
const Shape& window_shape,
const Strides& window_movement_strides,
const Shape& padding_below,
const Shape& padding_above,
bool include_padding_in_avg_computation)
{
// At the outermost level we will walk over every output coordinate O.
CoordinateTransform output_transform(out_shape);
for (const Coordinate& out_coord : output_transform)
{
// Our output coordinate O will have the form:
//
// (N,chan,i_1,...,i_n)
size_t batch_index = out_coord[0];
size_t channel = out_coord[1];
// For the input data we need to iterate the coordinate:
//
// I:
//
// over the range (noninclusive on the right):
//
// (N,chan,s_1*i_1,s_2*i_2,...,s_n*i_n) ->
//
// (N+1,chan+1,s_1*i_1 + window_shape_1,...,s_n*i_n + window_shape_n)
//
// with unit stride.
//
// We iterate this over the *padded* data, so below we will need to check for coordinates that fall in the padding area.
size_t n_spatial_dimensions = arg_shape.size() - 2;
Coordinate input_batch_transform_start(2 + n_spatial_dimensions);
Coordinate input_batch_transform_end(2 + n_spatial_dimensions);
Strides input_batch_transform_source_strides(2 + n_spatial_dimensions, 1);
AxisVector input_batch_transform_source_axis_order(2 + n_spatial_dimensions);
CoordinateDiff input_batch_transform_padding_below(2 + n_spatial_dimensions);
CoordinateDiff input_batch_transform_padding_above(2 + n_spatial_dimensions);
input_batch_transform_start[0] = batch_index;
input_batch_transform_end[0] = batch_index + 1;
input_batch_transform_start[1] = channel;
input_batch_transform_end[1] = channel + 1;
input_batch_transform_padding_below[0] = 0;
input_batch_transform_padding_below[1] = 0;
input_batch_transform_padding_above[0] = 0;
input_batch_transform_padding_above[1] = 0;
for (size_t i = 2; i < n_spatial_dimensions + 2; i++)
{
size_t window_shape_this_dim = window_shape[i - 2];
size_t movement_stride = window_movement_strides[i - 2];
input_batch_transform_start[i] = movement_stride * out_coord[i];
input_batch_transform_end[i] =
input_batch_transform_start[i] + window_shape_this_dim;
input_batch_transform_padding_below[i] = padding_below[i - 2];
input_batch_transform_padding_above[i] = padding_above[i - 2];
}
for (size_t i = 0; i < arg_shape.size(); i++)
{
input_batch_transform_source_axis_order[i] = i;
}
CoordinateTransform input_batch_transform(
arg_shape,
input_batch_transform_start,
input_batch_transform_end,
input_batch_transform_source_strides,
input_batch_transform_source_axis_order,
input_batch_transform_padding_below,
input_batch_transform_padding_above);
// As we go, we compute the sum value:
//
// output[O] := output[O] + arg[I]
//
// and the number of elements:
//
// n_elements := n_elements + 1
T result = 0;
size_t n_elements = 0;
for (const Coordinate& input_batch_coord : input_batch_transform)
{
bool in_bounds =
input_batch_transform.has_source_coordinate(input_batch_coord);
if (in_bounds || include_padding_in_avg_computation)
{
T v =
in_bounds ? arg[input_batch_transform.index(input_batch_coord)] : 0;
result += v;
n_elements++;
}
}
if (n_elements == 0)
{
throw std::runtime_error("AvgPool elements == 0, must be non-zero");
}
out[output_transform.index(out_coord)] = result / n_elements;
}
}
}
}
}
|
Add missing #include to reference/avg_pool.hpp (#2263)
|
Add missing #include to reference/avg_pool.hpp (#2263)
|
C++
|
apache-2.0
|
NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph,NervanaSystems/ngraph
|
347991a1c35ebb9bb3278e7bc06ad2af4e98c4a5
|
src/openboardview/FileFormats/CADFile.cpp
|
src/openboardview/FileFormats/CADFile.cpp
|
#include "CADFile.h"
#include "utils.h"
#include <assert.h>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <locale.h>
#include <stdint.h>
#include <string.h>
#include <unordered_map>
char *nextfield(char *p) {
if (p) {
while ((*p != '\t') && (*p != '\0') && (*p != '\r') && (*p != '\n')) {
p++;
}
}
if (*p == '\t') p++;
return p;
}
#define OUTLINE_MARGIN 20
void CADFile::gen_outline() {
// Determine board outline
int minx =
std::min_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.x < b.pos.x; })->pos.x - OUTLINE_MARGIN;
int maxx =
std::max_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.x < b.pos.x; })->pos.x + OUTLINE_MARGIN;
int miny =
std::min_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.y < b.pos.y; })->pos.y - OUTLINE_MARGIN;
int maxy =
std::max_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.y < b.pos.y; })->pos.y + OUTLINE_MARGIN;
format.push_back({minx, miny});
format.push_back({maxx, miny});
format.push_back({maxx, maxy});
format.push_back({minx, maxy});
format.push_back({minx, miny});
}
#undef OUTLINE_MARGIN
CADFile::CADFile(std::vector<char> &buf) {
auto buffer_size = buf.size();
float multiplier = 1000.0f;
char *saved_locale;
saved_locale = setlocale(LC_NUMERIC, "C"); // Use '.' as delimiter for strtod
ENSURE(buffer_size > 4);
size_t file_buf_size = 3 * (1 + buffer_size);
file_buf = (char *)calloc(1, file_buf_size);
ENSURE(file_buf != nullptr);
std::copy(buf.begin(), buf.end(), file_buf);
file_buf[buffer_size] = 0;
// This is for fixing degenerate utf8
char *arena = &file_buf[buffer_size + 1];
char *arena_end = file_buf + file_buf_size - 1;
*arena_end = 0;
int current_block = 0;
std::unordered_map<std::string, int> parts_id; // map between part name and part number
char **lines = stringfile(file_buf);
ENSURE(lines);
while (*lines) {
char *line = *lines;
++lines;
while (isspace((uint8_t)*line)) line++;
if (!line[0]) continue;
if (!strncmp(line, "COMP", 4)) {
current_block = 1;
} else if (!strncmp(line, "C_PIN", 5)) {
current_block = 2;
} else {
current_block = -1;
continue;
}
char *p = line;
char *s;
switch (current_block) {
case 1: { // Parts
BRDPart part;
BRDPin pin;
/*char *TYPE =*/READ_STR();
part.name = READ_STR();
/*char *Part(NR)=*/READ_STR();
/*char *Unknown =*/READ_STR();
/*char *Unknown =*/READ_STR();
/*char *X =*/READ_STR();
/*char *Y =*/READ_STR();
char *loc = READ_STR();
/*int *Unknown =*/READ_STR();
part.part_type = BRDPartType::SMD;
if (!strcmp(loc, "1"))//top 1 bot 2
part.mounting_side = BRDPartMountingSide::Top; // SMD part on top
else
part.mounting_side = BRDPartMountingSide::Bottom; // SMD part on bottom
part.end_of_pins = 0;
parts.push_back(part);
parts_id[part.name] = parts.size();
} break;
case 2: { // Pins
BRDPin pin;
/*char *TYPE =*/READ_STR();
char *part = READ_STR();
char *ptr;
ptr = strchr(part, '-'); //remove all after
if (ptr != NULL) //
{*ptr = '\0';} //
pin.part = parts_id.at(part);
double posx = READ_DOUBLE();
pin.pos.x = posx * multiplier;
double posy = READ_DOUBLE();
pin.pos.y = posy * multiplier;
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
pin.net = READ_STR();
pins.push_back(pin);
} break;
default: continue;
}
}
gen_outline();
num_parts = parts.size();
num_pins = pins.size();
num_format = format.size();
num_nails = nails.size();
setlocale(LC_NUMERIC, saved_locale); // Restore locale
valid = current_block != 0;
}
|
#include "CADFile.h"
#include "utils.h"
#include <assert.h>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <locale.h>
#include <stdint.h>
#include <string.h>
#include <unordered_map>
#define OUTLINE_MARGIN 20
void CADFile::gen_outline() {
// Determine board outline
int minx =
std::min_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.x < b.pos.x; })->pos.x - OUTLINE_MARGIN;
int maxx =
std::max_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.x < b.pos.x; })->pos.x + OUTLINE_MARGIN;
int miny =
std::min_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.y < b.pos.y; })->pos.y - OUTLINE_MARGIN;
int maxy =
std::max_element(pins.begin(), pins.end(), [](BRDPin a, BRDPin b) { return a.pos.y < b.pos.y; })->pos.y + OUTLINE_MARGIN;
format.push_back({minx, miny});
format.push_back({maxx, miny});
format.push_back({maxx, maxy});
format.push_back({minx, maxy});
format.push_back({minx, miny});
}
#undef OUTLINE_MARGIN
CADFile::CADFile(std::vector<char> &buf) {
auto buffer_size = buf.size();
float multiplier = 1000.0f;
char *saved_locale;
saved_locale = setlocale(LC_NUMERIC, "C"); // Use '.' as delimiter for strtod
ENSURE(buffer_size > 4);
size_t file_buf_size = 3 * (1 + buffer_size);
file_buf = (char *)calloc(1, file_buf_size);
ENSURE(file_buf != nullptr);
std::copy(buf.begin(), buf.end(), file_buf);
file_buf[buffer_size] = 0;
// This is for fixing degenerate utf8
char *arena = &file_buf[buffer_size + 1];
char *arena_end = file_buf + file_buf_size - 1;
*arena_end = 0;
int current_block = 0;
std::unordered_map<std::string, int> parts_id; // map between part name and part number
char **lines = stringfile(file_buf);
ENSURE(lines);
while (*lines) {
char *line = *lines;
++lines;
while (isspace((uint8_t)*line)) line++;
if (!line[0]) continue;
if (!strncmp(line, "COMP", 4)) {
current_block = 1;
} else if (!strncmp(line, "C_PIN", 5)) {
current_block = 2;
} else {
current_block = -1;
continue;
}
char *p = line;
char *s;
switch (current_block) {
case 1: { // Parts
BRDPart part;
BRDPin pin;
/*char *TYPE =*/READ_STR();
part.name = READ_STR();
/*char *Part(NR)=*/READ_STR();
/*char *Unknown =*/READ_STR();
/*char *Unknown =*/READ_STR();
/*char *X =*/READ_STR();
/*char *Y =*/READ_STR();
char *loc = READ_STR();
/*int *Unknown =*/READ_STR();
part.part_type = BRDPartType::SMD;
if (!strcmp(loc, "1"))//top 1 bot 2
part.mounting_side = BRDPartMountingSide::Top; // SMD part on top
else
part.mounting_side = BRDPartMountingSide::Bottom; // SMD part on bottom
part.end_of_pins = 0;
parts.push_back(part);
parts_id[part.name] = parts.size();
} break;
case 2: { // Pins
BRDPin pin;
/*char *TYPE =*/READ_STR();
char *part = READ_STR();
char *ptr;
ptr = strchr(part, '-'); //remove all after
if (ptr != NULL) //
{*ptr = '\0';} //
pin.part = parts_id.at(part);
double posx = READ_DOUBLE();
pin.pos.x = posx * multiplier;
double posy = READ_DOUBLE();
pin.pos.y = posy * multiplier;
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
/*int *Unknown =*/READ_UINT();
pin.net = READ_STR();
pins.push_back(pin);
} break;
default: continue;
}
}
gen_outline();
num_parts = parts.size();
num_pins = pins.size();
num_format = format.size();
num_nails = nails.size();
setlocale(LC_NUMERIC, saved_locale); // Restore locale
valid = current_block != 0;
}
|
Update CADFile.cpp
|
Update CADFile.cpp
|
C++
|
mit
|
chloridite/OpenBoardView,chloridite/OpenBoardView
|
3d8b636f9e506261c3993a8d716a68fbe5c1d095
|
brightray/browser/linux/inspectable_web_contents_view_linux.cc
|
brightray/browser/linux/inspectable_web_contents_view_linux.cc
|
#include "browser/linux/inspectable_web_contents_view_linux.h"
#include <glib-object.h>
#include <gtk/gtk.h>
#include "base/strings/stringprintf.h"
#include "browser/browser_client.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents) {
return new InspectableWebContentsViewLinux(inspectable_web_contents);
}
InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(
InspectableWebContentsImpl* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_window_(NULL) {
}
InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() {
if (devtools_window_) gtk_widget_destroy(devtools_window_);
}
#if 0 // some utility functions to debug GTK window hierarchies
static void dump_one(GtkWidget *wat, int indent) {
GtkAllocation alloc;
gtk_widget_get_allocation(wat, &alloc);
fprintf(stderr, "%*s[%p] %s @%d,%d %dx%d",
indent, "", wat,
g_type_name_from_instance((GTypeInstance*)wat),
alloc.x, alloc.y, alloc.width, alloc.height);
if (GTK_IS_WINDOW(wat)) {
fprintf(stderr, " - \"%s\"", gtk_window_get_title(GTK_WINDOW(wat)));
}
fputc('\n', stderr);
}
static void dump_the_whole_tree(GtkWidget *wat, int indent) {
if (!wat) {
fprintf(stderr, "(nil)\n");
return;
}
dump_one(wat, indent);
GList *kids = gtk_container_get_children(GTK_CONTAINER(wat));
for (GList *p = kids; p; p = p->next) {
dump_the_whole_tree(GTK_WIDGET(p->data), indent+2);
}
}
static void dump_parents(GtkWidget *wat) {
fprintf(stderr, "Parents:\n");
for (GtkWidget *p = gtk_widget_get_parent(wat); p; p = gtk_widget_get_parent(p)) {
dump_one(p, 2);
}
}
#endif
gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const {
auto web_contents = inspectable_web_contents_->GetWebContents();
return web_contents->GetView()->GetNativeView();
}
/* This code is a little bit hairy.
The dev tools can be in any one of five places:
1. Unassigned and invisible. This is the default state until someone asks
to 'inspect element' for the first time. In this case, devtools->parent is
NULL.
2. In an onscreen window, visible.
3. In the bottom half of a GtkVPaned.
4. In the right half of a GtkHPaned.
5. In an offscreen window, invisible. This is where they go once they have
been displayed and the user asks to "close" them. They can't be put back
into the unassigned state.
ShowDevTools() and is responsible for transitioning from any one of these
states to the three visible states, 2-4, as indicated by the contents of the
'dockside_' variable. The helper functions ShowDevToolsInWindow and
ShowDevToolsInPane focus on transitioning to states 2 and 3+4, respectively.
These helper functions are responsible for the entire transition, including
cleaning up any extraneous containers from the old state.
Hiding the dev tools is taken care of by CloseDevTools (from paned states
3+4 to invisible state 5) or by the "delete-event" signal on the
devtools_window_ (from window state 2 to 5).
Remember that GTK does reference counting, so a view with no refs and no
parent will be freed. Views that have a ref but no parents will lose their
dimensions. So it's best to move the devtools view from place to place with
gtk_widget_reparent whenever possible. Unfortunately, one cannot reparent
things into a GtkPaned, so fairly brittle use of g_object_[un]ref and
gtk_container_remove happens.
*/
void InspectableWebContentsViewLinux::ShowDevTools() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
DLOG(INFO) << base::StringPrintf(
"InspectableWebContentsViewLinux::ShowDevTools - parent=%s@%p window=%p dockside=\"%s\"",
g_type_name_from_instance((GTypeInstance*)parent),
parent,
devtools_window_,
dockside_.c_str());
if (!parent || GTK_IS_PANED(parent)) {
if (dockside_ == "undocked") ShowDevToolsInWindow();
else if (dockside_ == "bottom") ShowDevToolsInPane(true);
else if (dockside_ == "right") ShowDevToolsInPane(false);
} else {
DCHECK(parent == devtools_window_);
if (dockside_ == "undocked") gtk_widget_show_all(parent);
else if (dockside_ == "bottom") ShowDevToolsInPane(true);
else if (dockside_ == "right") ShowDevToolsInPane(false);
}
}
void InspectableWebContentsViewLinux::CloseDevTools() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
DLOG(INFO) << base::StringPrintf(
"InspectableWebContentsViewLinux::CloseDevTools - parent=%s@%p window=%p dockside=\"%s\"",
g_type_name_from_instance((GTypeInstance*)parent),
parent,
devtools_window_,
dockside_.c_str());
if (!parent)
return; // Not visible -> nothing to do
if (GTK_IS_PANED(parent)) {
GtkWidget *browser = GetBrowserWindow();
GtkWidget *view = GetNativeView();
if (!devtools_window_) MakeDevToolsWindow();
gtk_widget_reparent(devtools, devtools_window_);
g_object_ref(parent);
gtk_container_remove(GTK_CONTAINER(browser), parent);
gtk_widget_reparent(view, browser);
g_object_unref(parent);
} else {
DCHECK(parent == devtools_window_);
gtk_widget_hide(parent);
}
}
bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) {
DLOG(INFO) <<
"InspectableWebContentsViewLinux::SetDockSide: \"" << side << "\"";
if (side != "undocked" && side != "bottom" && side != "right")
return false; // unsupported display location
if (dockside_ == side)
return true; // no change from current location
dockside_ = side;
// If devtools already has a parent, then we're being asked to move it.
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
if (gtk_widget_get_parent(devtools)) {
ShowDevTools();
}
return true;
}
void InspectableWebContentsViewLinux::ShowDevToolsInWindow() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
if (!devtools_window_)
MakeDevToolsWindow();
if (!parent) {
gtk_container_add(GTK_CONTAINER(devtools_window_), devtools);
} else if (parent != devtools_window_) {
DCHECK(GTK_IS_PANED(parent));
gtk_widget_reparent(devtools, devtools_window_);
// Remove the pane.
GtkWidget *view = GetNativeView();
GtkWidget *browser = GetBrowserWindow();
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(parent), view);
gtk_container_remove(GTK_CONTAINER(browser), parent);
gtk_container_add(GTK_CONTAINER(browser), view);
g_object_unref(view);
}
gtk_widget_show_all(devtools_window_);
}
void InspectableWebContentsViewLinux::MakeDevToolsWindow() {
DCHECK(!devtools_window_);
devtools_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(devtools_window_), "Developer Tools");
gtk_window_set_default_size(GTK_WINDOW(devtools_window_), 800, 600);
g_signal_connect(GTK_OBJECT(devtools_window_),
"delete-event",
G_CALLBACK(gtk_widget_hide_on_delete),
this);
}
void InspectableWebContentsViewLinux::ShowDevToolsInPane(bool on_bottom) {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
GtkWidget *pane = on_bottom ? gtk_vpaned_new() : gtk_hpaned_new();
GtkWidget *view = GetNativeView();
GtkWidget *browser = GetBrowserWindow();
GtkAllocation alloc;
gtk_widget_get_allocation(browser, &alloc);
gtk_paned_set_position(GTK_PANED(pane),
on_bottom ? alloc.height * 2 / 3 : alloc.width / 2);
if (!parent) {
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(browser), view);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
} else if (GTK_IS_PANED(parent)) {
g_object_ref(view);
g_object_ref(devtools);
gtk_container_remove(GTK_CONTAINER(parent), view);
gtk_container_remove(GTK_CONTAINER(parent), devtools);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
g_object_unref(devtools);
gtk_container_remove(GTK_CONTAINER(browser), parent);
} else {
DCHECK(parent == devtools_window_);
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(devtools_window_), devtools);
gtk_container_remove(GTK_CONTAINER(browser), view);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
gtk_widget_hide(devtools_window_);
}
gtk_container_add(GTK_CONTAINER(browser), pane);
gtk_widget_show_all(pane);
}
GtkWidget *InspectableWebContentsViewLinux::GetBrowserWindow() {
GtkWidget *view = GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(view);
GtkWidget *browser =
GTK_IS_PANED(parent) ? gtk_widget_get_parent(parent) : parent;
DCHECK(GTK_IS_WINDOW(browser));
return browser;
}
} // namespace brightray
|
#include "browser/linux/inspectable_web_contents_view_linux.h"
#include <glib-object.h>
#include <gtk/gtk.h>
#include "base/strings/stringprintf.h"
#include "browser/browser_client.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents) {
return new InspectableWebContentsViewLinux(inspectable_web_contents);
}
InspectableWebContentsViewLinux::InspectableWebContentsViewLinux(
InspectableWebContentsImpl* inspectable_web_contents)
: inspectable_web_contents_(inspectable_web_contents),
devtools_window_(NULL) {
}
InspectableWebContentsViewLinux::~InspectableWebContentsViewLinux() {
if (devtools_window_) gtk_widget_destroy(devtools_window_);
}
#if 0 // some utility functions to debug GTK window hierarchies
static void dump_one(GtkWidget *wat, int indent) {
GtkAllocation alloc;
gtk_widget_get_allocation(wat, &alloc);
fprintf(stderr, "%*s[%p] %s @%d,%d %dx%d",
indent, "", wat,
g_type_name_from_instance(reinterpret_cast<GTypeInstance*>(wat)),
alloc.x, alloc.y, alloc.width, alloc.height);
if (GTK_IS_WINDOW(wat)) {
fprintf(stderr, " - \"%s\"", gtk_window_get_title(GTK_WINDOW(wat)));
}
fputc('\n', stderr);
}
static void dump_the_whole_tree(GtkWidget *wat, int indent) {
if (!wat) {
fprintf(stderr, "(nil)\n");
return;
}
dump_one(wat, indent);
GList *kids = gtk_container_get_children(GTK_CONTAINER(wat));
for (GList *p = kids; p; p = p->next) {
dump_the_whole_tree(GTK_WIDGET(p->data), indent+2);
}
}
static void dump_parents(GtkWidget *wat) {
fprintf(stderr, "Parents:\n");
for (GtkWidget *p = gtk_widget_get_parent(wat);
p;
p = gtk_widget_get_parent(p)) {
dump_one(p, 2);
}
}
#endif
gfx::NativeView InspectableWebContentsViewLinux::GetNativeView() const {
auto web_contents = inspectable_web_contents_->GetWebContents();
return web_contents->GetView()->GetNativeView();
}
/* This code is a little bit hairy.
The dev tools can be in any one of five places:
1. Unassigned and invisible. This is the default state until someone asks
to 'inspect element' for the first time. In this case, devtools->parent is
NULL.
2. In an onscreen window, visible.
3. In the bottom half of a GtkVPaned.
4. In the right half of a GtkHPaned.
5. In an offscreen window, invisible. This is where they go once they have
been displayed and the user asks to "close" them. They can't be put back
into the unassigned state.
ShowDevTools() and is responsible for transitioning from any one of these
states to the three visible states, 2-4, as indicated by the contents of the
'dockside_' variable. The helper functions ShowDevToolsInWindow and
ShowDevToolsInPane focus on transitioning to states 2 and 3+4, respectively.
These helper functions are responsible for the entire transition, including
cleaning up any extraneous containers from the old state.
Hiding the dev tools is taken care of by CloseDevTools (from paned states
3+4 to invisible state 5) or by the "delete-event" signal on the
devtools_window_ (from window state 2 to 5).
Remember that GTK does reference counting, so a view with no refs and no
parent will be freed. Views that have a ref but no parents will lose their
dimensions. So it's best to move the devtools view from place to place with
gtk_widget_reparent whenever possible. Unfortunately, one cannot reparent
things into a GtkPaned, so fairly brittle use of g_object_[un]ref and
gtk_container_remove happens.
*/
void InspectableWebContentsViewLinux::ShowDevTools() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
DLOG(INFO) << base::StringPrintf(
"InspectableWebContentsViewLinux::ShowDevTools - " \
"parent=%s@%p window=%p dockside=\"%s\"",
g_type_name_from_instance(reinterpret_cast<GTypeInstance*>(parent)),
parent,
devtools_window_,
dockside_.c_str());
if (!parent || GTK_IS_PANED(parent)) {
if (dockside_ == "undocked") ShowDevToolsInWindow();
else if (dockside_ == "bottom") ShowDevToolsInPane(true);
else if (dockside_ == "right") ShowDevToolsInPane(false);
} else {
DCHECK(parent == devtools_window_);
if (dockside_ == "undocked") gtk_widget_show_all(parent);
else if (dockside_ == "bottom") ShowDevToolsInPane(true);
else if (dockside_ == "right") ShowDevToolsInPane(false);
}
}
void InspectableWebContentsViewLinux::CloseDevTools() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
DLOG(INFO) << base::StringPrintf(
"InspectableWebContentsViewLinux::CloseDevTools - " \
"parent=%s@%p window=%p dockside=\"%s\"",
g_type_name_from_instance(reinterpret_cast<GTypeInstance*>(parent)),
parent,
devtools_window_,
dockside_.c_str());
if (!parent)
return; // Not visible -> nothing to do
if (GTK_IS_PANED(parent)) {
GtkWidget *browser = GetBrowserWindow();
GtkWidget *view = GetNativeView();
if (!devtools_window_) MakeDevToolsWindow();
gtk_widget_reparent(devtools, devtools_window_);
g_object_ref(parent);
gtk_container_remove(GTK_CONTAINER(browser), parent);
gtk_widget_reparent(view, browser);
g_object_unref(parent);
} else {
DCHECK(parent == devtools_window_);
gtk_widget_hide(parent);
}
}
bool InspectableWebContentsViewLinux::SetDockSide(const std::string& side) {
DLOG(INFO) <<
"InspectableWebContentsViewLinux::SetDockSide: \"" << side << "\"";
if (side != "undocked" && side != "bottom" && side != "right")
return false; // unsupported display location
if (dockside_ == side)
return true; // no change from current location
dockside_ = side;
// If devtools already has a parent, then we're being asked to move it.
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
if (gtk_widget_get_parent(devtools)) {
ShowDevTools();
}
return true;
}
void InspectableWebContentsViewLinux::ShowDevToolsInWindow() {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
if (!devtools_window_)
MakeDevToolsWindow();
if (!parent) {
gtk_container_add(GTK_CONTAINER(devtools_window_), devtools);
} else if (parent != devtools_window_) {
DCHECK(GTK_IS_PANED(parent));
gtk_widget_reparent(devtools, devtools_window_);
// Remove the pane.
GtkWidget *view = GetNativeView();
GtkWidget *browser = GetBrowserWindow();
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(parent), view);
gtk_container_remove(GTK_CONTAINER(browser), parent);
gtk_container_add(GTK_CONTAINER(browser), view);
g_object_unref(view);
}
gtk_widget_show_all(devtools_window_);
}
void InspectableWebContentsViewLinux::MakeDevToolsWindow() {
DCHECK(!devtools_window_);
devtools_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(devtools_window_), "Developer Tools");
gtk_window_set_default_size(GTK_WINDOW(devtools_window_), 800, 600);
g_signal_connect(GTK_OBJECT(devtools_window_),
"delete-event",
G_CALLBACK(gtk_widget_hide_on_delete),
this);
}
void InspectableWebContentsViewLinux::ShowDevToolsInPane(bool on_bottom) {
auto devtools_web_contents =
inspectable_web_contents()->devtools_web_contents();
GtkWidget *devtools = devtools_web_contents->GetView()->GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(devtools);
GtkWidget *pane = on_bottom ? gtk_vpaned_new() : gtk_hpaned_new();
GtkWidget *view = GetNativeView();
GtkWidget *browser = GetBrowserWindow();
GtkAllocation alloc;
gtk_widget_get_allocation(browser, &alloc);
gtk_paned_set_position(GTK_PANED(pane),
on_bottom ? alloc.height * 2 / 3 : alloc.width / 2);
if (!parent) {
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(browser), view);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
} else if (GTK_IS_PANED(parent)) {
g_object_ref(view);
g_object_ref(devtools);
gtk_container_remove(GTK_CONTAINER(parent), view);
gtk_container_remove(GTK_CONTAINER(parent), devtools);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
g_object_unref(devtools);
gtk_container_remove(GTK_CONTAINER(browser), parent);
} else {
DCHECK(parent == devtools_window_);
g_object_ref(view);
gtk_container_remove(GTK_CONTAINER(devtools_window_), devtools);
gtk_container_remove(GTK_CONTAINER(browser), view);
gtk_paned_add1(GTK_PANED(pane), view);
gtk_paned_add2(GTK_PANED(pane), devtools);
g_object_unref(view);
gtk_widget_hide(devtools_window_);
}
gtk_container_add(GTK_CONTAINER(browser), pane);
gtk_widget_show_all(pane);
}
GtkWidget *InspectableWebContentsViewLinux::GetBrowserWindow() {
GtkWidget *view = GetNativeView();
GtkWidget *parent = gtk_widget_get_parent(view);
GtkWidget *browser =
GTK_IS_PANED(parent) ? gtk_widget_get_parent(parent) : parent;
DCHECK(GTK_IS_WINDOW(browser));
return browser;
}
} // namespace brightray
|
Fix remaining cpplint errors in inspectable_web_contents_view_linux.cc
|
Fix remaining cpplint errors in inspectable_web_contents_view_linux.cc
|
C++
|
mit
|
gerhardberger/electron,bpasero/electron,gerhardberger/electron,the-ress/electron,electron/electron,biblerule/UMCTelnetHub,gerhardberger/electron,shiftkey/electron,tonyganch/electron,rajatsingla28/electron,biblerule/UMCTelnetHub,shiftkey/electron,wan-qy/electron,electron/electron,Floato/electron,renaesop/electron,bpasero/electron,miniak/electron,miniak/electron,seanchas116/electron,rreimann/electron,rajatsingla28/electron,seanchas116/electron,bpasero/electron,gerhardberger/electron,the-ress/electron,the-ress/electron,wan-qy/electron,electron/electron,biblerule/UMCTelnetHub,miniak/electron,thomsonreuters/electron,wan-qy/electron,renaesop/electron,tonyganch/electron,renaesop/electron,thomsonreuters/electron,renaesop/electron,shiftkey/electron,bpasero/electron,renaesop/electron,shiftkey/electron,tonyganch/electron,shiftkey/electron,Floato/electron,electron/electron,rreimann/electron,Floato/electron,seanchas116/electron,rreimann/electron,thomsonreuters/electron,rajatsingla28/electron,rreimann/electron,rreimann/electron,gerhardberger/electron,Floato/electron,the-ress/electron,rajatsingla28/electron,gerhardberger/electron,rajatsingla28/electron,Floato/electron,thomsonreuters/electron,electron/electron,the-ress/electron,miniak/electron,the-ress/electron,rajatsingla28/electron,wan-qy/electron,gerhardberger/electron,Floato/electron,biblerule/UMCTelnetHub,tonyganch/electron,biblerule/UMCTelnetHub,seanchas116/electron,tonyganch/electron,the-ress/electron,electron/electron,bpasero/electron,renaesop/electron,seanchas116/electron,tonyganch/electron,shiftkey/electron,thomsonreuters/electron,bpasero/electron,biblerule/UMCTelnetHub,electron/electron,wan-qy/electron,wan-qy/electron,miniak/electron,seanchas116/electron,thomsonreuters/electron,rreimann/electron,miniak/electron,bpasero/electron
|
17cda5c55273813cbedcced3a511f1c222978182
|
src/gui/painting/qwindowsurface_x11.cpp
|
src/gui/painting/qwindowsurface_x11.cpp
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui/QPaintDevice>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QWidget>
#include "private/qt_x11_p.h"
#include "private/qpixmap_x11_p.h"
#include "private/qwidget_p.h"
#include "qx11info_x11.h"
#include "qwindowsurface_x11_p.h"
QT_BEGIN_NAMESPACE
extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp
struct QX11WindowSurfacePrivate
{
QWidget *widget;
QPixmap device;
#ifndef QT_NO_XRENDER
bool translucentBackground;
#endif
};
QX11WindowSurface::QX11WindowSurface(QWidget *widget)
: QWindowSurface(widget), d_ptr(new QX11WindowSurfacePrivate), gc(0)
{
d_ptr->widget = widget;
#ifndef QT_NO_XRENDER
d_ptr->translucentBackground = X11->use_xrender
&& widget->x11Info().depth() == 32;
setStaticContentsSupport(!d_ptr->translucentBackground);
#else
setStaticContentsSupport(true);
#endif
}
QX11WindowSurface::~QX11WindowSurface()
{
delete d_ptr;
if (gc) {
XFreeGC(X11->display, gc);
gc = 0;
}
}
QPaintDevice *QX11WindowSurface::paintDevice()
{
return &d_ptr->device;
}
void QX11WindowSurface::beginPaint(const QRegion &rgn)
{
#ifndef QT_NO_XRENDER
if (d_ptr->translucentBackground) {
if (d_ptr->device.depth() != 32)
static_cast<QX11PixmapData *>(d_ptr->device.data_ptr().data())->convertToARGB32();
::Picture src = X11->getSolidFill(d_ptr->device.x11Info().screen(), Qt::transparent);
::Picture dst = d_ptr->device.x11PictureHandle();
const QVector<QRect> rects = rgn.rects();
const int w = d_ptr->device.width();
const int h = d_ptr->device.height();
for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it)
XRenderComposite(X11->display, PictOpSrc, src, 0, dst,
0, 0, w, h, it->x(), it->y(),
it->width(), it->height());
}
#endif
}
void QX11WindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
{
if (d_ptr->device.isNull())
return;
QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();
QRegion wrgn(rgn);
QRect br = rgn.boundingRect();
if (!wOffset.isNull())
wrgn.translate(-wOffset);
QRect wbr = wrgn.boundingRect();
int num;
XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num);
if (num <= 0)
return;
// qDebug() << "XSetClipRectangles";
// for (int i = 0; i < num; ++i)
// qDebug() << ' ' << i << rects[i].x << rects[i].x << rects[i].y << rects[i].width << rects[i].height;
if (num != 1)
XSetClipRectangles(X11->display, gc, 0, 0, rects, num, YXBanded);
XCopyArea(X11->display, d_ptr->device.handle(), widget->handle(), gc,
br.x() + offset.x(), br.y() + offset.y(), br.width(), br.height(), wbr.x(), wbr.y());
if (num != 1)
XSetClipMask(X11->display, gc, XNone);
}
void QX11WindowSurface::setGeometry(const QRect &rect)
{
QWindowSurface::setGeometry(rect);
const QSize size = rect.size();
if (d_ptr->device.size() == size || size.width() <= 0 || size.height() <= 0)
return;
#ifndef QT_NO_XRENDER
if (d_ptr->translucentBackground) {
QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType);
data->xinfo = d_ptr->widget->x11Info();
data->resize(size.width(), size.height());
d_ptr->device = QPixmap(data);
} else
#endif
{
QPixmap::x11SetDefaultScreen(d_ptr->widget->x11Info().screen());
QX11PixmapData *oldData = static_cast<QX11PixmapData *>(d_ptr->device.pixmapData());
Q_ASSERT(oldData);
if (!(oldData->flags & QX11PixmapData::Uninitialized) && hasStaticContents()) {
// Copy the content of the old pixmap into the new one.
QX11PixmapData *newData = new QX11PixmapData(QPixmapData::PixmapType);
newData->resize(size.width(), size.height());
Q_ASSERT(oldData->d == newData->d);
QRegion staticRegion(staticContents());
// Make sure we're inside the boundaries of the old pixmap.
staticRegion &= QRect(0, 0, oldData->w, oldData->h);
const QRect boundingRect(staticRegion.boundingRect());
const int dx = boundingRect.x();
const int dy = boundingRect.y();
int num;
XRectangle *rects = (XRectangle *)qt_getClipRects(staticRegion, num);
GC tmpGc = XCreateGC(X11->display, oldData->hd, 0, 0);
XSetClipRectangles(X11->display, tmpGc, 0, 0, rects, num, YXBanded);
XCopyArea(X11->display, oldData->hd, newData->hd, tmpGc,
dx, dy, qMin(boundingRect.width(), size.width()),
qMin(boundingRect.height(), size.height()), dx, dy);
XFreeGC(X11->display, tmpGc);
newData->flags &= ~QX11PixmapData::Uninitialized;
d_ptr->device = QPixmap(newData);
} else {
d_ptr->device = QPixmap(size);
}
}
if (gc) {
XFreeGC(X11->display, gc);
gc = 0;
}
if (!d_ptr->device.isNull()) {
gc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
XSetGraphicsExposures(X11->display, gc, False);
}
}
bool QX11WindowSurface::scroll(const QRegion &area, int dx, int dy)
{
QRect rect = area.boundingRect();
if (d_ptr->device.isNull())
return false;
GC gc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
XCopyArea(X11->display, d_ptr->device.handle(), d_ptr->device.handle(), gc,
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x()+dx, rect.y()+dy);
XFreeGC(X11->display, gc);
return true;
}
QPixmap QX11WindowSurface::grabWidget(const QWidget *widget,
const QRect& rect) const
{
if (!widget || d_ptr->device.isNull())
return QPixmap();
QRect srcRect;
// make sure the rect is inside the widget & clip to widget's rect
if (!rect.isEmpty())
srcRect = rect & widget->rect();
else
srcRect = widget->rect();
if (srcRect.isEmpty())
return QPixmap();
// If it's a child widget we have to translate the coordinates
if (widget != window())
srcRect.translate(widget->mapTo(window(), QPoint(0, 0)));
QPixmap::x11SetDefaultScreen(widget->x11Info().screen());
QPixmap px(srcRect.width(), srcRect.height());
GC tmpGc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
// Copy srcRect from the backing store to the new pixmap
XSetGraphicsExposures(X11->display, tmpGc, False);
XCopyArea(X11->display, d_ptr->device.handle(), px.handle(), tmpGc,
srcRect.x(), srcRect.y(), srcRect.width(), srcRect.height(), 0, 0);
XFreeGC(X11->display, tmpGc);
return px;
}
QT_END_NAMESPACE
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui/QPaintDevice>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QWidget>
#include "private/qt_x11_p.h"
#include "private/qpixmap_x11_p.h"
#include "private/qwidget_p.h"
#include "qx11info_x11.h"
#include "qwindowsurface_x11_p.h"
QT_BEGIN_NAMESPACE
extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp
struct QX11WindowSurfacePrivate
{
QWidget *widget;
QPixmap device;
#ifndef QT_NO_XRENDER
bool translucentBackground;
#endif
};
QX11WindowSurface::QX11WindowSurface(QWidget *widget)
: QWindowSurface(widget), d_ptr(new QX11WindowSurfacePrivate), gc(0)
{
d_ptr->widget = widget;
#ifndef QT_NO_XRENDER
d_ptr->translucentBackground = X11->use_xrender
&& widget->x11Info().depth() == 32;
setStaticContentsSupport(!d_ptr->translucentBackground);
#else
setStaticContentsSupport(true);
#endif
}
QX11WindowSurface::~QX11WindowSurface()
{
delete d_ptr;
if (gc) {
XFreeGC(X11->display, gc);
gc = 0;
}
}
QPaintDevice *QX11WindowSurface::paintDevice()
{
return &d_ptr->device;
}
void QX11WindowSurface::beginPaint(const QRegion &rgn)
{
#ifndef QT_NO_XRENDER
Q_ASSERT(!d_ptr->device.isNull());
if (d_ptr->translucentBackground) {
if (d_ptr->device.depth() != 32)
static_cast<QX11PixmapData *>(d_ptr->device.data_ptr().data())->convertToARGB32();
::Picture src = X11->getSolidFill(d_ptr->device.x11Info().screen(), Qt::transparent);
::Picture dst = d_ptr->device.x11PictureHandle();
const QVector<QRect> rects = rgn.rects();
const int w = d_ptr->device.width();
const int h = d_ptr->device.height();
for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it)
XRenderComposite(X11->display, PictOpSrc, src, 0, dst,
0, 0, w, h, it->x(), it->y(),
it->width(), it->height());
}
#endif
}
void QX11WindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
{
if (d_ptr->device.isNull())
return;
QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();
QRegion wrgn(rgn);
QRect br = rgn.boundingRect();
if (!wOffset.isNull())
wrgn.translate(-wOffset);
QRect wbr = wrgn.boundingRect();
int num;
XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num);
if (num <= 0)
return;
// qDebug() << "XSetClipRectangles";
// for (int i = 0; i < num; ++i)
// qDebug() << ' ' << i << rects[i].x << rects[i].x << rects[i].y << rects[i].width << rects[i].height;
if (num != 1)
XSetClipRectangles(X11->display, gc, 0, 0, rects, num, YXBanded);
XCopyArea(X11->display, d_ptr->device.handle(), widget->handle(), gc,
br.x() + offset.x(), br.y() + offset.y(), br.width(), br.height(), wbr.x(), wbr.y());
if (num != 1)
XSetClipMask(X11->display, gc, XNone);
}
void QX11WindowSurface::setGeometry(const QRect &rect)
{
QWindowSurface::setGeometry(rect);
const QSize size = rect.size();
if (d_ptr->device.size() == size || size.width() <= 0 || size.height() <= 0)
return;
#ifndef QT_NO_XRENDER
if (d_ptr->translucentBackground) {
QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType);
data->xinfo = d_ptr->widget->x11Info();
data->resize(size.width(), size.height());
d_ptr->device = QPixmap(data);
} else
#endif
{
QPixmap::x11SetDefaultScreen(d_ptr->widget->x11Info().screen());
QX11PixmapData *oldData = static_cast<QX11PixmapData *>(d_ptr->device.pixmapData());
if (oldData && !(oldData->flags & QX11PixmapData::Uninitialized) && hasStaticContents()) {
// Copy the content of the old pixmap into the new one.
QX11PixmapData *newData = new QX11PixmapData(QPixmapData::PixmapType);
newData->resize(size.width(), size.height());
Q_ASSERT(oldData->d == newData->d);
QRegion staticRegion(staticContents());
// Make sure we're inside the boundaries of the old pixmap.
staticRegion &= QRect(0, 0, oldData->w, oldData->h);
const QRect boundingRect(staticRegion.boundingRect());
const int dx = boundingRect.x();
const int dy = boundingRect.y();
int num;
XRectangle *rects = (XRectangle *)qt_getClipRects(staticRegion, num);
GC tmpGc = XCreateGC(X11->display, oldData->hd, 0, 0);
XSetClipRectangles(X11->display, tmpGc, 0, 0, rects, num, YXBanded);
XCopyArea(X11->display, oldData->hd, newData->hd, tmpGc,
dx, dy, qMin(boundingRect.width(), size.width()),
qMin(boundingRect.height(), size.height()), dx, dy);
XFreeGC(X11->display, tmpGc);
newData->flags &= ~QX11PixmapData::Uninitialized;
d_ptr->device = QPixmap(newData);
} else {
d_ptr->device = QPixmap(size);
}
}
if (gc) {
XFreeGC(X11->display, gc);
gc = 0;
}
if (!d_ptr->device.isNull()) {
gc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
XSetGraphicsExposures(X11->display, gc, False);
}
}
bool QX11WindowSurface::scroll(const QRegion &area, int dx, int dy)
{
QRect rect = area.boundingRect();
if (d_ptr->device.isNull())
return false;
GC gc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
XCopyArea(X11->display, d_ptr->device.handle(), d_ptr->device.handle(), gc,
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x()+dx, rect.y()+dy);
XFreeGC(X11->display, gc);
return true;
}
QPixmap QX11WindowSurface::grabWidget(const QWidget *widget,
const QRect& rect) const
{
if (!widget || d_ptr->device.isNull())
return QPixmap();
QRect srcRect;
// make sure the rect is inside the widget & clip to widget's rect
if (!rect.isEmpty())
srcRect = rect & widget->rect();
else
srcRect = widget->rect();
if (srcRect.isEmpty())
return QPixmap();
// If it's a child widget we have to translate the coordinates
if (widget != window())
srcRect.translate(widget->mapTo(window(), QPoint(0, 0)));
QPixmap::x11SetDefaultScreen(widget->x11Info().screen());
QPixmap px(srcRect.width(), srcRect.height());
GC tmpGc = XCreateGC(X11->display, d_ptr->device.handle(), 0, 0);
// Copy srcRect from the backing store to the new pixmap
XSetGraphicsExposures(X11->display, tmpGc, False);
XCopyArea(X11->display, d_ptr->device.handle(), px.handle(), tmpGc,
srcRect.x(), srcRect.y(), srcRect.width(), srcRect.height(), 0, 0);
XFreeGC(X11->display, tmpGc);
return px;
}
QT_END_NAMESPACE
|
Check for null pixmap
|
Check for null pixmap
Reviewed-by: Trond
|
C++
|
lgpl-2.1
|
pruiz/wkhtmltopdf-qt,radekp/qt,radekp/qt,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,radekp/qt,igor-sfdc/qt-wk,radekp/qt,radekp/qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,radekp/qt,pruiz/wkhtmltopdf-qt,radekp/qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,radekp/qt
|
6bf34780cb9dc1c18aa8df9b21aa99aca6c799b4
|
chrome/browser/tab_contents/render_view_host_delegate_helper.cc
|
chrome/browser/tab_contents/render_view_host_delegate_helper.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 "chrome/browser/tab_contents/render_view_host_delegate_helper.h"
#include <string>
#include "base/command_line.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_fullscreen_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
RenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {}
RenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {}
BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
int route_id,
Profile* profile,
SiteInstance* site,
const GURL& opener_url,
const string16& frame_name) {
ExtensionService* extensions_service = profile->GetExtensionService();
if (!opener_url.is_valid() ||
frame_name.empty() ||
!extensions_service ||
!extensions_service->is_ready())
return NULL;
// Only hosted apps have web extents, so this ensures that only hosted apps
// can create BackgroundContents. We don't have to check for background
// permission as that is checked in RenderMessageFilter when the CreateWindow
// message is processed.
const Extension* extension =
extensions_service->GetExtensionByWebExtent(opener_url);
if (!extension)
return NULL;
// Only allow a single background contents per app.
if (!profile->GetBackgroundContentsService() ||
profile->GetBackgroundContentsService()->GetAppBackgroundContents(
ASCIIToUTF16(extension->id())))
return NULL;
// Ensure that we're trying to open this from the extension's process.
ExtensionProcessManager* process_manager =
profile->GetExtensionProcessManager();
if (!site->GetProcess() || !process_manager ||
site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
return NULL;
// Passed all the checks, so this should be created as a BackgroundContents.
return profile->GetBackgroundContentsService()->CreateBackgroundContents(
site, route_id, profile, frame_name, ASCIIToUTF16(extension->id()));
}
TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
int route_id,
Profile* profile,
SiteInstance* site,
WebUITypeID webui_type,
RenderViewHostDelegate* opener,
WindowContainerType window_container_type,
const string16& frame_name) {
if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
BackgroundContents* contents = MaybeCreateBackgroundContents(
route_id,
profile,
site,
opener->GetURL(),
frame_name);
if (contents) {
pending_contents_[route_id] = contents->render_view_host();
return NULL;
}
}
// Create the new web contents. This will automatically create the new
// TabContentsView. In the future, we may want to create the view separately.
TabContents* new_contents =
new TabContents(profile,
site,
route_id,
opener->GetAsTabContents(),
NULL);
new_contents->set_opener_web_ui_type(webui_type);
TabContentsView* new_view = new_contents->view();
// TODO(brettw) it seems bogus that we have to call this function on the
// newly created object and give it one of its own member variables.
new_view->CreateViewForWidget(new_contents->render_view_host());
// Save the created window associated with the route so we can show it later.
pending_contents_[route_id] = new_contents->render_view_host();
return new_contents;
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
RenderWidgetHost* widget_host =
new RenderWidgetHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(widget_host);
// Popups should not get activated.
widget_view->set_popup_type(popup_type);
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
RenderWidgetHostView*
RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget(
int route_id, RenderProcessHost* process) {
RenderWidgetFullscreenHost* fullscreen_widget_host =
new RenderWidgetFullscreenHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host);
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
PendingContents::iterator iter = pending_contents_.find(route_id);
if (iter == pending_contents_.end()) {
DCHECK(false);
return NULL;
}
RenderViewHost* new_rvh = iter->second;
pending_contents_.erase(route_id);
// The renderer crashed or it is a TabContents and has no view.
if (!new_rvh->process()->HasConnection() ||
(new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
return NULL;
// TODO(brettw) this seems bogus to reach into here and initialize the host.
new_rvh->Init();
return new_rvh->delegate()->GetAsTabContents();
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
int route_id) {
PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
if (iter == pending_widget_views_.end()) {
DCHECK(false);
return NULL;
}
RenderWidgetHostView* widget_host_view = iter->second;
pending_widget_views_.erase(route_id);
RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
if (!widget_host->process()->HasConnection()) {
// The view has gone away or the renderer crashed. Nothing to do.
return NULL;
}
return widget_host_view;
}
void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
RenderWidgetHost* host) {
for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
i != pending_widget_views_.end(); ++i) {
if (host->view() == i->second) {
pending_widget_views_.erase(i);
return;
}
}
}
bool RenderViewHostDelegateHelper::gpu_enabled_ = true;
// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
Profile* profile, bool is_web_ui) {
PrefService* prefs = profile->GetPrefs();
WebPreferences web_prefs;
web_prefs.fixed_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily));
web_prefs.serif_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily));
web_prefs.sans_serif_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
// TODO(kochi): As we don't have setting UI for kWebKitStandardFontIsSerif,
// we always use web_prefs.serif_font_family as a standard font
// temporarily for now. Ideally we should have a pref UI for serif/sans
// selection as for CJK font sans-serif family font is the default.
// See discussion in http://crosbug.com/12311.
web_prefs.standard_font_family = web_prefs.serif_font_family;
web_prefs.cursive_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily));
web_prefs.fantasy_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily));
web_prefs.default_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFontSize);
web_prefs.default_fixed_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
web_prefs.minimum_font_size =
prefs->GetInteger(prefs::kWebKitMinimumFontSize);
web_prefs.minimum_logical_font_size =
prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
web_prefs.javascript_can_open_windows_automatically =
prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
web_prefs.dom_paste_enabled =
prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
web_prefs.shrinks_standalone_images_to_fit =
prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
const DictionaryValue* inspector_settings =
prefs->GetDictionary(prefs::kWebKitInspectorSettings);
if (inspector_settings) {
for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
iter != inspector_settings->end_keys(); ++iter) {
std::string value;
if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
web_prefs.inspector_settings.push_back(
std::make_pair(*iter, value));
}
}
web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
{ // Command line switches are used for preferences with no user interface.
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
web_prefs.developer_extras_enabled =
!command_line.HasSwitch(switches::kDisableDevTools);
web_prefs.javascript_enabled =
!command_line.HasSwitch(switches::kDisableJavaScript) &&
prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
web_prefs.web_security_enabled =
!command_line.HasSwitch(switches::kDisableWebSecurity) &&
prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
web_prefs.plugins_enabled =
!command_line.HasSwitch(switches::kDisablePlugins) &&
prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
web_prefs.java_enabled =
!command_line.HasSwitch(switches::kDisableJava) &&
prefs->GetBoolean(prefs::kWebKitJavaEnabled);
web_prefs.loads_images_automatically =
prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
web_prefs.uses_page_cache =
command_line.HasSwitch(switches::kEnableFastback);
web_prefs.remote_fonts_enabled =
!command_line.HasSwitch(switches::kDisableRemoteFonts);
web_prefs.xss_auditor_enabled =
!command_line.HasSwitch(switches::kDisableXSSAuditor);
web_prefs.application_cache_enabled =
!command_line.HasSwitch(switches::kDisableApplicationCache);
web_prefs.local_storage_enabled =
!command_line.HasSwitch(switches::kDisableLocalStorage);
web_prefs.databases_enabled =
!command_line.HasSwitch(switches::kDisableDatabases);
web_prefs.webaudio_enabled =
command_line.HasSwitch(switches::kEnableWebAudio);
web_prefs.experimental_webgl_enabled =
gpu_enabled() &&
!command_line.HasSwitch(switches::kDisable3DAPIs) &&
!command_line.HasSwitch(switches::kDisableExperimentalWebGL);
web_prefs.gl_multisampling_enabled =
!command_line.HasSwitch(switches::kDisableGLMultisampling);
web_prefs.site_specific_quirks_enabled =
!command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
web_prefs.allow_file_access_from_file_urls =
command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
web_prefs.show_composited_layer_borders =
command_line.HasSwitch(switches::kShowCompositedLayerBorders);
web_prefs.accelerated_compositing_enabled =
gpu_enabled() &&
!command_line.HasSwitch(switches::kDisableAcceleratedCompositing);
web_prefs.accelerated_2d_canvas_enabled =
gpu_enabled() &&
command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
web_prefs.accelerated_layers_enabled =
!command_line.HasSwitch(switches::kDisableAcceleratedLayers);
web_prefs.composite_to_texture_enabled =
command_line.HasSwitch(switches::kEnableCompositeToTexture);
web_prefs.accelerated_plugins_enabled =
command_line.HasSwitch(switches::kEnableAcceleratedPlugins);
web_prefs.accelerated_video_enabled =
!command_line.HasSwitch(switches::kDisableAcceleratedVideo);
web_prefs.memory_info_enabled =
command_line.HasSwitch(switches::kEnableMemoryInfo);
web_prefs.hyperlink_auditing_enabled =
!command_line.HasSwitch(switches::kNoPings);
web_prefs.interactive_form_validation_enabled =
!command_line.HasSwitch(switches::kDisableInteractiveFormValidation);
// The user stylesheet watcher may not exist in a testing profile.
if (profile->GetUserStyleSheetWatcher()) {
web_prefs.user_style_sheet_enabled = true;
web_prefs.user_style_sheet_location =
profile->GetUserStyleSheetWatcher()->user_style_sheet();
} else {
web_prefs.user_style_sheet_enabled = false;
}
}
web_prefs.uses_universal_detector =
prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
web_prefs.text_areas_are_resizable =
prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
// Make sure we will set the default_encoding with canonical encoding name.
web_prefs.default_encoding =
CharacterEncoding::GetCanonicalEncodingNameByAliasName(
web_prefs.default_encoding);
if (web_prefs.default_encoding.empty()) {
prefs->ClearPref(prefs::kDefaultCharset);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
}
DCHECK(!web_prefs.default_encoding.empty());
if (is_web_ui) {
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
}
return web_prefs;
}
void RenderViewHostDelegateHelper::UpdateInspectorSetting(
Profile* profile, const std::string& key, const std::string& value) {
DictionaryValue* inspector_settings =
profile->GetPrefs()->GetMutableDictionary(
prefs::kWebKitInspectorSettings);
inspector_settings->SetWithoutPathExpansion(key,
Value::CreateStringValue(value));
}
void RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) {
DictionaryValue* inspector_settings =
profile->GetPrefs()->GetMutableDictionary(
prefs::kWebKitInspectorSettings);
inspector_settings->Clear();
}
|
// 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/tab_contents/render_view_host_delegate_helper.h"
#include <string>
#include "base/command_line.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/background_contents_service.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/render_widget_fullscreen_host.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/site_instance.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_view.h"
#include "chrome/browser/user_style_sheet_watcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
RenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {}
RenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {}
BackgroundContents*
RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(
int route_id,
Profile* profile,
SiteInstance* site,
const GURL& opener_url,
const string16& frame_name) {
ExtensionService* extensions_service = profile->GetExtensionService();
if (!opener_url.is_valid() ||
frame_name.empty() ||
!extensions_service ||
!extensions_service->is_ready())
return NULL;
// Only hosted apps have web extents, so this ensures that only hosted apps
// can create BackgroundContents. We don't have to check for background
// permission as that is checked in RenderMessageFilter when the CreateWindow
// message is processed.
const Extension* extension =
extensions_service->GetExtensionByWebExtent(opener_url);
if (!extension)
return NULL;
// Only allow a single background contents per app.
if (!profile->GetBackgroundContentsService() ||
profile->GetBackgroundContentsService()->GetAppBackgroundContents(
ASCIIToUTF16(extension->id())))
return NULL;
// Ensure that we're trying to open this from the extension's process.
ExtensionProcessManager* process_manager =
profile->GetExtensionProcessManager();
if (!site->GetProcess() || !process_manager ||
site->GetProcess() != process_manager->GetExtensionProcess(opener_url))
return NULL;
// Passed all the checks, so this should be created as a BackgroundContents.
return profile->GetBackgroundContentsService()->CreateBackgroundContents(
site, route_id, profile, frame_name, ASCIIToUTF16(extension->id()));
}
TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(
int route_id,
Profile* profile,
SiteInstance* site,
WebUITypeID webui_type,
RenderViewHostDelegate* opener,
WindowContainerType window_container_type,
const string16& frame_name) {
if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
BackgroundContents* contents = MaybeCreateBackgroundContents(
route_id,
profile,
site,
opener->GetURL(),
frame_name);
if (contents) {
pending_contents_[route_id] = contents->render_view_host();
return NULL;
}
}
// Create the new web contents. This will automatically create the new
// TabContentsView. In the future, we may want to create the view separately.
TabContents* new_contents =
new TabContents(profile,
site,
route_id,
opener->GetAsTabContents(),
NULL);
new_contents->set_opener_web_ui_type(webui_type);
TabContentsView* new_view = new_contents->view();
// TODO(brettw) it seems bogus that we have to call this function on the
// newly created object and give it one of its own member variables.
new_view->CreateViewForWidget(new_contents->render_view_host());
// Save the created window associated with the route so we can show it later.
pending_contents_[route_id] = new_contents->render_view_host();
return new_contents;
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(
int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {
RenderWidgetHost* widget_host =
new RenderWidgetHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(widget_host);
// Popups should not get activated.
widget_view->set_popup_type(popup_type);
// Save the created widget associated with the route so we can show it later.
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
RenderWidgetHostView*
RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget(
int route_id, RenderProcessHost* process) {
RenderWidgetFullscreenHost* fullscreen_widget_host =
new RenderWidgetFullscreenHost(process, route_id);
RenderWidgetHostView* widget_view =
RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host);
pending_widget_views_[route_id] = widget_view;
return widget_view;
}
TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {
PendingContents::iterator iter = pending_contents_.find(route_id);
if (iter == pending_contents_.end()) {
DCHECK(false);
return NULL;
}
RenderViewHost* new_rvh = iter->second;
pending_contents_.erase(route_id);
// The renderer crashed or it is a TabContents and has no view.
if (!new_rvh->process()->HasConnection() ||
(new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))
return NULL;
// TODO(brettw) this seems bogus to reach into here and initialize the host.
new_rvh->Init();
return new_rvh->delegate()->GetAsTabContents();
}
RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(
int route_id) {
PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);
if (iter == pending_widget_views_.end()) {
DCHECK(false);
return NULL;
}
RenderWidgetHostView* widget_host_view = iter->second;
pending_widget_views_.erase(route_id);
RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
if (!widget_host->process()->HasConnection()) {
// The view has gone away or the renderer crashed. Nothing to do.
return NULL;
}
return widget_host_view;
}
void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(
RenderWidgetHost* host) {
for (PendingWidgetViews::iterator i = pending_widget_views_.begin();
i != pending_widget_views_.end(); ++i) {
if (host->view() == i->second) {
pending_widget_views_.erase(i);
return;
}
}
}
bool RenderViewHostDelegateHelper::gpu_enabled_ = true;
// static
WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(
Profile* profile, bool is_web_ui) {
PrefService* prefs = profile->GetPrefs();
WebPreferences web_prefs;
web_prefs.fixed_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily));
web_prefs.serif_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily));
web_prefs.sans_serif_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily));
if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))
web_prefs.standard_font_family = web_prefs.serif_font_family;
else
web_prefs.standard_font_family = web_prefs.sans_serif_font_family;
web_prefs.cursive_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily));
web_prefs.fantasy_font_family =
UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily));
web_prefs.default_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFontSize);
web_prefs.default_fixed_font_size =
prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
web_prefs.minimum_font_size =
prefs->GetInteger(prefs::kWebKitMinimumFontSize);
web_prefs.minimum_logical_font_size =
prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
web_prefs.javascript_can_open_windows_automatically =
prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
web_prefs.dom_paste_enabled =
prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
web_prefs.shrinks_standalone_images_to_fit =
prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
const DictionaryValue* inspector_settings =
prefs->GetDictionary(prefs::kWebKitInspectorSettings);
if (inspector_settings) {
for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());
iter != inspector_settings->end_keys(); ++iter) {
std::string value;
if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))
web_prefs.inspector_settings.push_back(
std::make_pair(*iter, value));
}
}
web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
{ // Command line switches are used for preferences with no user interface.
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
web_prefs.developer_extras_enabled =
!command_line.HasSwitch(switches::kDisableDevTools);
web_prefs.javascript_enabled =
!command_line.HasSwitch(switches::kDisableJavaScript) &&
prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);
web_prefs.web_security_enabled =
!command_line.HasSwitch(switches::kDisableWebSecurity) &&
prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);
web_prefs.plugins_enabled =
!command_line.HasSwitch(switches::kDisablePlugins) &&
prefs->GetBoolean(prefs::kWebKitPluginsEnabled);
web_prefs.java_enabled =
!command_line.HasSwitch(switches::kDisableJava) &&
prefs->GetBoolean(prefs::kWebKitJavaEnabled);
web_prefs.loads_images_automatically =
prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
web_prefs.uses_page_cache =
command_line.HasSwitch(switches::kEnableFastback);
web_prefs.remote_fonts_enabled =
!command_line.HasSwitch(switches::kDisableRemoteFonts);
web_prefs.xss_auditor_enabled =
!command_line.HasSwitch(switches::kDisableXSSAuditor);
web_prefs.application_cache_enabled =
!command_line.HasSwitch(switches::kDisableApplicationCache);
web_prefs.local_storage_enabled =
!command_line.HasSwitch(switches::kDisableLocalStorage);
web_prefs.databases_enabled =
!command_line.HasSwitch(switches::kDisableDatabases);
web_prefs.webaudio_enabled =
command_line.HasSwitch(switches::kEnableWebAudio);
web_prefs.experimental_webgl_enabled =
gpu_enabled() &&
!command_line.HasSwitch(switches::kDisable3DAPIs) &&
!command_line.HasSwitch(switches::kDisableExperimentalWebGL);
web_prefs.gl_multisampling_enabled =
!command_line.HasSwitch(switches::kDisableGLMultisampling);
web_prefs.site_specific_quirks_enabled =
!command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
web_prefs.allow_file_access_from_file_urls =
command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
web_prefs.show_composited_layer_borders =
command_line.HasSwitch(switches::kShowCompositedLayerBorders);
web_prefs.accelerated_compositing_enabled =
gpu_enabled() &&
!command_line.HasSwitch(switches::kDisableAcceleratedCompositing);
web_prefs.accelerated_2d_canvas_enabled =
gpu_enabled() &&
command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);
web_prefs.accelerated_layers_enabled =
!command_line.HasSwitch(switches::kDisableAcceleratedLayers);
web_prefs.composite_to_texture_enabled =
command_line.HasSwitch(switches::kEnableCompositeToTexture);
web_prefs.accelerated_plugins_enabled =
command_line.HasSwitch(switches::kEnableAcceleratedPlugins);
web_prefs.accelerated_video_enabled =
!command_line.HasSwitch(switches::kDisableAcceleratedVideo);
web_prefs.memory_info_enabled =
command_line.HasSwitch(switches::kEnableMemoryInfo);
web_prefs.hyperlink_auditing_enabled =
!command_line.HasSwitch(switches::kNoPings);
web_prefs.interactive_form_validation_enabled =
!command_line.HasSwitch(switches::kDisableInteractiveFormValidation);
// The user stylesheet watcher may not exist in a testing profile.
if (profile->GetUserStyleSheetWatcher()) {
web_prefs.user_style_sheet_enabled = true;
web_prefs.user_style_sheet_location =
profile->GetUserStyleSheetWatcher()->user_style_sheet();
} else {
web_prefs.user_style_sheet_enabled = false;
}
}
web_prefs.uses_universal_detector =
prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
web_prefs.text_areas_are_resizable =
prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
// Make sure we will set the default_encoding with canonical encoding name.
web_prefs.default_encoding =
CharacterEncoding::GetCanonicalEncodingNameByAliasName(
web_prefs.default_encoding);
if (web_prefs.default_encoding.empty()) {
prefs->ClearPref(prefs::kDefaultCharset);
web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);
}
DCHECK(!web_prefs.default_encoding.empty());
if (is_web_ui) {
web_prefs.loads_images_automatically = true;
web_prefs.javascript_enabled = true;
}
return web_prefs;
}
void RenderViewHostDelegateHelper::UpdateInspectorSetting(
Profile* profile, const std::string& key, const std::string& value) {
DictionaryValue* inspector_settings =
profile->GetPrefs()->GetMutableDictionary(
prefs::kWebKitInspectorSettings);
inspector_settings->SetWithoutPathExpansion(key,
Value::CreateStringValue(value));
}
void RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) {
DictionaryValue* inspector_settings =
profile->GetPrefs()->GetMutableDictionary(
prefs::kWebKitInspectorSettings);
inspector_settings->Clear();
}
|
Revert 75900 - Set the standard font from 'serif' family font.
|
Revert 75900 - Set the standard font from 'serif' family font.
This is regardless of serif/sans-serif preference, because we don't
have such pref UI for now.
Otherwise some languages (CJK), which has sans-serif as a default
font (IDS_STANDARD_FONT_IS_SERIF = false), they have no way to
select a standard fallback font.
Note that this is a temporary workaround that needs more fundamental fix.
BUG=73845, chromium-os:12311
TEST=manually (in Japanese, set the font and go to http://www.asahi.com )
Review URL: http://codereview.chromium.org/6568006
[email protected]
Review URL: http://codereview.chromium.org/6588004
git-svn-id: http://src.chromium.org/svn/trunk/src@76036 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 109057d5019ce2f347583620de7ea6c434408cf0
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
849a55e210cd05354a086b7c62693449bcc5ee69
|
VDMHelperCLR64/VDMHelperCLR64.cpp
|
VDMHelperCLR64/VDMHelperCLR64.cpp
|
// This is the main DLL file.
#include "stdafx.h"
#include "VDMHelperCLR64.h"
#include "../VDMHelper64/VDMHelperAPI.h"
#define GPA(_Mod, _Name) _Name = (decltype(::_Name)*)::GetProcAddress(_Mod, #_Name)
namespace VDMHelperCLR
{
VdmHelper::VdmHelper() : hHook(0)
{
hvdm = ::LoadLibrary(_T("VDMHelper64.dll"));
GPA(hvdm, VDMHookProc);
GPA(hvdm, VDMAllocGuid);
GPA(hvdm, VDMReleaseGuid);
RequestMoveWindowToDesktopMessage = RegisterWindowMessage(RequestMoveWindowToDesktop);
}
VdmHelper::~VdmHelper()
{
DeInit();
FreeLibrary(hvdm);
}
bool VdmHelper::Init()
{
if (!hvdm) throw gcnew System::InvalidOperationException("Initialization failed");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, VDMHookProc, hvdm, 0);
// start 32bit helper process
::ShellExecute(nullptr, nullptr, _T("InjectDll32.exe"), nullptr, nullptr, 0);
return hHook != 0;
}
bool VdmHelper::DeInit()
{
if (!hHook)return false;
UnhookWindowsHookEx(hHook);
hHook = 0;
return true;
}
void VdmHelper::MoveWindowToDesktop(IntPtr topLevelWindow, Guid desktopId)
{
BOOL isRunningOnX64 = FALSE;
::IsWow64Process(GetCurrentProcess(), &isRunningOnX64);
if (isRunningOnX64)
{
throw gcnew System::InvalidOperationException("You need call via 64bit dll");
}
// convert System.Guid to GUID
auto bytes = desktopId.ToByteArray();
pin_ptr<unsigned char> pbytes = &bytes[0];
GUID dest;
memcpy(&dest, pbytes, sizeof(GUID));
// allocate & request
auto hwnd = (HWND)topLevelWindow.ToPointer();
LPVOID rGuid = VDMAllocGuid(hwnd, &dest);
SendMessage(hwnd, RequestMoveWindowToDesktopMessage, 0, (LPARAM)rGuid);
VDMReleaseGuid(hwnd, rGuid);
}
}
|
// This is the main DLL file.
#include "stdafx.h"
#include "VDMHelperCLR64.h"
#include "../VDMHelper64/VDMHelperAPI.h"
#define GPA(_Mod, _Name) _Name = (decltype(::_Name)*)::GetProcAddress(_Mod, #_Name)
namespace VDMHelperCLR
{
VdmHelper::VdmHelper() : hHook(0)
{
hvdm = ::LoadLibrary(_T("VDMHelper64.dll"));
GPA(hvdm, VDMHookProc);
GPA(hvdm, VDMAllocGuid);
GPA(hvdm, VDMReleaseGuid);
RequestMoveWindowToDesktopMessage = RegisterWindowMessage(RequestMoveWindowToDesktop);
}
VdmHelper::~VdmHelper()
{
DeInit();
FreeLibrary(hvdm);
}
bool VdmHelper::Init()
{
if (!hvdm) throw gcnew System::InvalidOperationException("Initialization failed");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, VDMHookProc, hvdm, 0);
// start 32bit helper process
::ShellExecute(nullptr, nullptr, _T("InjectDll32.exe"), nullptr, nullptr, 0);
return hHook != 0;
}
bool VdmHelper::DeInit()
{
if (!hHook)return false;
UnhookWindowsHookEx(hHook);
hHook = 0;
// stop 32bit helper process
auto hwnd = ::FindWindow(_T("VDM.InjectDLL32.Class"), nullptr);
SendMessage(hwnd, WM_CLOSE, 0, 0);
return true;
}
void VdmHelper::MoveWindowToDesktop(IntPtr topLevelWindow, Guid desktopId)
{
BOOL isRunningOnX64 = FALSE;
::IsWow64Process(GetCurrentProcess(), &isRunningOnX64);
if (isRunningOnX64)
{
throw gcnew System::InvalidOperationException("You need call via 64bit dll");
}
// convert System.Guid to GUID
auto bytes = desktopId.ToByteArray();
pin_ptr<unsigned char> pbytes = &bytes[0];
GUID dest;
memcpy(&dest, pbytes, sizeof(GUID));
// allocate & request
auto hwnd = (HWND)topLevelWindow.ToPointer();
LPVOID rGuid = VDMAllocGuid(hwnd, &dest);
SendMessage(hwnd, RequestMoveWindowToDesktopMessage, 0, (LPARAM)rGuid);
VDMReleaseGuid(hwnd, rGuid);
}
}
|
quit helper process when deinit.
|
quit helper process when deinit.
|
C++
|
mit
|
tmyt/VDMHelper,tmyt/VDMHelper,tmyt/VDMHelper
|
f72e0432fd7f94c37990c4a4d7f7d44c65e20bea
|
src/budget.cpp
|
src/budget.cpp
|
//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <string>
#include <iostream>
#include <tuple>
#include "config.hpp"
#include "args.hpp"
#include "budget_exception.hpp"
//The different modules
#include "debts.hpp"
#include "accounts.hpp"
#include "expenses.hpp"
#include "overview.hpp"
#include "earnings.hpp"
#include "help.hpp"
#include "recurring.hpp"
#include "report.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "versioning.hpp"
#include "version.hpp"
#include "predict.hpp"
#include "gc.hpp"
using namespace budget;
namespace {
typedef std::tuple<
budget::debt_module,
budget::expenses_module,
budget::overview_module,
budget::accounts_module,
budget::earnings_module,
budget::recurring_module,
budget::fortune_module,
budget::report_module,
budget::objectives_module,
budget::wishes_module,
budget::versioning_module,
budget::version_module,
budget::predict_module,
budget::gc_module,
budget::help_module
> modules_tuple;
template<std::size_t I, typename Tuple, typename Functor>
struct for_each_impl {
static void for_each(Functor& func){
func.template operator()<typename std::tuple_element<I, Tuple>::type>();
for_each_impl<I - 1, Tuple, Functor>::for_each(func);
}
};
template<typename Tuple, typename Functor>
struct for_each_impl<0, Tuple, Functor> {
static void for_each(Functor& func){
func.template operator()<typename std::tuple_element<0, Tuple>::type>();
}
};
template<typename Tuple, typename Functor>
void for_each(Functor& func){
for_each_impl<std::tuple_size<Tuple>::value - 1, Tuple, Functor>::for_each(func);
}
enum class enabler_t { DUMMY };
constexpr const enabler_t dummy = enabler_t::DUMMY;
template<bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template<bool B>
using enable_if_u = typename std::enable_if<B, enabler_t>::type;
template<bool B, typename T = void>
using disable_if = std::enable_if<!B, T>;
template<bool B, typename T = void>
using disable_if_t = typename std::enable_if<!B, T>::type;
template<bool B, typename T = void>
using disable_if_u = typename std::enable_if<!B, enabler_t>::type;
template<class T>
struct Void {
typedef void type;
};
#define HAS_MEM_FUNC(func, name) \
template<typename T, typename Sign> \
struct name { \
typedef char yes[1]; \
typedef char no [2]; \
template <typename U, U> struct type_check; \
template <typename _1> static yes &chk(type_check<Sign, &_1::func> *); \
template <typename > static no &chk(...); \
static bool constexpr const value = sizeof(chk<T>(0)) == sizeof(yes); \
}
#define HAS_STATIC_FIELD(field, name) \
template <class T> \
class name { \
template<typename U, typename = \
typename std::enable_if<!std::is_member_pointer<decltype(&U::field)>::value>::type> \
static std::true_type check(int); \
template <typename> \
static std::false_type check(...); \
public: \
static constexpr const bool value = decltype(check<T>(0))::value; \
};
HAS_MEM_FUNC(load, has_load);
HAS_MEM_FUNC(unload, has_unload);
HAS_MEM_FUNC(preload, has_preload);
template<typename Module>
struct need_loading {
static const bool value = has_load<Module, void(Module::*)()>::value;
};
template<typename Module>
struct need_unloading {
static const bool value = has_unload<Module, void(Module::*)()>::value;
};
template<typename Module>
struct need_preloading {
static const bool value = has_preload<Module, void(Module::*)()>::value;
};
HAS_STATIC_FIELD(disable_preloading, has_disable_preloading_field)
template<typename Module, typename Enable = void>
struct disable_preloading {
static const bool value = false;
};
template<typename Module>
struct disable_preloading<Module, enable_if_t<has_disable_preloading_field<module_traits<Module>>::value>> {
static const bool value = module_traits<Module>::disable_preloading;
};
HAS_STATIC_FIELD(aliases, has_aliases_field)
template<typename Module, typename Enable = void>
struct has_aliases {
static const bool value = false;
};
template<typename Module>
struct has_aliases<Module, enable_if_t<has_aliases_field<module_traits<Module>>::value>> {
static const bool value = true;
};
struct module_loader {
template<typename Module, enable_if_u<need_preloading<Module>::value> = dummy>
inline void preload(){
Module module;
module.preload();
}
template<typename Module, disable_if_u<need_preloading<Module>::value> = dummy>
inline void preload(){
//NOP
}
template<typename Module>
inline void operator()(){
preload<Module>();
}
};
struct module_runner {
std::vector<std::string> args;
bool handled = false;
module_runner(std::vector<std::string>&& args) : args(std::forward<std::vector<std::string>>(args)) {
//Nothing to init
}
template<typename Module, enable_if_u<need_loading<Module>::value> = dummy>
inline void load(Module& module){
module.load();
}
template<typename Module, disable_if_u<need_loading<Module>::value> = dummy>
inline void load(Module&){
//NOP
}
template<typename Module, enable_if_u<need_unloading<Module>::value> = dummy>
inline void unload(Module& module){
module.unload();
}
template<typename Module, disable_if_u<need_unloading<Module>::value> = dummy>
inline void unload(Module&){
//NOP
}
template<typename Module>
inline void handle_module(){
//Preload each module that needs it
if(!disable_preloading<Module>::value){
module_loader loader;
for_each<modules_tuple>(loader);
}
Module module;
load(module);
module.handle(args);
unload(module);
handled = true;
}
template<typename Module>
inline void operator()(){
if(handled){
return;
}
if(args.empty()){
if(module_traits<Module>::is_default){
handle_module<Module>();
}
} else if(args[0] == module_traits<Module>::command){
handle_module<Module>();
}
}
};
struct aliases_collector {
std::vector<std::pair<const char*, const char*>> aliases;
template<typename Module, enable_if_u<has_aliases<Module>::value> = dummy>
inline void operator()(){
for(auto& v : module_traits<Module>::aliases){
aliases.push_back(v);
}
}
template<typename Module, disable_if_u<has_aliases<Module>::value> = dummy>
inline void operator()(){
//NOP
}
};
std::string exec_command(const std::string& command) {
std::stringstream output;
char buffer[1024];
FILE* stream = popen(command.c_str(), "r");
while (fgets(buffer, 1024, stream) != NULL) {
output << buffer;
}
pclose(stream);
return output.str();
}
bool has_enough_colors(){
auto colors = exec_command("tput colors");
colors = colors.substr(0, colors.length() - 1);
return to_number<int>(colors) > 4;
}
} //end of anonymous namespace
int main(int argc, const char* argv[]) {
std::locale global_locale("");
std::locale::global(global_locale);
if(!load_config()){
return 0;
}
if(!has_enough_colors()){
std::cout << "WARNING: The terminal does not seem to have enough colors, some command may not work as intended" << std::endl;
}
auto old_data_version = to_number<std::size_t>(internal_config_value("data_version"));
if(old_data_version > DATA_VERSION){
std::cout << "Unsupported database version, you should update budgetwarrior" << std::endl;
return 0;
}
if(old_data_version < DATA_VERSION){
std::cout << "Migrate data base..." << std::endl;
if(old_data_version == 1 && DATA_VERSION >= 2){
migrate_recurring_1_to_2();
}
if(old_data_version <= 2 && DATA_VERSION >= 3){
migrate_wishes_2_to_3();
}
if(old_data_version <= 3 && DATA_VERSION >= 4){
//migrate_debts_3_to_4();
migrate_wishes_3_to_4();
}
internal_config_value("data_version") = to_string(DATA_VERSION);
std::cout << "done" << std::endl;
}
//Collect all aliases
aliases_collector collector;
for_each<modules_tuple>(collector);
//Parse the command line args
auto args = parse_args(argc, argv, collector.aliases);
int code = 0;
try {
//Run the correct module
module_runner runner(std::move(args));
for_each<modules_tuple>(runner);
if(!runner.handled){
std::cout << "Unhandled command \"" << runner.args[0] << "\"" << std::endl;
code = 1;
}
} catch (const budget_exception& exception){
std::cout << exception.message() << std::endl;
code = 2;
}
save_config();
return code;
}
|
//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <string>
#include <iostream>
#include <tuple>
#include "cpp_utils/tmp.hpp"
#include "config.hpp"
#include "args.hpp"
#include "budget_exception.hpp"
//The different modules
#include "debts.hpp"
#include "accounts.hpp"
#include "expenses.hpp"
#include "overview.hpp"
#include "earnings.hpp"
#include "help.hpp"
#include "recurring.hpp"
#include "report.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "versioning.hpp"
#include "version.hpp"
#include "predict.hpp"
#include "gc.hpp"
using namespace budget;
namespace {
typedef std::tuple<
budget::debt_module,
budget::expenses_module,
budget::overview_module,
budget::accounts_module,
budget::earnings_module,
budget::recurring_module,
budget::fortune_module,
budget::report_module,
budget::objectives_module,
budget::wishes_module,
budget::versioning_module,
budget::version_module,
budget::predict_module,
budget::gc_module,
budget::help_module
> modules_tuple;
enum class enabler_t { DUMMY };
constexpr const enabler_t dummy = enabler_t::DUMMY;
template<bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template<bool B>
using enable_if_u = typename std::enable_if<B, enabler_t>::type;
template<bool B, typename T = void>
using disable_if = std::enable_if<!B, T>;
template<bool B, typename T = void>
using disable_if_t = typename std::enable_if<!B, T>::type;
template<bool B, typename T = void>
using disable_if_u = typename std::enable_if<!B, enabler_t>::type;
template<class T>
struct Void {
typedef void type;
};
HAS_MEM_FUNC(load, has_load);
HAS_MEM_FUNC(unload, has_unload);
HAS_MEM_FUNC(preload, has_preload);
template<typename Module>
struct need_loading {
static const bool value = has_load<Module, void(Module::*)()>::value;
};
template<typename Module>
struct need_unloading {
static const bool value = has_unload<Module, void(Module::*)()>::value;
};
template<typename Module>
struct need_preloading {
static const bool value = has_preload<Module, void(Module::*)()>::value;
};
HAS_STATIC_FIELD(disable_preloading, has_disable_preloading_field)
template<typename Module, typename Enable = void>
struct disable_preloading {
static const bool value = false;
};
template<typename Module>
struct disable_preloading<Module, enable_if_t<has_disable_preloading_field<module_traits<Module>>::value>> {
static const bool value = module_traits<Module>::disable_preloading;
};
HAS_STATIC_FIELD(aliases, has_aliases_field)
template<typename Module, typename Enable = void>
struct has_aliases {
static const bool value = false;
};
template<typename Module>
struct has_aliases<Module, enable_if_t<has_aliases_field<module_traits<Module>>::value>> {
static const bool value = true;
};
struct module_loader {
template<typename Module, enable_if_u<need_preloading<Module>::value> = dummy>
inline void preload(){
Module module;
module.preload();
}
template<typename Module, disable_if_u<need_preloading<Module>::value> = dummy>
inline void preload(){
//NOP
}
template<typename Module>
inline void operator()(){
preload<Module>();
}
};
struct module_runner {
std::vector<std::string> args;
bool handled = false;
module_runner(std::vector<std::string>&& args) : args(std::forward<std::vector<std::string>>(args)) {
//Nothing to init
}
template<typename Module, enable_if_u<need_loading<Module>::value> = dummy>
inline void load(Module& module){
module.load();
}
template<typename Module, disable_if_u<need_loading<Module>::value> = dummy>
inline void load(Module&){
//NOP
}
template<typename Module, enable_if_u<need_unloading<Module>::value> = dummy>
inline void unload(Module& module){
module.unload();
}
template<typename Module, disable_if_u<need_unloading<Module>::value> = dummy>
inline void unload(Module&){
//NOP
}
template<typename Module>
inline void handle_module(){
//Preload each module that needs it
if(!disable_preloading<Module>::value){
module_loader loader;
cpp::for_each_tuple_t<modules_tuple>(loader);
}
Module module;
load(module);
module.handle(args);
unload(module);
handled = true;
}
template<typename Module>
inline void operator()(){
if(handled){
return;
}
if(args.empty()){
if(module_traits<Module>::is_default){
handle_module<Module>();
}
} else if(args[0] == module_traits<Module>::command){
handle_module<Module>();
}
}
};
struct aliases_collector {
std::vector<std::pair<const char*, const char*>> aliases;
template<typename Module, enable_if_u<has_aliases<Module>::value> = dummy>
inline void operator()(){
for(auto& v : module_traits<Module>::aliases){
aliases.push_back(v);
}
}
template<typename Module, disable_if_u<has_aliases<Module>::value> = dummy>
inline void operator()(){
//NOP
}
};
std::string exec_command(const std::string& command) {
std::stringstream output;
char buffer[1024];
FILE* stream = popen(command.c_str(), "r");
while (fgets(buffer, 1024, stream) != NULL) {
output << buffer;
}
pclose(stream);
return output.str();
}
bool has_enough_colors(){
auto colors = exec_command("tput colors");
colors = colors.substr(0, colors.length() - 1);
return to_number<int>(colors) > 4;
}
} //end of anonymous namespace
int main(int argc, const char* argv[]) {
std::locale global_locale("");
std::locale::global(global_locale);
if(!load_config()){
return 0;
}
if(!has_enough_colors()){
std::cout << "WARNING: The terminal does not seem to have enough colors, some command may not work as intended" << std::endl;
}
auto old_data_version = to_number<std::size_t>(internal_config_value("data_version"));
if(old_data_version > DATA_VERSION){
std::cout << "Unsupported database version, you should update budgetwarrior" << std::endl;
return 0;
}
if(old_data_version < DATA_VERSION){
std::cout << "Migrate data base..." << std::endl;
if(old_data_version == 1 && DATA_VERSION >= 2){
migrate_recurring_1_to_2();
}
if(old_data_version <= 2 && DATA_VERSION >= 3){
migrate_wishes_2_to_3();
}
if(old_data_version <= 3 && DATA_VERSION >= 4){
//migrate_debts_3_to_4();
migrate_wishes_3_to_4();
}
internal_config_value("data_version") = to_string(DATA_VERSION);
std::cout << "done" << std::endl;
}
//Collect all aliases
aliases_collector collector;
cpp::for_each_tuple_t<modules_tuple>(collector);
//Parse the command line args
auto args = parse_args(argc, argv, collector.aliases);
int code = 0;
try {
//Run the correct module
module_runner runner(std::move(args));
cpp::for_each_tuple_t<modules_tuple>(runner);
if(!runner.handled){
std::cout << "Unhandled command \"" << runner.args[0] << "\"" << std::endl;
code = 1;
}
} catch (const budget_exception& exception){
std::cout << exception.message() << std::endl;
code = 2;
}
save_config();
return code;
}
|
Use cpp_utils
|
Use cpp_utils
|
C++
|
mit
|
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
|
0db34486b6051fbf2f4c125aebffdca856459983
|
src/rts/human_player.cpp
|
src/rts/human_player.cpp
|
#include "dioptre/locator.h"
#include "rts/human_player.h"
#include "rts/components/edge_scroll_component.h"
namespace rts {
HumanPlayer* HumanPlayer::spawn() {
HumanPlayer* humanPlayer = new HumanPlayer();
auto edgeScrollComponent = new components::EdgeScrollComponent();
humanPlayer->addComponent(edgeScrollComponent);
return humanPlayer;
}
void HumanPlayer::makeCurrent() {
dioptre::Object::makeCurrent();
auto graphicsService = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
auto camera = graphicsService->getCamera();
camera->makeCurrent();
}
std::vector<dioptre::Object*> HumanPlayer::getSelectedObjects() {
return selectedObjects_;
}
void HumanPlayer::select(dioptre::Object* object) {
if (std::find(selectedObjects_.begin(), selectedObjects_.end(), object) != selectedObjects_.end()) {
return;
}
selectedObjects_.push_back(object);
}
} // rts
|
#include "dioptre/locator.h"
#include "rts/human_player.h"
#include "rts/components/edge_scroll_component.h"
#include <algorithm>
namespace rts {
HumanPlayer* HumanPlayer::spawn() {
HumanPlayer* humanPlayer = new HumanPlayer();
auto edgeScrollComponent = new components::EdgeScrollComponent();
humanPlayer->addComponent(edgeScrollComponent);
return humanPlayer;
}
void HumanPlayer::makeCurrent() {
dioptre::Object::makeCurrent();
auto graphicsService = dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(dioptre::Module::M_GRAPHICS);
auto camera = graphicsService->getCamera();
camera->makeCurrent();
}
std::vector<dioptre::Object*> HumanPlayer::getSelectedObjects() {
return selectedObjects_;
}
void HumanPlayer::select(dioptre::Object* object) {
if (std::find(selectedObjects_.begin(), selectedObjects_.end(), object) != selectedObjects_.end()) {
return;
}
selectedObjects_.push_back(object);
}
} // rts
|
include missing header
|
include missing header
|
C++
|
mit
|
tobscher/rts,tobscher/rts,tobscher/rts
|
9c9201162ac141fa4eb888e488124a201f5706bc
|
src/scene/Ionosphere.cpp
|
src/scene/Ionosphere.cpp
|
/*
* Ionosphere.cpp
*
* Created on: 22 Jan 2015
* Author: rian
*/
#include <iostream>
#include <iomanip>
#include <cmath>
#include <iostream>
#include "Ionosphere.h"
#include "GeometryType.h"
#include "../math/Constants.h"
#include "../exporter/Data.h"
#include "../core/Application.h"
#include "../core/Config.h"
#include "../math/NormalDistribution.h"
namespace raytracer {
namespace scene {
using namespace std;
using namespace exporter;
using namespace core;
Ionosphere::Ionosphere() : Geometry() {
type = GeometryType::ionosphere;
}
Ionosphere::Ionosphere(Plane3d mesh) : Geometry(mesh) {
type = GeometryType::ionosphere;
}
Ionosphere::Ionosphere(Vector3d n, Vector3d c) : Geometry(n, c) {
type = GeometryType::ionosphere;
}
/**
* Precalculate fixed values for this ionospheric layer. Assume static ionosphere as the
* time periods that we're interested in are an order of magnitude lower than the processes
* of photochemical reactions (discussion with Cyril Simon Wedlund)
*/
void Ionosphere::setup() {
_altitude = getAltitude();
}
/**
* Interaction between ray and ionospheric layer
*/
void Ionosphere::interact(Ray *r, Vector3d &hitpos) {
setup();
int waveBehaviour = determineWaveBehaviour(r);
if (waveBehaviour == Ray::wave_reflection) {
reflect(r);
} else if (waveBehaviour == Ray::wave_refraction) {
refract(r);
}
r->o = hitpos;
attenuate(r);
rangeDelay(r);
phaseAdvance(r);
timeDelay(r);
exportData(r);
}
/**
*
*/
void Ionosphere::refract(Ray *r) {
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double theta_i = getIncidentAngle(r);
double ratio = r->previousRefractiveIndex/refractiveIndex;
double coefficient = ratio * cos(theta_i) - sqrt(1 - pow(ratio, 2) * (1 - pow(cos(theta_i), 2)));
Vector3d newR = Vector3d();
if (r->d.y > 0)
newR = r->d * ratio - mesh3d.normal * coefficient;
else
newR = r->d * ratio + mesh3d.normal * coefficient;
BOOST_LOG_TRIVIAL(debug) << std::fixed << "REFRACT Alt: " << std::setprecision(0) << getAltitude() << "\tr.d_i: " << r->d << "\tr.d_r: " << newR << "\tN: " << mesh3d.normal << "\tn1/n2: " << ratio << "\ttheta_i: " << theta_i;
r->d = newR.norm();
r->previousRefractiveIndex = refractiveIndex;
}
/**
*
*/
void Ionosphere::reflect(Ray *r) {
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double theta_i = getIncidentAngle(r);
Vector3d newR = Vector3d();
if (r->d.y > 0)
newR = r->d - mesh3d.normal * 2 * cos(theta_i);
else
newR = r->d + mesh3d.normal * 2 * cos(theta_i);
BOOST_LOG_TRIVIAL(debug) << std::fixed << "REFLECT Alt: " << std::setprecision(0) << getAltitude() << "\tr.d_i: " << r->d << "\tr.d_r: " << newR << "\tN: " << mesh3d.normal << "\ttheta_i: " << theta_i;
r->d = newR.norm();
r->previousRefractiveIndex = refractiveIndex;
}
/**
* A radio wave is attenuated by its propagation through the ionosphere.
* The attenuation calculation is based on Nielsen, 2007. Attenuation depends
* on the electron-neutral collision frequency, the altitude w.r.t the peak
* production altitude and the radio wave frequency. The result is in db/m
* and thus is internally converted to attenuation in db, taking the layer
* height and the ray angle into account.
* A ray with a higher SZA will travel a longer path through the layer and
* thus face more attenuation.
*/
void Ionosphere::attenuate(Ray *r) {
double m3tocm3 = 1e-6;
double theta_r = getMesh().normal.angle(r->d);
double magnitude = layerHeight * cos(theta_r);
double correctionFactor = 1e-2;
// double theta_r = r->getAngle() - Constants::PI/2 + getSolarZenithAngle2d();
//
// double ki = (-pow(getPlasmaFrequency(), 2) / (2 * Constants::C * mu_r))
// * getCollisionFrequency() / (pow(2 * Constants::PI * r->frequency, 2) + pow(getCollisionFrequency(), 2));
// printf("wp: %4.2e, f: %4.2e, colFreq: %4.2e ", getPlasmaFrequency(), r->frequency, getCollisionFrequency());
// double loss = - abs(20 * log10(exp(1)) * ki * magnitude * abs(1 / cos(getSolarZenithAngle2d())) * cos(abs(theta_r)));
// double loss = -1.15e-6 * (getElectronNumberDensity() * getCollisionFrequency() * magnitude) / pow(r->frequency, 2)
// * correctionFactor;
double collisionFrequency = getCollisionFrequency();
double loss = -4.6e-6
* (getElectronNumberDensity() * collisionFrequency / (pow(2 * Constants::PI * r->frequency, 2) + pow(collisionFrequency, 2)))
* magnitude;
// printf("magnitude: %4.2f, totalLoss: %4.2e, theta: %4.2f, alt: %4.2f ", magnitude, r->signalPower, theta_r, _altitude);
// printf("Loss: %4.2e ", loss);
r->signalPower += loss;
}
/**
* Range delay. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: m
*/
void Ionosphere::rangeDelay(Ray *r) {
r->rangeDelay += 0.403 * getTEC() / pow(r->frequency, 2);
}
/**
* Phase advance. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: rad
*/
void Ionosphere::phaseAdvance(Ray *r) {
r->phaseAdvance += (8.44e-7 / r->frequency ) * getTEC();
}
/**
* Time delay. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: sec
*/
void Ionosphere::timeDelay(Ray *r) {
r->timeDelay += (1.34e-7 / pow(r->frequency, 2)) * getTEC();
}
void Ionosphere::exportData(Ray *r) {
Data d;
d.x = r->o.x;
d.y = r->o.y;
d.z = r->o.z;
d.rayNumber = r->rayNumber;
d.mu_r_sqrt = pow(r->previousRefractiveIndex, 2);
d.n_e = getElectronNumberDensity();
d.omega_p = getPlasmaFrequency();
d.theta_0 = r->originalAngle;
d.frequency = r->frequency;
d.signalPower = r->signalPower;
d.timeOfFlight = r->timeOfFlight;
d.collisionType = GeometryType::ionosphere;
Application::getInstance().addToDataset(d);
}
/**
* Calculate the plasma frequency which depends on the electron number density
* which depends on the altitude (y). Use a chapman profile.
* @unit: rad s^-1
*/
double Ionosphere::getPlasmaFrequency() {
return sqrt(getElectronNumberDensity() * pow(Constants::ELEMENTARY_CHARGE, 2)
/ (Constants::ELECTRON_MASS * Constants::PERMITTIVITY_VACUUM));
}
/**
* Use a chapmanProfile to calculate the electron number density
* @unit: particles m^-3
*/
double Ionosphere::getElectronNumberDensity() {
return _electronNumberDensity;
}
/**
*
*/
void Ionosphere::superimposeElectronNumberDensity(double peakDensity, double peakAltitude, double neutralScaleHeight) {
double SZA = mesh3d.normal.angle(Vector3d::SUBSOLAR);
double correctedPeakAltitude = peakAltitude + 1e4 * log(1/cos(SZA));
double normalizedHeight = (getAltitude() - peakAltitude) / neutralScaleHeight;
double electronNumberDensity = peakDensity * cos(SZA) *
exp(0.5f * (1.0f - normalizedHeight - (1.0 / cos(SZA)) * exp(-normalizedHeight) ));
_electronNumberDensity += electronNumberDensity;
}
/**
* Compute the plasma refractive index. Three refractive methods are supplied:
* - SIMPLE:
* - KELSO: The simplified method as described in Kelso, 1964, p.208
* - AHDR: Refractive index according to the Appleton-Hartree
* dispersion relation. Only applies to a magnetized cold plasma.
*/
double Ionosphere::getRefractiveIndex(Ray *r, refractiveMethod m) {
double n = 1.0;
if (m == REFRACTION_KELSO) {
n = sqrt(1 - pow(getPlasmaFrequency(), 2) / pow(2 * Constants::PI * r->frequency, 2));
} else if (m == REFRACTION_AHDR) {
//n = 1 - X / (1);
}
return n;
}
/**
* Interpolate the altitude of this ionospheric layer. Throw an exception
* if the difference between the y-components of the edges of the mesh is
* too large, for this would imply the ionospheric layer is under an angle
* which does not make sense.
*/
double Ionosphere::getAltitude() {
if (_altitude < 1) {
_altitude = sqrt(pow(mesh3d.centerpoint.x, 2) + pow(mesh3d.centerpoint.y, 2) + pow(mesh3d.centerpoint.z, 2))
- Application::getInstance().getCelestialConfig().getInt("radius");
}
return _altitude;
}
/**
* The incident angle of a ray with respect to the ionospheric layer. This angle depends
* on the propagation angle of the ray and the angle of the layer w.r.t. the sun (SZA)
* The angle is then complementary to the angle between the ray direction vector and the
* normal of the plane.
*/
double Ionosphere::getIncidentAngle(Ray *r) {
// double SZA = getSolarZenithAngle2d();
// double beta = atan(r->d.y/r->d.x);
// double theta_i = Constants::PI/2 - beta - SZA;
return acos(abs(r->d * mesh3d.normal) / (r->d.magnitude() * mesh3d.normal.magnitude()));
}
/**
* Model the collision frequency
* @unit Hz
*/
double Ionosphere::getCollisionFrequency() {
//return Ionosphere::surfaceCollisionFrequency * exp(-_altitude / Constants::NEUTRAL_SCALE_HEIGHT);
double nCO2 = 2.8e17 * exp(-_altitude / Constants::NEUTRAL_SCALE_HEIGHT);
return 1.0436e-07 * nCO2;
}
/**
* Calculate the total electron content
* (TEC) which this ray experiences as it passes through
* the ionosphere.
*/
double Ionosphere::getTEC() {
return getElectronNumberDensity() * layerHeight;
}
/**
* A wave is either reflected or refracted depending on its incident angle. According to
* Snells' law, a critical angle exists for which the reflected angle is 90 deg. Incident
* angles above this critical angle are reflected, not refracted.
* @ todo: REWRITE COMPLETELY
*/
int Ionosphere::determineWaveBehaviour(Ray *r) {
r->behaviour = Ray::wave_none;
double criticalAngle;
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double incidentAngle = getIncidentAngle(r);
double angularFrequency = 2 * Constants::PI * r->frequency;
double epsilon = 1e-5;
if (incidentAngle > Constants::PI/2)
incidentAngle -= Constants::PI/2;
if (refractiveIndex <= r->previousRefractiveIndex)
criticalAngle = asin(refractiveIndex / r->previousRefractiveIndex);
else
criticalAngle = asin(r->previousRefractiveIndex / refractiveIndex);
if (r->previousRefractiveIndex > refractiveIndex &&
(incidentAngle >= criticalAngle || abs(angularFrequency - getPlasmaFrequency()) < epsilon))
r->behaviour = Ray::wave_reflection;
else
r->behaviour = Ray::wave_refraction;
return r->behaviour;
}
} /* namespace scene */
} /* namespace raytracer */
|
/*
* Ionosphere.cpp
*
* Created on: 22 Jan 2015
* Author: rian
*/
#include <iostream>
#include <iomanip>
#include <cmath>
#include <iostream>
#include "Ionosphere.h"
#include "GeometryType.h"
#include "../math/Constants.h"
#include "../exporter/Data.h"
#include "../core/Application.h"
#include "../core/Config.h"
#include "../math/NormalDistribution.h"
namespace raytracer {
namespace scene {
using namespace std;
using namespace exporter;
using namespace core;
Ionosphere::Ionosphere() : Geometry() {
type = GeometryType::ionosphere;
}
Ionosphere::Ionosphere(Plane3d mesh) : Geometry(mesh) {
type = GeometryType::ionosphere;
}
Ionosphere::Ionosphere(Vector3d n, Vector3d c) : Geometry(n, c) {
type = GeometryType::ionosphere;
}
/**
* Precalculate fixed values for this ionospheric layer. Assume static ionosphere as the
* time periods that we're interested in are an order of magnitude lower than the processes
* of photochemical reactions (discussion with Cyril Simon Wedlund)
*/
void Ionosphere::setup() {
_altitude = getAltitude();
}
/**
* Interaction between ray and ionospheric layer
*/
void Ionosphere::interact(Ray *r, Vector3d &hitpos) {
setup();
int waveBehaviour = determineWaveBehaviour(r);
if (waveBehaviour == Ray::wave_reflection) {
reflect(r);
} else if (waveBehaviour == Ray::wave_refraction) {
refract(r);
}
r->o = hitpos;
attenuate(r);
rangeDelay(r);
phaseAdvance(r);
timeDelay(r);
exportData(r);
}
/**
*
*/
void Ionosphere::refract(Ray *r) {
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double theta_i = getIncidentAngle(r);
double ratio = r->previousRefractiveIndex/refractiveIndex;
double coefficient = ratio * cos(theta_i) - sqrt(1 - pow(ratio, 2) * (1 - pow(cos(theta_i), 2)));
Vector3d newR = Vector3d();
if (r->d.y > 0)
newR = r->d * ratio - mesh3d.normal * coefficient;
else
newR = r->d * ratio + mesh3d.normal * coefficient;
BOOST_LOG_TRIVIAL(debug) << std::fixed << "REFRACT Alt: " << std::setprecision(0) << getAltitude() << "\tr.d_i: " << r->d << "\tr.d_r: " << newR << "\tN: " << mesh3d.normal << "\tn1/n2: " << ratio << "\ttheta_i: " << theta_i;
r->d = newR.norm();
r->previousRefractiveIndex = refractiveIndex;
}
/**
*
*/
void Ionosphere::reflect(Ray *r) {
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double theta_i = getIncidentAngle(r);
Vector3d newR = Vector3d();
if (r->d.y > 0)
newR = r->d - mesh3d.normal * 2 * cos(theta_i);
else
newR = r->d + mesh3d.normal * 2 * cos(theta_i);
BOOST_LOG_TRIVIAL(debug) << std::fixed << "REFLECT Alt: " << std::setprecision(0) << getAltitude() << "\tr.d_i: " << r->d << "\tr.d_r: " << newR << "\tN: " << mesh3d.normal << "\ttheta_i: " << theta_i;
r->d = newR.norm();
r->previousRefractiveIndex = refractiveIndex;
}
/**
* A radio wave is attenuated by its propagation through the ionosphere.
* The attenuation calculation is based on Nielsen, 2007. Attenuation depends
* on the electron-neutral collision frequency, the altitude w.r.t the peak
* production altitude and the radio wave frequency. The result is in db/m
* and thus is internally converted to attenuation in db, taking the layer
* height and the ray angle into account.
* A ray with a higher SZA will travel a longer path through the layer and
* thus face more attenuation.
*/
void Ionosphere::attenuate(Ray *r) {
double m3tocm3 = 1e-6;
double theta_r = getMesh().normal.angle(r->d);
double magnitude = layerHeight * cos(theta_r);
double correctionFactor = 1e-2;
// double theta_r = r->getAngle() - Constants::PI/2 + getSolarZenithAngle2d();
//
// double ki = (-pow(getPlasmaFrequency(), 2) / (2 * Constants::C * mu_r))
// * getCollisionFrequency() / (pow(2 * Constants::PI * r->frequency, 2) + pow(getCollisionFrequency(), 2));
// printf("wp: %4.2e, f: %4.2e, colFreq: %4.2e ", getPlasmaFrequency(), r->frequency, getCollisionFrequency());
// double loss = - abs(20 * log10(exp(1)) * ki * magnitude * abs(1 / cos(getSolarZenithAngle2d())) * cos(abs(theta_r)));
// double loss = -1.15e-6 * (getElectronNumberDensity() * getCollisionFrequency() * magnitude) / pow(r->frequency, 2)
// * correctionFactor;
double collisionFrequency = getCollisionFrequency();
double loss = -4.6e-6
* (getElectronNumberDensity() * collisionFrequency / (pow(2 * Constants::PI * r->frequency, 2) + pow(collisionFrequency, 2)))
* magnitude;
// printf("magnitude: %4.2f, totalLoss: %4.2e, theta: %4.2f, alt: %4.2f ", magnitude, r->signalPower, theta_r, _altitude);
// printf("Loss: %4.2e ", loss);
r->signalPower += loss;
}
/**
* Range delay. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: m
*/
void Ionosphere::rangeDelay(Ray *r) {
r->rangeDelay += 0.403 * getTEC() / pow(r->frequency, 2);
}
/**
* Phase advance. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: rad
*/
void Ionosphere::phaseAdvance(Ray *r) {
r->phaseAdvance += (8.44e-7 / r->frequency ) * getTEC();
}
/**
* Time delay. Data from Ho, 2002.
* @ todo: check formulas
* @ unit: sec
*/
void Ionosphere::timeDelay(Ray *r) {
r->timeDelay += (1.34e-7 / pow(r->frequency, 2)) * getTEC();
}
void Ionosphere::exportData(Ray *r) {
Data d;
d.x = r->o.x;
d.y = r->o.y;
d.z = r->o.z;
d.rayNumber = r->rayNumber;
d.mu_r_sqrt = pow(r->previousRefractiveIndex, 2);
d.n_e = getElectronNumberDensity();
d.omega_p = getPlasmaFrequency();
d.theta_0 = r->originalAngle;
d.frequency = r->frequency;
d.signalPower = r->signalPower;
d.timeOfFlight = r->timeOfFlight;
d.collisionType = GeometryType::ionosphere;
Application::getInstance().addToDataset(d);
}
/**
* Calculate the plasma frequency which depends on the electron number density
* which depends on the altitude (y). Use a chapman profile.
* @unit: rad s^-1
*/
double Ionosphere::getPlasmaFrequency() {
return sqrt(getElectronNumberDensity() * pow(Constants::ELEMENTARY_CHARGE, 2)
/ (Constants::ELECTRON_MASS * Constants::PERMITTIVITY_VACUUM));
}
/**
* Use a chapmanProfile to calculate the electron number density
* @unit: particles m^-3
*/
double Ionosphere::getElectronNumberDensity() {
return _electronNumberDensity;
}
/**
*
*/
void Ionosphere::superimposeElectronNumberDensity(double peakDensity, double peakAltitude, double neutralScaleHeight) {
double SZA = mesh3d.normal.angle(Vector3d::SUBSOLAR);
double correctedPeakAltitude = peakAltitude + 1e4 * log(1/cos(SZA));
double normalizedHeight = (getAltitude() - peakAltitude) / neutralScaleHeight;
double electronNumberDensity = peakDensity * cos(SZA) *
exp(0.5f * (1.0f - normalizedHeight - (1.0 / cos(SZA)) * exp(-normalizedHeight) ));
_electronNumberDensity += electronNumberDensity;
}
/**
* Compute the plasma refractive index. Three refractive methods are supplied:
* - SIMPLE:
* - KELSO: The simplified method as described in Kelso, 1964, p.208
* - AHDR: Refractive index according to the Appleton-Hartree
* dispersion relation. Only applies to a magnetized cold plasma.
*/
double Ionosphere::getRefractiveIndex(Ray *r, refractiveMethod m) {
double n = 1.0;
if (m == REFRACTION_KELSO) {
n = sqrt(1 - pow(getPlasmaFrequency(), 2) / pow(2 * Constants::PI * r->frequency, 2));
} else if (m == REFRACTION_AHDR) {
//n = 1 - X / (1);
}
return n;
}
/**
* Interpolate the altitude of this ionospheric layer. Throw an exception
* if the difference between the y-components of the edges of the mesh is
* too large, for this would imply the ionospheric layer is under an angle
* which does not make sense.
*/
double Ionosphere::getAltitude() {
if (_altitude < 1) {
_altitude = sqrt(pow(mesh3d.centerpoint.x, 2) + pow(mesh3d.centerpoint.y, 2) + pow(mesh3d.centerpoint.z, 2))
- Application::getInstance().getCelestialConfig().getInt("radius");
}
return _altitude;
}
/**
* The incident angle of a ray with respect to the ionospheric layer. This angle depends
* on the propagation angle of the ray and the angle of the layer w.r.t. the sun (SZA)
* The angle is then complementary to the angle between the ray direction vector and the
* normal of the plane.
*/
double Ionosphere::getIncidentAngle(Ray *r) {
// double SZA = getSolarZenithAngle2d();
// double beta = atan(r->d.y/r->d.x);
// double theta_i = Constants::PI/2 - beta - SZA;
return acos(abs(r->d * mesh3d.normal) / (r->d.magnitude() * mesh3d.normal.magnitude()));
}
/**
* Model the collision frequency
* @unit Hz
*/
double Ionosphere::getCollisionFrequency() {
return Ionosphere::surfaceCollisionFrequency * exp(-_altitude / Constants::NEUTRAL_SCALE_HEIGHT);
// double nCO2 = 2.8e17 * exp(-_altitude / Constants::NEUTRAL_SCALE_HEIGHT);
// return 1.0436e-07 * nCO2;
}
/**
* Calculate the total electron content
* (TEC) which this ray experiences as it passes through
* the ionosphere.
*/
double Ionosphere::getTEC() {
return getElectronNumberDensity() * layerHeight;
}
/**
* A wave is either reflected or refracted depending on its incident angle. According to
* Snells' law, a critical angle exists for which the reflected angle is 90 deg. Incident
* angles above this critical angle are reflected, not refracted.
* @ todo: REWRITE COMPLETELY
*/
int Ionosphere::determineWaveBehaviour(Ray *r) {
r->behaviour = Ray::wave_none;
double criticalAngle;
double refractiveIndex = getRefractiveIndex(r, Ionosphere::REFRACTION_KELSO);
double incidentAngle = getIncidentAngle(r);
double angularFrequency = 2 * Constants::PI * r->frequency;
double epsilon = 1e-5;
if (incidentAngle > Constants::PI/2)
incidentAngle -= Constants::PI/2;
if (refractiveIndex <= r->previousRefractiveIndex)
criticalAngle = asin(refractiveIndex / r->previousRefractiveIndex);
else
criticalAngle = asin(r->previousRefractiveIndex / refractiveIndex);
if (r->previousRefractiveIndex > refractiveIndex &&
(incidentAngle >= criticalAngle || abs(angularFrequency - getPlasmaFrequency()) < epsilon))
r->behaviour = Ray::wave_reflection;
else
r->behaviour = Ray::wave_refraction;
return r->behaviour;
}
} /* namespace scene */
} /* namespace raytracer */
|
Undo premature commit of change in collision frequency
|
Undo premature commit of change in collision frequency
|
C++
|
mit
|
rvangijlswijk/ionospheric-ray-tracer,rvangijlswijk/ionospheric-ray-tracer,rvangijlswijk/ionospheric-ray-tracer
|
d0a2137e94720af99b0e113b5f6a133ee89ff45a
|
scripts/eigen_gen_credits.cpp
|
scripts/eigen_gen_credits.cpp
|
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <list>
using namespace std;
// this function takes a line that may contain a name and/or email address,
// and returns just the name, while fixing the "bad cases".
std::string contributor_name(const std::string& line)
{
string result;
size_t position_of_email_address = line.find_first_of('<');
if(position_of_email_address != string::npos)
{
// there is an e-mail address.
// Hauke once committed as "John Smith", fix that.
if(line.find("hauke.heibel") != string::npos)
result = "Hauke Heibel";
else
{
// just remove the e-mail address
result = line.substr(0, position_of_email_address);
}
}
else
{
// there is no e-mail address.
if(line.find("convert-repo") != string::npos)
result = "";
else
result = line;
}
// remove trailing spaces
size_t length = result.length();
while(length >= 1 && result[length-1] == ' ') result.erase(--length);
return result;
}
// parses hg churn output to generate a contributors map.
map<string,int> contributors_map_from_churn_output(const char *filename)
{
map<string,int> contributors_map;
string line;
ifstream churn_out;
churn_out.open(filename, ios::in);
while(!getline(churn_out,line).eof())
{
// remove the histograms "******" that hg churn may draw at the end of some lines
size_t first_star = line.find_first_of('*');
if(first_star != string::npos) line.erase(first_star);
// remove trailing spaces
size_t length = line.length();
while(length >= 1 && line[length-1] == ' ') line.erase(--length);
// now the last space indicates where the number starts
size_t last_space = line.find_last_of(' ');
// get the number (of changesets or of modified lines for each contributor)
int number;
istringstream(line.substr(last_space+1)) >> number;
// get the name of the contributor
line.erase(last_space);
string name = contributor_name(line);
map<string,int>::iterator it = contributors_map.find(name);
// if new contributor, insert
if(it == contributors_map.end())
contributors_map.insert(pair<string,int>(name, number));
// if duplicate, just add the number
else
it->second += number;
}
churn_out.close();
return contributors_map;
}
// find the last name, i.e. the last word.
// for "van den Schbling" types of last names, that's not a problem, that's actually what we want.
string lastname(const string& name)
{
size_t last_space = name.find_last_of(' ');
if(last_space >= name.length()-1) return name;
else return name.substr(last_space+1);
}
struct contributor
{
string name;
int changedlines;
int changesets;
string url;
string misc;
contributor() : changedlines(0), changesets(0) {}
bool operator < (const contributor& other)
{
return lastname(name).compare(lastname(other.name)) < 0;
}
};
void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename)
{
string line;
ifstream online_info;
online_info.open(filename, ios::in);
while(!getline(online_info,line).eof())
{
string hgname, realname, url, misc;
size_t last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
misc = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
url = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
realname = line.substr(last_bar+1);
line.erase(last_bar);
hgname = line;
// remove the example line
if(hgname.find("MercurialName") != string::npos) continue;
list<contributor>::iterator it;
for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)
{}
if(it == contributors_list.end())
{
contributor c;
c.name = realname;
c.url = url;
c.misc = misc;
contributors_list.push_back(c);
}
else
{
it->name = realname;
it->url = url;
it->misc = misc;
}
}
}
int main()
{
// parse the hg churn output files
map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out");
//map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out");
// merge into the contributors list
list<contributor> contributors_list;
map<string,int>::iterator it;
for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)
{
contributor c;
c.name = it->first;
c.changedlines = it->second;
c.changesets = 0; //contributors_map_for_changesets.find(it->first)->second;
contributors_list.push_back(c);
}
add_online_info_into_contributors_list(contributors_list, "online-info.out");
contributors_list.sort();
cout << "{| cellpadding=\"5\"\n";
cout << "!\n";
cout << "! Lines changed\n";
cout << "!\n";
list<contributor>::iterator itc;
int i = 0;
for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)
{
if(itc->name.length() == 0) continue;
if(i%2) cout << "|-\n";
else cout << "|- style=\"background:#FFFFD0\"\n";
if(itc->url.length())
cout << "| [" << itc->url << " " << itc->name << "]\n";
else
cout << "| " << itc->name << "\n";
if(itc->changedlines)
cout << "| " << itc->changedlines << "\n";
else
cout << "| (no information)\n";
cout << "| " << itc->misc << "\n";
i++;
}
cout << "|}" << endl;
}
|
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <list>
using namespace std;
// this function takes a line that may contain a name and/or email address,
// and returns just the name, while fixing the "bad cases".
std::string contributor_name(const std::string& line)
{
string result;
// let's first take care of the case of isolated email addresses, like
// "[email protected]" entries
if(line.find("[email protected]") != string::npos)
{
return "Mark Borgerding";
}
// from there on we assume that we have a entry of the form
// either:
// Bla bli Blurp
// or:
// Bla bli Blurp <[email protected]>
size_t position_of_email_address = line.find_first_of('<');
if(position_of_email_address != string::npos)
{
// there is an e-mail address in <...>.
// Hauke once committed as "John Smith", fix that.
if(line.find("hauke.heibel") != string::npos)
result = "Hauke Heibel";
else
{
// just remove the e-mail address
result = line.substr(0, position_of_email_address);
}
}
else
{
// there is no e-mail address in <...>.
if(line.find("convert-repo") != string::npos)
result = "";
else
result = line;
}
// remove trailing spaces
size_t length = result.length();
while(length >= 1 && result[length-1] == ' ') result.erase(--length);
return result;
}
// parses hg churn output to generate a contributors map.
map<string,int> contributors_map_from_churn_output(const char *filename)
{
map<string,int> contributors_map;
string line;
ifstream churn_out;
churn_out.open(filename, ios::in);
while(!getline(churn_out,line).eof())
{
// remove the histograms "******" that hg churn may draw at the end of some lines
size_t first_star = line.find_first_of('*');
if(first_star != string::npos) line.erase(first_star);
// remove trailing spaces
size_t length = line.length();
while(length >= 1 && line[length-1] == ' ') line.erase(--length);
// now the last space indicates where the number starts
size_t last_space = line.find_last_of(' ');
// get the number (of changesets or of modified lines for each contributor)
int number;
istringstream(line.substr(last_space+1)) >> number;
// get the name of the contributor
line.erase(last_space);
string name = contributor_name(line);
map<string,int>::iterator it = contributors_map.find(name);
// if new contributor, insert
if(it == contributors_map.end())
contributors_map.insert(pair<string,int>(name, number));
// if duplicate, just add the number
else
it->second += number;
}
churn_out.close();
return contributors_map;
}
// find the last name, i.e. the last word.
// for "van den Schbling" types of last names, that's not a problem, that's actually what we want.
string lastname(const string& name)
{
size_t last_space = name.find_last_of(' ');
if(last_space >= name.length()-1) return name;
else return name.substr(last_space+1);
}
struct contributor
{
string name;
int changedlines;
int changesets;
string url;
string misc;
contributor() : changedlines(0), changesets(0) {}
bool operator < (const contributor& other)
{
return lastname(name).compare(lastname(other.name)) < 0;
}
};
void add_online_info_into_contributors_list(list<contributor>& contributors_list, const char *filename)
{
string line;
ifstream online_info;
online_info.open(filename, ios::in);
while(!getline(online_info,line).eof())
{
string hgname, realname, url, misc;
size_t last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
misc = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
url = line.substr(last_bar+1);
line.erase(last_bar);
last_bar = line.find_last_of('|');
if(last_bar == string::npos) continue;
if(last_bar < line.length())
realname = line.substr(last_bar+1);
line.erase(last_bar);
hgname = line;
// remove the example line
if(hgname.find("MercurialName") != string::npos) continue;
list<contributor>::iterator it;
for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)
{}
if(it == contributors_list.end())
{
contributor c;
c.name = realname;
c.url = url;
c.misc = misc;
contributors_list.push_back(c);
}
else
{
it->name = realname;
it->url = url;
it->misc = misc;
}
}
}
int main()
{
// parse the hg churn output files
map<string,int> contributors_map_for_changedlines = contributors_map_from_churn_output("churn-changedlines.out");
//map<string,int> contributors_map_for_changesets = contributors_map_from_churn_output("churn-changesets.out");
// merge into the contributors list
list<contributor> contributors_list;
map<string,int>::iterator it;
for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)
{
contributor c;
c.name = it->first;
c.changedlines = it->second;
c.changesets = 0; //contributors_map_for_changesets.find(it->first)->second;
contributors_list.push_back(c);
}
add_online_info_into_contributors_list(contributors_list, "online-info.out");
contributors_list.sort();
cout << "{| cellpadding=\"5\"\n";
cout << "!\n";
cout << "! Lines changed\n";
cout << "!\n";
list<contributor>::iterator itc;
int i = 0;
for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)
{
if(itc->name.length() == 0) continue;
if(i%2) cout << "|-\n";
else cout << "|- style=\"background:#FFFFD0\"\n";
if(itc->url.length())
cout << "| [" << itc->url << " " << itc->name << "]\n";
else
cout << "| " << itc->name << "\n";
if(itc->changedlines)
cout << "| " << itc->changedlines << "\n";
else
cout << "| (no information)\n";
cout << "| " << itc->misc << "\n";
i++;
}
cout << "|}" << endl;
}
|
handle mark's first commits before he configured his id
|
handle mark's first commits before he configured his id
|
C++
|
bsd-3-clause
|
toastedcrumpets/eigen,TSC21/Eigen,ritsu1228/eigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,TSC21/Eigen,toastedcrumpets/eigen,Zefz/eigen,toastedcrumpets/eigen,pasuka/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen,ritsu1228/eigen,ritsu1228/eigen,ROCmSoftwarePlatform/hipeigen,Zefz/eigen,ritsu1228/eigen,ritsu1228/eigen,Zefz/eigen,pasuka/eigen,TSC21/Eigen,Zefz/eigen,ROCmSoftwarePlatform/hipeigen,pasuka/eigen,TSC21/Eigen,toastedcrumpets/eigen
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.