text
stringlengths 54
60.6k
|
|---|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief NES Emulator ハンドラー
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2019 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/string_utils.hpp"
#include "emu/log.h"
#include "emu/nes/nes.h"
#include "emu/nes/nesinput.h"
#include "emu/nes/nesstate.h"
#include "emu/nes/nes_pal.h"
#include "emu/cpu/dis6502.hpp"
#include "chip/FAMIPAD.hpp"
extern "C" {
uint8_t get_fami_pad();
}
namespace emu {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief NESエミュレーション・クラス
@param[in] AUDIO_SAMPLE_RATE オーディオ・サンプル・レート
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t AUDIO_SAMPLE_RATE>
class nesemu {
static const int nes_width_ = 256;
static const int nes_height_ = 240;
static const int sample_rate_ = AUDIO_SAMPLE_RATE;
static const int sample_bits_ = 16;
static const int audio_len_ = (sample_rate_ / 60) + 1;
uint16_t audio_buf_[audio_len_];
bool nesrom_;
cpu::dis6502 disa_;
uint16_t mon_val_[3];
nesinput_t inp_[2];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
nesemu() noexcept : audio_buf_{ 0 }, nesrom_(false),
disa_(nes6502_getbyte, nes6502_putbyte),
mon_val_{ 0 }
{ }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] オーディオをサポートしない場合「false」
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start(bool audio_ena = true)
{
log_init();
nes_create(sample_rate_, sample_bits_);
inp_[0].type = INP_JOYPAD0;
inp_[0].data = 0;
input_register(&inp_[0]);
inp_[1].type = INP_JOYPAD1;
inp_[1].data = 0;
input_register(&inp_[1]);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エミュレーター・ファイルを開く
@param[in] filename ファイル名
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool open(const char* filename)
{
if(nes_insert_cart(filename) == 0) {
nesrom_ = true;
}
return nesrom_;
}
//-----------------------------------------------------------------//
/*!
@brief カートリッジが有効か?
@return 有効なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return nesrom_; }
//-----------------------------------------------------------------//
/*!
@brief 一時停止の取得
@return 一時停止
*/
//-----------------------------------------------------------------//
bool get_pause() const noexcept {
const nes_t* t = nes_getcontext();
return t->pause;
}
//-----------------------------------------------------------------//
/*!
@brief 一時停止
*/
//-----------------------------------------------------------------//
void enable_pause(bool ena = true) noexcept {
if(!nesrom_) return;
nes_pause(ena);
}
//-----------------------------------------------------------------//
/*!
@brief 情報取得
@return 情報テキスト
*/
//-----------------------------------------------------------------//
const char* get_info() noexcept {
nes_t* t = nes_getcontext();
if(t == nullptr) return nullptr;
if(t->rominfo == nullptr) return nullptr;
return rom_getinfo(t->rominfo);
}
//-----------------------------------------------------------------//
/*!
@brief エミュレーターを終了
*/
//-----------------------------------------------------------------//
void close() noexcept
{
if(nesrom_) {
nes_eject_cart();
nesrom_ = false;
}
}
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] org フレームバッファのアドレス
@param[in] xs フレームバッファのX幅
@param[in] ys フレームバッファのY幅
*/
//-----------------------------------------------------------------//
void service(void* org, uint32_t xs, uint32_t ys)
{
auto nes = nes_getcontext();
bitmap_t* v = nes->vidbuf;
const rgb_t* lut = get_palette();
if(v == nullptr || lut == nullptr) {
return;
}
{
inp_[0].data = 0; // Player 1
inp_[1].data = 0; // Player 2
uint8_t pad = get_fami_pad();
if(chip::on(pad, chip::FAMIPAD_ST::A)) {
inp_[0].data |= INP_PAD_A;
}
if(chip::on(pad, chip::FAMIPAD_ST::B)) {
inp_[0].data |= INP_PAD_B;
}
if(chip::on(pad, chip::FAMIPAD_ST::SELECT)) {
inp_[0].data |= INP_PAD_SELECT;
}
if(chip::on(pad, chip::FAMIPAD_ST::START)) {
inp_[0].data |= INP_PAD_START;
}
if(chip::on(pad, chip::FAMIPAD_ST::UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(chip::on(pad, chip::FAMIPAD_ST::DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
if(chip::on(pad, chip::FAMIPAD_ST::LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(chip::on(pad, chip::FAMIPAD_ST::RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
}
uint16_t luttmp[256];
for(uint32_t i = 0; i < 64; ++i) {
uint16_t r = lut[i].r; // R
uint16_t g = lut[i].g; // G
uint16_t b = lut[i].b; // B
// R(5), G(6), B(5)
luttmp[i] = ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3);
luttmp[i+128+64] = luttmp[i+128] = luttmp[i+64] = luttmp[i];
}
uint16_t* dst = static_cast<uint16_t*>(org);
dst += ((ys - (nes_height_ - 16)) / 2) * xs;
const uint8_t* src = v->data;
src += v->pitch * 16;
for(int h = 0; h < (nes_height_ - 16); ++h) {
uint16_t* tmp = dst;
tmp += (xs - nes_width_) / 2;
for(int w = 0; w < nes_width_ / 16; ++w) {
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
}
src += v->pitch - nes_width_;
dst += xs;
}
if(nesrom_) {
apu_process(audio_buf_, audio_len_);
nes_emulate(1);
}
}
//-----------------------------------------------------------------//
/*!
@brief オーディオ・バッファの長さを取得
@return オーディオ・バッファの長さ
*/
//-----------------------------------------------------------------//
uint32_t get_audio_len() const noexcept { return audio_len_; }
//-----------------------------------------------------------------//
/*!
@brief オーディオ・バッファを取得
@return オーディオ・バッファのポインター
*/
//-----------------------------------------------------------------//
const uint16_t* get_audio_buf() const noexcept { return audio_buf_; }
//-----------------------------------------------------------------//
/*!
@brief ステートのセーブ
@param[in] no スロット番号(0~9)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool save_state(int no) noexcept {
if(!nesrom_) return false;
state_setslot(no);
return state_save() == 0;
}
//-----------------------------------------------------------------//
/*!
@brief ステートのロード
@param[in] no スロット番号(0~9)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool load_state(int no) noexcept {
if(!nesrom_) return false;
state_setslot(no);
return state_load() == 0;
}
//-----------------------------------------------------------------//
/*!
@brief ハード・リセット
*/
//-----------------------------------------------------------------//
void reset() noexcept {
nes_reset(HARD_RESET);
}
//-----------------------------------------------------------------//
/*!
@brief モニター機能
@param[in] cmd コマンド
*/
//-----------------------------------------------------------------//
void monitor(const char* cmd) noexcept {
char ch;
uint16_t hexadec = 0;
bool write = false;
bool area = false;
while(1) {
ch = *cmd++;
if(ch >= 'a' && ch <= 'z') ch -= 0x20;
if(ch >= '0' && ch <= '9') {
mon_val_[0] <<= 4;
mon_val_[0] |= static_cast<uint16_t>(ch - '0');
++hexadec;
} else if(ch >= 'A' && ch <= 'F') {
mon_val_[0] <<= 4;
mon_val_[0] |= static_cast<uint16_t>(ch - 'A' + 10);
++hexadec;
} else if(ch == 'L') {
if(hexadec > 0) {
mon_val_[2] = mon_val_[0];
}
for(int i = 0; i < 20; ++i) {
char tmp[64];
disa_.disasm(mon_val_[2], tmp, sizeof(tmp));
utils::str::to_caps(tmp, tmp, sizeof(tmp));
utils::format("%s\n") % tmp;
mon_val_[2] = disa_.get_pc();
}
hexadec = 0;
write = false;
area = false;
} else if(ch == '.') {
mon_val_[1] = mon_val_[0];
write = false;
area = true;
hexadec = 0;
} else if(ch == ':') {
mon_val_[1] = mon_val_[0];
write = true;
area = false;
hexadec = 0;
} else if(ch == ' ' || ch == 0) {
if(write) {
if(hexadec > 0) {
nes6502_putbyte(mon_val_[1], mon_val_[0]);
mon_val_[1]++;
}
} else if(ch == 0) {
uint32_t org = 0;
uint32_t end = 0;
if(area) {
org = mon_val_[1];
if(hexadec > 0) {
end = mon_val_[0] + 1;
if(org > end) end = org;
} else {
end = org + 16;
}
area = false;
} else {
if(hexadec > 0) {
org = mon_val_[1] = mon_val_[0];
end = org + 1;
} else {
org = end = mon_val_[1];
}
}
while(org < end) {
char tmp[96];
auto l = end - org;
if(l == 0) l = 1;
else if(l > 16) l = 16;
org = disa_.dump(org, l, tmp, sizeof(tmp));
utils::format("%s\n") % tmp;
}
mon_val_[1] = org;
}
mon_val_[0] = 0;
hexadec = 0;
} else {
utils::format("%c?\n") % ch;
hexadec = 0;
write = false;
area = false;
}
if(ch == 0) break;
}
}
};
}
<commit_msg>Update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief NES Emulator ハンドラー
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018, 2019 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/string_utils.hpp"
#include "emu/log.h"
#include "emu/nes/nes.h"
#include "emu/nes/nesinput.h"
#include "emu/nes/nesstate.h"
#include "emu/nes/nes_pal.h"
#include "emu/cpu/dis6502.hpp"
#include "chip/FAMIPAD.hpp"
extern "C" {
uint8_t get_fami_pad();
}
namespace emu {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief NESエミュレーション・クラス
@param[in] AUDIO_SAMPLE_RATE オーディオ・サンプル・レート
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t AUDIO_SAMPLE_RATE>
class nesemu {
static const int nes_width_ = 256;
static const int nes_height_ = 240;
static const int sample_rate_ = AUDIO_SAMPLE_RATE;
static const int sample_bits_ = 16;
static const int audio_len_ = (sample_rate_ / 60) + 1;
uint16_t audio_buf_[audio_len_];
bool nesrom_;
cpu::dis6502 disa_;
uint16_t mon_val_[3];
nesinput_t inp_[2];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクタ
*/
//-----------------------------------------------------------------//
nesemu() noexcept : audio_buf_{ 0 }, nesrom_(false),
disa_(nes6502_getbyte, nes6502_putbyte),
mon_val_{ 0 }
{ }
//-----------------------------------------------------------------//
/*!
@brief 開始
@param[in] オーディオをサポートしない場合「false」
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start(bool audio_ena = true)
{
log_init();
nes_create(sample_rate_, sample_bits_);
inp_[0].type = INP_JOYPAD0;
inp_[0].data = 0;
input_register(&inp_[0]);
inp_[1].type = INP_JOYPAD1;
inp_[1].data = 0;
input_register(&inp_[1]);
return true;
}
//-----------------------------------------------------------------//
/*!
@brief エミュレーター・ファイルを開く
@param[in] filename ファイル名
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool open(const char* filename)
{
if(nes_insert_cart(filename) == 0) {
nesrom_ = true;
}
return nesrom_;
}
//-----------------------------------------------------------------//
/*!
@brief カートリッジが有効か?
@return 有効なら「true」
*/
//-----------------------------------------------------------------//
bool probe() const { return nesrom_; }
//-----------------------------------------------------------------//
/*!
@brief 一時停止の取得
@return 一時停止
*/
//-----------------------------------------------------------------//
bool get_pause() const noexcept {
const nes_t* t = nes_getcontext();
return t->pause;
}
//-----------------------------------------------------------------//
/*!
@brief 一時停止
*/
//-----------------------------------------------------------------//
void enable_pause(bool ena = true) noexcept {
if(!nesrom_) return;
nes_pause(ena);
}
//-----------------------------------------------------------------//
/*!
@brief 情報取得
@return 情報テキスト
*/
//-----------------------------------------------------------------//
const char* get_info() noexcept {
nes_t* t = nes_getcontext();
if(t == nullptr) return nullptr;
if(t->rominfo == nullptr) return nullptr;
return rom_getinfo(t->rominfo);
}
//-----------------------------------------------------------------//
/*!
@brief エミュレーターを終了
*/
//-----------------------------------------------------------------//
void close() noexcept
{
if(nesrom_) {
nes_eject_cart();
nesrom_ = false;
}
}
//-----------------------------------------------------------------//
/*!
@brief サービス
@param[in] org フレームバッファのアドレス
@param[in] xs フレームバッファのX幅
@param[in] ys フレームバッファのY幅
*/
//-----------------------------------------------------------------//
void service(void* org, uint32_t xs, uint32_t ys)
{
auto nes = nes_getcontext();
bitmap_t* v = nes->vidbuf;
const rgb_t* lut = get_palette();
if(v == nullptr || lut == nullptr) {
return;
}
{
inp_[0].data = 0; // Player 1
inp_[1].data = 0; // Player 2
uint8_t pad = get_fami_pad();
if(chip::on(pad, chip::FAMIPAD_ST::A)) {
inp_[0].data |= INP_PAD_A;
}
if(chip::on(pad, chip::FAMIPAD_ST::B)) {
inp_[0].data |= INP_PAD_B;
}
if(chip::on(pad, chip::FAMIPAD_ST::SELECT)) {
inp_[0].data |= INP_PAD_SELECT;
}
if(chip::on(pad, chip::FAMIPAD_ST::START)) {
inp_[0].data |= INP_PAD_START;
}
if(chip::on(pad, chip::FAMIPAD_ST::UP)) {
inp_[0].data |= INP_PAD_UP;
}
if(chip::on(pad, chip::FAMIPAD_ST::DOWN)) {
inp_[0].data |= INP_PAD_DOWN;
}
if(chip::on(pad, chip::FAMIPAD_ST::LEFT)) {
inp_[0].data |= INP_PAD_LEFT;
}
if(chip::on(pad, chip::FAMIPAD_ST::RIGHT)) {
inp_[0].data |= INP_PAD_RIGHT;
}
}
uint16_t luttmp[256];
for(uint32_t i = 0; i < 64; ++i) {
uint16_t r = lut[i].r; // R
uint16_t g = lut[i].g; // G
uint16_t b = lut[i].b; // B
// R(5), G(6), B(5)
luttmp[i] = ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3);
luttmp[i+128+64] = luttmp[i+128] = luttmp[i+64] = luttmp[i];
}
uint16_t* dst = static_cast<uint16_t*>(org);
dst += ((ys - (nes_height_ - 16)) / 2) * xs;
const uint8_t* src = v->data;
src += v->pitch * 16;
for(int h = 0; h < (nes_height_ - 16); ++h) {
uint16_t* tmp = dst;
tmp += (xs - nes_width_) / 2;
for(int w = 0; w < nes_width_ / 16; ++w) {
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
*tmp++ = luttmp[*src++]; *tmp++ = luttmp[*src++];
}
src += v->pitch - nes_width_;
dst += xs;
}
if(nesrom_) {
apu_process(audio_buf_, audio_len_);
nes_emulate(1);
}
}
//-----------------------------------------------------------------//
/*!
@brief オーディオ・バッファの長さを取得
@return オーディオ・バッファの長さ
*/
//-----------------------------------------------------------------//
uint32_t get_audio_len() const noexcept { return audio_len_; }
//-----------------------------------------------------------------//
/*!
@brief オーディオ・バッファを取得
@return オーディオ・バッファのポインター
*/
//-----------------------------------------------------------------//
const uint16_t* get_audio_buf() const noexcept { return audio_buf_; }
//-----------------------------------------------------------------//
/*!
@brief ステートのセーブ
@param[in] no スロット番号(0~9)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool save_state(int no) noexcept {
if(!nesrom_) return false;
state_setslot(no);
return state_save() == 0;
}
//-----------------------------------------------------------------//
/*!
@brief ステートのロード
@param[in] no スロット番号(0~9)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool load_state(int no) noexcept {
if(!nesrom_) return false;
state_setslot(no);
return state_load() == 0;
}
//-----------------------------------------------------------------//
/*!
@brief ハード・リセット
*/
//-----------------------------------------------------------------//
void reset() noexcept {
nes_reset(HARD_RESET);
}
//-----------------------------------------------------------------//
/*!
@brief モニター機能
@param[in] cmd コマンド
*/
//-----------------------------------------------------------------//
void monitor(const char* cmd) noexcept {
char ch;
uint16_t hexadec = 0;
bool write = false;
bool area = false;
bool search = false;
while(1) {
ch = *cmd++;
if(ch >= 'a' && ch <= 'z') ch -= 0x20;
if(ch >= '0' && ch <= '9') {
mon_val_[0] <<= 4;
mon_val_[0] |= static_cast<uint16_t>(ch - '0');
++hexadec;
} else if(ch >= 'A' && ch <= 'F') {
mon_val_[0] <<= 4;
mon_val_[0] |= static_cast<uint16_t>(ch - 'A' + 10);
++hexadec;
} else if(ch == 'L') { ///< disasm List
if(hexadec > 0) {
mon_val_[2] = mon_val_[0];
}
for(int i = 0; i < 20; ++i) {
char tmp[64];
disa_.disasm(mon_val_[2], tmp, sizeof(tmp));
utils::str::to_caps(tmp, tmp, sizeof(tmp));
utils::format("%s\n") % tmp;
mon_val_[2] = disa_.get_pc();
}
hexadec = 0;
write = false;
area = false;
} else if(ch == 'S') { ///< Search
mon_val_[2] = mon_val_[0];
search = true;
hexadec = 0;
} else if(ch == '.') {
mon_val_[1] = mon_val_[0];
write = false;
area = true;
hexadec = 0;
} else if(ch == ':') {
mon_val_[1] = mon_val_[0];
write = true;
area = false;
hexadec = 0;
} else if(ch == ' ' || ch == 0) {
if(write) {
if(hexadec > 0) {
nes6502_putbyte(mon_val_[1], mon_val_[0]);
mon_val_[1]++;
}
} else if(ch == 0) {
uint32_t org = 0;
uint32_t end = 0;
if(search) { // search
org = mon_val_[1];
end = mon_val_[2];
while(org <= end) {
auto rd = nes6502_getbyte(org);
if(rd == (mon_val_[0] & 0xff)) {
utils::format("%04X- %02X\n") % org % static_cast<uint16_t>(rd);
}
++org;
}
} else { // for dump
if(area) {
org = mon_val_[1];
if(hexadec > 0) {
end = mon_val_[0] + 1;
if(org > end) end = org;
} else {
end = org + 16;
}
area = false;
} else {
if(hexadec > 0) {
org = mon_val_[1] = mon_val_[0];
end = org + 1;
} else {
org = end = mon_val_[1];
}
}
while(org < end) {
char tmp[96];
auto l = end - org;
if(l == 0) l = 1;
else if(l > 16) l = 16;
org = disa_.dump(org, l, tmp, sizeof(tmp));
utils::format("%s\n") % tmp;
}
mon_val_[1] = org;
}
}
mon_val_[0] = 0;
hexadec = 0;
} else {
utils::format("%c?\n") % ch;
hexadec = 0;
write = false;
area = false;
search = false;
}
if(ch == 0) break;
}
}
};
}
<|endoftext|>
|
<commit_before>#include "TestCommon.hh" //to get argparser
using namespace SDLut;
Logger testlog("ScreenAccess");
class Assert : public AssertEngine
{
video::Rect assertedrect;
video::Color color;
public:
Assert(Logger& l, ArgParser& ap,video::Rect assertrect, video::Color c)
: AssertEngine(l,ap), assertedrect(assertrect), color(c)
{
if ( ! testlog.isFileLogEnabled() ) testlog.enableFileLog("TestScreenAccess.log");
}
bool assertresize(int width, int height)
{
if (assertedrect.getx() < 0) assertedrect.resetx(0);
if (assertedrect.gety() < 0) assertedrect.resety(0);
if ( (int)(assertedrect.getx() + assertedrect.getw() ) > width ) assertedrect.resetw( width - assertedrect.getx() );
if ( (int)(assertedrect.gety() + assertedrect.geth() ) > height ) assertedrect.reseth( height - assertedrect.gety() );
return true;
}
bool assertrender(video::ScreenBuffer& sb) const
{
bool res = true;
int x =assertedrect.getx(), y =assertedrect.gety();
while ( y < (int)assertedrect.geth())
{
while ( x < (int)assertedrect.getw() )
{
res = res && (sb.getColorAt(x,y) == color);
}
}
return res ;
}
};
class Test : public TestEngine
{
video::Rect testedrect;
video::Color color;
public:
Test(Logger& l, Assert & a, video::Rect testrect, video::Color c) : TestEngine(l,a), testedrect(testrect),color(c) {}
bool resize(int width, int height)
{
//check rect size
if (testedrect.getx() < 0) testedrect.resetx(0);
if (testedrect.gety() < 0) testedrect.resety(0);
if ( (int)(testedrect.getx() + testedrect.getw()) > width ) testedrect.resetw( width - testedrect.getx() );
if ( (int)(testedrect.gety() + testedrect.geth()) > height ) testedrect.reseth( height - testedrect.gety() );
return true;
}
bool render(video::ScreenBuffer& sb) const
{
if ( (1 == testedrect.geth() ) && ( testedrect.getw() == 1 ) )
{
sb.setColorAt( testedrect.getx(),testedrect.gety(),color );
}
else
{
//working around constness
video::Rect dstrect = testedrect;
sb.setColorAt( dstrect,color);
}
return true;
}
};
int main(int argc, char** argv)
{
ArgParser args(argc,argv);
//Starting with usual SDL window
App::getInstance().initVideo(false,true,false);
App::getInstance().setName ("SDLut::video Dumb test ");
//Setting Display size and BPP
App::getInstance().getDisplay().requestSize(300,240); // using autodetected bpp
App::getInstance().getDisplay().requestOpenGL(args.isOGL());
int exitstatus = -1;
///testing pixel set
video::Color color(Randomizer<unsigned char>::get(),Randomizer<unsigned char>::get(),Randomizer<unsigned char>::get());
video::Rect pix(Randomizer<unsigned int>::get(0,300),Randomizer<unsigned int>::get(0,240 - 64 )); //keeping some space for logos...
Assert asrt(testlog,args,pix,color);
Test engine(testlog,asrt,pix,color);
if (App::getInstance().getDisplay().show())
{
exitstatus = App::getInstance().getDisplay().mainLoop();
}
video::Rect scarea(Randomizer<unsigned int>::get(0,300),Randomizer<unsigned int>::get(0,240 - 64 )); //keeping some space for logos...
scarea.resetw(Randomizer<unsigned int>::get(1,300 - scarea.getx()));
scarea.reseth(Randomizer<unsigned int>::get(1,240-64 - scarea.gety()));
//quick check
if (scarea.getw() < 1)
{
scarea.resetw();
}
if (scarea.geth() < 1)
{
scarea.reseth();
}
///testing rect fill
//Declaring these here will construct them and reset the SDLut Callbacks as per parents classes in TestCommon.hh.
Assert asrtbis(testlog,args,scarea,color);
Test enginebis(testlog,asrtbis,scarea,color);
//BUG
//This should not be needed !!!
//TODO : FIX IT
App::getInstance().getDisplay().requestOpenGL(args.isOGL());
if (App::getInstance().getDisplay().show())
{
exitstatus = (exitstatus == 0) && App::getInstance().getDisplay().mainLoop();
}
return exitstatus;
}
<commit_msg>fix for midnight coding syndrome...<commit_after>#include "TestCommon.hh" //to get argparser
using namespace SDLut;
Logger testlog("ScreenAccess");
class Assert : public AssertEngine
{
video::Rect assertedrect;
video::Color color;
public:
Assert(Logger& l, ArgParser& ap,video::Rect assertrect, video::Color c)
: AssertEngine(l,ap), assertedrect(assertrect), color(c)
{
if ( ! testlog.isFileLogEnabled() ) testlog.enableFileLog("TestScreenAccess.log");
}
bool assertresize(int width, int height)
{
if (assertedrect.getx() < 0) assertedrect.resetx(0);
if (assertedrect.gety() < 0) assertedrect.resety(0);
if ( (int)(assertedrect.getx() + assertedrect.getw() ) > width ) assertedrect.resetw( width - assertedrect.getx() );
if ( (int)(assertedrect.gety() + assertedrect.geth() ) > height ) assertedrect.reseth( height - assertedrect.gety() );
return true;
}
bool assertrender(video::ScreenBuffer& sb) const
{
bool res = true;
unsigned int x =0, y =0;
while ( y < assertedrect.geth())
{
while ( x < assertedrect.getw())
{
res = res && (sb.getColorAt(x + assertedrect.getx(),y + assertedrect.gety()) == color);
x++;
}
y++;
}
return res ;
}
};
class Test : public TestEngine
{
video::Rect testedrect;
video::Color color;
public:
Test(Logger& l, Assert & a, video::Rect testrect, video::Color c) : TestEngine(l,a), testedrect(testrect),color(c) {}
bool resize(int width, int height)
{
//check rect size
if (testedrect.getx() < 0) testedrect.resetx(0);
if (testedrect.gety() < 0) testedrect.resety(0);
if ( (int)(testedrect.getx() + testedrect.getw()) > width ) testedrect.resetw( width - testedrect.getx() );
if ( (int)(testedrect.gety() + testedrect.geth()) > height ) testedrect.reseth( height - testedrect.gety() );
return true;
}
bool render(video::ScreenBuffer& sb) const
{
if ( (1 == testedrect.geth() ) && ( testedrect.getw() == 1 ) )
{
sb.setColorAt( testedrect.getx(),testedrect.gety(),color );
}
else
{
//working around constness
video::Rect dstrect = testedrect;
sb.setColorAt( dstrect,color);
}
return true;
}
};
int main(int argc, char** argv)
{
ArgParser args(argc,argv);
//Starting with usual SDL window
App::getInstance().initVideo(false,true,false);
App::getInstance().setName ("SDLut::video Dumb test ");
//Setting Display size and BPP
App::getInstance().getDisplay().requestSize(300,240); // using autodetected bpp
App::getInstance().getDisplay().requestOpenGL(args.isOGL());
int exitstatus = -1;
///testing pixel set
video::Color color(Randomizer<unsigned char>::get(),Randomizer<unsigned char>::get(),Randomizer<unsigned char>::get());
video::Rect pix(Randomizer<unsigned int>::get(0,300),Randomizer<unsigned int>::get(0,240 - 64 )); //keeping some space for logos...
Assert asrt(testlog,args,pix,color);
Test engine(testlog,asrt,pix,color);
if (App::getInstance().getDisplay().show())
{
exitstatus = App::getInstance().getDisplay().mainLoop();
}
video::Rect scarea(Randomizer<unsigned int>::get(0,300),Randomizer<unsigned int>::get(0,240 - 64 )); //keeping some space for logos...
scarea.resetw(Randomizer<unsigned int>::get(1,300 - scarea.getx()));
scarea.reseth(Randomizer<unsigned int>::get(1,240-64 - scarea.gety()));
//quick check
if (scarea.getw() < 1)
{
scarea.resetw();
}
if (scarea.geth() < 1)
{
scarea.reseth();
}
///testing rect fill
//Declaring these here will construct them and reset the SDLut Callbacks as per parents classes in TestCommon.hh.
Assert asrtbis(testlog,args,scarea,color);
Test enginebis(testlog,asrtbis,scarea,color);
//BUG
//This should not be needed !!!
//TODO : FIX IT
App::getInstance().getDisplay().requestOpenGL(args.isOGL());
if (App::getInstance().getDisplay().show())
{
exitstatus = (exitstatus == 0) && App::getInstance().getDisplay().mainLoop();
}
return exitstatus;
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
#define CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
#include "clotho/data_spaces/crossover/crossover_method_def.hpp"
#include "clotho/data_spaces/association_matrix/row_grouped_association_matrix.hpp"
#include "clotho/data_spaces/generators/small_crossover_event_generator.hpp"
#include "clotho/data_spaces/generators/buffered_small_crossover_event_generator.hpp"
#include "clotho/utility/bit_helper.hpp"
#include "clotho/utility/debruijn_bit_walker.hpp"
namespace clotho {
namespace genetics {
template < class RNG, class AlleleSpaceType, class BlockType >
class crossover_method< RNG, AlleleSpaceType, association_matrix< BlockType, row_grouped< 2 > > > {
public:
typedef RNG random_engine_type;
typedef AlleleSpaceType allele_type;
typedef association_matrix< BlockType, row_grouped< 2 > > sequence_space_type;
typedef typename sequence_space_type::raw_block_pointer sequence_iterator;
typedef typename sequence_space_type::raw_block_pointer genome_iterator;
typedef typename allele_type::position_type position_type;
typedef small_crossover_event_generator< RNG, position_type > event_generator_type;
typedef typename sequence_space_type::block_type block_type;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
crossover_method( RNG * rng, boost::property_tree::ptree & config ) :
m_event_gen( rng, config )
{}
void initAlleles( allele_type & alls ) {
m_event_gen.update( alls.getPositions(), alls.size());
}
void crossover( genome_iterator start, genome_iterator end, sequence_iterator s, size_t p_step, size_t s_step ) {
size_t N = m_event_gen.generate();
if( N != 0 ) {
size_t j = 0;
while( start != end ) {
block_type first = *start++;
block_type second = *start++;
block_type hets = first ^ second;
block_type sec = bit_helper_type::ALL_UNSET; // mask state from second strand
while( hets ) {
size_t idx = bit_walker_type::unset_next_index( hets ) + j;
if( m_event_gen( idx ) ) {
sec |= bit_helper_type::bit_offset( idx );
}
}
*s = ((first & ~sec) | (second & sec));
j += bit_helper_type::BITS_PER_BLOCK;
s += row_grouped< 2 >::GROUP_SIZE;
}
} else {
if( m_event_gen.getBaseSequence() != 0 ) {
++start;
++end;
}
size_t j = 0;
while( start != end ) {
*s = *start;
start += row_grouped< 2 >::GROUP_SIZE;
s += row_grouped< 2 >::GROUP_SIZE;
j += bit_helper_type::BITS_PER_BLOCK;
}
}
}
virtual ~crossover_method() {}
protected:
event_generator_type m_event_gen;
};
template < class BlockType >
struct base_crossover_method {
inline BlockType operator()( const BlockType & a, const BlockType & b, const BlockType & c) const {
return ((a & ~c) | (b & c));
}
};
template < class BlockType >
struct alt_crossover_method {
inline BlockType operator()( const BlockType & a, const BlockType & b, const BlockType & c) const {
return ((a & c) | (b & ~c));
}
};
template < class RNG, class AlleleSpaceType, class BlockType >
class crossover_method< RNG, AlleleSpaceType, association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef RNG random_engine_type;
typedef AlleleSpaceType allele_type;
typedef association_matrix< BlockType, row_grouped< 1 > > sequence_space_type;
typedef typename sequence_space_type::raw_block_pointer sequence_iterator;
typedef typename sequence_space_type::raw_block_pointer genome_iterator;
typedef typename allele_type::position_type position_type;
typedef buffered_small_crossover_event_generator< RNG, position_type > event_generator_type;
typedef typename sequence_space_type::block_type block_type;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
typedef base_crossover_method< block_type > base_method;
typedef alt_crossover_method< block_type > alt_method;
crossover_method( RNG * rng, boost::property_tree::ptree & config ) :
m_event_gen( rng, config )
{}
void initAlleles( allele_type & alls ) {
m_event_gen.update( alls.getPositions(), alls.size() );
}
/**
*
* @return soft max of result sequence
*/
unsigned int crossover( sequence_iterator first, unsigned int N, sequence_iterator second, unsigned int M, sequence_iterator s ) {
unsigned int res = 0;
if( m_event_gen.generate() != 0 ) {
if( m_event_gen.getBaseSequence() == 0 ) {
base_method met;
res = buffered_write_build_sequence( s, first, N, second, M, met );
} else {
alt_method met;
res = buffered_write_build_sequence(s, first, N, second, M, met );
}
} else if( m_event_gen.getBaseSequence() != 0 ) {
// use second strand
res = copy_sequence( s, second, M );
} else {
res = copy_sequence( s, first, N );
}
return res;
}
virtual ~crossover_method() {}
protected:
/**
*
* Copies global sequence data to local stack buffers
* Operates on stack buffers writing back to stack
* Copies stack to final output vector
*
* Is read and write buffering beneficial?
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int buffered_build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int soft_N, sequence_iterator second, const unsigned int soft_M, const Method & m ) {
const unsigned int N = 16;
block_type first_buffer[ N ]; // 16 * 8 == 128 byte buffer
block_type second_buffer[ N ];
const unsigned int soft_max = (( soft_N > soft_M )? soft_N : soft_M ); // soft maximum length
unsigned int last_block = 0;
unsigned int l = 0;
while( l < soft_max ) {
unsigned int j = (soft_max - l);
j = ((j > N) ? N : j);
// read global data to local buffers
memcpy( first_buffer, first + l, j * sizeof( block_type ) );
memcpy( second_buffer, second + l, j * sizeof( block_type ) );
unsigned int i = 0;
while( i < j ) {
const unsigned int offset = l + i;
block_type first = ((offset < soft_N ) ? first_buffer[ i ] : bit_helper_type::ALL_UNSET);
block_type second = ((offset < soft_M ) ? second_buffer[ i ] : bit_helper_type::ALL_UNSET);
block_type mask = buffered_build_mask( first, second, offset * bit_helper_type::BITS_PER_BLOCK );
mask = m( first, second, mask );
second_buffer[ i ] = mask;
++i;
if( mask ) {
last_block = offset + 1;
}
}
// write to result sequence
memcpy( res + l, second_buffer, j * sizeof(block_type) );
l += j;
}
return last_block;
}
/**
* Unraveled the set bit decoding
*/
block_type buffered_build_mask( block_type first, block_type second, unsigned int offset ) {
block_type hets = first ^ second;
block_type mask = bit_helper_type::ALL_UNSET; // mask state from second strand
unsigned int het_buffer[ bit_helper_type::BITS_PER_BLOCK ]; // i.e. buffer_size = 64 * 4 = 256 bytes buffer
if( hets ) {
m_event_gen.update_buffer( offset );
// decode set indices
unsigned int j = 0;
do {
het_buffer[ j ] = bit_walker_type::unset_next_index( hets );
++j;
} while( hets );
// evaluate positions at relative indices
unsigned int i = 0;
while( i < j ) {
unsigned int idx = het_buffer[ i ];
if( m_event_gen( idx ) ) {
mask |= clotho::utility::bit_masks[ idx ];
}
++i;
}
}
return mask;
}
/**
*
* Initial technique for building a crossover mask
*
*
*/
block_type build_mask( block_type first, block_type second, unsigned int offset ) {
block_type hets = first ^ second;
block_type mask = bit_helper_type::ALL_UNSET; // mask state from second strand
if( hets ) {
m_event_gen.update_buffer( offset );
do {
unsigned int idx = bit_walker_type::unset_next_index( hets );
if( m_event_gen( idx ) ) {
mask |= clotho::utility::bit_masks[ idx ];
}
} while( hets );
}
return mask;
}
template < class Method >
void build_sequence( sequence_iterator s, genome_iterator start, genome_iterator end, const Method & m ) {
size_t j = 0;
genome_iterator sec_ptr = end;
while( start != end ) {
block_type first = *start++;
block_type second = *sec_ptr++;
block_type mask = build_mask( first, second, j );
*s++ = m(first, second, mask);
j += bit_helper_type::BITS_PER_BLOCK;
}
}
/**
*
* Uses soft max of both sequence
*
* Is write buffer beneficial?
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int buffered_write_build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int soft_N, sequence_iterator second, const unsigned int soft_M, const Method & m ) {
const unsigned int N = 32;
block_type _buffer[ N ]; // 256 byte buffer
const unsigned int soft_max = (( soft_N > soft_M )? soft_N : soft_M ); // soft maximum length
unsigned int last_block = 0;
unsigned int i = 0, j = 0;
while( j < soft_max ) {
block_type a = ((j < soft_N ) ? first[ j ] : bit_helper_type::ALL_UNSET);
block_type b = ((j < soft_M ) ? second[ j ] : bit_helper_type::ALL_UNSET);
block_type mask = build_mask( a, b, j * bit_helper_type::BITS_PER_BLOCK );
mask = m( a, b, mask );
_buffer[ i++ ] = mask;
++j;
if( mask ) {
last_block = j;
}
if( i >= N ) {
// buffer is full
memcpy( res, _buffer, N * sizeof(block_type) );
res += N;
i = 0;
}
}
// write final buffer
if( i ) {
memcpy( res, _buffer, i * sizeof( block_type ) );
}
return last_block;
}
/**
*
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int N, sequence_iterator second, const unsigned int M, const Method & m ) {
const unsigned int W = (( N > M )? N : M );
unsigned int i = 0;
unsigned int last_block = 0;
while( i < W ) {
block_type a = ((i < N ) ? first[ i ] : bit_helper_type::ALL_UNSET);
block_type b = ((i < M ) ? second[ i ] : bit_helper_type::ALL_UNSET);
block_type mask = build_mask( a, b, i * bit_helper_type::BITS_PER_BLOCK );
mask = m(a, b, mask );
res[ i ] = mask;
++i;
if( mask ) {
last_block = i;
}
}
return last_block;
}
unsigned int copy_sequence( sequence_iterator s, sequence_iterator start, const size_t W ) {
memcpy( s, start, W * sizeof(block_type));
return W;
}
event_generator_type m_event_gen;
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
<commit_msg>Attempting something more efficient<commit_after>// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
#define CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
#include "clotho/data_spaces/crossover/crossover_method_def.hpp"
#include "clotho/data_spaces/association_matrix/row_grouped_association_matrix.hpp"
#include "clotho/data_spaces/generators/small_crossover_event_generator.hpp"
#include "clotho/data_spaces/generators/buffered_small_crossover_event_generator.hpp"
#include "clotho/utility/bit_helper.hpp"
#include "clotho/utility/debruijn_bit_walker.hpp"
namespace clotho {
namespace genetics {
template < class RNG, class AlleleSpaceType, class BlockType >
class crossover_method< RNG, AlleleSpaceType, association_matrix< BlockType, row_grouped< 2 > > > {
public:
typedef RNG random_engine_type;
typedef AlleleSpaceType allele_type;
typedef association_matrix< BlockType, row_grouped< 2 > > sequence_space_type;
typedef typename sequence_space_type::raw_block_pointer sequence_iterator;
typedef typename sequence_space_type::raw_block_pointer genome_iterator;
typedef typename allele_type::position_type position_type;
typedef small_crossover_event_generator< RNG, position_type > event_generator_type;
typedef typename sequence_space_type::block_type block_type;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
crossover_method( RNG * rng, boost::property_tree::ptree & config ) :
m_event_gen( rng, config )
{}
void initAlleles( allele_type & alls ) {
m_event_gen.update( alls.getPositions(), alls.size());
}
void crossover( genome_iterator start, genome_iterator end, sequence_iterator s, size_t p_step, size_t s_step ) {
size_t N = m_event_gen.generate();
if( N != 0 ) {
size_t j = 0;
while( start != end ) {
block_type first = *start++;
block_type second = *start++;
block_type hets = first ^ second;
block_type sec = bit_helper_type::ALL_UNSET; // mask state from second strand
while( hets ) {
size_t idx = bit_walker_type::unset_next_index( hets ) + j;
if( m_event_gen( idx ) ) {
sec |= bit_helper_type::bit_offset( idx );
}
}
*s = ((first & ~sec) | (second & sec));
j += bit_helper_type::BITS_PER_BLOCK;
s += row_grouped< 2 >::GROUP_SIZE;
}
} else {
if( m_event_gen.getBaseSequence() != 0 ) {
++start;
++end;
}
size_t j = 0;
while( start != end ) {
*s = *start;
start += row_grouped< 2 >::GROUP_SIZE;
s += row_grouped< 2 >::GROUP_SIZE;
j += bit_helper_type::BITS_PER_BLOCK;
}
}
}
virtual ~crossover_method() {}
protected:
event_generator_type m_event_gen;
};
template < class BlockType >
struct base_crossover_method {
inline BlockType operator()( const BlockType & a, const BlockType & b, const BlockType & c) const {
return ((a & ~c) | (b & c));
}
};
template < class BlockType >
struct alt_crossover_method {
inline BlockType operator()( const BlockType & a, const BlockType & b, const BlockType & c) const {
return ((a & c) | (b & ~c));
}
};
template < class RNG, class AlleleSpaceType, class BlockType >
class crossover_method< RNG, AlleleSpaceType, association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef RNG random_engine_type;
typedef AlleleSpaceType allele_type;
typedef association_matrix< BlockType, row_grouped< 1 > > sequence_space_type;
typedef typename sequence_space_type::raw_block_pointer sequence_iterator;
typedef typename sequence_space_type::raw_block_pointer genome_iterator;
typedef typename allele_type::position_type position_type;
typedef small_crossover_event_generator< RNG, position_type > event_generator_type;
typedef typename sequence_space_type::block_type block_type;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
typedef base_crossover_method< block_type > base_method;
typedef alt_crossover_method< block_type > alt_method;
crossover_method( RNG * rng, boost::property_tree::ptree & config ) :
m_event_gen( rng, config )
{}
void initAlleles( allele_type & alls ) {
m_event_gen.update( alls.getPositions(), alls.size() );
}
/**
*
* @return soft max of result sequence
*/
unsigned int crossover( sequence_iterator first, unsigned int N, sequence_iterator second, unsigned int M, sequence_iterator s ) {
unsigned int res = 0;
if( m_event_gen.generate() != 0 ) {
if( m_event_gen.getBaseSequence() == 0 ) {
base_method met;
res = build_sequence( s, first, N, second, M, met );
} else {
alt_method met;
res = build_sequence(s, first, N, second, M, met );
}
} else if( m_event_gen.getBaseSequence() != 0 ) {
// use second strand
res = copy_sequence( s, second, M );
} else {
res = copy_sequence( s, first, N );
}
return res;
}
virtual ~crossover_method() {}
protected:
/**
*
* Copies global sequence data to local stack buffers
* Operates on stack buffers writing back to stack
* Copies stack to final output vector
*
* Is read and write buffering beneficial?
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int buffered_build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int soft_N, sequence_iterator second, const unsigned int soft_M, const Method & m ) {
const unsigned int N = 16;
block_type first_buffer[ N ]; // 16 * 8 == 128 byte buffer
block_type second_buffer[ N ];
const unsigned int soft_max = (( soft_N > soft_M )? soft_N : soft_M ); // soft maximum length
unsigned int last_block = 0;
unsigned int l = 0;
while( l < soft_max ) {
unsigned int j = (soft_max - l);
j = ((j > N) ? N : j);
// read global data to local buffers
memcpy( first_buffer, first + l, j * sizeof( block_type ) );
memcpy( second_buffer, second + l, j * sizeof( block_type ) );
unsigned int i = 0;
while( i < j ) {
const unsigned int offset = l + i;
block_type first = ((offset < soft_N ) ? first_buffer[ i ] : bit_helper_type::ALL_UNSET);
block_type second = ((offset < soft_M ) ? second_buffer[ i ] : bit_helper_type::ALL_UNSET);
block_type mask = buffered_build_mask( first, second, offset * bit_helper_type::BITS_PER_BLOCK );
mask = m( first, second, mask );
second_buffer[ i ] = mask;
++i;
if( mask ) {
last_block = offset + 1;
}
}
// write to result sequence
memcpy( res + l, second_buffer, j * sizeof(block_type) );
l += j;
}
return last_block;
}
/**
* Unraveled the set bit decoding
*/
block_type buffered_build_mask( block_type first, block_type second, unsigned int offset ) {
block_type hets = first ^ second;
block_type mask = bit_helper_type::ALL_UNSET; // mask state from second strand
unsigned int het_buffer[ bit_helper_type::BITS_PER_BLOCK ]; // i.e. buffer_size = 64 * 4 = 256 bytes buffer
if( hets ) {
// decode set indices
unsigned int j = 0;
do {
het_buffer[ j ] = bit_walker_type::unset_next_index( hets );
++j;
} while( hets );
// evaluate positions at relative indices
unsigned int i = 0;
while( i < j ) {
unsigned int idx = het_buffer[ i ];
if( m_event_gen( offset + idx ) ) {
mask |= clotho::utility::bit_masks[ idx ];
}
++i;
}
}
return mask;
}
/**
*
* Initial technique for building a crossover mask
*
*
*/
block_type build_mask( block_type first, block_type second, unsigned int offset ) {
block_type hets = first ^ second;
block_type mask = bit_helper_type::ALL_UNSET; // mask state from second strand
if( hets ) {
do {
unsigned int idx = bit_walker_type::unset_next_index( hets );
if( m_event_gen( offset + idx ) ) {
mask |= clotho::utility::bit_masks[ idx ];
}
} while( hets );
}
return mask;
}
template < class Method >
void build_sequence( sequence_iterator s, genome_iterator start, genome_iterator end, const Method & m ) {
size_t j = 0;
genome_iterator sec_ptr = end;
while( start != end ) {
block_type first = *start++;
block_type second = *sec_ptr++;
block_type mask = build_mask( first, second, j );
*s++ = m(first, second, mask);
j += bit_helper_type::BITS_PER_BLOCK;
}
}
/**
*
* Uses soft max of both sequence
*
* Is write buffer beneficial?
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int buffered_write_build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int soft_N, sequence_iterator second, const unsigned int soft_M, const Method & m ) {
const unsigned int N = 32;
block_type _buffer[ N ]; // 256 byte buffer
const unsigned int soft_max = (( soft_N > soft_M )? soft_N : soft_M ); // soft maximum length
unsigned int last_block = 0;
unsigned int i = 0, j = 0;
while( j < soft_max ) {
block_type a = ((j < soft_N ) ? first[ j ] : bit_helper_type::ALL_UNSET);
block_type b = ((j < soft_M ) ? second[ j ] : bit_helper_type::ALL_UNSET);
block_type mask = build_mask( a, b, j * bit_helper_type::BITS_PER_BLOCK );
mask = m( a, b, mask );
_buffer[ i++ ] = mask;
++j;
if( mask ) {
last_block = j;
}
if( i >= N ) {
// buffer is full
memcpy( res, _buffer, N * sizeof(block_type) );
res += N;
i = 0;
}
}
// write final buffer
if( i ) {
memcpy( res, _buffer, i * sizeof( block_type ) );
}
return last_block;
}
/**
*
*
* @return soft max of result sequence
*/
template < class Method >
unsigned int build_sequence( sequence_iterator res, sequence_iterator first, const unsigned int N, sequence_iterator second, const unsigned int M, const Method & m ) {
const unsigned int W = (( N > M )? N : M );
unsigned int i = 0;
unsigned int last_block = 0;
while( i < W ) {
block_type a = first[ i ];
block_type b = second[ i ];
block_type mask = build_mask( a, b, i * bit_helper_type::BITS_PER_BLOCK );
mask = m(a, b, mask );
res[ i ] = mask;
++i;
if( mask ) {
last_block = i;
}
}
return last_block;
}
unsigned int copy_sequence( sequence_iterator s, sequence_iterator start, const size_t W ) {
memcpy( s, start, W * sizeof(block_type));
return W;
}
event_generator_type m_event_gen;
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_ROW_GROUPED_CROSSOVER_METHOD_HPP_
<|endoftext|>
|
<commit_before>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 15/09/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../Disassembler/Disassembler6502.hpp"
using namespace StaticAnalyser::Atari;
static void DeterminePagingFor2kCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment)
{
// if this is a 2kb cartridge then it's definitely either unpaged or a CommaVid
uint16_t entry_address, break_address;
entry_address = ((uint16_t)(segment.data[0x7fc] | (segment.data[0x7fd] << 8))) & 0x1fff;
break_address = ((uint16_t)(segment.data[0x7fe] | (segment.data[0x7ff] << 8))) & 0x1fff;
// a CommaVid start address needs to be outside of its RAM
if(entry_address < 0x1800 || break_address < 0x1800) return;
std::function<size_t(uint16_t address)> high_location_mapper = [](uint16_t address) {
address &= 0x1fff;
return (size_t)(address - 0x1800);
};
std::function<size_t(uint16_t address)> full_range_mapper = [](uint16_t address) {
if(!(address & 0x1000)) return (size_t)-1;
return (size_t)(address & 0x7ff);
};
StaticAnalyser::MOS6502::Disassembly high_location_disassembly =
StaticAnalyser::MOS6502::Disassemble(segment.data, high_location_mapper, {entry_address, break_address});
// StaticAnalyser::MOS6502::Disassembly full_range_disassembly =
// StaticAnalyser::MOS6502::Disassemble(segment.data, full_range_mapper, {entry_address, break_address});
// if there are no subroutines in the top 2kb of memory then this isn't a CommaVid
bool has_appropriate_subroutine_calls = false;
bool has_inappropriate_subroutine_calls = false;
for(uint16_t address : high_location_disassembly.internal_calls)
{
const uint16_t masked_address = address & 0x1fff;
has_appropriate_subroutine_calls |= (masked_address >= 0x1800);
has_inappropriate_subroutine_calls |= (masked_address < 0x1800);
}
// assumption here: a CommaVid will never branch into RAM. Possibly unsafe: if it won't then what's the RAM for?
if(!has_appropriate_subroutine_calls || has_inappropriate_subroutine_calls) return;
std::set<uint16_t> all_writes = high_location_disassembly.external_stores;
all_writes.insert(high_location_disassembly.external_modifies.begin(), high_location_disassembly.external_modifies.end());
// a CommaVid will use its RAM
if(all_writes.empty()) return;
bool has_appropriate_accesses = false;
for(uint16_t address : all_writes)
{
const uint16_t masked_address = address & 0x1fff;
if(masked_address >= 0x1400 && masked_address < 0x1800)
{
has_appropriate_accesses = true;
break;
}
}
// in desperation, accept any kind of store that looks likely to be intended for large amounts of memory
bool has_wide_area_store = false;
if(!has_appropriate_accesses)
{
for(std::map<uint16_t, StaticAnalyser::MOS6502::Instruction>::value_type &entry : high_location_disassembly.instructions_by_address)
{
if(entry.second.operation == StaticAnalyser::MOS6502::Instruction::STA)
{
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::Indirect;
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::IndexedIndirectX;
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::IndirectIndexedY;
}
}
}
// conclude that this is a CommaVid if it attempted to write something to the CommaVid RAM locations;
// caveat: false positives aren't likely to be problematic; a false positive is a 2KB ROM that always addresses
// itself so as to land in ROM even if mapped as a CommaVid and this code is on the fence as to whether it
// attempts to modify itself but it probably doesn't
if(has_appropriate_accesses || has_wide_area_store)
target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::CommaVid;
}
static void DeterminePagingFor8kCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment, const std::vector<StaticAnalyser::MOS6502::Disassembly> &disassemblies)
{
std::set<uint16_t> internal_accesses;
std::set<uint16_t> external_stores;
for(const StaticAnalyser::MOS6502::Disassembly &disassembly : disassemblies)
{
internal_accesses.insert(disassembly.internal_stores.begin(), disassembly.internal_stores.end());
internal_accesses.insert(disassembly.internal_modifies.begin(), disassembly.internal_modifies.end());
internal_accesses.insert(disassembly.internal_loads.begin(), disassembly.internal_loads.end());
external_stores.insert(disassembly.external_stores.begin(), disassembly.external_stores.end());
}
bool looks_like_atari = false;
bool looks_like_parker_bros = false;
for(uint16_t address : internal_accesses)
{
looks_like_atari |= ((address & 0x1fff) >= 0x1ff8) && ((address & 0x1fff) < 0x1ffa);
looks_like_parker_bros |= ((address & 0x1fff) >= 0x1fe0) && ((address & 0x1fff) < 0x1fe8);
}
if(looks_like_parker_bros) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::ParkerBros;
if(looks_like_atari) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::Atari8k;
}
static void DeterminePagingForCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment)
{
if(segment.data.size() == 2048)
{
DeterminePagingFor2kCartridge(target, segment);
return;
}
uint16_t entry_address, break_address;
entry_address = (uint16_t)(segment.data[segment.data.size() - 4] | (segment.data[segment.data.size() - 3] << 8));
break_address = (uint16_t)(segment.data[segment.data.size() - 2] | (segment.data[segment.data.size() - 1] << 8));
std::function<size_t(uint16_t address)> address_mapper = [](uint16_t address) {
if(!(address & 0x1000)) return (size_t)-1;
return (size_t)(address & 0xfff);
};
std::vector<StaticAnalyser::MOS6502::Disassembly> disassemblies;
std::set<uint16_t> internal_stores;
std::set<uint16_t> external_stores;
for(std::vector<uint8_t>::difference_type base = 0; base < segment.data.size(); base += 4096)
{
std::vector<uint8_t> sub_data(segment.data.begin() + base, segment.data.begin() + base + 4096);
disassemblies.push_back(StaticAnalyser::MOS6502::Disassemble(sub_data, address_mapper, {entry_address, break_address}));
internal_stores.insert(disassemblies.back().internal_stores.begin(), disassemblies.back().internal_stores.end());
external_stores.insert(disassemblies.back().external_stores.begin(), disassemblies.back().external_stores.end());
}
if(segment.data.size() == 8192)
{
DeterminePagingFor8kCartridge(target, segment, disassemblies);
}
// check for any sort of on-cartridge RAM; that might imply a Super Chip or else immediately tip the
// hat that this is a CBS RAM+ cartridge. Atari ROM images always have the same value stored over RAM
// regions.
bool has_superchip = true;
bool is_ram_plus = true;
for(size_t address = 0; address < 256; address++)
{
if(segment.data[address] != segment.data[0])
{
if(address < 128) has_superchip = false;
is_ram_plus = false;
}
}
target.atari.uses_superchip = has_superchip;
if(is_ram_plus) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::CBSRamPlus;
// check for a Tigervision or Tigervision-esque scheme
if(target.atari.paging_model == StaticAnalyser::Atari2600PagingModel::None)
{
bool looks_like_tigervision = external_stores.find(0x3f) != external_stores.end();
if(looks_like_tigervision) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::Tigervision;
}
}
void StaticAnalyser::Atari::AddTargets(
const std::list<std::shared_ptr<Storage::Disk::Disk>> &disks,
const std::list<std::shared_ptr<Storage::Tape::Tape>> &tapes,
const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges,
std::list<StaticAnalyser::Target> &destination)
{
// TODO: any sort of sanity checking at all; at the minute just trust the file type
// approximation already performed.
Target target;
target.machine = Target::Atari2600;
target.probability = 1.0;
target.disks = disks;
target.tapes = tapes;
target.cartridges = cartridges;
target.atari.paging_model = Atari2600PagingModel::None;
target.atari.uses_superchip = false;
// try to figure out the paging scheme
if(!cartridges.empty())
{
const std::list<Storage::Cartridge::Cartridge::Segment> &segments = cartridges.front()->get_segments();
if(segments.size() == 1)
{
const Storage::Cartridge::Cartridge::Segment &segment = segments.front();
DeterminePagingForCartridge(target, segment);
}
}
destination.push_back(target);
}
<commit_msg>Added an earlier exit.<commit_after>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 15/09/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../Disassembler/Disassembler6502.hpp"
using namespace StaticAnalyser::Atari;
static void DeterminePagingFor2kCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment)
{
// if this is a 2kb cartridge then it's definitely either unpaged or a CommaVid
uint16_t entry_address, break_address;
entry_address = ((uint16_t)(segment.data[0x7fc] | (segment.data[0x7fd] << 8))) & 0x1fff;
break_address = ((uint16_t)(segment.data[0x7fe] | (segment.data[0x7ff] << 8))) & 0x1fff;
// a CommaVid start address needs to be outside of its RAM
if(entry_address < 0x1800 || break_address < 0x1800) return;
std::function<size_t(uint16_t address)> high_location_mapper = [](uint16_t address) {
address &= 0x1fff;
return (size_t)(address - 0x1800);
};
std::function<size_t(uint16_t address)> full_range_mapper = [](uint16_t address) {
if(!(address & 0x1000)) return (size_t)-1;
return (size_t)(address & 0x7ff);
};
StaticAnalyser::MOS6502::Disassembly high_location_disassembly =
StaticAnalyser::MOS6502::Disassemble(segment.data, high_location_mapper, {entry_address, break_address});
// StaticAnalyser::MOS6502::Disassembly full_range_disassembly =
// StaticAnalyser::MOS6502::Disassemble(segment.data, full_range_mapper, {entry_address, break_address});
// if there are no subroutines in the top 2kb of memory then this isn't a CommaVid
bool has_appropriate_subroutine_calls = false;
bool has_inappropriate_subroutine_calls = false;
for(uint16_t address : high_location_disassembly.internal_calls)
{
const uint16_t masked_address = address & 0x1fff;
has_appropriate_subroutine_calls |= (masked_address >= 0x1800);
has_inappropriate_subroutine_calls |= (masked_address < 0x1800);
}
// assumption here: a CommaVid will never branch into RAM. Possibly unsafe: if it won't then what's the RAM for?
if(!has_appropriate_subroutine_calls || has_inappropriate_subroutine_calls) return;
std::set<uint16_t> all_writes = high_location_disassembly.external_stores;
all_writes.insert(high_location_disassembly.external_modifies.begin(), high_location_disassembly.external_modifies.end());
// a CommaVid will use its RAM
if(all_writes.empty()) return;
bool has_appropriate_accesses = false;
for(uint16_t address : all_writes)
{
const uint16_t masked_address = address & 0x1fff;
if(masked_address >= 0x1400 && masked_address < 0x1800)
{
has_appropriate_accesses = true;
break;
}
}
// in desperation, accept any kind of store that looks likely to be intended for large amounts of memory
bool has_wide_area_store = false;
if(!has_appropriate_accesses)
{
for(std::map<uint16_t, StaticAnalyser::MOS6502::Instruction>::value_type &entry : high_location_disassembly.instructions_by_address)
{
if(entry.second.operation == StaticAnalyser::MOS6502::Instruction::STA)
{
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::Indirect;
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::IndexedIndirectX;
has_wide_area_store |= entry.second.addressing_mode == StaticAnalyser::MOS6502::Instruction::IndirectIndexedY;
}
}
}
// conclude that this is a CommaVid if it attempted to write something to the CommaVid RAM locations;
// caveat: false positives aren't likely to be problematic; a false positive is a 2KB ROM that always addresses
// itself so as to land in ROM even if mapped as a CommaVid and this code is on the fence as to whether it
// attempts to modify itself but it probably doesn't
if(has_appropriate_accesses || has_wide_area_store)
target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::CommaVid;
}
static void DeterminePagingFor8kCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment, const std::vector<StaticAnalyser::MOS6502::Disassembly> &disassemblies)
{
std::set<uint16_t> internal_accesses;
std::set<uint16_t> external_stores;
for(const StaticAnalyser::MOS6502::Disassembly &disassembly : disassemblies)
{
internal_accesses.insert(disassembly.internal_stores.begin(), disassembly.internal_stores.end());
internal_accesses.insert(disassembly.internal_modifies.begin(), disassembly.internal_modifies.end());
internal_accesses.insert(disassembly.internal_loads.begin(), disassembly.internal_loads.end());
external_stores.insert(disassembly.external_stores.begin(), disassembly.external_stores.end());
}
bool looks_like_atari = false;
bool looks_like_parker_bros = false;
for(uint16_t address : internal_accesses)
{
looks_like_atari |= ((address & 0x1fff) >= 0x1ff8) && ((address & 0x1fff) < 0x1ffa);
looks_like_parker_bros |= ((address & 0x1fff) >= 0x1fe0) && ((address & 0x1fff) < 0x1fe8);
}
if(looks_like_parker_bros) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::ParkerBros;
if(looks_like_atari) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::Atari8k;
}
static void DeterminePagingForCartridge(StaticAnalyser::Target &target, const Storage::Cartridge::Cartridge::Segment &segment)
{
if(segment.data.size() == 2048)
{
DeterminePagingFor2kCartridge(target, segment);
return;
}
uint16_t entry_address, break_address;
entry_address = (uint16_t)(segment.data[segment.data.size() - 4] | (segment.data[segment.data.size() - 3] << 8));
break_address = (uint16_t)(segment.data[segment.data.size() - 2] | (segment.data[segment.data.size() - 1] << 8));
std::function<size_t(uint16_t address)> address_mapper = [](uint16_t address) {
if(!(address & 0x1000)) return (size_t)-1;
return (size_t)(address & 0xfff);
};
std::vector<StaticAnalyser::MOS6502::Disassembly> disassemblies;
std::set<uint16_t> internal_stores;
std::set<uint16_t> external_stores;
for(std::vector<uint8_t>::difference_type base = 0; base < segment.data.size(); base += 4096)
{
std::vector<uint8_t> sub_data(segment.data.begin() + base, segment.data.begin() + base + 4096);
disassemblies.push_back(StaticAnalyser::MOS6502::Disassemble(sub_data, address_mapper, {entry_address, break_address}));
internal_stores.insert(disassemblies.back().internal_stores.begin(), disassemblies.back().internal_stores.end());
external_stores.insert(disassemblies.back().external_stores.begin(), disassemblies.back().external_stores.end());
}
if(segment.data.size() == 8192)
{
DeterminePagingFor8kCartridge(target, segment, disassemblies);
}
// check for any sort of on-cartridge RAM; that might imply a Super Chip or else immediately tip the
// hat that this is a CBS RAM+ cartridge. Atari ROM images always have the same value stored over RAM
// regions.
bool has_superchip = true;
bool is_ram_plus = true;
for(size_t address = 0; address < 256; address++)
{
if(segment.data[address] != segment.data[0])
{
if(address < 128) has_superchip = false;
is_ram_plus = false;
if(!has_superchip && !is_ram_plus) break;
}
}
target.atari.uses_superchip = has_superchip;
if(is_ram_plus) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::CBSRamPlus;
// check for a Tigervision or Tigervision-esque scheme
if(target.atari.paging_model == StaticAnalyser::Atari2600PagingModel::None)
{
bool looks_like_tigervision = external_stores.find(0x3f) != external_stores.end();
if(looks_like_tigervision) target.atari.paging_model = StaticAnalyser::Atari2600PagingModel::Tigervision;
}
}
void StaticAnalyser::Atari::AddTargets(
const std::list<std::shared_ptr<Storage::Disk::Disk>> &disks,
const std::list<std::shared_ptr<Storage::Tape::Tape>> &tapes,
const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges,
std::list<StaticAnalyser::Target> &destination)
{
// TODO: any sort of sanity checking at all; at the minute just trust the file type
// approximation already performed.
Target target;
target.machine = Target::Atari2600;
target.probability = 1.0;
target.disks = disks;
target.tapes = tapes;
target.cartridges = cartridges;
target.atari.paging_model = Atari2600PagingModel::None;
target.atari.uses_superchip = false;
// try to figure out the paging scheme
if(!cartridges.empty())
{
const std::list<Storage::Cartridge::Cartridge::Segment> &segments = cartridges.front()->get_segments();
if(segments.size() == 1)
{
const Storage::Cartridge::Cartridge::Segment &segment = segments.front();
DeterminePagingForCartridge(target, segment);
}
}
destination.push_back(target);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/ui/accelerator_util.h"
#include <stdio.h>
#include <string>
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "ui/base/accelerators/accelerator.h"
namespace accelerator_util {
namespace {
// The sscanf is deprecated in Windows.
#if defined(OS_WIN)
#define SSCANF sscanf_s
#else
#define SSCANF sscanf
#endif
// Return key code of the char.
ui::KeyboardCode KeyboardCodeFromCharCode(char c, bool* shifted) {
*shifted = false;
switch (c) {
case 8: case 0x7F: return ui::VKEY_BACK;
case 9: return ui::VKEY_TAB;
case 0xD: case 3: return ui::VKEY_RETURN;
case 0x1B: return ui::VKEY_ESCAPE;
case ' ': return ui::VKEY_SPACE;
case 'a': return ui::VKEY_A;
case 'b': return ui::VKEY_B;
case 'c': return ui::VKEY_C;
case 'd': return ui::VKEY_D;
case 'e': return ui::VKEY_E;
case 'f': return ui::VKEY_F;
case 'g': return ui::VKEY_G;
case 'h': return ui::VKEY_H;
case 'i': return ui::VKEY_I;
case 'j': return ui::VKEY_J;
case 'k': return ui::VKEY_K;
case 'l': return ui::VKEY_L;
case 'm': return ui::VKEY_M;
case 'n': return ui::VKEY_N;
case 'o': return ui::VKEY_O;
case 'p': return ui::VKEY_P;
case 'q': return ui::VKEY_Q;
case 'r': return ui::VKEY_R;
case 's': return ui::VKEY_S;
case 't': return ui::VKEY_T;
case 'u': return ui::VKEY_U;
case 'v': return ui::VKEY_V;
case 'w': return ui::VKEY_W;
case 'x': return ui::VKEY_X;
case 'y': return ui::VKEY_Y;
case 'z': return ui::VKEY_Z;
case ')': *shifted = true; case '0': return ui::VKEY_0;
case '!': *shifted = true; case '1': return ui::VKEY_1;
case '@': *shifted = true; case '2': return ui::VKEY_2;
case '#': *shifted = true; case '3': return ui::VKEY_3;
case '$': *shifted = true; case '4': return ui::VKEY_4;
case '%': *shifted = true; case '5': return ui::VKEY_5;
case '^': *shifted = true; case '6': return ui::VKEY_6;
case '&': *shifted = true; case '7': return ui::VKEY_7;
case '*': *shifted = true; case '8': return ui::VKEY_8;
case '(': *shifted = true; case '9': return ui::VKEY_9;
case ':': *shifted = true; case ';': return ui::VKEY_OEM_1;
case '+': *shifted = true; case '=': return ui::VKEY_OEM_PLUS;
case '<': *shifted = true; case ',': return ui::VKEY_OEM_COMMA;
case '_': *shifted = true; case '-': return ui::VKEY_OEM_MINUS;
case '>': *shifted = true; case '.': return ui::VKEY_OEM_PERIOD;
case '?': *shifted = true; case '/': return ui::VKEY_OEM_2;
case '~': *shifted = true; case '`': return ui::VKEY_OEM_3;
case '{': *shifted = true; case '[': return ui::VKEY_OEM_4;
case '|': *shifted = true; case '\\': return ui::VKEY_OEM_5;
case '}': *shifted = true; case ']': return ui::VKEY_OEM_6;
case '"': *shifted = true; case '\'': return ui::VKEY_OEM_7;
default: return ui::VKEY_UNKNOWN;
}
}
} // namespace
bool StringToAccelerator(const std::string& description,
ui::Accelerator* accelerator) {
if (!IsStringASCII(description)) {
LOG(ERROR) << "The accelerator string can only contain ASCII characters";
return false;
}
std::string shortcut(StringToLowerASCII(description));
std::vector<std::string> tokens;
base::SplitString(shortcut, '+', &tokens);
if (tokens.size() < 2 || tokens.size() > 4) {
LOG(WARNING) << "Invalid accelerator description: " << description;
return false;
}
// Now, parse it into an accelerator.
int modifiers = ui::EF_NONE;
ui::KeyboardCode key = ui::VKEY_UNKNOWN;
for (size_t i = 0; i < tokens.size(); i++) {
// We use straight comparing instead of map because the accelerator tends
// to be correct and usually only uses few special tokens.
if (tokens[i].size() == 1) {
bool shifted = false;
key = KeyboardCodeFromCharCode(tokens[i][0], &shifted);
if (shifted)
modifiers |= ui::EF_SHIFT_DOWN;
} else if (tokens[i] == "ctrl") {
modifiers |= ui::EF_CONTROL_DOWN;
} else if (tokens[i] == "command") {
// The "Command" would be translated to "Ctrl" on platforms other than
// OS X.
#if defined(OS_MACOSX)
modifiers |= ui::EF_COMMAND_DOWN;
#else
modifiers |= ui::EF_CONTROL_DOWN;
#endif
} else if (tokens[i] == "alt") {
modifiers |= ui::EF_ALT_DOWN;
} else if (tokens[i] == "shift") {
modifiers |= ui::EF_SHIFT_DOWN;
} else if (tokens[i] == "tab") {
key = ui::VKEY_TAB;
} else if (tokens[i] == "space") {
key = ui::VKEY_SPACE;
} else if (tokens[i] == "backspace") {
key = ui::VKEY_BACK;
} else if (tokens[i] == "delete") {
key = ui::VKEY_DELETE;
} else if (tokens[i] == "enter" || tokens[i] == "return") {
key = ui::VKEY_RETURN;
} else if (tokens[i] == "up") {
key = ui::VKEY_UP;
} else if (tokens[i] == "down") {
key = ui::VKEY_DOWN;
} else if (tokens[i] == "left") {
key = ui::VKEY_LEFT;
} else if (tokens[i] == "right") {
key = ui::VKEY_RIGHT;
} else if (tokens[i] == "home") {
key = ui::VKEY_HOME;
} else if (tokens[i] == "end") {
key = ui::VKEY_END;
} else if (tokens[i] == "pagedown") {
key = ui::VKEY_PRIOR;
} else if (tokens[i] == "pageup") {
key = ui::VKEY_NEXT;
} else if (tokens[i] == "esc") {
key = ui::VKEY_ESCAPE;
} else if (tokens[i] == "volumemute") {
key = ui::VKEY_VOLUME_MUTE;
} else if (tokens[i] == "volumeup") {
key = ui::VKEY_VOLUME_UP;
} else if (tokens[i] == "volumedown") {
key = ui::VKEY_VOLUME_DOWN;
} else if (tokens[i] == "medianexttrack") {
key = ui::VKEY_MEDIA_NEXT_TRACK;
} else if (tokens[i] == "mediaprevioustrack") {
key = ui::VKEY_MEDIA_PREV_TRACK;
} else if (tokens[i] == "mediastop") {
key = ui::VKEY_MEDIA_STOP;
} else if (tokens[i] == "mediaplaypause") {
key = ui::VKEY_MEDIA_PLAY_PAUSE;
} else if (tokens[i].size() > 1 && tokens[i][0] == 'f') {
// F1 - F24.
int n;
if (SSCANF(tokens[i].c_str(), "f%d", &n) == 1 && n > 0 && n < 25) {
key = static_cast<ui::KeyboardCode>(ui::VKEY_F1 + n - 1);
} else {
LOG(WARNING) << tokens[i] << "is not available on keyboard";
return false;
}
} else {
LOG(WARNING) << "Invalid accelerator token: " << tokens[i];
return false;
}
}
if (key == ui::VKEY_UNKNOWN) {
LOG(WARNING) << "The accelerator doesn't contain a valid key";
return false;
}
*accelerator = ui::Accelerator(key, modifiers);
SetPlatformAccelerator(accelerator);
return true;
}
} // namespace accelerator_util
<commit_msg>Do not use sscanf.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/ui/accelerator_util.h"
#include <stdio.h>
#include <string>
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "ui/base/accelerators/accelerator.h"
namespace accelerator_util {
namespace {
// Return key code of the char.
ui::KeyboardCode KeyboardCodeFromCharCode(char c, bool* shifted) {
*shifted = false;
switch (c) {
case 8: case 0x7F: return ui::VKEY_BACK;
case 9: return ui::VKEY_TAB;
case 0xD: case 3: return ui::VKEY_RETURN;
case 0x1B: return ui::VKEY_ESCAPE;
case ' ': return ui::VKEY_SPACE;
case 'a': return ui::VKEY_A;
case 'b': return ui::VKEY_B;
case 'c': return ui::VKEY_C;
case 'd': return ui::VKEY_D;
case 'e': return ui::VKEY_E;
case 'f': return ui::VKEY_F;
case 'g': return ui::VKEY_G;
case 'h': return ui::VKEY_H;
case 'i': return ui::VKEY_I;
case 'j': return ui::VKEY_J;
case 'k': return ui::VKEY_K;
case 'l': return ui::VKEY_L;
case 'm': return ui::VKEY_M;
case 'n': return ui::VKEY_N;
case 'o': return ui::VKEY_O;
case 'p': return ui::VKEY_P;
case 'q': return ui::VKEY_Q;
case 'r': return ui::VKEY_R;
case 's': return ui::VKEY_S;
case 't': return ui::VKEY_T;
case 'u': return ui::VKEY_U;
case 'v': return ui::VKEY_V;
case 'w': return ui::VKEY_W;
case 'x': return ui::VKEY_X;
case 'y': return ui::VKEY_Y;
case 'z': return ui::VKEY_Z;
case ')': *shifted = true; case '0': return ui::VKEY_0;
case '!': *shifted = true; case '1': return ui::VKEY_1;
case '@': *shifted = true; case '2': return ui::VKEY_2;
case '#': *shifted = true; case '3': return ui::VKEY_3;
case '$': *shifted = true; case '4': return ui::VKEY_4;
case '%': *shifted = true; case '5': return ui::VKEY_5;
case '^': *shifted = true; case '6': return ui::VKEY_6;
case '&': *shifted = true; case '7': return ui::VKEY_7;
case '*': *shifted = true; case '8': return ui::VKEY_8;
case '(': *shifted = true; case '9': return ui::VKEY_9;
case ':': *shifted = true; case ';': return ui::VKEY_OEM_1;
case '+': *shifted = true; case '=': return ui::VKEY_OEM_PLUS;
case '<': *shifted = true; case ',': return ui::VKEY_OEM_COMMA;
case '_': *shifted = true; case '-': return ui::VKEY_OEM_MINUS;
case '>': *shifted = true; case '.': return ui::VKEY_OEM_PERIOD;
case '?': *shifted = true; case '/': return ui::VKEY_OEM_2;
case '~': *shifted = true; case '`': return ui::VKEY_OEM_3;
case '{': *shifted = true; case '[': return ui::VKEY_OEM_4;
case '|': *shifted = true; case '\\': return ui::VKEY_OEM_5;
case '}': *shifted = true; case ']': return ui::VKEY_OEM_6;
case '"': *shifted = true; case '\'': return ui::VKEY_OEM_7;
default: return ui::VKEY_UNKNOWN;
}
}
} // namespace
bool StringToAccelerator(const std::string& description,
ui::Accelerator* accelerator) {
if (!IsStringASCII(description)) {
LOG(ERROR) << "The accelerator string can only contain ASCII characters";
return false;
}
std::string shortcut(StringToLowerASCII(description));
std::vector<std::string> tokens;
base::SplitString(shortcut, '+', &tokens);
if (tokens.size() < 2 || tokens.size() > 4) {
LOG(WARNING) << "Invalid accelerator description: " << description;
return false;
}
// Now, parse it into an accelerator.
int modifiers = ui::EF_NONE;
ui::KeyboardCode key = ui::VKEY_UNKNOWN;
for (size_t i = 0; i < tokens.size(); i++) {
// We use straight comparing instead of map because the accelerator tends
// to be correct and usually only uses few special tokens.
if (tokens[i].size() == 1) {
bool shifted = false;
key = KeyboardCodeFromCharCode(tokens[i][0], &shifted);
if (shifted)
modifiers |= ui::EF_SHIFT_DOWN;
} else if (tokens[i] == "ctrl") {
modifiers |= ui::EF_CONTROL_DOWN;
} else if (tokens[i] == "command") {
// The "Command" would be translated to "Ctrl" on platforms other than
// OS X.
#if defined(OS_MACOSX)
modifiers |= ui::EF_COMMAND_DOWN;
#else
modifiers |= ui::EF_CONTROL_DOWN;
#endif
} else if (tokens[i] == "alt") {
modifiers |= ui::EF_ALT_DOWN;
} else if (tokens[i] == "shift") {
modifiers |= ui::EF_SHIFT_DOWN;
} else if (tokens[i] == "tab") {
key = ui::VKEY_TAB;
} else if (tokens[i] == "space") {
key = ui::VKEY_SPACE;
} else if (tokens[i] == "backspace") {
key = ui::VKEY_BACK;
} else if (tokens[i] == "delete") {
key = ui::VKEY_DELETE;
} else if (tokens[i] == "enter" || tokens[i] == "return") {
key = ui::VKEY_RETURN;
} else if (tokens[i] == "up") {
key = ui::VKEY_UP;
} else if (tokens[i] == "down") {
key = ui::VKEY_DOWN;
} else if (tokens[i] == "left") {
key = ui::VKEY_LEFT;
} else if (tokens[i] == "right") {
key = ui::VKEY_RIGHT;
} else if (tokens[i] == "home") {
key = ui::VKEY_HOME;
} else if (tokens[i] == "end") {
key = ui::VKEY_END;
} else if (tokens[i] == "pagedown") {
key = ui::VKEY_PRIOR;
} else if (tokens[i] == "pageup") {
key = ui::VKEY_NEXT;
} else if (tokens[i] == "esc") {
key = ui::VKEY_ESCAPE;
} else if (tokens[i] == "volumemute") {
key = ui::VKEY_VOLUME_MUTE;
} else if (tokens[i] == "volumeup") {
key = ui::VKEY_VOLUME_UP;
} else if (tokens[i] == "volumedown") {
key = ui::VKEY_VOLUME_DOWN;
} else if (tokens[i] == "medianexttrack") {
key = ui::VKEY_MEDIA_NEXT_TRACK;
} else if (tokens[i] == "mediaprevioustrack") {
key = ui::VKEY_MEDIA_PREV_TRACK;
} else if (tokens[i] == "mediastop") {
key = ui::VKEY_MEDIA_STOP;
} else if (tokens[i] == "mediaplaypause") {
key = ui::VKEY_MEDIA_PLAY_PAUSE;
} else if (tokens[i].size() > 1 && tokens[i][0] == 'f') {
// F1 - F24.
int n;
if (base::StringToInt(tokens[i].c_str() + 1, &n)) {
key = static_cast<ui::KeyboardCode>(ui::VKEY_F1 + n - 1);
} else {
LOG(WARNING) << tokens[i] << "is not available on keyboard";
return false;
}
} else {
LOG(WARNING) << "Invalid accelerator token: " << tokens[i];
return false;
}
}
if (key == ui::VKEY_UNKNOWN) {
LOG(WARNING) << "The accelerator doesn't contain a valid key";
return false;
}
*accelerator = ui::Accelerator(key, modifiers);
SetPlatformAccelerator(accelerator);
return true;
}
} // namespace accelerator_util
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ViewShellHint.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 13:27:19 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_HINT_HXX
#define SD_VIEW_SHELL_HINT_HXX
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
namespace sd {
/** Local derivation of the SfxHint class that defines some hint ids that
are used by the ViewShell class and its decendants.
*/
class ViewShellHint
: public SfxHint
{
public:
enum HintId {
// Indicate that a page resize is about to begin.
HINT_PAGE_RESIZE_START,
// Indicate that a page resize has been completed.
HINT_PAGE_RESIZE_END,
// Indicate that an edit mode change is about to begin.
HINT_CHANGE_EDIT_MODE_START,
// Indicate that an edit mode change has been completed.
HINT_CHANGE_EDIT_MODE_END
};
TYPEINFO();
ViewShellHint (HintId nHintId);
HintId GetHintId (void) const;
private:
HintId meHintId;
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impress37 (1.2.160); FILE MERGED 2005/03/04 14:55:54 af 1.2.160.1: #i43382# Added two new hint ids.<commit_after>/*************************************************************************
*
* $RCSfile: ViewShellHint.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-23 13:57:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_VIEW_SHELL_HINT_HXX
#define SD_VIEW_SHELL_HINT_HXX
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
namespace sd {
/** Local derivation of the SfxHint class that defines some hint ids that
are used by the ViewShell class and its decendants.
*/
class ViewShellHint
: public SfxHint
{
public:
enum HintId {
// Indicate that a page resize is about to begin.
HINT_PAGE_RESIZE_START,
// Indicate that a page resize has been completed.
HINT_PAGE_RESIZE_END,
// Indicate that an edit mode change is about to begin.
HINT_CHANGE_EDIT_MODE_START,
// Indicate that an edit mode change has been completed.
HINT_CHANGE_EDIT_MODE_END,
HINT_COMPLEX_MODEL_CHANGE_START,
HINT_COMPLEX_MODEL_CHANGE_END
};
TYPEINFO();
ViewShellHint (HintId nHintId);
HintId GetHintId (void) const;
private:
HintId meHintId;
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before><commit_msg>We shouldn't use BIDI_DEFAULT_(RTL|LTR) if we know the directionality of the page, because we won't like the result if string is mixed bidi (it may mark string as RTL instead of LTR if it starts with strong RTL characters, even if the global direction is LTR).<commit_after><|endoftext|>
|
<commit_before>#include <Core/Geometry/IndexedGeometry.hpp>
#include <iterator>
namespace Ra {
namespace Core {
namespace Geometry {
MultiIndexedGeometry::MultiIndexedGeometry( const MultiIndexedGeometry& other ) :
AttribArrayGeometry( other ) {
deepCopy( other );
}
MultiIndexedGeometry::MultiIndexedGeometry( MultiIndexedGeometry&& other ) :
AttribArrayGeometry( std::move( other ) ), m_indices( std::move( other.m_indices ) ) {}
MultiIndexedGeometry::MultiIndexedGeometry( const AttribArrayGeometry& other ) :
AttribArrayGeometry( other ) {}
MultiIndexedGeometry::MultiIndexedGeometry( AttribArrayGeometry&& other ) :
AttribArrayGeometry( std::move( other ) ) {}
MultiIndexedGeometry& MultiIndexedGeometry::operator=( const MultiIndexedGeometry& other ) {
AttribArrayGeometry::operator=( other );
deepCopy( other );
notify();
invalidateAabb();
return *this;
}
MultiIndexedGeometry& MultiIndexedGeometry::operator=( MultiIndexedGeometry&& other ) {
AttribArrayGeometry::operator=( std::move( other ) );
m_indices = std::move( other.m_indices );
notify();
invalidateAabb();
return *this;
}
void MultiIndexedGeometry::clear() {
AttribArrayGeometry::clear();
deepClear();
notify();
invalidateAabb();
}
void MultiIndexedGeometry::copy( const MultiIndexedGeometry& other ) {
AttribArrayGeometry::copyBaseGeometry( other );
deepCopy( other );
notify();
invalidateAabb();
}
/// \todo Implement MultiIndexedGeometry::checkConsistency
void MultiIndexedGeometry::checkConsistency() const {
#ifdef CORE_DEBUG
#endif
}
bool
/// \todo Implement MultiIndexedGeometry::append
MultiIndexedGeometry::append( const MultiIndexedGeometry& other ) {
bool isCopyComplete = true;
for ( const auto& [key, value] : m_indices )
{
auto it = other.m_indices.find( key );
if ( !( it == other.m_indices.end() && value.second->append( *( it->second.second ) ) ) )
isCopyComplete = false;
}
notify();
invalidateAabb();
return isCopyComplete;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
bool MultiIndexedGeometry::containsLayer( const LayerSemantic& semanticName ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) return true;
}
return false;
}
bool MultiIndexedGeometry::containsLayer( const LayerSemanticCollection& semantics ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
size_t MultiIndexedGeometry::countLayers( const LayerSemantic& semanticName ) const {
size_t c = 0;
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) ++c;
}
return c;
}
size_t MultiIndexedGeometry::countLayers( const LayerSemanticCollection& semantics ) const {
size_t c = 0;
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) ++c;
}
return c;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::pair<MultiIndexedGeometry::LayerKeyType, const GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrence( const LayerSemantic& semanticName ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) return {key, *( value.second )};
}
throw std::out_of_range( "Layer entry not found" );
}
std::pair<MultiIndexedGeometry::LayerKeyType, const GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrence( const LayerSemanticCollection& semantics ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) return {key, *( value.second )};
}
throw std::out_of_range( "Layer entry not found" );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::pair<MultiIndexedGeometry::LayerKeyType, GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrenceWithLock( const LayerSemantic& semanticName ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() )
{
CORE_ASSERT( !value.first, "try to get already locked layer" );
value.first = true;
return {key, *( value.second )};
}
}
throw std::out_of_range( "Layer entry not found" );
}
std::pair<MultiIndexedGeometry::LayerKeyType, GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrenceWithLock( const LayerSemanticCollection& semantics ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first == semantics )
{
CORE_ASSERT( !value.first, "try to get already locked layer" );
value.first = true;
return {key, *( value.second )};
}
}
throw std::out_of_range( "Layer entry not found" );
}
GeometryIndexLayerBase& MultiIndexedGeometry::getLayerWithLock( const LayerKeyType& layerKey ) {
auto& p = m_indices.at( layerKey );
CORE_ASSERT( !p.first, "try to get already locked layer" );
p.first = true;
return *( p.second );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void MultiIndexedGeometry::unlockFirstLayerOccurrence( const LayerSemantic& semanticName ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() )
{
CORE_ASSERT( value.first, "try to release unlocked layer" );
value.first = false;
notify();
return;
}
}
throw std::out_of_range( "Layer entry not found" );
}
void MultiIndexedGeometry::unlockFirstLayerOccurrence( const LayerSemanticCollection& semantics ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first == semantics )
{
CORE_ASSERT( value.first, "try to release unlocked layer" );
value.first = false;
notify();
return;
}
}
throw std::out_of_range( "Layer entry not found" );
}
void MultiIndexedGeometry::unlockLayer( const LayerKeyType& layerKey ) {
auto& p = m_indices.at( layerKey );
CORE_ASSERT( p.first, "try to release unlocked layer" );
p.first = true;
notify();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
bool MultiIndexedGeometry::addLayer( std::unique_ptr<GeometryIndexLayerBase>&& layer,
const std::string& layerName ) {
LayerKeyType key {layer->semantics(), layerName};
if ( m_indices.find( key ) != m_indices.end() ) return false;
m_indices.insert( {key, std::make_pair( false, layer.release() )} );
notify();
return true;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void MultiIndexedGeometry::deepCopy( const MultiIndexedGeometry& other ) {
m_indices = other.m_indices;
for ( auto& el : m_indices )
el.second.second = el.second.second->duplicate(); // replace copied entries by duplicates
}
void MultiIndexedGeometry::deepClear() {
for ( auto& el : m_indices )
delete el.second.second;
m_indices.clear();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::size_t MultiIndexedGeometry::KeyHash::operator()( const LayerKeyType& k ) const {
// Mix semantic collection into a single identifier string
std::ostringstream stream;
std::copy( k.first.begin(), k.first.end(), std::ostream_iterator<std::string>( stream, "" ) );
std::string result = stream.str();
std::sort( result.begin(), result.end() );
// Combine with layer name hash
return std::hash<std::string> {}( result ) ^ ( std::hash<std::string> {}( k.second ) << 1 );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void PointCloudIndexLayer::linearIndices( const AttribArrayGeometry& attr ) {
auto nbVert = attr.vertices().size();
collection().resize( nbVert );
collection().getMap() = IndexContainerType::Matrix::LinSpaced( nbVert, 0, nbVert - 1 );
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<commit_msg>[core] fix from code review: invalidate aabb before notify<commit_after>#include <Core/Geometry/IndexedGeometry.hpp>
#include <iterator>
namespace Ra {
namespace Core {
namespace Geometry {
MultiIndexedGeometry::MultiIndexedGeometry( const MultiIndexedGeometry& other ) :
AttribArrayGeometry( other ) {
deepCopy( other );
}
MultiIndexedGeometry::MultiIndexedGeometry( MultiIndexedGeometry&& other ) :
AttribArrayGeometry( std::move( other ) ), m_indices( std::move( other.m_indices ) ) {}
MultiIndexedGeometry::MultiIndexedGeometry( const AttribArrayGeometry& other ) :
AttribArrayGeometry( other ) {}
MultiIndexedGeometry::MultiIndexedGeometry( AttribArrayGeometry&& other ) :
AttribArrayGeometry( std::move( other ) ) {}
MultiIndexedGeometry& MultiIndexedGeometry::operator=( const MultiIndexedGeometry& other ) {
invalidateAabb();
AttribArrayGeometry::operator=( other );
deepCopy( other );
notify();
return *this;
}
MultiIndexedGeometry& MultiIndexedGeometry::operator=( MultiIndexedGeometry&& other ) {
invalidateAabb();
AttribArrayGeometry::operator=( std::move( other ) );
m_indices = std::move( other.m_indices );
notify();
return *this;
}
void MultiIndexedGeometry::clear() {
invalidateAabb();
AttribArrayGeometry::clear();
deepClear();
notify();
}
void MultiIndexedGeometry::copy( const MultiIndexedGeometry& other ) {
invalidateAabb();
AttribArrayGeometry::copyBaseGeometry( other );
deepCopy( other );
notify();
}
/// \todo Implement MultiIndexedGeometry::checkConsistency
void MultiIndexedGeometry::checkConsistency() const {
#ifdef CORE_DEBUG
#endif
}
bool
/// \todo Implement MultiIndexedGeometry::append
MultiIndexedGeometry::append( const MultiIndexedGeometry& other ) {
invalidateAabb();
bool isCopyComplete = true;
for ( const auto& [key, value] : m_indices )
{
auto it = other.m_indices.find( key );
if ( !( it == other.m_indices.end() && value.second->append( *( it->second.second ) ) ) )
isCopyComplete = false;
}
notify();
return isCopyComplete;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
bool MultiIndexedGeometry::containsLayer( const LayerSemantic& semanticName ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) return true;
}
return false;
}
bool MultiIndexedGeometry::containsLayer( const LayerSemanticCollection& semantics ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
size_t MultiIndexedGeometry::countLayers( const LayerSemantic& semanticName ) const {
size_t c = 0;
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) ++c;
}
return c;
}
size_t MultiIndexedGeometry::countLayers( const LayerSemanticCollection& semantics ) const {
size_t c = 0;
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) ++c;
}
return c;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::pair<MultiIndexedGeometry::LayerKeyType, const GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrence( const LayerSemantic& semanticName ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() ) return {key, *( value.second )};
}
throw std::out_of_range( "Layer entry not found" );
}
std::pair<MultiIndexedGeometry::LayerKeyType, const GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrence( const LayerSemanticCollection& semantics ) const {
for ( const auto& [key, value] : m_indices )
{
if ( key.first == semantics ) return {key, *( value.second )};
}
throw std::out_of_range( "Layer entry not found" );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::pair<MultiIndexedGeometry::LayerKeyType, GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrenceWithLock( const LayerSemantic& semanticName ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() )
{
CORE_ASSERT( !value.first, "try to get already locked layer" );
value.first = true;
return {key, *( value.second )};
}
}
throw std::out_of_range( "Layer entry not found" );
}
std::pair<MultiIndexedGeometry::LayerKeyType, GeometryIndexLayerBase&>
MultiIndexedGeometry::getFirstLayerOccurrenceWithLock( const LayerSemanticCollection& semantics ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first == semantics )
{
CORE_ASSERT( !value.first, "try to get already locked layer" );
value.first = true;
return {key, *( value.second )};
}
}
throw std::out_of_range( "Layer entry not found" );
}
GeometryIndexLayerBase& MultiIndexedGeometry::getLayerWithLock( const LayerKeyType& layerKey ) {
auto& p = m_indices.at( layerKey );
CORE_ASSERT( !p.first, "try to get already locked layer" );
p.first = true;
return *( p.second );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void MultiIndexedGeometry::unlockFirstLayerOccurrence( const LayerSemantic& semanticName ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first.find( semanticName ) != key.first.end() )
{
CORE_ASSERT( value.first, "try to release unlocked layer" );
value.first = false;
notify();
return;
}
}
throw std::out_of_range( "Layer entry not found" );
}
void MultiIndexedGeometry::unlockFirstLayerOccurrence( const LayerSemanticCollection& semantics ) {
for ( auto& [key, value] : m_indices )
{
if ( key.first == semantics )
{
CORE_ASSERT( value.first, "try to release unlocked layer" );
value.first = false;
notify();
return;
}
}
throw std::out_of_range( "Layer entry not found" );
}
void MultiIndexedGeometry::unlockLayer( const LayerKeyType& layerKey ) {
auto& p = m_indices.at( layerKey );
CORE_ASSERT( p.first, "try to release unlocked layer" );
p.first = true;
notify();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
bool MultiIndexedGeometry::addLayer( std::unique_ptr<GeometryIndexLayerBase>&& layer,
const std::string& layerName ) {
LayerKeyType key {layer->semantics(), layerName};
if ( m_indices.find( key ) != m_indices.end() ) return false;
m_indices.insert( {key, std::make_pair( false, layer.release() )} );
notify();
return true;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void MultiIndexedGeometry::deepCopy( const MultiIndexedGeometry& other ) {
m_indices = other.m_indices;
for ( auto& el : m_indices )
el.second.second = el.second.second->duplicate(); // replace copied entries by duplicates
}
void MultiIndexedGeometry::deepClear() {
for ( auto& el : m_indices )
delete el.second.second;
m_indices.clear();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
std::size_t MultiIndexedGeometry::KeyHash::operator()( const LayerKeyType& k ) const {
// Mix semantic collection into a single identifier string
std::ostringstream stream;
std::copy( k.first.begin(), k.first.end(), std::ostream_iterator<std::string>( stream, "" ) );
std::string result = stream.str();
std::sort( result.begin(), result.end() );
// Combine with layer name hash
return std::hash<std::string> {}( result ) ^ ( std::hash<std::string> {}( k.second ) << 1 );
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
void PointCloudIndexLayer::linearIndices( const AttribArrayGeometry& attr ) {
auto nbVert = attr.vertices().size();
collection().resize( nbVert );
collection().getMap() = IndexContainerType::Matrix::LinSpaced( nbVert, 0, nbVert - 1 );
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<|endoftext|>
|
<commit_before>/*##############################################################################
Copyright (C) 2011 HPCC Systems.
All rights reserved. This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## */
#ifndef _THACTIVITYMASTER_HPP
#define _THACTIVITYMASTER_HPP
#ifdef _WIN32
#ifdef ACTIVITYMASTERS_EXPORTS
#define actmaster_decl __declspec(dllexport)
#else
#define actmaster_decl __declspec(dllimport)
#endif
#else
#define actmaster_decl
#endif
enum masterEvents { ev_unknown, ev_done };
#include "thmfilemanager.hpp"
interface IGetSlaveData : extends IInterface
{
virtual bool getData(unsigned slave, unsigned part, MemoryBuffer &mb) = 0;
};
struct CSlaveMap : public IArrayOf<IPartDescriptor>, public CInterface
{
};
class CSlavePartMapping : public CSimpleInterface, implements IInterface
{
CIArrayOf<CSlaveMap> maps;
UnsignedArray partToNode;
unsigned fileWidth;
bool local;
StringAttr logicalName;
Linked<IFileDescriptor> fileDesc;
Linked<IUserDescriptor> userDesc;
public:
IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
CSlavePartMapping(const char *logicalName, IFileDescriptor &fileDesc, IUserDescriptor *userDesc, IGroup &localGroup, bool local, bool index, IHash *hash, IDistributedSuperFile *super);
unsigned queryNode(unsigned part)
{
if (part > partToNode.ordinality()) return NotFound;
return partToNode.item(part);
}
unsigned queryParts() { return partToNode.ordinality(); }
unsigned queryNumMaps() { return maps.ordinality(); }
unsigned queryMapWidth(unsigned map) { return maps.isItem(map)?maps.item(map).ordinality():0; }
void serializeFileOffsetMap(MemoryBuffer &mb);
void getParts(unsigned i, IArrayOf<IPartDescriptor> &parts);
void serializeMap(unsigned map, MemoryBuffer &mb, IGetSlaveData *extra=NULL);
static void serializeNullMap(MemoryBuffer &mb);
static void serializeNullOffsetMap(MemoryBuffer &mb);
};
CSlavePartMapping *getFileSlaveMaps(const char *logicalName, IFileDescriptor &file, IUserDescriptor *userDesc, IGroup &localGroup, bool local=false, bool index=false, IHash *hash=NULL, IDistributedSuperFile *super=NULL);
void checkSuperFileOwnership(IDistributedFile &file);
actmaster_decl void loadMasters();
#endif
<commit_msg>Fix gh-1002 - csv in child query issue<commit_after>/*##############################################################################
Copyright (C) 2011 HPCC Systems.
All rights reserved. This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
############################################################################## */
#ifndef _THACTIVITYMASTER_HPP
#define _THACTIVITYMASTER_HPP
#ifdef _WIN32
#ifdef ACTIVITYMASTERS_EXPORTS
#define actmaster_decl __declspec(dllexport)
#else
#define actmaster_decl __declspec(dllimport)
#endif
#else
#define actmaster_decl
#endif
enum masterEvents { ev_unknown, ev_done };
#include "thmfilemanager.hpp"
interface IGetSlaveData : extends IInterface
{
virtual bool getData(unsigned slave, unsigned part, MemoryBuffer &mb) = 0;
};
struct CSlaveMap : public IArrayOf<IPartDescriptor>, public CInterface
{
};
class CSlavePartMapping : public CSimpleInterface, implements IInterface
{
CIArrayOf<CSlaveMap> maps;
UnsignedArray partToNode;
unsigned fileWidth;
bool local;
StringAttr logicalName;
Linked<IFileDescriptor> fileDesc;
Linked<IUserDescriptor> userDesc;
public:
IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
CSlavePartMapping(const char *logicalName, IFileDescriptor &fileDesc, IUserDescriptor *userDesc, IGroup &localGroup, bool local, bool index, IHash *hash, IDistributedSuperFile *super);
unsigned queryNode(unsigned part)
{
if (part > partToNode.ordinality()) return NotFound;
return partToNode.item(part);
}
unsigned queryParts() { return partToNode.ordinality(); }
unsigned queryNumMaps() { return maps.ordinality(); }
unsigned queryMapWidth(unsigned map)
{
if (local)
map = 0;
if (!maps.isItem(map))
return 0;
return maps.item(map).ordinality();
}
void serializeFileOffsetMap(MemoryBuffer &mb);
void getParts(unsigned i, IArrayOf<IPartDescriptor> &parts);
void serializeMap(unsigned map, MemoryBuffer &mb, IGetSlaveData *extra=NULL);
static void serializeNullMap(MemoryBuffer &mb);
static void serializeNullOffsetMap(MemoryBuffer &mb);
};
CSlavePartMapping *getFileSlaveMaps(const char *logicalName, IFileDescriptor &file, IUserDescriptor *userDesc, IGroup &localGroup, bool local=false, bool index=false, IHash *hash=NULL, IDistributedSuperFile *super=NULL);
void checkSuperFileOwnership(IDistributedFile &file);
actmaster_decl void loadMasters();
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/osr/osr_output_device.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "ui/gfx/skia_util.h"
namespace atom {
OffScreenOutputDevice::OffScreenOutputDevice(bool transparent,
const OnPaintCallback& callback)
: transparent_(transparent),
callback_(callback),
active_(false) {
DCHECK(!callback_.is_null());
}
OffScreenOutputDevice::~OffScreenOutputDevice() {
}
void OffScreenOutputDevice::Resize(
const gfx::Size& pixel_size, float scale_factor) {
scale_factor_ = scale_factor;
if (viewport_pixel_size_ == pixel_size) return;
viewport_pixel_size_ = pixel_size;
canvas_.reset();
bitmap_.reset(new SkBitmap);
bitmap_->allocN32Pixels(viewport_pixel_size_.width(),
viewport_pixel_size_.height(),
!transparent_);
if (bitmap_->drawsNothing()) {
NOTREACHED();
bitmap_.reset();
return;
}
if (transparent_)
bitmap_->eraseARGB(0, 0, 0, 0);
canvas_.reset(new SkCanvas(*bitmap_));
}
SkCanvas* OffScreenOutputDevice::BeginPaint(const gfx::Rect& damage_rect) {
DCHECK(canvas_.get());
DCHECK(bitmap_.get());
damage_rect_ = damage_rect;
return canvas_.get();
}
void OffScreenOutputDevice::EndPaint() {
DCHECK(canvas_.get());
DCHECK(bitmap_.get());
if (!bitmap_.get()) return;
cc::SoftwareOutputDevice::EndPaint();
if (active_)
OnPaint(damage_rect_);
}
void OffScreenOutputDevice::SetActive(bool active) {
if (active == active_)
return;
active_ = active;
if (active_)
OnPaint(gfx::Rect(viewport_pixel_size_));
}
void OffScreenOutputDevice::OnPaint(const gfx::Rect& damage_rect) {
gfx::Rect rect = damage_rect;
rect.Intersect(gfx::Rect(viewport_pixel_size_));
if (rect.IsEmpty())
return;
SkAutoLockPixels bitmap_pixels_lock(*bitmap_);
callback_.Run(rect, *bitmap_);
}
} // namespace atom
<commit_msg>Update OffScreenOutputDevice<commit_after>// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/osr/osr_output_device.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "ui/gfx/skia_util.h"
namespace atom {
OffScreenOutputDevice::OffScreenOutputDevice(bool transparent,
const OnPaintCallback& callback)
: transparent_(transparent),
callback_(callback),
active_(false) {
DCHECK(!callback_.is_null());
}
OffScreenOutputDevice::~OffScreenOutputDevice() {
}
void OffScreenOutputDevice::Resize(
const gfx::Size& pixel_size, float scale_factor) {
if (viewport_pixel_size_ == pixel_size) return;
viewport_pixel_size_ = pixel_size;
canvas_.reset();
bitmap_.reset(new SkBitmap);
bitmap_->allocN32Pixels(viewport_pixel_size_.width(),
viewport_pixel_size_.height(),
!transparent_);
if (bitmap_->drawsNothing()) {
NOTREACHED();
bitmap_.reset();
return;
}
if (transparent_)
bitmap_->eraseARGB(0, 0, 0, 0);
canvas_.reset(new SkCanvas(*bitmap_));
}
SkCanvas* OffScreenOutputDevice::BeginPaint(const gfx::Rect& damage_rect) {
DCHECK(canvas_.get());
DCHECK(bitmap_.get());
damage_rect_ = damage_rect;
return canvas_.get();
}
void OffScreenOutputDevice::EndPaint() {
DCHECK(canvas_.get());
DCHECK(bitmap_.get());
if (!bitmap_.get()) return;
cc::SoftwareOutputDevice::EndPaint();
if (active_)
OnPaint(damage_rect_);
}
void OffScreenOutputDevice::SetActive(bool active) {
if (active == active_)
return;
active_ = active;
if (active_)
OnPaint(gfx::Rect(viewport_pixel_size_));
}
void OffScreenOutputDevice::OnPaint(const gfx::Rect& damage_rect) {
gfx::Rect rect = damage_rect;
rect.Intersect(gfx::Rect(viewport_pixel_size_));
if (rect.IsEmpty())
return;
SkAutoLockPixels bitmap_pixels_lock(*bitmap_);
callback_.Run(rect, *bitmap_);
}
} // namespace atom
<|endoftext|>
|
<commit_before>#include <vtkVersion.h>
int main(int, char *[])
{
std::cout << vtkVersion::GetVTKSourceVersion() << std::endl;
std::cout << vtkVersion::GetVTKMajorVersion() << std::endl;
std::cout << vtkVersion::GetVTKMinorVersion() << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>Updating CheckVTKVersion<commit_after>#include <vtkVersion.h>
#ifdef VTK_VERSION_NUMBER
#if VTK_VERSION_NUMBER >= 90000000000ULL
#define VTK_VER_GE_90 1
#endif
#else
#define VTK_VERSION_NUMBER_NOT_DEFINED 1
#endif
namespace {
/**
* Check the VTK version.
*
* @param major: Major version.
* @param major: Minor version.
* @param major: Build version.
*
* @return True if the requested VTK version is greater or equal to the actual
* VTK version.
*/
bool VTKVersionOk(unsigned long long const& major,
unsigned long long const& minor,
unsigned long long const& build);
} // namespace
int main(int, char*[])
{
#ifdef VTK_VERSION_NUMBER
std::cout << "Source version: " << vtkVersion::GetVTKSourceVersion()
<< std::endl;
std::cout << "Major Version : " << vtkVersion::GetVTKMajorVersion()
<< std::endl;
std::cout << "Minor Version : " << vtkVersion::GetVTKMinorVersion()
<< std::endl;
#elif VTK_VERSION_NUMBER_NOT_DEFINED
std::cout << "VTK VTK_VERSION_NUMBER is not defined." << std::endl;
std::cout << "VTK Major Version: " << VTK_MAJOR_VERSION << std::endl;
std::cout << "VTK Minor Version: " << VTK_MINOR_VERSION << std::endl;
#endif
#ifdef VTK_VER_GE_90
std::cout << "VTK Version is >= " << VTK_VERSION_NUMBER << std::endl;
#endif
if (!VTKVersionOk(8, 90, 0))
{
std::cerr << "You need VTK version 8.90 or greater to run this program."
<< std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "You have the needed VTK version" << endl;
}
return EXIT_SUCCESS;
}
namespace {
bool VTKVersionOk(unsigned long long const& major,
unsigned long long const& minor,
unsigned long long const& build)
{
unsigned long long neededVersion =
10000000000ULL * major + 100000000ULL * minor + build;
#ifndef VTK_VERSION_NUMBER
auto ver = vtkSmartPointer<vtkVersion>();
unsigned long long vtk_version_number =
10000000000ULL * ver->GetVTKMajorVersion() +
100000000ULL * ver->GetVTKMinorVersion() + ver->GetVTKBuildVersion();
if (vtk_version_number >= neededVersion)
{
return true;
}
return false;
#else
if (VTK_VERSION_NUMBER >= neededVersion)
{
return true;
}
return false;
#endif
}
} // namespace
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////
// sect2.cpp -- Emit the Section2 Procedures
// Date: Sat Nov 30 13:50:35 2013
///////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <sstream>
#include "glue.hpp"
#include "comp.hpp"
#include "config.hpp"
void
emit_section2() {
char sgenset[32];
std::fstream ads, adb;
sprintf(sgenset,"%04d",config.section2.genset);
std::cout << "Genset " << sgenset << " emit section2\n";
if ( !gcc_open(ads,config.section2.genset,".ads") )
exit(3);
if ( !gcc_open(adb,config.section2.genset,".adb") )
exit(3);
ads << "\n";
for ( auto it=config.section2.funcs.begin(); it != config.section2.funcs.end(); ++it ) {
s_config::s_section2::s_func& func = *it;
std::stringstream proto;
std::string binding_name = "UX_";
std::vector<std::string> macros_used;
bool skip = false;
if ( func.cases.size() > 0 ) {
skip = true; // For now
for ( auto cit=func.cases.cbegin(); cit != func.cases.cend(); ++cit ) {
const std::string varname = cit->first;
const s_config::s_section2::s_func::s_cases& centry = cit->second;
if ( centry.casevec.size() > 0 ) {
for ( auto vit=centry.casevec.cbegin(); vit != centry.casevec.cend(); ++vit ) {
const std::string& the_case = *vit;
auto mit = config.declared_macros.find(the_case);
if ( mit != config.declared_macros.end() ) {
skip = false;
macros_used.push_back(the_case);
}
}
}
}
}
if ( skip )
continue; // No cases are define macro names
binding_name += func.c_name; // Default internal c binding name
if ( func.alt_name != "" )
binding_name = func.alt_name;
proto << func.type;
if ( func.type != "function" )
proto << "procedure " << func.ada_name;
else proto << "function " << func.ada_name;
if ( func.aargs.size() > 0 ) {
proto << "(";
bool f=true;
for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
s_config::s_section2::s_func::s_aarg& arg = *ait;
if ( !f ) {
proto << "; ";
} else {
f = false;
}
proto << arg.name << ": ";
if ( arg.io != "in" )
proto << arg.io << " ";
proto << arg.type;
}
proto << ")";
if ( func.type == "function" )
proto << " return " << func.returns;
}
//////////////////////////////////////////////////////
// Generate the prototype in the Spec
//////////////////////////////////////////////////////
for ( auto mit = macros_used.begin(); mit != macros_used.end(); ++mit ) {
const std::string macro_name = *mit;
ads << " -- " << macro_name << "\n";
}
ads << " " << proto.str() << ";\n";
if ( func.finline )
ads << " pragma Inline(" << func.ada_name << ");\n\n";
//////////////////////////////////////////////////////
// The body
//////////////////////////////////////////////////////
adb << " " << proto.str() << " is\n";
// Use clauses
for ( auto uit=func.use_clauses.begin(); uit != func.use_clauses.end(); ++uit ) {
const std::string& use_clause = *uit;
adb << " use " << use_clause << ";\n";
}
// C Function Declaration
if ( func.returns != "" )
adb << " function " << binding_name;
else adb << " procedure " << binding_name;
if ( func.cargs.size() > 0 ) {
adb << "(";
bool f = true;
for ( auto cit=func.cargs.begin(); cit != func.cargs.end(); ++cit ) {
const s_config::s_section2::s_func::s_carg& arg = *cit;
if ( !f )
adb << "; ";
else f = false;
adb << arg.name << " : " << arg.type;
}
adb << ")";
}
if ( func.returns != "" )
adb << " return " << func.returns << ";\n";
else adb << ";\n";
// pragma Import(C,UX_close,"close");
adb << " pragma Import(C," << binding_name << ",\"" << func.c_name << "\");\n";
// Temporaries
for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
s_config::s_section2::s_func::s_aarg& arg = *ait;
if ( arg.io == "in" && arg.temp != "" ) {
std::stringstream s;
std::string tempname;
s << "T" << arg.argno;
tempname = s.str();
adb << " " << tempname << " : " << arg.type
<< " := " << arg.tempval << ";\n";
}
}
// Temporary variables
for ( auto t=func.temps.begin(); t != func.temps.end(); ++t ) {
s_config::s_section2::s_func::s_temp& temp = *t;
adb << " " << temp.name << " : " << temp.type;
if ( temp.init != "" )
adb << " := " << temp.init;
adb << ";\n";
}
// Return value:
if ( func.rname != "" ) {
adb << " " << func.rname << " : " << func.returns << ";\n";
}
adb << " begin\n";
// Insert pre-checks
if ( func.prechecks.size() > 0 ) {
for ( auto pit=func.prechecks.cbegin(); pit != func.prechecks.cend(); ++pit ) {
const std::string& cond = *pit;
adb << " if not ( " << cond << " ) then\n"
<< " " << func.on_error << ";\n"
<< " return;\n"
<< " end if;\n";
}
}
// Insert case & when checks
if ( func.cases.size() > 0 ) {
for ( auto cit=func.cases.cbegin(); cit != func.cases.cend(); ++cit ) {
const std::string varname = cit->first;
const s_config::s_section2::s_func::s_cases& centry = cit->second;
if ( centry.casevec.size() > 0 ) {
std::vector<std::string> kvec;
for ( auto vit=centry.casevec.cbegin(); vit != centry.casevec.cend(); ++vit ) {
const std::string& the_case = *vit;
auto mit = config.declared_macros.find(the_case);
if ( mit != config.declared_macros.end() )
kvec.push_back(the_case);
}
if ( kvec.size() > 0 ) {
adb << " case " << varname << " is\n";
for ( auto vit=kvec.cbegin(); vit != kvec.cend(); ++vit ) {
const std::string& the_case = *vit;
adb << " when " << the_case << "=>\n"
<< " null;\n";
}
adb << " when others =>\n"
<< " Error := EINVAL;\n";
if ( centry.on_error != "" )
adb << " " << centry.on_error << ";\n";
adb << " return;\n"
<< " end case;\n";
}
}
}
}
if ( func.rname != "" ) {
adb << " " << func.rname << " := " << binding_name;
} else {
adb << " " << binding_name;
}
if ( func.cargs.size() > 0 ) {
adb << "(";
bool f = true;
for ( auto fit=func.cargs.begin(); fit != func.cargs.end(); ++fit ) {
s_config::s_section2::s_func::s_carg& arg = *fit;
if ( f )
f = false;
else adb << ",";
adb << arg.from;
}
adb << ")";
}
adb << ";\n";
// Output values:
for ( auto oit=func.aargs.begin(); oit != func.aargs.end(); ++oit ) {
s_config::s_section2::s_func::s_aarg& arg = *oit;
if ( arg.from != "implied" ) {
if ( arg.io == "out" || arg.io == "in out" ) {
adb << " " << arg.name << " := "
<< arg.from << ";\n";
}
}
}
adb << " end " << func.ada_name << ";\n\n";
}
ads.close();
adb.close();
}
// End sect2.cpp
<commit_msg>Now emits proper Ada functions + defines adafpx_macro_* when required<commit_after>//////////////////////////////////////////////////////////////////////
// sect2.cpp -- Emit the Section2 Procedures
// Date: Sat Nov 30 13:50:35 2013
///////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <sstream>
#include <unordered_set>
#include "glue.hpp"
#include "comp.hpp"
#include "config.hpp"
void
emit_section2() {
char sgenset[32];
std::fstream ads, adb, cc;
std::unordered_set<std::string> inclset;
sprintf(sgenset,"%04d",config.section2.genset);
std::cout << "Genset " << sgenset << " emit section2\n";
if ( !gcc_open(ads,config.section2.genset,".ads") )
exit(3);
if ( !gcc_open(adb,config.section2.genset,".adb") )
exit(3);
ads << "\n";
for ( auto it=config.section2.funcs.begin(); it != config.section2.funcs.end(); ++it ) {
s_config::s_section2::s_func& func = *it;
std::stringstream proto;
std::string binding_name = "UX_";
std::vector<std::string> macros_used;
bool skip = false;
if ( func.cases.size() > 0 ) {
skip = true; // For now
for ( auto cit=func.cases.cbegin(); cit != func.cases.cend(); ++cit ) {
const std::string varname = cit->first;
const s_config::s_section2::s_func::s_cases& centry = cit->second;
if ( centry.casevec.size() > 0 ) {
for ( auto vit=centry.casevec.cbegin(); vit != centry.casevec.cend(); ++vit ) {
const std::string& the_case = *vit;
auto mit = config.declared_macros.find(the_case);
if ( mit != config.declared_macros.end() ) {
skip = false;
macros_used.push_back(the_case);
}
}
}
}
}
if ( skip )
continue; // No cases are define macro names
binding_name += func.c_name; // Default internal c binding name
if ( func.alt_name != "" )
binding_name = func.alt_name;
proto << func.type << " " << func.ada_name;
if ( func.aargs.size() > 0 ) {
proto << "(";
bool f=true;
for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
s_config::s_section2::s_func::s_aarg& arg = *ait;
if ( !f ) {
proto << "; ";
} else {
f = false;
}
proto << arg.name << ": ";
if ( arg.io != "in" )
proto << arg.io << " ";
proto << arg.type;
}
proto << ")";
if ( func.type == "function" )
proto << " return " << func.ada_return;
}
//////////////////////////////////////////////////////
// Generate the prototype in the Spec
//////////////////////////////////////////////////////
for ( auto mit = macros_used.begin(); mit != macros_used.end(); ++mit ) {
const std::string macro_name = *mit;
ads << " -- " << macro_name << "\n";
}
ads << " " << proto.str() << ";\n";
if ( func.finline )
ads << " pragma Inline(" << func.ada_name << ");\n\n";
//////////////////////////////////////////////////////
// The body
//////////////////////////////////////////////////////
adb << " " << proto.str() << " is\n";
// Use clauses
for ( auto uit=func.use_clauses.begin(); uit != func.use_clauses.end(); ++uit ) {
const std::string& use_clause = *uit;
adb << " use " << use_clause << ";\n";
}
// C Function Declaration
if ( func.returns != "" )
adb << " function " << binding_name;
else adb << " procedure " << binding_name;
if ( func.cargs.size() > 0 ) {
adb << "(";
bool f = true;
for ( auto cit=func.cargs.begin(); cit != func.cargs.end(); ++cit ) {
const s_config::s_section2::s_func::s_carg& arg = *cit;
if ( !f )
adb << "; ";
else f = false;
adb << arg.name << " : " << arg.type;
}
adb << ")";
}
if ( func.returns != "" )
adb << " return " << func.returns << ";\n";
else adb << ";\n";
// pragma Import(C,UX_close,"close");
adb << " pragma Import(C," << binding_name << ",\""
<< func.bind_prefix << func.c_name << "\");\n";
// Temporaries
for ( auto ait=func.aargs.begin(); ait != func.aargs.end(); ++ait ) {
s_config::s_section2::s_func::s_aarg& arg = *ait;
if ( arg.io == "in" && arg.temp != "" ) {
std::stringstream s;
std::string tempname;
s << "T" << arg.argno;
tempname = s.str();
adb << " " << tempname << " : " << arg.type
<< " := " << arg.tempval << ";\n";
}
}
// Temporary variables
for ( auto t=func.temps.begin(); t != func.temps.end(); ++t ) {
s_config::s_section2::s_func::s_temp& temp = *t;
adb << " " << temp.name << " : " << temp.type;
if ( temp.init != "" )
adb << " := " << temp.init;
adb << ";\n";
}
// Return value:
if ( func.rname != "" ) {
adb << " " << func.rname << " : " << func.returns << ";\n";
}
adb << " begin\n";
// Insert pre-checks
if ( func.prechecks.size() > 0 ) {
for ( auto pit=func.prechecks.cbegin(); pit != func.prechecks.cend(); ++pit ) {
const std::string& cond = *pit;
adb << " if not ( " << cond << " ) then\n"
<< " " << func.on_error << ";\n"
<< " return;\n"
<< " end if;\n";
}
}
// Insert case & when checks
if ( func.cases.size() > 0 ) {
for ( auto cit=func.cases.cbegin(); cit != func.cases.cend(); ++cit ) {
const std::string varname = cit->first;
const s_config::s_section2::s_func::s_cases& centry = cit->second;
if ( centry.casevec.size() > 0 ) {
std::vector<std::string> kvec;
for ( auto vit=centry.casevec.cbegin(); vit != centry.casevec.cend(); ++vit ) {
const std::string& the_case = *vit;
auto mit = config.declared_macros.find(the_case);
if ( mit != config.declared_macros.end() )
kvec.push_back(the_case);
}
if ( kvec.size() > 0 ) {
adb << " case " << varname << " is\n";
for ( auto vit=kvec.cbegin(); vit != kvec.cend(); ++vit ) {
const std::string& the_case = *vit;
adb << " when " << the_case << "=>\n"
<< " null;\n";
}
adb << " when others =>\n"
<< " Error := EINVAL;\n";
if ( centry.on_error != "" )
adb << " " << centry.on_error << ";\n";
adb << " return;\n"
<< " end case;\n";
}
}
}
}
if ( func.rname != "" ) {
adb << " " << func.rname << " := " << binding_name;
} else {
adb << " " << binding_name;
}
if ( func.cargs.size() > 0 ) {
adb << "(";
bool f = true;
for ( auto fit=func.cargs.begin(); fit != func.cargs.end(); ++fit ) {
s_config::s_section2::s_func::s_carg& arg = *fit;
if ( f )
f = false;
else adb << ",";
adb << arg.from;
}
adb << ")";
}
adb << ";\n";
// Output values:
for ( auto oit=func.aargs.begin(); oit != func.aargs.end(); ++oit ) {
s_config::s_section2::s_func::s_aarg& arg = *oit;
if ( arg.from != "implied" ) {
if ( arg.io == "out" || arg.io == "in out" ) {
adb << " " << arg.name << " := "
<< arg.from << ";\n";
}
}
}
// Function return value
if ( func.type == "function" ) {
adb << " return " << func.ada_rfrom << ";\n";
}
adb << " end " << func.ada_name << ";\n\n";
//////////////////////////////////////////////////////
// Check if a macro must be emitted
//////////////////////////////////////////////////////
if ( func.macro != "" ) {
if ( !cc.is_open() && !gcc_open(cc,config.section2.genset,".cc") )
exit(3);
for ( auto it=func.includes.begin(); it != func.includes.end(); ++it ) {
const std::string& incl = *it;
if ( inclset.find(incl) == inclset.end() ) {
if ( incl[0] != '.' )
cc << "#include <" << incl << ">\n";
else cc << "#include \"" << incl << "\"\n";
inclset.insert(incl);
}
}
cc << "\n"
<< func.macro << "\n\n";
}
}
ads.close();
adb.close();
cc.close();
}
// End sect2.cpp
<|endoftext|>
|
<commit_before>#pragma once
#include "standard_error_handler.hpp"
#include <libxml/xmlerror.h>
#include <libxml/xmlschemas.h>
class LibXml2ErrorHandler : public StandardErrorHandler {
public:
static void errors( void *ctx, xmlErrorPtr p );
};
class XmlErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( ) {
xmlSetStructuredErrorFunc( static_cast<void *>( this ),
&LibXml2ErrorHandler::errors );
}
};
class XmlSchemaParserErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( xmlSchemaParserCtxt *spcp ) {
xmlSchemaSetParserStructuredErrors( spcp, &LibXml2ErrorHandler::errors,
static_cast<void *>( this ) );
}
};
class XmlSchemaValidatorErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( xmlSchemaValidCtxt *schemaValidator ) {
xmlSchemaSetValidStructuredErrors( schemaValidator, &LibXml2ErrorHandler::errors,
static_cast<void *>( this ) );
}
};
<commit_msg>appended XPathErrorHandler<commit_after>#pragma once
#include "standard_error_handler.hpp"
#include <libxml/xmlerror.h>
#include <libxml/xmlschemas.h>
#include <libxml/xpath.h>
class LibXml2ErrorHandler : public StandardErrorHandler {
public:
static void errors( void *ctx, xmlErrorPtr p );
};
class XmlErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( ) {
xmlSetStructuredErrorFunc( static_cast<void *>( this ),
&LibXml2ErrorHandler::errors );
}
};
class XmlSchemaParserErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( xmlSchemaParserCtxt *spcp ) {
xmlSchemaSetParserStructuredErrors( spcp, &LibXml2ErrorHandler::errors,
static_cast<void *>( this ) );
}
};
class XmlSchemaValidatorErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( xmlSchemaValidCtxt *schemaValidator ) {
xmlSchemaSetValidStructuredErrors( schemaValidator, &LibXml2ErrorHandler::errors,
static_cast<void *>( this ) );
}
};
class XPathErrorHandler : public LibXml2ErrorHandler {
public:
void registerHandler( xmlXPathContext *xpathctxt ) {
xpathctxt->userData = this;
xpathctxt->error = &LibXml2ErrorHandler::errors;
}
};
<|endoftext|>
|
<commit_before>#include "model.h"
#include "model_io.h"
#include "modelwidget.h"
#include "figurepainter.h"
#include "recognition.h"
#include "layouting.h"
#include "model_ops.h"
#include <QPainter>
#include <QMouseEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <QWheelEvent>
#include <QGesture>
#include <QDebug>
#include <QTimer>
#include <QMenu>
Ui::ModelWidget::ModelWidget(QWidget *parent) :
QWidget(parent), mouseAction(MouseAction::None), _gridStep(0), _showTrack(true), _showRecognitionResult(true), _storeTracks(false) {
setFocusPolicy(Qt::FocusPolicy::StrongFocus);
grabGesture(Qt::PinchGesture);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this, &Ui::ModelWidget::customContextMenuRequested);
#if DISABLE_SHOW_RECOGNITION_RESULT == 1
setShowRecognitionResult(false);
#endif
}
void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) {
QPen oldPen = painter.pen();
std::vector<double> speeds = calculateRelativeSpeeds(track);
for (size_t i = 0; i + 1 < track.size(); i++) {
double k = speeds[i] * 510;
QColor color;
if (k <= 255) color = QColor(255, k, 0, 127);
else color = QColor(255 - (k - 255), 255, 0, 127);
QPen pen = oldPen;
pen.setColor(color);
painter.setPen(pen);
painter.drawLine(scaler(track[i]), scaler(track[i + 1]));
}
std::vector<int> stops = getSpeedBreakpoints(track);
for (int stop : stops) {
QPen pen = oldPen;
pen.setColor(QColor(0, 255, 255));
painter.setPen(pen);
painter.drawEllipse(scaler(track[stop]), scaler.scaleFactor * 10, scaler.scaleFactor * 10);
}
painter.setPen(oldPen);
}
int Ui::ModelWidget::gridStep() {
return _gridStep;
}
void Ui::ModelWidget::setGridStep(int newGridStep) {
if (newGridStep < 0) {
throw std::runtime_error("Grid step should be >= 0");
}
_gridStep = newGridStep;
update();
}
double Ui::ModelWidget::scaleFactor() {
return scaler.scaleFactor;
}
void Ui::ModelWidget::setScaleFactor(double newScaleFactor) {
if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs
throw std::runtime_error("Scale factor should be >= 0.01");
}
scaler.scaleFactor = newScaleFactor;
emit scaleFactorChanged();
update();
}
bool Ui::ModelWidget::showTrack() {
return _showTrack;
}
void Ui::ModelWidget::setShowTrack(bool newShowTrack) {
_showTrack = newShowTrack;
}
bool Ui::ModelWidget::showRecognitionResult() {
return _showRecognitionResult;
}
void Ui::ModelWidget::setShowRecognitionResult(bool newShowRecognitionResult) {
_showRecognitionResult = newShowRecognitionResult;
}
bool Ui::ModelWidget::storeTracks() {
return _storeTracks;
}
void Ui::ModelWidget::setStoreTracks(bool newStoreTracks) {
_storeTracks = newStoreTracks;
}
void Ui::ModelWidget::setModel(Model model) {
commitedModel = std::move(model);
previousModels.clear();
redoModels.clear();
emit canUndoChanged();
emit canRedoChanged();
extraTracks = std::vector<Track>();
}
Model &Ui::ModelWidget::getModel() {
return commitedModel;
}
void Ui::ModelWidget::addModelExtraTrack(Track track) {
extraTracks.push_back(std::move(track));
}
bool Ui::ModelWidget::canUndo() {
return !previousModels.empty();
}
void Ui::ModelWidget::undo() {
if (!canUndo()) {
throw std::runtime_error("Cannot undo");
}
redoModels.push_front(std::move(commitedModel));
commitedModel = std::move(previousModels.back());
previousModels.pop_back();
if (!canUndo()) {
emit canUndoChanged();
}
emit canRedoChanged();
update();
}
bool Ui::ModelWidget::canRedo() {
return !redoModels.empty();
}
void Ui::ModelWidget::redo() {
if (!canRedo()) {
throw std::runtime_error("Cannot redo");
}
previousModels.push_back(std::move(commitedModel));
commitedModel = std::move(redoModels.front());
redoModels.pop_front();
if (!canRedo()) {
canRedoChanged();
}
canUndoChanged();
update();
}
void Ui::ModelWidget::modifyModelAndCommit(std::function<void()> action) {
previousModels.push_back(commitedModel);
redoModels.clear();
action();
emit canUndoChanged();
emit canRedoChanged();
update();
}
double roundDownToMultiple(double x, double multiple) {
return floor(x / multiple) * multiple;
}
void Ui::ModelWidget::paintEvent(QPaintEvent *) {
QPainter painter(this);
painter.fillRect(QRect(QPoint(), size()), Qt::white);
QFont font;
font.setPointSizeF(10 * scaler.scaleFactor);
painter.setFont(font);
QPen pen(Qt::black);
pen.setWidthF(scaler.scaleFactor);
painter.setPen(pen);
FigurePainter fpainter(painter, scaler);
if (gridStep() > 0) {
int step = gridStep();
// Calculating visible area
Point p1 = scaler(QPointF(0, 0));
Point p2 = scaler(QPointF(width(), height()));
if (p1.x > p2.x) { std::swap(p1.x, p2.x); }
if (p1.y > p2.y) { std::swap(p1.y, p2.y); }
// Finding starting point for the grid
p1.x = roundDownToMultiple(p1.x, step);
p1.y = roundDownToMultiple(p1.y, step);
// Drawing
QPen pen(QColor(192, 192, 192, 255));
pen.setStyle(Qt::DashLine);
painter.setPen(pen);
for (int x = p1.x; x <= p2.x; x += step) {
painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y)));
}
for (int y = p1.y; y <= p2.y; y += step) {
painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y)));
}
}
Model copiedModel;
Model &modelToDraw = (lastTrack.empty() || !showRecognitionResult()) ? commitedModel : (copiedModel = commitedModel);
PFigure modified = showRecognitionResult() ? recognize(lastTrack, modelToDraw) : nullptr;
for (PFigure fig : modelToDraw) {
if (fig == modified) {
pen.setColor(Qt::magenta);
} else if (fig == modelToDraw.selectedFigure) {
pen.setColor(Qt::blue);
} else {
pen.setColor(Qt::black);
}
painter.setPen(pen);
fig->visit(fpainter);
}
pen.setColor(QColor(255, 0, 0, 16));
pen.setWidth(3 * scaler.scaleFactor);
painter.setPen(pen);
if (showTrack()) {
drawTrack(painter, scaler, lastTrack);
for (const Track &track : visibleTracks) {
drawTrack(painter, scaler, track);
}
}
for (const Track &track : extraTracks) {
drawTrack(painter, scaler, track);
}
}
void Ui::ModelWidget::customContextMenuRequested(const QPoint &pos) {
PFigure figure = findClickedFigure(commitedModel, scaler(pos));
if (figure) {
std::shared_ptr<figures::Curve> curve = std::dynamic_pointer_cast<figures::Curve>(figure);
if (curve) {
QMenu contextMenu;
QAction verticalSymmetry("Make vertically symmetric", this);
connect(&verticalSymmetry, &QAction::triggered, [this, curve]() {
modifyModelAndCommit([curve]() {
makeVerticallySymmetric(curve);
});
});
contextMenu.addAction(&verticalSymmetry);
QAction horizontalSymmetry("Make horizontally symmetric", this);
connect(&horizontalSymmetry, &QAction::triggered, [this, curve]() {
modifyModelAndCommit([curve]() {
makeHorizontallySymmetric(curve);
});
});
contextMenu.addAction(&horizontalSymmetry);
contextMenu.exec(mapToGlobal(pos));
}
auto bounded = std::dynamic_pointer_cast<figures::BoundedFigure>(figure);
if (bounded) {
QMenu contextMenu;
QAction topBottomTree("Arrange children in a tree", this);
connect(&topBottomTree, &QAction::triggered, [this, bounded]() {
modifyModelAndCommit([this, bounded]() {
makeTopBottomTree(commitedModel, bounded);
});
});
contextMenu.addAction(&topBottomTree);
contextMenu.exec(mapToGlobal(pos));
}
}
}
void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {
lastTrack = Track();
if (event->modifiers().testFlag(Qt::ShiftModifier) || event->buttons().testFlag(Qt::MiddleButton)) {
mouseAction = MouseAction::ViewpointMove;
viewpointMoveStart = event->pos();
viewpointMoveOldScaler = scaler;
setCursor(Qt::ClosedHandCursor);
} else if (event->buttons().testFlag(Qt::LeftButton)) {
mouseAction = MouseAction::TrackActive;
trackTimer.start();
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
}
update();
}
void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {
if (mouseAction == MouseAction::ViewpointMove) {
scaler = viewpointMoveOldScaler;
scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos());
update();
} else if (mouseAction == MouseAction::TrackActive) {
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
#if ENABLE_FAST_REDRAW == 1
if (showTrack() && !showRecognitionResult()) {
QPoint a = scaler(lastTrack[lastTrack.size() - 2]).toPoint();
QPoint b = event->pos();
QRect r = QRect(a, a).united(QRect(b, b));
r.adjust(-2, -2, +2, +2);
update(r);
} else
#endif
if (showTrack() || showRecognitionResult()) {
update();
}
} else {
event->ignore();
}
}
void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {
if (mouseAction == MouseAction::None) {
event->ignore();
return;
}
if (mouseAction == MouseAction::ViewpointMove) {
mouseAction = MouseAction::None;
setCursor(Qt::ArrowCursor);
scaler = viewpointMoveOldScaler;
scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos());
update();
return;
}
assert(mouseAction == MouseAction::TrackActive);
mouseAction = MouseAction::None;
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
if (storeTracks()) {
QFile file(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + ".track");
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::critical(this, "Error while saving track", "Unable to open file for writing");
} else {
std::stringstream stream;
stream << lastTrack;
std::string data = stream.str();
if (file.write(data.data(), data.length()) != data.length()) {
QMessageBox::critical(this, "Error while saving track", "Unable to write to opened file");
}
}
}
Model previousModel = commitedModel;
PFigure modifiedFigure = recognize(lastTrack, commitedModel);
if (_gridStep > 0 && modifiedFigure) {
GridAlignLayouter layouter(_gridStep);
layouter.updateLayout(commitedModel, modifiedFigure);
commitedModel.recalculate();
}
visibleTracks.push_back(lastTrack);
auto iterator = --visibleTracks.end();
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [this, iterator, timer]() {
visibleTracks.erase(iterator);
delete timer;
update();
});
timer->setInterval(1500);
timer->setSingleShot(true);
timer->start();
lastTrack = Track();
if (modifiedFigure) {
previousModels.push_back(previousModel);
redoModels.clear();
emit canUndoChanged();
emit canRedoChanged();
}
update();
}
void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) {
event->ignore();
if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) {
event->accept();
lastTrack = Track();
mouseAction = MouseAction::None;
update();
}
if (event->key() == Qt::Key_Delete) {
if (commitedModel.selectedFigure) {
event->accept();
modifyModelAndCommit([this]() {
for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) {
if (*it == commitedModel.selectedFigure) {
commitedModel.removeFigure(it);
break;
}
}
});
}
}
}
void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) {
event->ignore();
auto &figure = commitedModel.selectedFigure;
if (!figure) { return; }
Point eventPos = scaler(event->pos());
bool hit = false;
hit |= figure->isInsideOrOnBorder(eventPos);
hit |= figure->getApproximateDistanceToBorder(eventPos) <= figureSelectGap();
if (!hit) { return; }
event->accept();
bool ok;
QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label",
QString::fromStdString(figure->label()),
&ok);
if (ok) {
modifyModelAndCommit([figure, &newLabel]() {
figure->setLabel(newLabel.toStdString());
});
}
}
void Ui::ModelWidget::wheelEvent(QWheelEvent *event) {
event->ignore();
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->accept();
double scrolled = event->angleDelta().y() / 8;
double factor = 1.0 + 0.2 * (scrolled / 15); // 20% per each 15 degrees (standard step)
factor = std::max(factor, 0.1);
scaler.scaleWithFixedPoint(scaler(event->pos()), factor);
update();
}
}
bool Ui::ModelWidget::event(QEvent *event) {
if (event->type() == QEvent::Gesture) {
QGestureEvent *gevent = static_cast<QGestureEvent*>(event);
QPinchGesture *gesture = static_cast<QPinchGesture*>(gevent->gesture(Qt::PinchGesture));
if (gesture) {
gevent->accept(gesture);
lastTrack = Track();
mouseAction = MouseAction::None;
scaler.zeroPoint = scaler.zeroPoint + scaler(gesture->lastCenterPoint()) - scaler(gesture->centerPoint());
scaler.scaleWithFixedPoint(scaler(gesture->centerPoint()), gesture->scaleFactor());
emit scaleFactorChanged();
update();
return true;
}
}
return QWidget::event(event);
}
<commit_msg>modelwidget: 'emit' was added for some signal calls<commit_after>#include "model.h"
#include "model_io.h"
#include "modelwidget.h"
#include "figurepainter.h"
#include "recognition.h"
#include "layouting.h"
#include "model_ops.h"
#include <QPainter>
#include <QMouseEvent>
#include <QInputDialog>
#include <QMessageBox>
#include <QWheelEvent>
#include <QGesture>
#include <QDebug>
#include <QTimer>
#include <QMenu>
Ui::ModelWidget::ModelWidget(QWidget *parent) :
QWidget(parent), mouseAction(MouseAction::None), _gridStep(0), _showTrack(true), _showRecognitionResult(true), _storeTracks(false) {
setFocusPolicy(Qt::FocusPolicy::StrongFocus);
grabGesture(Qt::PinchGesture);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this, &Ui::ModelWidget::customContextMenuRequested);
#if DISABLE_SHOW_RECOGNITION_RESULT == 1
setShowRecognitionResult(false);
#endif
}
void drawTrack(QPainter &painter, Scaler &scaler, const Track &track) {
QPen oldPen = painter.pen();
std::vector<double> speeds = calculateRelativeSpeeds(track);
for (size_t i = 0; i + 1 < track.size(); i++) {
double k = speeds[i] * 510;
QColor color;
if (k <= 255) color = QColor(255, k, 0, 127);
else color = QColor(255 - (k - 255), 255, 0, 127);
QPen pen = oldPen;
pen.setColor(color);
painter.setPen(pen);
painter.drawLine(scaler(track[i]), scaler(track[i + 1]));
}
std::vector<int> stops = getSpeedBreakpoints(track);
for (int stop : stops) {
QPen pen = oldPen;
pen.setColor(QColor(0, 255, 255));
painter.setPen(pen);
painter.drawEllipse(scaler(track[stop]), scaler.scaleFactor * 10, scaler.scaleFactor * 10);
}
painter.setPen(oldPen);
}
int Ui::ModelWidget::gridStep() {
return _gridStep;
}
void Ui::ModelWidget::setGridStep(int newGridStep) {
if (newGridStep < 0) {
throw std::runtime_error("Grid step should be >= 0");
}
_gridStep = newGridStep;
update();
}
double Ui::ModelWidget::scaleFactor() {
return scaler.scaleFactor;
}
void Ui::ModelWidget::setScaleFactor(double newScaleFactor) {
if (!(newScaleFactor >= 0.01)) { // >= instead of < for NaNs
throw std::runtime_error("Scale factor should be >= 0.01");
}
scaler.scaleFactor = newScaleFactor;
emit scaleFactorChanged();
update();
}
bool Ui::ModelWidget::showTrack() {
return _showTrack;
}
void Ui::ModelWidget::setShowTrack(bool newShowTrack) {
_showTrack = newShowTrack;
}
bool Ui::ModelWidget::showRecognitionResult() {
return _showRecognitionResult;
}
void Ui::ModelWidget::setShowRecognitionResult(bool newShowRecognitionResult) {
_showRecognitionResult = newShowRecognitionResult;
}
bool Ui::ModelWidget::storeTracks() {
return _storeTracks;
}
void Ui::ModelWidget::setStoreTracks(bool newStoreTracks) {
_storeTracks = newStoreTracks;
}
void Ui::ModelWidget::setModel(Model model) {
commitedModel = std::move(model);
previousModels.clear();
redoModels.clear();
emit canUndoChanged();
emit canRedoChanged();
extraTracks = std::vector<Track>();
}
Model &Ui::ModelWidget::getModel() {
return commitedModel;
}
void Ui::ModelWidget::addModelExtraTrack(Track track) {
extraTracks.push_back(std::move(track));
}
bool Ui::ModelWidget::canUndo() {
return !previousModels.empty();
}
void Ui::ModelWidget::undo() {
if (!canUndo()) {
throw std::runtime_error("Cannot undo");
}
redoModels.push_front(std::move(commitedModel));
commitedModel = std::move(previousModels.back());
previousModels.pop_back();
if (!canUndo()) {
emit canUndoChanged();
}
emit canRedoChanged();
update();
}
bool Ui::ModelWidget::canRedo() {
return !redoModels.empty();
}
void Ui::ModelWidget::redo() {
if (!canRedo()) {
throw std::runtime_error("Cannot redo");
}
previousModels.push_back(std::move(commitedModel));
commitedModel = std::move(redoModels.front());
redoModels.pop_front();
if (!canRedo()) {
emit canRedoChanged();
}
emit canUndoChanged();
update();
}
void Ui::ModelWidget::modifyModelAndCommit(std::function<void()> action) {
previousModels.push_back(commitedModel);
redoModels.clear();
action();
emit canUndoChanged();
emit canRedoChanged();
update();
}
double roundDownToMultiple(double x, double multiple) {
return floor(x / multiple) * multiple;
}
void Ui::ModelWidget::paintEvent(QPaintEvent *) {
QPainter painter(this);
painter.fillRect(QRect(QPoint(), size()), Qt::white);
QFont font;
font.setPointSizeF(10 * scaler.scaleFactor);
painter.setFont(font);
QPen pen(Qt::black);
pen.setWidthF(scaler.scaleFactor);
painter.setPen(pen);
FigurePainter fpainter(painter, scaler);
if (gridStep() > 0) {
int step = gridStep();
// Calculating visible area
Point p1 = scaler(QPointF(0, 0));
Point p2 = scaler(QPointF(width(), height()));
if (p1.x > p2.x) { std::swap(p1.x, p2.x); }
if (p1.y > p2.y) { std::swap(p1.y, p2.y); }
// Finding starting point for the grid
p1.x = roundDownToMultiple(p1.x, step);
p1.y = roundDownToMultiple(p1.y, step);
// Drawing
QPen pen(QColor(192, 192, 192, 255));
pen.setStyle(Qt::DashLine);
painter.setPen(pen);
for (int x = p1.x; x <= p2.x; x += step) {
painter.drawLine(scaler(Point(x, p1.y)), scaler(Point(x, p2.y)));
}
for (int y = p1.y; y <= p2.y; y += step) {
painter.drawLine(scaler(Point(p1.x, y)), scaler(Point(p2.x, y)));
}
}
Model copiedModel;
Model &modelToDraw = (lastTrack.empty() || !showRecognitionResult()) ? commitedModel : (copiedModel = commitedModel);
PFigure modified = showRecognitionResult() ? recognize(lastTrack, modelToDraw) : nullptr;
for (PFigure fig : modelToDraw) {
if (fig == modified) {
pen.setColor(Qt::magenta);
} else if (fig == modelToDraw.selectedFigure) {
pen.setColor(Qt::blue);
} else {
pen.setColor(Qt::black);
}
painter.setPen(pen);
fig->visit(fpainter);
}
pen.setColor(QColor(255, 0, 0, 16));
pen.setWidth(3 * scaler.scaleFactor);
painter.setPen(pen);
if (showTrack()) {
drawTrack(painter, scaler, lastTrack);
for (const Track &track : visibleTracks) {
drawTrack(painter, scaler, track);
}
}
for (const Track &track : extraTracks) {
drawTrack(painter, scaler, track);
}
}
void Ui::ModelWidget::customContextMenuRequested(const QPoint &pos) {
PFigure figure = findClickedFigure(commitedModel, scaler(pos));
if (figure) {
std::shared_ptr<figures::Curve> curve = std::dynamic_pointer_cast<figures::Curve>(figure);
if (curve) {
QMenu contextMenu;
QAction verticalSymmetry("Make vertically symmetric", this);
connect(&verticalSymmetry, &QAction::triggered, [this, curve]() {
modifyModelAndCommit([curve]() {
makeVerticallySymmetric(curve);
});
});
contextMenu.addAction(&verticalSymmetry);
QAction horizontalSymmetry("Make horizontally symmetric", this);
connect(&horizontalSymmetry, &QAction::triggered, [this, curve]() {
modifyModelAndCommit([curve]() {
makeHorizontallySymmetric(curve);
});
});
contextMenu.addAction(&horizontalSymmetry);
contextMenu.exec(mapToGlobal(pos));
}
auto bounded = std::dynamic_pointer_cast<figures::BoundedFigure>(figure);
if (bounded) {
QMenu contextMenu;
QAction topBottomTree("Arrange children in a tree", this);
connect(&topBottomTree, &QAction::triggered, [this, bounded]() {
modifyModelAndCommit([this, bounded]() {
makeTopBottomTree(commitedModel, bounded);
});
});
contextMenu.addAction(&topBottomTree);
contextMenu.exec(mapToGlobal(pos));
}
}
}
void Ui::ModelWidget::mousePressEvent(QMouseEvent *event) {
lastTrack = Track();
if (event->modifiers().testFlag(Qt::ShiftModifier) || event->buttons().testFlag(Qt::MiddleButton)) {
mouseAction = MouseAction::ViewpointMove;
viewpointMoveStart = event->pos();
viewpointMoveOldScaler = scaler;
setCursor(Qt::ClosedHandCursor);
} else if (event->buttons().testFlag(Qt::LeftButton)) {
mouseAction = MouseAction::TrackActive;
trackTimer.start();
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
}
update();
}
void Ui::ModelWidget::mouseMoveEvent(QMouseEvent *event) {
if (mouseAction == MouseAction::ViewpointMove) {
scaler = viewpointMoveOldScaler;
scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos());
update();
} else if (mouseAction == MouseAction::TrackActive) {
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
#if ENABLE_FAST_REDRAW == 1
if (showTrack() && !showRecognitionResult()) {
QPoint a = scaler(lastTrack[lastTrack.size() - 2]).toPoint();
QPoint b = event->pos();
QRect r = QRect(a, a).united(QRect(b, b));
r.adjust(-2, -2, +2, +2);
update(r);
} else
#endif
if (showTrack() || showRecognitionResult()) {
update();
}
} else {
event->ignore();
}
}
void Ui::ModelWidget::mouseReleaseEvent(QMouseEvent *event) {
if (mouseAction == MouseAction::None) {
event->ignore();
return;
}
if (mouseAction == MouseAction::ViewpointMove) {
mouseAction = MouseAction::None;
setCursor(Qt::ArrowCursor);
scaler = viewpointMoveOldScaler;
scaler.zeroPoint = scaler.zeroPoint + scaler(viewpointMoveStart) - scaler(event->pos());
update();
return;
}
assert(mouseAction == MouseAction::TrackActive);
mouseAction = MouseAction::None;
lastTrack.points.push_back(TrackPoint(scaler(event->pos()), trackTimer.elapsed()));
if (storeTracks()) {
QFile file(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss") + ".track");
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::critical(this, "Error while saving track", "Unable to open file for writing");
} else {
std::stringstream stream;
stream << lastTrack;
std::string data = stream.str();
if (file.write(data.data(), data.length()) != data.length()) {
QMessageBox::critical(this, "Error while saving track", "Unable to write to opened file");
}
}
}
Model previousModel = commitedModel;
PFigure modifiedFigure = recognize(lastTrack, commitedModel);
if (_gridStep > 0 && modifiedFigure) {
GridAlignLayouter layouter(_gridStep);
layouter.updateLayout(commitedModel, modifiedFigure);
commitedModel.recalculate();
}
visibleTracks.push_back(lastTrack);
auto iterator = --visibleTracks.end();
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, [this, iterator, timer]() {
visibleTracks.erase(iterator);
delete timer;
update();
});
timer->setInterval(1500);
timer->setSingleShot(true);
timer->start();
lastTrack = Track();
if (modifiedFigure) {
previousModels.push_back(previousModel);
redoModels.clear();
emit canUndoChanged();
emit canRedoChanged();
}
update();
}
void Ui::ModelWidget::keyReleaseEvent(QKeyEvent *event) {
event->ignore();
if (event->key() == Qt::Key_Escape && mouseAction == MouseAction::TrackActive) {
event->accept();
lastTrack = Track();
mouseAction = MouseAction::None;
update();
}
if (event->key() == Qt::Key_Delete) {
if (commitedModel.selectedFigure) {
event->accept();
modifyModelAndCommit([this]() {
for (auto it = commitedModel.begin(); it != commitedModel.end(); it++) {
if (*it == commitedModel.selectedFigure) {
commitedModel.removeFigure(it);
break;
}
}
});
}
}
}
void Ui::ModelWidget::mouseDoubleClickEvent(QMouseEvent *event) {
event->ignore();
auto &figure = commitedModel.selectedFigure;
if (!figure) { return; }
Point eventPos = scaler(event->pos());
bool hit = false;
hit |= figure->isInsideOrOnBorder(eventPos);
hit |= figure->getApproximateDistanceToBorder(eventPos) <= figureSelectGap();
if (!hit) { return; }
event->accept();
bool ok;
QString newLabel = QInputDialog::getMultiLineText(this, "Figure label", "Specify new figure label",
QString::fromStdString(figure->label()),
&ok);
if (ok) {
modifyModelAndCommit([figure, &newLabel]() {
figure->setLabel(newLabel.toStdString());
});
}
}
void Ui::ModelWidget::wheelEvent(QWheelEvent *event) {
event->ignore();
if (event->modifiers().testFlag(Qt::ControlModifier)) {
event->accept();
double scrolled = event->angleDelta().y() / 8;
double factor = 1.0 + 0.2 * (scrolled / 15); // 20% per each 15 degrees (standard step)
factor = std::max(factor, 0.1);
scaler.scaleWithFixedPoint(scaler(event->pos()), factor);
update();
}
}
bool Ui::ModelWidget::event(QEvent *event) {
if (event->type() == QEvent::Gesture) {
QGestureEvent *gevent = static_cast<QGestureEvent*>(event);
QPinchGesture *gesture = static_cast<QPinchGesture*>(gevent->gesture(Qt::PinchGesture));
if (gesture) {
gevent->accept(gesture);
lastTrack = Track();
mouseAction = MouseAction::None;
scaler.zeroPoint = scaler.zeroPoint + scaler(gesture->lastCenterPoint()) - scaler(gesture->centerPoint());
scaler.scaleWithFixedPoint(scaler(gesture->centerPoint()), gesture->scaleFactor());
emit scaleFactorChanged();
update();
return true;
}
}
return QWidget::event(event);
}
<|endoftext|>
|
<commit_before>#include "UT4WebAdmin.h"
#include "Base64.h"
#define UT4WA_PLUGIN_FOLDER "UT4WebAdmin"
#define UT4WA_WWW_FOLDER "www"
#define PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
#define DENIED2 "<html><head><title>Acces denied</title></head><body>Access denied</body></html>"
#define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
UUT4WebAdmin::UUT4WebAdmin(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
daemon = nullptr;
GameMode = nullptr;
}
void UUT4WebAdmin::Init()
{
// Don't garbage collect me
SetFlags(RF_MarkAsRootSet);
if (WebHttpPort == 0)
{
WebHttpPort = 8080;
}
if (HeadAdminUsername.IsEmpty()) {
HeadAdminUsername = FString("webadmin");
}
if (HeadAdminPassword.IsEmpty()) {
HeadAdminPassword = FString("webadminpassword");
}
StartMicroHttp();
}
TSharedPtr<FJsonObject> GetGameInfoJSON()
{
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);;
// Get a reference of any object using the UTBaseGameMode
AUTBaseGameMode* BaseGameMode;
BaseGameMode = Cast<AUTBaseGameMode>(GWorld->GetAuthGameMode());
if (BaseGameMode) {
// GameMode
JsonObject->SetBoolField(TEXT("IsMatchInProgress"), BaseGameMode->IsMatchInProgress());
JsonObject->SetBoolField(TEXT("HasMatchEnded"), BaseGameMode->HasMatchEnded());
JsonObject->SetNumberField(TEXT("NumTravellingPlayers"), BaseGameMode->NumTravellingPlayers);
JsonObject->SetStringField(TEXT("NetworkNumber"), BaseGameMode->GetNetworkNumber());
JsonObject->SetStringField(TEXT("MatchState"), BaseGameMode->GetMatchState().ToString());
// UTBaseGameMode
JsonObject->SetStringField(TEXT("ServerInstanceID"), BaseGameMode->ServerInstanceID);
JsonObject->SetStringField(TEXT("ServerInstanceGUID"), BaseGameMode->ServerInstanceGUID.ToString()); // The Unique ID for this game instance.
JsonObject->SetStringField(TEXT("ContextGUID"), BaseGameMode->ContextGUID.ToString()); // ?
JsonObject->SetStringField(TEXT("ServerPassword"), BaseGameMode->ServerPassword);
JsonObject->SetStringField(TEXT("SpectatePassword"), BaseGameMode->SpectatePassword);
JsonObject->SetBoolField(TEXT("bRequirePassword"), BaseGameMode->bRequirePassword);
JsonObject->SetStringField(TEXT("DisplayName"), BaseGameMode->DisplayName.ToString());
JsonObject->SetNumberField(TEXT("MinAllowedRank"), BaseGameMode->MinAllowedRank);
JsonObject->SetNumberField(TEXT("MaxAllowedRank"), BaseGameMode->MaxAllowedRank);
JsonObject->SetBoolField(TEXT("bTrainingGround"), BaseGameMode->bTrainingGround);
JsonObject->SetNumberField(TEXT("NumPlayers"), BaseGameMode->GetNumPlayers());
JsonObject->SetNumberField(TEXT("NumMatches"), BaseGameMode->GetNumMatches()); // 1 if dedi server else [0, .., X] range for hubs/lobbies
JsonObject->SetNumberField(TEXT("CurrentPlaylistId"), BaseGameMode->CurrentPlaylistId); // no idea what this is about
JsonObject->SetBoolField(TEXT("bPrivateMatch"), BaseGameMode->bPrivateMatch);
JsonObject->SetStringField(TEXT("RankedLeagueName"), BaseGameMode->GetRankedLeagueName()); // always empty for the moment
JsonObject->SetBoolField(TEXT("SupportsInstantReplay"), BaseGameMode->SupportsInstantReplay());
JsonObject->SetBoolField(TEXT("bIsLANGame"), BaseGameMode->bIsLANGame);
if (BaseGameMode->IsLobbyServer())
{
AUTLobbyGameMode* LobbyGameMode;
LobbyGameMode = GWorld->GetAuthGameMode<AUTLobbyGameMode>();
if (LobbyGameMode)
{
JsonObject->SetStringField(TEXT("ServType"), TEXT("dedis"));
// TODO get instance data
}
}
}
return JsonObject;
}
// Method to serve json file to client
int serve_json_file(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls, TSharedPtr<FJsonObject> json)
{
int ret;
struct MHD_Response *response;
FString JsonText;
TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&JsonText);
FJsonSerializer::Serialize(json.ToSharedRef(), Writer);
std::string tmpStr = TCHAR_TO_ANSI(*JsonText);
char *jsonChar = new char[tmpStr.length() + 1];
strcpy(jsonChar, tmpStr.c_str());
response = MHD_create_response_from_buffer(strlen(jsonChar),
(void*)jsonChar, MHD_RESPMEM_PERSISTENT);
MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, "application/json");
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
}
int handle_game_info(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
if (strcmp(method, MHD_HTTP_METHOD_GET) == 0) {
TSharedPtr<FJsonObject> matchInfoJson = GetGameInfoJSON();
return serve_json_file(cls, connection, url, method, version, upload_data, upload_data_size, con_cls, matchInfoJson);
}
else {
// TODO handle post request for kick/ban/modify server info ...
}
return MHD_NO;
}
// Server files from root folder
const FString wwwStr = FPaths::GamePluginsDir() + UT4WA_PLUGIN_FOLDER + "/" + UT4WA_WWW_FOLDER + "/";
int handle_serve_file(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method, // GET / POST / PUT ...
const char *version, // HTML version 1.1
const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
struct MHD_Response *response;
char *path = NULL;
int ret;
// redirect from http://myserver:port/ to http://myserver:port/index.html
if (strcmp(url, "/") == 0) {
path = "index.html";
}
if (NULL == path) {
path = new char[strlen(&url[1]) + 1];
strcpy(path, &url[1]);
}
const char *www = TCHAR_TO_ANSI(*wwwStr);
// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(www) + strlen(path) + 1;
// allocate enough memory for the concatenated string:
char* concatString = new char[bufferSize];
// copy strings one and two over to the new buffer:
strcpy(concatString, www);
strcat(concatString, path);
FILE* f;
f = fopen(concatString, "rb");
if (f != NULL) {
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
response = MHD_create_response_from_buffer(strlen(where),
(void*)where, MHD_RESPMEM_PERSISTENT);
fclose(f);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
}
else {
const char *notExist = "<html><body>File not found !</body></html>";
response = MHD_create_response_from_buffer(strlen(notExist),
(void*)notExist, MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
}
MHD_destroy_response(response);
return ret;
}
int answer_to_connection(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method, // GET / POST / PUT ...
const char *version, // HTML version 1.1
const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
int ret;
struct MHD_Response *response;
char *username;
const char *realm = "someusername";
const char *password = "somepassword";
username = MHD_digest_auth_get_username(connection);
// username authentification
if (NULL == username) {
response = MHD_create_response_from_buffer(strlen(DENIED2), DENIED2, MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_auth_fail_response(connection, realm,
realm,
response,
MHD_NO);
MHD_destroy_response(response);
return ret;
}
// check username / password OK
ret = MHD_digest_auth_check(connection, realm,
username,
password,
300);
FString usernameFStr = ANSI_TO_TCHAR(username);
// bad username / password return invalid authentification
if ((ret == MHD_INVALID_NONCE) ||
(ret == MHD_NO))
{
response = MHD_create_response_from_buffer(strlen(DENIED2),
DENIED2,
MHD_RESPMEM_PERSISTENT);
if (NULL == response)
return MHD_NO;
ret = MHD_queue_auth_fail_response(connection, realm,
OPAQUE,
response,
(ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);
MHD_destroy_response(response);
UE_LOG(UT4WebAdmin, Warning, TEXT("User '%s' failed to authenticate."), *usernameFStr);
return ret;
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT("User '%s' authenticated."), *usernameFStr);
}
// USER AUTHENTICATED LET'S GO !
// TODO handle POST methods in the future
if ((0 != strcmp(method, MHD_HTTP_METHOD_GET)) &&
(0 != strcmp(method, MHD_HTTP_METHOD_HEAD)))
return MHD_NO;
if (strcmp(url, "/gameinfo") == 0) {
return handle_game_info(cls, connection, url, method, version, upload_data, upload_data_size, con_cls);
}
else {
return handle_serve_file(cls, connection, url, method, version, upload_data, upload_data_size, con_cls);
}
}
void UUT4WebAdmin::StartMicroHttp()
{
// SSL not working yet need some more investigation
if (WebHttpsEnabled) {
if (NULL == *WebServerCertificateFile || NULL == *WebServerKeyFile) {
UE_LOG(UT4WebAdmin, Warning, TEXT("Server key or certificate file is not set."));
return;
}
// openssl req -days 365 -out server.pem -new -x509 -key server.key
FILE* fcert_file = fopen(TCHAR_TO_ANSI(*WebServerCertificateFile), "r");
// openssl genrsa -out server.key 1024
FILE* fkey_file = fopen(TCHAR_TO_ANSI(*WebServerKeyFile), "r");
if (NULL != fcert_file && NULL != fkey_file) {
fseek(fcert_file, 0, SEEK_END);
size_t size = ftell(fcert_file);
char* cert_pem = new char[size];
rewind(fcert_file);
fread(cert_pem, sizeof(char), size, fcert_file);
fseek(fkey_file, 0, SEEK_END);
size_t size2 = ftell(fkey_file);
char* key_pem = new char[size2];
rewind(fkey_file);
fread(key_pem, sizeof(char), size2, fkey_file);
daemon = MHD_start_daemon(MHD_USE_AUTO | MHD_USE_SELECT_INTERNALLY | MHD_USE_TLS | MHD_USE_DEBUG, WebHttpPort, NULL, NULL,
&answer_to_connection, NULL,
MHD_OPTION_HTTPS_MEM_KEY, key_pem,
MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
MHD_OPTION_END);
}
if (NULL != fcert_file) {
fclose(fcert_file);
}
if (NULL != fkey_file) {
fclose(fkey_file);
}
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT("Starting HTTP server without SSL"));
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG, WebHttpPort, NULL, NULL,
&answer_to_connection, NULL, MHD_OPTION_END);
}
if (daemon == NULL) {
UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
UE_LOG(UT4WebAdmin, Warning, TEXT(" UT4WebAdmin failed to start http(s) server !"));
UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
UE_LOG(UT4WebAdmin, Log, TEXT(" UT4WebAdmin started at port: %i "), WebHttpPort);
UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
}
}
void UUT4WebAdmin::Stop()
{
if (NULL != daemon) {
MHD_stop_daemon(daemon);
}
}
void UUT4WebAdmin::Tick(float DeltaTime)
{
//poll(MGServer, 1);
// TODO
}
TStatId UUT4WebAdmin::GetStatId() const
{
RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdmin, STATGROUP_Tickables);
}
<commit_msg>simplified generic serve_json_file method<commit_after>#include "UT4WebAdmin.h"
#include "Base64.h"
#define UT4WA_PLUGIN_FOLDER "UT4WebAdmin"
#define UT4WA_WWW_FOLDER "www"
#define PAGE "<html><head><title>File not found</title></head><body>File not found</body></html>"
#define DENIED2 "<html><head><title>Acces denied</title></head><body>Access denied</body></html>"
#define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4"
UUT4WebAdmin::UUT4WebAdmin(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
daemon = nullptr;
GameMode = nullptr;
}
void UUT4WebAdmin::Init()
{
// Don't garbage collect me
SetFlags(RF_MarkAsRootSet);
if (WebHttpPort == 0)
{
WebHttpPort = 8080;
}
if (HeadAdminUsername.IsEmpty()) {
HeadAdminUsername = FString("webadmin");
}
if (HeadAdminPassword.IsEmpty()) {
HeadAdminPassword = FString("webadminpassword");
}
StartMicroHttp();
}
TSharedPtr<FJsonObject> GetGameInfoJSON()
{
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);;
// Get a reference of any object using the UTBaseGameMode
AUTBaseGameMode* BaseGameMode;
BaseGameMode = Cast<AUTBaseGameMode>(GWorld->GetAuthGameMode());
if (BaseGameMode) {
// GameMode
JsonObject->SetBoolField(TEXT("IsMatchInProgress"), BaseGameMode->IsMatchInProgress());
JsonObject->SetBoolField(TEXT("HasMatchEnded"), BaseGameMode->HasMatchEnded());
JsonObject->SetNumberField(TEXT("NumTravellingPlayers"), BaseGameMode->NumTravellingPlayers);
JsonObject->SetStringField(TEXT("NetworkNumber"), BaseGameMode->GetNetworkNumber());
JsonObject->SetStringField(TEXT("MatchState"), BaseGameMode->GetMatchState().ToString());
// UTBaseGameMode
JsonObject->SetStringField(TEXT("ServerInstanceID"), BaseGameMode->ServerInstanceID);
JsonObject->SetStringField(TEXT("ServerInstanceGUID"), BaseGameMode->ServerInstanceGUID.ToString()); // The Unique ID for this game instance.
JsonObject->SetStringField(TEXT("ContextGUID"), BaseGameMode->ContextGUID.ToString()); // ?
JsonObject->SetStringField(TEXT("ServerPassword"), BaseGameMode->ServerPassword);
JsonObject->SetStringField(TEXT("SpectatePassword"), BaseGameMode->SpectatePassword);
JsonObject->SetBoolField(TEXT("bRequirePassword"), BaseGameMode->bRequirePassword);
JsonObject->SetStringField(TEXT("DisplayName"), BaseGameMode->DisplayName.ToString());
JsonObject->SetNumberField(TEXT("MinAllowedRank"), BaseGameMode->MinAllowedRank);
JsonObject->SetNumberField(TEXT("MaxAllowedRank"), BaseGameMode->MaxAllowedRank);
JsonObject->SetBoolField(TEXT("bTrainingGround"), BaseGameMode->bTrainingGround);
JsonObject->SetNumberField(TEXT("NumPlayers"), BaseGameMode->GetNumPlayers());
JsonObject->SetNumberField(TEXT("NumMatches"), BaseGameMode->GetNumMatches()); // 1 if dedi server else [0, .., X] range for hubs/lobbies
JsonObject->SetNumberField(TEXT("CurrentPlaylistId"), BaseGameMode->CurrentPlaylistId); // no idea what this is about
JsonObject->SetBoolField(TEXT("bPrivateMatch"), BaseGameMode->bPrivateMatch);
JsonObject->SetStringField(TEXT("RankedLeagueName"), BaseGameMode->GetRankedLeagueName()); // always empty for the moment
JsonObject->SetBoolField(TEXT("SupportsInstantReplay"), BaseGameMode->SupportsInstantReplay());
JsonObject->SetBoolField(TEXT("bIsLANGame"), BaseGameMode->bIsLANGame);
if (BaseGameMode->IsLobbyServer())
{
AUTLobbyGameMode* LobbyGameMode;
LobbyGameMode = GWorld->GetAuthGameMode<AUTLobbyGameMode>();
if (LobbyGameMode)
{
JsonObject->SetStringField(TEXT("ServType"), TEXT("dedis"));
// TODO get instance data
}
}
}
return JsonObject;
}
// Method to serve json file to client
int serve_json_file(struct MHD_Connection *connection, TSharedPtr<FJsonObject> json)
{
int ret;
struct MHD_Response *response;
FString JsonText;
TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&JsonText);
FJsonSerializer::Serialize(json.ToSharedRef(), Writer);
std::string tmpStr = TCHAR_TO_ANSI(*JsonText);
char *jsonChar = new char[tmpStr.length() + 1];
strcpy(jsonChar, tmpStr.c_str());
response = MHD_create_response_from_buffer(strlen(jsonChar),
(void*)jsonChar, MHD_RESPMEM_PERSISTENT);
MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, "application/json");
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
}
int handle_game_info(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
if (strcmp(method, MHD_HTTP_METHOD_GET) == 0) {
TSharedPtr<FJsonObject> matchInfoJson = GetGameInfoJSON();
return serve_json_file(connection, matchInfoJson);
}
else {
// TODO handle post request for kick/ban/modify server info ...
}
return MHD_NO;
}
// Server files from root folder
const FString wwwStr = FPaths::GamePluginsDir() + UT4WA_PLUGIN_FOLDER + "/" + UT4WA_WWW_FOLDER + "/";
int handle_serve_file(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method, // GET / POST / PUT ...
const char *version, // HTML version 1.1
const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
struct MHD_Response *response;
char *path = NULL;
int ret;
// redirect from http://myserver:port/ to http://myserver:port/index.html
if (strcmp(url, "/") == 0) {
path = "index.html";
}
if (NULL == path) {
path = new char[strlen(&url[1]) + 1];
strcpy(path, &url[1]);
}
const char *www = TCHAR_TO_ANSI(*wwwStr);
// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(www) + strlen(path) + 1;
// allocate enough memory for the concatenated string:
char* concatString = new char[bufferSize];
// copy strings one and two over to the new buffer:
strcpy(concatString, www);
strcat(concatString, path);
FILE* f;
f = fopen(concatString, "rb");
if (f != NULL) {
// Determine file size
fseek(f, 0, SEEK_END);
size_t size = ftell(f);
char* where = new char[size];
rewind(f);
fread(where, sizeof(char), size, f);
response = MHD_create_response_from_buffer(strlen(where),
(void*)where, MHD_RESPMEM_PERSISTENT);
fclose(f);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
}
else {
const char *notExist = "<html><body>File not found !</body></html>";
response = MHD_create_response_from_buffer(strlen(notExist),
(void*)notExist, MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
}
MHD_destroy_response(response);
return ret;
}
int answer_to_connection(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method, // GET / POST / PUT ...
const char *version, // HTML version 1.1
const char *upload_data,
size_t *upload_data_size, void **con_cls)
{
int ret;
struct MHD_Response *response;
char *username;
const char *realm = "someusername";
const char *password = "somepassword";
username = MHD_digest_auth_get_username(connection);
// username authentification
if (NULL == username) {
response = MHD_create_response_from_buffer(strlen(DENIED2), DENIED2, MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_auth_fail_response(connection, realm,
realm,
response,
MHD_NO);
MHD_destroy_response(response);
return ret;
}
// check username / password OK
ret = MHD_digest_auth_check(connection, realm,
username,
password,
300);
FString usernameFStr = ANSI_TO_TCHAR(username);
// bad username / password return invalid authentification
if ((ret == MHD_INVALID_NONCE) ||
(ret == MHD_NO))
{
response = MHD_create_response_from_buffer(strlen(DENIED2),
DENIED2,
MHD_RESPMEM_PERSISTENT);
if (NULL == response)
return MHD_NO;
ret = MHD_queue_auth_fail_response(connection, realm,
OPAQUE,
response,
(ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO);
MHD_destroy_response(response);
UE_LOG(UT4WebAdmin, Warning, TEXT("User '%s' failed to authenticate."), *usernameFStr);
return ret;
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT("User '%s' authenticated."), *usernameFStr);
}
// USER AUTHENTICATED LET'S GO !
// TODO handle POST methods in the future
if ((0 != strcmp(method, MHD_HTTP_METHOD_GET)) &&
(0 != strcmp(method, MHD_HTTP_METHOD_HEAD)))
return MHD_NO;
if (strcmp(url, "/gameinfo") == 0) {
return handle_game_info(cls, connection, url, method, version, upload_data, upload_data_size, con_cls);
}
else {
return handle_serve_file(cls, connection, url, method, version, upload_data, upload_data_size, con_cls);
}
}
void UUT4WebAdmin::StartMicroHttp()
{
// SSL not working yet need some more investigation
if (WebHttpsEnabled) {
if (NULL == *WebServerCertificateFile || NULL == *WebServerKeyFile) {
UE_LOG(UT4WebAdmin, Warning, TEXT("Server key or certificate file is not set."));
return;
}
// openssl req -days 365 -out server.pem -new -x509 -key server.key
FILE* fcert_file = fopen(TCHAR_TO_ANSI(*WebServerCertificateFile), "r");
// openssl genrsa -out server.key 1024
FILE* fkey_file = fopen(TCHAR_TO_ANSI(*WebServerKeyFile), "r");
if (NULL != fcert_file && NULL != fkey_file) {
fseek(fcert_file, 0, SEEK_END);
size_t size = ftell(fcert_file);
char* cert_pem = new char[size];
rewind(fcert_file);
fread(cert_pem, sizeof(char), size, fcert_file);
fseek(fkey_file, 0, SEEK_END);
size_t size2 = ftell(fkey_file);
char* key_pem = new char[size2];
rewind(fkey_file);
fread(key_pem, sizeof(char), size2, fkey_file);
daemon = MHD_start_daemon(MHD_USE_AUTO | MHD_USE_SELECT_INTERNALLY | MHD_USE_TLS | MHD_USE_DEBUG, WebHttpPort, NULL, NULL,
&answer_to_connection, NULL,
MHD_OPTION_HTTPS_MEM_KEY, key_pem,
MHD_OPTION_HTTPS_MEM_CERT, cert_pem,
MHD_OPTION_END);
}
if (NULL != fcert_file) {
fclose(fcert_file);
}
if (NULL != fkey_file) {
fclose(fkey_file);
}
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT("Starting HTTP server without SSL"));
daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG, WebHttpPort, NULL, NULL,
&answer_to_connection, NULL, MHD_OPTION_END);
}
if (daemon == NULL) {
UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
UE_LOG(UT4WebAdmin, Warning, TEXT(" UT4WebAdmin failed to start http(s) server !"));
UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
}
else {
UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
UE_LOG(UT4WebAdmin, Log, TEXT(" UT4WebAdmin started at port: %i "), WebHttpPort);
UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *"));
}
}
void UUT4WebAdmin::Stop()
{
if (NULL != daemon) {
MHD_stop_daemon(daemon);
}
}
void UUT4WebAdmin::Tick(float DeltaTime)
{
//poll(MGServer, 1);
// TODO
}
TStatId UUT4WebAdmin::GetStatId() const
{
RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdmin, STATGROUP_Tickables);
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <iostream>
#include "messaging.hpp"
#include "impl_zmq.hpp"
#include "common/params.h"
#include "common/swaglog.h"
#include "common/timing.h"
#include "common/util.h"
#include "ublox_msg.h"
using namespace ublox;
extern volatile sig_atomic_t do_exit;
void write_file(std::string fpath, uint8_t *to_write, int length) {
FILE* f = fopen(fpath.c_str(), "wb");
if (!f) {
std::cout << "Open " << fpath << " failed" << std::endl;
return;
}
fwrite(to_write, length, 1, f);
fclose(f);
}
static size_t len = 0U;
static size_t consumed = 0U;
static uint8_t *data = NULL;
static int save_idx = 0;
static std::string prefix;
Message * poll_ubloxraw_msg(Poller * poller) {
assert(poller);
size_t consuming = min(len - consumed, 128);
if(consumed < len) {
// create message
MessageBuilder msg_builder;
auto ublox_raw = msg_builder.initEvent().initUbloxRaw(consuming);
memcpy(ublox_raw.begin(), (void *)(data + consumed), consuming);
auto bytes = msg_builder.toBytes();
Message * msg = new ZMQMessage();
msg->init((char*)bytes.begin(), bytes.size());
consumed += consuming;
return msg;
} else {
do_exit = 1;
return NULL;
}
}
int send_gps_event(PubSocket *s, const void *buf, size_t length) {
assert(s);
write_file(prefix + "/" + std::to_string(save_idx), (uint8_t *)buf, length);
save_idx++;
return length;
}
int main(int argc, char** argv) {
if(argc < 3) {
printf("Format: ubloxd_test stream_file_path save_prefix\n");
return 0;
}
// Parse 11360 msgs, generate 9452 events
data = (uint8_t *)read_file(argv[1], &len);
if(data == NULL) {
LOGE("Read file %s failed\n", argv[1]);
return -1;
}
prefix = argv[2];
ubloxd_main(poll_ubloxraw_msg, send_gps_event);
free(data);
printf("Generated %d cereal events\n", save_idx);
if(save_idx != 9452) {
printf("Event count error: %d\n", save_idx);
return -1;
}
return 0;
}
<commit_msg>Fix ubloxd test compilation (#20101)<commit_after>#include <stdio.h>
#include <iostream>
#include <cassert>
#include <algorithm>
#include "messaging.hpp"
#include "impl_zmq.hpp"
#include "common/params.h"
#include "common/swaglog.h"
#include "common/timing.h"
#include "common/util.h"
#include "ublox_msg.h"
using namespace ublox;
extern volatile sig_atomic_t do_exit;
void write_file(std::string fpath, uint8_t *to_write, int length) {
FILE* f = fopen(fpath.c_str(), "wb");
if (!f) {
std::cout << "Open " << fpath << " failed" << std::endl;
return;
}
fwrite(to_write, length, 1, f);
fclose(f);
}
static size_t len = 0U;
static size_t consumed = 0U;
static uint8_t *data = NULL;
static int save_idx = 0;
static std::string prefix;
Message * poll_ubloxraw_msg(Poller * poller) {
assert(poller);
size_t consuming = std::min((int)(len - consumed), 128);
if(consumed < len) {
// create message
MessageBuilder msg_builder;
auto ublox_raw = msg_builder.initEvent().initUbloxRaw(consuming);
memcpy(ublox_raw.begin(), (void *)(data + consumed), consuming);
auto bytes = msg_builder.toBytes();
Message * msg = new ZMQMessage();
msg->init((char*)bytes.begin(), bytes.size());
consumed += consuming;
return msg;
} else {
do_exit = 1;
return NULL;
}
}
int send_gps_event(PubSocket *s, const void *buf, size_t length) {
assert(s);
write_file(prefix + "/" + std::to_string(save_idx), (uint8_t *)buf, length);
save_idx++;
return length;
}
int main(int argc, char** argv) {
if(argc < 3) {
printf("Format: ubloxd_test stream_file_path save_prefix\n");
return 0;
}
// Parse 11360 msgs, generate 9452 events
data = (uint8_t *)read_file(argv[1], &len);
if(data == NULL) {
LOGE("Read file %s failed\n", argv[1]);
return -1;
}
prefix = argv[2];
ubloxd_main(poll_ubloxraw_msg, send_gps_event);
free(data);
printf("Generated %d cereal events\n", save_idx);
if(save_idx != 9452) {
printf("Event count error: %d\n", save_idx);
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
** Author(s):
** - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <iostream>
#include <alcommon-ng/collections/variables_list.hpp>
#include <alcommon-ng/messaging/call_definition.hpp>
#include <alcommon-ng/messaging/result_definition.hpp>
#include <alcommon-ng/serialization/thrift/serialize.hpp>
namespace AL {
namespace Serialization {
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const int &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(int)" << std::endl);
protocol->writeI32(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const float &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(float)" << std::endl);
//protocol->writeDouble(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const double &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(double)" << std::endl);
protocol->writeDouble(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const bool &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(bool)" << std::endl);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const std::string &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(std::string)" << std::endl);
protocol->writeString(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::EmptyValue &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(EmptyValue)" << std::endl);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::ResultDefinition &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(ResultDefinition)" << std::endl);
//protocol->readWriteMessage();
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol,const AL::Messaging::VariableValue &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(VariablesValue)" << std::endl);
protocol->writeStructBegin("VariableValue");
protocol->writeFieldBegin("which", ::apache::thrift::protocol::T_I32, 1);
VariableValueSerializeVisitor visitor(protocol);
t.value().apply_visitor(visitor);
protocol->writeFieldEnd();
protocol->writeStructEnd();
//thriftSerialize(protocol, dynamic_cast<std::list< AL::Messaging::VariableValue >(t));
}
// void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::VariablesList &t, int field)
// {
// DEBUGOUT_THRIFT_SER(std::cout << "Serialize(VariablesList)" << std::endl);
// thriftSerialize(protocol, dynamic_cast<const std::vector< AL::Messaging::VariableValue > &>(t));
// }
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::CallDefinition &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(CallDefinition)" << std::endl);
protocol->writeStructBegin("CallDefinition");
protocol->writeFieldBegin("MethodName", ::apache::thrift::protocol::T_STRING, 2);
protocol->writeString(t.methodName());
protocol->writeFieldEnd();
protocol->writeFieldBegin("ModuleName", ::apache::thrift::protocol::T_STRING, 3);
protocol->writeString(t.moduleName());
protocol->writeFieldEnd();
protocol->writeFieldBegin("Params", ::apache::thrift::protocol::T_STRUCT, 4);
thriftSerialize(protocol, t.args());
protocol->writeFieldEnd();
protocol->writeStructEnd();
}
}
}
<commit_msg>thrift: fix compil<commit_after>/*
** Author(s):
** - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <iostream>
#include <alcommon-ng/collections/variables_list.hpp>
#include <alcommon-ng/messaging/call_definition.hpp>
#include <alcommon-ng/messaging/result_definition.hpp>
#include <alcommon-ng/serialization/thrift/serialize.hpp>
namespace AL {
namespace Serialization {
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const int &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(int)" << std::endl);
protocol->writeI32(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const float &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(float)" << std::endl);
//protocol->writeDouble(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const double &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(double)" << std::endl);
protocol->writeDouble(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const bool &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(bool)" << std::endl);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol* protocol, const std::string &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(std::string)" << std::endl);
protocol->writeString(t);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::EmptyValue &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(EmptyValue)" << std::endl);
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::ResultDefinition &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(ResultDefinition)" << std::endl);
//protocol->readWriteMessage();
}
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol,const AL::Messaging::VariableValue &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(VariablesValue)" << std::endl);
protocol->writeStructBegin("VariableValue");
protocol->writeFieldBegin("which", ::apache::thrift::protocol::T_I32, 1);
VariableValueSerializeVisitor visitor(protocol);
t.value().apply_visitor(visitor);
protocol->writeFieldEnd();
protocol->writeStructEnd();
//thriftSerialize(protocol, dynamic_cast<std::list< AL::Messaging::VariableValue >(t));
}
// void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::VariablesList &t, int field)
// {
// DEBUGOUT_THRIFT_SER(std::cout << "Serialize(VariablesList)" << std::endl);
// thriftSerialize(protocol, dynamic_cast<const std::vector< AL::Messaging::VariableValue > &>(t));
// }
void thriftSerialize(::apache::thrift::protocol::TProtocol *protocol, const AL::Messaging::CallDefinition &t, int field)
{
DEBUGOUT_THRIFT_SER(std::cout << "Serialize(CallDefinition)" << std::endl);
protocol->writeStructBegin("CallDefinition");
protocol->writeFieldBegin("MethodName", ::apache::thrift::protocol::T_STRING, 2);
protocol->writeString(t.methodName());
protocol->writeFieldEnd();
protocol->writeFieldBegin("Params", ::apache::thrift::protocol::T_STRUCT, 4);
thriftSerialize(protocol, t.args());
protocol->writeFieldEnd();
protocol->writeStructEnd();
}
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the Electron Orbital Explorer. The Electron
* Orbital Explorer is distributed under the Simplified BSD License
* (also called the "BSD 2-Clause License"), in hopes that these
* rendering techniques might be used by other programmers in
* applications such as scientific visualization, video gaming, and so
* on. If you find value in this software and use its technologies for
* another purpose, I would love to hear back from you at bjthinks (at)
* gmail (dot) com. If you improve this software and agree to release
* your modifications under the below license, I encourage you to fork
* the development tree on github and push your modifications. The
* Electron Orbital Explorer's development URL is:
* https://github.com/bjthinks/orbital-explorer
* (This paragraph is not part of the software license and may be
* removed.)
*
* Copyright (c) 2013, Brian W. Johnson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <cstdlib>
#include <SDL.h>
#include "config.hh"
#include "glprocs.hh"
#include "render.hh"
#include "viewport.hh"
#include "controls.hh"
#include "icon.hh"
#include "widget.hh"
#include "parameters.hh"
#include "ui.hh"
using namespace std;
void set_sdl_attr(SDL_GLattr attr, int value)
{
if (SDL_GL_SetAttribute(attr, value) < 0) {
fprintf(stderr, "SDL_GL_SetAttribute(): %s\n", SDL_GetError());
exit(1);
}
}
static int go()
{
//
// Initialize SDL
//
if (SDL_Init(SDL_INIT_VIDEO) < 0 ) {
fprintf(stderr, "SDL_Init(): %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Quit);
// Request at least 24-bit color
set_sdl_attr(SDL_GL_RED_SIZE, 8);
set_sdl_attr(SDL_GL_GREEN_SIZE, 8);
set_sdl_attr(SDL_GL_BLUE_SIZE, 8);
// Tell OpenGL we don't need a depth or alpha buffer
set_sdl_attr(SDL_GL_DEPTH_SIZE, 0);
set_sdl_attr(SDL_GL_ALPHA_SIZE, 0);
// Request double buffering
set_sdl_attr(SDL_GL_DOUBLEBUFFER, 1);
#ifdef __APPLE__
// Apple defaults to an OpenGL 2.1 Compatibility context unless you
// specify otherwise.
set_sdl_attr(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
set_sdl_attr(SDL_GL_CONTEXT_MINOR_VERSION, 2);
set_sdl_attr(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
Viewport viewport(640, 480);
// Create a window
SDL_Window *window =
SDL_CreateWindow("Electron Orbital Explorer",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
viewport.getWidth(), viewport.getHeight(),
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
fprintf(stderr, "SDL_CreateWindow(): %s\n", SDL_GetError());
exit(1);
}
SDL_Surface *icon = getIcon();
SDL_SetWindowIcon(window, icon);
SDL_FreeSurface(icon);
// Create an OpenGL context associated with the window
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
if (!glcontext) {
fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
exit(1);
}
//
// Get access to OpenGL functions
//
initGLProcs();
//
// Initialize orbital rendering pipeline
//
initialize();
resizeTextures(viewport);
//
// Initialize controls
//
initControls(viewport);
//
// Main loop
//
Camera camera;
SDL_Event event;
bool show_controls = true;
Container ui;
CameraController cc(ui, camera);
cc.resize(viewport.getWidth(), viewport.getHeight());
while (1) {
// Clear the event queue, then redraw a frame
while (SDL_PollEvent(&event)) {
// Can controls handle the event, or is it a resize event?
int handled = false;
if (show_controls || event.type == SDL_WINDOWEVENT)
handled = handleControls(event);
// If event hasn't been fully handled by controls, process it
if (!handled) {
switch (event.type) {
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
viewport.resize(event.window.data1, event.window.data2);
cc.resize(event.window.data1, event.window.data2);
resizeTextures(viewport);
}
break;
case SDL_MOUSEBUTTONDOWN:
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Click(event.button.x,
viewport.getHeight() - 1 - event.button.y));
break;
case SDL_MOUSEBUTTONUP:
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Unclick(event.button.x,
viewport.getHeight() - 1 - event.button.y));
break;
case SDL_MOUSEMOTION:
{
int buttons = NoButton;
if (event.motion.state & SDL_BUTTON_LMASK)
buttons |= LeftButton;
if (event.motion.state & SDL_BUTTON_MMASK)
buttons |= MiddleButton;
if (event.motion.state & SDL_BUTTON_RMASK)
buttons |= RightButton;
if (buttons != NoButton)
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Drag(event.motion.x, event.motion.y,
buttons, event.motion.xrel, event.motion.yrel));
else
; // Maybe add a Move event later -- don't need it now
}
break;
case SDL_MOUSEWHEEL:
cc.handleWheel(Wheel(event.wheel.y));
break;
case SDL_KEYDOWN:
int key, mod;
key = event.key.keysym.sym;
// Ignore the Num Lock key state
mod = event.key.keysym.mod & ~KMOD_NUM;
if (mod == KMOD_NONE) {
switch (key) {
case SDLK_LEFT:
camera.rotate(-DISCRETE_ROTATION_SIZE, 0);
break;
case SDLK_RIGHT:
camera.rotate(DISCRETE_ROTATION_SIZE, 0);
break;
case SDLK_UP:
camera.rotate(0, -DISCRETE_ROTATION_SIZE);
break;
case SDLK_DOWN:
camera.rotate(0, DISCRETE_ROTATION_SIZE);
break;
case SDLK_PAGEUP:
camera.zoom(-DISCRETE_ZOOM_SIZE);
break;
case SDLK_PAGEDOWN:
camera.zoom(DISCRETE_ZOOM_SIZE);
break;
case SDLK_F11:
static int fullscreen_mode = 0;
fullscreen_mode ^= SDL_WINDOW_FULLSCREEN_DESKTOP;
SDL_SetWindowFullscreen(window, fullscreen_mode);
break;
case SDLK_F10:
show_controls = !show_controls;
break;
default:
break;
}
}
else if (mod == KMOD_LSHIFT || mod == KMOD_RSHIFT ||
mod == KMOD_SHIFT) {
switch (key) {
case SDLK_LEFT:
camera.spin(DISCRETE_ROTATION_SIZE);
break;
case SDLK_RIGHT:
camera.spin(-DISCRETE_ROTATION_SIZE);
break;
case SDLK_UP:
camera.zoom(-DISCRETE_ZOOM_SIZE);
break;
case SDLK_DOWN:
camera.zoom(DISCRETE_ZOOM_SIZE);
break;
default:
break;
}
}
break;
case SDL_QUIT:
return 0;
}
}
}
display(viewport, camera);
if (show_controls)
drawControls();
ui.draw(Region(0, 0, viewport.getWidth(), viewport.getHeight()));
SDL_GL_SwapWindow(window);
}
return 0;
}
int main(int argc, char *argv[])
{
#ifdef __APPLE__
//
// Compensate for a bug in some versions of AntTweakBar. ATB
// attempts to dynamically link with the OpenGL framework without
// specifying a full pathname. Setting DYLD_LIBRARY_PATH fixes the
// issue, but this environment variable must be set prior to running
// the app. So we check it, and, if needed, set it properly and
// re-exec ourself. :-(
//
const char *pathvar = "DYLD_LIBRARY_PATH";
string new_path("/System/Library/Frameworks/OpenGL.framework/"
"Versions/Current");
const char *actual_path_cstr = getenv(pathvar);
string actual_path(actual_path_cstr ? actual_path_cstr : "");
if (new_path != actual_path.substr(0, new_path.length()) &&
// Try to prevent an infinite loop, in case something goes wrong
actual_path.length() < 4000) {
if (actual_path != "")
new_path += ":" + actual_path;
setenv(pathvar, new_path.c_str(), 1);
execvp(argv[0], argv);
// If the exec fails, the best we can do is simply continue...
}
#endif
const string polite_error_message =
"I\'m sorry, Electron Orbital Explorer has crashed.\n"
"This should never happen and is a bug in the program.\n"
"Please copy and paste the following error message,\n"
"and send it to the developer.\n";
try {
return go();
} catch (exception &e) {
cerr << polite_error_message;
cerr << e.what() << "\n";
return 1;
} catch (...) {
cerr << polite_error_message;
cerr << "Exception: unknown uncaught object thrown\n";
return 1;
}
}
<commit_msg>Enable multisample antialiasing for user interface<commit_after>/*
* This file is part of the Electron Orbital Explorer. The Electron
* Orbital Explorer is distributed under the Simplified BSD License
* (also called the "BSD 2-Clause License"), in hopes that these
* rendering techniques might be used by other programmers in
* applications such as scientific visualization, video gaming, and so
* on. If you find value in this software and use its technologies for
* another purpose, I would love to hear back from you at bjthinks (at)
* gmail (dot) com. If you improve this software and agree to release
* your modifications under the below license, I encourage you to fork
* the development tree on github and push your modifications. The
* Electron Orbital Explorer's development URL is:
* https://github.com/bjthinks/orbital-explorer
* (This paragraph is not part of the software license and may be
* removed.)
*
* Copyright (c) 2013, Brian W. Johnson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <cstdlib>
#include <SDL.h>
#include "config.hh"
#include "glprocs.hh"
#include "render.hh"
#include "viewport.hh"
#include "controls.hh"
#include "icon.hh"
#include "widget.hh"
#include "parameters.hh"
#include "ui.hh"
using namespace std;
void set_sdl_attr(SDL_GLattr attr, int value)
{
if (SDL_GL_SetAttribute(attr, value) < 0) {
fprintf(stderr, "SDL_GL_SetAttribute(): %s\n", SDL_GetError());
exit(1);
}
}
static int go()
{
//
// Initialize SDL
//
if (SDL_Init(SDL_INIT_VIDEO) < 0 ) {
fprintf(stderr, "SDL_Init(): %s\n", SDL_GetError());
return 1;
}
atexit(SDL_Quit);
// Request at least 24-bit color
set_sdl_attr(SDL_GL_RED_SIZE, 8);
set_sdl_attr(SDL_GL_GREEN_SIZE, 8);
set_sdl_attr(SDL_GL_BLUE_SIZE, 8);
// Tell OpenGL we don't need a depth or alpha buffer
set_sdl_attr(SDL_GL_DEPTH_SIZE, 0);
set_sdl_attr(SDL_GL_ALPHA_SIZE, 0);
// Request double buffering
set_sdl_attr(SDL_GL_DOUBLEBUFFER, 1);
// Use a multisampled default framebuffer
set_sdl_attr(SDL_GL_MULTISAMPLEBUFFERS, 1);
set_sdl_attr(SDL_GL_MULTISAMPLESAMPLES, 4);
#ifdef __APPLE__
// Apple defaults to an OpenGL 2.1 Compatibility context unless you
// specify otherwise.
set_sdl_attr(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
set_sdl_attr(SDL_GL_CONTEXT_MINOR_VERSION, 2);
set_sdl_attr(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
Viewport viewport(640, 480);
// Create a window
SDL_Window *window =
SDL_CreateWindow("Electron Orbital Explorer",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
viewport.getWidth(), viewport.getHeight(),
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if (!window) {
fprintf(stderr, "SDL_CreateWindow(): %s\n", SDL_GetError());
exit(1);
}
SDL_Surface *icon = getIcon();
SDL_SetWindowIcon(window, icon);
SDL_FreeSurface(icon);
// Create an OpenGL context associated with the window
SDL_GLContext glcontext = SDL_GL_CreateContext(window);
if (!glcontext) {
fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
exit(1);
}
//
// Get access to OpenGL functions
//
initGLProcs();
//
// Initialize orbital rendering pipeline
//
initialize();
resizeTextures(viewport);
//
// Initialize controls
//
initControls(viewport);
//
// Main loop
//
Camera camera;
SDL_Event event;
bool show_controls = true;
Container ui;
CameraController cc(ui, camera);
cc.resize(viewport.getWidth(), viewport.getHeight());
while (1) {
// Clear the event queue, then redraw a frame
while (SDL_PollEvent(&event)) {
// Can controls handle the event, or is it a resize event?
int handled = false;
if (show_controls || event.type == SDL_WINDOWEVENT)
handled = handleControls(event);
// If event hasn't been fully handled by controls, process it
if (!handled) {
switch (event.type) {
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
viewport.resize(event.window.data1, event.window.data2);
cc.resize(event.window.data1, event.window.data2);
resizeTextures(viewport);
}
break;
case SDL_MOUSEBUTTONDOWN:
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Click(event.button.x,
viewport.getHeight() - 1 - event.button.y));
break;
case SDL_MOUSEBUTTONUP:
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Unclick(event.button.x,
viewport.getHeight() - 1 - event.button.y));
break;
case SDL_MOUSEMOTION:
{
int buttons = NoButton;
if (event.motion.state & SDL_BUTTON_LMASK)
buttons |= LeftButton;
if (event.motion.state & SDL_BUTTON_MMASK)
buttons |= MiddleButton;
if (event.motion.state & SDL_BUTTON_RMASK)
buttons |= RightButton;
if (buttons != NoButton)
ui.handle(Region(0, 0, viewport.getWidth(), viewport.getHeight()),
Drag(event.motion.x, event.motion.y,
buttons, event.motion.xrel, event.motion.yrel));
else
; // Maybe add a Move event later -- don't need it now
}
break;
case SDL_MOUSEWHEEL:
cc.handleWheel(Wheel(event.wheel.y));
break;
case SDL_KEYDOWN:
int key, mod;
key = event.key.keysym.sym;
// Ignore the Num Lock key state
mod = event.key.keysym.mod & ~KMOD_NUM;
if (mod == KMOD_NONE) {
switch (key) {
case SDLK_LEFT:
camera.rotate(-DISCRETE_ROTATION_SIZE, 0);
break;
case SDLK_RIGHT:
camera.rotate(DISCRETE_ROTATION_SIZE, 0);
break;
case SDLK_UP:
camera.rotate(0, -DISCRETE_ROTATION_SIZE);
break;
case SDLK_DOWN:
camera.rotate(0, DISCRETE_ROTATION_SIZE);
break;
case SDLK_PAGEUP:
camera.zoom(-DISCRETE_ZOOM_SIZE);
break;
case SDLK_PAGEDOWN:
camera.zoom(DISCRETE_ZOOM_SIZE);
break;
case SDLK_F11:
static int fullscreen_mode = 0;
fullscreen_mode ^= SDL_WINDOW_FULLSCREEN_DESKTOP;
SDL_SetWindowFullscreen(window, fullscreen_mode);
break;
case SDLK_F10:
show_controls = !show_controls;
break;
default:
break;
}
}
else if (mod == KMOD_LSHIFT || mod == KMOD_RSHIFT ||
mod == KMOD_SHIFT) {
switch (key) {
case SDLK_LEFT:
camera.spin(DISCRETE_ROTATION_SIZE);
break;
case SDLK_RIGHT:
camera.spin(-DISCRETE_ROTATION_SIZE);
break;
case SDLK_UP:
camera.zoom(-DISCRETE_ZOOM_SIZE);
break;
case SDLK_DOWN:
camera.zoom(DISCRETE_ZOOM_SIZE);
break;
default:
break;
}
}
break;
case SDL_QUIT:
return 0;
}
}
}
display(viewport, camera);
if (show_controls)
drawControls();
ui.draw(Region(0, 0, viewport.getWidth(), viewport.getHeight()));
SDL_GL_SwapWindow(window);
}
return 0;
}
int main(int argc, char *argv[])
{
#ifdef __APPLE__
//
// Compensate for a bug in some versions of AntTweakBar. ATB
// attempts to dynamically link with the OpenGL framework without
// specifying a full pathname. Setting DYLD_LIBRARY_PATH fixes the
// issue, but this environment variable must be set prior to running
// the app. So we check it, and, if needed, set it properly and
// re-exec ourself. :-(
//
const char *pathvar = "DYLD_LIBRARY_PATH";
string new_path("/System/Library/Frameworks/OpenGL.framework/"
"Versions/Current");
const char *actual_path_cstr = getenv(pathvar);
string actual_path(actual_path_cstr ? actual_path_cstr : "");
if (new_path != actual_path.substr(0, new_path.length()) &&
// Try to prevent an infinite loop, in case something goes wrong
actual_path.length() < 4000) {
if (actual_path != "")
new_path += ":" + actual_path;
setenv(pathvar, new_path.c_str(), 1);
execvp(argv[0], argv);
// If the exec fails, the best we can do is simply continue...
}
#endif
const string polite_error_message =
"I\'m sorry, Electron Orbital Explorer has crashed.\n"
"This should never happen and is a bug in the program.\n"
"Please copy and paste the following error message,\n"
"and send it to the developer.\n";
try {
return go();
} catch (exception &e) {
cerr << polite_error_message;
cerr << e.what() << "\n";
return 1;
} catch (...) {
cerr << polite_error_message;
cerr << "Exception: unknown uncaught object thrown\n";
return 1;
}
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "exceptions.hpp"
#include "wamp_message.hpp"
#include "wamp_transport_handler.hpp"
#include <boost/asio/buffer.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <system_error>
namespace autobahn {
template <class Socket>
wamp_rawsocket_transport<Socket>::wamp_rawsocket_transport(
boost::asio::io_service& io_service,
const endpoint_type& remote_endpoint,
bool debug_enabled)
: wamp_transport()
, m_socket(io_service)
, m_remote_endpoint(remote_endpoint)
, m_connect()
, m_disconnect()
, m_handshake_buffer()
, m_message_length(0)
, m_message_unpacker()
, m_debug_enabled(debug_enabled)
{
memset(m_handshake_buffer, 0, sizeof(m_handshake_buffer));
}
template <class Socket>
boost::future<void> wamp_rawsocket_transport<Socket>::connect()
{
if (m_socket.is_open()) {
m_connect.set_exception(boost::copy_exception(network_error("network transport already connected")));
return m_connect.get_future();
}
std::weak_ptr<wamp_rawsocket_transport<Socket>> weak_self = this->shared_from_this();
auto connect_handler = [=](const boost::system::error_code& error_code) {
auto shared_self = weak_self.lock();
if (!shared_self) {
return;
}
if (error_code) {
m_connect.set_exception(boost::copy_exception(
std::system_error(error_code.value(), std::system_category(), "connect")));
return;
}
// FIXME: There should be a wamp_rawsocket_properties object or something
// similar that can be passed in to help deal with overiding these
// handshake parameters.
//
// Send the initial handshake packet informing the server which
// serialization format we wish to use, and our maximum message size.
m_handshake_buffer[0] = 0x7F; // magic byte
m_handshake_buffer[1] = 0xF2; // we are ready to receive messages up to 2**24 octets and encoded using MsgPack
m_handshake_buffer[2] = 0x00; // reserved
m_handshake_buffer[3] = 0x00; // reserved
boost::asio::write(
m_socket,
boost::asio::buffer(m_handshake_buffer, sizeof(m_handshake_buffer)));
auto handshake_reply = [=](
const boost::system::error_code& error,
std::size_t bytes_transferred) {
auto shared_self = weak_self.lock();
if (shared_self) {
handshake_reply_handler(error, bytes_transferred);
}
};
try {
// Read the 4-byte handshake reply from the server
boost::asio::async_read(
m_socket,
boost::asio::buffer(m_handshake_buffer, sizeof(m_handshake_buffer)),
handshake_reply);
} catch (const std::exception& e) {
m_connect.set_exception(boost::copy_exception(e));
}
};
m_socket.async_connect(m_remote_endpoint, connect_handler);
return m_connect.get_future();
}
template <class Socket>
boost::future<void> wamp_rawsocket_transport<Socket>::disconnect()
{
if (!m_socket.is_open()) {
throw network_error("network transport already disconnected");
}
m_socket.close();
m_disconnect.set_value();
return m_disconnect.get_future();
}
template <class Socket>
bool wamp_rawsocket_transport<Socket>::is_connected() const
{
return m_socket.is_open();
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::send_message(wamp_message&& message)
{
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
packer.pack(message.fields());
// Write the length prefix as the message header.
uint32_t length = htonl(buffer->size());
boost::asio::write(m_socket, boost::asio::buffer(&length, sizeof(length)));
// Write actual serialized message.
boost::asio::write(m_socket, boost::asio::buffer(buffer->data(), buffer->size()));
if (m_debug_enabled) {
std::cerr << "TX message (" << buffer->size() << " octets) ..." << std::endl;
std::cerr << "TX message: " << message << std::endl;
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::set_pause_handler(pause_handler&& handler)
{
m_pause_handler = std::move(handler);
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::set_resume_handler(resume_handler&& handler)
{
m_resume_handler = std::move(handler);
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::pause()
{
if (m_pause_handler) {
m_pause_handler();
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::resume()
{
if (m_resume_handler) {
m_resume_handler();
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::attach(
const std::shared_ptr<wamp_transport_handler>& handler)
{
if (m_handler) {
throw std::logic_error("handler already attached");
}
m_handler = handler;
m_handler->on_attach(this->shared_from_this());
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::detach()
{
if (!m_handler) {
throw std::logic_error("no handler attached");
}
m_handler->on_detach(true, "wamp.error.goodbye");
m_handler.reset();
}
template <class Socket>
bool wamp_rawsocket_transport<Socket>::has_handler() const
{
return m_handler != nullptr;
}
template <class Socket>
Socket& wamp_rawsocket_transport<Socket>::socket()
{
return m_socket;
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::handshake_reply_handler(
const boost::system::error_code& error_code,
std::size_t /* bytes_transferred */)
{
if (error_code) {
if (m_debug_enabled) {
std::cerr << "rawsocket handshake error: " << error_code << std::endl;
}
m_connect.set_exception(boost::copy_exception(
std::system_error(error_code.value(), std::system_category(), "async_read")));
return;
}
if (m_debug_enabled) {
std::cerr << "RawSocket handshake reply received" << std::endl;
}
if (m_handshake_buffer[0] != 0x7F) {
m_connect.set_exception(boost::copy_exception(protocol_error("invalid handshake frame")));
return;
}
// Indicates that the handshake reply is an error.
if ((m_handshake_buffer[1] & 0x0F) == 0x00) {
uint32_t error = m_handshake_buffer[1] & 0xF0;
if (m_debug_enabled) {
std::cerr << "rawsocket handshake error: " << std::hex << error << std::endl;
}
std::stringstream error_string;
if (error == 0x00) {
error_string << "illegal error code (" << error << ")";
} else if (error == 0x10) {
error_string << "serializer unsupported";
} else if (error == 0x20) {
error_string << "maximum message length unacceptable";
} else if (error == 0x30) {
error_string << "use of reserved bits (unsupported feature)";
} else if (error == 0x40) {
error_string << "maximum connection count reached";
} else {
error_string << "unknown/reserved error code (" << error << ")";
}
m_connect.set_exception(boost::copy_exception(protocol_error(error_string.str())));
return;
}
uint32_t serializer_type = (m_handshake_buffer[1] & 0x0F);
if (serializer_type == 0x01) {
m_connect.set_exception(boost::copy_exception(protocol_error("json currently not supported")));
} else if (serializer_type == 0x02) {
if (m_debug_enabled) {
std::cerr << "connect successful: valid handshake" << std::endl;
}
m_connect.set_value();
receive_message();
} else {
std::stringstream error_string;
error_string << "rawsocket handshake error: invalid serializer type (" << serializer_type << ")";
m_connect.set_exception(boost::copy_exception(protocol_error(error_string.str())));
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message()
{
if (m_debug_enabled) {
std::cerr << "RX preparing to receive message .." << std::endl;
}
boost::asio::async_read(
m_socket,
boost::asio::buffer(&m_message_length, sizeof(m_message_length)),
bind(&wamp_rawsocket_transport<Socket>::receive_message_header,
this->shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message_header(
const boost::system::error_code& error_code,
std::size_t /* bytes transferred */)
{
if (!error_code) {
m_message_length = ntohl(m_message_length);
if (m_debug_enabled) {
std::cerr << "RX message (" << m_message_length << " octets) ..." << std::endl;
}
m_message_unpacker.reserve_buffer(m_message_length);
boost::asio::async_read(
m_socket,
boost::asio::buffer(m_message_unpacker.buffer(), m_message_length),
bind(&wamp_rawsocket_transport<Socket>::receive_message_body,
this->shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
return;
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message_body(
const boost::system::error_code& error_code,
std::size_t /* bytes transferred */)
{
if (error_code) {
if (m_debug_enabled && error_code != boost::asio::error::operation_aborted) {
std::cerr << "Receive error: " << error_code << std::endl;
}
return;
}
if (m_debug_enabled) {
std::cerr << "RX message received." << std::endl;
}
if (m_handler) {
m_message_unpacker.buffer_consumed(m_message_length);
msgpack::unpacked result;
while (m_message_unpacker.next(&result)) {
wamp_message::message_fields fields;
result.get().convert(fields);
wamp_message message(std::move(fields), std::move(*(result.zone())));
if (m_debug_enabled) {
std::cerr << "RX message: " << message << std::endl;
}
m_handler->on_message(std::move(message));
}
} else {
std::cerr << "RX message ignored: no handler attached" << std::endl;
}
receive_message();
}
} // namespace autobahn
<commit_msg>make wamp_rawsocket_transport::connect reenterable<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Tavendo GmbH
//
// Boost Software License - Version 1.0 - August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#include "exceptions.hpp"
#include "wamp_message.hpp"
#include "wamp_transport_handler.hpp"
#include <boost/asio/buffer.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <system_error>
namespace autobahn {
template <class Socket>
wamp_rawsocket_transport<Socket>::wamp_rawsocket_transport(
boost::asio::io_service& io_service,
const endpoint_type& remote_endpoint,
bool debug_enabled)
: wamp_transport()
, m_socket(io_service)
, m_remote_endpoint(remote_endpoint)
, m_connect()
, m_disconnect()
, m_handshake_buffer()
, m_message_length(0)
, m_message_unpacker()
, m_debug_enabled(debug_enabled)
{
memset(m_handshake_buffer, 0, sizeof(m_handshake_buffer));
}
template <class Socket>
boost::future<void> wamp_rawsocket_transport<Socket>::connect()
{
m_connect = boost::promise<void>(); // reset the promise
if (m_socket.is_open()) {
m_connect.set_exception(boost::copy_exception(network_error("network transport already connected")));
return m_connect.get_future();
}
std::weak_ptr<wamp_rawsocket_transport<Socket>> weak_self = this->shared_from_this();
auto connect_handler = [=](const boost::system::error_code& error_code) {
auto shared_self = weak_self.lock();
if (!shared_self) {
return;
}
if (error_code) {
m_socket.close(); // async_connect will leave it open
m_connect.set_exception(boost::copy_exception(
std::system_error(error_code.value(), std::system_category(), "connect")));
return;
}
// FIXME: There should be a wamp_rawsocket_properties object or something
// similar that can be passed in to help deal with overiding these
// handshake parameters.
//
// Send the initial handshake packet informing the server which
// serialization format we wish to use, and our maximum message size.
m_handshake_buffer[0] = 0x7F; // magic byte
m_handshake_buffer[1] = 0xF2; // we are ready to receive messages up to 2**24 octets and encoded using MsgPack
m_handshake_buffer[2] = 0x00; // reserved
m_handshake_buffer[3] = 0x00; // reserved
boost::asio::write(
m_socket,
boost::asio::buffer(m_handshake_buffer, sizeof(m_handshake_buffer)));
auto handshake_reply = [=](
const boost::system::error_code& error,
std::size_t bytes_transferred) {
auto shared_self = weak_self.lock();
if (shared_self) {
handshake_reply_handler(error, bytes_transferred);
}
};
try {
// Read the 4-byte handshake reply from the server
boost::asio::async_read(
m_socket,
boost::asio::buffer(m_handshake_buffer, sizeof(m_handshake_buffer)),
handshake_reply);
} catch (const std::exception& e) {
m_connect.set_exception(boost::copy_exception(e));
}
};
m_socket.async_connect(m_remote_endpoint, connect_handler);
return m_connect.get_future();
}
template <class Socket>
boost::future<void> wamp_rawsocket_transport<Socket>::disconnect()
{
if (!m_socket.is_open()) {
throw network_error("network transport already disconnected");
}
m_socket.close();
m_disconnect.set_value();
return m_disconnect.get_future();
}
template <class Socket>
bool wamp_rawsocket_transport<Socket>::is_connected() const
{
return m_socket.is_open();
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::send_message(wamp_message&& message)
{
auto buffer = std::make_shared<msgpack::sbuffer>();
msgpack::packer<msgpack::sbuffer> packer(*buffer);
packer.pack(message.fields());
// Write the length prefix as the message header.
uint32_t length = htonl(buffer->size());
boost::asio::write(m_socket, boost::asio::buffer(&length, sizeof(length)));
// Write actual serialized message.
boost::asio::write(m_socket, boost::asio::buffer(buffer->data(), buffer->size()));
if (m_debug_enabled) {
std::cerr << "TX message (" << buffer->size() << " octets) ..." << std::endl;
std::cerr << "TX message: " << message << std::endl;
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::set_pause_handler(pause_handler&& handler)
{
m_pause_handler = std::move(handler);
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::set_resume_handler(resume_handler&& handler)
{
m_resume_handler = std::move(handler);
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::pause()
{
if (m_pause_handler) {
m_pause_handler();
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::resume()
{
if (m_resume_handler) {
m_resume_handler();
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::attach(
const std::shared_ptr<wamp_transport_handler>& handler)
{
if (m_handler) {
throw std::logic_error("handler already attached");
}
m_handler = handler;
m_handler->on_attach(this->shared_from_this());
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::detach()
{
if (!m_handler) {
throw std::logic_error("no handler attached");
}
m_handler->on_detach(true, "wamp.error.goodbye");
m_handler.reset();
}
template <class Socket>
bool wamp_rawsocket_transport<Socket>::has_handler() const
{
return m_handler != nullptr;
}
template <class Socket>
Socket& wamp_rawsocket_transport<Socket>::socket()
{
return m_socket;
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::handshake_reply_handler(
const boost::system::error_code& error_code,
std::size_t /* bytes_transferred */)
{
if (error_code) {
if (m_debug_enabled) {
std::cerr << "rawsocket handshake error: " << error_code << std::endl;
}
m_connect.set_exception(boost::copy_exception(
std::system_error(error_code.value(), std::system_category(), "async_read")));
return;
}
if (m_debug_enabled) {
std::cerr << "RawSocket handshake reply received" << std::endl;
}
if (m_handshake_buffer[0] != 0x7F) {
m_connect.set_exception(boost::copy_exception(protocol_error("invalid handshake frame")));
return;
}
// Indicates that the handshake reply is an error.
if ((m_handshake_buffer[1] & 0x0F) == 0x00) {
uint32_t error = m_handshake_buffer[1] & 0xF0;
if (m_debug_enabled) {
std::cerr << "rawsocket handshake error: " << std::hex << error << std::endl;
}
std::stringstream error_string;
if (error == 0x00) {
error_string << "illegal error code (" << error << ")";
} else if (error == 0x10) {
error_string << "serializer unsupported";
} else if (error == 0x20) {
error_string << "maximum message length unacceptable";
} else if (error == 0x30) {
error_string << "use of reserved bits (unsupported feature)";
} else if (error == 0x40) {
error_string << "maximum connection count reached";
} else {
error_string << "unknown/reserved error code (" << error << ")";
}
m_connect.set_exception(boost::copy_exception(protocol_error(error_string.str())));
return;
}
uint32_t serializer_type = (m_handshake_buffer[1] & 0x0F);
if (serializer_type == 0x01) {
m_connect.set_exception(boost::copy_exception(protocol_error("json currently not supported")));
} else if (serializer_type == 0x02) {
if (m_debug_enabled) {
std::cerr << "connect successful: valid handshake" << std::endl;
}
m_connect.set_value();
receive_message();
} else {
std::stringstream error_string;
error_string << "rawsocket handshake error: invalid serializer type (" << serializer_type << ")";
m_connect.set_exception(boost::copy_exception(protocol_error(error_string.str())));
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message()
{
if (m_debug_enabled) {
std::cerr << "RX preparing to receive message .." << std::endl;
}
boost::asio::async_read(
m_socket,
boost::asio::buffer(&m_message_length, sizeof(m_message_length)),
bind(&wamp_rawsocket_transport<Socket>::receive_message_header,
this->shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message_header(
const boost::system::error_code& error_code,
std::size_t /* bytes transferred */)
{
if (!error_code) {
m_message_length = ntohl(m_message_length);
if (m_debug_enabled) {
std::cerr << "RX message (" << m_message_length << " octets) ..." << std::endl;
}
m_message_unpacker.reserve_buffer(m_message_length);
boost::asio::async_read(
m_socket,
boost::asio::buffer(m_message_unpacker.buffer(), m_message_length),
bind(&wamp_rawsocket_transport<Socket>::receive_message_body,
this->shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
return;
}
}
template <class Socket>
void wamp_rawsocket_transport<Socket>::receive_message_body(
const boost::system::error_code& error_code,
std::size_t /* bytes transferred */)
{
if (error_code) {
if (m_debug_enabled && error_code != boost::asio::error::operation_aborted) {
std::cerr << "Receive error: " << error_code << std::endl;
}
return;
}
if (m_debug_enabled) {
std::cerr << "RX message received." << std::endl;
}
if (m_handler) {
m_message_unpacker.buffer_consumed(m_message_length);
msgpack::unpacked result;
while (m_message_unpacker.next(&result)) {
wamp_message::message_fields fields;
result.get().convert(fields);
wamp_message message(std::move(fields), std::move(*(result.zone())));
if (m_debug_enabled) {
std::cerr << "RX message: " << message << std::endl;
}
m_handler->on_message(std::move(message));
}
} else {
std::cerr << "RX message ignored: no handler attached" << std::endl;
}
receive_message();
}
} // namespace autobahn
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------------
// Author : A. Mastroserio
//-----------------------------------------------------------------------
#ifndef ALISPDUTILS_CXX
#define ALISPDUTILS_CXX
#include <TString.h>
#include "AliSPDUtils.h"
ClassImp(AliSPDUtils)
//______________________________________________________________________________
const Int_t AliSPDUtils::fgkDDLModuleMap[20][12] = {
{ 4, 5, 0, 1, 80, 81, 84, 85, 88, 89, 92, 93},
{12,13, 8, 9, 96, 97,100,101,104,105,108,109},
{20,21,16,17,112,113,116,117,120,121,124,125},
{28,29,24,25,128,129,132,133,136,137,140,141},
{36,37,32,33,144,145,148,149,152,153,156,157},
{44,45,40,41,160,161,164,165,168,169,172,173},
{52,53,48,49,176,177,180,181,184,185,188,189},
{60,61,56,57,192,193,196,197,200,201,204,205},
{68,69,64,65,208,209,212,213,216,217,220,221},
{76,77,72,73,224,225,228,229,232,233,236,237},
{ 7, 6, 3, 2, 83, 82, 87, 86, 91, 90, 95, 94},
{15,14,11,10, 99, 98,103,102,107,106,111,110},
{23,22,19,18,115,114,119,118,123,122,127,126},
{31,30,27,26,131,130,135,134,139,138,143,142},
{39,38,35,34,147,146,151,150,155,154,159,158},
{47,46,43,42,163,162,167,166,171,170,175,174},
{55,54,51,50,179,178,183,182,187,186,191,190},
{63,62,59,58,195,194,199,198,203,202,207,206},
{71,70,67,66,211,210,215,214,219,218,223,222},
{79,78,75,74,227,226,231,230,235,234,239,238}
};
//___________________________________________________________________________
AliSPDUtils::~AliSPDUtils() {
//
//destructor
//
}
//__________________________________________________________________________
Bool_t AliSPDUtils::OfflineToOnline(UInt_t module, UInt_t colM, UInt_t rowM, UInt_t& eq, UInt_t& hs, UInt_t& chip, UInt_t& col, UInt_t& row) {
// converts offline coordinates to online
eq = GetOnlineEqIdFromOffline(module);
hs = GetOnlineHSFromOffline(module);
chip = GetOnlineChipFromOffline(module,colM);
col = GetOnlineColFromOffline(module,colM);
row = GetOnlineRowFromOffline(module,rowM);
if (eq>=20 || hs>=6 || chip>=10 || col>=32 || row>=256) return kFALSE;
else return kTRUE;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::OnlineToOffline(UInt_t eq, UInt_t hs, UInt_t chip, UInt_t col, UInt_t row, UInt_t& module, UInt_t& colM, UInt_t& rowM) {
// converts online coordinates to offline
module = GetOfflineModuleFromOnline(eq,hs,chip);
colM = GetOfflineColFromOnline(eq,hs,chip,col);
rowM = GetOfflineRowFromOnline(eq,hs,chip,row);
if (module>=240 || colM>=160 || rowM>=256) return kFALSE;
else return kTRUE;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::GetOfflineFromOfflineChipKey(UInt_t chipkey,UInt_t& module, UInt_t& chip){
// converts offline chip key to offline chip coordinates (V. Altini)
if (chipkey>=1200) {
TString errMess = Form("%d is not a valid Chip Key number",chipkey);
printf(Form(" ERROR : %s\n",errMess.Data()));
return 0;
}
module = chipkey/5;
chip=chipkey%20%5;
return 1;
}
//________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineModuleFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip) {
// online->offline (module)
if (eqId<20 && hs<6 && chip<10) return fgkDDLModuleMap[eqId][hs*2+chip/5];
else return 240;
}
//________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineChipKeyFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip) {
// online->offline (chip key: 0-1199)
if (eqId<20 && hs<6 && chip<10) {
UInt_t module = GetOfflineModuleFromOnline(eqId,hs,chip);
UInt_t chipInModule = ( chip>4 ? chip-5 : chip );
if(eqId>9) chipInModule = 4 - chipInModule; // side C only
return (module*5 + chipInModule);
} else return 1200;
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineEqIdFromOffline(UInt_t module) {
// offline->online (eq)
for (UInt_t eqId=0; eqId<20; eqId++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eqId,iModule)==(Int_t)module) return eqId;
}
}
return 20; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineHSFromOffline(UInt_t module) {
// offline->online (hs)
for (UInt_t eqId=0; eqId<20; eqId++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eqId,iModule)==(Int_t)module) return iModule/2;
}
}
return 6; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineChipFromOffline(UInt_t module, UInt_t colM) {
// offline->online (chip)
for (UInt_t eq=0; eq<20; eq++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eq,iModule)==(Int_t)module) {
if (module<80) {
if (eq<10) { // side A
return (159-colM)/32 + 5*(iModule%2);
}
else { // side C
return colM/32 + 5*(iModule%2);
}
}
else if (module<240) {
if (eq<10) { // side A
return colM/32 + 5*(iModule%2);
}
else { // side C
return (159-colM)/32 + 5*(iModule%2);
}
}
}
}
}
return 10; // error
}
//__________________________________________________________________________
Int_t AliSPDUtils::GetModuleNumber(UInt_t iDDL, UInt_t iModule) {
if (iDDL<20 && iModule<12) return fgkDDLModuleMap[iDDL][iModule];
else return 240;
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineColFromOffline(UInt_t module, UInt_t colM) {
// offline->online (col)
if (module<80) { // inner layer
return colM%32;
}
else if (module<240) { // outer layer
return colM%32;
}
return 32; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineRowFromOffline(UInt_t module, UInt_t rowM) {
// offline->online (row)
if (module<80) { // inner layer
return (255-rowM);
}
else if (module<240) { // outer layer
return (255-rowM);
}
return 256; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineColFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip, UInt_t col) {
// online->offline (col)
if (eqId>=20 || hs>=6 || chip>=10 || col>=32) return 160; // error
UInt_t offset = 32 * (chip % 5);
if (hs<2) {
if (eqId<10) {
return 159 - (31-col + offset); // inner layer, side A
}
else {
return col + offset; // inner layer, side C
}
}
else {
if (eqId<10) {
return (col + offset); // outer layer, side A
}
else {
return 159 - (31-col + offset); // outer layer, side C
}
}
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineRowFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip, UInt_t row) {
// online->offline (row)
if (eqId>=20 || hs>=6 || chip>=10 || row>=256) return 256; // error
return 255-row;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::GetOnlineFromOfflineChipKey(UInt_t chipkey,UInt_t& eq, UInt_t& hs, UInt_t& chip){
// online Eq, hs and chip from offline chipkey (V. Altini)
if (chipkey>=1200) {
TString errMess = Form("%d is not a valid Chip Key number",chipkey);
printf(Form("ERROR : %s \n",errMess.Data()));
return 0;
}
eq = GetOnlineEqIdFromOffline(chipkey/5);
hs = GetOnlineHSFromOffline(chipkey/5);
chip=chipkey%20;
if(chip>9) chip=19-chip;
return 1;
}
#endif
<commit_msg>Warning corrected.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------------
// Author : A. Mastroserio
//-----------------------------------------------------------------------
#ifndef ALISPDUTILS_CXX
#define ALISPDUTILS_CXX
#include <TString.h>
#include "AliSPDUtils.h"
ClassImp(AliSPDUtils)
//______________________________________________________________________________
const Int_t AliSPDUtils::fgkDDLModuleMap[20][12] = {
{ 4, 5, 0, 1, 80, 81, 84, 85, 88, 89, 92, 93},
{12,13, 8, 9, 96, 97,100,101,104,105,108,109},
{20,21,16,17,112,113,116,117,120,121,124,125},
{28,29,24,25,128,129,132,133,136,137,140,141},
{36,37,32,33,144,145,148,149,152,153,156,157},
{44,45,40,41,160,161,164,165,168,169,172,173},
{52,53,48,49,176,177,180,181,184,185,188,189},
{60,61,56,57,192,193,196,197,200,201,204,205},
{68,69,64,65,208,209,212,213,216,217,220,221},
{76,77,72,73,224,225,228,229,232,233,236,237},
{ 7, 6, 3, 2, 83, 82, 87, 86, 91, 90, 95, 94},
{15,14,11,10, 99, 98,103,102,107,106,111,110},
{23,22,19,18,115,114,119,118,123,122,127,126},
{31,30,27,26,131,130,135,134,139,138,143,142},
{39,38,35,34,147,146,151,150,155,154,159,158},
{47,46,43,42,163,162,167,166,171,170,175,174},
{55,54,51,50,179,178,183,182,187,186,191,190},
{63,62,59,58,195,194,199,198,203,202,207,206},
{71,70,67,66,211,210,215,214,219,218,223,222},
{79,78,75,74,227,226,231,230,235,234,239,238}
};
//___________________________________________________________________________
AliSPDUtils::~AliSPDUtils() {
//
//destructor
//
}
//__________________________________________________________________________
Bool_t AliSPDUtils::OfflineToOnline(UInt_t module, UInt_t colM, UInt_t rowM, UInt_t& eq, UInt_t& hs, UInt_t& chip, UInt_t& col, UInt_t& row) {
// converts offline coordinates to online
eq = GetOnlineEqIdFromOffline(module);
hs = GetOnlineHSFromOffline(module);
chip = GetOnlineChipFromOffline(module,colM);
col = GetOnlineColFromOffline(module,colM);
row = GetOnlineRowFromOffline(module,rowM);
if (eq>=20 || hs>=6 || chip>=10 || col>=32 || row>=256) return kFALSE;
else return kTRUE;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::OnlineToOffline(UInt_t eq, UInt_t hs, UInt_t chip, UInt_t col, UInt_t row, UInt_t& module, UInt_t& colM, UInt_t& rowM) {
// converts online coordinates to offline
module = GetOfflineModuleFromOnline(eq,hs,chip);
colM = GetOfflineColFromOnline(eq,hs,chip,col);
rowM = GetOfflineRowFromOnline(eq,hs,chip,row);
if (module>=240 || colM>=160 || rowM>=256) return kFALSE;
else return kTRUE;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::GetOfflineFromOfflineChipKey(UInt_t chipkey,UInt_t& module, UInt_t& chip){
// converts offline chip key to offline chip coordinates (V. Altini)
if (chipkey>=1200) {
TString errMess = Form("%d is not a valid Chip Key number",chipkey);
printf(" ERROR : %s\n", errMess.Data());
return 0;
}
module = chipkey/5;
chip=chipkey%20%5;
return 1;
}
//________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineModuleFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip) {
// online->offline (module)
if (eqId<20 && hs<6 && chip<10) return fgkDDLModuleMap[eqId][hs*2+chip/5];
else return 240;
}
//________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineChipKeyFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip) {
// online->offline (chip key: 0-1199)
if (eqId<20 && hs<6 && chip<10) {
UInt_t module = GetOfflineModuleFromOnline(eqId,hs,chip);
UInt_t chipInModule = ( chip>4 ? chip-5 : chip );
if(eqId>9) chipInModule = 4 - chipInModule; // side C only
return (module*5 + chipInModule);
} else return 1200;
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineEqIdFromOffline(UInt_t module) {
// offline->online (eq)
for (UInt_t eqId=0; eqId<20; eqId++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eqId,iModule)==(Int_t)module) return eqId;
}
}
return 20; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineHSFromOffline(UInt_t module) {
// offline->online (hs)
for (UInt_t eqId=0; eqId<20; eqId++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eqId,iModule)==(Int_t)module) return iModule/2;
}
}
return 6; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineChipFromOffline(UInt_t module, UInt_t colM) {
// offline->online (chip)
for (UInt_t eq=0; eq<20; eq++) {
for (UInt_t iModule=0; iModule<12; iModule++) {
if (GetModuleNumber(eq,iModule)==(Int_t)module) {
if (module<80) {
if (eq<10) { // side A
return (159-colM)/32 + 5*(iModule%2);
}
else { // side C
return colM/32 + 5*(iModule%2);
}
}
else if (module<240) {
if (eq<10) { // side A
return colM/32 + 5*(iModule%2);
}
else { // side C
return (159-colM)/32 + 5*(iModule%2);
}
}
}
}
}
return 10; // error
}
//__________________________________________________________________________
Int_t AliSPDUtils::GetModuleNumber(UInt_t iDDL, UInt_t iModule) {
if (iDDL<20 && iModule<12) return fgkDDLModuleMap[iDDL][iModule];
else return 240;
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineColFromOffline(UInt_t module, UInt_t colM) {
// offline->online (col)
if (module<80) { // inner layer
return colM%32;
}
else if (module<240) { // outer layer
return colM%32;
}
return 32; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOnlineRowFromOffline(UInt_t module, UInt_t rowM) {
// offline->online (row)
if (module<80) { // inner layer
return (255-rowM);
}
else if (module<240) { // outer layer
return (255-rowM);
}
return 256; // error
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineColFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip, UInt_t col) {
// online->offline (col)
if (eqId>=20 || hs>=6 || chip>=10 || col>=32) return 160; // error
UInt_t offset = 32 * (chip % 5);
if (hs<2) {
if (eqId<10) {
return 159 - (31-col + offset); // inner layer, side A
}
else {
return col + offset; // inner layer, side C
}
}
else {
if (eqId<10) {
return (col + offset); // outer layer, side A
}
else {
return 159 - (31-col + offset); // outer layer, side C
}
}
}
//__________________________________________________________________________
UInt_t AliSPDUtils::GetOfflineRowFromOnline(UInt_t eqId, UInt_t hs, UInt_t chip, UInt_t row) {
// online->offline (row)
if (eqId>=20 || hs>=6 || chip>=10 || row>=256) return 256; // error
return 255-row;
}
//__________________________________________________________________________
Bool_t AliSPDUtils::GetOnlineFromOfflineChipKey(UInt_t chipkey,UInt_t& eq, UInt_t& hs, UInt_t& chip){
// online Eq, hs and chip from offline chipkey (V. Altini)
if (chipkey>=1200) {
TString errMess = Form("%d is not a valid Chip Key number",chipkey);
printf("ERROR : %s \n", errMess.Data());
return 0;
}
eq = GetOnlineEqIdFromOffline(chipkey/5);
hs = GetOnlineHSFromOffline(chipkey/5);
chip=chipkey%20;
if(chip>9) chip=19-chip;
return 1;
}
#endif
<|endoftext|>
|
<commit_before>/**
* @file cache.cpp
*
* @date Nov 21, 2012
* @author perämäki
*/
#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
cache::cache()
{
itsLogger = logger_factory::Instance()->GetLog("cache");
}
string cache::UniqueName(const info& info)
{
string producer_id = boost::lexical_cast<string> (info.Producer().Id());
string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = info.Param().Name();
string level_value = boost::lexical_cast<string>(info.Level().Value());
string level = HPLevelTypeToString.at(info.Level().Type());
return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
string cache::UniqueNameFromOptions(search_options& options)
{
string producer_id = boost::lexical_cast<string> (options.prod.Id());
string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = options.param.Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
void cache::Insert(info& anInfo, bool pin)
{
SplitToPool(anInfo, pin);
}
void cache::SplitToPool(info& anInfo, bool pin)
{
// Cached data is never replaced by another data that has
// the same uniqueName
string uniqueName = UniqueName(anInfo);
if (cache_pool::Instance()->Find(uniqueName))
{
itsLogger->Trace("Data with key " + uniqueName + " already exists at cache");
// Update timestamp of this cache item
cache_pool::Instance()->UpdateTime(uniqueName);
return;
}
#ifdef HAVE_CUDA
if (anInfo.Grid()->IsPackedData())
{
itsLogger->Trace("Removing packed data from cached info");
dynamic_cast<himan::regular_grid*> (anInfo.Grid())->PackedData().Clear();
}
#endif
assert(!anInfo.Grid()->IsPackedData());
assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Ni() != 999999);
assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Nj() != 999999);
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
params.push_back(anInfo.Param());
levels.push_back(anInfo.Level());
times.push_back(anInfo.Time());
auto newInfo = make_shared<info> (anInfo);
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->Create(anInfo.Grid());
assert(uniqueName == UniqueName(*newInfo));
// Race condition?
cache_pool::Instance()->Insert(uniqueName, newInfo, pin);
}
vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger->Trace( "Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean()
{
cache_pool::Instance()->Clean();
}
size_t cache::Size() const
{
return cache_pool::Instance()->Size();
}
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool() : itsCacheLimit(-1)
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
void cache_pool::CacheLimit(int theCacheLimit)
{
itsCacheLimit = theCacheLimit;
}
bool cache_pool::Find(const string& uniqueName)
{
for (const auto& kv : itsCache)
{
if (kv.first == uniqueName)
{
return true;
}
}
return false;
}
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
Lock lock(itsInsertMutex);
cache_item item;
item.info = anInfo;
item.access_time = time(nullptr);
item.pinned = pin;
itsCache.insert(pair<string, cache_item>(uniqueName, item));
itsLogger->Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string> (pin));
if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t> (itsCacheLimit))
{
Clean();
}
}
void cache_pool::UpdateTime(const std::string& uniqueName)
{
itsCache[uniqueName].access_time = time(nullptr);
}
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
assert(itsCacheLimit > 0);
if (itsCache.size() <= static_cast<size_t> (itsCacheLimit))
{
return;
}
string oldestName;
time_t oldestTime = INT_MAX;
for (const auto& kv : itsCache)
{
if (kv.second.access_time < oldestTime && !kv.second.pinned)
{
oldestName = kv.first;
oldestTime = kv.second.access_time;
}
}
assert(!oldestName.empty());
itsCache.erase(oldestName);
itsLogger->Trace("Data cleared from cache: " + oldestName + " with time: " + boost::lexical_cast<string> (oldestTime));
itsLogger->Trace("Cache size: " + boost::lexical_cast<string> (itsCache.size()));
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return make_shared<info> (*itsCache[uniqueName].info);
}
size_t cache_pool::Size() const
{
return itsCache.size();
}
<commit_msg>Cache now supports ensemble forecasts<commit_after>/**
* @file cache.cpp
*
* @date Nov 21, 2012
* @author perämäki
*/
#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include "regular_grid.h"
using namespace std;
using namespace himan::plugin;
typedef lock_guard<mutex> Lock;
cache::cache()
{
itsLogger = logger_factory::Instance()->GetLog("cache");
}
string cache::UniqueName(const info& info)
{
string producer_id = boost::lexical_cast<string> (info.Producer().Id());
string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = info.Param().Name();
string level_value = boost::lexical_cast<string>(info.Level().Value());
string level = HPLevelTypeToString.at(info.Level().Type());
string forecast_value = boost::lexical_cast<string>(info.ForecastType().Value());
return producer_id + '_' + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value
+ '_' + forecast_value;
}
string cache::UniqueNameFromOptions(search_options& options)
{
string producer_id = boost::lexical_cast<string> (options.prod.Id());
string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
string param = options.param.Name();
string level_value = boost::lexical_cast<string>((options.level).Value());
string level = HPLevelTypeToString.at(options.level.Type());
return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}
void cache::Insert(info& anInfo, bool pin)
{
SplitToPool(anInfo, pin);
}
void cache::SplitToPool(info& anInfo, bool pin)
{
// Cached data is never replaced by another data that has
// the same uniqueName
string uniqueName = UniqueName(anInfo);
if (cache_pool::Instance()->Find(uniqueName))
{
itsLogger->Trace("Data with key " + uniqueName + " already exists at cache");
// Update timestamp of this cache item
cache_pool::Instance()->UpdateTime(uniqueName);
return;
}
#ifdef HAVE_CUDA
if (anInfo.Grid()->IsPackedData())
{
itsLogger->Trace("Removing packed data from cached info");
dynamic_cast<himan::regular_grid*> (anInfo.Grid())->PackedData().Clear();
}
#endif
assert(!anInfo.Grid()->IsPackedData());
assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Ni() != 999999);
assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Nj() != 999999);
vector<param> params;
vector<level> levels;
vector<forecast_time> times;
params.push_back(anInfo.Param());
levels.push_back(anInfo.Level());
times.push_back(anInfo.Time());
auto newInfo = make_shared<info> (anInfo);
newInfo->Params(params);
newInfo->Levels(levels);
newInfo->Times(times);
newInfo->Create(anInfo.Grid());
assert(uniqueName == UniqueName(*newInfo));
// Race condition?
cache_pool::Instance()->Insert(uniqueName, newInfo, pin);
}
vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
string uniqueName = UniqueNameFromOptions(options);
vector<shared_ptr<himan::info>> info;
if (cache_pool::Instance()->Find(uniqueName))
{
info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
itsLogger->Trace( "Found matching data for " + uniqueName);
}
return info;
}
void cache::Clean()
{
cache_pool::Instance()->Clean();
}
size_t cache::Size() const
{
return cache_pool::Instance()->Size();
}
cache_pool* cache_pool::itsInstance = NULL;
cache_pool::cache_pool() : itsCacheLimit(-1)
{
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}
cache_pool* cache_pool::Instance()
{
if (!itsInstance)
{
itsInstance = new cache_pool();
}
return itsInstance;
}
void cache_pool::CacheLimit(int theCacheLimit)
{
itsCacheLimit = theCacheLimit;
}
bool cache_pool::Find(const string& uniqueName)
{
for (const auto& kv : itsCache)
{
if (kv.first == uniqueName)
{
return true;
}
}
return false;
}
void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
Lock lock(itsInsertMutex);
cache_item item;
item.info = anInfo;
item.access_time = time(nullptr);
item.pinned = pin;
itsCache.insert(pair<string, cache_item>(uniqueName, item));
itsLogger->Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string> (pin));
if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t> (itsCacheLimit))
{
Clean();
}
}
void cache_pool::UpdateTime(const std::string& uniqueName)
{
itsCache[uniqueName].access_time = time(nullptr);
}
void cache_pool::Clean()
{
Lock lock(itsDeleteMutex);
assert(itsCacheLimit > 0);
if (itsCache.size() <= static_cast<size_t> (itsCacheLimit))
{
return;
}
string oldestName;
time_t oldestTime = INT_MAX;
for (const auto& kv : itsCache)
{
if (kv.second.access_time < oldestTime && !kv.second.pinned)
{
oldestName = kv.first;
oldestTime = kv.second.access_time;
}
}
assert(!oldestName.empty());
itsCache.erase(oldestName);
itsLogger->Trace("Data cleared from cache: " + oldestName + " with time: " + boost::lexical_cast<string> (oldestTime));
itsLogger->Trace("Cache size: " + boost::lexical_cast<string> (itsCache.size()));
}
shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
Lock lock(itsGetMutex);
return make_shared<info> (*itsCache[uniqueName].info);
}
size_t cache_pool::Size() const
{
return itsCache.size();
}
<|endoftext|>
|
<commit_before>#include "simdjson.h"
#include <unistd.h>
#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
using namespace rapidjson;
using namespace simdjson;
struct stat_s {
size_t number_count;
size_t object_count;
size_t array_count;
size_t null_count;
size_t true_count;
size_t false_count;
bool valid;
};
typedef struct stat_s stat_t;
bool stat_equal(const stat_t &s1, const stat_t &s2) {
return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) &&
(s1.object_count == s2.object_count) &&
(s1.array_count == s2.array_count) &&
(s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) &&
(s1.false_count == s2.false_count);
}
void print_stat(const stat_t &s) {
if (!s.valid) {
printf("invalid\n");
return;
}
printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n",
s.number_count, s.object_count, s.array_count, s.null_count,
s.true_count, s.false_count);
}
__attribute__((noinline)) stat_t
simdjson_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
simdjson::ParsedJson pj = build_parsed_json(p);
answer.valid = pj.is_valid();
if (!answer.valid) {
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
size_t tape_idx = 0;
uint64_t tape_val = pj.doc.tape[tape_idx++];
uint8_t type = (tape_val >> 56);
size_t how_many = 0;
assert(type == 'r');
how_many = tape_val & simdjson::internal::JSON_VALUE_MASK;
for (; tape_idx < how_many; tape_idx++) {
tape_val = pj.doc.tape[tape_idx];
// uint64_t payload = tape_val & simdjson::internal::JSON_VALUE_MASK;
type = (tape_val >> 56);
switch (type) {
case 'l': // we have a long int
answer.number_count++;
tape_idx++; // skipping the integer
break;
case 'u': // we have a long uint
answer.number_count++;
tape_idx++; // skipping the unsigned integer
break;
case 'd': // we have a double
answer.number_count++;
tape_idx++; // skipping the double
break;
case 'n': // we have a null
answer.null_count++;
break;
case 't': // we have a true
answer.true_count++;
break;
case 'f': // we have a false
answer.false_count++;
break;
case '{': // we have an object
answer.object_count++;
break;
case '}': // we end an object
break;
case '[': // we start an array
answer.array_count++;
break;
case ']': // we end an array
break;
default:
break; // ignore
}
}
return answer;
}
// see
// https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp
void sajson_traverse(stat_t &stats, const sajson::value &node) {
using namespace sajson;
switch (node.get_type()) {
case TYPE_NULL:
stats.null_count++;
break;
case TYPE_FALSE:
stats.false_count++;
break;
case TYPE_TRUE:
stats.true_count++;
break;
case TYPE_ARRAY: {
stats.array_count++;
auto length = node.get_length();
for (size_t i = 0; i < length; ++i) {
sajson_traverse(stats, node.get_array_element(i));
}
break;
}
case TYPE_OBJECT: {
stats.object_count++;
auto length = node.get_length();
for (auto i = 0u; i < length; ++i) {
sajson_traverse(stats, node.get_object_value(i));
}
break;
}
case TYPE_STRING:
// skip
break;
case TYPE_DOUBLE:
case TYPE_INTEGER:
stats.number_count++; // node.get_number_value();
break;
default:
assert(false && "unknown node type");
}
}
__attribute__((noinline)) stat_t
sasjon_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size());
if(buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
auto d = sajson::parse(sajson::dynamic_allocation(),
sajson::mutable_string_view(p.size(), buffer));
answer.valid = d.is_valid();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
sajson_traverse(answer, d.get_root());
free(buffer);
return answer;
}
void rapid_traverse(stat_t &stats, const rapidjson::Value &v) {
switch (v.GetType()) {
case kNullType:
stats.null_count++;
break;
case kFalseType:
stats.false_count++;
break;
case kTrueType:
stats.true_count++;
break;
case kObjectType:
for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd();
++m) {
rapid_traverse(stats, m->value);
}
stats.object_count++;
break;
case kArrayType:
for (Value::ConstValueIterator i = v.Begin(); i != v.End();
++i) { // v.Size();
rapid_traverse(stats, *i);
}
stats.array_count++;
break;
case kStringType:
break;
case kNumberType:
stats.number_count++;
break;
}
}
__attribute__((noinline)) stat_t
rapid_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size() + 1);
if(buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
rapidjson::Document d;
d.ParseInsitu<kParseValidateEncodingFlag>(buffer);
answer.valid = !d.HasParseError();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
rapid_traverse(answer, d);
free(buffer);
return answer;
}
__attribute__((noinline)) stat_t
rapid_accurate_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size() + 1);
if(buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
rapidjson::Document d;
d.ParseInsitu<kParseValidateEncodingFlag|kParseFullPrecisionFlag>(buffer);
answer.valid = !d.HasParseError();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
rapid_traverse(answer, d);
free(buffer);
return answer;
}
int main(int argc, char *argv[]) {
bool verbose = false;
bool just_data = false;
int c;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr
<< "Using different parsers, we compute the content statistics of "
"JSON documents."
<< std::endl;
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
if (optind + 1 < argc) {
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
<< std::endl;
}
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1024 * 1024)
std::cout << p.size() / (1024 * 1024) << " MB ";
else if (p.size() > 1024)
std::cout << p.size() / 1024 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
stat_t s1 = simdjson_compute_stats(p);
if (verbose) {
printf("simdjson: ");
print_stat(s1);
}
stat_t s2 = rapid_compute_stats(p);
if (verbose) {
printf("rapid: ");
print_stat(s2);
}
stat_t s2a = rapid_accurate_compute_stats(p);
if (verbose) {
printf("rapid full: ");
print_stat(s2);
}
stat_t s3 = sasjon_compute_stats(p);
if (verbose) {
printf("sasjon: ");
print_stat(s3);
}
assert(stat_equal(s1, s2));
assert(stat_equal(s1, s3));
int repeat = 50;
int volume = p.size();
if (just_data) {
printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
BEST_TIME("simdjson ", simdjson_compute_stats(p).valid, true, , repeat,
volume, !just_data);
BEST_TIME("RapidJSON ", rapid_compute_stats(p).valid, true, , repeat, volume,
!just_data);
BEST_TIME("sasjon ", sasjon_compute_stats(p).valid, true, , repeat, volume,
!just_data);
}
<commit_msg>Fixing issue 601 (#618)<commit_after>#include "simdjson.h"
#include <unistd.h>
#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "sajson.h"
using namespace rapidjson;
using namespace simdjson;
struct stat_s {
size_t number_count;
size_t object_count;
size_t array_count;
size_t null_count;
size_t true_count;
size_t false_count;
bool valid;
};
typedef struct stat_s stat_t;
bool stat_equal(const stat_t &s1, const stat_t &s2) {
return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) &&
(s1.object_count == s2.object_count) &&
(s1.array_count == s2.array_count) &&
(s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) &&
(s1.false_count == s2.false_count);
}
void print_stat(const stat_t &s) {
if (!s.valid) {
printf("invalid\n");
return;
}
printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n",
s.number_count, s.object_count, s.array_count, s.null_count,
s.true_count, s.false_count);
}
really_inline void simdjson_process_atom(stat_t &s,
simdjson::document::element element) {
if (element.is_number()) {
s.number_count++;
} else if (element.is_bool()) {
if (element.as_bool()) {
s.true_count++;
} else {
s.false_count++;
}
} else if (element.is_null()) {
s.null_count++;
}
}
void simdjson_recurse(stat_t &s, simdjson::document::element element) {
if (element.is_array()) {
s.array_count++;
auto [array, array_error] = element.as_array();
for (auto child : array) {
if (child.is_array() || child.is_object()) {
simdjson_recurse(s, child);
} else {
simdjson_process_atom(s, child);
}
}
} else if (element.is_object()) {
s.object_count++;
auto [object, object_error] = element.as_object();
for (auto [key, value] : object) {
if (value.is_array() || value.is_object()) {
simdjson_recurse(s, value);
} else {
simdjson_process_atom(s, value);
}
}
} else {
simdjson_process_atom(s, element);
}
}
__attribute__((noinline)) stat_t
simdjson_compute_stats(const simdjson::padded_string &p) {
stat_t s{};
simdjson::document::parser parser;
auto [doc, error] = parser.parse(p);
if (error) {
s.valid = false;
return s;
}
s.valid = true;
simdjson_recurse(s, doc.root());
return s;
}
// see
// https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp
void sajson_traverse(stat_t &stats, const sajson::value &node) {
using namespace sajson;
switch (node.get_type()) {
case TYPE_NULL:
stats.null_count++;
break;
case TYPE_FALSE:
stats.false_count++;
break;
case TYPE_TRUE:
stats.true_count++;
break;
case TYPE_ARRAY: {
stats.array_count++;
auto length = node.get_length();
for (size_t i = 0; i < length; ++i) {
sajson_traverse(stats, node.get_array_element(i));
}
break;
}
case TYPE_OBJECT: {
stats.object_count++;
auto length = node.get_length();
for (auto i = 0u; i < length; ++i) {
sajson_traverse(stats, node.get_object_value(i));
}
break;
}
case TYPE_STRING:
// skip
break;
case TYPE_DOUBLE:
case TYPE_INTEGER:
stats.number_count++; // node.get_number_value();
break;
default:
assert(false && "unknown node type");
}
}
__attribute__((noinline)) stat_t
sasjon_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size());
if (buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
auto d = sajson::parse(sajson::dynamic_allocation(),
sajson::mutable_string_view(p.size(), buffer));
answer.valid = d.is_valid();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
sajson_traverse(answer, d.get_root());
free(buffer);
return answer;
}
void rapid_traverse(stat_t &stats, const rapidjson::Value &v) {
switch (v.GetType()) {
case kNullType:
stats.null_count++;
break;
case kFalseType:
stats.false_count++;
break;
case kTrueType:
stats.true_count++;
break;
case kObjectType:
for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd();
++m) {
rapid_traverse(stats, m->value);
}
stats.object_count++;
break;
case kArrayType:
for (Value::ConstValueIterator i = v.Begin(); i != v.End();
++i) { // v.Size();
rapid_traverse(stats, *i);
}
stats.array_count++;
break;
case kStringType:
break;
case kNumberType:
stats.number_count++;
break;
}
}
__attribute__((noinline)) stat_t
rapid_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size() + 1);
if (buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
rapidjson::Document d;
d.ParseInsitu<kParseValidateEncodingFlag>(buffer);
answer.valid = !d.HasParseError();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
rapid_traverse(answer, d);
free(buffer);
return answer;
}
__attribute__((noinline)) stat_t
rapid_accurate_compute_stats(const simdjson::padded_string &p) {
stat_t answer;
char *buffer = (char *)malloc(p.size() + 1);
if (buffer == nullptr) {
return answer;
}
memcpy(buffer, p.data(), p.size());
buffer[p.size()] = '\0';
rapidjson::Document d;
d.ParseInsitu<kParseValidateEncodingFlag | kParseFullPrecisionFlag>(buffer);
answer.valid = !d.HasParseError();
if (!answer.valid) {
free(buffer);
return answer;
}
answer.number_count = 0;
answer.object_count = 0;
answer.array_count = 0;
answer.null_count = 0;
answer.true_count = 0;
answer.false_count = 0;
rapid_traverse(answer, d);
free(buffer);
return answer;
}
int main(int argc, char *argv[]) {
bool verbose = false;
bool just_data = false;
int c;
while ((c = getopt(argc, argv, "vt")) != -1)
switch (c) {
case 't':
just_data = true;
break;
case 'v':
verbose = true;
break;
default:
abort();
}
if (optind >= argc) {
std::cerr
<< "Using different parsers, we compute the content statistics of "
"JSON documents."
<< std::endl;
std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
exit(1);
}
const char *filename = argv[optind];
if (optind + 1 < argc) {
std::cerr << "warning: ignoring everything after " << argv[optind + 1]
<< std::endl;
}
auto [p, error] = simdjson::padded_string::load(filename);
if (error) {
std::cerr << "Could not load the file " << filename << std::endl;
return EXIT_FAILURE;
}
if (verbose) {
std::cout << "Input has ";
if (p.size() > 1024 * 1024)
std::cout << p.size() / (1024 * 1024) << " MB ";
else if (p.size() > 1024)
std::cout << p.size() / 1024 << " KB ";
else
std::cout << p.size() << " B ";
std::cout << std::endl;
}
stat_t s1 = simdjson_compute_stats(p);
if (verbose) {
printf("simdjson: ");
print_stat(s1);
}
stat_t s2 = rapid_compute_stats(p);
if (verbose) {
printf("rapid: ");
print_stat(s2);
}
stat_t s2a = rapid_accurate_compute_stats(p);
if (verbose) {
printf("rapid full: ");
print_stat(s2a);
}
stat_t s3 = sasjon_compute_stats(p);
if (verbose) {
printf("sasjon: ");
print_stat(s3);
}
assert(stat_equal(s1, s2));
assert(stat_equal(s1, s3));
int repeat = 50;
int volume = p.size();
if (just_data) {
printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
}
BEST_TIME("simdjson ", simdjson_compute_stats(p).valid, true, ,
repeat, volume, !just_data);
BEST_TIME("RapidJSON ", rapid_compute_stats(p).valid, true, ,
repeat, volume, !just_data);
BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true, ,
repeat, volume, !just_data);
BEST_TIME("sasjon ", sasjon_compute_stats(p).valid, true, ,
repeat, volume, !just_data);
}
<|endoftext|>
|
<commit_before>#include "metaEditorSupportPlugin.h"
#include <QtCore/QProcess>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtGui/QDesktopWidget>
#include "../../../qrkernel/settingsManager.h"
#include "../../../qrmc/metaCompiler.h"
#include "editorGenerator.h"
#include "xmlParser.h"
Q_EXPORT_PLUGIN2(metaEditorSupportPlugin, metaEditor::MetaEditorSupportPlugin)
using namespace qReal;
using namespace metaEditor;
MetaEditorSupportPlugin::MetaEditorSupportPlugin()
: mGenerateEditorForQrxcAction(NULL)
, mGenerateEditorWithQrmcAction(NULL)
, mParseEditorXmlAction(NULL)
, mRepoControlApi(NULL)
, mCompilerSettingsPage(new PreferencesCompilerPage())
{
mAppTranslator.load(":/metaEditorSupport_" + QLocale::system().name());
QApplication::installTranslator(&mAppTranslator);
}
MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}
void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
mRepoControlApi = &configurator.repoControlInterface();
}
QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));
/*mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));
mParseEditorXmlAction.setText(tr("Parse editor xml"));
ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
*/
return QList<ActionInfo>() << generateEditorForQrxcActionInfo;
//<< generateEditorWithQrmcActionInfo
//<< parseEditorXmlActionInfo;
}
QPair<QString, PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
return qMakePair(QObject::tr("Compiler"), static_cast<PreferencesPage*>(mCompilerSettingsPage));
}
void MetaEditorSupportPlugin::generateEditorForQrxc()
{
EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());
QDir dir(".");
QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
foreach (Id const &key, metamodelList.keys()) {
QString const nameOfTheDirectory = metamodelList[key].first;
QString const pathToQRealRoot = metamodelList[key].second;
dir.mkpath(nameOfTheDirectory);
QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);
if (!mMainWindowInterface->errorReporter()->wereErrors()) {
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
loadNewEditor(nameOfTheDirectory, metamodelNames
, SettingsManager::value("pathToQmake").toString()
, SettingsManager::value("pathToMake").toString()
, SettingsManager::value("pluginExtension").toString()
, SettingsManager::value("prefix").toString());
}
}
if (metamodelList.isEmpty()) {
mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
}
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mRepoControlApi->workingFile());
IdList const metamodels = mLogicalRepoApi->children(Id::rootId());
QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
int forEditor = 60 / metamodels.size();
foreach (Id const &key, metamodels) {
QString const objectType = key.element();
if (objectType == "MetamodelDiagram") {
QString name = mLogicalRepoApi->stringProperty(key, "name of the directory");
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading..")
, QString(tr("Do you want to compile and load editor %1?")).arg(name)
, QMessageBox::Yes, QMessageBox::No)
== QMessageBox::No)
{
continue;
}
progress->setValue(5);
if (!metaCompiler.compile(name)) { // generating source code for all metamodels
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("Cannot generate source code for editor ") + name);
continue;
}
progress->setValue(20);
QProcess builder;
builder.setWorkingDirectory("../qrmc/plugins");
builder.start(SettingsManager::value("pathToQmake").toString());
qDebug() << "qmake";
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(40);
builder.start(SettingsManager::value("pathToMake").toString());
bool finished = builder.waitForFinished(100000);
qDebug() << "make";
if (finished && (builder.exitCode() == 0)) {
qDebug() << "make ok";
progress->setValue(progress->value() + forEditor / 2);
QString normalizedName = name.at(0).toUpper() + name.mid(1);
if (!name.isEmpty()) {
if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("cannot unload plugin ") + normalizedName);
progress->close();
delete progress;
continue;
}
}
QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
+ name
+ "."
+ SettingsManager::value("pluginExtension").toString()
;
if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
progress->setValue(progress->value() + forEditor / 2);
}
}
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
void MetaEditorSupportPlugin::parseEditorXml()
{
if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
return;
}
QDir dir(".");
QString directoryName = ".";
while (dir.cdUp()) {
QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
foreach (QFileInfo const &directory, infoList){
if (directory.baseName() == "qrxml") {
directoryName = directory.absolutePath() + "/qrxml";
}
}
}
QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
, tr("Select xml file to parse")
, directoryName
, "XML files (*.xml)");
if (fileName.isEmpty())
return;
XmlParser parser(*mLogicalRepoApi);
parser.parseFile(fileName);
parser.loadIncludeList(fileName);
mMainWindowInterface->reinitModels();
}
void MetaEditorSupportPlugin::deleteGeneratedFiles(QString const &directoryName, QString const &fileBaseName)
{
QFile filePro(fileBaseName + ".pro");
QFile fileXml(fileBaseName + ".xml");
QDir::setCurrent(directoryName);
filePro.remove();
fileXml.remove();
}
void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
, QPair<QString, QString> const &metamodelNames
, QString const &commandFirst
, QString const &commandSecond
, QString const &extension
, QString const &prefix)
{
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QString const metamodelName = metamodelNames.first;
QString const normalizerMetamodelName = metamodelNames.second;
if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
return;
}
QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);
QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
progress->setValue(5);
if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot unload plugin"));
deleteGeneratedFiles(directoryName, normalizerMetamodelName);
progress->close();
delete progress;
return;
}
progress->setValue(20);
QProcess builder;
builder.setWorkingDirectory(directoryName);
builder.start(commandFirst);
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(60);
builder.start(commandSecond);
if (builder.waitForFinished() && (builder.exitCode() == 0)) {
progress->setValue(80);
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
deleteGeneratedFiles(directoryName, normalizerMetamodelName);
}
progress->setValue(100);
progress->close();
delete progress;
}
<commit_msg>fixed bug with working directory for generation<commit_after>#include "metaEditorSupportPlugin.h"
#include <QtCore/QProcess>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtGui/QDesktopWidget>
#include "../../../qrkernel/settingsManager.h"
#include "../../../qrmc/metaCompiler.h"
#include "editorGenerator.h"
#include "xmlParser.h"
Q_EXPORT_PLUGIN2(metaEditorSupportPlugin, metaEditor::MetaEditorSupportPlugin)
using namespace qReal;
using namespace metaEditor;
MetaEditorSupportPlugin::MetaEditorSupportPlugin()
: mGenerateEditorForQrxcAction(NULL)
, mGenerateEditorWithQrmcAction(NULL)
, mParseEditorXmlAction(NULL)
, mRepoControlApi(NULL)
, mCompilerSettingsPage(new PreferencesCompilerPage())
{
mAppTranslator.load(":/metaEditorSupport_" + QLocale::system().name());
QApplication::installTranslator(&mAppTranslator);
}
MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}
void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
mRepoControlApi = &configurator.repoControlInterface();
}
QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));
/*mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));
mParseEditorXmlAction.setText(tr("Parse editor xml"));
ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
*/
return QList<ActionInfo>() << generateEditorForQrxcActionInfo;
//<< generateEditorWithQrmcActionInfo
//<< parseEditorXmlActionInfo;
}
QPair<QString, PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
return qMakePair(QObject::tr("Compiler"), static_cast<PreferencesPage*>(mCompilerSettingsPage));
}
void MetaEditorSupportPlugin::generateEditorForQrxc()
{
EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());
QDir dir(".");
QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
foreach (Id const &key, metamodelList.keys()) {
QString const nameOfTheDirectory = metamodelList[key].first;
QString const pathToQRealRoot = metamodelList[key].second;
dir.mkpath(nameOfTheDirectory);
QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);
if (!mMainWindowInterface->errorReporter()->wereErrors()) {
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
loadNewEditor(nameOfTheDirectory, metamodelNames
, SettingsManager::value("pathToQmake").toString()
, SettingsManager::value("pathToMake").toString()
, SettingsManager::value("pluginExtension").toString()
, SettingsManager::value("prefix").toString());
}
}
if (metamodelList.isEmpty()) {
mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
}
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mRepoControlApi->workingFile());
IdList const metamodels = mLogicalRepoApi->children(Id::rootId());
QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
int forEditor = 60 / metamodels.size();
foreach (Id const &key, metamodels) {
QString const objectType = key.element();
if (objectType == "MetamodelDiagram") {
QString name = mLogicalRepoApi->stringProperty(key, "name of the directory");
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading..")
, QString(tr("Do you want to compile and load editor %1?")).arg(name)
, QMessageBox::Yes, QMessageBox::No)
== QMessageBox::No)
{
continue;
}
progress->setValue(5);
if (!metaCompiler.compile(name)) { // generating source code for all metamodels
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("Cannot generate source code for editor ") + name);
continue;
}
progress->setValue(20);
QProcess builder;
builder.setWorkingDirectory("../qrmc/plugins");
builder.start(SettingsManager::value("pathToQmake").toString());
qDebug() << "qmake";
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(40);
builder.start(SettingsManager::value("pathToMake").toString());
bool finished = builder.waitForFinished(100000);
qDebug() << "make";
if (finished && (builder.exitCode() == 0)) {
qDebug() << "make ok";
progress->setValue(progress->value() + forEditor / 2);
QString normalizedName = name.at(0).toUpper() + name.mid(1);
if (!name.isEmpty()) {
if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("cannot unload plugin ") + normalizedName);
progress->close();
delete progress;
continue;
}
}
QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
+ name
+ "."
+ SettingsManager::value("pluginExtension").toString()
;
if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
progress->setValue(progress->value() + forEditor / 2);
}
}
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
void MetaEditorSupportPlugin::parseEditorXml()
{
if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
return;
}
QDir dir(".");
QString directoryName = ".";
while (dir.cdUp()) {
QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
foreach (QFileInfo const &directory, infoList){
if (directory.baseName() == "qrxml") {
directoryName = directory.absolutePath() + "/qrxml";
}
}
}
QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
, tr("Select xml file to parse")
, directoryName
, "XML files (*.xml)");
if (fileName.isEmpty())
return;
XmlParser parser(*mLogicalRepoApi);
parser.parseFile(fileName);
parser.loadIncludeList(fileName);
mMainWindowInterface->reinitModels();
}
void MetaEditorSupportPlugin::deleteGeneratedFiles(QString const &directoryName, QString const &fileBaseName)
{
QFile filePro(directoryName + "/" + fileBaseName + ".pro");
QFile fileXml(directoryName + "/" + fileBaseName + ".xml");
filePro.remove();
fileXml.remove();
}
void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
, QPair<QString, QString> const &metamodelNames
, QString const &commandFirst
, QString const &commandSecond
, QString const &extension
, QString const &prefix)
{
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QString const metamodelName = metamodelNames.first;
QString const normalizerMetamodelName = metamodelNames.second;
if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
return;
}
QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);
QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
progress->setValue(5);
if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot unload plugin"));
deleteGeneratedFiles(directoryName, normalizerMetamodelName);
progress->close();
delete progress;
return;
}
progress->setValue(20);
QProcess builder;
builder.setWorkingDirectory(directoryName);
builder.start(commandFirst);
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(60);
builder.start(commandSecond);
if (builder.waitForFinished() && (builder.exitCode() == 0)) {
progress->setValue(80);
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
deleteGeneratedFiles(directoryName, normalizerMetamodelName);
}
progress->setValue(100);
progress->close();
delete progress;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <exception>
#include <math.h>
#include <string.h>
#include "calculator.h"
using namespace std;
// ======================================================================================
int check(const char*& text, int value, bool invalid=false);
void check_calc();
/*
* ======================================================================================
* ======================================================================================
* ======================================================================================
*/
template<typename T>
void check(const char* text, T value, bool invalid=false)
{
Calculator<T, Parser<T>> calc;
const char* text_ptr = text;
try
{
auto result = calc.token_sequence(text);
if (almost_equal(result, value) && !invalid)
std::cout << "Passed: " << text_ptr << " = " << value << std::endl;
else
std::cout << "Failed: " << text_ptr << " = " << result << " (" << value << " expected)" << std::endl;
}
catch(char const* msg)
{
if (invalid)
std::cout << "Passed: " << text_ptr << " Exception message: " << msg << std::endl;
else
std::cout << "Failed: " << text_ptr << " Exception message: " << msg << " (" << value << " expected)" <<std::endl;
}
}
template <typename T>
void check_calc()
{
check<T>("1+2", 3);
check<T>("2+ 2", 4);
check<T>("2 +2", 4);
check<T>("2 + 2", 4);
check<T>("2 + 2", 4);
check<T>("2", 2);
check<T>("-2", -2);
check<T>("-2 - 2", -4);
check<T>("2- 2", 0);
check<T>("2- - 2", 4);
check<T>("100 + 2", 102);
check<T>("101 + 2", 103);
check<T>("8 - 6 * 2 / 2", 2);
check<T>("8 - 6 / 2 * 2", 2);
check<T>("8 - 6 / 2 * - 2", 14);
check<T>("2 + 3 * 4 - -2", 16);
check<T>("2*-2", -4);
check<T>("Pi", (T)constants["Pi"]);
check<T>("Pi + e", (T)constants["Pi"] + (T)constants["e"]);
check<T>("-Pi + 11", -(T)constants["Pi"] + 11);
check<T>("(2)", 2);
check<T>("(-2)", -2);
check<T>("(e)", (T)constants["e"]);
check<T>("(-e)", -(T)constants["e"]);
check<T>("(e*2)+2", (T)constants["e"]* 2 + 2);
check<T>("(e+2)+2", (T)constants["e"]+ 2 + 2);
check<T>("e+(2)+2", (T)constants["e"]+ 2 + 2);
check<T>("e+(2+2)", (T)constants["e"]+ 2 + 2);
check<T>("e/(2)", (T)(constants["e"] / 2));
check<T>("(2+e)/2", (T)((2 + constants["e"]) / 2));
check<T>("1.5 + 1.5", (T)(1.5) + (T)(1.5));
check<T>("1.511111", (T)(1.511111));
check<T>("1.5 * 2", (T)(1.5) * 2);
check<T>("2-+2", 0, true);
check<T>("2++2", 0, true);
check<T>("2 c 2", 0, true);
check<T>("2 2", 0, true);
check<T>("((2+2", 0, true);
check<T>("(2)+2)", 0, true);
check<T>("(2)+2/(2-2)", 0, true);
check<T>(".2 + 2", 0, true);
check<T>("(2 + 2", 0, true);
check<T>(")2 + 2", 0, true);
check<T>("2*+ 2", 0, true);
check<T>("2+* 2", 0, true);
check<T>("2..+* 2", 0, true);
}
/*
* ======================================================================================
* ======================================================================================
* ======================================================================================
*/
int main(int argc, char* argv[])
{
if (argc < 3)
{
cout << "Not enough arguments. Try: " << argv[0] << " <type> <expr>." << endl;
cout << "Inner test begun..." << endl;
check_calc<int>();
check_calc<double>();
check_calc<long>();
return 0;
}
const char* type = argv[1];
const char* text = argv[2];
try
{
if(strcmp(type, "int") == 0)
{
Calculator<int, Parser<int>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else if(strcmp(type, "long") == 0)
{
Calculator<long, Parser<long>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else if(strcmp(type, "double") == 0)
{
Calculator<double, Parser<double>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else
{
throw "Unknown type.";
}
}
catch(char const* msg)
{
std::cout << endl << "Exception message: " << msg << std::endl;
return -2;
}
return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <exception>
#include <math.h>
#include <string.h>
#include "calculator.hpp"
using namespace std;
// ======================================================================================
int check(const char*& text, int value, bool invalid=false);
void check_calc();
/*
* ======================================================================================
* ======================================================================================
* ======================================================================================
*/
template<typename T>
void check(const char* text, T value, bool invalid=false)
{
Calculator<T, Parser<T>> calc;
const char* text_ptr = text;
try
{
auto result = calc.token_sequence(text);
if (almost_equal(result, value) && !invalid)
std::cout << "Passed: " << text_ptr << " = " << value << std::endl;
else
std::cout << "Failed: " << text_ptr << " = " << result << " (" << value << " expected)" << std::endl;
}
catch(char const* msg)
{
if (invalid)
std::cout << "Passed: " << text_ptr << " Exception message: " << msg << std::endl;
else
std::cout << "Failed: " << text_ptr << " Exception message: " << msg << " (" << value << " expected)" <<std::endl;
}
}
template <typename T>
void check_calc()
{
check<T>("1+2", 3);
check<T>("2+ 2", 4);
check<T>("2 +2", 4);
check<T>("2 + 2", 4);
check<T>("2 + 2", 4);
check<T>("2", 2);
check<T>("-2", -2);
check<T>("-2 - 2", -4);
check<T>("2- 2", 0);
check<T>("2- - 2", 4);
check<T>("100 + 2", 102);
check<T>("101 + 2", 103);
check<T>("8 - 6 * 2 / 2", 2);
check<T>("8 - 6 / 2 * 2", 2);
check<T>("8 - 6 / 2 * - 2", 14);
check<T>("2 + 3 * 4 - -2", 16);
check<T>("2*-2", -4);
check<T>("Pi", (T)constants["Pi"]);
check<T>("Pi + e", (T)constants["Pi"] + (T)constants["e"]);
check<T>("-Pi + 11", -(T)constants["Pi"] + 11);
check<T>("(2)", 2);
check<T>("(-2)", -2);
check<T>("(e)", (T)constants["e"]);
check<T>("(-e)", -(T)constants["e"]);
check<T>("(e*2)+2", (T)constants["e"]* 2 + 2);
check<T>("(e+2)+2", (T)constants["e"]+ 2 + 2);
check<T>("e+(2)+2", (T)constants["e"]+ 2 + 2);
check<T>("e+(2+2)", (T)constants["e"]+ 2 + 2);
check<T>("e/(2)", (T)(constants["e"] / 2));
check<T>("(2+e)/2", (T)((2 + constants["e"]) / 2));
check<T>("1.5 + 1.5", (T)(1.5) + (T)(1.5));
check<T>("1.511111", (T)(1.511111));
check<T>("1.5 * 2", (T)(1.5) * 2);
check<T>("2-+2", 0, true);
check<T>("2++2", 0, true);
check<T>("2 c 2", 0, true);
check<T>("2 2", 0, true);
check<T>("((2+2", 0, true);
check<T>("(2)+2)", 0, true);
check<T>("(2)+2/(2-2)", 0, true);
check<T>(".2 + 2", 0, true);
check<T>("(2 + 2", 0, true);
check<T>(")2 + 2", 0, true);
check<T>("2*+ 2", 0, true);
check<T>("2+* 2", 0, true);
check<T>("2..+* 2", 0, true);
}
/*
* ======================================================================================
* ======================================================================================
* ======================================================================================
*/
int main(int argc, char* argv[])
{
if (argc < 3)
{
cout << "Not enough arguments. Try: " << argv[0] << " <type> <expr>." << endl;
cout << "Inner test begun..." << endl;
check_calc<int>();
check_calc<double>();
check_calc<long>();
return 0;
}
const char* type = argv[1];
const char* text = argv[2];
try
{
if(strcmp(type, "int") == 0)
{
Calculator<int, Parser<int>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else if(strcmp(type, "long") == 0)
{
Calculator<long, Parser<long>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else if(strcmp(type, "double") == 0)
{
Calculator<double, Parser<double>> calc;
//cout << "Input text = " << text << endl;
cout << calc.token_sequence(text) << endl;
}
else
{
throw "Unknown type.";
}
}
catch(char const* msg)
{
std::cout << endl << "Exception message: " << msg << std::endl;
return -2;
}
return 0;
}
<|endoftext|>
|
<commit_before>
#include "manu343726/turbo_core/turbo_core.hpp"
#include <tick/requires.h>
#include <iostream>
template<typename metatype, typename ctor, typename value = ctor>
struct TypeDecorator
{
using Type = metatype;
using Ctor = ctor;
using Value = value;
};
template<typename Type, typename BoxedValue>
struct is_a : std::false_type {};
template<typename Type, typename Ctor, typename Value>
struct is_a<Type, TypeDecorator<Type,Ctor,Value>> : std::true_type {};
template<typename Ctor, typename BoxedValue>
struct constructed_by : std::false_type {};
template<typename Type, typename Ctor, typename Value>
struct constructed_by<Ctor, TypeDecorator<Type,Ctor,Value>> : std::true_type {};
struct Maybe
{
struct Just
{
template<typename T>
struct apply
{
using type = TypeDecorator<Maybe, Just, T>;
};
};
struct Nothing
{
using type = TypeDecorator<Maybe, Nothing>;
};
};
#define IS_A(...) TICK_CLASS_REQUIRES(is_a<__VA_ARGS__>())
#define MATCHES(...) TICK_CLASS_REQUIRES(constructed_by<__VA_ARGS__>())
struct is_nothing
{
template<typename T, typename = void>
struct apply
{
typedef struct error {} type;
};
template<typename T>
struct apply<T, MATCHES(Maybe::Just, T)>
{
using type = std::false_type;
};
template<typename T>
struct apply<T, MATCHES(Maybe::Nothing, T)>
{
using type = std::true_type;
};
};
using maybe_int = $(Maybe::Just, int);
int main()
{
std::cout << tml::to_string<maybe_int>() << std::endl;
std::cout << tml::to_string<$(is_nothing, maybe_int)>() << std::endl;
}<commit_msg>Currying as closure<commit_after>
#include "manu343726/turbo_core/turbo_core.hpp"
#include <tick/requires.h>
#include <iostream>
template<typename metatype, typename ctor, typename value = ctor>
struct TypeDecorator
{
using Type = metatype;
using Ctor = ctor;
using Value = value;
};
template<typename Type, typename BoxedValue>
struct is_a : std::false_type {};
template<typename Type, typename Ctor, typename Value>
struct is_a<Type, TypeDecorator<Type,Ctor,Value>> : std::true_type {};
template<typename Ctor, typename BoxedValue>
struct constructed_by : std::false_type {};
template<typename Type, typename Ctor, typename Value>
struct constructed_by<Ctor, TypeDecorator<Type,Ctor,Value>> : std::true_type {};
struct Maybe
{
struct Just
{
template<typename T>
struct apply
{
using type = TypeDecorator<Maybe, Just, T>;
};
};
struct Nothing
{
using type = TypeDecorator<Maybe, Nothing>;
};
};
#define IS_A(...) TICK_CLASS_REQUIRES(is_a<__VA_ARGS__>())
#define MATCHES(...) TICK_CLASS_REQUIRES(constructed_by<__VA_ARGS__>())
struct is_nothing
{
template<typename T, typename = void>
struct apply
{
typedef struct error {} type;
};
template<typename T>
struct apply<T, MATCHES(Maybe::Just, T)>
{
using type = std::false_type;
};
template<typename T>
struct apply<T, MATCHES(Maybe::Nothing, T)>
{
using type = std::true_type;
};
};
using maybe_int = $(Maybe::Just, int);
struct f
{
template<typename... Head>
struct apply
{
struct type
{
template<typename... Tail>
using apply = f::apply<Head...,Tail...>;
};
};
template<typename A, typename B, typename C>
struct apply<A, B, C>
{
using type = C;
};
};
using a = $(f, int);
using b = $(a, char);
using c = $(b, bool);
int main()
{
std::cout << tml::to_string<a>() << std::endl;
std::cout << tml::to_string<b>() << std::endl;
std::cout << tml::to_string<c>() << std::endl;
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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 "main.h"
void test_is_same_dense()
{
typedef Matrix<double,Dynamic,Dynamic,ColMajor> ColMatrixXd;
ColMatrixXd m1(10,10);
Ref<ColMatrixXd> ref_m1(m1);
Ref<const ColMatrixXd> const_ref_m1(m1);
VERIFY(is_same_dense(m1,m1));
VERIFY(is_same_dense(m1,ref_m1));
VERIFY(is_same_dense(const_ref_m1,m1));
VERIFY(is_same_dense(const_ref_m1,ref_m1));
VERIFY(is_same_dense(m1.block(0,0,m1.rows(),m1.cols()),m1));
VERIFY(!is_same_dense(m1.row(0),m1.col(0)));
Ref<const ColMatrixXd> const_ref_m1_row(m1.row(1));
VERIFY(!is_same_dense(m1.row(1),const_ref_m1_row));
Ref<const ColMatrixXd> const_ref_m1_col(m1.col(1));
VERIFY(is_same_dense(m1.col(1),const_ref_m1_col));
}
<commit_msg>Fix unit test.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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 "main.h"
using internal::is_same_dense;
void test_is_same_dense()
{
typedef Matrix<double,Dynamic,Dynamic,ColMajor> ColMatrixXd;
ColMatrixXd m1(10,10);
Ref<ColMatrixXd> ref_m1(m1);
Ref<const ColMatrixXd> const_ref_m1(m1);
VERIFY(is_same_dense(m1,m1));
VERIFY(is_same_dense(m1,ref_m1));
VERIFY(is_same_dense(const_ref_m1,m1));
VERIFY(is_same_dense(const_ref_m1,ref_m1));
VERIFY(is_same_dense(m1.block(0,0,m1.rows(),m1.cols()),m1));
VERIFY(!is_same_dense(m1.row(0),m1.col(0)));
Ref<const ColMatrixXd> const_ref_m1_row(m1.row(1));
VERIFY(!is_same_dense(m1.row(1),const_ref_m1_row));
Ref<const ColMatrixXd> const_ref_m1_col(m1.col(1));
VERIFY(is_same_dense(m1.col(1),const_ref_m1_col));
}
<|endoftext|>
|
<commit_before>#pragma once
// math_frac.hpp: fractional functions for posits
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
namespace sw {
namespace unum {
// the current shims are NON-COMPLIANT with the posit standard, which says that every function must be
// correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.
template<size_t nbits, size_t es>
posit<nbits,es> frac(posit<nbits,es> x) {
return posit<nbits,es>(double(x)-long(x));
}
} // namespace unum
} // namespace sw
<commit_msg>WIP: additional mathematical function shims<commit_after>#pragma once
// math_frac.hpp: fractional functions for posits
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
namespace sw {
namespace unum {
// the current shims are NON-COMPLIANT with the posit standard, which says that every function must be
// correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.
template<size_t nbits, size_t es>
posit<nbits,es> fmod(posit<nbits,es> x, posit<nbits,es> y) {
return posit<nbits,es>(std::fmod(double(x), double(y)));
}
template<size_t nbits, size_t es>
posit<nbits,es> remainder(posit<nbits,es> x, posit<nbits,es> y) {
return posit<nbits,es>(std::remainder(double(x), double(y)));
}
template<size_t nbits, size_t es>
posit<nbits,es> frac(posit<nbits,es> x) {
return posit<nbits,es>(double(x)-long(x));
}
} // namespace unum
} // namespace sw
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision: 11316 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkDialogBar.h"
#include "mitkProperties.h"
#include <qgroupbox.h>
#include <qlayout.h>
#include <qfont.h>
#include <qobjectlist.h>
QmitkDialogBar
::QmitkDialogBar(
const char *caption, QObject *parent, const char *name, QmitkStdMultiWidget *multiWidget,
mitk::DataTreeIteratorBase *dataIt )
: QmitkBaseFunctionalityComponent( parent, name, dataIt ),
m_GroupBox( NULL ),
m_MultiWidget( multiWidget ),
m_Caption( caption )
{
}
QmitkDialogBar
::~QmitkDialogBar()
{
}
QWidget *
QmitkDialogBar
::CreateControlWidget( QWidget *parent )
{
m_GroupBox = new QGroupBox( parent );
m_GroupBox->setColumnLayout( 0, Qt::Vertical );
m_GroupBox->layout()->setSpacing( 6 );
m_GroupBox->setMargin( 11 );
m_GroupBox->setTitle( m_Caption );
QWidget *dialogBar = this->CreateDialogBar( m_GroupBox );
QFont captionFont = m_GroupBox->font();
captionFont.setBold( true );
m_GroupBox->setFont( captionFont );
QObjectList* childList = m_GroupBox->queryList( "QWidget" );
QObjectListIt childIter( *childList );
QObject* child;
QWidget* widget;
while ( (child = childIter.current()) )
{
if (child->inherits("QWidget"))
{
widget = static_cast<QWidget*>( child );
widget->unsetFont();
QFont normalFont = widget->font();
normalFont.setBold( false );
widget->setFont( normalFont );
}
++childIter;
}
QGridLayout *grid = new QGridLayout( m_GroupBox->layout(), 1, 1, 2 );
grid->setAlignment( Qt::AlignTop );
grid->addWidget( dialogBar, 0, 0 );
return m_GroupBox;
}
void
QmitkDialogBar
::ToggleVisible( bool visible )
{
if ( m_GroupBox )
{
m_GroupBox->setHidden( !visible );
}
// Reflect new visible state in global preferences
if ( m_GlobalOptions )
{
QString dialogBarStateName = "DialogBar " + m_Caption + " active";
m_GlobalOptions->SetProperty(
dialogBarStateName, new mitk::BoolProperty( visible ) );
}
}
const QString &
QmitkDialogBar
::GetCaption() const
{
return m_Caption;
}
QmitkStdMultiWidget *
QmitkDialogBar
::GetMultiWidget() const
{
return m_MultiWidget;
}
void
QmitkDialogBar
::SetGlobalOptions( mitk::PropertyList::Pointer options )
{
m_GlobalOptions = options;
}
<commit_msg>ENH (#876): Hide DialogBar by default right after instantiation<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision: 11316 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "QmitkDialogBar.h"
#include "mitkProperties.h"
#include <qgroupbox.h>
#include <qlayout.h>
#include <qfont.h>
#include <qobjectlist.h>
QmitkDialogBar
::QmitkDialogBar(
const char *caption, QObject *parent, const char *name, QmitkStdMultiWidget *multiWidget,
mitk::DataTreeIteratorBase *dataIt )
: QmitkBaseFunctionalityComponent( parent, name, dataIt ),
m_GroupBox( NULL ),
m_MultiWidget( multiWidget ),
m_Caption( caption )
{
}
QmitkDialogBar
::~QmitkDialogBar()
{
}
QWidget *
QmitkDialogBar
::CreateControlWidget( QWidget *parent )
{
m_GroupBox = new QGroupBox( parent );
m_GroupBox->setHidden( true );
m_GroupBox->setColumnLayout( 0, Qt::Vertical );
m_GroupBox->layout()->setSpacing( 6 );
m_GroupBox->setMargin( 11 );
m_GroupBox->setTitle( m_Caption );
QWidget *dialogBar = this->CreateDialogBar( m_GroupBox );
QFont captionFont = m_GroupBox->font();
captionFont.setBold( true );
m_GroupBox->setFont( captionFont );
QObjectList* childList = m_GroupBox->queryList( "QWidget" );
QObjectListIt childIter( *childList );
QObject* child;
QWidget* widget;
while ( (child = childIter.current()) )
{
if (child->inherits("QWidget"))
{
widget = static_cast<QWidget*>( child );
widget->unsetFont();
QFont normalFont = widget->font();
normalFont.setBold( false );
widget->setFont( normalFont );
}
++childIter;
}
QGridLayout *grid = new QGridLayout( m_GroupBox->layout(), 1, 1, 2 );
grid->setAlignment( Qt::AlignTop );
grid->addWidget( dialogBar, 0, 0 );
return m_GroupBox;
}
void
QmitkDialogBar
::ToggleVisible( bool visible )
{
if ( m_GroupBox )
{
m_GroupBox->setHidden( !visible );
}
// Reflect new visible state in global preferences
if ( m_GlobalOptions )
{
QString dialogBarStateName = "DialogBar " + m_Caption + " active";
m_GlobalOptions->SetProperty(
dialogBarStateName, new mitk::BoolProperty( visible ) );
}
}
const QString &
QmitkDialogBar
::GetCaption() const
{
return m_Caption;
}
QmitkStdMultiWidget *
QmitkDialogBar
::GetMultiWidget() const
{
return m_MultiWidget;
}
void
QmitkDialogBar
::SetGlobalOptions( mitk::PropertyList::Pointer options )
{
m_GlobalOptions = options;
}
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "Filterflipuv.h"
#include "Pixeldefs.h"
#include <assert.h>
namespace avg {
FilterFlipUV::FilterFlipUV()
: Filter()
{
}
FilterFlipUV::~FilterFlipUV()
{
}
void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const
{
PixelFormat PF = pBmp->getPixelFormat();
assert(pBmp->getPixelFormat() == YCbCr422);
for (int y = 0; y < pBmp->getSize().y; y++) {
unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride();
for (int x = 0; x < pBmp->getSize().x/2; x++) {
unsigned char tmp = pLine[x*4+1];
pLine[x*4+1] = pLine[x*4+3];
pLine[x*4+3] = tmp;
}
}
}
} // namespace
<commit_msg>Fixed compiler warning.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2006 Ulrich von Zadow
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Current versions can be found at www.libavg.de
//
#include "Filterflipuv.h"
#include "Pixeldefs.h"
#include <assert.h>
namespace avg {
FilterFlipUV::FilterFlipUV()
: Filter()
{
}
FilterFlipUV::~FilterFlipUV()
{
}
void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const
{
assert(pBmp->getPixelFormat() == YCbCr422);
for (int y = 0; y < pBmp->getSize().y; y++) {
unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride();
for (int x = 0; x < pBmp->getSize().x/2; x++) {
unsigned char tmp = pLine[x*4+1];
pLine[x*4+1] = pLine[x*4+3];
pLine[x*4+3] = tmp;
}
}
}
} // namespace
<|endoftext|>
|
<commit_before>#include "SqlBuilderBase.h"
#include <QSqlError>
#include <QSqlRecord>
#include <QString>
#include <QSqlDriver>
#include "ClassMapBase.h"
#include "ConfigurationMap.h"
#include "QueryModels/DeleteQueryModel.h"
#include "QueryModels/InsertQueryModel.h"
#include "QueryModels/SelectQueryModel.h"
#include "QueryModels/UpdateFieldQueryModel.h"
#include "QueryModels/UpdateQueryModel.h"
namespace QtOrm {
namespace Sql {
using namespace Config;
SqlBuilderBase::SqlBuilderBase(QObject *parent) : QObject(parent) {
}
QSqlQuery SqlBuilderBase::selectQuery() {
queryModel = getQueryModel(QueryModelType::Select);
QSqlQuery query(database);
query.prepare(queryModel->getSqlText());
QSharedPointer<SelectQueryModel> selectQueryModel = queryModel.dynamicCast<SelectQueryModel>();
QSharedPointer<GroupConditions> sharedConditions = QSharedPointer<GroupConditions>::create(conditions);
bindValues(query, sharedConditions, selectQueryModel->getConditionPlaceholder());
selectQueryModel->clearPlaceHolders();
return query;
}
QString SqlBuilderBase::getPlaceHolder(const QString ¶m) {
return QString(":%1").arg(param);
}
void SqlBuilderBase::bindValues(QSqlQuery &query, const QSharedPointer<GroupConditions> &conditions,
const QMap<QSharedPointer<Condition>, QString> &placeHolders) {
for (QSharedPointer<Condition> &condition : conditions->getConditions()) {
if (!condition->getValues().isEmpty()) {
QString placeHolder = placeHolders[condition];
QList<Operation> operations{Operation::Between, Operation::In};
// bool betweenOrIn = condition.dynamicCast<ConditionBetween>() || condition.dynamicCast<ConditionIn>();
bool betweenOrIn = operations.contains(condition->getOperation());
if (betweenOrIn) {
QString almostReadyPlaceHolder = getPlaceHolder(placeHolder);
int i = 1;
for (QVariant &value : condition->getValues()) {
QString valuePlaceholder = QString("%1_%2").arg(almostReadyPlaceHolder).arg(i);
query.bindValue(valuePlaceholder, value);
i++;
}
} else {
query.bindValue(getPlaceHolder(placeHolder), condition->getValues().first());
}
for (QSharedPointer<GroupConditions> &g : conditions->getGroups()) {
bindValues(query, g, placeHolders);
}
}
}
}
QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel(QueryModelType queryType) {
QString className = classBase->getClassName();
if (queryCache) {
if (QSharedPointer<QueryModel> model = queryCache->getModel(queryType, className, propertyName)) {
if (queryType == QueryModelType::Select) {
QSharedPointer<SelectQueryModel> selectModel = model.dynamicCast<SelectQueryModel>();
selectModel->setConditions(conditions);
selectModel->setOrderColumns(orderBy);
}
return model;
}
}
return createModelAndAddToCache(queryType);
}
QSharedPointer<QueryModel> SqlBuilderBase::createModelAndAddToCache(QueryModelType queryType) {
QString className = classBase->getClassName();
QSharedPointer<QueryModel> newModel = createModel(queryType);
if (queryCache) {
queryCache->addModel(queryType, newModel, className, propertyName);
}
return newModel;
}
QSharedPointer<QueryModel> SqlBuilderBase::createModel(QueryModelType queryType) {
QSharedPointer<QueryModel> result;
switch (queryType) {
case QueryModelType::Select: {
QSharedPointer<SelectQueryModel> selectModel = QSharedPointer<SelectQueryModel>::create();
selectModel->setClassBase(classBase);
selectModel->buildModel();
selectModel->setConditions(conditions);
selectModel->setOrderColumns(orderBy);
result = selectModel;
break;
}
case QueryModelType::Insert: {
QSharedPointer<InsertQueryModel> insertModel = QSharedPointer<InsertQueryModel>::create();
insertModel->setClassBase(classBase);
insertModel->setHasLastInsertedIdFeature(hasLastInsertedIdFeature());
insertModel->buildModel();
result = insertModel;
break;
}
case QueryModelType::Update: {
QSharedPointer<UpdateQueryModel> updateModel = QSharedPointer<UpdateQueryModel>::create();
updateModel->setClassBase(classBase);
updateModel->buildModel();
result = updateModel;
break;
}
case QueryModelType::UpdateColumn: {
QSharedPointer<UpdateFieldQueryModel> updateColumnModel = QSharedPointer<UpdateFieldQueryModel>::create();
updateColumnModel->setClassBase(classBase);
updateColumnModel->setPropertyName(propertyName);
updateColumnModel->buildModel();
result = updateColumnModel;
break;
}
case QueryModelType::Delete: {
QSharedPointer<DeleteQueryModel> deleteModel = QSharedPointer<DeleteQueryModel>::create();
deleteModel->setClassBase(classBase);
deleteModel->buildModel();
result = deleteModel;
break;
}
// throw exception
}
return result;
}
bool SqlBuilderBase::hasLastInsertedIdFeature() {
return database.driver()->hasFeature(QSqlDriver::LastInsertId) && database.driverName() != "QPSQL";
}
QList<OrderColumn> SqlBuilderBase::getOrderBy() const {
return orderBy;
}
void SqlBuilderBase::setOrderBy(const QList<OrderColumn> &value) {
orderBy = value;
}
QSharedPointer<QueryCache> SqlBuilderBase::getQueryCache() const {
return queryCache;
}
void SqlBuilderBase::setQueryCache(QSharedPointer<QueryCache> value) {
queryCache = value;
}
QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel() const {
return queryModel;
}
QSqlDatabase SqlBuilderBase::getDatabase() const {
return database;
}
void SqlBuilderBase::setDatabase(const QSqlDatabase &value) {
database = value;
}
QSharedPointer<QObject> SqlBuilderBase::getObject() const {
return object;
}
void SqlBuilderBase::setObject(QSharedPointer<QObject> value) {
object = value;
}
QSharedPointer<ClassMapBase> SqlBuilderBase::getClassBase() const {
return classBase;
}
void SqlBuilderBase::setClassBase(QSharedPointer<ClassMapBase> value) {
classBase = value;
}
GroupConditions SqlBuilderBase::getConditions() const {
return conditions;
}
void SqlBuilderBase::setConditions(const GroupConditions &value) {
conditions = value;
}
}
}
<commit_msg>deep parse for bind values<commit_after>#include "SqlBuilderBase.h"
#include <QSqlError>
#include <QSqlRecord>
#include <QString>
#include <QSqlDriver>
#include "ClassMapBase.h"
#include "ConfigurationMap.h"
#include "QueryModels/DeleteQueryModel.h"
#include "QueryModels/InsertQueryModel.h"
#include "QueryModels/SelectQueryModel.h"
#include "QueryModels/UpdateFieldQueryModel.h"
#include "QueryModels/UpdateQueryModel.h"
namespace QtOrm {
namespace Sql {
using namespace Config;
SqlBuilderBase::SqlBuilderBase(QObject *parent) : QObject(parent) {
}
QSqlQuery SqlBuilderBase::selectQuery() {
queryModel = getQueryModel(QueryModelType::Select);
QSqlQuery query(database);
query.prepare(queryModel->getSqlText());
QSharedPointer<SelectQueryModel> selectQueryModel = queryModel.dynamicCast<SelectQueryModel>();
QSharedPointer<GroupConditions> sharedConditions = QSharedPointer<GroupConditions>::create(conditions);
bindValues(query, sharedConditions, selectQueryModel->getConditionPlaceholder());
selectQueryModel->clearPlaceHolders();
return query;
}
QString SqlBuilderBase::getPlaceHolder(const QString ¶m) {
return QString(":%1").arg(param);
}
void SqlBuilderBase::bindValues(QSqlQuery &query, const QSharedPointer<GroupConditions> &conditions,
const QMap<QSharedPointer<Condition>, QString> &placeHolders) {
for (QSharedPointer<Condition> &condition : conditions->getConditions()) {
if (!condition->getValues().isEmpty()) {
QString placeHolder = placeHolders[condition];
QList<Operation> operations{Operation::Between, Operation::In};
// bool betweenOrIn = condition.dynamicCast<ConditionBetween>() || condition.dynamicCast<ConditionIn>();
bool betweenOrIn = operations.contains(condition->getOperation());
if (betweenOrIn) {
QString almostReadyPlaceHolder = getPlaceHolder(placeHolder);
int i = 1;
for (QVariant &value : condition->getValues()) {
QString valuePlaceholder = QString("%1_%2").arg(almostReadyPlaceHolder).arg(i);
query.bindValue(valuePlaceholder, value);
i++;
}
} else {
query.bindValue(getPlaceHolder(placeHolder), condition->getValues().first());
}
}
}
for (QSharedPointer<GroupConditions> &g : conditions->getGroups()) {
bindValues(query, g, placeHolders);
}
}
QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel(QueryModelType queryType) {
QString className = classBase->getClassName();
if (queryCache) {
if (QSharedPointer<QueryModel> model = queryCache->getModel(queryType, className, propertyName)) {
if (queryType == QueryModelType::Select) {
QSharedPointer<SelectQueryModel> selectModel = model.dynamicCast<SelectQueryModel>();
selectModel->setConditions(conditions);
selectModel->setOrderColumns(orderBy);
}
return model;
}
}
return createModelAndAddToCache(queryType);
}
QSharedPointer<QueryModel> SqlBuilderBase::createModelAndAddToCache(QueryModelType queryType) {
QString className = classBase->getClassName();
QSharedPointer<QueryModel> newModel = createModel(queryType);
if (queryCache) {
queryCache->addModel(queryType, newModel, className, propertyName);
}
return newModel;
}
QSharedPointer<QueryModel> SqlBuilderBase::createModel(QueryModelType queryType) {
QSharedPointer<QueryModel> result;
switch (queryType) {
case QueryModelType::Select: {
QSharedPointer<SelectQueryModel> selectModel = QSharedPointer<SelectQueryModel>::create();
selectModel->setClassBase(classBase);
selectModel->buildModel();
selectModel->setConditions(conditions);
selectModel->setOrderColumns(orderBy);
result = selectModel;
break;
}
case QueryModelType::Insert: {
QSharedPointer<InsertQueryModel> insertModel = QSharedPointer<InsertQueryModel>::create();
insertModel->setClassBase(classBase);
insertModel->setHasLastInsertedIdFeature(hasLastInsertedIdFeature());
insertModel->buildModel();
result = insertModel;
break;
}
case QueryModelType::Update: {
QSharedPointer<UpdateQueryModel> updateModel = QSharedPointer<UpdateQueryModel>::create();
updateModel->setClassBase(classBase);
updateModel->buildModel();
result = updateModel;
break;
}
case QueryModelType::UpdateColumn: {
QSharedPointer<UpdateFieldQueryModel> updateColumnModel = QSharedPointer<UpdateFieldQueryModel>::create();
updateColumnModel->setClassBase(classBase);
updateColumnModel->setPropertyName(propertyName);
updateColumnModel->buildModel();
result = updateColumnModel;
break;
}
case QueryModelType::Delete: {
QSharedPointer<DeleteQueryModel> deleteModel = QSharedPointer<DeleteQueryModel>::create();
deleteModel->setClassBase(classBase);
deleteModel->buildModel();
result = deleteModel;
break;
}
// throw exception
}
return result;
}
bool SqlBuilderBase::hasLastInsertedIdFeature() {
return database.driver()->hasFeature(QSqlDriver::LastInsertId) && database.driverName() != "QPSQL";
}
QList<OrderColumn> SqlBuilderBase::getOrderBy() const {
return orderBy;
}
void SqlBuilderBase::setOrderBy(const QList<OrderColumn> &value) {
orderBy = value;
}
QSharedPointer<QueryCache> SqlBuilderBase::getQueryCache() const {
return queryCache;
}
void SqlBuilderBase::setQueryCache(QSharedPointer<QueryCache> value) {
queryCache = value;
}
QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel() const {
return queryModel;
}
QSqlDatabase SqlBuilderBase::getDatabase() const {
return database;
}
void SqlBuilderBase::setDatabase(const QSqlDatabase &value) {
database = value;
}
QSharedPointer<QObject> SqlBuilderBase::getObject() const {
return object;
}
void SqlBuilderBase::setObject(QSharedPointer<QObject> value) {
object = value;
}
QSharedPointer<ClassMapBase> SqlBuilderBase::getClassBase() const {
return classBase;
}
void SqlBuilderBase::setClassBase(QSharedPointer<ClassMapBase> value) {
classBase = value;
}
GroupConditions SqlBuilderBase::getConditions() const {
return conditions;
}
void SqlBuilderBase::setConditions(const GroupConditions &value) {
conditions = value;
}
}
}
<|endoftext|>
|
<commit_before>#include "BVSExampleModule.h"
// This is your module's constructor.
// Please do not change its signature as it is called by the framework (so the
// framework actually creates your module) and the framework assigns the unique
// identifier and gives you access to the its config.
// However, you might use it to create your data structures etc., or you can use
// the onLoad() and onClose() functions, just be consistent in order to avoid
// weird errors.
BVSExampleModule::BVSExampleModule(const std::string id, const BVS::Config& config)
: BVS::Module()
, id(id)
, logger(id)
, config(config)
, input("testIn", BVS::ConnectorType::INPUT)
, output("testOut", BVS::ConnectorType::OUTPUT)
{
}
// This is your module's destructor.
// See the constructor for more info.
BVSExampleModule::~BVSExampleModule()
{
}
// Executed at module load.
BVS::Status BVSExampleModule::onLoad()
{
LOG(2, "loaded BVSExampleModule module!");
return BVS::Status::OK;
}
// UNUSED
BVS::Status BVSExampleModule::preExecute()
{
return BVS::Status::OK;
}
// Put all your work here.
BVS::Status BVSExampleModule::execute()
{
LOG(2, "Execution of " << id << "!");
return BVS::Status::OK;
}
// UNUSED
BVS::Status BVSExampleModule::postExecute()
{
return BVS::Status::OK;
}
BVS::Status BVSExampleModule::debugDisplay()
{
return BVS::Status::OK;
}
// Executed at module unload.
BVS::Status BVSExampleModule::onClose()
{
return BVS::Status::OK;
}
// This function is called by the framework upon creating a module instance of
// this class. It creates the module and registers it within the framework.
// DO NOT CHANGE OR DELETE
extern "C" {
// register with framework
int bvsRegisterModule(std::string id, BVS::Config& config)
{
registerModule(id, new BVSExampleModule(id, config));
return 0;
}
}
<commit_msg>namespace: fix missing module stuff<commit_after>#include "BVSExampleModule.h"
// This is your module's constructor.
// Please do not change its signature as it is called by the framework (so the
// framework actually creates your module) and the framework assigns the unique
// identifier and gives you access to the its config.
// However, you might use it to create your data structures etc., or you can use
// the onLoad() and onClose() functions, just be consistent in order to avoid
// weird errors.
BVSExampleModule::BVSExampleModule(const std::string id, const BVS::Config& config)
: BVS::Module()
, id(id)
, logger(id)
, config(config)
, input("testIn", BVS::ConnectorType::INPUT)
, output("testOut", BVS::ConnectorType::OUTPUT)
{
}
// This is your module's destructor.
// See the constructor for more info.
BVSExampleModule::~BVSExampleModule()
{
}
// Put all your work here.
BVS::Status BVSExampleModule::execute()
{
LOG(2, "Execution of " << id << "!");
return BVS::Status::OK;
}
// UNUSED
BVS::Status BVSExampleModule::debugDisplay()
{
return BVS::Status::OK;
}
// This function is called by the framework upon creating a module instance of
// this class. It creates the module and registers it within the framework.
// DO NOT CHANGE OR DELETE
extern "C" {
// register with framework
int bvsRegisterModule(std::string id, BVS::Config& config)
{
registerModule(id, new BVSExampleModule(id, config));
return 0;
}
}
<|endoftext|>
|
<commit_before>#include <sys/prctl.h>
#include <sys/wait.h>
#include <boost/lexical_cast.hpp>
#include "typename.h"
#include "Logger.h"
#include "demangle.h"
#include "exceptions.h"
logger::LogChannel tracelog("tracelog", "[trace] ");
stack_trace_::stack_trace_() {
std::string programName = get_program_name();
std::string pid = get_pid();
_stack_trace.push_back(std::string("\t[trace] back trace for ") + programName + " (" + pid + "):");
// create a pipe to read gdb's output
int pipefds[2];
int res = pipe(pipefds);
if (res < 0)
return;
// create a pipe to be used as a barrier
int barrierfds[2];
res = pipe(barrierfds);
if (res < 0)
return;
// fork
int childPid = fork();
// child:
if (!childPid) {
LOG_ALL(tracelog) << "[child] waiting for parent process to allow attaching" << std::endl;
// close writing end of barrier pipe
close(barrierfds[1]);
// wait until parent closes barrier pipe
char buf[1];
while (read(barrierfds[0], buf, sizeof(buf)) > 0)
LOG_ALL(tracelog) << "[child] " << buf[0] << std::endl;
LOG_ALL(tracelog) << "[child] parent process closed barrier pipe, preparing gdb invocation" << std::endl;
// close barrier pipe
close(barrierfds[0]);
// close reading end of output pipe
close(pipefds[0]);
// redirect stdout and stderr to output pipe
dup2(pipefds[1], 1);
dup2(pipefds[1], 2);
// close writing end of pipe (_we_ don't need it any longer)
close(pipefds[1]);
// start gdb
execlp("gdb", "gdb", "--batch", "-n", "-ex", "bt full", programName.c_str(), pid.c_str(), NULL);
// parent:
} else {
LOG_ALL(tracelog) << "[parent] allowing child to attach" << std::endl;
// allow our child process to attach
prctl(PR_SET_PTRACER, childPid, 0, 0, 0);
LOG_ALL(tracelog) << "[parent] closing barrier pipe" << std::endl;
// close barrier pipe to let child proceed
close(barrierfds[0]);
close(barrierfds[1]);
LOG_ALL(tracelog) << "[parent] barrier pipe closed" << std::endl;
// close the write end of pipe
close(pipefds[1]);
// capture child's output
std::string output;
// read the whole output of gdb
char buf[1];
size_t n;
while ((n = read(pipefds[0], buf, sizeof(buf))))
output += std::string(buf, n);
LOG_ALL(tracelog) << "[parent] end of pipe; I read: " << std::endl << output << std::endl;
// split it at newline characters
std::stringstream oss(output);
std::string line;
// ignore every line until '#0 ...'
while (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0')));
// copy remaining lines to stack trace
do {
if (line.size() > 0 && line[0] != '\n')
_stack_trace.push_back(std::string("\t[trace] ") + line);
} while (std::getline(oss, line));
// wait for the child to finish
waitpid(childPid, NULL, 0);
}
return;
}
const std::vector<std::string>&
stack_trace_::get_stack_trace() const {
return _stack_trace;
}
const std::string&
stack_trace_::get_program_name() {
if (_program_name == "")
initialise_program_name();
return _program_name;
}
std::string
stack_trace_::get_pid() {
return boost::lexical_cast<std::string>(getpid());
}
void
stack_trace_::initialise_program_name() {
char link[1024];
char name[1024];
snprintf(link, sizeof link, "/proc/%d/exe", getpid());
int size = readlink(link, name, sizeof link);
if (size == -1) {
_program_name = "[program name not found]";
return;
}
for (int i = 0; i < size; i++)
_program_name += name[i];
}
void handleException(boost::exception& e, std::ostream& out) {
out << std::endl;
out << "caught exception" << std::endl << std::endl;
if (boost::get_error_info<stack_trace>(e)) {
out << "###############" << std::endl;
out << "# STACK TRACE #" << std::endl;
out << "###############" << std::endl;
out << std::endl << std::endl;
out << *boost::get_error_info<stack_trace>(e);
out << std::endl << std::endl;
}
out << "#####################" << std::endl;
out << "# EXCEPTION SUMMARY #" << std::endl;
out << "#####################" << std::endl;
out << std::endl << std::endl;
out << "exception type:" << std::endl << std::endl << "\t" << typeName(e) << std::endl << std::endl;
if (boost::get_error_info<boost::throw_function>(e)) {
out << "throw location:" << std::endl << std::endl;
out << "\t" << *boost::get_error_info<boost::throw_function>(e) << std::endl;
if (boost::get_error_info<boost::throw_file>(e)) {
out << "\tin " << *boost::get_error_info<boost::throw_file>(e);
if (boost::get_error_info<boost::throw_line>(e))
out << "(" << *boost::get_error_info<boost::throw_line>(e) << ")";
}
out << std::endl;
}
if (boost::get_error_info<error_message>(e)) {
out << std::endl << "error message:" << std::endl << std::endl;;
out << "\t" << *boost::get_error_info<error_message>(e);
out << std::endl;
}
}
<commit_msg>fixed formatting of exception output<commit_after>#include <sys/prctl.h>
#include <sys/wait.h>
#include <boost/lexical_cast.hpp>
#include "typename.h"
#include "Logger.h"
#include "demangle.h"
#include "exceptions.h"
logger::LogChannel tracelog("tracelog", "[trace] ");
stack_trace_::stack_trace_() {
std::string programName = get_program_name();
std::string pid = get_pid();
_stack_trace.push_back(std::string("\t[trace] back trace for ") + programName + " (" + pid + "):");
// create a pipe to read gdb's output
int pipefds[2];
int res = pipe(pipefds);
if (res < 0)
return;
// create a pipe to be used as a barrier
int barrierfds[2];
res = pipe(barrierfds);
if (res < 0)
return;
// fork
int childPid = fork();
// child:
if (!childPid) {
LOG_ALL(tracelog) << "[child] waiting for parent process to allow attaching" << std::endl;
// close writing end of barrier pipe
close(barrierfds[1]);
// wait until parent closes barrier pipe
char buf[1];
while (read(barrierfds[0], buf, sizeof(buf)) > 0)
LOG_ALL(tracelog) << "[child] " << buf[0] << std::endl;
LOG_ALL(tracelog) << "[child] parent process closed barrier pipe, preparing gdb invocation" << std::endl;
// close barrier pipe
close(barrierfds[0]);
// close reading end of output pipe
close(pipefds[0]);
// redirect stdout and stderr to output pipe
dup2(pipefds[1], 1);
dup2(pipefds[1], 2);
// close writing end of pipe (_we_ don't need it any longer)
close(pipefds[1]);
// start gdb
execlp("gdb", "gdb", "--batch", "-n", "-ex", "bt full", programName.c_str(), pid.c_str(), NULL);
// parent:
} else {
LOG_ALL(tracelog) << "[parent] allowing child to attach" << std::endl;
// allow our child process to attach
prctl(PR_SET_PTRACER, childPid, 0, 0, 0);
LOG_ALL(tracelog) << "[parent] closing barrier pipe" << std::endl;
// close barrier pipe to let child proceed
close(barrierfds[0]);
close(barrierfds[1]);
LOG_ALL(tracelog) << "[parent] barrier pipe closed" << std::endl;
// close the write end of pipe
close(pipefds[1]);
// capture child's output
std::string output;
// read the whole output of gdb
char buf[1];
size_t n;
while ((n = read(pipefds[0], buf, sizeof(buf))))
output += std::string(buf, n);
LOG_ALL(tracelog) << "[parent] end of pipe; I read: " << std::endl << output << std::endl;
// split it at newline characters
std::stringstream oss(output);
std::string line;
// ignore every line until '#0 ...'
while (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0')));
// copy remaining lines to stack trace
do {
if (line.size() > 0 && line[0] != '\n')
_stack_trace.push_back(std::string("\t[trace] ") + line);
} while (std::getline(oss, line));
// wait for the child to finish
waitpid(childPid, NULL, 0);
}
return;
}
const std::vector<std::string>&
stack_trace_::get_stack_trace() const {
return _stack_trace;
}
const std::string&
stack_trace_::get_program_name() {
if (_program_name == "")
initialise_program_name();
return _program_name;
}
std::string
stack_trace_::get_pid() {
return boost::lexical_cast<std::string>(getpid());
}
void
stack_trace_::initialise_program_name() {
char link[1024];
char name[1024];
snprintf(link, sizeof link, "/proc/%d/exe", getpid());
int size = readlink(link, name, sizeof link);
if (size == -1) {
_program_name = "[program name not found]";
return;
}
for (int i = 0; i < size; i++)
_program_name += name[i];
}
void handleException(boost::exception& e, std::ostream& out) {
out << std::endl;
out << "caught exception" << std::endl << std::endl;
if (boost::get_error_info<stack_trace>(e)) {
out << "###############" << std::endl;
out << "# STACK TRACE #" << std::endl;
out << "###############" << std::endl;
out << std::endl << std::endl;
out << *boost::get_error_info<stack_trace>(e);
out << std::endl << std::endl;
}
out << "#####################" << std::endl;
out << "# EXCEPTION SUMMARY #" << std::endl;
out << "#####################" << std::endl;
out << std::endl << std::endl;
out << "exception type:" << std::endl << std::endl << "\t" << typeName(e) << std::endl << std::endl;
if (boost::get_error_info<boost::throw_function>(e)) {
out << "throw location:" << std::endl << std::endl;
out << "\t" << *boost::get_error_info<boost::throw_function>(e) << std::endl;
if (boost::get_error_info<boost::throw_file>(e)) {
out << "\tin " << *boost::get_error_info<boost::throw_file>(e);
if (boost::get_error_info<boost::throw_line>(e))
out << "(" << *boost::get_error_info<boost::throw_line>(e) << ")";
}
out << std::endl;
}
if (boost::get_error_info<error_message>(e)) {
out << std::endl << "error message:" << std::endl << std::endl;;
out << "\t" << *boost::get_error_info<error_message>(e);
out << std::endl << std::endl;
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Math/MlcpConstraintType.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintData.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Framework/Assert.h"
namespace SurgSim
{
namespace Physics
{
Constraint::Constraint(ConstraintType constraintType,
std::shared_ptr<ConstraintData> data,
std::shared_ptr<Representation> representation0,
const SurgSim::DataStructures::Location& location0,
std::shared_ptr<Representation> representation1,
const SurgSim::DataStructures::Location& location1)
{
m_mlcpMap[INVALID_CONSTRAINT] = Math::MLCP_INVALID_CONSTRAINT;
m_mlcpMap[FIXED_3DPOINT] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
m_mlcpMap[FIXED_3DROTATION_VECTOR] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
m_mlcpMap[FRICTIONAL_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONAL_CONSTRAINT;
m_mlcpMap[FRICTIONLESS_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
setInformation(constraintType, data, representation0, location0, representation1, location1);
}
Constraint::~Constraint()
{
}
const std::pair<std::shared_ptr<ConstraintImplementation>, std::shared_ptr<ConstraintImplementation>>&
Constraint::getImplementations() const
{
return m_implementations;
}
const std::pair<std::shared_ptr<Localization>, std::shared_ptr<Localization>>& Constraint::getLocalizations() const
{
return m_localizations;
}
std::shared_ptr<ConstraintData> Constraint::getData() const
{
return m_data;
}
size_t Constraint::getNumDof() const
{
return m_numDof;
}
void Constraint::build(double dt,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation0,
size_t indexOfRepresentation1,
size_t indexOfConstraint)
{
doBuild(dt, *m_data.get(), mlcp, indexOfRepresentation0, indexOfRepresentation1, indexOfConstraint);
m_implementations.first->build(
dt,
*m_data.get(),
m_localizations.first,
mlcp,
indexOfRepresentation0,
indexOfConstraint,
CONSTRAINT_POSITIVE_SIDE);
m_implementations.second->build(
dt,
*m_data.get(),
m_localizations.second,
mlcp,
indexOfRepresentation1,
indexOfConstraint,
CONSTRAINT_NEGATIVE_SIDE);
mlcp->constraintTypes.push_back(m_mlcpMap[m_constraintType]);
}
bool Constraint::isActive()
{
return m_localizations.first->getRepresentation()->isActive() &&
m_localizations.second->getRepresentation()->isActive();
}
void Constraint::doBuild(double dt,
const ConstraintData& data,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation0,
size_t indexOfRepresentation1,
size_t indexOfConstraint)
{
}
void Constraint::setInformation(SurgSim::Physics::ConstraintType constraintType,
std::shared_ptr<ConstraintData> data,
std::shared_ptr<Representation> representation0,
const SurgSim::DataStructures::Location& location0,
std::shared_ptr<Representation> representation1,
const SurgSim::DataStructures::Location& location1)
{
m_constraintType = constraintType;
SURGSIM_ASSERT(data != nullptr) << "ConstraintData can't be nullptr";
SURGSIM_ASSERT(representation0 != nullptr) << "First representation can't be nullptr";
SURGSIM_ASSERT(representation1 != nullptr) << "Second representation can't be nullptr";
auto localization0 = representation0->createLocalization(location0);
SURGSIM_ASSERT(localization0 != nullptr) << "Could not create localization for " << representation0->getName();
auto localization1 = representation1->createLocalization(location1);
SURGSIM_ASSERT(localization1 != nullptr) << "Could not create localization for " << representation1->getName();
auto implementation0 = representation0->getConstraintImplementation(m_constraintType);
SURGSIM_ASSERT(implementation0 != nullptr) << "Could not get implementation for " << representation0->getName();
auto implementation1 = representation1->getConstraintImplementation(m_constraintType);
SURGSIM_ASSERT(implementation1 != nullptr) << "Could not get implementation for " << representation1->getName();
SURGSIM_ASSERT(implementation0->getNumDof() == implementation1->getNumDof())
<< "The number of DOFs does not match between the two implementations";
m_data = data;
m_implementations = std::make_pair(implementation0, implementation1);
m_localizations = std::make_pair(localization0, localization1);
m_numDof = implementation0->getNumDof();
}
}; // namespace Physics
}; // namespace SurgSim
<commit_msg>Fix segfault from INVALID_CONSTRAINT used as array index<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Math/MlcpConstraintType.h"
#include "SurgSim/Physics/Constraint.h"
#include "SurgSim/Physics/ConstraintData.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Framework/Assert.h"
namespace SurgSim
{
namespace Physics
{
Constraint::Constraint(ConstraintType constraintType,
std::shared_ptr<ConstraintData> data,
std::shared_ptr<Representation> representation0,
const SurgSim::DataStructures::Location& location0,
std::shared_ptr<Representation> representation1,
const SurgSim::DataStructures::Location& location1)
{
m_mlcpMap[FIXED_3DPOINT] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
m_mlcpMap[FIXED_3DROTATION_VECTOR] = Math::MLCP_BILATERAL_3D_CONSTRAINT;
m_mlcpMap[FRICTIONAL_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONAL_CONSTRAINT;
m_mlcpMap[FRICTIONLESS_3DCONTACT] = Math::MLCP_UNILATERAL_3D_FRICTIONLESS_CONSTRAINT;
setInformation(constraintType, data, representation0, location0, representation1, location1);
}
Constraint::~Constraint()
{
}
const std::pair<std::shared_ptr<ConstraintImplementation>, std::shared_ptr<ConstraintImplementation>>&
Constraint::getImplementations() const
{
return m_implementations;
}
const std::pair<std::shared_ptr<Localization>, std::shared_ptr<Localization>>& Constraint::getLocalizations() const
{
return m_localizations;
}
std::shared_ptr<ConstraintData> Constraint::getData() const
{
return m_data;
}
size_t Constraint::getNumDof() const
{
return m_numDof;
}
void Constraint::build(double dt,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation0,
size_t indexOfRepresentation1,
size_t indexOfConstraint)
{
doBuild(dt, *m_data.get(), mlcp, indexOfRepresentation0, indexOfRepresentation1, indexOfConstraint);
m_implementations.first->build(
dt,
*m_data.get(),
m_localizations.first,
mlcp,
indexOfRepresentation0,
indexOfConstraint,
CONSTRAINT_POSITIVE_SIDE);
m_implementations.second->build(
dt,
*m_data.get(),
m_localizations.second,
mlcp,
indexOfRepresentation1,
indexOfConstraint,
CONSTRAINT_NEGATIVE_SIDE);
mlcp->constraintTypes.push_back(
(m_constraintType != INVALID_CONSTRAINT) ? m_mlcpMap[m_constraintType] : Math::MLCP_INVALID_CONSTRAINT);
}
bool Constraint::isActive()
{
return m_localizations.first->getRepresentation()->isActive() &&
m_localizations.second->getRepresentation()->isActive();
}
void Constraint::doBuild(double dt,
const ConstraintData& data,
MlcpPhysicsProblem* mlcp,
size_t indexOfRepresentation0,
size_t indexOfRepresentation1,
size_t indexOfConstraint)
{
}
void Constraint::setInformation(SurgSim::Physics::ConstraintType constraintType,
std::shared_ptr<ConstraintData> data,
std::shared_ptr<Representation> representation0,
const SurgSim::DataStructures::Location& location0,
std::shared_ptr<Representation> representation1,
const SurgSim::DataStructures::Location& location1)
{
m_constraintType = constraintType;
SURGSIM_ASSERT(data != nullptr) << "ConstraintData can't be nullptr";
SURGSIM_ASSERT(representation0 != nullptr) << "First representation can't be nullptr";
SURGSIM_ASSERT(representation1 != nullptr) << "Second representation can't be nullptr";
auto localization0 = representation0->createLocalization(location0);
SURGSIM_ASSERT(localization0 != nullptr) << "Could not create localization for " << representation0->getName();
auto localization1 = representation1->createLocalization(location1);
SURGSIM_ASSERT(localization1 != nullptr) << "Could not create localization for " << representation1->getName();
auto implementation0 = representation0->getConstraintImplementation(m_constraintType);
SURGSIM_ASSERT(implementation0 != nullptr) << "Could not get implementation for " << representation0->getName();
auto implementation1 = representation1->getConstraintImplementation(m_constraintType);
SURGSIM_ASSERT(implementation1 != nullptr) << "Could not get implementation for " << representation1->getName();
SURGSIM_ASSERT(implementation0->getNumDof() == implementation1->getNumDof())
<< "The number of DOFs does not match between the two implementations";
m_data = data;
m_implementations = std::make_pair(implementation0, implementation1);
m_localizations = std::make_pair(localization0, localization1);
m_numDof = implementation0->getNumDof();
}
}; // namespace Physics
}; // namespace SurgSim
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "kabcmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kicon.h>
#include <klocale.h>
#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
using namespace Akonadi;
class KABCModel::Private
{
public:
};
KABCModel::KABCModel( QObject *parent )
: Akonadi::ItemModel( parent ),
d( new Private() )
{
fetchScope().fetchFullPayload();
}
KABCModel::~KABCModel()
{
delete d;
}
int KABCModel::columnCount( const QModelIndex& ) const
{
return 4;
}
QVariant KABCModel::data( const QModelIndex &index, int role ) const
{
// pass through the queries for ItemModel
if ( role == ItemModel::IdRole || role == ItemModel::MimeTypeRole )
return ItemModel::data( index, role );
if ( !index.isValid() )
return QVariant();
if ( index.row() >= rowCount() )
return QVariant();
const Item item = itemForIndex( index );
if ( item.mimeType() == QLatin1String( "text/directory" ) ) {
if ( !item.hasPayload<KABC::Addressee>() )
return QVariant();
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 ) {
const KABC::Picture picture = addr.photo();
if ( picture.isIntern() ) {
return picture.data().scaled( QSize( 16, 16 ) );
} else {
return KIcon( QLatin1String( "x-office-contact" ) );
}
}
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
if ( !addr.formattedName().isEmpty() )
return addr.formattedName();
else
return addr.assembledName();
case 1:
return addr.givenName();
break;
case 2:
return addr.familyName();
break;
case 3:
return addr.preferredEmail();
break;
default:
break;
}
}
} else if ( item.mimeType() == KABC::ContactGroup::mimeType() ) {
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 )
return KIcon( QLatin1String( "x-mail-distribution-list" ) );
else
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
{
const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();
return group.name();
}
break;
default:
break;
}
}
}
return QVariant();
}
QVariant KABCModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
if ( orientation != Qt::Horizontal )
return QVariant();
switch ( section ) {
case 0:
return i18nc( "@title:column, name of a person", "Name" );
break;
case 1:
return KABC::Addressee::givenNameLabel();
break;
case 2:
return KABC::Addressee::familyNameLabel();
break;
case 3:
return KABC::Addressee::emailLabel();
break;
default:
break;
}
return QVariant();
}
<commit_msg>Check for payload before accessing it. Same check as for the addressee case.<commit_after>/*
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "kabcmodel.h"
#include <kabc/addressee.h>
#include <kabc/contactgroup.h>
#include <kicon.h>
#include <klocale.h>
#include <akonadi/item.h>
#include <akonadi/itemfetchjob.h>
#include <akonadi/itemfetchscope.h>
using namespace Akonadi;
class KABCModel::Private
{
public:
};
KABCModel::KABCModel( QObject *parent )
: Akonadi::ItemModel( parent ),
d( new Private() )
{
fetchScope().fetchFullPayload();
}
KABCModel::~KABCModel()
{
delete d;
}
int KABCModel::columnCount( const QModelIndex& ) const
{
return 4;
}
QVariant KABCModel::data( const QModelIndex &index, int role ) const
{
// pass through the queries for ItemModel
if ( role == ItemModel::IdRole || role == ItemModel::MimeTypeRole )
return ItemModel::data( index, role );
if ( !index.isValid() )
return QVariant();
if ( index.row() >= rowCount() )
return QVariant();
const Item item = itemForIndex( index );
if ( item.mimeType() == QLatin1String( "text/directory" ) ) {
if ( !item.hasPayload<KABC::Addressee>() )
return QVariant();
const KABC::Addressee addr = item.payload<KABC::Addressee>();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 ) {
const KABC::Picture picture = addr.photo();
if ( picture.isIntern() ) {
return picture.data().scaled( QSize( 16, 16 ) );
} else {
return KIcon( QLatin1String( "x-office-contact" ) );
}
}
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
if ( !addr.formattedName().isEmpty() )
return addr.formattedName();
else
return addr.assembledName();
case 1:
return addr.givenName();
break;
case 2:
return addr.familyName();
break;
case 3:
return addr.preferredEmail();
break;
default:
break;
}
}
} else if ( item.mimeType() == KABC::ContactGroup::mimeType() ) {
if ( !item.hasPayload<KABC::ContactGroup>() )
return QVariant();
if ( role == Qt::DecorationRole ) {
if ( index.column() == 0 )
return KIcon( QLatin1String( "x-mail-distribution-list" ) );
else
return QVariant();
} else if ( role == Qt::DisplayRole ) {
switch ( index.column() ) {
case 0:
{
const KABC::ContactGroup group = item.payload<KABC::ContactGroup>();
return group.name();
}
break;
default:
break;
}
}
}
return QVariant();
}
QVariant KABCModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
return QVariant();
if ( orientation != Qt::Horizontal )
return QVariant();
switch ( section ) {
case 0:
return i18nc( "@title:column, name of a person", "Name" );
break;
case 1:
return KABC::Addressee::givenNameLabel();
break;
case 2:
return KABC::Addressee::familyNameLabel();
break;
case 3:
return KABC::Addressee::emailLabel();
break;
default:
break;
}
return QVariant();
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "MethodReference.h"
#include "Resolver.h"
#include "Walkers.h"
namespace method_reference {
IRInstruction* make_load_const(uint16_t dest, size_t val) {
auto load = new IRInstruction(OPCODE_CONST);
load->set_dest(dest);
load->set_literal(static_cast<int32_t>(val));
return load;
}
IRInstruction* make_invoke(DexMethod* callee,
IROpcode opcode,
std::vector<uint16_t> args) {
always_assert(callee->is_def() && is_public(callee));
auto invoke = (new IRInstruction(opcode))->set_method(callee);
invoke->set_arg_word_count(args.size());
for (size_t i = 0; i < args.size(); i++) {
invoke->set_src(i, args.at(i));
}
return invoke;
}
void patch_callsite(const CallSiteSpec& spec,
const boost::optional<uint32_t>& additional_arg) {
const auto caller = spec.caller;
const auto call_insn = spec.call_insn;
const auto callee = spec.new_callee;
TRACE(REFU, 9, " patching call site at %s\n", SHOW(call_insn));
always_assert_log(is_public(callee),
"Updating a call site with a non-public new callee %s\n",
SHOW(callee));
auto code = caller->get_code();
auto additional_arg_reg = code->allocate_temp();
auto load_additional_arg =
make_load_const(additional_arg_reg, additional_arg.get_value_or(0));
// Assuming the following move-result is there and good.
std::vector<uint16_t> args;
for (size_t i = 0; i < call_insn->srcs_size(); i++) {
args.push_back(call_insn->src(i));
}
if (additional_arg != boost::none) {
args.push_back(additional_arg_reg);
}
auto invoke = make_invoke(callee, call_insn->opcode(), args);
if (additional_arg != boost::none) {
code->insert_after(
call_insn, std::vector<IRInstruction*>{load_additional_arg, invoke});
} else {
code->insert_after(call_insn, std::vector<IRInstruction*>{invoke});
}
// remove original call.
code->remove_opcode(call_insn);
TRACE(REFU, 9, " patched call site in %s\n%s\n", SHOW(caller), SHOW(code));
}
void update_call_refs_simple(
const Scope& scope,
const std::unordered_map<DexMethod*, DexMethod*>& old_to_new_callee) {
auto patcher = [&](DexMethod* meth, IRCode& code) {
for (auto& mie : InstructionIterable(code)) {
auto insn = mie.insn;
if (!insn->has_method()) {
continue;
}
const auto method =
resolve_method(insn->get_method(), opcode_to_search(insn));
if (method == nullptr || old_to_new_callee.count(method) == 0) {
continue;
}
auto new_callee = old_to_new_callee.at(method);
// At this point, a non static private should not exist.
always_assert_log(!is_private(new_callee) || is_static(new_callee),
"%s\n",
vshow(new_callee).c_str());
TRACE(REFU, 9, " Updated call %s to %s\n", SHOW(insn), SHOW(new_callee));
insn->set_method(new_callee);
if (new_callee->is_virtual()) {
always_assert_log(is_invoke_virtual(insn->opcode()),
"invalid callsite %s\n",
SHOW(insn));
} else if (is_static(new_callee)) {
always_assert_log(is_invoke_static(insn->opcode()),
"invalid callsite %s\n",
SHOW(insn));
}
}
};
walk::parallel::code(scope, patcher);
}
CallSites collect_call_refs(const Scope& scope,
const MethodOrderedSet& callees) {
auto patcher = [&](std::nullptr_t, DexMethod* meth) {
CallSites call_sites;
auto code = meth->get_code();
if (!code) {
return call_sites;
}
for (auto& mie : InstructionIterable(meth->get_code())) {
auto insn = mie.insn;
if (!insn->has_method()) {
continue;
}
const auto method =
resolve_method(insn->get_method(),
opcode_to_search(const_cast<IRInstruction*>(insn)));
if (method == nullptr || callees.count(method) == 0) {
continue;
}
call_sites.emplace_back(meth, insn);
TRACE(REFU, 9, " Found call %s from %s\n", SHOW(insn), SHOW(meth));
}
return call_sites;
};
CallSites call_sites =
walk::parallel::reduce_methods<std::nullptr_t, CallSites>(
scope,
patcher,
[](CallSites left, CallSites right) {
left.insert(left.end(), right.begin(), right.end());
return left;
},
[](int) { return nullptr; });
return call_sites;
}
} // namespace method_reference
<commit_msg>Update all protected (and package protected) methods to public when patching<commit_after>/**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "MethodReference.h"
#include "Resolver.h"
#include "Walkers.h"
namespace method_reference {
IRInstruction* make_load_const(uint16_t dest, size_t val) {
auto load = new IRInstruction(OPCODE_CONST);
load->set_dest(dest);
load->set_literal(static_cast<int32_t>(val));
return load;
}
IRInstruction* make_invoke(DexMethod* callee,
IROpcode opcode,
std::vector<uint16_t> args) {
always_assert(callee->is_def() && is_public(callee));
auto invoke = (new IRInstruction(opcode))->set_method(callee);
invoke->set_arg_word_count(args.size());
for (size_t i = 0; i < args.size(); i++) {
invoke->set_src(i, args.at(i));
}
return invoke;
}
void patch_callsite(const CallSiteSpec& spec,
const boost::optional<uint32_t>& additional_arg) {
const auto caller = spec.caller;
const auto call_insn = spec.call_insn;
const auto callee = spec.new_callee;
TRACE(REFU, 9, " patching call site at %s\n", SHOW(call_insn));
// Update package protected or protected methods to public.
if (is_static(callee) || is_any_init(callee) || !is_private(callee)) {
set_public(callee);
}
always_assert_log(
is_public(callee) || callee->get_class() == caller->get_class(),
"Updating a call site of %s when not accessible from %s\n",
SHOW(callee), SHOW(caller));
auto code = caller->get_code();
auto additional_arg_reg = code->allocate_temp();
auto load_additional_arg =
make_load_const(additional_arg_reg, additional_arg.get_value_or(0));
// Assuming the following move-result is there and good.
std::vector<uint16_t> args;
for (size_t i = 0; i < call_insn->srcs_size(); i++) {
args.push_back(call_insn->src(i));
}
if (additional_arg != boost::none) {
args.push_back(additional_arg_reg);
}
auto invoke = make_invoke(callee, call_insn->opcode(), args);
if (additional_arg != boost::none) {
code->insert_after(
call_insn, std::vector<IRInstruction*>{load_additional_arg, invoke});
} else {
code->insert_after(call_insn, std::vector<IRInstruction*>{invoke});
}
// remove original call.
code->remove_opcode(call_insn);
TRACE(REFU, 9, " patched call site in %s\n%s\n", SHOW(caller), SHOW(code));
}
void update_call_refs_simple(
const Scope& scope,
const std::unordered_map<DexMethod*, DexMethod*>& old_to_new_callee) {
auto patcher = [&](DexMethod* meth, IRCode& code) {
for (auto& mie : InstructionIterable(code)) {
auto insn = mie.insn;
if (!insn->has_method()) {
continue;
}
const auto method =
resolve_method(insn->get_method(), opcode_to_search(insn));
if (method == nullptr || old_to_new_callee.count(method) == 0) {
continue;
}
auto new_callee = old_to_new_callee.at(method);
// At this point, a non static private should not exist.
always_assert_log(!is_private(new_callee) || is_static(new_callee),
"%s\n",
vshow(new_callee).c_str());
TRACE(REFU, 9, " Updated call %s to %s\n", SHOW(insn), SHOW(new_callee));
insn->set_method(new_callee);
if (new_callee->is_virtual()) {
always_assert_log(is_invoke_virtual(insn->opcode()),
"invalid callsite %s\n",
SHOW(insn));
} else if (is_static(new_callee)) {
always_assert_log(is_invoke_static(insn->opcode()),
"invalid callsite %s\n",
SHOW(insn));
}
}
};
walk::parallel::code(scope, patcher);
}
CallSites collect_call_refs(const Scope& scope,
const MethodOrderedSet& callees) {
auto patcher = [&](std::nullptr_t, DexMethod* meth) {
CallSites call_sites;
auto code = meth->get_code();
if (!code) {
return call_sites;
}
for (auto& mie : InstructionIterable(meth->get_code())) {
auto insn = mie.insn;
if (!insn->has_method()) {
continue;
}
const auto method =
resolve_method(insn->get_method(),
opcode_to_search(const_cast<IRInstruction*>(insn)));
if (method == nullptr || callees.count(method) == 0) {
continue;
}
call_sites.emplace_back(meth, insn);
TRACE(REFU, 9, " Found call %s from %s\n", SHOW(insn), SHOW(meth));
}
return call_sites;
};
CallSites call_sites =
walk::parallel::reduce_methods<std::nullptr_t, CallSites>(
scope,
patcher,
[](CallSites left, CallSites right) {
left.insert(left.end(), right.begin(), right.end());
return left;
},
[](int) { return nullptr; });
return call_sites;
}
} // namespace method_reference
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/login_prompt.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/browser/views/login_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/notification_service.h"
#include "chrome/views/dialog_delegate.h"
#include "grit/generated_resources.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
using namespace std;
using views::LoginView;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
static void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHost::ExtraRequestInfo* info =
ResourceDispatcherHost::ExtraInfoForRequest(request);
if (!info)
return;
info->login_handler = NULL;
}
// Get the signon_realm under which this auth info should be stored.
//
// The format of the signon_realm for proxy auth is:
// proxy-host/auth-realm
// The format of the signon_realm for server auth is:
// url-scheme://url-host[:url-port]/auth-realm
//
// Be careful when changing this function, since you could make existing
// saved logins un-retrievable.
std::string GetSignonRealm(const GURL& url,
const net::AuthChallengeInfo& auth_info) {
std::string signon_realm;
if (auth_info.is_proxy) {
signon_realm = WideToASCII(auth_info.host);
signon_realm.append("/");
} else {
// Take scheme, host, and port from the url.
signon_realm = url.GetOrigin().spec();
// This ends with a "/".
}
signon_realm.append(WideToUTF8(auth_info.realm));
return signon_realm;
}
// ----------------------------------------------------------------------------
// LoginHandlerImpl
// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerImpl : public LoginHandler,
public base::RefCountedThreadSafe<LoginHandlerImpl>,
public views::DialogDelegate {
public:
LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)
: dialog_(NULL),
handled_auth_(false),
request_(request),
request_loop_(MessageLoop::current()),
ui_loop_(ui_loop),
password_manager_(NULL) {
DCHECK(request_) << "LoginHandler constructed with NULL request";
AddRef(); // matched by ReleaseLater.
if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,
&tab_contents_id_)) {
NOTREACHED();
}
}
~LoginHandlerImpl() {
}
// Initialize the UI part of the LoginHandler.
// Scary thread safety note: This can potentially be called *after* SetAuth
// or CancelAuth (say, if the request was cancelled before the UI thread got
// control). However, that's OK since any UI interaction in those functions
// will occur via an InvokeLater on the UI thread, which is guaranteed
// to happen after this is called (since this was InvokeLater'd first).
void InitWithDialog(ConstrainedWindow* dlg) {
DCHECK(MessageLoop::current() == ui_loop_);
dialog_ = dlg;
SendNotifications();
}
// Returns the WebContents that needs authentication.
WebContents* GetWebContentsForLogin() {
DCHECK(MessageLoop::current() == ui_loop_);
return tab_util::GetWebContentsByID(render_process_host_id_,
tab_contents_id_);
}
void set_login_view(LoginView* login_view) {
login_view_ = login_view;
}
void set_password_form(const PasswordForm& form) {
password_form_ = form;
}
void set_password_manager(PasswordManager* password_manager) {
password_manager_ = password_manager;
}
// views::DialogDelegate methods:
virtual std::wstring GetDialogButtonLabel(DialogButton button) const {
if (button == DIALOGBUTTON_OK)
return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);
return DialogDelegate::GetDialogButtonLabel(button);
}
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);
}
virtual void WindowClosing() {
DCHECK(MessageLoop::current() == ui_loop_);
// Reference is no longer valid.
dialog_ = NULL;
if (!WasAuthHandled(true)) {
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
SendNotifications();
}
}
virtual void DeleteDelegate() {
// Delete this object once all InvokeLaters have been called.
request_loop_->ReleaseSoon(FROM_HERE, this);
}
virtual bool Cancel() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
CancelAuth();
return true;
}
virtual bool Accept() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
SetAuth(login_view_->GetUsername(), login_view_->GetPassword());
return true;
}
virtual views::View* GetContentsView() {
return login_view_;
}
// LoginHandler:
virtual void SetAuth(const std::wstring& username,
const std::wstring& password) {
if (WasAuthHandled(true))
return;
// Tell the password manager the credentials were submitted / accepted.
if (password_manager_) {
password_form_.username_value = username;
password_form_.password_value = password;
password_manager_->ProvisionallySavePassword(password_form_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SetAuthDeferred, username, password));
}
virtual void CancelAuth() {
if (WasAuthHandled(true))
return;
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
}
virtual void OnRequestCancelled() {
DCHECK(MessageLoop::current() == request_loop_) <<
"Why is OnRequestCancelled called from the UI thread?";
// Reference is no longer valid.
request_ = NULL;
// Give up on auth if the request was cancelled.
CancelAuth();
}
private:
// Calls SetAuth from the request_loop.
void SetAuthDeferred(const std::wstring& username,
const std::wstring& password) {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->SetAuth(username, password);
ResetLoginHandlerForRequest(request_);
}
}
// Calls CancelAuth from the request_loop.
void CancelAuthDeferred() {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->CancelAuth();
// Verify that CancelAuth does destroy the request via our delegate.
DCHECK(request_ != NULL);
ResetLoginHandlerForRequest(request_);
}
}
// Closes the view_contents from the UI loop.
void CloseContentsDeferred() {
DCHECK(MessageLoop::current() == ui_loop_);
// The hosting ConstrainedWindow may have been freed.
if (dialog_)
dialog_->CloseConstrainedWindow();
}
// Returns whether authentication had been handled (SetAuth or CancelAuth).
// If |set_handled| is true, it will mark authentication as handled.
bool WasAuthHandled(bool set_handled) {
AutoLock lock(handled_auth_lock_);
bool was_handled = handled_auth_;
if (set_handled)
handled_auth_ = true;
return was_handled;
}
// Notify observers that authentication is needed or received. The automation
// proxy uses this for testing.
void SendNotifications() {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
WebContents* requesting_contents = GetWebContentsForLogin();
if (!requesting_contents)
return;
NavigationController* controller = requesting_contents->controller();
if (!WasAuthHandled(false)) {
LoginNotificationDetails details(this);
service->Notify(NotificationType::AUTH_NEEDED,
Source<NavigationController>(controller),
Details<LoginNotificationDetails>(&details));
} else {
service->Notify(NotificationType::AUTH_SUPPLIED,
Source<NavigationController>(controller),
NotificationService::NoDetails());
}
}
// True if we've handled auth (SetAuth or CancelAuth has been called).
bool handled_auth_;
Lock handled_auth_lock_;
// The ConstrainedWindow that is hosting our LoginView.
// This should only be accessed on the ui_loop_.
ConstrainedWindow* dialog_;
// The MessageLoop of the thread that the ChromeViewContents lives in.
MessageLoop* ui_loop_;
// The request that wants login data.
// This should only be accessed on the request_loop_.
URLRequest* request_;
// The MessageLoop of the thread that the URLRequest lives in.
MessageLoop* request_loop_;
// The LoginView that contains the user's login information
LoginView* login_view_;
// The PasswordForm sent to the PasswordManager. This is so we can refer to it
// when later notifying the password manager if the credentials were accepted
// or rejected.
// This should only be accessed on the ui_loop_.
PasswordForm password_form_;
// Points to the password manager owned by the TabContents requesting auth.
// Can be null if the TabContents is not a WebContents.
// This should only be accessed on the ui_loop_.
PasswordManager* password_manager_;
// Cached from the URLRequest, in case it goes NULL on us.
int render_process_host_id_;
int tab_contents_id_;
DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);
};
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)
: auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
WebContents* parent_contents = handler_->GetWebContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
wstring explanation = auth_info_->realm.empty() ?
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,
auth_info_->host) :
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host,
auth_info_->realm);
LoginView* view = new LoginView(explanation);
// Tell the password manager to look for saved passwords. There is only
// a password manager when dealing with a WebContents type.
if (parent_contents->type() == TAB_CONTENTS_WEB) {
PasswordManager* password_manager =
parent_contents->AsWebContents()->GetPasswordManager();
// Set the model for the login view. The model (password manager) is owned
// by the view's parent TabContents, so natural destruction order means we
// don't have to worry about calling SetModel(NULL), because the view will
// be deleted before the password manager.
view->SetModel(password_manager);
std::vector<PasswordForm> v;
MakeInputForPasswordManager(parent_contents->GetURL(), &v);
password_manager->PasswordFormsSeen(v);
handler_->set_password_manager(password_manager);
}
handler_->set_login_view(view);
ConstrainedWindow* dialog =
parent_contents->CreateConstrainedDialog(handler_, view);
handler_->InitWithDialog(dialog);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
const GURL& origin_url,
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
dialog_form.origin = origin_url;
dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->set_password_form(dialog_form);
}
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandlerImpl* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request,
MessageLoop* ui_loop) {
LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);
ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));
return handler;
}
<commit_msg>bustage fix - moved file<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/login_prompt.h"
#include "base/command_line.h"
#include "base/lock.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/browser/views/login_view.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/notification_service.h"
#include "chrome/views/window/dialog_delegate.h"
#include "grit/generated_resources.h"
#include "net/base/auth.h"
#include "net/url_request/url_request.h"
using namespace std;
using views::LoginView;
class LoginHandlerImpl;
// Helper to remove the ref from an URLRequest to the LoginHandler.
// Should only be called from the IO thread, since it accesses an URLRequest.
static void ResetLoginHandlerForRequest(URLRequest* request) {
ResourceDispatcherHost::ExtraRequestInfo* info =
ResourceDispatcherHost::ExtraInfoForRequest(request);
if (!info)
return;
info->login_handler = NULL;
}
// Get the signon_realm under which this auth info should be stored.
//
// The format of the signon_realm for proxy auth is:
// proxy-host/auth-realm
// The format of the signon_realm for server auth is:
// url-scheme://url-host[:url-port]/auth-realm
//
// Be careful when changing this function, since you could make existing
// saved logins un-retrievable.
std::string GetSignonRealm(const GURL& url,
const net::AuthChallengeInfo& auth_info) {
std::string signon_realm;
if (auth_info.is_proxy) {
signon_realm = WideToASCII(auth_info.host);
signon_realm.append("/");
} else {
// Take scheme, host, and port from the url.
signon_realm = url.GetOrigin().spec();
// This ends with a "/".
}
signon_realm.append(WideToUTF8(auth_info.realm));
return signon_realm;
}
// ----------------------------------------------------------------------------
// LoginHandlerImpl
// This class simply forwards the authentication from the LoginView (on
// the UI thread) to the URLRequest (on the I/O thread).
// This class uses ref counting to ensure that it lives until all InvokeLaters
// have been called.
class LoginHandlerImpl : public LoginHandler,
public base::RefCountedThreadSafe<LoginHandlerImpl>,
public views::DialogDelegate {
public:
LoginHandlerImpl(URLRequest* request, MessageLoop* ui_loop)
: dialog_(NULL),
handled_auth_(false),
request_(request),
request_loop_(MessageLoop::current()),
ui_loop_(ui_loop),
password_manager_(NULL) {
DCHECK(request_) << "LoginHandler constructed with NULL request";
AddRef(); // matched by ReleaseLater.
if (!tab_util::GetTabContentsID(request_, &render_process_host_id_,
&tab_contents_id_)) {
NOTREACHED();
}
}
~LoginHandlerImpl() {
}
// Initialize the UI part of the LoginHandler.
// Scary thread safety note: This can potentially be called *after* SetAuth
// or CancelAuth (say, if the request was cancelled before the UI thread got
// control). However, that's OK since any UI interaction in those functions
// will occur via an InvokeLater on the UI thread, which is guaranteed
// to happen after this is called (since this was InvokeLater'd first).
void InitWithDialog(ConstrainedWindow* dlg) {
DCHECK(MessageLoop::current() == ui_loop_);
dialog_ = dlg;
SendNotifications();
}
// Returns the WebContents that needs authentication.
WebContents* GetWebContentsForLogin() {
DCHECK(MessageLoop::current() == ui_loop_);
return tab_util::GetWebContentsByID(render_process_host_id_,
tab_contents_id_);
}
void set_login_view(LoginView* login_view) {
login_view_ = login_view;
}
void set_password_form(const PasswordForm& form) {
password_form_ = form;
}
void set_password_manager(PasswordManager* password_manager) {
password_manager_ = password_manager;
}
// views::DialogDelegate methods:
virtual std::wstring GetDialogButtonLabel(DialogButton button) const {
if (button == DIALOGBUTTON_OK)
return l10n_util::GetString(IDS_LOGIN_DIALOG_OK_BUTTON_LABEL);
return DialogDelegate::GetDialogButtonLabel(button);
}
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(IDS_LOGIN_DIALOG_TITLE);
}
virtual void WindowClosing() {
DCHECK(MessageLoop::current() == ui_loop_);
// Reference is no longer valid.
dialog_ = NULL;
if (!WasAuthHandled(true)) {
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
SendNotifications();
}
}
virtual void DeleteDelegate() {
// Delete this object once all InvokeLaters have been called.
request_loop_->ReleaseSoon(FROM_HERE, this);
}
virtual bool Cancel() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
CancelAuth();
return true;
}
virtual bool Accept() {
DCHECK(MessageLoop::current() == ui_loop_);
DCHECK(dialog_) << "LoginHandler invoked without being attached";
SetAuth(login_view_->GetUsername(), login_view_->GetPassword());
return true;
}
virtual views::View* GetContentsView() {
return login_view_;
}
// LoginHandler:
virtual void SetAuth(const std::wstring& username,
const std::wstring& password) {
if (WasAuthHandled(true))
return;
// Tell the password manager the credentials were submitted / accepted.
if (password_manager_) {
password_form_.username_value = username;
password_form_.password_value = password;
password_manager_->ProvisionallySavePassword(password_form_);
}
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SetAuthDeferred, username, password));
}
virtual void CancelAuth() {
if (WasAuthHandled(true))
return;
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CloseContentsDeferred));
ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::SendNotifications));
request_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &LoginHandlerImpl::CancelAuthDeferred));
}
virtual void OnRequestCancelled() {
DCHECK(MessageLoop::current() == request_loop_) <<
"Why is OnRequestCancelled called from the UI thread?";
// Reference is no longer valid.
request_ = NULL;
// Give up on auth if the request was cancelled.
CancelAuth();
}
private:
// Calls SetAuth from the request_loop.
void SetAuthDeferred(const std::wstring& username,
const std::wstring& password) {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->SetAuth(username, password);
ResetLoginHandlerForRequest(request_);
}
}
// Calls CancelAuth from the request_loop.
void CancelAuthDeferred() {
DCHECK(MessageLoop::current() == request_loop_);
if (request_) {
request_->CancelAuth();
// Verify that CancelAuth does destroy the request via our delegate.
DCHECK(request_ != NULL);
ResetLoginHandlerForRequest(request_);
}
}
// Closes the view_contents from the UI loop.
void CloseContentsDeferred() {
DCHECK(MessageLoop::current() == ui_loop_);
// The hosting ConstrainedWindow may have been freed.
if (dialog_)
dialog_->CloseConstrainedWindow();
}
// Returns whether authentication had been handled (SetAuth or CancelAuth).
// If |set_handled| is true, it will mark authentication as handled.
bool WasAuthHandled(bool set_handled) {
AutoLock lock(handled_auth_lock_);
bool was_handled = handled_auth_;
if (set_handled)
handled_auth_ = true;
return was_handled;
}
// Notify observers that authentication is needed or received. The automation
// proxy uses this for testing.
void SendNotifications() {
DCHECK(MessageLoop::current() == ui_loop_);
NotificationService* service = NotificationService::current();
WebContents* requesting_contents = GetWebContentsForLogin();
if (!requesting_contents)
return;
NavigationController* controller = requesting_contents->controller();
if (!WasAuthHandled(false)) {
LoginNotificationDetails details(this);
service->Notify(NotificationType::AUTH_NEEDED,
Source<NavigationController>(controller),
Details<LoginNotificationDetails>(&details));
} else {
service->Notify(NotificationType::AUTH_SUPPLIED,
Source<NavigationController>(controller),
NotificationService::NoDetails());
}
}
// True if we've handled auth (SetAuth or CancelAuth has been called).
bool handled_auth_;
Lock handled_auth_lock_;
// The ConstrainedWindow that is hosting our LoginView.
// This should only be accessed on the ui_loop_.
ConstrainedWindow* dialog_;
// The MessageLoop of the thread that the ChromeViewContents lives in.
MessageLoop* ui_loop_;
// The request that wants login data.
// This should only be accessed on the request_loop_.
URLRequest* request_;
// The MessageLoop of the thread that the URLRequest lives in.
MessageLoop* request_loop_;
// The LoginView that contains the user's login information
LoginView* login_view_;
// The PasswordForm sent to the PasswordManager. This is so we can refer to it
// when later notifying the password manager if the credentials were accepted
// or rejected.
// This should only be accessed on the ui_loop_.
PasswordForm password_form_;
// Points to the password manager owned by the TabContents requesting auth.
// Can be null if the TabContents is not a WebContents.
// This should only be accessed on the ui_loop_.
PasswordManager* password_manager_;
// Cached from the URLRequest, in case it goes NULL on us.
int render_process_host_id_;
int tab_contents_id_;
DISALLOW_EVIL_CONSTRUCTORS(LoginHandlerImpl);
};
// ----------------------------------------------------------------------------
// LoginDialogTask
// This task is run on the UI thread and creates a constrained window with
// a LoginView to prompt the user. The response will be sent to LoginHandler,
// which then routes it to the URLRequest on the I/O thread.
class LoginDialogTask : public Task {
public:
LoginDialogTask(net::AuthChallengeInfo* auth_info, LoginHandlerImpl* handler)
: auth_info_(auth_info), handler_(handler) {
}
virtual ~LoginDialogTask() {
}
void Run() {
WebContents* parent_contents = handler_->GetWebContentsForLogin();
if (!parent_contents) {
// The request was probably cancelled.
return;
}
wstring explanation = auth_info_->realm.empty() ?
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION_NO_REALM,
auth_info_->host) :
l10n_util::GetStringF(IDS_LOGIN_DIALOG_DESCRIPTION,
auth_info_->host,
auth_info_->realm);
LoginView* view = new LoginView(explanation);
// Tell the password manager to look for saved passwords. There is only
// a password manager when dealing with a WebContents type.
if (parent_contents->type() == TAB_CONTENTS_WEB) {
PasswordManager* password_manager =
parent_contents->AsWebContents()->GetPasswordManager();
// Set the model for the login view. The model (password manager) is owned
// by the view's parent TabContents, so natural destruction order means we
// don't have to worry about calling SetModel(NULL), because the view will
// be deleted before the password manager.
view->SetModel(password_manager);
std::vector<PasswordForm> v;
MakeInputForPasswordManager(parent_contents->GetURL(), &v);
password_manager->PasswordFormsSeen(v);
handler_->set_password_manager(password_manager);
}
handler_->set_login_view(view);
ConstrainedWindow* dialog =
parent_contents->CreateConstrainedDialog(handler_, view);
handler_->InitWithDialog(dialog);
}
private:
// Helper to create a PasswordForm and stuff it into a vector as input
// for PasswordManager::PasswordFormsSeen, the hook into PasswordManager.
void MakeInputForPasswordManager(
const GURL& origin_url,
std::vector<PasswordForm>* password_manager_input) {
PasswordForm dialog_form;
if (LowerCaseEqualsASCII(auth_info_->scheme, "basic")) {
dialog_form.scheme = PasswordForm::SCHEME_BASIC;
} else if (LowerCaseEqualsASCII(auth_info_->scheme, "digest")) {
dialog_form.scheme = PasswordForm::SCHEME_DIGEST;
} else {
dialog_form.scheme = PasswordForm::SCHEME_OTHER;
}
dialog_form.origin = origin_url;
dialog_form.signon_realm = GetSignonRealm(dialog_form.origin, *auth_info_);
password_manager_input->push_back(dialog_form);
// Set the password form for the handler (by copy).
handler_->set_password_form(dialog_form);
}
// Info about who/where/what is asking for authentication.
scoped_refptr<net::AuthChallengeInfo> auth_info_;
// Where to send the authentication when obtained.
// This is owned by the ResourceDispatcherHost that invoked us.
LoginHandlerImpl* handler_;
DISALLOW_EVIL_CONSTRUCTORS(LoginDialogTask);
};
// ----------------------------------------------------------------------------
// Public API
LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
URLRequest* request,
MessageLoop* ui_loop) {
LoginHandlerImpl* handler = new LoginHandlerImpl(request, ui_loop);
ui_loop->PostTask(FROM_HERE, new LoginDialogTask(auth_info, handler));
return handler;
}
<|endoftext|>
|
<commit_before>#include "pprint/c_pprint.hpp"
#include <ostream>
#include <string>
#include <vector>
#include <stdexcept>
namespace bfc {
namespace pprint {
c_pprint::c_pprint(void) = default;
/* Halp I feel so dirty halp. */
c_pprint::config::config(void) :
prelude{
"#include <stdio.h>",
"static unsigned char mem[30000];",
"static unsigned char *bfc_hp = mem + 10000;",
"#define bfc_add(off, val) (bfc_hp[(off)] += (val))",
"#define bfc_sub(off, val) (bfc_hp[(off)] -= (val))",
"#define bfc_mov(off) (bfc_hp += (off))",
"#define bfc_mul(off, val) \
do { \
bfc_hp[(off)] += *bfc_hp * (val); \
*bfc_hp = 0; \
} while(0)",
"#define bfc_getc(off) \
do { \
int _bfc_ch = getchar(); \
if (_bfc_ch != EOF) \
bfc_hp[(off)] = _bfc_ch; \
} while (0)",
"#define bfc_putc(off) putchar(bfc_hp[(off)])",
"int main(void) {"
},
postlude {
" return 0;",
"}"
},
label_prefix{"bfc_l"},
hp_iden{"bfc_hp"},
getc_iden{"bfc_getc"},
putc_iden{"bfc_putc"},
add_iden{"bfc_add"},
sub_iden{"bfc_sub"},
mul_iden{"bfc_mul"},
mov_iden{"bfc_mov"}
/*set_iden{"bfc_set"}*/
{}
namespace {
class pp_delegate : public ast::visitor {
using label_id = unsigned long;
public:
pp_delegate(std::ostream &out, const c_pprint::config &opts) :
ast::visitor{}, next_label_id{0}, opts{opts}, sink{out}
{}
void emit(const ast::node &node)
{
node.accept(*this);
}
ast::visitor::status visit(const ast::program &prgm) override
{
pp_prelude();
for (auto &node: prgm)
node.accept(*this);
pp_postlude();
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::loop &loop) override
{
auto begin_id = get_label();
auto end_id = get_label();
pp_label(begin_id);
pp_bez(end_id);
for (auto &node: loop)
node.accept(*this);
pp_bnz(begin_id);
pp_label(end_id);
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::add &node) override
{
pp_add(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::sub &node) override
{
pp_sub(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mul &node) override
{
pp_mul(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mov &node) override
{
pp_mov(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::read &node) override
{
pp_getc(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::write &node) override
{
pp_putc(node.offset());
return ast::visitor::CONTINUE;
}
private:
label_id get_label(void) noexcept
{
auto id = next_label_id;
next_label_id += 1;
return id;
}
void pp_indent(void) const
{
sink << ' ' << ' ';
}
void pp_indent(unsigned long nlevels) const
{
while (nlevels--)
pp_indent();
}
template <class InputIt>
void pp_iter(InputIt begin, InputIt end) const
{
for (; begin != end; ++begin)
sink << *begin << std::endl;
}
void pp_label_name(unsigned long id)
{
sink << opts.label_prefix << id;
}
void pp_label(unsigned long id)
{
pp_label_name(id);
sink << ':' << std::endl;
}
void pp_jump(unsigned long id)
{
pp_indent();
sink << "goto ";
pp_label_name(id);
sink << ';' << std::endl;
}
void pp_bez(label_id id)
{
pp_branch(id, true);
}
void pp_bnz(label_id id)
{
pp_branch(id, false);
}
void pp_branch(label_id id, bool invert)
{
pp_indent();
sink << "if (";
if (invert)
sink << '!';
sink << "*" << opts.hp_iden;
sink << ')' << std::endl;
pp_indent(2);
pp_jump(id);
}
void pp_fn(const char *fn)
{
pp_indent();
sink << fn << "();" << std::endl;
}
template <class Arg>
void pp_fn(const char *fn, Arg &&arg)
{
pp_indent();
sink << fn << '(' << arg << ");" << std::endl;
}
template <class Arg, class ...Args>
void pp_fn(const char *fn, Arg &&arg, Args &&...args)
{
pp_indent();
sink << fn << '(' << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
sink << ");" << std::endl;
}
template <class Arg>
void pp_fn_recur(Arg &&arg)
{
sink << ", " << std::forward<Arg>(arg);
}
template <class Arg, class ...Args>
void pp_fn_recur(Arg &&arg, Args &&...args)
{
sink << ", " << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
}
void pp_prelude(void) const
{
auto &vec = opts.prelude;
pp_iter(vec.begin(), vec.end());
}
void pp_postlude(void) const
{
auto &vec = opts.postlude;
pp_iter(vec.begin(), vec.end());
}
void pp_add(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.add_iden.data(), offset, value);
}
void pp_sub(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.sub_iden.data(), offset, value);
}
void pp_mul(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.mul_iden.data(), offset, value);
}
void pp_getc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.getc_iden.data(), offset);
}
void pp_putc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.putc_iden.data(), offset);
}
void pp_mov(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.mov_iden.data(), offset);
}
label_id next_label_id;
const c_pprint::config &opts;
std::ostream &sink;
};
}
void
c_pprint::emit(std::ostream &out, const ast::node &node)
{
auto pp = pp_delegate{out, opts};
pp.emit(node);
}
}
}
<commit_msg>squelch order warning<commit_after>#include "pprint/c_pprint.hpp"
#include <ostream>
#include <string>
#include <vector>
#include <stdexcept>
namespace bfc {
namespace pprint {
c_pprint::c_pprint(void) = default;
/* Halp I feel so dirty halp. */
c_pprint::config::config(void) :
prelude{
"#include <stdio.h>",
"static unsigned char mem[30000];",
"static unsigned char *bfc_hp = mem + 10000;",
"#define bfc_add(off, val) (bfc_hp[(off)] += (val))",
"#define bfc_sub(off, val) (bfc_hp[(off)] -= (val))",
"#define bfc_mov(off) (bfc_hp += (off))",
"#define bfc_mul(off, val) \
do { \
bfc_hp[(off)] += *bfc_hp * (val); \
*bfc_hp = 0; \
} while(0)",
"#define bfc_getc(off) \
do { \
int _bfc_ch = getchar(); \
if (_bfc_ch != EOF) \
bfc_hp[(off)] = _bfc_ch; \
} while (0)",
"#define bfc_putc(off) putchar(bfc_hp[(off)])",
"int main(void) {"
},
postlude {
" return 0;",
"}"
},
label_prefix{"bfc_l"},
hp_iden{"bfc_hp"},
mov_iden{"bfc_mov"},
getc_iden{"bfc_getc"},
putc_iden{"bfc_putc"},
add_iden{"bfc_add"},
sub_iden{"bfc_sub"},
mul_iden{"bfc_mul"}
/*set_iden{"bfc_set"}*/
{}
namespace {
class pp_delegate : public ast::visitor {
using label_id = unsigned long;
public:
pp_delegate(std::ostream &out, const c_pprint::config &opts) :
ast::visitor{}, next_label_id{0}, opts{opts}, sink{out}
{}
void emit(const ast::node &node)
{
node.accept(*this);
}
ast::visitor::status visit(const ast::program &prgm) override
{
pp_prelude();
for (auto &node: prgm)
node.accept(*this);
pp_postlude();
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::loop &loop) override
{
auto begin_id = get_label();
auto end_id = get_label();
pp_label(begin_id);
pp_bez(end_id);
for (auto &node: loop)
node.accept(*this);
pp_bnz(begin_id);
pp_label(end_id);
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::add &node) override
{
pp_add(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::sub &node) override
{
pp_sub(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mul &node) override
{
pp_mul(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mov &node) override
{
pp_mov(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::read &node) override
{
pp_getc(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::write &node) override
{
pp_putc(node.offset());
return ast::visitor::CONTINUE;
}
private:
label_id get_label(void) noexcept
{
auto id = next_label_id;
next_label_id += 1;
return id;
}
void pp_indent(void) const
{
sink << ' ' << ' ';
}
void pp_indent(unsigned long nlevels) const
{
while (nlevels--)
pp_indent();
}
template <class InputIt>
void pp_iter(InputIt begin, InputIt end) const
{
for (; begin != end; ++begin)
sink << *begin << std::endl;
}
void pp_label_name(unsigned long id)
{
sink << opts.label_prefix << id;
}
void pp_label(unsigned long id)
{
pp_label_name(id);
sink << ':' << std::endl;
}
void pp_jump(unsigned long id)
{
pp_indent();
sink << "goto ";
pp_label_name(id);
sink << ';' << std::endl;
}
void pp_bez(label_id id)
{
pp_branch(id, true);
}
void pp_bnz(label_id id)
{
pp_branch(id, false);
}
void pp_branch(label_id id, bool invert)
{
pp_indent();
sink << "if (";
if (invert)
sink << '!';
sink << "*" << opts.hp_iden;
sink << ')' << std::endl;
pp_indent(2);
pp_jump(id);
}
void pp_fn(const char *fn)
{
pp_indent();
sink << fn << "();" << std::endl;
}
template <class Arg>
void pp_fn(const char *fn, Arg &&arg)
{
pp_indent();
sink << fn << '(' << arg << ");" << std::endl;
}
template <class Arg, class ...Args>
void pp_fn(const char *fn, Arg &&arg, Args &&...args)
{
pp_indent();
sink << fn << '(' << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
sink << ");" << std::endl;
}
template <class Arg>
void pp_fn_recur(Arg &&arg)
{
sink << ", " << std::forward<Arg>(arg);
}
template <class Arg, class ...Args>
void pp_fn_recur(Arg &&arg, Args &&...args)
{
sink << ", " << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
}
void pp_prelude(void) const
{
auto &vec = opts.prelude;
pp_iter(vec.begin(), vec.end());
}
void pp_postlude(void) const
{
auto &vec = opts.postlude;
pp_iter(vec.begin(), vec.end());
}
void pp_add(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.add_iden.data(), offset, value);
}
void pp_sub(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.sub_iden.data(), offset, value);
}
void pp_mul(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.mul_iden.data(), offset, value);
}
void pp_getc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.getc_iden.data(), offset);
}
void pp_putc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.putc_iden.data(), offset);
}
void pp_mov(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.mov_iden.data(), offset);
}
label_id next_label_id;
const c_pprint::config &opts;
std::ostream &sink;
};
}
void
c_pprint::emit(std::ostream &out, const ast::node &node)
{
auto pp = pp_delegate{out, opts};
pp.emit(node);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// Flakey, http:L//crbug.com/57053
TEST_F(PPAPITest, FLAKY_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
// TODO(dumi): figure out why this test is flaky on Mac and Win XP (dbg).
#if defined(OS_MACOSX) || defined(OS_WIN)
#define DISABLED_ON_MAC_AND_WIN(test_name) DISABLED_##test_name
#else
#define DISABLED_ON_MAC_AND_WIN(test_name) test_name
#endif
TEST_F(PPAPITest, DISABLED_ON_MAC_AND_WIN(FileIO)) {
RunTestViaHTTP("FileIO");
}
TEST_F(PPAPITest, FileRef) {
RunTestViaHTTP("FileRef");
}
TEST_F(PPAPITest, DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
<commit_msg>Disable crashy PPAPITest.FileIO/FileRef.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "build/build_config.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/glue/plugins/plugin_switches.h"
namespace {
// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif
} // namespace
class PPAPITest : public UITest {
public:
PPAPITest() {
// Append the switch to register the pepper plugin.
// library name = <out dir>/<test_name>.<library_extension>
// MIME type = application/x-ppapi-<test_name>
FilePath plugin_dir;
PathService::Get(base::DIR_EXE, &plugin_dir);
FilePath plugin_lib = plugin_dir.Append(library_name);
EXPECT_TRUE(file_util::PathExists(plugin_lib));
FilePath::StringType pepper_plugin = plugin_lib.value();
pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_plugin);
// The test sends us the result via a cookie.
launch_arguments_.AppendSwitch(switches::kEnableFileCookies);
// Some stuff is hung off of the testing interface which is not enabled
// by default.
launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);
// Give unlimited quota for files to Pepper tests.
// TODO(dumi): remove this switch once we have a quota management
// system in place.
launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);
}
void RunTest(const std::string& test_case) {
FilePath test_path;
PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
// Sanity check the file name.
EXPECT_TRUE(file_util::PathExists(test_path));
GURL::Replacements replacements;
replacements.SetQuery(test_case.c_str(),
url_parse::Component(0, test_case.size()));
GURL test_url = net::FilePathToFileURL(test_path);
RunTestURL(test_url.ReplaceComponents(replacements));
}
void RunTestViaHTTP(const std::string& test_case) {
net::TestServer test_server(
net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("ppapi/tests")));
ASSERT_TRUE(test_server.Start());
RunTestURL(test_server.GetURL("files/test_case.html?" + test_case));
}
private:
void RunTestURL(const GURL& test_url) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(test_url));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), test_url,
"COMPLETION_COOKIE", action_max_timeout_ms());
EXPECT_STREQ("PASS", escaped_value.c_str());
}
};
TEST_F(PPAPITest, FAILS_Instance) {
RunTest("Instance");
}
TEST_F(PPAPITest, Graphics2D) {
RunTest("Graphics2D");
}
// TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.
// Possibly all the image allocations slow things down on a loaded bot too much.
TEST_F(PPAPITest, FLAKY_ImageData) {
RunTest("ImageData");
}
TEST_F(PPAPITest, Buffer) {
RunTest("Buffer");
}
// Flakey, http:L//crbug.com/57053
TEST_F(PPAPITest, FLAKY_URLLoader) {
RunTestViaHTTP("URLLoader");
}
// Flaky, http://crbug.com/51012
TEST_F(PPAPITest, FLAKY_PaintAggregator) {
RunTestViaHTTP("PaintAggregator");
}
// Flaky, http://crbug.com/48544.
TEST_F(PPAPITest, FLAKY_Scrollbar) {
RunTest("Scrollbar");
}
TEST_F(PPAPITest, UrlUtil) {
RunTest("UrlUtil");
}
TEST_F(PPAPITest, CharSet) {
RunTest("CharSet");
}
TEST_F(PPAPITest, Var) {
RunTest("Var");
}
// TODO(dumi): figure out why this test is flaky / crashing.
TEST_F(PPAPITest, DISABLED_FileIO) {
RunTestViaHTTP("FileIO");
}
// TODO(dumi): figure out why this test is flaky / crashing.
TEST_F(PPAPITest, DISABLED_FileRef) {
RunTestViaHTTP("FileRef");
}
TEST_F(PPAPITest, DirectoryReader) {
RunTestViaHTTP("DirectoryReader");
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/views/controls/label.h"
#include <math.h>
#include "app/gfx/chrome_canvas.h"
#include "app/gfx/chrome_font.h"
#include "app/gfx/insets.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/gfx/text_elider.h"
#include "chrome/views/background.h"
namespace views {
const char Label::kViewClassName[] = "chrome/views/Label";
static const SkColor kEnabledColor = SK_ColorBLACK;
static const SkColor kDisabledColor = SkColorSetRGB(161, 161, 146);
static const int kFocusBorderPadding = 1;
Label::Label() {
Init(L"", GetDefaultFont());
}
Label::Label(const std::wstring& text) {
Init(text, GetDefaultFont());
}
Label::Label(const std::wstring& text, const ChromeFont& font) {
Init(text, font);
}
void Label::Init(const std::wstring& text, const ChromeFont& font) {
contains_mouse_ = false;
font_ = font;
text_size_valid_ = false;
SetText(text);
url_set_ = false;
color_ = kEnabledColor;
horiz_alignment_ = ALIGN_CENTER;
is_multi_line_ = false;
allow_character_break_ = false;
collapse_when_hidden_ = false;
rtl_alignment_mode_ = USE_UI_ALIGNMENT;
paint_as_focused_ = false;
has_focus_border_ = false;
}
Label::~Label() {
}
gfx::Size Label::GetPreferredSize() {
gfx::Size prefsize;
// Return a size of (0, 0) if the label is not visible and if the
// collapse_when_hidden_ flag is set.
// TODO(munjal): This logic probably belongs to the View class. But for now,
// put it here since putting it in View class means all inheriting classes
// need ot respect the collapse_when_hidden_ flag.
if (!IsVisible() && collapse_when_hidden_)
return prefsize;
if (is_multi_line_) {
int w = width(), h = 0;
ChromeCanvas::SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());
prefsize.SetSize(w, h);
} else {
prefsize = GetTextSize();
}
gfx::Insets insets = GetInsets();
prefsize.Enlarge(insets.width(), insets.height());
return prefsize;
}
int Label::ComputeMultiLineFlags() {
int flags = ChromeCanvas::MULTI_LINE;
if (allow_character_break_)
flags |= ChromeCanvas::CHARACTER_BREAK;
switch (horiz_alignment_) {
case ALIGN_LEFT:
flags |= ChromeCanvas::TEXT_ALIGN_LEFT;
break;
case ALIGN_CENTER:
flags |= ChromeCanvas::TEXT_ALIGN_CENTER;
break;
case ALIGN_RIGHT:
flags |= ChromeCanvas::TEXT_ALIGN_RIGHT;
break;
}
return flags;
}
void Label::CalculateDrawStringParams(
std::wstring* paint_text, gfx::Rect* text_bounds, int* flags) {
DCHECK(paint_text && text_bounds && flags);
if (url_set_) {
// TODO(jungshik) : Figure out how to get 'intl.accept_languages'
// preference and use it when calling ElideUrl.
*paint_text = gfx::ElideUrl(url_, font_, width(), std::wstring());
// An URLs is always treated as an LTR text and therefore we should
// explicitly mark it as such if the locale is RTL so that URLs containing
// Hebrew or Arabic characters are displayed correctly.
//
// Note that we don't check the View's UI layout setting in order to
// determine whether or not to insert the special Unicode formatting
// characters. We use the locale settings because an URL is always treated
// as an LTR string, even if its containing view does not use an RTL UI
// layout.
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)
l10n_util::WrapStringWithLTRFormatting(paint_text);
} else {
*paint_text = text_;
}
if (is_multi_line_) {
gfx::Insets insets = GetInsets();
text_bounds->SetRect(insets.left(),
insets.top(),
width() - insets.width(),
height() - insets.height());
*flags = ComputeMultiLineFlags();
} else {
*text_bounds = GetTextBounds();
*flags = 0;
}
}
void Label::Paint(ChromeCanvas* canvas) {
PaintBackground(canvas);
std::wstring paint_text;
gfx::Rect text_bounds;
int flags = 0;
CalculateDrawStringParams(&paint_text, &text_bounds, &flags);
canvas->DrawStringInt(paint_text,
font_,
color_,
text_bounds.x(),
text_bounds.y(),
text_bounds.width(),
text_bounds.height(),
flags);
// The focus border always hugs the text, regardless of the label's bounds.
if (HasFocus() || paint_as_focused_) {
int w = text_bounds.width();
int h = 0;
// We explicitly OR in MULTI_LINE here since SizeStringInt seems to return
// an incorrect height for single line text when the MULTI_LINE flag isn't
// specified. o_O...
ChromeCanvas::SizeStringInt(paint_text, font_, &w, &h,
flags | ChromeCanvas::MULTI_LINE);
gfx::Rect focus_rect = text_bounds;
focus_rect.set_width(w);
focus_rect.set_height(h);
focus_rect.Inset(-kFocusBorderPadding, -kFocusBorderPadding);
canvas->DrawFocusRect(focus_rect.x(), focus_rect.y(), focus_rect.width(),
focus_rect.height());
}
}
void Label::PaintBackground(ChromeCanvas* canvas) {
const Background* bg = contains_mouse_ ? GetMouseOverBackground() : NULL;
if (!bg)
bg = background();
if (bg)
bg->Paint(canvas, this);
}
void Label::SetFont(const ChromeFont& font) {
font_ = font;
text_size_valid_ = false;
SchedulePaint();
}
ChromeFont Label::GetFont() const {
return font_;
}
void Label::SetText(const std::wstring& text) {
text_ = text;
url_set_ = false;
text_size_valid_ = false;
SchedulePaint();
}
void Label::SetURL(const GURL& url) {
url_ = url;
text_ = UTF8ToWide(url_.spec());
url_set_ = true;
text_size_valid_ = false;
SchedulePaint();
}
const std::wstring Label::GetText() const {
if (url_set_)
return UTF8ToWide(url_.spec());
else
return text_;
}
const GURL Label::GetURL() const {
if (url_set_)
return url_;
else
return GURL(WideToUTF8(text_));
}
gfx::Size Label::GetTextSize() {
if (!text_size_valid_) {
text_size_.SetSize(font_.GetStringWidth(text_), font_.height());
text_size_valid_ = true;
}
if (text_size_valid_)
return text_size_;
return gfx::Size();
}
int Label::GetHeightForWidth(int w) {
if (is_multi_line_) {
gfx::Insets insets = GetInsets();
w = std::max<int>(0, w - insets.width());
int h = 0;
ChromeCanvas cc(0, 0, true);
cc.SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());
return h + insets.height();
}
return View::GetHeightForWidth(w);
}
std::string Label::GetClassName() const {
return kViewClassName;
}
void Label::SetColor(const SkColor& color) {
color_ = color;
}
const SkColor Label::GetColor() const {
return color_;
}
void Label::SetHorizontalAlignment(Alignment a) {
// If the View's UI layout is right-to-left and rtl_alignment_mode_ is
// USE_UI_ALIGNMENT, we need to flip the alignment so that the alignment
// settings take into account the text directionality.
if (UILayoutIsRightToLeft() && rtl_alignment_mode_ == USE_UI_ALIGNMENT) {
if (a == ALIGN_LEFT)
a = ALIGN_RIGHT;
else if (a == ALIGN_RIGHT)
a = ALIGN_LEFT;
}
if (horiz_alignment_ != a) {
horiz_alignment_ = a;
SchedulePaint();
}
}
Label::Alignment Label::GetHorizontalAlignment() const {
return horiz_alignment_;
}
void Label::SetRTLAlignmentMode(RTLAlignmentMode mode) {
rtl_alignment_mode_ = mode;
}
Label::RTLAlignmentMode Label::GetRTLAlignmentMode() const {
return rtl_alignment_mode_;
}
void Label::SetMultiLine(bool f) {
if (f != is_multi_line_) {
is_multi_line_ = f;
SchedulePaint();
}
}
void Label::SetAllowCharacterBreak(bool f) {
if (f != allow_character_break_) {
allow_character_break_ = f;
SchedulePaint();
}
}
bool Label::IsMultiLine() {
return is_multi_line_;
}
void Label::SetTooltipText(const std::wstring& tooltip_text) {
tooltip_text_ = tooltip_text;
}
bool Label::GetTooltipText(int x, int y, std::wstring* tooltip) {
DCHECK(tooltip);
// If a tooltip has been explicitly set, use it.
if (!tooltip_text_.empty()) {
tooltip->assign(tooltip_text_);
return true;
}
// Show the full text if the text does not fit.
if (!is_multi_line_ && font_.GetStringWidth(text_) > width()) {
*tooltip = text_;
return true;
}
return false;
}
void Label::OnMouseMoved(const MouseEvent& e) {
UpdateContainsMouse(e);
}
void Label::OnMouseEntered(const MouseEvent& event) {
UpdateContainsMouse(event);
}
void Label::OnMouseExited(const MouseEvent& event) {
SetContainsMouse(false);
}
void Label::SetMouseOverBackground(Background* background) {
mouse_over_background_.reset(background);
}
const Background* Label::GetMouseOverBackground() const {
return mouse_over_background_.get();
}
void Label::SetEnabled(bool enabled) {
if (enabled == enabled_)
return;
View::SetEnabled(enabled);
SetColor(enabled ? kEnabledColor : kDisabledColor);
}
gfx::Insets Label::GetInsets() const {
gfx::Insets insets = View::GetInsets();
if (IsFocusable() || has_focus_border_) {
insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,
kFocusBorderPadding, kFocusBorderPadding);
}
return insets;
}
// static
ChromeFont Label::GetDefaultFont() {
return ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);
}
void Label::UpdateContainsMouse(const MouseEvent& event) {
SetContainsMouse(GetTextBounds().Contains(event.x(), event.y()));
}
void Label::SetContainsMouse(bool contains_mouse) {
if (contains_mouse_ == contains_mouse)
return;
contains_mouse_ = contains_mouse;
if (GetMouseOverBackground())
SchedulePaint();
}
gfx::Rect Label::GetTextBounds() {
gfx::Size text_size = GetTextSize();
gfx::Insets insets = GetInsets();
int avail_width = width() - insets.width();
// Respect the size set by the owner view
text_size.set_width(std::min(avail_width, text_size.width()));
int text_y = insets.top() +
(height() - text_size.height() - insets.height()) / 2;
int text_x;
switch (horiz_alignment_) {
case ALIGN_LEFT:
text_x = insets.left();
break;
case ALIGN_CENTER:
// We put any extra margin pixel on the left rather than the right, since
// GetTextExtentPoint32() can report a value one too large on the right.
text_x = insets.left() + (avail_width + 1 - text_size.width()) / 2;
break;
case ALIGN_RIGHT:
text_x = width() - insets.right() - text_size.width();
break;
default:
NOTREACHED();
text_x = 0;
break;
}
return gfx::Rect(text_x, text_y, text_size.width(), text_size.height());
}
void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<std::wstring> lines;
SplitString(text_, L'\n', &lines);
int label_width = 0;
for (std::vector<std::wstring>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width, font_.GetStringWidth(*iter));
}
gfx::Insets insets = GetInsets();
label_width += insets.width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
bool Label::GetAccessibleRole(AccessibilityTypes::Role* role) {
DCHECK(role);
*role = AccessibilityTypes::ROLE_TEXT;
return true;
}
bool Label::GetAccessibleName(std::wstring* name) {
*name = GetText();
return true;
}
bool Label::GetAccessibleState(AccessibilityTypes::State* state) {
DCHECK(state);
*state = AccessibilityTypes::STATE_READONLY;
return true;
}
} // namespace views
<commit_msg>This CL fixes issue 4376 -- Press "Tab" key to navigate - Text focus is showing at wrong place in Hebrew and Arabic. (http://crbug.com/4376)<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/views/controls/label.h"
#include <math.h>
#include "app/gfx/chrome_canvas.h"
#include "app/gfx/chrome_font.h"
#include "app/gfx/insets.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/gfx/text_elider.h"
#include "chrome/views/background.h"
namespace views {
const char Label::kViewClassName[] = "chrome/views/Label";
static const SkColor kEnabledColor = SK_ColorBLACK;
static const SkColor kDisabledColor = SkColorSetRGB(161, 161, 146);
static const int kFocusBorderPadding = 1;
Label::Label() {
Init(L"", GetDefaultFont());
}
Label::Label(const std::wstring& text) {
Init(text, GetDefaultFont());
}
Label::Label(const std::wstring& text, const ChromeFont& font) {
Init(text, font);
}
void Label::Init(const std::wstring& text, const ChromeFont& font) {
contains_mouse_ = false;
font_ = font;
text_size_valid_ = false;
SetText(text);
url_set_ = false;
color_ = kEnabledColor;
horiz_alignment_ = ALIGN_CENTER;
is_multi_line_ = false;
allow_character_break_ = false;
collapse_when_hidden_ = false;
rtl_alignment_mode_ = USE_UI_ALIGNMENT;
paint_as_focused_ = false;
has_focus_border_ = false;
}
Label::~Label() {
}
gfx::Size Label::GetPreferredSize() {
gfx::Size prefsize;
// Return a size of (0, 0) if the label is not visible and if the
// collapse_when_hidden_ flag is set.
// TODO(munjal): This logic probably belongs to the View class. But for now,
// put it here since putting it in View class means all inheriting classes
// need ot respect the collapse_when_hidden_ flag.
if (!IsVisible() && collapse_when_hidden_)
return prefsize;
if (is_multi_line_) {
int w = width(), h = 0;
ChromeCanvas::SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());
prefsize.SetSize(w, h);
} else {
prefsize = GetTextSize();
}
gfx::Insets insets = GetInsets();
prefsize.Enlarge(insets.width(), insets.height());
return prefsize;
}
int Label::ComputeMultiLineFlags() {
int flags = ChromeCanvas::MULTI_LINE;
if (allow_character_break_)
flags |= ChromeCanvas::CHARACTER_BREAK;
switch (horiz_alignment_) {
case ALIGN_LEFT:
flags |= ChromeCanvas::TEXT_ALIGN_LEFT;
break;
case ALIGN_CENTER:
flags |= ChromeCanvas::TEXT_ALIGN_CENTER;
break;
case ALIGN_RIGHT:
flags |= ChromeCanvas::TEXT_ALIGN_RIGHT;
break;
}
return flags;
}
void Label::CalculateDrawStringParams(
std::wstring* paint_text, gfx::Rect* text_bounds, int* flags) {
DCHECK(paint_text && text_bounds && flags);
if (url_set_) {
// TODO(jungshik) : Figure out how to get 'intl.accept_languages'
// preference and use it when calling ElideUrl.
*paint_text = gfx::ElideUrl(url_, font_, width(), std::wstring());
// An URLs is always treated as an LTR text and therefore we should
// explicitly mark it as such if the locale is RTL so that URLs containing
// Hebrew or Arabic characters are displayed correctly.
//
// Note that we don't check the View's UI layout setting in order to
// determine whether or not to insert the special Unicode formatting
// characters. We use the locale settings because an URL is always treated
// as an LTR string, even if its containing view does not use an RTL UI
// layout.
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)
l10n_util::WrapStringWithLTRFormatting(paint_text);
} else {
*paint_text = text_;
}
if (is_multi_line_) {
gfx::Insets insets = GetInsets();
text_bounds->SetRect(insets.left(),
insets.top(),
width() - insets.width(),
height() - insets.height());
*flags = ComputeMultiLineFlags();
} else {
*text_bounds = GetTextBounds();
*flags = 0;
}
}
void Label::Paint(ChromeCanvas* canvas) {
PaintBackground(canvas);
std::wstring paint_text;
gfx::Rect text_bounds;
int flags = 0;
CalculateDrawStringParams(&paint_text, &text_bounds, &flags);
canvas->DrawStringInt(paint_text,
font_,
color_,
text_bounds.x(),
text_bounds.y(),
text_bounds.width(),
text_bounds.height(),
flags);
// The focus border always hugs the text, regardless of the label's bounds.
if (HasFocus() || paint_as_focused_) {
int w = text_bounds.width();
int h = 0;
// We explicitly OR in MULTI_LINE here since SizeStringInt seems to return
// an incorrect height for single line text when the MULTI_LINE flag isn't
// specified. o_O...
ChromeCanvas::SizeStringInt(paint_text, font_, &w, &h,
flags | ChromeCanvas::MULTI_LINE);
gfx::Rect focus_rect = text_bounds;
focus_rect.set_width(w);
focus_rect.set_height(h);
focus_rect.Inset(-kFocusBorderPadding, -kFocusBorderPadding);
canvas->DrawFocusRect(MirroredLeftPointForRect(focus_rect), focus_rect.y(),
focus_rect.width(), focus_rect.height());
}
}
void Label::PaintBackground(ChromeCanvas* canvas) {
const Background* bg = contains_mouse_ ? GetMouseOverBackground() : NULL;
if (!bg)
bg = background();
if (bg)
bg->Paint(canvas, this);
}
void Label::SetFont(const ChromeFont& font) {
font_ = font;
text_size_valid_ = false;
SchedulePaint();
}
ChromeFont Label::GetFont() const {
return font_;
}
void Label::SetText(const std::wstring& text) {
text_ = text;
url_set_ = false;
text_size_valid_ = false;
SchedulePaint();
}
void Label::SetURL(const GURL& url) {
url_ = url;
text_ = UTF8ToWide(url_.spec());
url_set_ = true;
text_size_valid_ = false;
SchedulePaint();
}
const std::wstring Label::GetText() const {
if (url_set_)
return UTF8ToWide(url_.spec());
else
return text_;
}
const GURL Label::GetURL() const {
if (url_set_)
return url_;
else
return GURL(WideToUTF8(text_));
}
gfx::Size Label::GetTextSize() {
if (!text_size_valid_) {
text_size_.SetSize(font_.GetStringWidth(text_), font_.height());
text_size_valid_ = true;
}
if (text_size_valid_)
return text_size_;
return gfx::Size();
}
int Label::GetHeightForWidth(int w) {
if (is_multi_line_) {
gfx::Insets insets = GetInsets();
w = std::max<int>(0, w - insets.width());
int h = 0;
ChromeCanvas cc(0, 0, true);
cc.SizeStringInt(text_, font_, &w, &h, ComputeMultiLineFlags());
return h + insets.height();
}
return View::GetHeightForWidth(w);
}
std::string Label::GetClassName() const {
return kViewClassName;
}
void Label::SetColor(const SkColor& color) {
color_ = color;
}
const SkColor Label::GetColor() const {
return color_;
}
void Label::SetHorizontalAlignment(Alignment a) {
// If the View's UI layout is right-to-left and rtl_alignment_mode_ is
// USE_UI_ALIGNMENT, we need to flip the alignment so that the alignment
// settings take into account the text directionality.
if (UILayoutIsRightToLeft() && rtl_alignment_mode_ == USE_UI_ALIGNMENT) {
if (a == ALIGN_LEFT)
a = ALIGN_RIGHT;
else if (a == ALIGN_RIGHT)
a = ALIGN_LEFT;
}
if (horiz_alignment_ != a) {
horiz_alignment_ = a;
SchedulePaint();
}
}
Label::Alignment Label::GetHorizontalAlignment() const {
return horiz_alignment_;
}
void Label::SetRTLAlignmentMode(RTLAlignmentMode mode) {
rtl_alignment_mode_ = mode;
}
Label::RTLAlignmentMode Label::GetRTLAlignmentMode() const {
return rtl_alignment_mode_;
}
void Label::SetMultiLine(bool f) {
if (f != is_multi_line_) {
is_multi_line_ = f;
SchedulePaint();
}
}
void Label::SetAllowCharacterBreak(bool f) {
if (f != allow_character_break_) {
allow_character_break_ = f;
SchedulePaint();
}
}
bool Label::IsMultiLine() {
return is_multi_line_;
}
void Label::SetTooltipText(const std::wstring& tooltip_text) {
tooltip_text_ = tooltip_text;
}
bool Label::GetTooltipText(int x, int y, std::wstring* tooltip) {
DCHECK(tooltip);
// If a tooltip has been explicitly set, use it.
if (!tooltip_text_.empty()) {
tooltip->assign(tooltip_text_);
return true;
}
// Show the full text if the text does not fit.
if (!is_multi_line_ && font_.GetStringWidth(text_) > width()) {
*tooltip = text_;
return true;
}
return false;
}
void Label::OnMouseMoved(const MouseEvent& e) {
UpdateContainsMouse(e);
}
void Label::OnMouseEntered(const MouseEvent& event) {
UpdateContainsMouse(event);
}
void Label::OnMouseExited(const MouseEvent& event) {
SetContainsMouse(false);
}
void Label::SetMouseOverBackground(Background* background) {
mouse_over_background_.reset(background);
}
const Background* Label::GetMouseOverBackground() const {
return mouse_over_background_.get();
}
void Label::SetEnabled(bool enabled) {
if (enabled == enabled_)
return;
View::SetEnabled(enabled);
SetColor(enabled ? kEnabledColor : kDisabledColor);
}
gfx::Insets Label::GetInsets() const {
gfx::Insets insets = View::GetInsets();
if (IsFocusable() || has_focus_border_) {
insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding,
kFocusBorderPadding, kFocusBorderPadding);
}
return insets;
}
// static
ChromeFont Label::GetDefaultFont() {
return ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);
}
void Label::UpdateContainsMouse(const MouseEvent& event) {
SetContainsMouse(GetTextBounds().Contains(event.x(), event.y()));
}
void Label::SetContainsMouse(bool contains_mouse) {
if (contains_mouse_ == contains_mouse)
return;
contains_mouse_ = contains_mouse;
if (GetMouseOverBackground())
SchedulePaint();
}
gfx::Rect Label::GetTextBounds() {
gfx::Size text_size = GetTextSize();
gfx::Insets insets = GetInsets();
int avail_width = width() - insets.width();
// Respect the size set by the owner view
text_size.set_width(std::min(avail_width, text_size.width()));
int text_y = insets.top() +
(height() - text_size.height() - insets.height()) / 2;
int text_x;
switch (horiz_alignment_) {
case ALIGN_LEFT:
text_x = insets.left();
break;
case ALIGN_CENTER:
// We put any extra margin pixel on the left rather than the right, since
// GetTextExtentPoint32() can report a value one too large on the right.
text_x = insets.left() + (avail_width + 1 - text_size.width()) / 2;
break;
case ALIGN_RIGHT:
text_x = width() - insets.right() - text_size.width();
break;
default:
NOTREACHED();
text_x = 0;
break;
}
return gfx::Rect(text_x, text_y, text_size.width(), text_size.height());
}
void Label::SizeToFit(int max_width) {
DCHECK(is_multi_line_);
std::vector<std::wstring> lines;
SplitString(text_, L'\n', &lines);
int label_width = 0;
for (std::vector<std::wstring>::const_iterator iter = lines.begin();
iter != lines.end(); ++iter) {
label_width = std::max(label_width, font_.GetStringWidth(*iter));
}
gfx::Insets insets = GetInsets();
label_width += insets.width();
if (max_width > 0)
label_width = std::min(label_width, max_width);
SetBounds(x(), y(), label_width, 0);
SizeToPreferredSize();
}
bool Label::GetAccessibleRole(AccessibilityTypes::Role* role) {
DCHECK(role);
*role = AccessibilityTypes::ROLE_TEXT;
return true;
}
bool Label::GetAccessibleName(std::wstring* name) {
*name = GetText();
return true;
}
bool Label::GetAccessibleState(AccessibilityTypes::State* state) {
DCHECK(state);
*state = AccessibilityTypes::STATE_READONLY;
return true;
}
} // namespace views
<|endoftext|>
|
<commit_before>#include <pluginlib/class_list_macros.h>
#include <kdl_parser/kdl_parser.hpp>
#include <math.h>
#include <Eigen/LU>
#include <utils/pseudo_inversion.h>
#include <utils/skew_symmetric.h>
#include <lwr_controllers/one_task_inverse_kinematics.h>
namespace lwr_controllers
{
OneTaskInverseKinematics::OneTaskInverseKinematics() {}
OneTaskInverseKinematics::~OneTaskInverseKinematics() {}
bool OneTaskInverseKinematics::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n)
{
nh_ = n;
// get URDF and name of root and tip from the parameter server
std::string robot_description, root_name, tip_name;
if (!ros::param::search(n.getNamespace(),"robot_description", robot_description))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No robot description (URDF) found on parameter server ("<<n.getNamespace()<<"/robot_description)");
return false;
}
if (!nh_.getParam("root_name", root_name))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No root name found on parameter server ("<<n.getNamespace()<<"/root_name)");
return false;
}
if (!nh_.getParam("tip_name", tip_name))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No tip name found on parameter server ("<<n.getNamespace()<<"/tip_name)");
return false;
}
// Get the gravity vector (direction and magnitude)
KDL::Vector gravity_ = KDL::Vector::Zero();
gravity_(2) = -9.81;
// Construct an URDF model from the xml string
std::string xml_string;
if (n.hasParam(robot_description))
n.getParam(robot_description.c_str(), xml_string);
else
{
ROS_ERROR("Parameter %s not set, shutting down node...", robot_description.c_str());
n.shutdown();
return false;
}
if (xml_string.size() == 0)
{
ROS_ERROR("Unable to load robot model from parameter %s",robot_description.c_str());
n.shutdown();
return false;
}
ROS_DEBUG("%s content\n%s", robot_description.c_str(), xml_string.c_str());
// Get urdf model out of robot_description
urdf::Model model;
if (!model.initString(xml_string))
{
ROS_ERROR("Failed to parse urdf file");
n.shutdown();
return false;
}
ROS_INFO("Successfully parsed urdf file");
KDL::Tree kdl_tree_;
if (!kdl_parser::treeFromUrdfModel(model, kdl_tree_))
{
ROS_ERROR("Failed to construct kdl tree");
n.shutdown();
return false;
}
// Parsing joint limits from urdf model
boost::shared_ptr<const urdf::Link> link_ = model.getLink(tip_name);
boost::shared_ptr<const urdf::Joint> joint_;
joint_limits_.min.resize(kdl_tree_.getNrOfJoints());
joint_limits_.max.resize(kdl_tree_.getNrOfJoints());
joint_limits_.center.resize(kdl_tree_.getNrOfJoints());
int index;
for (int i = 0; i < kdl_tree_.getNrOfJoints() && link_; i++)
{
joint_ = model.getJoint(link_->parent_joint->name);
index = kdl_tree_.getNrOfJoints() - i - 1;
joint_limits_.min(index) = joint_->limits->lower;
joint_limits_.max(index) = joint_->limits->upper;
joint_limits_.center(index) = (joint_limits_.min(index) + joint_limits_.max(index))/2;
link_ = model.getLink(link_->getParent()->name);
}
// Populate the KDL chain
if(!kdl_tree_.getChain(root_name, tip_name, kdl_chain_))
{
ROS_ERROR_STREAM("Failed to get KDL chain from tree: ");
ROS_ERROR_STREAM(" "<<root_name<<" --> "<<tip_name);
ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfJoints()<<" joints");
ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfSegments()<<" segments");
ROS_ERROR_STREAM(" The segments are:");
KDL::SegmentMap segment_map = kdl_tree_.getSegments();
KDL::SegmentMap::iterator it;
for( it=segment_map.begin(); it != segment_map.end(); it++ )
ROS_ERROR_STREAM( " "<<(*it).first);
return false;
}
ROS_DEBUG("Number of segments: %d", kdl_chain_.getNrOfSegments());
ROS_DEBUG("Number of joints in chain: %d", kdl_chain_.getNrOfJoints());
// Get joint handles for all of the joints in the chain
for(std::vector<KDL::Segment>::const_iterator it = kdl_chain_.segments.begin()+1; it != kdl_chain_.segments.end(); ++it)
{
joint_handles_.push_back(robot->getHandle(it->getJoint().getName()));
ROS_DEBUG("%s", it->getJoint().getName().c_str() );
}
ROS_DEBUG(" Number of joints in handle = %lu", joint_handles_.size() );
jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_));
id_solver_.reset(new KDL::ChainDynParam(kdl_chain_,gravity_));
fk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));
ik_vel_solver_.reset(new KDL::ChainIkSolverVel_pinv(kdl_chain_));
ik_pos_solver_.reset(new KDL::ChainIkSolverPos_NR_JL(kdl_chain_,joint_limits_.min,joint_limits_.max,*fk_pos_solver_,*ik_vel_solver_));
joint_msr_states_.resize(kdl_chain_.getNrOfJoints());
joint_des_states_.resize(kdl_chain_.getNrOfJoints());
tau_cmd_.resize(kdl_chain_.getNrOfJoints());
J_.resize(kdl_chain_.getNrOfJoints());
PIDs_.resize(kdl_chain_.getNrOfJoints());
sub_command_ = nh_.subscribe("command_configuration", 1, &OneTaskInverseKinematics::command_configuration, this);
sub_gains_ = nh_.subscribe("set_gains", 1, &OneTaskInverseKinematics::set_gains, this);
return true;
}
void OneTaskInverseKinematics::starting(const ros::Time& time)
{
// get joint positions
for(int i=0; i < joint_handles_.size(); i++)
{
joint_msr_states_.q(i) = joint_handles_[i].getPosition();
joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();
joint_des_states_.q(i) = joint_msr_states_.q(i);
}
Kp = 60;
Ki = 1.2;
Kd = 10;
for (int i = 0; i < PIDs_.size(); i++)
PIDs_[i].initPid(Kp,Ki,Kd,0.3,-0.3);
ROS_INFO("PIDs gains are: Kp = %f, Ki = %f, Kd = %f",Kp,Ki,Kd);
// computing forward kinematics
fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
//Desired posture
x_des_ = x_;
cmd_flag_ = 0;
}
void OneTaskInverseKinematics::update(const ros::Time& time, const ros::Duration& period)
{
// get joint positions
for(int i=0; i < joint_handles_.size(); i++)
{
joint_msr_states_.q(i) = joint_handles_[i].getPosition();
joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();
}
if (cmd_flag_)
{
// ANALYTIC METHOD FOR INVERSE KINEMATICS
// computing Jacobian
jnt_to_jac_solver_->JntToJac(joint_msr_states_.q,J_);
// computing J_pinv_
pseudo_inverse(J_.data,J_pinv_);
// computing forward kinematics
fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
// end-effector position/orientation error
x_err_.vel = x_des_.p - x_.p;
// getting quaternion from rotation matrix
x_.M.GetQuaternion(quat_curr_.v(0),quat_curr_.v(1),quat_curr_.v(2),quat_curr_.a);
x_des_.M.GetQuaternion(quat_des_.v(0),quat_des_.v(1),quat_des_.v(2),quat_des_.a);
skew_symmetric(quat_des_.v,skew_);
for (int i = 0; i < skew_.rows(); i++)
{
v_temp_(i) = 0.0;
for (int k = 0; k < skew_.cols(); k++)
v_temp_(i) += skew_(i,k)*(quat_curr_.v(k));
}
x_err_.rot = quat_curr_.a*quat_des_.v - quat_des_.a*quat_curr_.v - v_temp_;
// computing q_dot
for (int i = 0; i < J_pinv_.rows(); i++)
{
joint_des_states_.qdot(i) = 0.0;
for (int k = 0; k < J_pinv_.cols(); k++)
joint_des_states_.qdot(i) += .3*J_pinv_(i,k)*x_err_(k);
}
// integrating q_dot -> getting q (Euler method)
for (int i = 0; i < joint_handles_.size(); i++)
joint_des_states_.q(i) += period.toSec()*joint_des_states_.qdot(i);
for (int i =0; i < joint_handles_.size(); i++)
{
if (joint_des_states_.q(i) < joint_limits_.min(i) )
joint_des_states_.q(i) = joint_limits_.min(i);
if (joint_des_states_.q(i) > joint_limits_.max(i) )
joint_des_states_.q(i) = joint_limits_.max(i);
}
// computing differential inverse kinematics
// ik_pos_solver_->CartToJnt(joint_msr_states_.q,x_des_,joint_des_states_.q);
// computing forward kinematics
// fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
if (Equal(x_,x_des_,0.025))
{
ROS_INFO("On target");
cmd_flag_ = 0;
}
}
// set controls for joints
for (int i = 0; i < joint_handles_.size(); i++)
{
tau_cmd_(i) = PIDs_[i].computeCommand(joint_des_states_.q(i) - joint_msr_states_.q(i),period);
joint_handles_[i].setCommand(tau_cmd_(i));
}
}
void OneTaskInverseKinematics::command_configuration(const lwr_controllers::PoseRPY::ConstPtr &msg)
{
KDL::Frame frame_des_;
switch(msg->id)
{
case 0:
frame_des_ = KDL::Frame(
KDL::Rotation::RPY(msg->orientation.roll,
msg->orientation.pitch,
msg->orientation.yaw),
KDL::Vector(msg->position.x,
msg->position.y,
msg->position.z));
break;
case 1: // position only
frame_des_ = KDL::Frame(
KDL::Vector(msg->position.x,
msg->position.y,
msg->position.z));
break;
case 2: // orientation only
frame_des_ = KDL::Frame(
KDL::Rotation::RPY(msg->orientation.roll,
msg->orientation.pitch,
msg->orientation.yaw));
break;
default:
ROS_INFO("Wrong message ID");
return;
}
x_des_ = frame_des_;
cmd_flag_ = 1;
}
void OneTaskInverseKinematics::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg)
{
if(msg->data.size() == 3)
{
for(int i = 0; i < PIDs_.size(); i++)
PIDs_[i].setGains(msg->data[0],msg->data[1],msg->data[2],0.3,-0.3);
ROS_INFO("New gains set: Kp = %f, Ki = %f, Kd = %f",msg->data[0],msg->data[1],msg->data[2]);
}
else
ROS_INFO("PIDs gains needed are 3 (Kp, Ki and Kd)");
}
}
PLUGINLIB_EXPORT_CLASS(lwr_controllers::OneTaskInverseKinematics, controller_interface::ControllerBase)
<commit_msg>small tweaks to tau and gains<commit_after>#include <pluginlib/class_list_macros.h>
#include <kdl_parser/kdl_parser.hpp>
#include <math.h>
#include <Eigen/LU>
#include <utils/pseudo_inversion.h>
#include <utils/skew_symmetric.h>
#include <lwr_controllers/one_task_inverse_kinematics.h>
namespace lwr_controllers
{
OneTaskInverseKinematics::OneTaskInverseKinematics() {}
OneTaskInverseKinematics::~OneTaskInverseKinematics() {}
bool OneTaskInverseKinematics::init(hardware_interface::EffortJointInterface *robot, ros::NodeHandle &n)
{
nh_ = n;
// get URDF and name of root and tip from the parameter server
std::string robot_description, root_name, tip_name;
if (!ros::param::search(n.getNamespace(),"robot_description", robot_description))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No robot description (URDF) found on parameter server ("<<n.getNamespace()<<"/robot_description)");
return false;
}
if (!nh_.getParam("root_name", root_name))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No root name found on parameter server ("<<n.getNamespace()<<"/root_name)");
return false;
}
if (!nh_.getParam("tip_name", tip_name))
{
ROS_ERROR_STREAM("OneTaskInverseKinematics: No tip name found on parameter server ("<<n.getNamespace()<<"/tip_name)");
return false;
}
// Get the gravity vector (direction and magnitude)
KDL::Vector gravity_ = KDL::Vector::Zero();
gravity_(2) = -9.81;
// Construct an URDF model from the xml string
std::string xml_string;
if (n.hasParam(robot_description))
n.getParam(robot_description.c_str(), xml_string);
else
{
ROS_ERROR("Parameter %s not set, shutting down node...", robot_description.c_str());
n.shutdown();
return false;
}
if (xml_string.size() == 0)
{
ROS_ERROR("Unable to load robot model from parameter %s",robot_description.c_str());
n.shutdown();
return false;
}
ROS_DEBUG("%s content\n%s", robot_description.c_str(), xml_string.c_str());
// Get urdf model out of robot_description
urdf::Model model;
if (!model.initString(xml_string))
{
ROS_ERROR("Failed to parse urdf file");
n.shutdown();
return false;
}
ROS_INFO("Successfully parsed urdf file");
KDL::Tree kdl_tree_;
if (!kdl_parser::treeFromUrdfModel(model, kdl_tree_))
{
ROS_ERROR("Failed to construct kdl tree");
n.shutdown();
return false;
}
// Parsing joint limits from urdf model
boost::shared_ptr<const urdf::Link> link_ = model.getLink(tip_name);
boost::shared_ptr<const urdf::Joint> joint_;
joint_limits_.min.resize(kdl_tree_.getNrOfJoints());
joint_limits_.max.resize(kdl_tree_.getNrOfJoints());
joint_limits_.center.resize(kdl_tree_.getNrOfJoints());
int index;
for (int i = 0; i < kdl_tree_.getNrOfJoints() && link_; i++)
{
joint_ = model.getJoint(link_->parent_joint->name);
index = kdl_tree_.getNrOfJoints() - i - 1;
joint_limits_.min(index) = joint_->limits->lower;
joint_limits_.max(index) = joint_->limits->upper;
joint_limits_.center(index) = (joint_limits_.min(index) + joint_limits_.max(index))/2;
link_ = model.getLink(link_->getParent()->name);
}
// Populate the KDL chain
if(!kdl_tree_.getChain(root_name, tip_name, kdl_chain_))
{
ROS_ERROR_STREAM("Failed to get KDL chain from tree: ");
ROS_ERROR_STREAM(" "<<root_name<<" --> "<<tip_name);
ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfJoints()<<" joints");
ROS_ERROR_STREAM(" Tree has "<<kdl_tree_.getNrOfSegments()<<" segments");
ROS_ERROR_STREAM(" The segments are:");
KDL::SegmentMap segment_map = kdl_tree_.getSegments();
KDL::SegmentMap::iterator it;
for( it=segment_map.begin(); it != segment_map.end(); it++ )
ROS_ERROR_STREAM( " "<<(*it).first);
return false;
}
ROS_DEBUG("Number of segments: %d", kdl_chain_.getNrOfSegments());
ROS_DEBUG("Number of joints in chain: %d", kdl_chain_.getNrOfJoints());
// Get joint handles for all of the joints in the chain
for(std::vector<KDL::Segment>::const_iterator it = kdl_chain_.segments.begin()+1; it != kdl_chain_.segments.end(); ++it)
{
joint_handles_.push_back(robot->getHandle(it->getJoint().getName()));
ROS_DEBUG("%s", it->getJoint().getName().c_str() );
}
ROS_DEBUG(" Number of joints in handle = %lu", joint_handles_.size() );
jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_));
id_solver_.reset(new KDL::ChainDynParam(kdl_chain_,gravity_));
fk_pos_solver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));
ik_vel_solver_.reset(new KDL::ChainIkSolverVel_pinv(kdl_chain_));
ik_pos_solver_.reset(new KDL::ChainIkSolverPos_NR_JL(kdl_chain_,joint_limits_.min,joint_limits_.max,*fk_pos_solver_,*ik_vel_solver_));
joint_msr_states_.resize(kdl_chain_.getNrOfJoints());
joint_des_states_.resize(kdl_chain_.getNrOfJoints());
tau_cmd_.resize(kdl_chain_.getNrOfJoints());
J_.resize(kdl_chain_.getNrOfJoints());
PIDs_.resize(kdl_chain_.getNrOfJoints());
sub_command_ = nh_.subscribe("command_configuration", 1, &OneTaskInverseKinematics::command_configuration, this);
sub_gains_ = nh_.subscribe("set_gains", 1, &OneTaskInverseKinematics::set_gains, this);
return true;
}
void OneTaskInverseKinematics::starting(const ros::Time& time)
{
// get joint positions
for(int i=0; i < joint_handles_.size(); i++)
{
joint_msr_states_.q(i) = joint_handles_[i].getPosition();
joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();
joint_des_states_.q(i) = joint_msr_states_.q(i);
}
Kp = 60;
Ki = 1.2;
Kd = 10;
for (int i = 0; i < PIDs_.size(); i++)
{
PIDs_[i].initPid(Kp,Ki,Kd,0.3,-0.3);
}
ROS_INFO("PIDs gains are: Kp = %f, Ki = %f, Kd = %f",Kp,Ki,Kd);
// computing forward kinematics
fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
//Desired posture
x_des_ = x_;
cmd_flag_ = 0;
}
void OneTaskInverseKinematics::update(const ros::Time& time, const ros::Duration& period)
{
// get joint positions
for(int i=0; i < joint_handles_.size(); i++)
{
joint_msr_states_.q(i) = joint_handles_[i].getPosition();
joint_msr_states_.qdot(i) = joint_handles_[i].getVelocity();
}
if (cmd_flag_)
{
// ANALYTIC METHOD FOR INVERSE KINEMATICS
// computing Jacobian
jnt_to_jac_solver_->JntToJac(joint_msr_states_.q,J_);
// computing J_pinv_
pseudo_inverse(J_.data,J_pinv_);
// computing forward kinematics
fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
// end-effector position/orientation error
x_err_.vel = x_des_.p - x_.p;
// getting quaternion from rotation matrix
x_.M.GetQuaternion(quat_curr_.v(0),quat_curr_.v(1),quat_curr_.v(2),quat_curr_.a);
x_des_.M.GetQuaternion(quat_des_.v(0),quat_des_.v(1),quat_des_.v(2),quat_des_.a);
skew_symmetric(quat_des_.v,skew_);
for (int i = 0; i < skew_.rows(); i++)
{
v_temp_(i) = 0.0;
for (int k = 0; k < skew_.cols(); k++)
v_temp_(i) += skew_(i,k)*(quat_curr_.v(k));
}
x_err_.rot = quat_curr_.a*quat_des_.v - quat_des_.a*quat_curr_.v - v_temp_;
// computing q_dot
for (int i = 0; i < J_pinv_.rows(); i++)
{
joint_des_states_.qdot(i) = 0.0;
for (int k = 0; k < J_pinv_.cols(); k++)
joint_des_states_.qdot(i) += .7*J_pinv_(i,k)*x_err_(k);
}
// integrating q_dot -> getting q (Euler method)
for (int i = 0; i < joint_handles_.size(); i++)
joint_des_states_.q(i) += period.toSec()*joint_des_states_.qdot(i);
for (int i =0; i < joint_handles_.size(); i++)
{
if (joint_des_states_.q(i) < joint_limits_.min(i) )
joint_des_states_.q(i) = joint_limits_.min(i);
if (joint_des_states_.q(i) > joint_limits_.max(i) )
joint_des_states_.q(i) = joint_limits_.max(i);
}
// computing differential inverse kinematics
// ik_pos_solver_->CartToJnt(joint_msr_states_.q,x_des_,joint_des_states_.q);
// computing forward kinematics
// fk_pos_solver_->JntToCart(joint_msr_states_.q,x_);
if (Equal(x_,x_des_,0.005))
{
ROS_INFO("On target");
cmd_flag_ = 0;
}
}
// set controls for joints
for (int i = 0; i < joint_handles_.size(); i++)
{
tau_cmd_(i) = PIDs_[i].computeCommand(joint_des_states_.q(i) - joint_msr_states_.q(i),period);
joint_handles_[i].setCommand(tau_cmd_(i));
}
}
void OneTaskInverseKinematics::command_configuration(const lwr_controllers::PoseRPY::ConstPtr &msg)
{
KDL::Frame frame_des_;
switch(msg->id)
{
case 0:
frame_des_ = KDL::Frame(
KDL::Rotation::RPY(msg->orientation.roll,
msg->orientation.pitch,
msg->orientation.yaw),
KDL::Vector(msg->position.x,
msg->position.y,
msg->position.z));
break;
case 1: // position only
frame_des_ = KDL::Frame(
KDL::Vector(msg->position.x,
msg->position.y,
msg->position.z));
break;
case 2: // orientation only
frame_des_ = KDL::Frame(
KDL::Rotation::RPY(msg->orientation.roll,
msg->orientation.pitch,
msg->orientation.yaw));
break;
default:
ROS_INFO("Wrong message ID");
return;
}
x_des_ = frame_des_;
cmd_flag_ = 1;
}
void OneTaskInverseKinematics::set_gains(const std_msgs::Float64MultiArray::ConstPtr &msg)
{
if(msg->data.size() == 3)
{
for(int i = 0; i < PIDs_.size(); i++)
PIDs_[i].setGains(msg->data[0],msg->data[1],msg->data[2],0.3,-0.3);
ROS_INFO("New gains set: Kp = %f, Ki = %f, Kd = %f",msg->data[0],msg->data[1],msg->data[2]);
}
else
ROS_INFO("PIDs gains needed are 3 (Kp, Ki and Kd)");
}
}
PLUGINLIB_EXPORT_CLASS(lwr_controllers::OneTaskInverseKinematics, controller_interface::ControllerBase)
<|endoftext|>
|
<commit_before>#include "resizer.h"
Resizer::Resizer(QObject *parent) : QObject(parent)
{
}
int Resizer::width() const
{
return m_width;
}
int Resizer::height() const
{
return m_height;
}
void Resizer::process()
{
m_outputImage = QImage(m_path).
scaled(width(), height(), Qt::KeepAspectRatio).
convertToFormat(QImage::Format_ARGB32_Premultiplied);
emit finished();
emit finished(m_outputImage);
}
void Resizer::setInputImagePath(QString path)
{
m_path = path;
}
void Resizer::setWidth(int width)
{
if(m_width != width)
{
m_width = width;
}
}
void Resizer::setHeight(int height)
{
if(m_height != height)
{
m_height = height;
}
}
<commit_msg>Changed resizing algorithm<commit_after>#include "resizer.h"
#include <QImageReader>
#include <QDebug>
Resizer::Resizer(QObject *parent) : QObject(parent)
{
}
int Resizer::width() const
{
return m_width;
}
int Resizer::height() const
{
return m_height;
}
void Resizer::process()
{
QImageReader imageReader(m_path);
QSize originalSize(imageReader.size());
QSize scaledSize = originalSize;
if((originalSize.width() || originalSize.height()) == 0)
{
return;
}
// qDebug() << "!!!!!!!!!" << originalSize.width() / width() <<
// originalSize.height() / height();
// Source form coefficient
double kfs = static_cast<double>(originalSize.width()) /
static_cast<double>(originalSize.height());
// Destination form coefficient
double kfd = static_cast<double>(width()) /
static_cast<double>(height());
double scaleFactor = 1.0;
if(kfs > kfd)
{
scaleFactor = static_cast<double>(width()) /
static_cast<double>(originalSize.width());
scaledSize.setWidth(width());
scaledSize.setHeight(originalSize.height() * scaleFactor);
//qDebug() << "kfs > kfd";
}
else
{
scaleFactor = static_cast<double>(height()) /
static_cast<double>(originalSize.height());
scaledSize.setWidth(originalSize.width() * scaleFactor);
scaledSize.setHeight(height());
//qDebug() << "kfs < kfd";
}
// qDebug() << "Original size: " << originalSize;
// qDebug() << "Scaled size: " << scaledSize;
// qDebug() << "kfs =" << kfs;
// qDebug() << "kfd =" << kfd;
imageReader.setScaledSize(scaledSize);
imageReader.read(&m_outputImage);
m_outputImage = m_outputImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
emit finished();
emit finished(m_outputImage);
}
void Resizer::setInputImagePath(QString path)
{
m_path = path;
}
void Resizer::setWidth(int width)
{
if(m_width != width)
{
m_width = width;
}
}
void Resizer::setHeight(int height)
{
if(m_height != height)
{
m_height = height;
}
}
<|endoftext|>
|
<commit_before>#include "chrono_parallel/physics/ChSystemParallel.h"
#include <omp.h>
using namespace chrono;
using namespace chrono::collision;
ChSystemParallelDEM::ChSystemParallelDEM(unsigned int max_objects,
ChContactDEM::NormalForceModel normal_model,
ChContactDEM::TangentialForceModel tangential_model)
: ChSystemParallel(max_objects),
normal_force_model(normal_model),
tangential_force_model(tangential_model)
{
LCP_descriptor = new ChLcpSystemDescriptorParallelDEM();
LCP_solver_speed = new ChLcpSolverParallelDEM();
((ChLcpSystemDescriptorParallelDEM*) LCP_descriptor)->data_container = data_manager;
((ChLcpSolverParallel*) LCP_solver_speed)->data_container = data_manager;
((ChCollisionSystemParallel *) collision_system)->SetCollisionEnvelope(0);
//Set this so that the CD can check what type of system it is (needed for narrowphase)
data_manager->settings.system_type = SYSTEM_DEM;
data_manager->system_timer.AddTimer("ChLcpSolverParallelDEM_ProcessContact");
}
void ChSystemParallelDEM::LoadMaterialSurfaceData(ChSharedPtr<ChBody> newbody)
{
assert(typeid(*newbody.get_ptr()) == typeid(ChBodyDEM));
ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*) newbody.get_ptr())->GetMaterialSurfaceDEM();
data_manager->host_data.elastic_moduli.push_back(R2(mat->GetYoungModulus(), mat->GetPoissonRatio()));
data_manager->host_data.mu.push_back(mat->GetSfriction());
data_manager->host_data.cohesion_data.push_back(mat->GetCohesion());
switch (normal_force_model) {
case ChContactDEM::HuntCrossley:
data_manager->host_data.alpha.push_back(mat->GetDissipationFactor());
break;
}
//gpu_data_manager->host_data.cr.push_back(mat->GetRestitution());
}
void ChSystemParallelDEM::UpdateBodies()
{
real3 *vel_pointer = data_manager->host_data.vel_data.data();
real3 *omg_pointer = data_manager->host_data.omg_data.data();
real3 *pos_pointer = data_manager->host_data.pos_data.data();
real4 *rot_pointer = data_manager->host_data.rot_data.data();
real3 *inr_pointer = data_manager->host_data.inr_data.data();
real3 *frc_pointer = data_manager->host_data.frc_data.data();
real3 *trq_pointer = data_manager->host_data.trq_data.data();
bool *active_pointer = data_manager->host_data.active_data.data();
real *mass_pointer = data_manager->host_data.mass_data.data();
real3 *lim_pointer = data_manager->host_data.lim_data.data();
real2* elastic_moduli = data_manager->host_data.elastic_moduli.data();
real* mu = data_manager->host_data.mu.data();
real* alpha = data_manager->host_data.alpha.data();
real* cr = data_manager->host_data.cr.data();
real* cohesion = data_manager->host_data.cohesion_data.data();
#pragma omp parallel for
for (int i = 0; i < bodylist.size(); i++) {
bodylist[i]->UpdateTime(ChTime);
//bodylist[i]->TrySleeping(); // See if the body can fall asleep; if so, put it to sleeping
//bodylist[i]->ClampSpeed(); // Apply limits (if in speed clamping mode) to speeds.
bodylist[i]->ComputeGyro(); // Set the gyroscopic momentum.
bodylist[i]->UpdateForces(ChTime);
bodylist[i]->VariablesFbReset();
bodylist[i]->VariablesFbLoadForces(GetStep());
bodylist[i]->VariablesQbLoadSpeed();
}
for (int i = 0; i < bodylist.size(); i++) {
bodylist[i]->UpdateMarkers(ChTime);
//bodylist[i]->InjectVariables(*this->LCP_descriptor);
}
#pragma omp parallel for
for (int i = 0; i < bodylist.size(); i++) {
ChMatrix<>& qb = bodylist[i]->Variables().Get_qb();
ChMatrix<>& fb = bodylist[i]->Variables().Get_fb();
ChVector<>& pos = bodylist[i]->GetPos();
ChQuaternion<>& rot = bodylist[i]->GetRot();
ChMatrix33<>& inertia = bodylist[i]->VariablesBody().GetBodyInvInertia();
vel_pointer[i] = (R3(qb.ElementN(0), qb.ElementN(1), qb.ElementN(2)));
omg_pointer[i] = (R3(qb.ElementN(3), qb.ElementN(4), qb.ElementN(5)));
pos_pointer[i] = (R3(pos.x, pos.y, pos.z));
rot_pointer[i] = (R4(rot.e0, rot.e1, rot.e2, rot.e3));
inr_pointer[i] = (R3(inertia.GetElement(0, 0), inertia.GetElement(1, 1), inertia.GetElement(2, 2)));
frc_pointer[i] = (R3(fb.ElementN(0), fb.ElementN(1), fb.ElementN(2))); //forces
trq_pointer[i] = (R3(fb.ElementN(3), fb.ElementN(4), fb.ElementN(5))); //torques
active_pointer[i] = bodylist[i]->IsActive();
mass_pointer[i] = 1.0f / bodylist[i]->VariablesBody().GetBodyMass();
lim_pointer[i] = (R3(bodylist[i]->GetLimitSpeed(), .05 / GetStep(), .05 / GetStep()));
ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*) bodylist[i])->GetMaterialSurfaceDEM();
elastic_moduli[i] = R2(mat->GetYoungModulus(), mat->GetPoissonRatio());
mu[i] = mat->GetSfriction();
cohesion[i] = mat->GetCohesion();
//cr[i] = mat->GetRestitution();
switch (normal_force_model) {
case ChContactDEM::HuntCrossley:
alpha[i] = mat->GetDissipationFactor();
break;
}
bodylist[i]->GetCollisionModel()->SyncPosition();
}
}
void ChSystemParallelDEM::ChangeCollisionSystem(ChCollisionSystem* newcollsystem)
{
ChSystemParallel::ChangeCollisionSystem(newcollsystem);
if (ChCollisionSystemParallel* coll_sys = dynamic_cast<ChCollisionSystemParallel*>(collision_system))
coll_sys->SetCollisionEnvelope(0);
}
void ChSystemParallelDEM::PrintStepStats()
{
double timer_solver_setup = data_manager->system_timer.GetTime("ChLcpSolverParallel_Setup");
double timer_solver_rhs = data_manager->system_timer.GetTime("ChLcpSolverParallel_RHS");
double timer_solver_stab = data_manager->system_timer.GetTime("ChLcpSolverParallel_Stab");
std::cout << std::endl;
std::cout << "System Information" << std::endl;
std::cout << "------------------" << std::endl;
std::cout << " Number of bodies " << GetNumBodies() << std::endl;
std::cout << " Number of contacts " << GetNcontacts() << std::endl;
std::cout << " Number of bilaterals " << GetNumBilaterals() << std::endl;
std::cout << std::endl;
std::cout << "Timing Information" << std::endl;
std::cout << "------------------" << std::endl;
std::cout << "Simulation time " << GetTimerStep() << std::endl;
std::cout << " Collision detection " << GetTimerCollision() << std::endl;
std::cout << " broad phase " << GetTimerCollisionBroad() << std::endl;
std::cout << " narrow phase " << GetTimerCollisionNarrow() << std::endl;
std::cout << " Update " << GetTimerUpdate() << std::endl;
std::cout << " Solver " << GetTimerLcp() << std::endl;
std::cout << " contact force calc " << GetTimerProcessContact() << std::endl;
std::cout << " setup " << timer_solver_setup << std::endl;
std::cout << " RHS " << timer_solver_rhs << std::endl;
std::cout << " stabilization " << timer_solver_stab << std::endl;
std::cout << std::endl;
}
<commit_msg>Use a single parallel for loop for body updates in a ChsystemParallelDEM.<commit_after>#include "chrono_parallel/physics/ChSystemParallel.h"
#include <omp.h>
using namespace chrono;
using namespace chrono::collision;
ChSystemParallelDEM::ChSystemParallelDEM(unsigned int max_objects,
ChContactDEM::NormalForceModel normal_model,
ChContactDEM::TangentialForceModel tangential_model)
: ChSystemParallel(max_objects),
normal_force_model(normal_model),
tangential_force_model(tangential_model)
{
LCP_descriptor = new ChLcpSystemDescriptorParallelDEM();
LCP_solver_speed = new ChLcpSolverParallelDEM();
((ChLcpSystemDescriptorParallelDEM*) LCP_descriptor)->data_container = data_manager;
((ChLcpSolverParallel*) LCP_solver_speed)->data_container = data_manager;
((ChCollisionSystemParallel *) collision_system)->SetCollisionEnvelope(0);
//Set this so that the CD can check what type of system it is (needed for narrowphase)
data_manager->settings.system_type = SYSTEM_DEM;
data_manager->system_timer.AddTimer("ChLcpSolverParallelDEM_ProcessContact");
}
void ChSystemParallelDEM::LoadMaterialSurfaceData(ChSharedPtr<ChBody> newbody)
{
assert(typeid(*newbody.get_ptr()) == typeid(ChBodyDEM));
ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*) newbody.get_ptr())->GetMaterialSurfaceDEM();
data_manager->host_data.elastic_moduli.push_back(R2(mat->GetYoungModulus(), mat->GetPoissonRatio()));
data_manager->host_data.mu.push_back(mat->GetSfriction());
data_manager->host_data.cohesion_data.push_back(mat->GetCohesion());
switch (normal_force_model) {
case ChContactDEM::HuntCrossley:
data_manager->host_data.alpha.push_back(mat->GetDissipationFactor());
break;
}
//gpu_data_manager->host_data.cr.push_back(mat->GetRestitution());
}
void ChSystemParallelDEM::UpdateBodies()
{
real3 *vel_pointer = data_manager->host_data.vel_data.data();
real3 *omg_pointer = data_manager->host_data.omg_data.data();
real3 *pos_pointer = data_manager->host_data.pos_data.data();
real4 *rot_pointer = data_manager->host_data.rot_data.data();
real3 *inr_pointer = data_manager->host_data.inr_data.data();
real3 *frc_pointer = data_manager->host_data.frc_data.data();
real3 *trq_pointer = data_manager->host_data.trq_data.data();
bool *active_pointer = data_manager->host_data.active_data.data();
real *mass_pointer = data_manager->host_data.mass_data.data();
real3 *lim_pointer = data_manager->host_data.lim_data.data();
real2* elastic_moduli = data_manager->host_data.elastic_moduli.data();
real* mu = data_manager->host_data.mu.data();
real* alpha = data_manager->host_data.alpha.data();
real* cr = data_manager->host_data.cr.data();
real* cohesion = data_manager->host_data.cohesion_data.data();
#pragma omp parallel for
for (int i = 0; i < bodylist.size(); i++) {
bodylist[i]->Update(ChTime);
bodylist[i]->VariablesFbLoadForces(GetStep());
bodylist[i]->VariablesQbLoadSpeed();
ChMatrix<>& qb = bodylist[i]->Variables().Get_qb();
ChMatrix<>& fb = bodylist[i]->Variables().Get_fb();
ChVector<>& pos = bodylist[i]->GetPos();
ChQuaternion<>& rot = bodylist[i]->GetRot();
ChMatrix33<>& inertia = bodylist[i]->VariablesBody().GetBodyInvInertia();
vel_pointer[i] = (R3(qb.ElementN(0), qb.ElementN(1), qb.ElementN(2)));
omg_pointer[i] = (R3(qb.ElementN(3), qb.ElementN(4), qb.ElementN(5)));
pos_pointer[i] = (R3(pos.x, pos.y, pos.z));
rot_pointer[i] = (R4(rot.e0, rot.e1, rot.e2, rot.e3));
inr_pointer[i] = (R3(inertia.GetElement(0, 0), inertia.GetElement(1, 1), inertia.GetElement(2, 2)));
frc_pointer[i] = (R3(fb.ElementN(0), fb.ElementN(1), fb.ElementN(2))); //forces
trq_pointer[i] = (R3(fb.ElementN(3), fb.ElementN(4), fb.ElementN(5))); //torques
active_pointer[i] = bodylist[i]->IsActive();
mass_pointer[i] = 1.0f / bodylist[i]->VariablesBody().GetBodyMass();
lim_pointer[i] = (R3(bodylist[i]->GetLimitSpeed(), .05 / GetStep(), .05 / GetStep()));
ChSharedPtr<ChMaterialSurfaceDEM>& mat = ((ChBodyDEM*) bodylist[i])->GetMaterialSurfaceDEM();
elastic_moduli[i] = R2(mat->GetYoungModulus(), mat->GetPoissonRatio());
mu[i] = mat->GetSfriction();
cohesion[i] = mat->GetCohesion();
//cr[i] = mat->GetRestitution();
switch (normal_force_model) {
case ChContactDEM::HuntCrossley:
alpha[i] = mat->GetDissipationFactor();
break;
}
bodylist[i]->GetCollisionModel()->SyncPosition();
}
}
void ChSystemParallelDEM::ChangeCollisionSystem(ChCollisionSystem* newcollsystem)
{
ChSystemParallel::ChangeCollisionSystem(newcollsystem);
if (ChCollisionSystemParallel* coll_sys = dynamic_cast<ChCollisionSystemParallel*>(collision_system))
coll_sys->SetCollisionEnvelope(0);
}
void ChSystemParallelDEM::PrintStepStats()
{
double timer_solver_setup = data_manager->system_timer.GetTime("ChLcpSolverParallel_Setup");
double timer_solver_rhs = data_manager->system_timer.GetTime("ChLcpSolverParallel_RHS");
double timer_solver_stab = data_manager->system_timer.GetTime("ChLcpSolverParallel_Stab");
std::cout << std::endl;
std::cout << "System Information" << std::endl;
std::cout << "------------------" << std::endl;
std::cout << " Number of bodies " << GetNumBodies() << std::endl;
std::cout << " Number of contacts " << GetNcontacts() << std::endl;
std::cout << " Number of bilaterals " << GetNumBilaterals() << std::endl;
std::cout << std::endl;
std::cout << "Timing Information" << std::endl;
std::cout << "------------------" << std::endl;
std::cout << "Simulation time " << GetTimerStep() << std::endl;
std::cout << " Collision detection " << GetTimerCollision() << std::endl;
std::cout << " broad phase " << GetTimerCollisionBroad() << std::endl;
std::cout << " narrow phase " << GetTimerCollisionNarrow() << std::endl;
std::cout << " Update " << GetTimerUpdate() << std::endl;
std::cout << " Solver " << GetTimerLcp() << std::endl;
std::cout << " contact force calc " << GetTimerProcessContact() << std::endl;
std::cout << " setup " << timer_solver_setup << std::endl;
std::cout << " RHS " << timer_solver_rhs << std::endl;
std::cout << " stabilization " << timer_solver_stab << std::endl;
std::cout << std::endl;
}
<|endoftext|>
|
<commit_before>#include "UltrasonicObstacleDetector2020.h"
UltrasonicDetector2020::UltrasonicDetector2020()
{
DEBUG_REQUEST_REGISTER("UltrasonicDetector2020:draw3D:measurements", "", false);
rightReceiverInTorso.translation = {47.7, -41.6, 50.9};
leftReceiverInTorso.translation = {47.7, 41.6, 50.9};
rightReceiverInTorso.rotation = RotationMatrix::getRotationZ(-0.4363)
* RotationMatrix::getRotationY(0.2618);
leftReceiverInTorso.rotation = RotationMatrix::getRotationZ(0.4363)
* RotationMatrix::getRotationY(0.2618);
rightInWorld.reserve(UltraSoundReceiveData::numOfUSEcho);
leftInWorld.reserve(UltraSoundReceiveData::numOfUSEcho);
getDebugParameterList().add(¶meter);
}
void UltrasonicDetector2020::execute()
{
// reset percept representation and measuremnt vectors
getUltrasonicObstaclePercept().location_on_ground.clear();
leftInWorld.clear();
rightInWorld.clear();
// transform measurements into world coordinates if not too far away
Pose3D torso = getKinematicChain().theLinks[KinematicChain::Torso].M;
for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) {
if(getUltraSoundReceiveData().dataLeft[i] < 5.0) { // == 5.0 means no echo
leftInWorld.push_back(torso * leftReceiverInTorso * Vector3d(getUltraSoundReceiveData().dataLeft[i] * 1000,0,0));
}
if(getUltraSoundReceiveData().dataRight[i] < 5.0) { // == 5.0 means no echo
rightInWorld.push_back(torso * rightReceiverInTorso * Vector3d(getUltraSoundReceiveData().dataRight[i] * 1000,0,0));
}
}
// filter out ground (-> later assume reflection?)
for(auto& point : leftInWorld){
if(point.z > parameter.ground_threshold){
getUltrasonicObstaclePercept().location_on_ground.push_back({point.x, point.y});
}
}
for(auto& point : rightInWorld){
if(point.z > parameter.ground_threshold){
getUltrasonicObstaclePercept().location_on_ground.push_back({point.x, point.y});
}
}
// 3. provide obstacle model measurements
draw();
}
//bool UltrasonicObstacleLocator2020::is_new_data_avaliable() const
//{
// for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) {
// if(getUltraSoundReceiveData().dataLeft[i] != lastValidUltraSoundReceiveData.dataLeft[i] ||
// getUltraSoundReceiveData().dataRight[i] != lastValidUltraSoundReceiveData.dataRight[i])
// {
// return true;
// }
// }
// return false;
//}
void UltrasonicDetector2020::draw() const
{
DEBUG_REQUEST("UltrasonicObstacleLocation2020:draw3D:measurements",
for(auto& point : leftInWorld){
SPHERE("0000FF", 10, point);
}
for(auto& point : rightInWorld){
SPHERE("FF0000", 10, point);
}
);
}
<commit_msg>fix debug request<commit_after>#include "UltrasonicObstacleDetector2020.h"
UltrasonicDetector2020::UltrasonicDetector2020()
{
DEBUG_REQUEST_REGISTER("UltrasonicDetector2020:draw3D:measurements", "", false);
rightReceiverInTorso.translation = {47.7, -41.6, 50.9};
leftReceiverInTorso.translation = {47.7, 41.6, 50.9};
rightReceiverInTorso.rotation = RotationMatrix::getRotationZ(-0.4363)
* RotationMatrix::getRotationY(0.2618);
leftReceiverInTorso.rotation = RotationMatrix::getRotationZ(0.4363)
* RotationMatrix::getRotationY(0.2618);
rightInWorld.reserve(UltraSoundReceiveData::numOfUSEcho);
leftInWorld.reserve(UltraSoundReceiveData::numOfUSEcho);
getDebugParameterList().add(¶meter);
}
void UltrasonicDetector2020::execute()
{
// reset percept representation and measuremnt vectors
getUltrasonicObstaclePercept().location_on_ground.clear();
leftInWorld.clear();
rightInWorld.clear();
// transform measurements into world coordinates if not too far away
Pose3D torso = getKinematicChain().theLinks[KinematicChain::Torso].M;
for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) {
if(getUltraSoundReceiveData().dataLeft[i] < 5.0) { // == 5.0 means no echo
leftInWorld.push_back(torso * leftReceiverInTorso * Vector3d(getUltraSoundReceiveData().dataLeft[i] * 1000,0,0));
}
if(getUltraSoundReceiveData().dataRight[i] < 5.0) { // == 5.0 means no echo
rightInWorld.push_back(torso * rightReceiverInTorso * Vector3d(getUltraSoundReceiveData().dataRight[i] * 1000,0,0));
}
}
// filter out ground (-> later assume reflection?)
for(auto& point : leftInWorld){
if(point.z > parameter.ground_threshold){
getUltrasonicObstaclePercept().location_on_ground.push_back({point.x, point.y});
}
}
for(auto& point : rightInWorld){
if(point.z > parameter.ground_threshold){
getUltrasonicObstaclePercept().location_on_ground.push_back({point.x, point.y});
}
}
// 3. provide obstacle model measurements
draw();
}
//bool UltrasonicObstacleLocator2020::is_new_data_avaliable() const
//{
// for(int i = 0; i < UltraSoundReceiveData::numOfUSEcho; i++) {
// if(getUltraSoundReceiveData().dataLeft[i] != lastValidUltraSoundReceiveData.dataLeft[i] ||
// getUltraSoundReceiveData().dataRight[i] != lastValidUltraSoundReceiveData.dataRight[i])
// {
// return true;
// }
// }
// return false;
//}
void UltrasonicDetector2020::draw() const
{
DEBUG_REQUEST("UltrasonicDetector2020:draw3D:measurements",
for(auto& point : leftInWorld){
SPHERE("0000FF", 10, point);
}
for(auto& point : rightInWorld){
SPHERE("FF0000", 10, point);
}
);
}
<|endoftext|>
|
<commit_before>/************************************************************
USAGE: This file is used to test a new implementation of an
ecmdDataBuffer Member Function. It runs the new implementation
and compares the result and performance to the original/old
implementation.
Look for 'CHANGE_CODE_HERE' flags below to see where you have
to update this file
************************************************************/
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- ----- -----------------------------
// initial Creation 04/20/07 Shashank Common TestCase framework to compare
// and analyze old and new function in ecmdDataBuffer.C
// End Change Log *****************************************************
#include <list>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <sys/times.h>
#include <stdlib.h> // for random()
// eCMD Includes
#include <ecmdClientCapi.H>
#include <ecmdDataBuffer.H>
#include <ecmdUtils.H>
#include <ecmdSharedUtils.H>
#include <ecmdStructs.H>
/************************************************************
CHANGE_CODE_HERE
Include the headers and define the macros required for the
preferred function(old version) which user want to analyze
and compare with the new version of that fucntion.The old
function is defined later (see bottom).
************************************************************/
const char* program_name ;
void print_usage(FILE* stream, int exit_code)
{
fprintf(stream,"Usage: %s :options \n",program_name);
fprintf(stream,
" help Display the usage information\n"
" -bitMax value The maximum number of bits user want to set in the DataBuffer\n"
" -increment value The value of increment in the for loop\n"
" -seed value Value for random() # seed that creates test array"
" eg. \n"
" ecmd_DataBuffer_tc help \n"
" ecmd_DataBuffer_tc -bitMax 300 -increment 2 \n");
exit(exit_code);
}
int main (int argc, char *argv[])
{
printf("***Start main***\n");
uint32_t rc = ECMD_SUCCESS;
printf("***Start of Testcase...\n");
printf("***TestCase : To test, compare, and analyze the new function with the old function\n");
/****************************************
parse the CommandLine options
*****************************************/
program_name=argv[0];
char * curArg;
// Default Values
// this variable is used for the increment value user want to use in the "for" loop
int increment=1;
// this variable is used for the maximum bit size user want to set in databuffer.
int bitMax=100;
// this variable is used for the 'seed' of srandom
int seed=1;
//To display help
if (argc > 1)
{
//To display help
if ( ( !strcasecmp(argv[1], "help") || !strcasecmp(argv[1], "-h") || !strcasecmp(argv[1], "--help"))
&& (argc > 1) )
print_usage(stdout,0);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-bitMax");
if(curArg!=NULL)
bitMax = (uint32_t)atoi(curArg);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-increment");
if(curArg!=NULL)
increment = (uint32_t)atoi(curArg);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-seed");
if(curArg!=NULL)
seed = (uint32_t)atoi(curArg);
} // end of argc>1 check
printf("***Value of bitMax = %d, increment = %d, seed = %d\n***(Note: These values can be set via cmdline - see 'help')\n",bitMax, increment, seed);
/****************************************
Create Variables
*****************************************/
//Declaration of DataBuffer
ecmdDataBuffer buf_old,buf_new;
//variable declared to record the time taken by the function in CPU ticks
clock_t start_new,stop_new,start_old,stop_old;
static clock_t old_time = 0,new_time = 0;
//Variable used to record the number of times the function is called.
static uint32_t FunCnt_old = 0,FunCnt_new = 0;
// Create test array
uint32_t wordMax = bitMax % 32 ? (bitMax / 32 + 1) : bitMax / 32;
uint32_t * test_array = new uint32_t[wordMax];
srandom(seed); // set random 'seed'
for (uint32_t test_array_loop = 0; test_array_loop < wordMax ; test_array_loop++)
test_array[test_array_loop] = random();
/****************************************
Test Loop
*****************************************/
for(int i=0;i<bitMax ; i++){
for(int j=0 ;j< i+1;j=j+increment){
//bit size is set in the databuffer for new function
buf_new.setBitLength(j+1);
//start time stamp for new function
start_new=times(NULL);
/*****************************************************************
CHANGE_CODE_HERE
Call new version of function that user want to analyze
eg.
rc=buf_new.insert(array,0,j+1);
This function need to be defined in the ecmaDataBuffer.C
*****************************************************************/
//stop time stamp for new function
stop_new=times(NULL);
//calculate the time taken by new function in the processing
new_time=new_time + (stop_new-start_new);
//calculate the number of times the new function is called
FunCnt_new=FunCnt_new+1;
//check if there is no error in the called new function.
if(rc){
printf("\nnew function failed at break point j= %d for i= %d, rc= 0x%x",j,i,rc);
break;
}
//otherwise process the old function
else {
//bit size is set in the databuffer for the old function
buf_old.setBitLength(j+1);
//start time stamp for the old function
start_old=times(NULL);
/**************************************************************
CHANGE_CODE_HERE
Call old version of function that user want to analyze
eg.
rc=buf_old.old_insert( array,0,j+1);
This function need to be defined here in the test case only(see
bottom).
**************************************************************/
//stop time stamp for the old function.
stop_old=times(NULL);
//calculate the time taken by old function in the processing
old_time=old_time + (stop_old-start_old);
//calculate the number of times the new function is called
FunCnt_old=FunCnt_old+1;
//check if there is no error in the called old function.
if(rc){
printf("\nold function failed at break point j= %d for i= %d, rc= 0x%x\n",j,i,rc);
break;
}
//comparison is made to check whether the new function and old function give the same result
if(buf_old!=buf_new){
printf("comparison Failed:the new function and old function do not match\n"
"comparison failed at break point j= %d for i= %d\n"
"the string should be:(0x%s)\n"
"but the string is :(0x%s)\n",
j,i,buf_old.genHexLeftStr().c_str(),buf_new.genHexLeftStr().c_str());
rc= ECMD_FAILURE;
break;
}
}
}
}
printf("TOTAL TIME in CPU ticks for old_function = %lu for Function Count = %d\n",old_time,FunCnt_old);
printf("TOTAL TIME in CPU ticks for new_function = %lu for Function Count = %d\n",new_time,FunCnt_new);
if (rc != ECMD_SUCCESS)
printf("\n****ERROR: TESTCASE FAILED ,exit returning rc (0x%08x)***\n",rc);
else {
printf("\n***Testcase Passed***");
printf("\n***End of Testcase***\n");
}
return rc;
}
/*******************************************************************************************************************
CHANGE_CODE_HERE
Define here the old version of the function that user want to analyze and compare.This function has been
copied from the ecmdDataBuffer.C
eg.
uint32_t ecmdDataBuffer::old_insert(const uint32_t *i_dataIn, uint32_t i_targetStart, uint32_t i_len, uint32_t i_sourceStart){
uint32_t rc = ECMD_DBUF_SUCCESS;
if (i_targetStart+i_len > iv_NumBits) {
ETRAC3("**** ERROR : ecmdDataBuffer::insert: i_targetStart %d + i_len %d > iv_NumBits (%d)", i_targetStart, i_len, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else if (i_targetStart >= iv_NumBits) {
ETRAC2("**** ERROR : ecmdDataBuffer::insert: i_targetStart %d >= iv_NumBits (%d)", i_targetStart, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else if (i_len > iv_NumBits) {
ETRAC2("**** ERROR : ecmdDataBuffer::insert: i_len %d > iv_NumBits (%d)", i_len, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else {
uint32_t mask = 0x80000000 >> (i_sourceStart % 32);
const uint32_t * sourcePtr = i_dataIn;
for (uint32_t i = 0; i < i_len; i++) {
if (sourcePtr[(i+i_sourceStart)/32] & mask) {
rc = this->setBit(i_targetStart+i);
}
else {
rc = this->clearBit(i_targetStart+i);
}
mask >>= 1;
if (mask == 0x00000000) {
mask = 0x80000000;
}
if (rc) break;
}
}
return rc;
}
********************************************************************************************************************/
<commit_msg>usage instructions update<commit_after>/************************************************************
USAGE: This file is used to test a new implementation of an
ecmdDataBuffer Member Function. It runs the new implementation
and compares the result and performance to the original/old
implementation.
Look for 'CHANGE_CODE_HERE' flags below to see where you have
to update this file
************************************************************/
// Change Log *********************************************************
//
// Flag Reason Vers Date Coder Description
// ---- -------- ---- -------- ----- -----------------------------
// initial Creation 04/20/07 Shashank Common TestCase framework to compare
// and analyze old and new function in ecmdDataBuffer.C
// End Change Log *****************************************************
#include <list>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <sys/times.h>
#include <stdlib.h> // for random()
// eCMD Includes
#include <ecmdClientCapi.H>
#include <ecmdDataBuffer.H>
#include <ecmdUtils.H>
#include <ecmdSharedUtils.H>
#include <ecmdStructs.H>
/************************************************************
CHANGE_CODE_HERE
Include the headers and define the macros required for the
preferred function(old version) which user want to analyze
and compare with the new version of that fucntion.The old
function is defined later (see bottom).
************************************************************/
const char* program_name ;
void print_usage(FILE* stream, int exit_code)
{
fprintf(stream,"Usage: %s :options \n",program_name);
fprintf(stream,
" help Display the usage information\n"
" -bitMax value The maximum number of bits user want to set in the DataBuffer\n"
" -increment value The value of increment in the for loop\n"
" -seed value Value for random() # seed that creates test array"
" eg. \n"
" ecmd_DataBuffer_tc help \n"
" ecmd_DataBuffer_tc -bitMax 300 -increment 2 \n");
exit(exit_code);
}
int main (int argc, char *argv[])
{
printf("***Start main***\n");
uint32_t rc = ECMD_SUCCESS;
printf("***Start of Testcase...\n");
printf("***TestCase : To test, compare, and analyze the new function with the old function\n");
/****************************************
parse the CommandLine options
*****************************************/
program_name=argv[0];
char * curArg;
// Default Values
// this variable is used for the increment value user want to use in the "for" loop
int increment=1;
// this variable is used for the maximum bit size user want to set in databuffer.
int bitMax=100;
// this variable is used for the 'seed' of srandom
int seed=1;
//To display help
if (argc > 1)
{
//To display help
if ( ( !strcasecmp(argv[1], "help") || !strcasecmp(argv[1], "-h") || !strcasecmp(argv[1], "--help"))
&& (argc > 1) )
print_usage(stdout,0);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-bitMax");
if(curArg!=NULL)
bitMax = (uint32_t)atoi(curArg);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-increment");
if(curArg!=NULL)
increment = (uint32_t)atoi(curArg);
curArg = ecmdParseOptionWithArgs(&argc, &argv, "-seed");
if(curArg!=NULL)
seed = (uint32_t)atoi(curArg);
} // end of argc>1 check
printf("***Value of bitMax = %d, increment = %d, seed = %d\n***(Note: These values can be set via cmdline - see 'help')\n",bitMax, increment, seed);
/****************************************
Create Variables
*****************************************/
//Declaration of DataBuffer
ecmdDataBuffer buf_old,buf_new;
//variable declared to record the time taken by the function in CPU ticks
clock_t start_new,stop_new,start_old,stop_old;
static clock_t old_time = 0,new_time = 0;
//Variable used to record the number of times the function is called.
static uint32_t FunCnt_old = 0,FunCnt_new = 0;
// Create test array
uint32_t wordMax = bitMax % 32 ? (bitMax / 32 + 1) : bitMax / 32;
uint32_t * test_array = new uint32_t[wordMax];
srandom(seed); // set random 'seed'
for (uint32_t test_array_loop = 0; test_array_loop < wordMax ; test_array_loop++)
test_array[test_array_loop] = random();
/****************************************
Test Loop
*****************************************/
for(int i=0;i<bitMax ; i++){
for(int j=0 ;j< i+1;j=j+increment){
//bit size is set in the databuffer for new function
buf_new.setBitLength(j+1);
//start time stamp for new function
start_new=times(NULL);
/*****************************************************************
CHANGE_CODE_HERE
Call new version of function that user want to analyze
eg.
rc=buf_new.insert(array,0,j+1);
This function need to be defined in the ecmaDataBuffer.C
*****************************************************************/
//stop time stamp for new function
stop_new=times(NULL);
//calculate the time taken by new function in the processing
new_time=new_time + (stop_new-start_new);
//calculate the number of times the new function is called
FunCnt_new=FunCnt_new+1;
//check if there is no error in the called new function.
if(rc){
printf("\nnew function failed at break point j= %d for i= %d, rc= 0x%x",j,i,rc);
break;
}
//otherwise process the old function
else {
//bit size is set in the databuffer for the old function
buf_old.setBitLength(j+1);
//start time stamp for the old function
start_old=times(NULL);
/**************************************************************
CHANGE_CODE_HERE
Call old version of function that user want to analyze
eg.
rc=buf_old.old_insert( array,0,j+1);
This function need to be defined here in the test case only(see
bottom).
**************************************************************/
//stop time stamp for the old function.
stop_old=times(NULL);
//calculate the time taken by old function in the processing
old_time=old_time + (stop_old-start_old);
//calculate the number of times the new function is called
FunCnt_old=FunCnt_old+1;
//check if there is no error in the called old function.
if(rc){
printf("\nold function failed at break point j= %d for i= %d, rc= 0x%x\n",j,i,rc);
break;
}
//comparison is made to check whether the new function and old function give the same result
if(buf_old!=buf_new){
printf("comparison Failed:the new function and old function do not match\n"
"comparison failed at break point j= %d for i= %d\n"
"the string should be:(0x%s)\n"
"but the string is :(0x%s)\n",
j,i,buf_old.genHexLeftStr().c_str(),buf_new.genHexLeftStr().c_str());
rc= ECMD_FAILURE;
break;
}
}
}
}
printf("TOTAL TIME in CPU ticks for old_function = %lu for Function Count = %d\n",old_time,FunCnt_old);
printf("TOTAL TIME in CPU ticks for new_function = %lu for Function Count = %d\n",new_time,FunCnt_new);
if (rc != ECMD_SUCCESS)
printf("\n****ERROR: TESTCASE FAILED ,exit returning rc (0x%08x)***\n",rc);
else {
printf("\n***Testcase Passed***");
printf("\n***End of Testcase***\n");
}
return rc;
}
/*******************************************************************************************************************
CHANGE_CODE_HERE
1) Define here the old version of the function that user want to analyze and compare. This function has been
copied from the ecmdDataBuffer.C
2) For compile reasons, the old function must also be defined in a local copy of ecmdDataBuffer.H.
For Example:
uint32_t ecmdDataBuffer::old_insert(const uint32_t *i_dataIn, uint32_t i_targetStart, uint32_t i_len, uint32_t i_sourceStart){
uint32_t rc = ECMD_DBUF_SUCCESS;
if (i_targetStart+i_len > iv_NumBits) {
ETRAC3("**** ERROR : ecmdDataBuffer::insert: i_targetStart %d + i_len %d > iv_NumBits (%d)", i_targetStart, i_len, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else if (i_targetStart >= iv_NumBits) {
ETRAC2("**** ERROR : ecmdDataBuffer::insert: i_targetStart %d >= iv_NumBits (%d)", i_targetStart, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else if (i_len > iv_NumBits) {
ETRAC2("**** ERROR : ecmdDataBuffer::insert: i_len %d > iv_NumBits (%d)", i_len, iv_NumBits);
RETURN_ERROR(ECMD_DBUF_BUFFER_OVERFLOW);
} else {
uint32_t mask = 0x80000000 >> (i_sourceStart % 32);
const uint32_t * sourcePtr = i_dataIn;
for (uint32_t i = 0; i < i_len; i++) {
if (sourcePtr[(i+i_sourceStart)/32] & mask) {
rc = this->setBit(i_targetStart+i);
}
else {
rc = this->clearBit(i_targetStart+i);
}
mask >>= 1;
if (mask == 0x00000000) {
mask = 0x80000000;
}
if (rc) break;
}
}
return rc;
}
********************************************************************************************************************/
<|endoftext|>
|
<commit_before>#ifndef AUTOCHECK_REPORTER_HPP
#define AUTOCHECK_REPORTER_HPP
#include <iostream>
#include <sstream>
#include <cmath>
#include "distribution.hpp"
namespace autocheck {
class reporter {
public:
virtual void success(size_t tests, size_t max_tests,
size_t trivial = 0,
distribution&& dist = distribution()) const = 0;
virtual void failure(size_t tests, const char* reason) const = 0;
virtual ~reporter() {}
};
int round_percentage(size_t a, size_t b) {
return static_cast<int>(ceil(100.0 * a / b));
}
void report_success(std::ostream& out, size_t tests, size_t max_tests,
size_t trivial, distribution&& dist)
{
if (tests < max_tests) {
out << "Arguments exhausted after " << tests << " tests."
<< std::endl;
} else {
assert(tests == max_tests);
out << "OK, passed " << tests << " tests";
if (trivial) {
out << " (" << round_percentage(trivial, tests) << "% trivial)";
}
out << "." << std::endl;
}
/* Sort tags in descending order by size. */
std::sort(dist.begin(), dist.end(),
[] (const dist_tag& a, const dist_tag& b) {
return (std::get<1>(a) == std::get<1>(b))
? (std::get<0>(a) < std::get<0>(b))
: (std::get<1>(a) > std::get<1>(b));
});
for (const dist_tag& tag : dist) {
out << round_percentage(std::get<1>(tag), tests) << "% "
<< std::get<0>(tag) << "." << std::endl;
}
}
void report_failure(std::ostream& out, size_t tests, const char* reason) {
out << "Falsifiable, after " << tests << " tests:" << std::endl
<< reason << std::endl;
}
class ostream_reporter : public reporter {
private:
std::ostream& out;
public:
ostream_reporter(std::ostream& out = std::cout) : out(out) {}
virtual void success(size_t tests, size_t max_tests,
size_t trivial, distribution&& dist) const
{
report_success(out, tests, max_tests, trivial, std::move(dist));
}
virtual void failure(size_t tests, const char* reason) const {
report_failure(out, tests, reason);
}
};
#ifdef ASSERT_TRUE
class gtest_reporter : public reporter {
public:
virtual void success(size_t tests, size_t max_tests,
size_t trivial, distribution&& dist) const
{
report_success(std::clog, tests, max_tests, trivial, std::move(dist));
ASSERT_TRUE(true);
}
virtual void failure(size_t tests, const char* reason) const {
std::ostringstream out;
report_failure(out, tests, reason);
static const bool AUTOCHECK_SUCCESS = false;
ASSERT_TRUE(AUTOCHECK_SUCCESS) << out.str();
}
};
#endif // ASSERT_TRUE
}
#endif
<commit_msg>inlining functions<commit_after>#ifndef AUTOCHECK_REPORTER_HPP
#define AUTOCHECK_REPORTER_HPP
#include <iostream>
#include <sstream>
#include <cmath>
#include "distribution.hpp"
namespace autocheck {
class reporter {
public:
virtual void success(size_t tests, size_t max_tests,
size_t trivial = 0,
distribution&& dist = distribution()) const = 0;
virtual void failure(size_t tests, const char* reason) const = 0;
virtual ~reporter() {}
};
inline int round_percentage(size_t a, size_t b) {
return static_cast<int>(ceil(100.0 * a / b));
}
inline void report_success(std::ostream& out, size_t tests, size_t max_tests,
size_t trivial, distribution&& dist)
{
if (tests < max_tests) {
out << "Arguments exhausted after " << tests << " tests."
<< std::endl;
} else {
assert(tests == max_tests);
out << "OK, passed " << tests << " tests";
if (trivial) {
out << " (" << round_percentage(trivial, tests) << "% trivial)";
}
out << "." << std::endl;
}
/* Sort tags in descending order by size. */
std::sort(dist.begin(), dist.end(),
[] (const dist_tag& a, const dist_tag& b) {
return (std::get<1>(a) == std::get<1>(b))
? (std::get<0>(a) < std::get<0>(b))
: (std::get<1>(a) > std::get<1>(b));
});
for (const dist_tag& tag : dist) {
out << round_percentage(std::get<1>(tag), tests) << "% "
<< std::get<0>(tag) << "." << std::endl;
}
}
inline void report_failure(std::ostream& out, size_t tests, const char* reason) {
out << "Falsifiable, after " << tests << " tests:" << std::endl
<< reason << std::endl;
}
class ostream_reporter : public reporter {
private:
std::ostream& out;
public:
ostream_reporter(std::ostream& out = std::cout) : out(out) {}
virtual void success(size_t tests, size_t max_tests,
size_t trivial, distribution&& dist) const
{
report_success(out, tests, max_tests, trivial, std::move(dist));
}
virtual void failure(size_t tests, const char* reason) const {
report_failure(out, tests, reason);
}
};
#ifdef ASSERT_TRUE
class gtest_reporter : public reporter {
public:
virtual void success(size_t tests, size_t max_tests,
size_t trivial, distribution&& dist) const
{
report_success(std::clog, tests, max_tests, trivial, std::move(dist));
ASSERT_TRUE(true);
}
virtual void failure(size_t tests, const char* reason) const {
std::ostringstream out;
report_failure(out, tests, reason);
static const bool AUTOCHECK_SUCCESS = false;
ASSERT_TRUE(AUTOCHECK_SUCCESS) << out.str();
}
};
#endif // ASSERT_TRUE
}
#endif
<|endoftext|>
|
<commit_before>/**
* Created by Jian Chen
* Inspired by the book: C++ Concurrency In Action
* Thanks to its author: Anthony Williams
* @since 2016.05.15
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
* @thread-safe
*/
#pragma once
#include "semaphore.hpp"
#include "callable.hpp"
#include <functional>
#include <future>
#include <thread>
#include <atomic>
#include <queue>
namespace chen
{
class threadpool final
{
public:
/**
* Construct with thread count
*/
threadpool(std::size_t count = 0);
~threadpool();
public:
/**
* Post a function to pool
*/
template <typename F>
std::future<typename std::result_of<F()>::type> post(F f)
{
typedef typename std::result_of<F()>::type result_type;
std::packaged_task<result_type()> task(std::move(f));
std::future<result_type> future(task.get_future());
std::unique_lock<std::mutex> lock(this->_mutex);
this->_queue.push(std::move(task));
lock.unlock();
this->_semaphore.post();
return future;
}
private:
/**
* Working thread
*/
void run();
/**
* Clean pool
*/
void clean();
private:
std::mutex _mutex;
std::queue<callable> _queue;
std::atomic<bool> _exit;
std::vector<std::thread> _pool;
chen::semaphore _semaphore;
private:
threadpool(const threadpool&) = delete;
threadpool& operator=(const threadpool&) = delete;
};
}<commit_msg>misc: use emplace<commit_after>/**
* Created by Jian Chen
* Inspired by the book: C++ Concurrency In Action
* Thanks to its author: Anthony Williams
* @since 2016.05.15
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
* @thread-safe
*/
#pragma once
#include "semaphore.hpp"
#include "callable.hpp"
#include <functional>
#include <future>
#include <thread>
#include <atomic>
#include <queue>
namespace chen
{
class threadpool final
{
public:
/**
* Construct with thread count
*/
threadpool(std::size_t count = 0);
~threadpool();
public:
/**
* Post a function to pool
*/
template <typename F>
std::future<typename std::result_of<F()>::type> post(F f)
{
typedef typename std::result_of<F()>::type result_type;
std::packaged_task<result_type()> task(std::move(f));
std::future<result_type> future(task.get_future());
std::unique_lock<std::mutex> lock(this->_mutex);
this->_queue.emplace(std::move(task));
lock.unlock();
this->_semaphore.post();
return future;
}
private:
/**
* Working thread
*/
void run();
/**
* Clean pool
*/
void clean();
private:
std::mutex _mutex;
std::queue<callable> _queue;
std::atomic<bool> _exit;
std::vector<std::thread> _pool;
chen::semaphore _semaphore;
private:
threadpool(const threadpool&) = delete;
threadpool& operator=(const threadpool&) = delete;
};
}<|endoftext|>
|
<commit_before>/**
* This file defines the lock graph data structure used during the post-mortem
* program analysis.
*/
#ifndef D2_CORE_LOCK_GRAPH_HPP
#define D2_CORE_LOCK_GRAPH_HPP
#include <d2/detail/lock_debug_info.hpp>
#include <d2/lock_id.hpp>
#include <d2/segment.hpp>
#include <d2/thread_id.hpp>
#include <boost/assert.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/named_graph.hpp>
#include <boost/move/move.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/operators.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
namespace d2 {
namespace lock_graph_detail {
/**
* Set whose underlying representation can be shared by several owners.
*
* @note This structure is optimized so that several duplicated read-only
* copies of it are space efficient.
*/
template <typename Set>
struct shared_set {
typedef Set underlying_set_type;
//! Construct an empty set.
shared_set()
: set_(new underlying_set_type())
{ }
//! Construct a shared set sharing its underlying set with `other`.
/*implicit*/ shared_set(shared_set const& other)
: set_(other.set_)
{ }
//! Construct a shared set with an underlying set equal to `other`.
explicit shared_set(BOOST_RV_REF(underlying_set_type) other)
: set_(new underlying_set_type(boost::move(other)))
{ }
//! Return a constant reference to the underlying set of `*this`.
operator underlying_set_type const&() const {
BOOST_ASSERT_MSG(set_, "invariant broken: the shared_ptr of a "
"shared set instance is invalid");
return *set_;
}
private:
boost::shared_ptr<underlying_set_type const> set_;
};
/**
* Set of locks held by a thread.
*
* @note We use a `shared_set` because an instance of `Gatelocks` is stored
* on each edge of the lock graph. We could use a `flyweight` too, but
* benchmarking shows that the current solution offers a better
* space/time tradeoff.
* The main differences between the two approaches are:
* - `flyweight` requires the set to be hashed everytime, which is
* more CPU intensive.
* - Using a `shared_set` is suboptimal because there may be some
* repetition of the gatelocks in the lock graph when the gatelocks
* are the same on different events.
*/
typedef shared_set<boost::unordered_set<LockId> > Gatelocks;
/**
* Label stored on each edge of a lock graph.
*/
struct LockGraphLabel : boost::equality_comparable<LockGraphLabel> {
LockGraphLabel(Segment s1, ThreadId thread,
Gatelocks const& gatelocks, Segment s2)
: s1(s1), s2(s2), thread_(thread), gatelocks_(gatelocks)
{ }
detail::LockDebugInfo l1_info, l2_info;
Segment s1, s2;
friend Gatelocks::underlying_set_type const&
gatelocks_of(LockGraphLabel const& self) {
return self.gatelocks_;
}
friend ThreadId const& thread_of(LockGraphLabel const& self) {
return self.thread_;
}
friend bool operator==(LockGraphLabel const& a, LockGraphLabel const& b) {
// Note: We test the easiest first, i.e. the threads and segments,
// which are susceptible of being similar to integers.
return a.s1 == b.s1 &&
a.s2 == b.s2 &&
thread_of(a) == thread_of(b) &&
a.l1_info == b.l1_info &&
a.l2_info == b.l2_info &&
gatelocks_of(a) == gatelocks_of(b);
}
private:
ThreadId thread_;
Gatelocks gatelocks_;
};
/**
* Directed graph representing the contexts in which synchronization objects
* were acquired by threads.
*/
typedef boost::adjacency_list<
boost::vecS, boost::vecS, boost::directedS, LockId, LockGraphLabel
> LockGraph;
} // end namespace lock_graph_detail
namespace core {
using lock_graph_detail::LockGraph;
using lock_graph_detail::LockGraphLabel;
using lock_graph_detail::Gatelocks;
}
} // end namespace d2
namespace boost {
namespace graph {
// This is to be able to refer to a vertex in the lock graph using the
// LockId associated to it.
template <> struct internal_vertex_name<d2::LockId> {
typedef multi_index::identity<d2::LockId> type;
};
} // end namespace graph
} // end namespace boost
#endif // !D2_CORE_LOCK_GRAPH_HPP
<commit_msg>Use make_shared in the shared_set.<commit_after>/**
* This file defines the lock graph data structure used during the post-mortem
* program analysis.
*/
#ifndef D2_CORE_LOCK_GRAPH_HPP
#define D2_CORE_LOCK_GRAPH_HPP
#include <d2/detail/lock_debug_info.hpp>
#include <d2/lock_id.hpp>
#include <d2/segment.hpp>
#include <d2/thread_id.hpp>
#include <boost/assert.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/named_graph.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/move.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/operators.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>
namespace d2 {
namespace lock_graph_detail {
/**
* Set whose underlying representation can be shared by several owners.
*
* @note This structure is optimized so that several duplicated read-only
* copies of it are space efficient.
*/
template <typename Set>
struct shared_set {
typedef Set underlying_set_type;
//! Construct an empty set.
shared_set()
: set_(boost::make_shared<underlying_set_type>())
{ }
//! Construct a shared set sharing its underlying set with `other`.
/*implicit*/ shared_set(shared_set const& other)
: set_(other.set_)
{ }
//! Construct a shared set with an underlying set equal to `other`.
explicit shared_set(BOOST_RV_REF(underlying_set_type) other)
: set_(boost::make_shared<underlying_set_type>(boost::move(other)))
{ }
//! Return a constant reference to the underlying set of `*this`.
operator underlying_set_type const&() const {
BOOST_ASSERT_MSG(set_, "invariant broken: the shared_ptr of a "
"shared set instance is invalid");
return *set_;
}
private:
boost::shared_ptr<underlying_set_type const> set_;
};
/**
* Set of locks held by a thread.
*
* @note We use a `shared_set` because an instance of `Gatelocks` is stored
* on each edge of the lock graph. We could use a `flyweight` too, but
* benchmarking shows that the current solution offers a better
* space/time tradeoff.
* The main differences between the two approaches are:
* - `flyweight` requires the set to be hashed everytime, which is
* more CPU intensive.
* - Using a `shared_set` is suboptimal because there may be some
* repetition of the gatelocks in the lock graph when the gatelocks
* are the same on different events.
*/
typedef shared_set<boost::unordered_set<LockId> > Gatelocks;
/**
* Label stored on each edge of a lock graph.
*/
struct LockGraphLabel : boost::equality_comparable<LockGraphLabel> {
LockGraphLabel(Segment s1, ThreadId thread,
Gatelocks const& gatelocks, Segment s2)
: s1(s1), s2(s2), thread_(thread), gatelocks_(gatelocks)
{ }
detail::LockDebugInfo l1_info, l2_info;
Segment s1, s2;
friend Gatelocks::underlying_set_type const&
gatelocks_of(LockGraphLabel const& self) {
return self.gatelocks_;
}
friend ThreadId const& thread_of(LockGraphLabel const& self) {
return self.thread_;
}
friend bool operator==(LockGraphLabel const& a, LockGraphLabel const& b) {
// Note: We test the easiest first, i.e. the threads and segments,
// which are susceptible of being similar to integers.
return a.s1 == b.s1 &&
a.s2 == b.s2 &&
thread_of(a) == thread_of(b) &&
a.l1_info == b.l1_info &&
a.l2_info == b.l2_info &&
gatelocks_of(a) == gatelocks_of(b);
}
private:
ThreadId thread_;
Gatelocks gatelocks_;
};
/**
* Directed graph representing the contexts in which synchronization objects
* were acquired by threads.
*/
typedef boost::adjacency_list<
boost::vecS, boost::vecS, boost::directedS, LockId, LockGraphLabel
> LockGraph;
} // end namespace lock_graph_detail
namespace core {
using lock_graph_detail::LockGraph;
using lock_graph_detail::LockGraphLabel;
using lock_graph_detail::Gatelocks;
}
} // end namespace d2
namespace boost {
namespace graph {
// This is to be able to refer to a vertex in the lock graph using the
// LockId associated to it.
template <> struct internal_vertex_name<d2::LockId> {
typedef multi_index::identity<d2::LockId> type;
};
} // end namespace graph
} // end namespace boost
#endif // !D2_CORE_LOCK_GRAPH_HPP
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "cpp_utils/assert.hpp" //Assertions
#include "etl/etl.hpp"
#include "neural_base.hpp"
#include "util/tmp.hpp"
#include "layer_traits.hpp"
namespace dll {
/*!
* \brief Standard dynamic convolutional layer of neural network.
*/
template <typename Desc>
struct dyn_conv_layer final : neural_base<dyn_conv_layer<Desc>> {
using desc = Desc; ///< The descriptor type
using weight = typename desc::weight; ///< The weight type
using this_type = dyn_conv_layer<desc>; ///< This type
static constexpr const bool dbn_only = layer_traits<this_type>::is_dbn_only();
static constexpr const function activation_function = desc::activation_function;
using input_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one input
using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
using input_t = std::vector<input_one_t>; ///< The type for many input
using output_t = std::vector<output_one_t>; ///< The type for many output
//TODO CHECK
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>;
using w_type = etl::dyn_matrix<weight, 4>;
using b_type = etl::dyn_matrix<weight, 1>;
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
//No copying
dyn_conv_layer(const dyn_conv_layer& layer) = delete;
dyn_conv_layer& operator=(const dyn_conv_layer& layer) = delete;
//No moving
dyn_conv_layer(dyn_conv_layer&& layer) = delete;
dyn_conv_layer& operator=(dyn_conv_layer&& layer) = delete;
size_t nv1; ///< The first visible dimension
size_t nv2; ///< The second visible dimension
size_t nh1; ///< The first output dimension
size_t nh2; ///< The second output dimension
size_t nc; ///< The number of input channels
size_t k; ///< The number of filters
size_t nw1; ///< The first dimension of the filters
size_t nw2; ///< The second dimension of the filters
dyn_conv_layer(){
// Nothing else to init
}
void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2){
this->nv1 = nv1;
this->nv2 = nv2;
this->nh1 = nh1;
this->nh2 = nh2;
this->nc = nc;
this->k = k;
this->nw1 = nv1 - nh1 + 1;
this->nw2 = nv2 - nh2 + 1;
w = etl::dyn_matrix<weight, 4>(nc, k, nw1, nw2);
b = etl::dyn_vector<weight>(k);
//Initialize the weights and biases following Lecun approach
//to initialization [lecun-98b]
w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
if (activation_function == function::RELU) {
b = 0.01;
} else {
b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
}
}
std::size_t input_size() const noexcept {
return nc * nv1 * nv2;
}
std::size_t output_size() const noexcept {
return k * nh1 * nh2;
}
std::size_t parameters() const noexcept {
return k * nw1 * nw2;
}
std::string to_short_string() const {
char buffer[1024];
snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
return {buffer};
}
void display() const {
std::cout << to_short_string() << std::endl;
}
void backup_weights() {
unique_safe_get(bak_w) = w;
unique_safe_get(bak_b) = b;
}
void restore_weights() {
w = *bak_w;
b = *bak_b;
}
template <typename V>
void activate_hidden(output_one_t& output, const V& v) const {
etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution
auto w_f = etl::force_temporary(w);
//flip all the kernels horizontally and vertically
for (std::size_t channel = 0; channel < nc; ++channel) {
for (size_t k = 0; k < k; ++k) {
w_f(channel)(k).fflip_inplace();
}
}
v_cv(1) = 0;
for (std::size_t channel = 0; channel < nc; ++channel) {
etl::conv_2d_valid_multi(v(channel), w_f(channel), v_cv(0));
v_cv(1) += v_cv(0);
}
output = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
}
template <typename H1, typename V>
void batch_activate_hidden(H1&& output, const V& v) const {
etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution
const auto Batch = etl::dim<0>(v);
auto w_f = force_temporary(w);
//flip all the kernels horizontally and vertically
for (std::size_t channel = 0; channel < nc; ++channel) {
for (size_t k = 0; k < k; ++k) {
w_f(channel)(k).fflip_inplace();
}
}
for (std::size_t batch = 0; batch < Batch; ++batch) {
v_cv(1) = 0;
for (std::size_t channel = 0; channel < nc; ++channel) {
etl::conv_2d_valid_multi(v(batch)(channel), w_f(channel), v_cv(0));
v_cv(1) += v_cv(0);
}
output(batch) = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
}
}
void prepare_input(input_one_t& input) const {
input = input_one_t(nc, nv1, nv2);
}
template <typename Input>
output_t prepare_output(std::size_t samples) const {
output_t output;
output.reserve(samples);
for(size_t i = 0; i < samples; ++i){
output.emplace_back(k, nh1, nh2);
}
return output;
}
template <typename Input>
output_one_t prepare_one_output() const {
return output_one_t(k, nh1, nh2);
}
template <std::size_t B>
auto prepare_input_batch(){
return etl::dyn_matrix<weight, 4>(B, nc, nv1, nv2);
}
template <std::size_t B>
auto prepare_output_batch(){
return etl::dyn_matrix<weight, 4>(B, k, nh1, nh2);
}
template <typename DBN>
void init_sgd_context() {
this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
}
};
} //end of dll namespace
<commit_msg>Fix dyn_conv :(<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "cpp_utils/assert.hpp" //Assertions
#include "etl/etl.hpp"
#include "neural_base.hpp"
#include "util/tmp.hpp"
#include "layer_traits.hpp"
namespace dll {
/*!
* \brief Standard dynamic convolutional layer of neural network.
*/
template <typename Desc>
struct dyn_conv_layer final : neural_base<dyn_conv_layer<Desc>> {
using desc = Desc; ///< The descriptor type
using weight = typename desc::weight; ///< The weight type
using this_type = dyn_conv_layer<desc>; ///< This type
static constexpr const bool dbn_only = layer_traits<this_type>::is_dbn_only();
static constexpr const function activation_function = desc::activation_function;
using input_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one input
using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
using input_t = std::vector<input_one_t>; ///< The type for many input
using output_t = std::vector<output_one_t>; ///< The type for many output
//TODO CHECK
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>;
using w_type = etl::dyn_matrix<weight, 4>;
using b_type = etl::dyn_matrix<weight, 1>;
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
//No copying
dyn_conv_layer(const dyn_conv_layer& layer) = delete;
dyn_conv_layer& operator=(const dyn_conv_layer& layer) = delete;
//No moving
dyn_conv_layer(dyn_conv_layer&& layer) = delete;
dyn_conv_layer& operator=(dyn_conv_layer&& layer) = delete;
size_t nv1; ///< The first visible dimension
size_t nv2; ///< The second visible dimension
size_t nh1; ///< The first output dimension
size_t nh2; ///< The second output dimension
size_t nc; ///< The number of input channels
size_t k; ///< The number of filters
size_t nw1; ///< The first dimension of the filters
size_t nw2; ///< The second dimension of the filters
dyn_conv_layer(){
// Nothing else to init
}
void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2){
this->nv1 = nv1;
this->nv2 = nv2;
this->nh1 = nh1;
this->nh2 = nh2;
this->nc = nc;
this->k = k;
this->nw1 = nv1 - nh1 + 1;
this->nw2 = nv2 - nh2 + 1;
w = etl::dyn_matrix<weight, 4>(nc, k, nw1, nw2);
b = etl::dyn_vector<weight>(k);
//Initialize the weights and biases following Lecun approach
//to initialization [lecun-98b]
w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
if (activation_function == function::RELU) {
b = 0.01;
} else {
b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
}
}
std::size_t input_size() const noexcept {
return nc * nv1 * nv2;
}
std::size_t output_size() const noexcept {
return k * nh1 * nh2;
}
std::size_t parameters() const noexcept {
return k * nw1 * nw2;
}
std::string to_short_string() const {
char buffer[1024];
snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
return {buffer};
}
void display() const {
std::cout << to_short_string() << std::endl;
}
void backup_weights() {
unique_safe_get(bak_w) = w;
unique_safe_get(bak_b) = b;
}
void restore_weights() {
w = *bak_w;
b = *bak_b;
}
template <typename V>
void activate_hidden(output_one_t& output, const V& v) const {
etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution
const auto K = k;
auto w_f = etl::force_temporary(w);
//flip all the kernels horizontally and vertically
for (std::size_t channel = 0; channel < nc; ++channel) {
for (size_t k = 0; k < K; ++k) {
w_f(channel)(k).fflip_inplace();
}
}
v_cv(1) = 0;
for (std::size_t channel = 0; channel < nc; ++channel) {
etl::conv_2d_valid_multi(v(channel), w_f(channel), v_cv(0));
v_cv(1) += v_cv(0);
}
output = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
}
template <typename H1, typename V>
void batch_activate_hidden(H1&& output, const V& v) const {
etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution
const auto Batch = etl::dim<0>(v);
const auto K = k;
auto w_f = force_temporary(w);
//flip all the kernels horizontally and vertically
for (std::size_t channel = 0; channel < nc; ++channel) {
for (size_t k = 0; k < K; ++k) {
w_f(channel)(k).fflip_inplace();
}
}
for (std::size_t batch = 0; batch < Batch; ++batch) {
v_cv(1) = 0;
for (std::size_t channel = 0; channel < nc; ++channel) {
etl::conv_2d_valid_multi(v(batch)(channel), w_f(channel), v_cv(0));
v_cv(1) += v_cv(0);
}
output(batch) = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
}
}
void prepare_input(input_one_t& input) const {
input = input_one_t(nc, nv1, nv2);
}
template <typename Input>
output_t prepare_output(std::size_t samples) const {
output_t output;
output.reserve(samples);
for(size_t i = 0; i < samples; ++i){
output.emplace_back(k, nh1, nh2);
}
return output;
}
template <typename Input>
output_one_t prepare_one_output() const {
return output_one_t(k, nh1, nh2);
}
template <std::size_t B>
auto prepare_input_batch(){
return etl::dyn_matrix<weight, 4>(B, nc, nv1, nv2);
}
template <std::size_t B>
auto prepare_output_batch(){
return etl::dyn_matrix<weight, 4>(B, k, nh1, nh2);
}
template <typename DBN>
void init_sgd_context() {
this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
}
};
} //end of dll namespace
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, 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_VERSION_HPP_INCLUDED
#define TORRENT_VERSION_HPP_INCLUDED
#define LIBTORRENT_VERSION_MAJOR 0
#define LIBTORRENT_VERSION_MINOR 13
#define LIBTORRENT_VERSION "0.13.0.0"
#endif
<commit_msg>bumped version number<commit_after>/*
Copyright (c) 2003, 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_VERSION_HPP_INCLUDED
#define TORRENT_VERSION_HPP_INCLUDED
#define LIBTORRENT_VERSION_MAJOR 0
#define LIBTORRENT_VERSION_MINOR 14
#define LIBTORRENT_VERSION "0.14.0.0"
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generator/trajectory_evaluator.h"
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
bool is_auto_tuning,
std::shared_ptr<PathTimeNeighborhood> pathtime_neighborhood)
: is_auto_tuning_(is_auto_tuning),
pathtime_neighborhood_(pathtime_neighborhood) {
for (const auto lon_trajectory : lon_trajectories) {
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
if (!is_auto_tuning_) {
double cost =
evaluate(planning_target, lon_trajectory, lat_trajectory, nullptr);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!is_auto_tuning_) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!is_auto_tuning_) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!is_auto_tuning_) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.empty();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!is_auto_tuning_) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!is_auto_tuning_) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
const {
CHECK(is_auto_tuning_);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// currently consider three costs:
// 1. the cost of jerk, currently only consider longitudinal jerk.
// 2. the cost of time to achieve the objective
// 3. the cost of failure to achieve the planning objective.
double weight_lon_travel = 1000.0;
double weight_lon_jerk = 1.0;
double weight_lon_obstacle = 100.0;
double weight_lat_offset = 1.0;
double lon_travel_cost =
compute_lon_objective_cost(lon_trajectory, planning_target);
double lon_jerk_cost = compute_lon_comfort_cost(lon_trajectory);
// for evaluating lateral trajectories
std::vector<double> s_values;
double s = 0.0;
while (s < FLAGS_decision_horizon) {
s_values.push_back(s);
s += FLAGS_trajectory_space_resolution;
}
double lat_offset_cost = compute_lat_offset_cost(lat_trajectory, s_values);
double lon_obstacle_cost = compute_lon_obstacle_cost(lon_trajectory);
if (cost_components) {
cost_components->push_back(lon_travel_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_obstacle_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_travel_cost * weight_lon_travel + lon_jerk_cost * weight_lon_jerk +
lat_offset_cost * weight_lat_offset +
lon_obstacle_cost * weight_lon_obstacle;
}
double TrajectoryEvaluator::compute_lat_offset_cost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double weight_same_side_offset = 1.0;
double weight_opposite_side_offset = 10.0;
double cost = 0.0;
for (const auto& s : s_values) {
double c = lat_trajectory->Evaluate(0, s);
if (c * lat_offset_start < 0.0) {
c = c * c * weight_opposite_side_offset;
} else {
c = c * c * weight_same_side_offset;
}
cost += c;
}
return cost;
}
double TrajectoryEvaluator::compute_lon_comfort_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost = 0.0;
double t = 0.0;
while (t < FLAGS_trajectory_time_length) {
double c = lon_trajectory->Evaluate(3, t);
cost += c * c;
t = t + FLAGS_trajectory_time_resolution;
}
return cost;
}
double TrajectoryEvaluator::compute_lon_objective_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target) const {
double weight_dist_travelled = 10.0;
double weight_on_reference_speed = 1.0;
double t_max = lon_trajectory->ParamLength();
double dist_s =
lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);
double cost = 0.0;
double t = 0.0;
while (t < FLAGS_trajectory_time_length) {
double c = planning_target.cruise_speed() - lon_trajectory->Evaluate(1, t);
cost += std::fabs(c);
t += FLAGS_trajectory_time_resolution;
}
cost *= weight_on_reference_speed;
cost += weight_dist_travelled * 1.0 / (1.0 + dist_s);
return cost;
}
// TODO(@all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::compute_lon_obstacle_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double start_time = 0.0;
double end_time = FLAGS_trajectory_time_length;
const auto& pt_intervals = pathtime_neighborhood_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
double obstacle_cost = 0.0;
for (std::size_t i = 0; i < pt_intervals.size(); ++i) {
const auto& pt_interval = pt_intervals[i];
if (pt_interval.empty()) {
continue;
}
double t = start_time + i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
for (const auto& m : pt_interval) {
double mid_s = (m.first + m.second) * 0.5;
obstacle_cost += 1.0 / std::exp(std::abs(traj_s - mid_s));
}
}
return obstacle_cost;
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: [lattice] adjust cost functions to make them in the same scale<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/trajectory_generator/trajectory_evaluator.h"
#include <cmath>
#include <functional>
#include <limits>
#include <utility>
#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"
namespace apollo {
namespace planning {
using Trajectory1d = Curve1d;
TrajectoryEvaluator::TrajectoryEvaluator(
const PlanningTarget& planning_target,
const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
bool is_auto_tuning,
std::shared_ptr<PathTimeNeighborhood> pathtime_neighborhood)
: is_auto_tuning_(is_auto_tuning),
pathtime_neighborhood_(pathtime_neighborhood) {
for (const auto lon_trajectory : lon_trajectories) {
if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
continue;
}
for (const auto lat_trajectory : lat_trajectories) {
if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
*lon_trajectory)) {
continue;
}
if (!is_auto_tuning_) {
double cost =
evaluate(planning_target, lon_trajectory, lat_trajectory, nullptr);
cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
} else {
std::vector<double> cost_components;
double cost = evaluate(planning_target, lon_trajectory, lat_trajectory,
&cost_components);
cost_queue_with_components_.push(PairCostWithComponents(
{lon_trajectory, lat_trajectory}, {cost_components, cost}));
}
}
}
if (!is_auto_tuning_) {
ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
} else {
ADEBUG << "Number of valid 1d trajectory pairs: "
<< cost_queue_with_components_.size();
}
}
bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
if (!is_auto_tuning_) {
return !cost_queue_.empty();
} else {
return !cost_queue_with_components_.empty();
}
}
std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
if (!is_auto_tuning_) {
return cost_queue_.size();
} else {
return cost_queue_with_components_.empty();
}
}
std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
CHECK(has_more_trajectory_pairs() == true);
if (!is_auto_tuning_) {
auto top = cost_queue_.top();
cost_queue_.pop();
return top.first;
} else {
auto top = cost_queue_with_components_.top();
cost_queue_with_components_.pop();
return top.first;
}
}
double TrajectoryEvaluator::top_trajectory_pair_cost() const {
if (!is_auto_tuning_) {
return cost_queue_.top().second;
} else {
return cost_queue_with_components_.top().second.second;
}
}
std::vector<double>
TrajectoryEvaluator::top_trajectory_pair_component_cost() const {
CHECK(is_auto_tuning_);
return cost_queue_with_components_.top().second.first;
}
double TrajectoryEvaluator::evaluate(
const PlanningTarget& planning_target,
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const std::shared_ptr<Trajectory1d>& lat_trajectory,
std::vector<double>* cost_components) const {
// currently consider three costs:
// 1. the cost of jerk, currently only consider longitudinal jerk.
// 2. the cost of time to achieve the objective
// 3. the cost of failure to achieve the planning objective.
double weight_lon_travel = 5.0;
double weight_lon_jerk = 1.0;
double weight_lon_obstacle = 1.0;
double weight_lat_offset = 1.0;
double lon_travel_cost =
compute_lon_objective_cost(lon_trajectory, planning_target);
double lon_jerk_cost = compute_lon_comfort_cost(lon_trajectory);
// for evaluating lateral trajectories
std::vector<double> s_values;
double s = 0.0;
while (s < FLAGS_decision_horizon) {
s_values.push_back(s);
s += FLAGS_trajectory_space_resolution;
}
double lat_offset_cost = compute_lat_offset_cost(lat_trajectory, s_values);
double lon_obstacle_cost = compute_lon_obstacle_cost(lon_trajectory);
if (cost_components) {
cost_components->push_back(lon_travel_cost);
cost_components->push_back(lon_jerk_cost);
cost_components->push_back(lon_obstacle_cost);
cost_components->push_back(lat_offset_cost);
}
return lon_travel_cost * weight_lon_travel +
lon_jerk_cost * weight_lon_jerk +
lat_offset_cost * weight_lat_offset +
lon_obstacle_cost * weight_lon_obstacle;
}
double TrajectoryEvaluator::compute_lat_offset_cost(
const std::shared_ptr<Trajectory1d>& lat_trajectory,
const std::vector<double>& s_values) const {
double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
double weight_same_side_offset = 1.0;
double weight_opposite_side_offset = 10.0;
double lat_offset_bound = 3.0;
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (const auto& s : s_values) {
double lat_offset = lat_trajectory->Evaluate(0, s);
double cost = lat_offset / lat_offset_bound;
if (lat_offset * lat_offset_start < 0.0) {
cost_sqr_sum += cost * cost * weight_opposite_side_offset;
cost_abs_sum += std::abs(cost) * weight_opposite_side_offset;
} else {
cost_sqr_sum += cost * cost * weight_same_side_offset;
cost_abs_sum += std::abs(cost) * weight_same_side_offset;
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::compute_lon_comfort_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
// TODO(all) need a new gflag for jerk_bound?
double jerk_bound = FLAGS_longitudinal_jerk_upper_bound;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double jerk = lon_trajectory->Evaluate(3, t);
double cost = jerk / jerk_bound;
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
double TrajectoryEvaluator::compute_lon_objective_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory,
const PlanningTarget& planning_target) const {
double weight_dist_travelled = 10.0;
double weight_on_reference_speed = 1.0;
double t_max = lon_trajectory->ParamLength();
double dist_s =
lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);
double speed_cost_sqr_sum = 0.0;
double speed_cost_abs_sum = 0.0;
for (double t = 0.0; t < FLAGS_trajectory_time_length;
t += FLAGS_trajectory_time_resolution) {
double cost = planning_target.cruise_speed() -
lon_trajectory->Evaluate(1, t);
speed_cost_sqr_sum += cost * cost;
speed_cost_abs_sum += std::abs(cost);
}
double speed_cost = speed_cost_sqr_sum /
(speed_cost_abs_sum + FLAGS_lattice_epsilon);
double dist_travelled_cost = 1.0 / (1.0 + dist_s);
return (weight_on_reference_speed * speed_cost +
weight_dist_travelled * dist_travelled_cost) /
(weight_on_reference_speed + weight_dist_travelled);
}
// TODO(@all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::compute_lon_obstacle_cost(
const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
double start_time = 0.0;
double end_time = FLAGS_trajectory_time_length;
const auto& pt_intervals = pathtime_neighborhood_->GetPathBlockingIntervals(
start_time, end_time, FLAGS_trajectory_time_resolution);
// TODO(all) move buffer and sigma to gflags
double buffer = 1.0;
double sigma = 0.5;
double cost_sqr_sum = 0.0;
double cost_abs_sum = 0.0;
for (std::size_t i = 0; i < pt_intervals.size(); ++i) {
const auto& pt_interval = pt_intervals[i];
if (pt_interval.empty()) {
continue;
}
double t = start_time + i * FLAGS_trajectory_time_resolution;
double traj_s = lon_trajectory->Evaluate(0, t);
for (const auto& m : pt_interval) {
double cost = 0.0;
if (traj_s > m.first - buffer && traj_s < m.second + buffer) {
cost = 1.0;
} else if (traj_s < m.first) {
double dist = traj_s - m.first + buffer;
cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
} else if (traj_s > m.second) {
double dist = m.second + buffer - traj_s;
cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
}
cost_sqr_sum += cost * cost;
cost_abs_sum += std::abs(cost);
}
}
return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}
std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
const PlanningTarget& planning_target,
const std::vector<apollo::common::SpeedPoint> st_points,
const std::vector<apollo::common::FrenetFramePoint> sl_points) {
std::vector<double> ret;
return ret;
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
.L $ALICE_ROOT/../src/STAT/AliTreeTrending.cxx+
*/
#include "TStatToolkit.h"
#include "Riostream.h"
#include <iostream>
#include "TSystem.h"
#include "TNamed.h"
#include "TFile.h"
#include "TTree.h"
#include "TPRegexp.h"
#include "TFriendElement.h"
#include "AliExternalInfo.h"
#include "TTreeFormula.h"
#include "TTreeFormulaManager.h"
#include "AliTreeTrending.h"
#include "TEntryList.h"
#include "AliLog.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliTreeTrending.h"
ClassImp(AliTreeTrending)
using std::cout;
using std::endl;
// constants
const Int_t kMaxCanvasWidth=3000;
const Int_t kMinCanvasWidth=1000;
const Int_t kStepCanvasWidth=500;
AliTreeTrending::AliTreeTrending():
TNamed(),
fTree(NULL),
fUserDescription(NULL),
fLatexDescription(NULL),
fStatusGraph(NULL)
{
}
//_____________________________________________________________________________
AliTreeTrending::AliTreeTrending(const char *name, const char *title):
TNamed(name, title),
fTree(NULL),
fUserDescription(NULL),
fLatexDescription(NULL),
fStatusGraph(NULL)
{
//
//
}
TObjArray * AliTreeTrending::GetTexDescription(TLatex *latex){
//
// Get latex version of description
//
TObjArray * description= new TObjArray();
TString sTimestamp = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
TString sAlirootVer;
TString sAliphysicsVer;
if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
}else {
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
}
if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
}else {
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
}
//
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
if (fUserDescription!=NULL){
Int_t entries=fUserDescription->GetEntries();
for (Int_t i=0; i<entries; i++){
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-((6+i)*1.1)*latex->GetTextSize(),
TString::Format("%s: %s",fUserDescription->At(i)->GetName(), fUserDescription->At(i)->GetTitle()).Data()));
}
}
return description;
}
void AliTreeTrending::AddUserDescription(TNamed * description){
//
// Add user description
// AliTreeTrending is owner
//
if (fUserDescription==NULL) fUserDescription = new TObjArray;
fUserDescription->AddLast(description);
}
Bool_t AliTreeTrending::InitSummaryTrending(TString statusDescription[3], Float_t descriptionSize){
//
// Init drawing for the <detector> QA
// Detector specific qaConfig() has to be called before invoking this function
// 0.) Make descriptor
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
// 3.) compute detector status graphs
//
// 0.) Make descriptor
//
if (fTree==NULL) {
AliError("Input tree not defined");
return 0;
}
if (fTree->GetAlias("tagID")==NULL && fTree->GetBranch("tagID")==NULL) {
AliError("tagID is not defined");
return 0;
}
TLatex *latex= new TLatex;
latex->SetX(0.11);
latex->SetY(0.8);
latex->SetTextSize(descriptionSize);
fLatexDescription = GetTexDescription(latex);
//
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
//
TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(fTree,"tagID:tagID","");
Int_t numberOfTags = gr->GetN();
cout<<"number of graph entries: "<<numberOfTags<<endl;
double SpaceForLegend = 0.;
Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;
Int_t canvas_height = 600;
if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;
if ( canvas_width<kMinCanvasWidth) canvas_width=kMinCanvasWidth;
fWorkingCanvas = new TCanvas("fWorkingCanvas","fWorkingCanvas",canvas_width,canvas_height);
fWorkingCanvas->SetGrid(3);
fWorkingCanvas->cd();
gPad->SetTicks(1,2);
// fWorkingCanvas->SetRightMargin(SpaceForLegend/canvas_width);
double leftlegend = 1 - 180./fWorkingCanvas->GetWw();
double rightlegend = 1 - 10./fWorkingCanvas->GetWw();
//
// 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
//
TString sStatusbarVars = statusDescription[0];
TString sStatusbarNames = statusDescription[1];
TString sCriteria = statusDescription[2];
cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
cout << "sCriteria = " << sCriteria.Data() << endl;
//
// 3.) compute detector status graphs
//
TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
fStatusGraph = new TObjArray();
int igr=0;
for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
fStatusGraph->Add( TStatToolkit::MakeStatusMultGr(fTree, sVar.Data(), "", sCriteria.Data(), igr) );
TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
((TMultiGraph*) fStatusGraph->At(igr))->SetTitle(sYtitle.Data());
igr++;
}
return kTRUE;
}
void AliTreeTrending::SetDefaultStyle(){
//
// ??? Who is owner of drawing style ???
//
//
gROOT->SetStyle("Plain");
gStyle->SetPalette(1);
gStyle->SetLabelSize(0.04,"x");
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
void AliTreeTrending::AppendStatusPad(Float_t padratio, Float_t bottomMargin, Float_t rightMargin){
//
// Add status pad and latex description to the canvas (can be pad?)
// status pad and latex description using data mbers of trendingDraw class
//
// 1.) Split canvase
// 2.) Draw status bar in lower part of canvas
//
if (fLatexDescription==NULL){
AliError("LatexDescription not initialized. Run AliTreeTrending::InitSummaryTrending");
return;
}
TCanvas *c1 = fWorkingCanvas;
c1->cd();
fLatexDescription->DrawClone();
//
// 1.) Split canvas
//
TCanvas* c1_clone = (TCanvas*) c1->Clone("c1_clone");
c1->Clear();
// produce new pads
c1->cd();
TPad* pad1 = new TPad("pad1", "pad1", 0., padratio, 1., 1.);
pad1->Draw();
pad1->SetNumber(1); // so it can be called via "c1->cd(1);"
c1->cd();
TPad* pad2 = new TPad("pad2", "pad2", 0., 0., 1., padratio);
pad2->Draw();
pad2->SetNumber(2);
// draw original canvas into first pad
c1->cd(1);
c1_clone->DrawClonePad();
pad1->SetBottomMargin(0.001);
pad1->SetRightMargin(rightMargin);
// set up second pad
c1->cd(2);
pad2->SetGrid(3);
pad2->SetTopMargin(0);
pad2->SetBottomMargin(bottomMargin); // for the long x-axis labels (runnumbers)
pad2->SetRightMargin(rightMargin);
//
//
const Int_t nvars = fStatusGraph->GetEntriesFast();
TGraph* grAxis = (TGraph*) ((TMultiGraph*) fStatusGraph->At(0))->GetListOfGraphs()->At(0);
grAxis->SetMaximum(0.5*nvars+0.5);
grAxis->SetMinimum(0);
grAxis->GetYaxis()->SetLabelSize(0);
grAxis->GetYaxis()->SetTitle("");
grAxis->SetTitle("");
Int_t entries = grAxis->GetN();
grAxis->GetXaxis()->SetLabelSize(5.7*TMath::Min(TMath::Max(5./entries,0.01),0.03));
grAxis->GetXaxis()->LabelsOption("v");
grAxis->Draw("ap");
//
// draw multigraphs & names of status variables on the y axis
for (Int_t i=0; i<nvars; i++){
((TMultiGraph*) fStatusGraph->At(i))->Draw("p");
TLatex* ylabel = new TLatex(-0.1, 0.5*i+0.5, ((TMultiGraph*) fStatusGraph->At(i))->GetTitle());
ylabel->SetTextAlign(32); //hor:right & vert:centered
ylabel->SetTextSize(0.025/gPad->GetHNDC());
ylabel->Draw();
}
c1->cd(1)->Draw();
}
<commit_msg>ATO-46, ATO-83 - +using std::cout; Needed in ROOT6<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
.L $ALICE_ROOT/../src/STAT/AliTreeTrending.cxx+
*/
#include "TStatToolkit.h"
#include "Riostream.h"
#include <iostream>
#include "TSystem.h"
#include "TNamed.h"
#include "TFile.h"
#include "TTree.h"
#include "TPRegexp.h"
#include "TFriendElement.h"
#include "AliExternalInfo.h"
#include "TTreeFormula.h"
#include "TTreeFormulaManager.h"
#include "AliTreeTrending.h"
#include "TEntryList.h"
#include "AliLog.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliTreeTrending.h"
using std::cout;
using std::cerr;
using std::endl;
ClassImp(AliTreeTrending)
using std::cout;
using std::endl;
// constants
const Int_t kMaxCanvasWidth=3000;
const Int_t kMinCanvasWidth=1000;
const Int_t kStepCanvasWidth=500;
AliTreeTrending::AliTreeTrending():
TNamed(),
fTree(NULL),
fUserDescription(NULL),
fLatexDescription(NULL),
fStatusGraph(NULL)
{
}
//_____________________________________________________________________________
AliTreeTrending::AliTreeTrending(const char *name, const char *title):
TNamed(name, title),
fTree(NULL),
fUserDescription(NULL),
fLatexDescription(NULL),
fStatusGraph(NULL)
{
//
//
}
TObjArray * AliTreeTrending::GetTexDescription(TLatex *latex){
//
// Get latex version of description
//
TObjArray * description= new TObjArray();
TString sTimestamp = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
TString sAlirootVer;
TString sAliphysicsVer;
if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
}else {
sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
}
if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
}else {
sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
}
//
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
if (fUserDescription!=NULL){
Int_t entries=fUserDescription->GetEntries();
for (Int_t i=0; i<entries; i++){
description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-((6+i)*1.1)*latex->GetTextSize(),
TString::Format("%s: %s",fUserDescription->At(i)->GetName(), fUserDescription->At(i)->GetTitle()).Data()));
}
}
return description;
}
void AliTreeTrending::AddUserDescription(TNamed * description){
//
// Add user description
// AliTreeTrending is owner
//
if (fUserDescription==NULL) fUserDescription = new TObjArray;
fUserDescription->AddLast(description);
}
Bool_t AliTreeTrending::InitSummaryTrending(TString statusDescription[3], Float_t descriptionSize){
//
// Init drawing for the <detector> QA
// Detector specific qaConfig() has to be called before invoking this function
// 0.) Make descriptor
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
// 3.) compute detector status graphs
//
// 0.) Make descriptor
//
if (fTree==NULL) {
AliError("Input tree not defined");
return 0;
}
if (fTree->GetAlias("tagID")==NULL && fTree->GetBranch("tagID")==NULL) {
AliError("tagID is not defined");
return 0;
}
TLatex *latex= new TLatex;
latex->SetX(0.11);
latex->SetY(0.8);
latex->SetTextSize(descriptionSize);
fLatexDescription = GetTexDescription(latex);
//
// 1.) Make default canvas - addopt canvas width to the number of entries to draw
//
TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(fTree,"tagID:tagID","");
Int_t numberOfTags = gr->GetN();
cout<<"number of graph entries: "<<numberOfTags<<endl;
double SpaceForLegend = 0.;
Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;
Int_t canvas_height = 600;
if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;
if ( canvas_width<kMinCanvasWidth) canvas_width=kMinCanvasWidth;
fWorkingCanvas = new TCanvas("fWorkingCanvas","fWorkingCanvas",canvas_width,canvas_height);
fWorkingCanvas->SetGrid(3);
fWorkingCanvas->cd();
gPad->SetTicks(1,2);
// fWorkingCanvas->SetRightMargin(SpaceForLegend/canvas_width);
double leftlegend = 1 - 180./fWorkingCanvas->GetWw();
double rightlegend = 1 - 10./fWorkingCanvas->GetWw();
//
// 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
//
TString sStatusbarVars = statusDescription[0];
TString sStatusbarNames = statusDescription[1];
TString sCriteria = statusDescription[2];
cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
cout << "sCriteria = " << sCriteria.Data() << endl;
//
// 3.) compute detector status graphs
//
TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
fStatusGraph = new TObjArray();
int igr=0;
for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
fStatusGraph->Add( TStatToolkit::MakeStatusMultGr(fTree, sVar.Data(), "", sCriteria.Data(), igr) );
TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
((TMultiGraph*) fStatusGraph->At(igr))->SetTitle(sYtitle.Data());
igr++;
}
return kTRUE;
}
void AliTreeTrending::SetDefaultStyle(){
//
// ??? Who is owner of drawing style ???
//
//
gROOT->SetStyle("Plain");
gStyle->SetPalette(1);
gStyle->SetLabelSize(0.04,"x");
gStyle->SetPadTickX(1);
gStyle->SetPadTickY(1);
}
void AliTreeTrending::AppendStatusPad(Float_t padratio, Float_t bottomMargin, Float_t rightMargin){
//
// Add status pad and latex description to the canvas (can be pad?)
// status pad and latex description using data mbers of trendingDraw class
//
// 1.) Split canvase
// 2.) Draw status bar in lower part of canvas
//
if (fLatexDescription==NULL){
AliError("LatexDescription not initialized. Run AliTreeTrending::InitSummaryTrending");
return;
}
TCanvas *c1 = fWorkingCanvas;
c1->cd();
fLatexDescription->DrawClone();
//
// 1.) Split canvas
//
TCanvas* c1_clone = (TCanvas*) c1->Clone("c1_clone");
c1->Clear();
// produce new pads
c1->cd();
TPad* pad1 = new TPad("pad1", "pad1", 0., padratio, 1., 1.);
pad1->Draw();
pad1->SetNumber(1); // so it can be called via "c1->cd(1);"
c1->cd();
TPad* pad2 = new TPad("pad2", "pad2", 0., 0., 1., padratio);
pad2->Draw();
pad2->SetNumber(2);
// draw original canvas into first pad
c1->cd(1);
c1_clone->DrawClonePad();
pad1->SetBottomMargin(0.001);
pad1->SetRightMargin(rightMargin);
// set up second pad
c1->cd(2);
pad2->SetGrid(3);
pad2->SetTopMargin(0);
pad2->SetBottomMargin(bottomMargin); // for the long x-axis labels (runnumbers)
pad2->SetRightMargin(rightMargin);
//
//
const Int_t nvars = fStatusGraph->GetEntriesFast();
TGraph* grAxis = (TGraph*) ((TMultiGraph*) fStatusGraph->At(0))->GetListOfGraphs()->At(0);
grAxis->SetMaximum(0.5*nvars+0.5);
grAxis->SetMinimum(0);
grAxis->GetYaxis()->SetLabelSize(0);
grAxis->GetYaxis()->SetTitle("");
grAxis->SetTitle("");
Int_t entries = grAxis->GetN();
grAxis->GetXaxis()->SetLabelSize(5.7*TMath::Min(TMath::Max(5./entries,0.01),0.03));
grAxis->GetXaxis()->LabelsOption("v");
grAxis->Draw("ap");
//
// draw multigraphs & names of status variables on the y axis
for (Int_t i=0; i<nvars; i++){
((TMultiGraph*) fStatusGraph->At(i))->Draw("p");
TLatex* ylabel = new TLatex(-0.1, 0.5*i+0.5, ((TMultiGraph*) fStatusGraph->At(i))->GetTitle());
ylabel->SetTextAlign(32); //hor:right & vert:centered
ylabel->SetTextSize(0.025/gPad->GetHNDC());
ylabel->Draw();
}
c1->cd(1)->Draw();
}
<|endoftext|>
|
<commit_before>//******************************************************************
//
// Copyright 2015 Samsung Electronics 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 <PrimitiveResource.h>
#include <ResourceAttributes.h>
#include <ResponseStatement.h>
#include <internal/ResourceAtrributesConverter.h>
#include <OCPlatform.h>
using OC::QueryParamsMap;
using OC::OCRepresentation;
using OC::ObserveType;
using std::bind;
using std::shared_ptr;
using std::vector;
using std::string;
using namespace std::placeholders;
namespace
{
using namespace OIC::Service;
ResponseStatement createResponseStatement(const OCRepresentation& ocRepresentation)
{
return ResponseStatement::create(
ResourceAttributesConverter::fromOCRepresentation(ocRepresentation));
}
} // unnamed namespace
namespace OIC
{
namespace Service
{
PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) :
m_ocResource{ ocResource }
{
}
PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr)
{
return std::shared_ptr< PrimitiveResource >(new PrimitiveResource{ ptr });
}
void PrimitiveResource::requestGet(GetCallback callback)
{
m_ocResource->get(QueryParamsMap(), bind(callback, _1, bind(createResponseStatement, _2), _3));
}
void PrimitiveResource::requestSet(const ResourceAttributes& attrs, SetCallback callback)
{
m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs), QueryParamsMap{},
bind(callback, _1, bind(createResponseStatement, _2), _3));
}
void PrimitiveResource::requestObserve(ObserveCallback callback)
{
m_ocResource->observe(ObserveType::ObserveAll, QueryParamsMap{},
bind(callback, _1, bind(createResponseStatement, _2), _3, _4));
}
void PrimitiveResource::cancelObserve()
{
m_ocResource->cancelObserve();
}
bool PrimitiveResource::isObservable() const
{
return m_ocResource->isObservable();
}
string PrimitiveResource::getUri() const
{
return m_ocResource->uri();
}
string PrimitiveResource::getHost() const
{
return m_ocResource->host();
}
vector< string > PrimitiveResource::getTypes() const
{
return m_ocResource->getResourceTypes();
}
vector< string > PrimitiveResource::getInterfaces() const
{
return m_ocResource->getResourceInterfaces();
}
void discoverResource(const std::string& host, const std::string& resourceURI,
OCConnectivityType connectivityType, FindCallback resourceHandler)
{
OC::OCPlatform::findResource(host, resourceURI, connectivityType,
std::bind(&PrimitiveResource::create, std::placeholders::_1));
}
}
}
<commit_msg>Remove unnecessary using-declarations from PrimitiveResource<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics 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 <PrimitiveResource.h>
#include <ResourceAttributes.h>
#include <ResponseStatement.h>
#include <internal/ResourceAtrributesConverter.h>
#include <OCPlatform.h>
namespace
{
using namespace OIC::Service;
ResponseStatement createResponseStatement(const OC::OCRepresentation& ocRepresentation)
{
return ResponseStatement::create(
ResourceAttributesConverter::fromOCRepresentation(ocRepresentation));
}
} // unnamed namespace
namespace OIC
{
namespace Service
{
using namespace std::placeholders;
PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) :
m_ocResource{ ocResource }
{
}
PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr)
{
return std::shared_ptr< PrimitiveResource >(new PrimitiveResource{ ptr });
}
void PrimitiveResource::requestGet(GetCallback callback)
{
m_ocResource->get(OC::QueryParamsMap(),
std::bind(callback, _1, std::bind(createResponseStatement, _2), _3));
}
void PrimitiveResource::requestSet(const ResourceAttributes& attrs, SetCallback callback)
{
m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs),
OC::QueryParamsMap{},
std::bind(callback, _1, std::bind(createResponseStatement, _2), _3));
}
void PrimitiveResource::requestObserve(ObserveCallback callback)
{
m_ocResource->observe(OC::ObserveType::ObserveAll, OC::QueryParamsMap{},
bind(callback, _1, bind(createResponseStatement, _2), _3, _4));
}
void PrimitiveResource::cancelObserve()
{
m_ocResource->cancelObserve();
}
bool PrimitiveResource::isObservable() const
{
return m_ocResource->isObservable();
}
std::string PrimitiveResource::getUri() const
{
return m_ocResource->uri();
}
std::string PrimitiveResource::getHost() const
{
return m_ocResource->host();
}
std::vector< std::string > PrimitiveResource::getTypes() const
{
return m_ocResource->getResourceTypes();
}
std::vector< std::string > PrimitiveResource::getInterfaces() const
{
return m_ocResource->getResourceInterfaces();
}
void discoverResource(const std::string& host, const std::string& resourceURI,
OCConnectivityType connectivityType, FindCallback resourceHandler)
{
OC::OCPlatform::findResource(host, resourceURI, connectivityType,
std::bind(&PrimitiveResource::create, std::placeholders::_1));
}
}
}
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/random/rdrand.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_RDRAND_HPP
#define MCKL_RANDOM_RDRAND_HPP
#include <mckl/random/internal/common.hpp>
#include <immintrin.h>
#ifndef MCKL_RDRAND_NTRIAL_MAX
#define MCKL_RDRAND_NTRIAL_MAX 0
#endif
namespace mckl
{
/// \brief Invoke the RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType, std::size_t W>
inline bool rdrand(UIntType *, std::integral_constant<int, W>);
/// \brief Invoke the 16-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 16>)
{
unsigned short r;
int cf = _rdrand16_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief Invoke the 32-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 32>)
{
unsigned r;
int cf = _rdrand32_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief Invoke the 64-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 64>)
{
#if defined(MCKL_MSVC) || (defined(MCKL_INTEL) && MCKL_INTEL_VERSION < 1600)
unsigned __int64 r;
#else
unsigned long long r;
#endif
int cf = _rdrand64_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief RDRAND generator
/// \ingroup RDRAND
template <typename ResultType, std::size_t NTrialMax = MCKL_RDRAND_NTRIAL_MAX>
class RDRANDEngine
{
static_assert(std::is_unsigned<ResultType>::value,
"**RDRANDEngine** used with ResultType other than unsigned integer "
"types");
static_assert(std::numeric_limits<ResultType>::digits == 16 ||
std::numeric_limits<ResultType>::digits == 32 ||
std::numeric_limits<ResultType>::digits == 64,
"**RDRANDEngine** used with ResultType of size other than 16, 32 or "
"64 bits");
public:
using result_type = ResultType;
template <typename Seed>
explicit RDRANDEngine(const Seed &)
{
}
template <typename Seed>
void seed(const Seed &)
{
}
result_type operator()()
{
return generate(std::integral_constant<bool, NTrialMax != 0>());
}
void discard(std::size_t) {}
static constexpr result_type min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type max()
{
return std::numeric_limits<result_type>::max();
}
friend bool operator==(const RDRANDEngine<ResultType, NTrialMax> &,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return false;
}
friend bool operator!=(const RDRANDEngine<ResultType, NTrialMax> &,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return true;
}
template <typename CharT, typename CharTraits>
friend std::basic_ostream<CharT, CharTraits> &operator<<(
std::basic_ostream<CharT, CharTraits> &os,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return os;
}
template <typename CharT, typename CharTraits>
friend std::basic_istream<CharT, CharTraits> &operator>>(
std::basic_istream<CharT, CharTraits> &is,
RDRANDEngine<ResultType, NTrialMax> &)
{
return is;
}
private:
result_type generate(std::true_type)
{
result_type r;
std::size_t ntrial = 0;
while (true) {
++ntrial;
bool success = rdrand<result_type>(
&r, std::integral_constant<int,
std::numeric_limits<result_type>::digits>());
if (success || ntrial > NTrialMax)
break;
}
runtime_assert(ntrial < NTrialMax,
"**RDRAND::generator** maximum number of trials exceeded", true);
return r;
}
result_type generate(std::false_type)
{
result_type r;
while (true) {
bool success = rdrand<result_type>(
&r, std::integral_constant<int,
std::numeric_limits<result_type>::digits>());
if (success)
break;
}
return r;
}
}; // class RDRANDEngine
/// \brief C++11 Engine using 16-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND16 = RDRANDEngine<std::uint16_t>;
/// \brief C++11 Engine using 32-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND32 = RDRANDEngine<std::uint32_t>;
/// \brief C++11 Engine using 64-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND64 = RDRANDEngine<std::uint64_t>;
} // namespace mckl
#endif // MCKL_RANDOM_RDRAND_HPP
<commit_msg>fix rdrand default seed<commit_after>//============================================================================
// MCKL/include/mckl/random/rdrand.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_RANDOM_RDRAND_HPP
#define MCKL_RANDOM_RDRAND_HPP
#include <mckl/random/internal/common.hpp>
#include <immintrin.h>
#ifndef MCKL_RDRAND_NTRIAL_MAX
#define MCKL_RDRAND_NTRIAL_MAX 0
#endif
namespace mckl
{
/// \brief Invoke the RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType, std::size_t W>
inline bool rdrand(UIntType *, std::integral_constant<int, W>);
/// \brief Invoke the 16-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 16>)
{
unsigned short r;
int cf = _rdrand16_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief Invoke the 32-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 32>)
{
unsigned r;
int cf = _rdrand32_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief Invoke the 64-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 64>)
{
#if defined(MCKL_MSVC) || (defined(MCKL_INTEL) && MCKL_INTEL_VERSION < 1600)
unsigned __int64 r;
#else
unsigned long long r;
#endif
int cf = _rdrand64_step(&r);
*rand = static_cast<UIntType>(r);
return cf != 0;
}
/// \brief RDRAND generator
/// \ingroup RDRAND
template <typename ResultType, std::size_t NTrialMax = MCKL_RDRAND_NTRIAL_MAX>
class RDRANDEngine
{
static_assert(std::is_unsigned<ResultType>::value,
"**RDRANDEngine** used with ResultType other than unsigned integer "
"types");
static_assert(std::numeric_limits<ResultType>::digits == 16 ||
std::numeric_limits<ResultType>::digits == 32 ||
std::numeric_limits<ResultType>::digits == 64,
"**RDRANDEngine** used with ResultType of size other than 16, 32 or "
"64 bits");
public:
using result_type = ResultType;
RDRANDEngine() {}
template <typename Seed>
explicit RDRANDEngine(const Seed &)
{
}
template <typename Seed>
void seed(const Seed &)
{
}
result_type operator()()
{
return generate(std::integral_constant<bool, NTrialMax != 0>());
}
void discard(std::size_t) {}
static constexpr result_type min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type max()
{
return std::numeric_limits<result_type>::max();
}
friend bool operator==(const RDRANDEngine<ResultType, NTrialMax> &,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return false;
}
friend bool operator!=(const RDRANDEngine<ResultType, NTrialMax> &,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return true;
}
template <typename CharT, typename CharTraits>
friend std::basic_ostream<CharT, CharTraits> &operator<<(
std::basic_ostream<CharT, CharTraits> &os,
const RDRANDEngine<ResultType, NTrialMax> &)
{
return os;
}
template <typename CharT, typename CharTraits>
friend std::basic_istream<CharT, CharTraits> &operator>>(
std::basic_istream<CharT, CharTraits> &is,
RDRANDEngine<ResultType, NTrialMax> &)
{
return is;
}
private:
result_type generate(std::true_type)
{
result_type r;
std::size_t ntrial = 0;
while (true) {
++ntrial;
bool success = rdrand<result_type>(
&r, std::integral_constant<int,
std::numeric_limits<result_type>::digits>());
if (success || ntrial > NTrialMax)
break;
}
runtime_assert(ntrial < NTrialMax,
"**RDRAND::generator** maximum number of trials exceeded", true);
return r;
}
result_type generate(std::false_type)
{
result_type r;
while (true) {
bool success = rdrand<result_type>(
&r, std::integral_constant<int,
std::numeric_limits<result_type>::digits>());
if (success)
break;
}
return r;
}
}; // class RDRANDEngine
/// \brief C++11 Engine using 16-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND16 = RDRANDEngine<std::uint16_t>;
/// \brief C++11 Engine using 32-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND32 = RDRANDEngine<std::uint32_t>;
/// \brief C++11 Engine using 64-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND64 = RDRANDEngine<std::uint64_t>;
} // namespace mckl
#endif // MCKL_RANDOM_RDRAND_HPP
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <type_traits>
#include <string>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = (TargetType)src.get<SourceType>();
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
return std::to_string(value.get<T>());
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any& value)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string& str_value)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any& value)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any& value)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
<commit_msg>Add pointer to function signature dereference_signature. modified: include/reflection_binding.hpp<commit_after>#pragma once
#include <utility>
#include <type_traits>
#include <string>
#include "any.hpp"
#include <type_list.hpp>
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = (TargetType)src.get<SourceType>();
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
return std::to_string(value.get<T>());
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any& value)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string& str_value)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any& value)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any& value)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
<|endoftext|>
|
<commit_before>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP
#include <string>
#include <type_traits>
#include <utility>
#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = static_cast<TargetType>(src.get<SourceType>());
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
return std::to_string(value.get<T>());
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any& value)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string& str_value)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any& value)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any& value)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
#endif
<commit_msg>Remove name of unused parameter. modified: include/reflection_binding.hpp<commit_after>#ifndef REFLECTION_BINDING_HPP
#define REFLECTION_BINDING_HPP
#include <string>
#include <type_traits>
#include <utility>
#include "any.hpp"
#include <function_deduction.hpp>
#include <member_variable_deduction.hpp>
#include <type_list.hpp>
#include <void_t.hpp>
namespace shadow
{
// free function signature
typedef any (*free_function_binding_signature)(any*);
// member function signature
typedef any (*member_function_binding_signature)(any&, any*);
// member variable getter
typedef any (*member_variable_get_binding_signature)(const any&);
// member variable setter
typedef void (*member_variable_set_binding_signature)(any&, const any&);
// constructor signature
typedef any (*constructor_binding_signature)(any*);
// conversion signature
typedef any (*conversion_binding_signature)(const any&);
// string serialize signature
typedef std::string (*string_serialization_signature)(const any&);
// string deserialization signature
typedef any (*string_deserialization_signature)(const std::string&);
// address of signature
typedef any (*address_of_signature)(any&);
// dereference signature
typedef any (*dereference_signature)(any&);
////////////////////////////////////////////////////////////////////////////////
// generic bind point for free functions
// has the same signature as function pointer free_function_binding_signature
// which can be stored in the free_function_info struct
namespace free_function_detail
{
// necessary to handle void as return type differently when calling underlying
// free function
template <class ReturnType>
struct return_type_specializer
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
return FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
// dispatch: unpacks argument type list and sequence to correctly index into
// argument array and call get with the right types to retrieve raw values
// from the anys
template <class FunctionPointerType,
FunctionPointerType FunctionPointerValue,
class... ArgTypes,
std::size_t... ArgSeq>
static any
dispatch(any* argument_array,
metamusil::t_list::type_list<ArgTypes...>,
std::index_sequence<ArgSeq...>)
{
// necessary to remove reference from types as any only stores
// unqualified types, ie values only
FunctionPointerValue(
argument_array[ArgSeq]
.get<typename std::remove_reference_t<ArgTypes>>()...);
// return empty any, ie 'void'
return any();
}
};
// the value of the function pointer is stored at runtime in the template
// overload set
// this enables any function to be wrapped into uniform function signature that
// can be stored homogenously at runtime
template <class FunctionPointerType, FunctionPointerType FunctionPointerValue>
any
generic_free_function_bind_point(any* argument_array)
{
typedef metamusil::deduce_return_type_t<FunctionPointerType> return_type;
typedef metamusil::deduce_parameter_types_t<FunctionPointerType>
parameter_types;
// make integer sequence from type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
return return_type_specializer<return_type>::
template dispatch<FunctionPointerType, FunctionPointerValue>(
argument_array, parameter_types(), parameter_sequence());
}
} // namespace free_function_detail
namespace member_function_detail
{
template <class ReturnType>
struct return_type_specializer
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
return (object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
}
};
template <>
struct return_type_specializer<void>
{
template <class MemFunPointerType,
MemFunPointerType MemFunPointerValue,
class ObjectType,
class... ParamTypes,
std::size_t... ParamSequence>
static any
dispatch(any& object,
any* argument_array,
metamusil::t_list::type_list<ParamTypes...>,
std::index_sequence<ParamSequence...>)
{
(object.get<ObjectType>().*MemFunPointerValue)(
argument_array[ParamSequence]
.get<std::remove_reference_t<ParamTypes>>()...);
return any();
}
};
template <class MemFunPointerType, MemFunPointerType MemFunPointerValue>
any
generic_member_function_bind_point(any& object, any* argument_array)
{
// deduce return type
typedef metamusil::deduce_return_type_t<MemFunPointerType> return_type;
// deduce parameter types
typedef metamusil::deduce_parameter_types_t<MemFunPointerType>
parameter_types;
// make integer sequence from parameter type list
typedef metamusil::t_list::index_sequence_for_t<parameter_types>
parameter_sequence;
// deduce object type
typedef metamusil::deduce_object_type_t<MemFunPointerType> object_type;
return return_type_specializer<return_type>::
template dispatch<MemFunPointerType, MemFunPointerValue, object_type>(
object, argument_array, parameter_types(), parameter_sequence());
}
} // namespace member_function_detail
namespace member_variable_detail
{
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
any
get_dispatch(const any& object)
{
return (object.get<ObjectType>().*MemVarPointerValue);
}
template <class MemVarPointerType,
MemVarPointerType MemVarPointerValue,
class ObjectType,
class MemVarType>
void
set_dispatch(any& object, const any& value)
{
(object.get<ObjectType>().*MemVarPointerValue) = value.get<MemVarType>();
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
any
generic_member_variable_get_bind_point(const any& object)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return get_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object);
}
template <class MemVarPointerType, MemVarPointerType MemVarPointerValue>
void
generic_member_variable_set_bind_point(any& object, const any& value)
{
typedef metamusil::deduce_member_variable_object_type_t<MemVarPointerType>
object_type;
typedef metamusil::deduce_member_variable_type_t<MemVarPointerType>
member_variable_type;
return set_dispatch<MemVarPointerType,
MemVarPointerValue,
object_type,
member_variable_type>(object, value);
}
} // namespace member_variable_detail
namespace constructor_detail
{
// purpose of braced_init_selector is to attempt to use constructor T(...) if
// available, otherwise fall back to braced init list initialization
template <class, class T, class... ParamTypes>
struct braced_init_selector_impl
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T{argument_array[Seq].get<ParamTypes>()...};
return out;
}
};
template <class T, class... ParamTypes>
struct braced_init_selector_impl<
metamusil::void_t<decltype(T(std::declval<ParamTypes>()...))>,
T,
ParamTypes...>
{
template <std::size_t... Seq>
static any
constructor_dispatch(any* argument_array, std::index_sequence<Seq...>)
{
any out = T(argument_array[Seq].get<ParamTypes>()...);
return out;
}
};
template <class T, class... ParamTypes>
using braced_init_selector = braced_init_selector_impl<void, T, ParamTypes...>;
template <class T, class... ParamTypes>
any
generic_constructor_bind_point(any* argument_array)
{
typedef std::index_sequence_for<ParamTypes...> param_sequence;
return braced_init_selector<T, ParamTypes...>::constructor_dispatch(
argument_array, param_sequence());
}
} // namespace constructor_detail
namespace conversion_detail
{
template <class TargetType, class SourceType, class = void>
struct conversion_specializer;
template <>
struct conversion_specializer<void, void>;
template <class TargetType, class SourceType>
struct conversion_specializer<
TargetType,
SourceType,
std::enable_if_t<std::is_convertible<SourceType, TargetType>::value>>
{
static any
dispatch(const any& src)
{
TargetType temp = static_cast<TargetType>(src.get<SourceType>());
return temp;
}
};
template <class TargetType, class SourceType>
any
generic_conversion_bind_point(const any& src)
{
return conversion_specializer<TargetType, SourceType>::dispatch(src);
}
} // namespace conversion_detail
namespace string_serialization_detail
{
template <class T, class = void>
struct string_serialize_type_selector;
template <class T>
struct string_serialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static std::string
dispatch(const any& value)
{
return std::to_string(value.get<T>());
}
};
template <>
struct string_serialize_type_selector<std::string>
{
static std::string
dispatch(const any& value)
{
return value.get<std::string>();
}
};
template <>
struct string_serialize_type_selector<char>
{
static std::string
dispatch(const any& value)
{
std::string out;
out.push_back(value.get<char>());
return out;
}
};
template <>
struct string_serialize_type_selector<void>
{
static std::string
dispatch(const any&)
{
return "empty";
}
};
template <class T>
std::string
generic_string_serialization_bind_point(const any& value)
{
return string_serialize_type_selector<T>::dispatch(value);
}
template <class T, class = void>
struct string_deserialize_type_selector;
template <class T>
struct string_deserialize_type_selector<
T,
std::enable_if_t<std::is_arithmetic<T>::value>>
{
static any
dispatch(const std::string& str_value)
{
T out = std::stold(str_value);
return out;
}
};
template <>
struct string_deserialize_type_selector<char>
{
static any
dispatch(const std::string& str_value)
{
return str_value[0];
}
};
template <>
struct string_deserialize_type_selector<std::string>
{
static any
dispatch(const std::string& str_value)
{
return str_value;
}
};
template <>
struct string_deserialize_type_selector<int>
{
static any
dispatch(const std::string& str_value)
{
return std::stoi(str_value);
}
};
template <>
struct string_deserialize_type_selector<long>
{
static any
dispatch(const std::string& str_value)
{
return std::stol(str_value);
}
};
template <>
struct string_deserialize_type_selector<long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoll(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoul(str_value);
}
};
template <>
struct string_deserialize_type_selector<unsigned long long>
{
static any
dispatch(const std::string& str_value)
{
return std::stoull(str_value);
}
};
template <>
struct string_deserialize_type_selector<float>
{
static any
dispatch(const std::string& str_value)
{
return std::stof(str_value);
}
};
template <>
struct string_deserialize_type_selector<double>
{
static any
dispatch(const std::string& str_value)
{
return std::stod(str_value);
}
};
template <>
struct string_deserialize_type_selector<long double>
{
static any
dispatch(const std::string& str_value)
{
return std::stold(str_value);
}
};
template <>
struct string_deserialize_type_selector<void>
{
static any
dispatch(const std::string&)
{
return shadow::any();
}
};
template <class T>
any
generic_string_deserialization_bind_point(const std::string& str_value)
{
return string_deserialize_type_selector<T>::dispatch(str_value);
}
} // namespace string_serialization_detail
namespace pointer_detail
{
template <class T>
inline any
generic_address_of_bind_point(any& value)
{
return any(&(value.get<T>()));
}
template <>
inline any
generic_address_of_bind_point<void>(any&)
{
return any(nullptr);
}
template <class T>
inline any
generic_dereference_bind_point(any& value)
{
return any(*(value.get<T*>()));
}
template <>
inline any
generic_dereference_bind_point<void>(any&)
{
return any();
}
} // namespace pointer_detail
} // namespace shadow
#endif
<|endoftext|>
|
<commit_before>// FileSections.cpp
/*
* (C) Copyright 2015 Noah Roth
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "stdafx.hpp"
#include "FileSections.hpp"
using namespace RCT3Asset;
DataEntry::DataEntry() : Size(0), Offset(0), Data(nullptr)
{
}
DataSection::DataSection() : Offset(0)
{
}
DataEntry& DataSection::CreateAndAdd(unsigned int size, RCT3Debugging::OutputLog& log)
{
DataEntry entry;
entry.Size = size;
entry.Offset = 0;
entry.Data = nullptr;
if (size)
entry.Data = new unsigned char[size]();
Entries.push_back(entry);
return Entries.back();
}
DataEntry& DataSection::CreateAndInsert(unsigned int size, RCT3Debugging::OutputLog& log)
{
DataEntry entry;
entry.Data = nullptr;
entry.Size = size;
entry.Offset = 0;
if (size)
entry.Data = new unsigned char[size]();
Entries.insert(Entries.begin(), entry);
return Entries.front();
}
DataSection& FileSections::Get(unsigned int index)
{
if (index < 9)
return _sections[index];
return _sections[8];
}
DataSection& FileSections::operator[](unsigned int index)
{
return Get(index);
}
unsigned int FileSections::UpdateOffsets(unsigned int startingOffset, RCT3Debugging::OutputLog& log)
{
unsigned int currOffset = startingOffset;
for (unsigned int i = 0; i < 9; i++)
{
for (unsigned int j = 0; j < _sections[i].Entries.size(); j++)
{
_sections[i].Entries[j].Offset = currOffset;
currOffset += _sections[i].Entries[j].Size;
}
_sections[i].Offset = currOffset;
}
log.Debug("FileSections::UpdateOffsets(..): returned " + STR(currOffset));
return currOffset;
}<commit_msg>Relocated ExtraData, reinforcing RAII<commit_after>// FileSections.cpp
/*
* (C) Copyright 2015 Noah Roth
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
#include "stdafx.hpp"
#include "FileSections.hpp"
using namespace RCT3Asset;
ExtraData::ExtraData(unsigned int size, void* data)
: Size(size), Data(reinterpret_cast<unsigned char*>(data))
{
}
ExtraData::ExtraData()
: Size(0), Data(nullptr)
{
}
ExtraData::~ExtraData()
{
if (Data != nullptr)
{
delete[] Data;
}
}
DataEntry::DataEntry()
: Size(0), Offset(0), Data(nullptr)
{
}
DataEntry::~DataEntry()
{
if (Data != nullptr)
{
delete[] Data;
}
}
DataSection::DataSection()
: Offset(0)
{
}
DataEntry& DataSection::CreateAndAdd(unsigned int size, RCT3Debugging::OutputLog& log)
{
DataEntry entry;
entry.Size = size;
entry.Offset = 0;
entry.Data = nullptr;
if (size)
entry.Data = new unsigned char[size]();
Entries.push_back(entry);
return Entries.back();
}
DataEntry& DataSection::CreateAndInsert(unsigned int size, RCT3Debugging::OutputLog& log)
{
DataEntry entry;
entry.Data = nullptr;
entry.Size = size;
entry.Offset = 0;
if (size)
entry.Data = new unsigned char[size]();
Entries.insert(Entries.begin(), entry);
return Entries.front();
}
DataSection& FileSections::Get(unsigned int index)
{
if (index < 9)
return _sections[index];
return _sections[8];
}
DataSection& FileSections::operator[](unsigned int index)
{
return Get(index);
}
unsigned int FileSections::UpdateOffsets(unsigned int startingOffset, RCT3Debugging::OutputLog& log)
{
unsigned int currOffset = startingOffset;
for (unsigned int i = 0; i < 9; i++)
{
for (unsigned int j = 0; j < _sections[i].Entries.size(); j++)
{
_sections[i].Entries[j].Offset = currOffset;
currOffset += _sections[i].Entries[j].Size;
}
_sections[i].Offset = currOffset;
}
log.Debug("FileSections::UpdateOffsets(..): returned " + STR(currOffset));
return currOffset;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2dpolypolygoncutter.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX
#define _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX
//#ifndef _SAL_TYPES_H_
//#include <sal/types.h>
//#endif
//
//#ifndef _BGFX_POINT_B2DPOINT_HXX
//#include <basegfx/point/b2dpoint.hxx>
//#endif
//
//#ifndef _BGFX_RANGE_B2DRANGE_HXX
//#include <basegfx/range/b2drange.hxx>
//#endif
#include <basegfx/polygon/b2dpolypolygon.hxx>
//#include <vector>
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
namespace tools
{
// solve all crossovers in a polyPolygon. This re-layouts all contained polygons so that the
// result will contain only non-cutting polygons. For that reason, points will be added at
// crossover and touch points and the single Polygons may be re-combined. The orientations
// of the contained polygons in not changed but used as hints.
// If bSelfCrossovers is set, first all self-intersections of the contained polygons will be
// solved.
B2DPolyPolygon SolveCrossovers(const B2DPolyPolygon& rCandidate, bool bSelfCrossovers = true);
// version for single polygons. This is for solving self-intersections. Result will be free of
// crossovers. When result contains multiple polygons, it may be necessary to rearrange their
// orientations since holes may have been created (use correctOrientations eventually).
B2DPolyPolygon SolveCrossovers(const B2DPolygon& rCandidate);
// Neutral polygons will be stripped. Neutral polygons are ones who's orientation is
// neutral, so normally they have no volume -> just closed paths. A polygon with the same
// positive and negative oriented volume is also neutral, so this may not be wanted. It is
// safe to call with crossover-free polygons, though (that's where it's mostly used).
B2DPolyPolygon StripNeutralPolygons(const B2DPolyPolygon& rCandidate);
// Remove not necessary polygons. Works only correct with crossover-free polygons. For each
// polygon, the depth for the PolyPolygon is calculated. The orientation is used to identify holes.
// Start value for holes is -1, for polygons it's zero. Ech time a polygon is contained in another one,
// it's depth is increased when inside a polygon, decreased when inside a hole. The result is a depth
// which e.g. is -1 for holes outside everything, 1 for a polygon covered by another polygon and zero
// for e.g. holes in a polygon or polygons outside everythig else.
// In the 2nd step, all polygons with depth other than zero are removed. If bKeepAboveZero is used,
// all polygons < 1 are removed. The bKeepAboveZero mode is useful for clipping, e.g. just append
// one polygon to another and use this mode -> only parts where two polygons overlapped will be kept.
// In combination with correct orientation of the input orientations and the SolveCrossover calls this
// can be combined for logical polygon operations or polygon clipping.
B2DPolyPolygon StripDispensablePolygons(const B2DPolyPolygon& rCandidate, bool bKeepAboveZero = false);
} // end of namespace tools
} // end of namespace basegfx
//////////////////////////////////////////////////////////////////////////////
#endif /* _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX */
<commit_msg>INTEGRATION: CWS aw033 (1.7.2); FILE MERGED 2008/05/14 14:42:30 aw 1.7.2.4: RESYNC: (1.8-1.9); FILE MERGED 2007/12/12 13:13:23 aw 1.7.2.3: #i39532# clipping changes 2007/12/03 13:53:13 aw 1.7.2.2: #i39532# checkin for resync 2005/10/28 11:21:56 aw 1.7.2.1: #i39532#<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: b2dpolypolygoncutter.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX
#define _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace basegfx
{
namespace tools
{
// Solve all crossovers in a polyPolygon. This re-layouts all contained polygons so that the
// result will contain only non-cutting polygons. For that reason, points will be added at
// crossover and touch points and the single Polygons may be re-combined. The orientations
// of the contained polygons in not changed but used as topological information.
// Self crossovers of the contained sub-polygons are implicitely handled, but to not lose
// the topological information, it may be necessary to remove self-intersections of the
// contained sub-polygons in a preparing step and to explicitely correct their orientations.
B2DPolyPolygon solveCrossovers(const B2DPolyPolygon& rCandidate);
// Version for single polygons. This is for solving self-intersections. Result will be free of
// crossovers. When result contains multiple polygons, it may be necessary to rearrange their
// orientations since holes may have been created (use correctOrientations eventually).
B2DPolyPolygon solveCrossovers(const B2DPolygon& rCandidate);
// Neutral polygons will be stripped. Neutral polygons are ones who's orientation is
// neutral, so normally they have no volume -> just closed paths. A polygon with the same
// positive and negative oriented volume is also neutral, so this may not be wanted. It is
// safe to call with crossover-free polygons, though (that's where it's mostly used).
B2DPolyPolygon stripNeutralPolygons(const B2DPolyPolygon& rCandidate);
// Remove not necessary polygons. Works only correct with crossover-free polygons. For each
// polygon, the depth for the PolyPolygon is calculated. The orientation is used to identify holes.
// Start value for holes is -1, for polygons it's zero. Ech time a polygon is contained in another one,
// it's depth is increased when inside a polygon, decreased when inside a hole. The result is a depth
// which e.g. is -1 for holes outside everything, 1 for a polygon covered by another polygon and zero
// for e.g. holes in a polygon or polygons outside everythig else.
// In the 2nd step, all polygons with depth other than zero are removed. If bKeepAboveZero is used,
// all polygons < 1 are removed. The bKeepAboveZero mode is useful for clipping, e.g. just append
// one polygon to another and use this mode -> only parts where two polygons overlapped will be kept.
// In combination with correct orientation of the input orientations and the SolveCrossover calls this
// can be combined for logical polygon operations or polygon clipping.
B2DPolyPolygon stripDispensablePolygons(const B2DPolyPolygon& rCandidate, bool bKeepAboveZero = false);
// For convenience: The four basic operations OR, XOR, AND and DIFF for
// two PolyPolygons. These are combinations of the above methods. To not be forced
// to do evtl. already done preparations twice, You have to do the operations Yourself.
//
// A source preparation consists of preparing it to be seen as XOR-Rule PolyPolygon,
// so it is freed of intersections, self-intersections and the orientations are corrected.
// Important is that it will define the same areas as before, but is intersection-free.
// As an example think about a single polygon looping in itself and having holes. To
// topologically correctly handle this, it is necessary to remove all intersections and
// to correct the orientations. The orientation of the isolated holes e.g. will be negative.
// Topologically it is necessary to prepare each polygon which is seen as entity. It is
// not sufficient just to concatenate them and prepare the result, this may be topologically
// different since the simple concatenation will be seen as XOR. To work correctly, You
// may need to OR those polygons.
// Preparations: solve self-intersections and intersections, remove neutral
// parts and correct orientations.
B2DPolyPolygon prepareForPolygonOperation(const B2DPolygon& rCandidate);
B2DPolyPolygon prepareForPolygonOperation(const B2DPolyPolygon& rCandidate);
// OR: Return all areas where CandidateA or CandidateB exist
B2DPolyPolygon solvePolygonOperationOr(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB);
// XOR: Return all areas where CandidateA or CandidateB exist, but not both
B2DPolyPolygon solvePolygonOperationXor(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB);
// AND: Return all areas where CandidateA and CandidateB exist
B2DPolyPolygon solvePolygonOperationAnd(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB);
// DIFF: Return all areas where CandidateA is not covered by CandidateB (cut B out of A)
B2DPolyPolygon solvePolygonOperationDiff(const B2DPolyPolygon& rCandidateA, const B2DPolyPolygon& rCandidateB);
} // end of namespace tools
} // end of namespace basegfx
//////////////////////////////////////////////////////////////////////////////
#endif /* _BGFX_POLYGON_B2DPOLYPOLYGONCUTTER_HXX */
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SKLAND_CORE_MEMORY_HPP_
#define SKLAND_CORE_MEMORY_HPP_
#include "defines.hpp"
#include <memory>
#include <atomic>
namespace skland {
namespace core {
/**
* @ingroup core
* @brief The base class for objects that may be shared by multiple objects.
* @tparam T The type of reference count, must be int, int32_t, long, size_t etc.
*
* Though we can use std::shared_ptr to store any type of object, there still be situation
* that we need to indicate what kind of object can be used in shared ptr.
*/
class SPCountedBase {
template<typename T> friend
class SharedPtr;
template<typename T> friend
class WeakPtr;
public:
SKLAND_DECLARE_NONCOPYABLE_AND_NONMOVALE(SPCountedBase);
struct Counter {
Counter()
: use_count(0), weak_count(0) {
_DEBUG("%s\n", __func__);
}
~Counter() {
_DEBUG("%s\n", __func__);
}
/**
* @brief The number of SharedPtr instances pointing to the object
*/
std::atomic_ulong use_count;
/**
* @brief The number of WeakPtr instances pointing to the object,
* plus one if the "use_count" is still > 0
*/
std::atomic_ulong weak_count;
};
SPCountedBase()
: counter_(new Counter) {}
virtual ~SPCountedBase() {
if (nullptr != counter_) {
_DEBUG("use_count: %ld, weak_count: %ld\n", counter_->use_count.load(), counter_->weak_count.load());
}
delete counter_;
}
size_t use_count() const {
return counter_->use_count.load();
}
size_t weak_count() const {
return counter_->weak_count.load();
}
private:
Counter *counter_;
};
/**
* @ingroup core
* @brief Shared pointer
* @tparam T
*/
template<typename T>
class SharedPtr {
template<typename R> friend
class WeakPtr;
template<typename R>
friend void swap(SharedPtr<R> &src, SharedPtr<R> &dst);
public:
SharedPtr() = default;
explicit SharedPtr(T *obj) : ptr_(obj) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
SharedPtr(const SharedPtr &orig)
: ptr_(orig.ptr_) {
if (nullptr != ptr_) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
}
/**
* @brief Move constructor
* @param orig
*/
SharedPtr(SharedPtr &&orig) noexcept
: ptr_(orig.ptr_), counter_(orig.counter_) {
orig.ptr_ = nullptr;
orig.counter_ = nullptr;
}
~SharedPtr() {
if (nullptr != counter_) {
_ASSERT((nullptr != ptr_) && (ptr_->counter_ == counter_));
--counter_->use_count;
if (0 == counter_->use_count) {
ptr_->counter_ = nullptr; // set this value to avoid destroying the counter
// Important: avoid double delete counter_:
++counter_->weak_count;
delete ptr_;
--counter_->weak_count;
if (0 == counter_->weak_count) delete counter_;
}
} else {
_ASSERT(nullptr == ptr_);
}
}
/**
* @brief Copy assignment
* @param other
* @return
*/
SharedPtr &operator=(const SharedPtr &other) noexcept {
reset(other.ptr_);
return *this;
}
/**
* @brief Move assignment
* @param other
* @return
*/
SharedPtr &operator=(SharedPtr &&other) noexcept {
ptr_ = other.ptr_;
counter_ = other.counter_;
other.ptr_ = nullptr;
other.counter_ = nullptr;
return *this;
}
SharedPtr &operator=(T *obj) noexcept {
reset(obj);
return *this;
}
/**
* @brief Swap content
* @param other
*/
void swap(SharedPtr &other) noexcept {
T *object = ptr_;
SPCountedBase::Counter *counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
other.ptr_ = object;
other.counter_ = counter;
}
/**
* @brief Reset pointer
* @param obj
*/
void reset(T *obj = nullptr) {
T *old_object = ptr_;
SPCountedBase::Counter *old_counter = counter_;
ptr_ = obj;
counter_ = nullptr;
if (nullptr != ptr_) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
if (nullptr != old_counter) {
_ASSERT((nullptr != old_object) && (old_object->counter_ == old_counter));
--old_counter->use_count;
if (0 == old_counter->use_count) {
old_object->counter_ = nullptr;
// Important: avoid double delete old_counter:
++old_counter->weak_count;
delete old_object;
--old_counter->weak_count;
if (0 == old_counter->weak_count) delete old_counter;
}
} else {
_ASSERT(nullptr == old_object);
}
}
/**
* @brief Get pointer
* @return
*/
T *get() const {
return ptr_;
}
/**
* @brief Dereference object
* @return
*/
T &operator*() const {
return *ptr_;
}
/**
* @brief Dereference object member
* @return
*/
T *operator->() const {
return ptr_;
}
/**
* @brief Use count
* @return
*/
size_t use_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->use_count.load();
}
size_t weak_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->weak_count.load();
}
/**
* @brief Returns whether this shared pointer does not share ownership over its pointer with other.
* @return
*/
bool unique() const noexcept {
return 1 == use_count();
}
explicit operator bool() const {
if (nullptr == ptr_) {
_ASSERT(nullptr == counter_);
return false;
}
_ASSERT(ptr_->counter_ == counter_);
return true;
}
private:
T *ptr_ = nullptr;
SPCountedBase::Counter *counter_ = nullptr;
};
template<typename T>
class WeakPtr {
public:
WeakPtr() = default;
WeakPtr(const WeakPtr &orig) {
ptr_ = orig.ptr_;
counter_ = orig.counter_;
if (nullptr != counter_) ++counter_->weak_count;
}
explicit WeakPtr(const SharedPtr<T> &orig) {
ptr_ = orig.ptr_;
counter_ = orig.counter_;
if (nullptr != counter_) ++counter_->weak_count;
}
~WeakPtr() {
if (nullptr != counter_) {
--counter_->weak_count;
if ((0 == counter_->use_count) && (0 == counter_->weak_count)) {
delete counter_;
}
}
}
WeakPtr &operator=(const SharedPtr<T> &other) {
SPCountedBase::Counter *old_counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
if (nullptr != counter_) ++counter_->weak_count;
if (nullptr != old_counter) {
--old_counter->weak_count;
if ((0 == old_counter->use_count) && (0 == old_counter->weak_count)) {
delete old_counter;
}
}
return *this;
}
WeakPtr &operator=(const WeakPtr &other) {
SPCountedBase::Counter *old_counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
if (nullptr != counter_) ++counter_->weak_count;
if (nullptr != old_counter) {
--old_counter->weak_count;
if ((0 == old_counter->use_count) && (0 == old_counter->weak_count)) {
delete old_counter;
}
}
return *this;
}
void reset() {
ptr_ = nullptr;
if (nullptr != counter_) {
--counter_->weak_count;
if ((0 == counter_->use_count) && (0 == counter_->weak_count)) {
delete counter_;
}
counter_ = nullptr;
}
}
size_t use_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->use_count.load();
}
size_t weak_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->weak_count.load();
}
SharedPtr<T> lock() const noexcept {
return SharedPtr<T>(ptr_);
}
private:
T *ptr_ = nullptr;
SPCountedBase::Counter *counter_ = nullptr;
};
/**
* @ingroup core
* @brief Constructs an object of type T and wraps it in a std::unique_ptr
* @tparam T
* @tparam Args
* @param args list of arguments with which an instance of T will be constructed
* @return std::unique_ptr of an instance of type T
*
* This template function is the same as std::make_unique in C++14
*/
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<typename T, typename ... Args>
SharedPtr<T> make_shared(Args &&... args) {
return SharedPtr<T>(new T(std::forward<Args>(args)...));
};
template<typename T>
void swap(SharedPtr<T> &src, SharedPtr<T> &dst) {
T *object = src.ptr_;
SPCountedBase::Counter *counter = src.counter_;
src.ptr_ = dst.ptr_;
src.counter_ = dst.counter_;
dst.ptr_ = object;
dst.counter_ = counter;
}
} // namespace core
} // namespace skland
#endif // SKLAND_CORE_MEMORY_HPP_
<commit_msg>Documentation work.<commit_after>/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SKLAND_CORE_MEMORY_HPP_
#define SKLAND_CORE_MEMORY_HPP_
#include "defines.hpp"
#include <memory>
#include <atomic>
namespace skland {
namespace core {
/**
* @ingroup core
* @brief The base class for objects that may be shared by multiple objects.
*
* SPCountedBase is the base class to be used in SharedPtr and WeakPtr for
* implementing our custom reference counting smart pointer. Though we can use
* std::shared_ptr to store any type of object, there still be situation that we
* need to indicate what kind of object can be used in a shared pointer.
*
* You usually define your own sub class of SPCountedBase, create and contain an
* instance in a SharedPtr. Use WeakPtr to avoid curcular references in
* appropriate time.
*
* Each SPCountedBase object has a pointer to a Counter object which stores 2
* different counters:
*
* - use_count: the number of SharedPtr instances pointing to this
* SPCountedBase object
*
* - weak_count: the number of WeakPtr instances pointing to this
* SPCountedBase object
*
* A SPCountedBase object knows its reference status by checking the counters by
* use_count() or weak_count(). When a SPCountedBase object is created by new
* operator and not controled by any SharedPtr or WeakPtr, both use_count and
* weak_count are zero, in this case you can safely delete the instance.
*/
class SPCountedBase {
template<typename T> friend
class SharedPtr;
template<typename T> friend
class WeakPtr;
public:
SKLAND_DECLARE_NONCOPYABLE_AND_NONMOVALE(SPCountedBase);
struct Counter {
Counter()
: use_count(0), weak_count(0) {
_DEBUG("%s\n", __func__);
}
~Counter() {
_DEBUG("%s\n", __func__);
}
/**
* @brief The number of SharedPtr instances pointing to the object
*/
std::atomic_ulong use_count;
/**
* @brief The number of WeakPtr instances pointing to the object, plus one
* if the "use_count" is still > 0
*/
std::atomic_ulong weak_count;
};
SPCountedBase()
: counter_(new Counter) {}
virtual ~SPCountedBase() {
if (nullptr != counter_) {
_DEBUG("use_count: %ld, weak_count: %ld\n",
counter_->use_count.load(),
counter_->weak_count.load());
}
delete counter_;
}
size_t use_count() const {
return counter_->use_count.load();
}
size_t weak_count() const {
return counter_->weak_count.load();
}
private:
Counter *counter_;
};
/**
* @ingroup core
* @brief Shared pointer
* @tparam T
*/
template<typename T>
class SharedPtr {
template<typename R> friend
class WeakPtr;
template<typename R>
friend void swap(SharedPtr<R> &src, SharedPtr<R> &dst);
public:
SharedPtr() = default;
explicit SharedPtr(T *obj) : ptr_(obj) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
SharedPtr(const SharedPtr &orig)
: ptr_(orig.ptr_) {
if (nullptr != ptr_) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
}
/**
* @brief Move constructor
* @param orig
*/
SharedPtr(SharedPtr &&orig) noexcept
: ptr_(orig.ptr_), counter_(orig.counter_) {
orig.ptr_ = nullptr;
orig.counter_ = nullptr;
}
~SharedPtr() {
if (nullptr != counter_) {
_ASSERT((nullptr != ptr_) && (ptr_->counter_ == counter_));
--counter_->use_count;
if (0 == counter_->use_count) {
ptr_->counter_ = nullptr; // set this value to avoid destroying the counter
// Important: avoid double delete counter_:
++counter_->weak_count;
delete ptr_;
--counter_->weak_count;
if (0 == counter_->weak_count) delete counter_;
}
} else {
_ASSERT(nullptr == ptr_);
}
}
/**
* @brief Copy assignment
* @param other
* @return
*/
SharedPtr &operator=(const SharedPtr &other) noexcept {
reset(other.ptr_);
return *this;
}
/**
* @brief Move assignment
* @param other
* @return
*/
SharedPtr &operator=(SharedPtr &&other) noexcept {
ptr_ = other.ptr_;
counter_ = other.counter_;
other.ptr_ = nullptr;
other.counter_ = nullptr;
return *this;
}
SharedPtr &operator=(T *obj) noexcept {
reset(obj);
return *this;
}
/**
* @brief Swap content
* @param other
*/
void swap(SharedPtr &other) noexcept {
T *object = ptr_;
SPCountedBase::Counter *counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
other.ptr_ = object;
other.counter_ = counter;
}
/**
* @brief Reset pointer
* @param obj
*/
void reset(T *obj = nullptr) {
T *old_object = ptr_;
SPCountedBase::Counter *old_counter = counter_;
ptr_ = obj;
counter_ = nullptr;
if (nullptr != ptr_) {
counter_ = ptr_->counter_;
++counter_->use_count;
}
if (nullptr != old_counter) {
_ASSERT((nullptr != old_object) && (old_object->counter_ == old_counter));
--old_counter->use_count;
if (0 == old_counter->use_count) {
old_object->counter_ = nullptr;
// Important: avoid double delete old_counter:
++old_counter->weak_count;
delete old_object;
--old_counter->weak_count;
if (0 == old_counter->weak_count) delete old_counter;
}
} else {
_ASSERT(nullptr == old_object);
}
}
/**
* @brief Get pointer
* @return
*/
T *get() const {
return ptr_;
}
/**
* @brief Dereference object
* @return
*/
T &operator*() const {
return *ptr_;
}
/**
* @brief Dereference object member
* @return
*/
T *operator->() const {
return ptr_;
}
/**
* @brief Use count
* @return
*/
size_t use_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->use_count.load();
}
size_t weak_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->weak_count.load();
}
/**
* @brief Returns whether this shared pointer does not share ownership over
* its pointer with other.
* @return
*/
bool unique() const noexcept {
return 1 == use_count();
}
explicit operator bool() const {
if (nullptr == ptr_) {
_ASSERT(nullptr == counter_);
return false;
}
_ASSERT(ptr_->counter_ == counter_);
return true;
}
private:
T *ptr_ = nullptr;
SPCountedBase::Counter *counter_ = nullptr;
};
/**
* @ingroup core
* @brief Weak ptr
* @tparam T
*/
template<typename T>
class WeakPtr {
public:
WeakPtr() = default;
WeakPtr(const WeakPtr &orig) {
ptr_ = orig.ptr_;
counter_ = orig.counter_;
if (nullptr != counter_) ++counter_->weak_count;
}
explicit WeakPtr(const SharedPtr<T> &orig) {
ptr_ = orig.ptr_;
counter_ = orig.counter_;
if (nullptr != counter_) ++counter_->weak_count;
}
~WeakPtr() {
if (nullptr != counter_) {
--counter_->weak_count;
if ((0 == counter_->use_count) && (0 == counter_->weak_count)) {
delete counter_;
}
}
}
WeakPtr &operator=(const SharedPtr<T> &other) {
SPCountedBase::Counter *old_counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
if (nullptr != counter_) ++counter_->weak_count;
if (nullptr != old_counter) {
--old_counter->weak_count;
if ((0 == old_counter->use_count) && (0 == old_counter->weak_count)) {
delete old_counter;
}
}
return *this;
}
WeakPtr &operator=(const WeakPtr &other) {
SPCountedBase::Counter *old_counter = counter_;
ptr_ = other.ptr_;
counter_ = other.counter_;
if (nullptr != counter_) ++counter_->weak_count;
if (nullptr != old_counter) {
--old_counter->weak_count;
if ((0 == old_counter->use_count) && (0 == old_counter->weak_count)) {
delete old_counter;
}
}
return *this;
}
void reset() {
ptr_ = nullptr;
if (nullptr != counter_) {
--counter_->weak_count;
if ((0 == counter_->use_count) && (0 == counter_->weak_count)) {
delete counter_;
}
counter_ = nullptr;
}
}
size_t use_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->use_count.load();
}
size_t weak_count() const noexcept {
return nullptr == counter_ ? 0 : counter_->weak_count.load();
}
/**
* @brief Returns a SharedPtr with the object preserved if it is not expired.
*
* When you try to obtain a SharedPtr by this method, the WeakPtr checks the
* "use count", and if it's > 0 returns a valid SharedPtr . If the "use count"
* was already zero you get an empty SharedPtr instance instead.
*/
SharedPtr<T> lock() const noexcept {
if (counter_->use_count > 0) {
return SharedPtr<T>(ptr_);
}
return SharedPtr<T>();
}
private:
T *ptr_ = nullptr;
SPCountedBase::Counter *counter_ = nullptr;
};
/**
* @ingroup core
* @brief Constructs an object of type T and wraps it in a std::unique_ptr
* @tparam T
* @tparam Args
* @param args list of arguments with which an instance of T will be constructed
* @return std::unique_ptr of an instance of type T
*
* This template function is the same as std::make_unique in C++14
*/
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args &&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<typename T, typename ... Args>
SharedPtr<T> make_shared(Args &&... args) {
return SharedPtr<T>(new T(std::forward<Args>(args)...));
};
template<typename T>
void swap(SharedPtr<T> &src, SharedPtr<T> &dst) {
T *object = src.ptr_;
SPCountedBase::Counter *counter = src.counter_;
src.ptr_ = dst.ptr_;
src.counter_ = dst.counter_;
dst.ptr_ = object;
dst.counter_ = counter;
}
} // namespace core
} // namespace skland
#endif // SKLAND_CORE_MEMORY_HPP_
<|endoftext|>
|
<commit_before>#pragma once
// generic (non-architecture-specific) implementations of gemmBitserial
// and other related functions
static GEMMContext allocGEMMContext_generic(
uint64_t lhsRows, uint64_t depth, uint64_t rhsRows,
uint64_t lhsBits, uint64_t rhsBits,
bool lhsSigned, bool rhsSigned
) {
const uint64_t regblock_lhs = 2;
const uint64_t regblock_d = 1;
const uint64_t regblock_rhs = 2;
const uint64_t cacheBits = 32*1024*8;
return allocGEMMContext_base(
lhsRows, depth, rhsRows, lhsBits, rhsBits, lhsSigned, rhsSigned,
regblock_lhs, regblock_d, regblock_rhs, cacheBits
);
};
/* Multiply a lhs_block x rhs_block chunk of the given matrices, starting at
(bA, bBT) using 2x1x2 register tiling. For internal use.
*/
inline void gemmBinary_generic_chunk_tile2x1x2(
uint64_t * A, uint64_t * BT, int32_t * CT,
int32_t alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT,
uint64_t bA, uint64_t bBT,
uint64_t lhs_block, uint64_t rhs_block,
uint64_t rowsA_orig, uint64_t rowsBT_orig) {
const uint64_t Atile = 2, DepthTile = 1, BTtile = 2;
const size_t num_acc = Atile*BTtile;
for(uint64_t rBT = bBT; rBT < bBT + rhs_block; rBT += BTtile) {
uint64_t * BTptr = &BT[rBT * depth_words];
for(uint64_t rA = bA; rA < bA + lhs_block; rA += Atile) {
uint64_t * Aptr = &A[rA * depth_words];
int32_t acc[num_acc] = {0};
for(uint64_t d = 0; d < depth_words; d += DepthTile) {
const uint64_t a0 = Aptr[d], a1 = Aptr[d + depth_words];
const uint64_t b0 = BTptr[d], b1 = BTptr[d + depth_words];
acc[0] += __builtin_popcountll(a0 & b0);
acc[1] += __builtin_popcountll(a0 & b1);
acc[2] += __builtin_popcountll(a1 & b0);
acc[3] += __builtin_popcountll(a1 & b1);
}
for(uint64_t at = 0; at < Atile; at++) {
for(uint64_t bt = 0; bt < BTtile; bt++) {
if(((rBT + bt) < rowsBT_orig) && ((rA + at) < rowsA_orig)) {
CT[(rBT + bt) * rowsA_orig + (rA + at)] += acc[at * BTtile + bt] * alpha;
}
}
}
}
}
}
/* CT = A * BT using cache blocking and 2x1x2 register blocking where possible.
For internal use.
*/
static void gemmBinary_generic_L1_tile2x1x2(
uint64_t * A, uint64_t * BT, int32_t * CT, int32_t alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT,
uint64_t rowsA_orig, uint64_t rowsBT_orig,
uint64_t lhsBlock, uint64_t rhsBlock
) {
const uint64_t Atile = 2, DepthTile = 1, BTtile = 2;
assert(rowsBT % rhsBlock == 0);
assert(rowsA % lhsBlock == 0);
assert(lhsBlock % Atile == 0);
assert(rhsBlock % BTtile == 0);
for(uint64_t bBT = 0; bBT < rowsBT; bBT += rhsBlock) {
for(uint64_t bA = 0; bA < rowsA; bA += lhsBlock) {
gemmBinary_generic_chunk_tile2x1x2(
A, BT, CT, alpha, rowsA, depth_words, rowsBT, bA, bBT,
lhsBlock, rhsBlock, rowsA_orig, rowsBT_orig
);
}
}
}
/* Bit-serial GEMM via a series of calls to gemmBinary.
Note that rhs must be given in transposed form, and the result is also
produced transposed.
*/
static void gemmBitSerial_generic_usingBinary(GEMMContext ctx) {
// ensure that matrix shapes are compatible
assert(ctx.lhs.ncols == ctx.rhs.ncols);
const uint64_t lhsbits = ctx.lhs.nbits;
const uint64_t rhsbits = ctx.rhs.nbits;
// clear contents of result matrix by setting everything to zero
memset(ctx.res, 0, ctx.lhs.nrows*ctx.rhs.nrows*sizeof(int32_t));
// call binary GEMM for each bit position
for(uint64_t lbit = 0; lbit < lhsbits; lbit++) {
bool neg_lhs = ctx.lhs.issigned && (lbit == lhsbits-1);
for(uint64_t rbit = 0; rbit < rhsbits; rbit++) {
bool neg_rhs = ctx.rhs.issigned && (rbit == rhsbits-1);
bool neg = neg_rhs ^ neg_lhs;
int32_t alpha = neg ? -(1 << (lbit+rbit)) : (1 << (lbit+rbit));
gemmBinary_generic_L1_tile2x1x2(
ctx.lhs.bitplaneptr(lbit), ctx.rhs.bitplaneptr(rbit), ctx.res, alpha,
ctx.lhs.nrows_a, ctx.lhs.wordsPerRow(), ctx.rhs.nrows_a,
ctx.lhs.nrows, ctx.rhs.nrows, ctx.lhsBlock, ctx.rhsBlock
);
}
}
}
<commit_msg>bring back naive gemmBitSerial, useful for verification<commit_after>#pragma once
// generic (non-architecture-specific) implementations of gemmBitserial
// and other related functions
static GEMMContext allocGEMMContext_generic(
uint64_t lhsRows, uint64_t depth, uint64_t rhsRows,
uint64_t lhsBits, uint64_t rhsBits,
bool lhsSigned, bool rhsSigned
) {
const uint64_t regblock_lhs = 2;
const uint64_t regblock_d = 1;
const uint64_t regblock_rhs = 2;
const uint64_t cacheBits = 32*1024*8;
return allocGEMMContext_base(
lhsRows, depth, rhsRows, lhsBits, rhsBits, lhsSigned, rhsSigned,
regblock_lhs, regblock_d, regblock_rhs, cacheBits
);
};
/* Multiply a lhs_block x rhs_block chunk of the given matrices, starting at
(bA, bBT) using 2x1x2 register tiling. For internal use.
*/
inline void gemmBinary_generic_chunk_tile2x1x2(
uint64_t * A, uint64_t * BT, int32_t * CT,
int32_t alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT,
uint64_t bA, uint64_t bBT,
uint64_t lhs_block, uint64_t rhs_block,
uint64_t rowsA_orig, uint64_t rowsBT_orig) {
const uint64_t Atile = 2, DepthTile = 1, BTtile = 2;
const size_t num_acc = Atile*BTtile;
for(uint64_t rBT = bBT; rBT < bBT + rhs_block; rBT += BTtile) {
uint64_t * BTptr = &BT[rBT * depth_words];
for(uint64_t rA = bA; rA < bA + lhs_block; rA += Atile) {
uint64_t * Aptr = &A[rA * depth_words];
int32_t acc[num_acc] = {0};
for(uint64_t d = 0; d < depth_words; d += DepthTile) {
const uint64_t a0 = Aptr[d], a1 = Aptr[d + depth_words];
const uint64_t b0 = BTptr[d], b1 = BTptr[d + depth_words];
acc[0] += __builtin_popcountll(a0 & b0);
acc[1] += __builtin_popcountll(a0 & b1);
acc[2] += __builtin_popcountll(a1 & b0);
acc[3] += __builtin_popcountll(a1 & b1);
}
for(uint64_t at = 0; at < Atile; at++) {
for(uint64_t bt = 0; bt < BTtile; bt++) {
if(((rBT + bt) < rowsBT_orig) && ((rA + at) < rowsA_orig)) {
CT[(rBT + bt) * rowsA_orig + (rA + at)] += acc[at * BTtile + bt] * alpha;
}
}
}
}
}
}
/* CT = A * BT using cache blocking and 2x1x2 register blocking where possible.
For internal use.
*/
static void gemmBinary_generic_L1_tile2x1x2(
uint64_t * A, uint64_t * BT, int32_t * CT, int32_t alpha,
uint64_t rowsA, uint64_t depth_words, uint64_t rowsBT,
uint64_t rowsA_orig, uint64_t rowsBT_orig,
uint64_t lhsBlock, uint64_t rhsBlock
) {
const uint64_t Atile = 2, DepthTile = 1, BTtile = 2;
assert(rowsBT % rhsBlock == 0);
assert(rowsA % lhsBlock == 0);
assert(lhsBlock % Atile == 0);
assert(rhsBlock % BTtile == 0);
for(uint64_t bBT = 0; bBT < rowsBT; bBT += rhsBlock) {
for(uint64_t bA = 0; bA < rowsA; bA += lhsBlock) {
gemmBinary_generic_chunk_tile2x1x2(
A, BT, CT, alpha, rowsA, depth_words, rowsBT, bA, bBT,
lhsBlock, rhsBlock, rowsA_orig, rowsBT_orig
);
}
}
}
/* Bit-serial GEMM via a series of calls to gemmBinary.
Note that rhs must be given in transposed form, and the result is also
produced transposed.
*/
static void gemmBitSerial_generic_usingBinary(GEMMContext ctx) {
// ensure that matrix shapes are compatible
assert(ctx.lhs.ncols == ctx.rhs.ncols);
const uint64_t lhsbits = ctx.lhs.nbits;
const uint64_t rhsbits = ctx.rhs.nbits;
// clear contents of result matrix by setting everything to zero
memset(ctx.res, 0, ctx.lhs.nrows*ctx.rhs.nrows*sizeof(int32_t));
// call binary GEMM for each bit position
for(uint64_t lbit = 0; lbit < lhsbits; lbit++) {
bool neg_lhs = ctx.lhs.issigned && (lbit == lhsbits-1);
for(uint64_t rbit = 0; rbit < rhsbits; rbit++) {
bool neg_rhs = ctx.rhs.issigned && (rbit == rhsbits-1);
bool neg = neg_rhs ^ neg_lhs;
int32_t alpha = neg ? -(1 << (lbit+rbit)) : (1 << (lbit+rbit));
gemmBinary_generic_L1_tile2x1x2(
ctx.lhs.bitplaneptr(lbit), ctx.rhs.bitplaneptr(rbit), ctx.res, alpha,
ctx.lhs.nrows_a, ctx.lhs.wordsPerRow(), ctx.rhs.nrows_a,
ctx.lhs.nrows, ctx.rhs.nrows, ctx.lhsBlock, ctx.rhsBlock
);
}
}
}
/* Standalone bit-serial GEMM. Note that rhs must be given in transposed
form, and the result is also produced transposed.
*/
static void gemmBitSerial_generic_naive(GEMMContext ctx) {
// ensure that matrix shapes are compatible
assert(ctx.lhs.ncols == ctx.rhs.ncols);
const uint64_t lhsbits = ctx.lhs.nbits;
const uint64_t rhsbits = ctx.rhs.nbits;
const uint64_t out_rows = ctx.lhs.nrows;
const uint64_t out_cols = ctx.rhs.nrows;
const uint64_t depth = ctx.lhs.wordsPerRow();
for(uint64_t i = 0; i < out_cols; i++) {
for(uint64_t j = 0; j < out_rows; j++) {
int32_t rowres = 0;
for(uint64_t lbit = 0; lbit < lhsbits; lbit++) {
bool neg_lhs = ctx.lhs.issigned && (lbit == lhsbits-1);
for(uint64_t rbit = 0; rbit < rhsbits; rbit++) {
bool neg_rhs = ctx.rhs.issigned && (rbit == rhsbits-1);
uint64_t * ldata = ctx.lhs.rowptr(lbit, j);
uint64_t * rdata = ctx.rhs.rowptr(rbit, i);
uint64_t andcard = 0;
// AND-popcount-accumulate over row pair
for(uint64_t k = 0; k < depth; k++) {
andcard += __builtin_popcountll(ldata[k] & rdata[k]);
}
// scale
andcard = andcard << (lbit + rbit);
// negate if needed
rowres += (neg_lhs ^ neg_rhs) ? -andcard : andcard;
}
}
ctx.res[i * ctx.lhs.nrows + j] = rowres;
}
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkDashedStreamLine.hh
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
// .NAME vtkDashedStreamLine - generate constant-time dashed streamline in arbitrary dataset
// .SECTION Description
// vtkDashedStreamLine is a filter that generates a "dashed" streamline for
// an arbitrary dataset. The streamline consists of a series of dashes, each
// of which represents (approximately) a constant time increment. Thus in the
// resulting visual representation, relatively long dashes represent areas of
// high velocity, and small dashes represent areas of low velocity.
//
// vtkDashedStreamLine introduces the instance variable DashFactor.
// DashFactor interacts with its superclass' instance variable StepLength to
// create the dashes. DashFactor is the percentage of the StepLength line
// segment that is visible. Thus if DashFactor=0.75, the dashes will be
// "three-quarters on" and "one-quarter off".
// .SECTION See Also
// vtkStreamer, vtkStreamLine, vtkStreamPoints
#ifndef __vtkDashedStreamLine_h
#define __vtkDashedStreamLine_h
#include "vtkStreamLine.hh"
class vtkDashedStreamLine : public vtkStreamLine
{
public:
vtkDashedStreamLine();
char *GetClassName() {return "vtkDashedStreamLine";};
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// For each dash, specify the fraction of the dash that is "on". A factor
// of 1.0 will result in a continuous line, a factor of 0.5 will result in
// dashed that are half on and half off.
vtkSetClampMacro(DashFactor,float,0.01,1.0);
vtkGetMacro(DashFactor,float);
protected:
// Convert streamer array into vtkPolyData
void Execute();
// the fraction of on versus off in dash
float DashFactor;
};
#endif
<commit_msg>ENH: Fixed comments<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkDashedStreamLine.hh
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
// .NAME vtkDashedStreamLine - generate constant-time dashed streamline in arbitrary dataset
// .SECTION Description
// vtkDashedStreamLine is a filter that generates a "dashed" streamline for
// an arbitrary dataset. The streamline consists of a series of dashes, each
// of which represents (approximately) a constant time increment. Thus in the
// resulting visual representation, relatively long dashes represent areas of
// high velocity, and small dashes represent areas of low velocity.
//
// vtkDashedStreamLine introduces the instance variable DashFactor.
// DashFactor interacts with its superclass' instance variable StepLength to
// create the dashes. DashFactor is the percentage of the StepLength line
// segment that is visible. Thus if DashFactor=0.75, the dashes will be
// "three-quarters on" and "one-quarter off".
// .SECTION See Also
// vtkStreamer vtkStreamLine vtkStreamPoints
#ifndef __vtkDashedStreamLine_h
#define __vtkDashedStreamLine_h
#include "vtkStreamLine.hh"
class vtkDashedStreamLine : public vtkStreamLine
{
public:
vtkDashedStreamLine();
char *GetClassName() {return "vtkDashedStreamLine";};
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// For each dash, specify the fraction of the dash that is "on". A factor
// of 1.0 will result in a continuous line, a factor of 0.5 will result in
// dashed that are half on and half off.
vtkSetClampMacro(DashFactor,float,0.01,1.0);
vtkGetMacro(DashFactor,float);
protected:
// Convert streamer array into vtkPolyData
void Execute();
// the fraction of on versus off in dash
float DashFactor;
};
#endif
<|endoftext|>
|
<commit_before>/*~
* Copyright (C) 2013 - 2016 George Makrydakis <george@irrequietus.eu>
*
* This file is part of 'clause', a highly generic C++ meta-programming library,
* subject to the terms and conditions of the Mozilla Public License v 2.0. If
* a copy of the MPLv2 license text was not distributed with this file, you can
* obtain it at: http://mozilla.org/MPL/2.0/.
*
* The 'clause' library is an experimental library in active development with
* a source code repository at: https://github.com/irrequietus/clause.git and
* issue tracker at https://github.com/irrequietus/clause/issues.
*
*/
#ifndef CLAUSE_PPMPF_ALGORITHMS_MAP_HH
#define CLAUSE_PPMPF_ALGORITHMS_MAP_HH
#include <clause/ppmpf/collections/tuple.hh>
#include <clause/ppmpf/collections/sequence.hh>
/*~
* @desc A high order function applying a given function to each element of a
* a given ppmpf collection (sequences, safe and unsafe ppmpf tuples),
* also supporting closures with a particular syntax and expanding to
* a ppmpf collection of the same typeclause.
* @pfrg fexp: a plain function or a ppmpf closure.
* @pfrg tycl: a ppmpf typeclause.
* @pexp Application of fexp over a ppmpf collection as the latter is described
* in the typeclause enclosing it.
*/
#define PPMPF_MAP(fexp,tycl) \
PPMPF_TYPEFY( PPMPF_PFLD1 \
, PPMPF_MHD \
, PPMPF_MAP_MHD \
, fexp \
, PPMPF_IFELSE( PPMPF_IS(PPMPF_TYPEOF(tycl), 2) \
, \
, () )\
, tycl )
#endif /* CLAUSE_PPMPF_ALGORITHMS_MAP_HH */
<commit_msg>Using <clause/ppmpf/algorithms/map.hh> includes vxpp fmap too now.<commit_after>/*~
* Copyright (C) 2013 - 2016 George Makrydakis <george@irrequietus.eu>
*
* This file is part of 'clause', a highly generic C++ meta-programming library,
* subject to the terms and conditions of the Mozilla Public License v 2.0. If
* a copy of the MPLv2 license text was not distributed with this file, you can
* obtain it at: http://mozilla.org/MPL/2.0/.
*
* The 'clause' library is an experimental library in active development with
* a source code repository at: https://github.com/irrequietus/clause.git and
* issue tracker at https://github.com/irrequietus/clause/issues.
*
*/
#ifndef CLAUSE_PPMPF_ALGORITHMS_MAP_HH
#define CLAUSE_PPMPF_ALGORITHMS_MAP_HH
#include <clause/ppmpf/collections/tuple.hh>
#include <clause/ppmpf/collections/sequence.hh>
#include <clause/ppmpf/vxpp.hh>
/*~
* @desc A high order function applying a given function to each element of a
* a given ppmpf collection (sequences, safe and unsafe ppmpf tuples),
* also supporting closures with a particular syntax and expanding to
* a ppmpf collection of the same typeclause.
* @pfrg fexp: a plain function or a ppmpf closure.
* @pfrg tycl: a ppmpf typeclause.
* @pexp Application of fexp over a ppmpf collection as the latter is described
* in the typeclause enclosing it.
*/
#define PPMPF_MAP(fexp,tycl) \
PPMPF_TYPEFY( PPMPF_PFLD1 \
, PPMPF_MHD \
, PPMPF_MAP_MHD \
, fexp \
, PPMPF_IFELSE( PPMPF_IS(PPMPF_TYPEOF(tycl), 2) \
, \
, () )\
, tycl )
#endif /* CLAUSE_PPMPF_ALGORITHMS_MAP_HH */
<|endoftext|>
|
<commit_before>/*
@ 0xCCCCCCCC
*/
#include <iostream>
#include "signals.h"
void foo(int i, const int& j, int&& k)
{
std::cout << "foo" << std::endl;
}
struct Foo {
static void foo(int i, const int& j, int&& k)
{
std::cout << "Foo::foo" << std::endl;
}
};
int main()
{
Signal<int, const int&, int&&> s;
std::function<void(int, const int&, int&&)> f(&foo);
Slot slot = s.Connect(&foo);
s.Connect(&Foo::foo);
s.Connect(f);
s.Emit(1, 3, 5);
slot.Disconnect();
s.Emit(5, 3, 1);
s.DisconnectAll();
s.Emit(3, 2, 1);
return 0;
}<commit_msg>Signal-Slot: update test code<commit_after>/*
@ 0xCCCCCCCC
*/
#include <iostream>
#include <functional>
#include "signals.h"
void foo(int i, const int& j, int&& k)
{
std::cout << "foo" << std::endl;
}
struct Foo {
static void sfoo(int i, const int& j, int&& k)
{
std::cout << "Foo::sfoo" << std::endl;
}
void foo(int i, const int& j, int&& k)
{
s = "world";
std::cout << "Foo::foo" << std::endl;
}
std::string s = "hello";
};
int main()
{
Signal<int, const int&, int&&> s;
Slot slot = s.Connect(&foo);
s.Connect(&Foo::sfoo);
auto foo = std::make_shared<Foo>();
auto pf = foo.get();
using namespace std::placeholders;
s.Connect(std::bind(&Foo::foo, pf, _1, _2, _3), foo);
s.Emit(1, 3, 5);
slot.Disconnect();
s.Emit(5, 3, 1);
foo.reset();
s.Emit(5, 3, 1);
s.DisconnectAll();
s.Emit(3, 2, 1);
return 0;
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct BmodP {
long long index;
long long value;
}mod1[10000000];
bool cmp(BmodP tmp1, BmodP tmp2) {
if(tmp1.value<tmp2.value || (tmp1.value==tmp2.value&&tmp1.index<tmp2.index)) return true;
return false;
}
long long* extendEuclid(long long a, long long b) {
long long *sol = new long long[2];
if(b==0) {
sol[0] = 1;
sol[1] = 0;
return sol;
} else {
long long *tmp = extendEuclid(b, a%b);
sol[0] = tmp[1];
sol[1] = tmp[0]-(long long)floor(a/b)*tmp[1];
return sol;
}
}
// a^n%p
long long pow_mod(long long a, long long n, long long p) {
if(n==0) return 1;
long long x = pow_mod(a, n/2, p);
long long ans = ((x%p) * (x %p))%p;
if(n%2==1) ans = ((ans%p)*(a%p))%p;
return ans;
}
long long bi_search(long long m, long long x) {
long long low = 0;
long long high = m-1;
while(low<=high) {
long long mid = (low+high)/2;
if(mod1[mid].value==x) {
return mod1[mid].index;
} else if(mod1[mid].value<x) {
low = mid+1;
} else {
high = mid-1;
}
}
return -1;
}
int main()
{
long long P, B, N;
while(scanf("%lld%lld%lld", &P, &B, &N)!=EOF) {
bool is_find = false;
long long m = (long long)ceil(sqrt((double)(P)));
//calculate B^j%p, j=0,1,...,m-1
for(long long j=0; j<m; j++) {
mod1[j].index = j;
mod1[j].value = pow_mod(B, j, P);
}
//sort array mod1, later used for binary search
sort(mod1, mod1+m, cmp);
//binary search mod1, need to delete repeated mod[j].value
for(long long i=0; i<m-1; i++) {
if(mod1[i+1].value==mod1[i].value) {
mod1[i+1].index = mod1[i].index;
}
}
//calculate N*inv(B^{im})%P, i=0,1,...,m-1
long long *invB = extendEuclid(B, P);
while(invB[0] <0) invB[0]+=P;
//long long bm = pow_mod(invB[0], m, P);
for(long long i=0; i<m; i++) {
long long tmp = pow_mod(invB[0], i*m, P);
long long res = ((tmp%P) * (N % P))%P;
//serach res in mod1
long long j = bi_search(m, res);
if(j!=-1) {
long long L = i*m + j;
cout << L << endl;
is_find = true;
break;
}
}
if(!is_find) cout << "no solution" << endl;
}
return 0;
}
<commit_msg>update discrete logarithm<commit_after>#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
struct BmodP {
long long index;
long long value;
}mod1[10000000];
bool cmp(BmodP tmp1, BmodP tmp2) {
if(tmp1.value<tmp2.value || (tmp1.value==tmp2.value&&tmp1.index<tmp2.index)) return true;
return false;
}
long long* extendEuclid(long long a, long long b) {
long long *sol = new long long[2];
if(b==0) {
sol[0] = 1;
sol[1] = 0;
return sol;
} else {
long long *tmp = extendEuclid(b, a%b);
sol[0] = tmp[1];
sol[1] = tmp[0]-(long long)floor(a/b)*tmp[1];
return sol;
}
}
// a^n%p
long long pow_mod(long long a, long long n, long long p) {
if(n==0) return 1;
long long x = pow_mod(a, n/2, p);
long long ans = ((x%p) * (x %p))%p;
if(n%2==1) ans = ((ans%p)*(a%p))%p;
return ans;
}
long long bi_search(long long m, long long x) {
long long low = 0;
long long high = m-1;
while(low<=high) {
long long mid = (low+high)/2;
if(mod1[mid].value==x) {
return mod1[mid].index;
} else if(mod1[mid].value<x) {
low = mid+1;
} else {
high = mid-1;
}
}
return -1;
}
int main()
{
long long P, B, N;
while(scanf("%lld%lld%lld", &P, &B, &N)!=EOF) {
bool is_find = false;
long long m = (long long)ceil(sqrt((double)(P)));
//calculate B^j%p, j=0,1,...,m-1
for(long long j=0; j<m; j++) {
mod1[j].index = j;
mod1[j].value = pow_mod(B, j, P);
}
//sort array mod1, later used for binary search
sort(mod1, mod1+m, cmp);
//There may exist same value with different index, let the big index be the small index
//otherwise, binary search may find the bigger index
for(long long i=0; i<m-1; i++) {
if(mod1[i+1].value==mod1[i].value) {
mod1[i+1].index = mod1[i].index;
}
}
//calculate N*inv(B^{im})%P, i=0,1,...,m-1
long long *invB = extendEuclid(B, P);
while(invB[0] <0) invB[0]+=P;
//long long bm = pow_mod(invB[0], m, P);
for(long long i=0; i<m; i++) {
long long tmp = pow_mod(invB[0], i*m, P);
long long res = ((tmp%P) * (N % P))%P;
//serach res in mod1
long long j = bi_search(m, res);
if(j!=-1) {
long long L = i*m + j;
cout << L << endl;
is_find = true;
break;
}
}
if(!is_find) cout << "no solution" << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_surface_gl.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/shell/platform/android/android_shell_holder.h"
namespace flutter {
AndroidSurfaceGL::AndroidSurfaceGL(
std::shared_ptr<AndroidContext> android_context,
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
const AndroidSurface::Factory& surface_factory)
: external_view_embedder_(
std::make_unique<AndroidExternalViewEmbedder>(android_context,
jni_facade,
surface_factory)),
android_context_(
std::static_pointer_cast<AndroidContextGL>(android_context)),
native_window_(nullptr),
onscreen_surface_(nullptr),
offscreen_surface_(nullptr) {
// Acquire the offscreen surface.
offscreen_surface_ = android_context_->CreateOffscreenSurface();
if (!offscreen_surface_->IsValid()) {
offscreen_surface_ = nullptr;
}
}
AndroidSurfaceGL::~AndroidSurfaceGL() = default;
void AndroidSurfaceGL::TeardownOnScreenContext() {
// When the onscreen surface is destroyed, the context and the surface
// instance should be deleted. Issue:
// https://github.com/flutter/flutter/issues/64414
android_context_->ClearCurrent();
onscreen_surface_ = nullptr;
}
bool AndroidSurfaceGL::IsValid() const {
return offscreen_surface_ && android_context_->IsValid();
}
std::unique_ptr<Surface> AndroidSurfaceGL::CreateGPUSurface(
GrDirectContext* gr_context) {
if (gr_context) {
return std::make_unique<GPUSurfaceGL>(sk_ref_sp(gr_context), this, true);
}
return std::make_unique<GPUSurfaceGL>(this, true);
}
bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
FML_DCHECK(native_window_);
if (size == onscreen_surface_->GetSize()) {
return true;
}
android_context_->ClearCurrent();
// Ensure the destructor is called since it destroys the `EGLSurface` before
// creating a new onscreen surface.
onscreen_surface_ = nullptr;
onscreen_surface_ = android_context_->CreateOnscreenSurface(native_window_);
if (!onscreen_surface_->IsValid()) {
FML_LOG(ERROR) << "Unable to create EGL window surface on resize.";
return false;
}
onscreen_surface_->MakeCurrent();
return true;
}
bool AndroidSurfaceGL::ResourceContextMakeCurrent() {
FML_DCHECK(IsValid());
return offscreen_surface_->MakeCurrent();
}
bool AndroidSurfaceGL::ResourceContextClearCurrent() {
FML_DCHECK(IsValid());
return android_context_->ClearCurrent();
}
bool AndroidSurfaceGL::SetNativeWindow(
fml::RefPtr<AndroidNativeWindow> window) {
FML_DCHECK(IsValid());
FML_DCHECK(window);
native_window_ = window;
// Create the onscreen surface.
onscreen_surface_ = android_context_->CreateOnscreenSurface(window);
if (!onscreen_surface_->IsValid()) {
return false;
}
return true;
}
std::unique_ptr<GLContextResult> AndroidSurfaceGL::GLContextMakeCurrent() {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
auto default_context_result = std::make_unique<GLContextDefaultResult>(
onscreen_surface_->MakeCurrent());
return std::move(default_context_result);
}
bool AndroidSurfaceGL::GLContextClearCurrent() {
FML_DCHECK(IsValid());
return android_context_->ClearCurrent();
}
bool AndroidSurfaceGL::GLContextPresent(uint32_t fbo_id) {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
return onscreen_surface_->SwapBuffers();
}
intptr_t AndroidSurfaceGL::GLContextFBO(GLFrameInfo frame_info) const {
FML_DCHECK(IsValid());
// The default window bound framebuffer on Android.
return 0;
}
// |GPUSurfaceGLDelegate|
ExternalViewEmbedder* AndroidSurfaceGL::GetExternalViewEmbedder() {
return external_view_embedder_.get();
}
} // namespace flutter
<commit_msg>Ensure the destructor is called since it destroys the `EGLSurface` before creating a new onscreen surface. (#20916)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_surface_gl.h"
#include <utility>
#include "flutter/fml/logging.h"
#include "flutter/fml/memory/ref_ptr.h"
#include "flutter/shell/platform/android/android_shell_holder.h"
namespace flutter {
AndroidSurfaceGL::AndroidSurfaceGL(
std::shared_ptr<AndroidContext> android_context,
std::shared_ptr<PlatformViewAndroidJNI> jni_facade,
const AndroidSurface::Factory& surface_factory)
: external_view_embedder_(
std::make_unique<AndroidExternalViewEmbedder>(android_context,
jni_facade,
surface_factory)),
android_context_(
std::static_pointer_cast<AndroidContextGL>(android_context)),
native_window_(nullptr),
onscreen_surface_(nullptr),
offscreen_surface_(nullptr) {
// Acquire the offscreen surface.
offscreen_surface_ = android_context_->CreateOffscreenSurface();
if (!offscreen_surface_->IsValid()) {
offscreen_surface_ = nullptr;
}
}
AndroidSurfaceGL::~AndroidSurfaceGL() = default;
void AndroidSurfaceGL::TeardownOnScreenContext() {
// When the onscreen surface is destroyed, the context and the surface
// instance should be deleted. Issue:
// https://github.com/flutter/flutter/issues/64414
android_context_->ClearCurrent();
onscreen_surface_ = nullptr;
}
bool AndroidSurfaceGL::IsValid() const {
return offscreen_surface_ && android_context_->IsValid();
}
std::unique_ptr<Surface> AndroidSurfaceGL::CreateGPUSurface(
GrDirectContext* gr_context) {
if (gr_context) {
return std::make_unique<GPUSurfaceGL>(sk_ref_sp(gr_context), this, true);
}
return std::make_unique<GPUSurfaceGL>(this, true);
}
bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
FML_DCHECK(native_window_);
if (size == onscreen_surface_->GetSize()) {
return true;
}
android_context_->ClearCurrent();
// Ensure the destructor is called since it destroys the `EGLSurface` before
// creating a new onscreen surface.
onscreen_surface_ = nullptr;
onscreen_surface_ = android_context_->CreateOnscreenSurface(native_window_);
if (!onscreen_surface_->IsValid()) {
FML_LOG(ERROR) << "Unable to create EGL window surface on resize.";
return false;
}
onscreen_surface_->MakeCurrent();
return true;
}
bool AndroidSurfaceGL::ResourceContextMakeCurrent() {
FML_DCHECK(IsValid());
return offscreen_surface_->MakeCurrent();
}
bool AndroidSurfaceGL::ResourceContextClearCurrent() {
FML_DCHECK(IsValid());
return android_context_->ClearCurrent();
}
bool AndroidSurfaceGL::SetNativeWindow(
fml::RefPtr<AndroidNativeWindow> window) {
FML_DCHECK(IsValid());
FML_DCHECK(window);
native_window_ = window;
// Ensure the destructor is called since it destroys the `EGLSurface` before
// creating a new onscreen surface.
onscreen_surface_ = nullptr;
// Create the onscreen surface.
onscreen_surface_ = android_context_->CreateOnscreenSurface(window);
if (!onscreen_surface_->IsValid()) {
return false;
}
return true;
}
std::unique_ptr<GLContextResult> AndroidSurfaceGL::GLContextMakeCurrent() {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
auto default_context_result = std::make_unique<GLContextDefaultResult>(
onscreen_surface_->MakeCurrent());
return std::move(default_context_result);
}
bool AndroidSurfaceGL::GLContextClearCurrent() {
FML_DCHECK(IsValid());
return android_context_->ClearCurrent();
}
bool AndroidSurfaceGL::GLContextPresent(uint32_t fbo_id) {
FML_DCHECK(IsValid());
FML_DCHECK(onscreen_surface_);
return onscreen_surface_->SwapBuffers();
}
intptr_t AndroidSurfaceGL::GLContextFBO(GLFrameInfo frame_info) const {
FML_DCHECK(IsValid());
// The default window bound framebuffer on Android.
return 0;
}
// |GPUSurfaceGLDelegate|
ExternalViewEmbedder* AndroidSurfaceGL::GetExternalViewEmbedder() {
return external_view_embedder_.get();
}
} // namespace flutter
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simplemapi.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-03-26 13:51:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_SIMPLEMAPI_HXX
#define INCLUDED_SIMPLEMAPI_HXX
#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <mapi.h>
#ifndef __MINGW32__
#include <mapix.h>
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif
class CSimpleMapi
{
public:
/**
@throws std::runtime_error
if either the mapi32.dll could not be loaded at all
or necessary function exports are missing
*/
CSimpleMapi(); // throws std::runtime_error;
~CSimpleMapi();
ULONG MAPILogon(
ULONG ulUIParam,
LPTSTR lpszProfileName,
LPTSTR lpszPassword,
FLAGS flFlags,
ULONG ulReserved,
LPLHANDLE lplhSession );
ULONG MAPILogoff(
LHANDLE lhSession,
ULONG ulUIParam,
FLAGS flFlags,
ULONG ulReserved );
ULONG MAPISendMail(
LHANDLE lhSession,
ULONG ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved );
private:
HMODULE m_hMapiDll;
LPMAPILOGON m_lpfnMapiLogon;
LPMAPILOGOFF m_lpfnMapiLogoff;
LPMAPISENDMAIL m_lpfnMapiSendMail;
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.82); FILE MERGED 2008/03/31 13:17:14 rt 1.5.82.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: simplemapi.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_SIMPLEMAPI_HXX
#define INCLUDED_SIMPLEMAPI_HXX
#define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#include <mapi.h>
#ifndef __MINGW32__
#include <mapix.h>
#endif
#if defined _MSC_VER
#pragma warning(pop)
#endif
class CSimpleMapi
{
public:
/**
@throws std::runtime_error
if either the mapi32.dll could not be loaded at all
or necessary function exports are missing
*/
CSimpleMapi(); // throws std::runtime_error;
~CSimpleMapi();
ULONG MAPILogon(
ULONG ulUIParam,
LPTSTR lpszProfileName,
LPTSTR lpszPassword,
FLAGS flFlags,
ULONG ulReserved,
LPLHANDLE lplhSession );
ULONG MAPILogoff(
LHANDLE lhSession,
ULONG ulUIParam,
FLAGS flFlags,
ULONG ulReserved );
ULONG MAPISendMail(
LHANDLE lhSession,
ULONG ulUIParam,
lpMapiMessage lpMessage,
FLAGS flFlags,
ULONG ulReserved );
private:
HMODULE m_hMapiDll;
LPMAPILOGON m_lpfnMapiLogon;
LPMAPILOGOFF m_lpfnMapiLogoff;
LPMAPISENDMAIL m_lpfnMapiSendMail;
};
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Embedded Framework 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 "dom_node_impl.h"
#include "browser_impl.h"
#include "cef_thread.h"
#include "dom_document_impl.h"
#include "dom_event_impl.h"
#include "tracker.h"
#include "base/logging.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAttribute.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEventListener.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNamedNodeMap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
using WebKit::WebAttribute;
using WebKit::WebDocument;
using WebKit::WebDOMEvent;
using WebKit::WebDOMEventListener;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebNamedNodeMap;
using WebKit::WebNode;
using WebKit::WebString;
namespace {
// Wrapper implementation for WebDOMEventListener.
class CefDOMEventListenerWrapper : public WebDOMEventListener,
public CefTrackObject
{
public:
CefDOMEventListenerWrapper(CefBrowserImpl* browser, WebFrame* frame,
CefRefPtr<CefDOMEventListener> listener)
: browser_(browser), frame_(frame), listener_(listener)
{
// Cause this object to be deleted immediately before the frame is closed.
browser->UIT_AddFrameObject(frame, this);
}
virtual ~CefDOMEventListenerWrapper()
{
REQUIRE_UIT();
}
virtual void handleEvent(const WebDOMEvent& event)
{
CefRefPtr<CefDOMDocumentImpl> documentImpl;
CefRefPtr<CefDOMEventImpl> eventImpl;
if (!event.isNull()) {
// Create CefDOMDocumentImpl and CefDOMEventImpl objects that are valid
// only for the scope of this method.
const WebDocument& document = frame_->document();
if (!document.isNull()) {
documentImpl = new CefDOMDocumentImpl(browser_, frame_);
eventImpl = new CefDOMEventImpl(documentImpl, event);
}
}
listener_->HandleEvent(eventImpl.get());
if(eventImpl.get())
eventImpl->Detach();
if (documentImpl.get())
documentImpl->Detach();
}
protected:
CefBrowserImpl* browser_;
WebFrame* frame_;
CefRefPtr<CefDOMEventListener> listener_;
};
} // namespace
CefDOMNodeImpl::CefDOMNodeImpl(CefRefPtr<CefDOMDocumentImpl> document,
const WebKit::WebNode& node)
: document_(document), node_(node)
{
}
CefDOMNodeImpl::~CefDOMNodeImpl()
{
REQUIRE_UIT();
if (document_.get() && !node_.isNull()) {
// Remove the node from the document.
document_->RemoveNode(node_);
}
}
CefDOMNodeImpl::Type CefDOMNodeImpl::GetType()
{
if (!VerifyContext())
return DOM_NODE_TYPE_UNSUPPORTED;
switch (node_.nodeType()) {
case WebNode::ElementNode:
return DOM_NODE_TYPE_ELEMENT;
case WebNode::AttributeNode:
return DOM_NODE_TYPE_ATTRIBUTE;
case WebNode::TextNode:
return DOM_NODE_TYPE_TEXT;
case WebNode::CDataSectionNode:
return DOM_NODE_TYPE_CDATA_SECTION;
case WebNode::EntityReferenceNode:
return DOM_NODE_TYPE_ENTITY_REFERENCE;
case WebNode::EntityNode:
return DOM_NODE_TYPE_ENTITY;
case WebNode::ProcessingInstructionsNode:
return DOM_NODE_TYPE_PROCESSING_INSTRUCTIONS;
case WebNode::CommentNode:
return DOM_NODE_TYPE_COMMENT;
case WebNode::DocumentNode:
return DOM_NODE_TYPE_DOCUMENT;
case WebNode::DocumentTypeNode:
return DOM_NODE_TYPE_DOCUMENT_TYPE;
case WebNode::DocumentFragmentNode:
return DOM_NODE_TYPE_DOCUMENT_FRAGMENT;
case WebNode::NotationNode:
return DOM_NODE_TYPE_NOTATION;
case WebNode::XPathNamespaceNode:
return DOM_NODE_TYPE_XPATH_NAMESPACE;
default:
return DOM_NODE_TYPE_UNSUPPORTED;
}
}
bool CefDOMNodeImpl::IsText()
{
if (!VerifyContext())
return false;
return node_.isTextNode();
}
bool CefDOMNodeImpl::IsElement()
{
if (!VerifyContext())
return false;
return node_.isElementNode();
}
CefString CefDOMNodeImpl::GetName()
{
CefString str;
if (!VerifyContext())
return str;
const WebString& name = node_.nodeName();
if (!name.isNull())
str = name;
return str;
}
CefString CefDOMNodeImpl::GetValue()
{
CefString str;
if (!VerifyContext())
return str;
const WebString& value = node_.nodeValue();
if (!value.isNull())
str = value;
return str;
}
bool CefDOMNodeImpl::SetValue(const CefString& value)
{
if (!VerifyContext())
return false;
if (node_.isElementNode())
return false;
return node_.setNodeValue(string16(value));
}
CefString CefDOMNodeImpl::GetAsMarkup()
{
CefString str;
if (!VerifyContext())
return str;
const WebString& markup = node_.createMarkup();
if (!markup.isNull())
str = markup;
return str;
}
CefRefPtr<CefDOMDocument> CefDOMNodeImpl::GetDocument()
{
if (!VerifyContext())
return NULL;
return document_.get();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetParent()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.parentNode());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetPreviousSibling()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.previousSibling());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetNextSibling()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.nextSibling());
}
bool CefDOMNodeImpl::HasChildren()
{
if (!VerifyContext())
return false;
return node_.hasChildNodes();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetFirstChild()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.firstChild());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetLastChild()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.lastChild());
}
void CefDOMNodeImpl::AddEventListener(const CefString& eventType,
CefRefPtr<CefDOMEventListener> listener,
bool useCapture)
{
if (!VerifyContext())
return;
node_.addEventListener(string16(eventType),
new CefDOMEventListenerWrapper(document_->GetBrowser(),
document_->GetFrame(), listener),
useCapture);
}
CefString CefDOMNodeImpl::GetElementTagName()
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& tagname = element.tagName();
if (!tagname.isNull())
str = tagname;
return str;
}
bool CefDOMNodeImpl::HasElementAttributes()
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
const WebElement& element = node_.to<WebKit::WebElement>();
return (element.attributes().length() > 0);
}
bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName)
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
const WebElement& element = node_.to<WebKit::WebElement>();
return element.hasAttribute(string16(attrName));
}
CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName)
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& attr = element.getAttribute(string16(attrName));
if (!attr.isNull())
str = attr;
return str;
}
void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap)
{
if (!VerifyContext())
return;
if (!node_.isElementNode()) {
NOTREACHED();
return;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebNamedNodeMap& map = element.attributes();
unsigned int len = map.length();
if (len == 0)
return;
string16 nameStr, valueStr;
for (unsigned int i = 0; i < len; ++i) {
const WebAttribute& attrib = map.attributeItem(i);
string16 nameStr, valueStr;
const WebString& name = attrib.localName();
if (!name.isNull())
nameStr = name;
const WebString& value = attrib.value();
if (!value.isNull())
valueStr = value;
attrMap.insert(std::make_pair(nameStr, valueStr));
}
}
bool CefDOMNodeImpl::SetElementAttribute(const CefString& attrName,
const CefString& value)
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
WebElement element = node_.to<WebKit::WebElement>();
return element.setAttribute(string16(attrName), string16(value));
}
CefString CefDOMNodeImpl::GetElementInnerText()
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& text = element.innerText();
if (!text.isNull())
str = text;
return str;
}
void CefDOMNodeImpl::Detach()
{
document_ = NULL;
node_.assign(WebNode());
}
bool CefDOMNodeImpl::VerifyContext()
{
if (!document_.get()) {
NOTREACHED();
return false;
}
if (!document_->VerifyContext())
return false;
if(node_.isNull()) {
NOTREACHED();
return false;
}
return true;
}
<commit_msg>Add support for retrieving values from DOM form elements.<commit_after>// Copyright (c) 2011 The Chromium Embedded Framework 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 "dom_node_impl.h"
#include "browser_impl.h"
#include "cef_thread.h"
#include "dom_document_impl.h"
#include "dom_event_impl.h"
#include "tracker.h"
#include "base/logging.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAttribute.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEvent.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEventListener.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormControlElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNamedNodeMap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h"
#include "webkit/glue/form_field.h"
using WebKit::WebAttribute;
using WebKit::WebDocument;
using WebKit::WebDOMEvent;
using WebKit::WebDOMEventListener;
using WebKit::WebElement;
using WebKit::WebFrame;
using WebKit::WebFormControlElement;
using WebKit::WebNamedNodeMap;
using WebKit::WebNode;
using WebKit::WebString;
namespace {
// Wrapper implementation for WebDOMEventListener.
class CefDOMEventListenerWrapper : public WebDOMEventListener,
public CefTrackObject
{
public:
CefDOMEventListenerWrapper(CefBrowserImpl* browser, WebFrame* frame,
CefRefPtr<CefDOMEventListener> listener)
: browser_(browser), frame_(frame), listener_(listener)
{
// Cause this object to be deleted immediately before the frame is closed.
browser->UIT_AddFrameObject(frame, this);
}
virtual ~CefDOMEventListenerWrapper()
{
REQUIRE_UIT();
}
virtual void handleEvent(const WebDOMEvent& event)
{
CefRefPtr<CefDOMDocumentImpl> documentImpl;
CefRefPtr<CefDOMEventImpl> eventImpl;
if (!event.isNull()) {
// Create CefDOMDocumentImpl and CefDOMEventImpl objects that are valid
// only for the scope of this method.
const WebDocument& document = frame_->document();
if (!document.isNull()) {
documentImpl = new CefDOMDocumentImpl(browser_, frame_);
eventImpl = new CefDOMEventImpl(documentImpl, event);
}
}
listener_->HandleEvent(eventImpl.get());
if(eventImpl.get())
eventImpl->Detach();
if (documentImpl.get())
documentImpl->Detach();
}
protected:
CefBrowserImpl* browser_;
WebFrame* frame_;
CefRefPtr<CefDOMEventListener> listener_;
};
} // namespace
CefDOMNodeImpl::CefDOMNodeImpl(CefRefPtr<CefDOMDocumentImpl> document,
const WebKit::WebNode& node)
: document_(document), node_(node)
{
}
CefDOMNodeImpl::~CefDOMNodeImpl()
{
REQUIRE_UIT();
if (document_.get() && !node_.isNull()) {
// Remove the node from the document.
document_->RemoveNode(node_);
}
}
CefDOMNodeImpl::Type CefDOMNodeImpl::GetType()
{
if (!VerifyContext())
return DOM_NODE_TYPE_UNSUPPORTED;
switch (node_.nodeType()) {
case WebNode::ElementNode:
return DOM_NODE_TYPE_ELEMENT;
case WebNode::AttributeNode:
return DOM_NODE_TYPE_ATTRIBUTE;
case WebNode::TextNode:
return DOM_NODE_TYPE_TEXT;
case WebNode::CDataSectionNode:
return DOM_NODE_TYPE_CDATA_SECTION;
case WebNode::EntityReferenceNode:
return DOM_NODE_TYPE_ENTITY_REFERENCE;
case WebNode::EntityNode:
return DOM_NODE_TYPE_ENTITY;
case WebNode::ProcessingInstructionsNode:
return DOM_NODE_TYPE_PROCESSING_INSTRUCTIONS;
case WebNode::CommentNode:
return DOM_NODE_TYPE_COMMENT;
case WebNode::DocumentNode:
return DOM_NODE_TYPE_DOCUMENT;
case WebNode::DocumentTypeNode:
return DOM_NODE_TYPE_DOCUMENT_TYPE;
case WebNode::DocumentFragmentNode:
return DOM_NODE_TYPE_DOCUMENT_FRAGMENT;
case WebNode::NotationNode:
return DOM_NODE_TYPE_NOTATION;
case WebNode::XPathNamespaceNode:
return DOM_NODE_TYPE_XPATH_NAMESPACE;
default:
return DOM_NODE_TYPE_UNSUPPORTED;
}
}
bool CefDOMNodeImpl::IsText()
{
if (!VerifyContext())
return false;
return node_.isTextNode();
}
bool CefDOMNodeImpl::IsElement()
{
if (!VerifyContext())
return false;
return node_.isElementNode();
}
CefString CefDOMNodeImpl::GetName()
{
CefString str;
if (!VerifyContext())
return str;
const WebString& name = node_.nodeName();
if (!name.isNull())
str = name;
return str;
}
CefString CefDOMNodeImpl::GetValue()
{
CefString str;
if (!VerifyContext())
return str;
if (node_.isElementNode()) {
const WebElement& element = node_.to<WebKit::WebElement>();
if (element.isFormControlElement()) {
// Retrieve the value from the form control element.
const WebFormControlElement& formElement =
node_.to<WebKit::WebFormControlElement>();
webkit_glue::FormField formField(formElement);
str = formField.value();
}
}
if (str.empty()) {
const WebString& value = node_.nodeValue();
if (!value.isNull())
str = value;
}
return str;
}
bool CefDOMNodeImpl::SetValue(const CefString& value)
{
if (!VerifyContext())
return false;
if (node_.isElementNode())
return false;
return node_.setNodeValue(string16(value));
}
CefString CefDOMNodeImpl::GetAsMarkup()
{
CefString str;
if (!VerifyContext())
return str;
const WebString& markup = node_.createMarkup();
if (!markup.isNull())
str = markup;
return str;
}
CefRefPtr<CefDOMDocument> CefDOMNodeImpl::GetDocument()
{
if (!VerifyContext())
return NULL;
return document_.get();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetParent()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.parentNode());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetPreviousSibling()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.previousSibling());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetNextSibling()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.nextSibling());
}
bool CefDOMNodeImpl::HasChildren()
{
if (!VerifyContext())
return false;
return node_.hasChildNodes();
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetFirstChild()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.firstChild());
}
CefRefPtr<CefDOMNode> CefDOMNodeImpl::GetLastChild()
{
if (!VerifyContext())
return NULL;
return document_->GetOrCreateNode(node_.lastChild());
}
void CefDOMNodeImpl::AddEventListener(const CefString& eventType,
CefRefPtr<CefDOMEventListener> listener,
bool useCapture)
{
if (!VerifyContext())
return;
node_.addEventListener(string16(eventType),
new CefDOMEventListenerWrapper(document_->GetBrowser(),
document_->GetFrame(), listener),
useCapture);
}
CefString CefDOMNodeImpl::GetElementTagName()
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& tagname = element.tagName();
if (!tagname.isNull())
str = tagname;
return str;
}
bool CefDOMNodeImpl::HasElementAttributes()
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
const WebElement& element = node_.to<WebKit::WebElement>();
return (element.attributes().length() > 0);
}
bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName)
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
const WebElement& element = node_.to<WebKit::WebElement>();
return element.hasAttribute(string16(attrName));
}
CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName)
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& attr = element.getAttribute(string16(attrName));
if (!attr.isNull())
str = attr;
return str;
}
void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap)
{
if (!VerifyContext())
return;
if (!node_.isElementNode()) {
NOTREACHED();
return;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebNamedNodeMap& map = element.attributes();
unsigned int len = map.length();
if (len == 0)
return;
string16 nameStr, valueStr;
for (unsigned int i = 0; i < len; ++i) {
const WebAttribute& attrib = map.attributeItem(i);
string16 nameStr, valueStr;
const WebString& name = attrib.localName();
if (!name.isNull())
nameStr = name;
const WebString& value = attrib.value();
if (!value.isNull())
valueStr = value;
attrMap.insert(std::make_pair(nameStr, valueStr));
}
}
bool CefDOMNodeImpl::SetElementAttribute(const CefString& attrName,
const CefString& value)
{
if (!VerifyContext())
return false;
if (!node_.isElementNode()) {
NOTREACHED();
return false;
}
WebElement element = node_.to<WebKit::WebElement>();
return element.setAttribute(string16(attrName), string16(value));
}
CefString CefDOMNodeImpl::GetElementInnerText()
{
CefString str;
if (!VerifyContext())
return str;
if (!node_.isElementNode()) {
NOTREACHED();
return str;
}
const WebElement& element = node_.to<WebKit::WebElement>();
const WebString& text = element.innerText();
if (!text.isNull())
str = text;
return str;
}
void CefDOMNodeImpl::Detach()
{
document_ = NULL;
node_.assign(WebNode());
}
bool CefDOMNodeImpl::VerifyContext()
{
if (!document_.get()) {
NOTREACHED();
return false;
}
if (!document_->VerifyContext())
return false;
if(node_.isNull()) {
NOTREACHED();
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 08:17:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "UriSchemeParser_vndDOTsunDOTstarDOTscript.hxx"
#include "UriReference.hxx"
#include "supportsService.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/uri/XUriReference.hpp"
#include "com/sun/star/uri/XUriSchemeParser.hpp"
#include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <new>
namespace css = com::sun::star;
namespace {
int getHexWeight(sal_Unicode c) {
return c >= '0' && c <= '9' ? static_cast< int >(c - '0')
: c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10)
: c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10)
: -1;
}
int parseEscaped(rtl::OUString const & part, sal_Int32 * index) {
if (part.getLength() - *index < 3 || part[*index] != '%') {
return -1;
}
int n1 = getHexWeight(part[*index + 1]);
int n2 = getHexWeight(part[*index + 2]);
if (n1 < 0 || n2 < 0) {
return -1;
}
*index += 3;
return (n1 << 4) | n2;
}
rtl::OUString parsePart(
rtl::OUString const & part, bool namePart, sal_Int32 * index)
{
rtl::OUStringBuffer buf;
while (*index < part.getLength()) {
sal_Unicode c = part[*index];
if (namePart ? c == '?' : c == '&' || c == '=') {
break;
} else if (c == '%') {
sal_Int32 i = *index;
int n = parseEscaped(part, &i);
if (n >= 0 && n <= 0x7F) {
buf.append(static_cast< sal_Unicode >(n));
} else if (n >= 0xC0 && n <= 0xFC) {
sal_Int32 encoded;
int shift;
sal_Int32 min;
if (n <= 0xDF) {
encoded = (n & 0x1F) << 6;
shift = 0;
min = 0x80;
} else if (n <= 0xEF) {
encoded = (n & 0x0F) << 12;
shift = 6;
min = 0x800;
} else if (n <= 0xF7) {
encoded = (n & 0x07) << 18;
shift = 12;
min = 0x10000;
} else if (n <= 0xFB) {
encoded = (n & 0x03) << 24;
shift = 18;
min = 0x200000;
} else {
encoded = 0;
shift = 24;
min = 0x4000000;
}
bool utf8 = true;
for (; shift >= 0; shift -= 6) {
n = parseEscaped(part, &i);
if (n < 0x80 || n > 0xBF) {
utf8 = false;
break;
}
encoded |= (n & 0x3F) << shift;
}
if (!utf8 || encoded < min
|| encoded >= 0xD800 && encoded <= 0xDFFF
|| encoded > 0x10FFFF)
{
break;
}
if (encoded <= 0xFFFF) {
buf.append(static_cast< sal_Unicode >(encoded));
} else {
buf.append(static_cast< sal_Unicode >(
(encoded >> 10) | 0xD800));
buf.append(static_cast< sal_Unicode >(
(encoded & 0x3FF) | 0xDC00));
}
} else {
break;
}
*index = i;
} else {
buf.append(c);
++*index;
}
}
return buf.makeStringAndClear();
}
bool parseSchemeSpecificPart(rtl::OUString const & part) {
sal_Int32 len = part.getLength();
sal_Int32 i = 0;
if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') {
return false;
}
if (i == len) {
return true;
}
for (;;) {
++i; // skip '?' or '&'
if (parsePart(part, false, &i).getLength() == 0 || i == len
|| part[i] != '=')
{
return false;
}
++i;
parsePart(part, false, &i);
if (i == len) {
return true;
}
if (part[i] != '&') {
return false;
}
}
}
class UrlReference:
public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference >
{
public:
UrlReference(rtl::OUString const & scheme, rtl::OUString const & path):
m_base(
scheme, false, false, rtl::OUString(), path, false, rtl::OUString())
{}
virtual rtl::OUString SAL_CALL getUriReference()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getUriReference(); }
virtual sal_Bool SAL_CALL isAbsolute()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.isAbsolute(); }
virtual rtl::OUString SAL_CALL getScheme()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getScheme(); }
virtual rtl::OUString SAL_CALL getSchemeSpecificPart()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getSchemeSpecificPart(); }
virtual sal_Bool SAL_CALL isHierarchical()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.isHierarchical(); }
virtual sal_Bool SAL_CALL hasAuthority()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasAuthority(); }
virtual rtl::OUString SAL_CALL getAuthority()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getAuthority(); }
virtual rtl::OUString SAL_CALL getPath()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPath(); }
virtual sal_Bool SAL_CALL hasRelativePath()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasRelativePath(); }
virtual sal_Int32 SAL_CALL getPathSegmentCount()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPathSegmentCount(); }
virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index)
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPathSegment(index); }
virtual sal_Bool SAL_CALL hasQuery()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasQuery(); }
virtual rtl::OUString SAL_CALL getQuery()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getQuery(); }
virtual sal_Bool SAL_CALL hasFragment()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasFragment(); }
virtual rtl::OUString SAL_CALL getFragment()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getFragment(); }
virtual void SAL_CALL setFragment(rtl::OUString const & fragment)
throw (com::sun::star::uno::RuntimeException)
{ m_base.setFragment(fragment); }
virtual void SAL_CALL clearFragment()
throw (com::sun::star::uno::RuntimeException)
{ m_base.clearFragment(); }
virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException);
virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException);
private:
UrlReference(UrlReference &); // not implemented
void operator =(UrlReference); // not implemented
virtual ~UrlReference() {}
sal_Int32 findParameter(rtl::OUString const & key);
stoc::uriproc::UriReference m_base;
};
rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) {
osl::MutexGuard g(m_base.m_mutex);
sal_Int32 i = 0;
return parsePart(m_base.m_path, true, &i);
}
sal_Bool UrlReference::hasParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException)
{
osl::MutexGuard g(m_base.m_mutex);
return findParameter(key) >= 0;
}
rtl::OUString UrlReference::getParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException)
{
osl::MutexGuard g(m_base.m_mutex);
sal_Int32 i = findParameter(key);
return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString();
}
sal_Int32 UrlReference::findParameter(rtl::OUString const & key) {
sal_Int32 i = 0;
parsePart(m_base.m_path, true, &i); // skip name
for (;;) {
if (i == m_base.m_path.getLength()) {
return -1;
}
++i; // skip '?' or '&'
rtl::OUString k = parsePart(m_base.m_path, false, &i);
++i; // skip '='
if (k == key) {
return i;
}
parsePart(m_base.m_path, false, &i); // skip value
}
}
class Parser: public cppu::WeakImplHelper2<
css::lang::XServiceInfo, css::uri::XUriSchemeParser >
{
public:
Parser() {}
virtual rtl::OUString SAL_CALL getImplementationName()
throw (css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
throw (css::uno::RuntimeException);
virtual css::uno::Sequence< rtl::OUString > SAL_CALL
getSupportedServiceNames() throw (css::uno::RuntimeException);
virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL
parse(
rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
throw (css::uno::RuntimeException);
private:
Parser(Parser &); // not implemented
void operator =(Parser); // not implemented
virtual ~Parser() {}
};
rtl::OUString Parser::getImplementationName()
throw (css::uno::RuntimeException)
{
return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
getImplementationName();
}
sal_Bool Parser::supportsService(rtl::OUString const & serviceName)
throw (css::uno::RuntimeException)
{
return stoc::uriproc::supportsService(
getSupportedServiceNames(), serviceName);
}
css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames()
throw (css::uno::RuntimeException)
{
return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
getSupportedServiceNames();
}
css::uno::Reference< css::uri::XUriReference >
Parser::parse(
rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
throw (css::uno::RuntimeException)
{
if (!parseSchemeSpecificPart(schemeSpecificPart)) {
return 0;
}
try {
return new UrlReference(scheme, schemeSpecificPart);
} catch (std::bad_alloc &) {
throw css::uno::RuntimeException(
rtl::OUString::createFromAscii("std::bad_alloc"), 0);
}
}
}
namespace stoc { namespace uriproc {
namespace UriSchemeParser_vndDOTsunDOTstarDOTscript {
css::uno::Reference< css::uno::XInterface > create(
css::uno::Reference< css::uno::XComponentContext > const &)
SAL_THROW((css::uno::Exception))
{
//TODO: single instance
try {
return static_cast< cppu::OWeakObject * >(new Parser);
} catch (std::bad_alloc &) {
throw css::uno::RuntimeException(
rtl::OUString::createFromAscii("std::bad_alloc"), 0);
}
}
rtl::OUString getImplementationName() {
return rtl::OUString::createFromAscii(
"com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
}
css::uno::Sequence< rtl::OUString > getSupportedServiceNames() {
css::uno::Sequence< rtl::OUString > s(1);
s[0] = rtl::OUString::createFromAscii(
"com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
return s;
}
} } }
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.36); FILE MERGED 2006/09/01 17:41:19 kaib 1.4.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 17:38:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"
#include "UriSchemeParser_vndDOTsunDOTstarDOTscript.hxx"
#include "UriReference.hxx"
#include "supportsService.hxx"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/uri/XUriReference.hpp"
#include "com/sun/star/uri/XUriSchemeParser.hpp"
#include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <new>
namespace css = com::sun::star;
namespace {
int getHexWeight(sal_Unicode c) {
return c >= '0' && c <= '9' ? static_cast< int >(c - '0')
: c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10)
: c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10)
: -1;
}
int parseEscaped(rtl::OUString const & part, sal_Int32 * index) {
if (part.getLength() - *index < 3 || part[*index] != '%') {
return -1;
}
int n1 = getHexWeight(part[*index + 1]);
int n2 = getHexWeight(part[*index + 2]);
if (n1 < 0 || n2 < 0) {
return -1;
}
*index += 3;
return (n1 << 4) | n2;
}
rtl::OUString parsePart(
rtl::OUString const & part, bool namePart, sal_Int32 * index)
{
rtl::OUStringBuffer buf;
while (*index < part.getLength()) {
sal_Unicode c = part[*index];
if (namePart ? c == '?' : c == '&' || c == '=') {
break;
} else if (c == '%') {
sal_Int32 i = *index;
int n = parseEscaped(part, &i);
if (n >= 0 && n <= 0x7F) {
buf.append(static_cast< sal_Unicode >(n));
} else if (n >= 0xC0 && n <= 0xFC) {
sal_Int32 encoded;
int shift;
sal_Int32 min;
if (n <= 0xDF) {
encoded = (n & 0x1F) << 6;
shift = 0;
min = 0x80;
} else if (n <= 0xEF) {
encoded = (n & 0x0F) << 12;
shift = 6;
min = 0x800;
} else if (n <= 0xF7) {
encoded = (n & 0x07) << 18;
shift = 12;
min = 0x10000;
} else if (n <= 0xFB) {
encoded = (n & 0x03) << 24;
shift = 18;
min = 0x200000;
} else {
encoded = 0;
shift = 24;
min = 0x4000000;
}
bool utf8 = true;
for (; shift >= 0; shift -= 6) {
n = parseEscaped(part, &i);
if (n < 0x80 || n > 0xBF) {
utf8 = false;
break;
}
encoded |= (n & 0x3F) << shift;
}
if (!utf8 || encoded < min
|| encoded >= 0xD800 && encoded <= 0xDFFF
|| encoded > 0x10FFFF)
{
break;
}
if (encoded <= 0xFFFF) {
buf.append(static_cast< sal_Unicode >(encoded));
} else {
buf.append(static_cast< sal_Unicode >(
(encoded >> 10) | 0xD800));
buf.append(static_cast< sal_Unicode >(
(encoded & 0x3FF) | 0xDC00));
}
} else {
break;
}
*index = i;
} else {
buf.append(c);
++*index;
}
}
return buf.makeStringAndClear();
}
bool parseSchemeSpecificPart(rtl::OUString const & part) {
sal_Int32 len = part.getLength();
sal_Int32 i = 0;
if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') {
return false;
}
if (i == len) {
return true;
}
for (;;) {
++i; // skip '?' or '&'
if (parsePart(part, false, &i).getLength() == 0 || i == len
|| part[i] != '=')
{
return false;
}
++i;
parsePart(part, false, &i);
if (i == len) {
return true;
}
if (part[i] != '&') {
return false;
}
}
}
class UrlReference:
public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference >
{
public:
UrlReference(rtl::OUString const & scheme, rtl::OUString const & path):
m_base(
scheme, false, false, rtl::OUString(), path, false, rtl::OUString())
{}
virtual rtl::OUString SAL_CALL getUriReference()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getUriReference(); }
virtual sal_Bool SAL_CALL isAbsolute()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.isAbsolute(); }
virtual rtl::OUString SAL_CALL getScheme()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getScheme(); }
virtual rtl::OUString SAL_CALL getSchemeSpecificPart()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getSchemeSpecificPart(); }
virtual sal_Bool SAL_CALL isHierarchical()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.isHierarchical(); }
virtual sal_Bool SAL_CALL hasAuthority()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasAuthority(); }
virtual rtl::OUString SAL_CALL getAuthority()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getAuthority(); }
virtual rtl::OUString SAL_CALL getPath()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPath(); }
virtual sal_Bool SAL_CALL hasRelativePath()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasRelativePath(); }
virtual sal_Int32 SAL_CALL getPathSegmentCount()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPathSegmentCount(); }
virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index)
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getPathSegment(index); }
virtual sal_Bool SAL_CALL hasQuery()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasQuery(); }
virtual rtl::OUString SAL_CALL getQuery()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getQuery(); }
virtual sal_Bool SAL_CALL hasFragment()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.hasFragment(); }
virtual rtl::OUString SAL_CALL getFragment()
throw (com::sun::star::uno::RuntimeException)
{ return m_base.getFragment(); }
virtual void SAL_CALL setFragment(rtl::OUString const & fragment)
throw (com::sun::star::uno::RuntimeException)
{ m_base.setFragment(fragment); }
virtual void SAL_CALL clearFragment()
throw (com::sun::star::uno::RuntimeException)
{ m_base.clearFragment(); }
virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException);
virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException);
private:
UrlReference(UrlReference &); // not implemented
void operator =(UrlReference); // not implemented
virtual ~UrlReference() {}
sal_Int32 findParameter(rtl::OUString const & key);
stoc::uriproc::UriReference m_base;
};
rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) {
osl::MutexGuard g(m_base.m_mutex);
sal_Int32 i = 0;
return parsePart(m_base.m_path, true, &i);
}
sal_Bool UrlReference::hasParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException)
{
osl::MutexGuard g(m_base.m_mutex);
return findParameter(key) >= 0;
}
rtl::OUString UrlReference::getParameter(rtl::OUString const & key)
throw (css::uno::RuntimeException)
{
osl::MutexGuard g(m_base.m_mutex);
sal_Int32 i = findParameter(key);
return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString();
}
sal_Int32 UrlReference::findParameter(rtl::OUString const & key) {
sal_Int32 i = 0;
parsePart(m_base.m_path, true, &i); // skip name
for (;;) {
if (i == m_base.m_path.getLength()) {
return -1;
}
++i; // skip '?' or '&'
rtl::OUString k = parsePart(m_base.m_path, false, &i);
++i; // skip '='
if (k == key) {
return i;
}
parsePart(m_base.m_path, false, &i); // skip value
}
}
class Parser: public cppu::WeakImplHelper2<
css::lang::XServiceInfo, css::uri::XUriSchemeParser >
{
public:
Parser() {}
virtual rtl::OUString SAL_CALL getImplementationName()
throw (css::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
throw (css::uno::RuntimeException);
virtual css::uno::Sequence< rtl::OUString > SAL_CALL
getSupportedServiceNames() throw (css::uno::RuntimeException);
virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL
parse(
rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
throw (css::uno::RuntimeException);
private:
Parser(Parser &); // not implemented
void operator =(Parser); // not implemented
virtual ~Parser() {}
};
rtl::OUString Parser::getImplementationName()
throw (css::uno::RuntimeException)
{
return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
getImplementationName();
}
sal_Bool Parser::supportsService(rtl::OUString const & serviceName)
throw (css::uno::RuntimeException)
{
return stoc::uriproc::supportsService(
getSupportedServiceNames(), serviceName);
}
css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames()
throw (css::uno::RuntimeException)
{
return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
getSupportedServiceNames();
}
css::uno::Reference< css::uri::XUriReference >
Parser::parse(
rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
throw (css::uno::RuntimeException)
{
if (!parseSchemeSpecificPart(schemeSpecificPart)) {
return 0;
}
try {
return new UrlReference(scheme, schemeSpecificPart);
} catch (std::bad_alloc &) {
throw css::uno::RuntimeException(
rtl::OUString::createFromAscii("std::bad_alloc"), 0);
}
}
}
namespace stoc { namespace uriproc {
namespace UriSchemeParser_vndDOTsunDOTstarDOTscript {
css::uno::Reference< css::uno::XInterface > create(
css::uno::Reference< css::uno::XComponentContext > const &)
SAL_THROW((css::uno::Exception))
{
//TODO: single instance
try {
return static_cast< cppu::OWeakObject * >(new Parser);
} catch (std::bad_alloc &) {
throw css::uno::RuntimeException(
rtl::OUString::createFromAscii("std::bad_alloc"), 0);
}
}
rtl::OUString getImplementationName() {
return rtl::OUString::createFromAscii(
"com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
}
css::uno::Sequence< rtl::OUString > getSupportedServiceNames() {
css::uno::Sequence< rtl::OUString > s(1);
s[0] = rtl::OUString::createFromAscii(
"com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
return s;
}
} } }
<|endoftext|>
|
<commit_before>#pragma once
#include <gcl/mp/meta/functional.hpp>
namespace gcl::mp
{
template <std::size_t index>
struct type_index {};
template <typename... types>
struct tuple {
constexpr static auto size = sizeof...(types);
constexpr static auto empty = size == 0;
template <std::size_t index>
constexpr static auto valid_index = not empty and index <= (size - 1);
constexpr tuple() requires(not empty)
: storage{generate_storage(types{}...)}
{}
constexpr tuple(types&&... values)
: storage{generate_storage(std::forward<decltype(values)>(values)...)}
{}
constexpr tuple(tuple&&) = default;
private:
// storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
using index_sequence = std::make_index_sequence<sizeof...(types)>;
static constexpr auto generate_storage(types&&... values)
{ // defer parameter pack expansion (msvc-cl, Clang)
return generate_storage_impl(index_sequence{}, std::forward<decltype(values)>(values)...);
}
template <std::size_t... indexes>
static constexpr auto generate_storage_impl(std::index_sequence<indexes...>, types&&... values)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) constexpr mutable noexcept -> auto&& { return value; };
};
return gcl::mp::meta::functional::overload{
generate_storage_entry.template operator()<types, indexes>(std::forward<decltype(values)>(values))...};
};
using storage_type = decltype(generate_storage(types{}...));
mutable storage_type storage;
template <std::size_t index>
requires(valid_index<index>)
struct type_at_impl { // defer symbol (Clang)
using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
};
public:
template <std::size_t index>
requires(valid_index<index>)
using type_at = typename type_at_impl<index>::type;
template <std::size_t index>
requires(valid_index<index>)
constexpr auto& get() & noexcept
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(valid_index<index>) constexpr const auto& get() const& noexcept
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(valid_index<index>) constexpr auto&& get() && noexcept
{
return std::move(storage(type_index<index>{}));
}
template <std::size_t index>
requires(valid_index<index>) constexpr const auto&& get() const&& noexcept
{
return std::move(storage(type_index<index>{}));
}
template <typename... arg_types>
requires(sizeof...(arg_types) == size) constexpr bool operator==(
const tuple<arg_types...>& other) const noexcept
{
return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
return (((get<indexes>() == other.template get<indexes>()) && ...));
}
(std::make_index_sequence<size>{});
}
};
// When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :
/*static constexpr auto generate_storage(types&&... values)
{
return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
std::forward<decltype(values)>(values))...};
}
(std::make_index_sequence<sizeof...(types)>{});
};*/
}
namespace gcl::mp
{
template <std::size_t I, class... Types>
constexpr auto & get(tuple<Types...>& value) noexcept
{
return value.template get<I>();
}
template <std::size_t I, class... Types>
constexpr auto && get(tuple<Types...>&& value) noexcept
{
return std::move(value.template get<I>());
}
template <std::size_t I, class... Types>
constexpr auto const& get(const tuple<Types...>& value) noexcept
{
return value.template get<I>();
}
template <std::size_t I, class... Types>
constexpr auto const&& get(const tuple<Types...>&& value) noexcept
{
return std::move(value.template get<I>());
}
template <class...>
struct tuple_size;
template <class... Types>
struct tuple_size<tuple<Types...>> : std::integral_constant<std::size_t, sizeof...(Types)> {};
template <class T>
constexpr auto tuple_size_v = tuple_size<T>::value;
template <class T, class... Types>
constexpr T& get(tuple<Types...>& value) noexcept;
template <class T, class... Types>
constexpr T&& get(tuple<Types...>&& value) noexcept;
template <class T, class... Types>
constexpr const T& get(const tuple<Types...>& value) noexcept;
template <class T, class... Types>
constexpr const T&& get(const tuple<Types...>&& value) noexcept;
}
#if defined(GCL_ENABLE_COMPILE_TIME_TESTS)
#include <stdexcept>
#include <exception>
namespace gcl::mp::tests::tuples::values
{
using namespace gcl::mp;
using empty_tuple = tuple<>;
using one_element_tuple = tuple<int>;
using two_element_tuple = tuple<int, char>;
static constexpr auto empty_tuple_default_init = empty_tuple{};
static constexpr auto one_element_tuple_default_init = one_element_tuple{};
static constexpr auto two_element_tuple_default_init = two_element_tuple{};
static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};
static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);
static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&>().get<0>()), int&>);
static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&&>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&&>().get<0>()), int&&>);
void non_literal_type(){
struct can_throw_constructor {
can_throw_constructor() { throw std::runtime_error{""}; };
};
using faillible_tuple = tuple<can_throw_constructor>;
[[maybe_unused]] const auto faillible_tuple_default_init = faillible_tuple{};
[[maybe_unused]] const auto faillible_tuple_value_init = faillible_tuple{can_throw_constructor{}};
}
}
namespace gcl::mp::tests::tuples::get
{
using namespace gcl::mp;
using tuple_type = tuple<int, char>;
static_assert(std::is_same_v<char&, decltype(std::declval<tuple_type&>().get<1>())>);
static_assert(std::is_same_v<char&&, decltype(std::declval<tuple_type&&>().get<1>())>);
static_assert(std::is_same_v<const char&, decltype(std::declval<const tuple_type&>().get<1>())>);
static_assert(std::is_same_v<const char&&, decltype(std::declval<const tuple_type&&>().get<1>())>);
static_assert(std::is_same_v<char&, decltype(gcl::mp::get<1>(std::declval<tuple_type&>()))>);
static_assert(std::is_same_v<char&&, decltype(gcl::mp::get<1>(std::declval<tuple_type&&>()))>);
static_assert(std::is_same_v<const char&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&>()))>);
static_assert(std::is_same_v<const char&&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&&>()))>);
}
namespace gcl::mp::tests::tuples::size
{
using namespace gcl::mp;
using tuple_type = tuple<int, char>;
static_assert(tuple<>::size == 0);
static_assert(tuple<>::size == tuple_size_v<tuple<>>);
static_assert(tuple_type::size == 2);
static_assert(tuple_type::size == tuple_size_v<tuple_type>);
}
#endif<commit_msg>[mp/meta/tuple] : tuple_element<commit_after>#pragma once
#include <gcl/mp/meta/functional.hpp>
#include <type_traits>
// todo : filter, apply, for_each, for_each_index
namespace gcl::mp
{
template <std::size_t index>
struct type_index {};
template <typename... types>
struct tuple {
constexpr static auto size = sizeof...(types);
constexpr static auto empty = size == 0;
template <std::size_t index>
constexpr static auto valid_index = not empty and index <= (size - 1);
constexpr tuple() requires(not empty)
: storage{generate_storage(types{}...)}
{}
constexpr tuple(types&&... values)
: storage{generate_storage(std::forward<decltype(values)>(values)...)}
{}
constexpr tuple(tuple&&) = default;
private:
// storage : by-pass missing features : auto non-static members, lambdas in unevaluated context
using index_sequence = std::make_index_sequence<sizeof...(types)>;
static constexpr auto generate_storage(types&&... values)
{ // defer parameter pack expansion (msvc-cl, Clang)
return generate_storage_impl(index_sequence{}, std::forward<decltype(values)>(values)...);
}
template <std::size_t... indexes>
static constexpr auto generate_storage_impl(std::index_sequence<indexes...>, types&&... values)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) constexpr mutable noexcept -> auto&& { return value; };
};
return gcl::mp::meta::functional::overload{
generate_storage_entry.template operator()<types, indexes>(std::forward<decltype(values)>(values))...};
};
using storage_type = decltype(generate_storage(types{}...));
mutable storage_type storage;
template <std::size_t index>
requires(valid_index<index>)
struct type_at_impl { // defer symbol (Clang)
using type = std::remove_reference_t<decltype(std::declval<tuple>().template get<index>())>;
};
public:
template <std::size_t index>
requires(valid_index<index>)
using type_at = typename type_at_impl<index>::type;
template <std::size_t index>
requires(valid_index<index>)
constexpr auto& get() & noexcept
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(valid_index<index>) [[nodiscard]] constexpr const auto& get() const& noexcept
{
return storage(type_index<index>{});
}
template <std::size_t index>
requires(valid_index<index>) [[nodiscard]] constexpr auto&& get() && noexcept
{
return std::move(storage(type_index<index>{}));
}
template <std::size_t index>
requires(valid_index<index>) [[nodiscard]] constexpr const auto&& get() const&& noexcept
{
return std::move(storage(type_index<index>{}));
}
template <typename... arg_types>
requires(sizeof...(arg_types) == size) constexpr bool operator==(
const tuple<arg_types...>& other) const noexcept
{
return [ this, &other ]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
return (((get<indexes>() == other.template get<indexes>()) && ...));
}
(std::make_index_sequence<size>{});
}
};
// When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :
/*static constexpr auto generate_storage(types&&... values)
{
return [&values...]<std::size_t... indexes>(std::index_sequence<indexes...>)
{
static_assert(sizeof...(indexes) == sizeof...(types));
static_assert(sizeof...(indexes) == sizeof...(values));
const auto generate_storage_entry = []<typename T, std::size_t index>(T && init_value) constexpr
{
return [value = init_value](type_index<index>) mutable -> auto& { return value; };
};
return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()<types, indexes>(
std::forward<decltype(values)>(values))...};
}
(std::make_index_sequence<sizeof...(types)>{});
};*/
}
namespace gcl::mp
{
template <std::size_t I, class... Types>
[[nodiscard]] constexpr auto& get(tuple<Types...>& value) noexcept
{
return value.template get<I>();
}
template <std::size_t I, class... Types>
[[nodiscard]] constexpr auto&& get(tuple<Types...>&& value) noexcept
{
return std::move(value.template get<I>());
}
template <std::size_t I, class... Types>
[[nodiscard]] constexpr auto const& get(const tuple<Types...>& value) noexcept
{
return value.template get<I>();
}
template <std::size_t I, class... Types>
[[nodiscard]] constexpr auto const&& get(const tuple<Types...>&& value) noexcept
{
return std::move(value.template get<I>());
}
template <class tuple_type>
struct tuple_size;
template <class... Types>
struct tuple_size<tuple<Types...>> : std::integral_constant<std::size_t, sizeof...(Types)> {};
template <class T>
constexpr auto tuple_size_v = tuple_size<T>::value;
// how to implement this without recursion ?
template <std::size_t index, class tuple_type>
struct tuple_element;
template <std::size_t index, class first, class... rest>
struct tuple_element<index, tuple<first, rest...>> : tuple_element<(index - 1), tuple<rest...>> {};
template <class first, class... rest>
struct tuple_element<0, tuple<first, rest...>> {
using type = first;
};
template <size_t index>
struct tuple_element<index, tuple<>> {
static_assert([]() constexpr { return false; }(), "gcl::mp::tuple : out of range");
};
template <std::size_t index, class tuple_type>
using tuple_element_t = typename tuple_element<index, tuple_type>::type;
// https://quick-bench.com/q/va85-AzD0ppFuVO6zUTzrC1B6bE
template <class T, class... Types>
constexpr T& get(tuple<Types...>& value) noexcept;
template <class T, class... Types>
constexpr T&& get(tuple<Types...>&& value) noexcept;
template <class T, class... Types>
constexpr const T& get(const tuple<Types...>& value) noexcept;
template <class T, class... Types>
constexpr const T&& get(const tuple<Types...>&& value) noexcept;
}
#if defined(GCL_ENABLE_COMPILE_TIME_TESTS)
#include <stdexcept>
#include <exception>
namespace gcl::mp::tests::tuples::values
{
using namespace gcl::mp;
using empty_tuple = tuple<>;
using one_element_tuple = tuple<int>;
using two_element_tuple = tuple<int, char>;
static constexpr auto empty_tuple_default_init = empty_tuple{};
static constexpr auto one_element_tuple_default_init = one_element_tuple{};
static constexpr auto two_element_tuple_default_init = two_element_tuple{};
static constexpr auto one_element_tuple_values_init = one_element_tuple{42};
static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};
static_assert(std::is_same_v<tuple<int, char>, decltype(tuple{42, 'a'})>);
static_assert(std::is_same_v<two_element_tuple::type_at<0>, int>);
static_assert(std::is_same_v<two_element_tuple::type_at<1>, char>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&>().get<0>()), int&>);
static_assert(std::is_same_v<decltype(std::declval<const two_element_tuple&>().get<1>()), const char&>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple>().get<0>()), int&&>);
static_assert(std::is_same_v<decltype(std::declval<two_element_tuple&&>().get<0>()), int&&>);
void non_literal_type(){
struct can_throw_constructor {
can_throw_constructor() { throw std::runtime_error{""}; };
};
using faillible_tuple = tuple<can_throw_constructor>;
[[maybe_unused]] const auto faillible_tuple_default_init = faillible_tuple{};
[[maybe_unused]] const auto faillible_tuple_value_init = faillible_tuple{can_throw_constructor{}};
}
}
namespace gcl::mp::tests::tuples::get
{
using namespace gcl::mp;
using tuple_type = tuple<int, char>;
static_assert(std::is_same_v<char&, decltype(std::declval<tuple_type&>().get<1>())>);
static_assert(std::is_same_v<char&&, decltype(std::declval<tuple_type&&>().get<1>())>);
static_assert(std::is_same_v<const char&, decltype(std::declval<const tuple_type&>().get<1>())>);
static_assert(std::is_same_v<const char&&, decltype(std::declval<const tuple_type&&>().get<1>())>);
static_assert(std::is_same_v<char&, decltype(gcl::mp::get<1>(std::declval<tuple_type&>()))>);
static_assert(std::is_same_v<char&&, decltype(gcl::mp::get<1>(std::declval<tuple_type&&>()))>);
static_assert(std::is_same_v<const char&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&>()))>);
static_assert(std::is_same_v<const char&&, decltype(gcl::mp::get<1>(std::declval<const tuple_type&&>()))>);
}
namespace gcl::mp::tests::tuples::size
{
using namespace gcl::mp;
using tuple_type = tuple<int, char>;
static_assert(tuple<>::size == 0);
static_assert(tuple<>::size == tuple_size_v<tuple<>>);
static_assert(tuple_type::size == 2);
static_assert(tuple_type::size == tuple_size_v<tuple_type>);
}
namespace gcl::mp::tests::tuples::tuple_element
{
using namespace gcl::mp;
using tuple_type = tuple<int, char>;
static_assert(std::is_same_v<tuple_element_t<0, tuple_type>, int>);
static_assert(std::is_same_v<tuple_element_t<1, tuple_type>, char>);
}
#endif<|endoftext|>
|
<commit_before>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Holds the latest temperature value from the temperature temperature sensor
float temperature;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
// setmotor intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
pthread_t depthThread;
//pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
printf("Threads started\n");
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
printf("Depth Thread Started\n");
// Initialize pressure sensor
//pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
printf("IN the depth thread while loop\n");
// Read pressure sensor by passing calibration structure
//ms5837 = read_pressure(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
//depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
//printf("Current Depth:\t %.3f\n",depth);
//usleep(1000000);
// read IMU values from fifo file
substate.imu = read_imu_fifo();
// Write IMU data
printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: "
"%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
substate.imu.yaw, substate.imu.pitch, substate.imu.roll,
substate.imu.p, substate.imu.q, substate.imu.r,
substate.imu.sys, substate.imu.gyro, substate.imu.accel,
substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
substate.imu.z_acc);
sleep(1);
//printf("\nYawPID_err: %f Motor Percent: %f ", yaw_pid.err, motor_percent);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
/*void *navigation(void* arg)
{
printf("Nav Thread Started\n");
initialize_motors(motor_channels, HERTZ);
float yaw = 0; //Local variable for if statements
/////////////////yaw controller initialization////////////////////////////////
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.sat = YAW_SAT;
yaw_pid.dt = DT; // initialize time step
////////////////depth controller initialization///////////////////////////////
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.dt = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; // Depth controller saturation values
depth_pid.sat = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) // AUV pointed right
{
yaw = substate.imu.yaw;
}
else // AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
//calculate yaw controller output
motor_percent = marchPID(substate.imu, yaw);
// Set port motor
set_motor(0, motor_percent);
// Set starboard motor
set_motor(1, motor_percent);
// Sleep for 5 ms
usleep(5000);
}
// Turn motors off
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
/*void *safety_thread(void* arg)
{
printf("Safety Thread Started\n");
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
temperature = read_temp_fifo();
printf("Temperature: %f degC\n", temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check for leak
leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<commit_msg>gasdg<commit_after>/******************************************************************************
* Main script for the 2017 RoboFishy Scripps AUV
******************************************************************************/
#include "Mapper.h"
// Multithreading
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
// Sampling Values
#define SAMPLE_RATE 200 // sample rate of main control loop (Hz)
#define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE!
// Conversion Factors
#define UNITS_KPA 0.1 // converts pressure from mbar to kPa
/******************************************************************************
* Controller Gains
******************************************************************************/
// Yaw Controller
#define KP_YAW 0.01
#define KI_YAW 0
#define KD_YAW 1
// Depth Controller
#define KP_DEPTH 0
#define KI_DEPTH 0
#define KD_DEPTH 0
// Saturation Constants
#define YAW_SAT 1 // upper limit of yaw controller
#define DEPTH_SAT 1 // upper limit of depth controller
#define INT_SAT 10 // upper limit of integral windup
#define DINT_SAT 10 // upper limit of depth integral windup
// Filter Values
#define A1 0.3 // for MS5837 pressure sensor
#define A2 0.4 // for MS5837 pressure sensor
// Fluid Densities in kg/m^3
#define DENSITY_FRESHWATER 997
#define DENSITY_SALTWATER 1029
// Acceleration Due to Gravity in m/s^2
#define GRAVITY 9.81
// Depth Start Value
#define DEPTH_START 50 // starting depth (mm)
// Stop Timer
#define STOP_TIME 4 // seconds
// Leak Sensor Inpu and Power Pin
#define LEAKPIN 27 // connected to GPIO 27
#define LEAKPOWERPIN 17 // providing Vcc to leak board
/******************************************************************************
* Declare Threads
******************************************************************************/
void *navigation(void* arg);
void *depth_thread(void* arg);
void *safety_thread(void* arg);
/******************************************************************************
* Global Variables
******************************************************************************/
// Holds the setpoint data structure with current setpoints
//setpoint_t setpoint;
// Holds the calibration values for the MS5837 pressure sensor
pressure_calib_t pressure_calib;
// Holds the latest pressure value from the MS5837 pressure sensor
ms5837_t ms5837;
// Holds the latest temperature value from the temperature temperature sensor
float temperature;
// Holds the constants and latest errors of the yaw pid controller
pid_data_t yaw_pid;
// Holds the constants and latest errors of the depth pid controller
pid_data_t depth_pid;
// Motor channels
int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3};
// Ignoring sstate
float depth = 0;
// setmotor intialization
float motor_percent = 0;
/******************************************************************************
* Main Function
******************************************************************************/
int main()
{
// Initialize Python interpreter
Py_Initialize();
// Set up RasPi GPIO pins through wiringPi
wiringPiSetupGpio();
// Check if AUV is initialized correctly
if( initialize_sensors() < 0 )
{
return -1;
}
printf("\nAll components are initialized\n");
substate.mode = INITIALIZING;
substate.laserarmed = ARMED;
printf("Starting Threads\n");
initializeTAttr();
// Thread handles
//pthread_t navigationThread;
pthread_t depthThread;
//pthread_t safetyThread;
//pthread_t disarmlaserThread;
// Create threads using modified attributes
//pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL);
//pthread_create (&safetyThread, &tattrlow, safety_thread, NULL);
pthread_create (&depthThread, &tattrmed, depth_thread, NULL);
// Destroy the thread attributes
destroyTAttr();
printf("Threads started\n");
// Start timer!
time_t start = time(0);
// Run main while loop, wait until it's time to stop
while(substate.mode != STOPPED)
{
// Check if we've passed the stop time
if(difftime(time(0),start) > STOP_TIME)
substate.mode = STOPPED;
// Sleep a little
usleep(100000);
}
// Exit cleanly
cleanup_auv();
return 0;
}
/******************************************************************************
* Depth Thread
*
* For Recording Depth & Determining If AUV is in Water or Not
******************************************************************************/
void *depth_thread(void* arg)
{
printf("Depth Thread Started\n");
// Initialize pressure sensor
//pressure_calib = init_pressure_sensor();
while(substate.mode!=STOPPED)
{
printf("IN the depth thread while loop\n");
// Read pressure sensor by passing calibration structure
//ms5837 = read_pressure(pressure_calib);
// Calculate depth (no idea what the magic numbers are)
//depth = (ms5837.pressure-1013)*10.197-88.8; // units?
// 1013: ambient pressure (mbar)
// 10.197*p_mbar = p_mmH20
//printf("Current Depth:\t %.3f\n",depth);
//usleep(1000000);
// read IMU values from fifo file
substate.imu = read_imu_fifo();
// Write IMU data
//printf("\nYaw: %f Roll: %f Pitch: %f p: %f q: %f r: %f Sys: %i Gyro: "
// "%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ",
// substate.imu.yaw, substate.imu.pitch, substate.imu.roll,
// substate.imu.p, substate.imu.q, substate.imu.r,
// substate.imu.sys, substate.imu.gyro, substate.imu.accel,
// substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc,
// substate.imu.z_acc);
sleep(1);
printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent);
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Navigation Thread
*
* For yaw control
*****************************************************************************/
void *navigation(void* arg)
{
printf("Nav Thread Started\n");
initialize_motors(motor_channels, HERTZ);
float yaw = 0; //Local variable for if statements
/******************************************************************************
* Yaw Control Initialization
*****************************************************************************/
yaw_pid.old = 0; // Initialize old imu data
yaw_pid.setpoint = 0; // Initialize setpoint
yaw_pid.derr = 0;
yaw_pid.ierr = 0; // Initialize error values
yaw_pid.perr = 0;
yaw_pid.kp = KP_YAW;
yaw_pid.kd = KD_YAW; // Initialize gain values
yaw_pid.ki = KI_YAW;
yaw_pid.isat = INT_SAT; // Initialize saturation values
yaw_pid.sat = YAW_SAT;
yaw_pid.dt = DT; // initialize time step
/******************************************************************************
* Depth Control Initialization
*****************************************************************************/
depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters)
depth_pid.old = 0; // Initialize old depth
depth_pid.dt = DT; // Initialize depth controller time step
depth_pid.kp = KP_DEPTH;
depth_pid.kd = KD_DEPTH; // Depth controller gain initialization
depth_pid.ki = KI_DEPTH;
depth_pid.perr = 0;
depth_pid.ierr = 0; // Initialize depth controller error values
depth_pid.derr = 0;
depth_pid.isat = INT_SAT; // Depth controller saturation values
depth_pid.sat = DEPTH_SAT;
while(substate.mode!=STOPPED)
{
// read IMU values from fifo file
substate.imu = read_imu_fifo();
if (substate.imu.yaw < 180) // AUV pointed right
{
yaw = substate.imu.yaw;
}
else // AUV pointed left
{
yaw =(substate.imu.yaw-360);
}
//calculate yaw controller output
motor_percent = marchPID(substate.imu, yaw);
// Set port motor
set_motor(0, motor_percent);
// Set starboard motor
set_motor(1, motor_percent);
// Sleep for 5 ms
usleep(5000);
}
// Turn motors off
set_motor(0, 0);
set_motor(1, 0);
set_motor(2, 0);
pthread_exit(NULL);
}//*/
/******************************************************************************
* Safety Thread
*
* Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or
* water intrusion is detected
*****************************************************************************/
/*void *safety_thread(void* arg)
{
printf("Safety Thread Started\n");
// Set up WiringPi for use // (not sure if actually needed)
wiringPiSetup();
// Leak detection pins
pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT
pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc
digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc
// Leak checking variables
int leakState; // holds the state (HIGH or LOW) of the LEAKPIN
// Test if temp sensor reads anything
temperature = read_temp_fifo();
printf("Temperature: %f degC\n", temperature);
while( substate.mode != STOPPED )
{
// Check if depth threshold has been exceeded
if( substate.fdepth > DEPTH_STOP )
{
substate.mode = STOPPED;
printf("We're too deep! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check temperature
// Shut down AUV if housing temperature gets too high
if( temperature > TEMP_STOP )
{
substate.mode = STOPPED;
printf("It's too hot! Shutting down...\n");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
// Check for leak
leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN
if( leakState == HIGH )
{
substate.mode = STOPPED;
printf("LEAK DETECTED! Shutting down...\n");
continue;
}
else if (leakState == LOW)
{
// We're still good
substate.mode = RUNNING;
}
// Check IMU accelerometer for collision (1+ g detected)
if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY
|| (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY )
{
substate.mode = STOPPED;
printf("Collision detected. Shutting down...");
continue;
}
else
{
// We're still good
substate.mode = RUNNING;
}
}
pthread_exit(NULL);
}//*/
/******************************************************************************
* Logging Thread
*
* Logs the sensor output data into a file
*****************************************************************************/
/*
PI_THREAD (logging_thread)
{
while(substate.mode!=STOPPED){
FILE *fd = fopen("log.txt", "a");
char buffer[100] = {0};
// add logging values to the next line
sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0],
sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]);
fputs(buffer, fd);
fclose(fd);
//sleep for 100 ms
usleep(100000);
}
return 0;
}
*/
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <basegfx/numeric/ftools.hxx>
#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif
// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif
#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT
#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus
#if DIRECTX_VERSION < 0x0900
#include <multimon.h>
// Be compatible with directdraw 3.0. Lets see how far this takes us
#define DIRECTDRAW_VERSION 0x0300
#include <ddraw.h>
// Be compatible with direct3d 5.0. Lets see how far this takes us
#define DIRECT3D_VERSION 0x0500
#define D3D_OVERLOADS
#include <d3d.h>
typedef IDirectDrawSurface surface_type;
#else
#include <d3d9.h>
#include <d3dx9.h>
// #include <dxerr9.h> #i107614# removing include, it has been changed in the latest sdk fron August2009 from dxerr9.h into dxerr.h
typedef IDirect3DSurface9 surface_type;
#endif
#undef DrawText
#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif
#include <gdiplus.h>
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
namespace dxcanvas
{
// some shared pointer typedefs to Gdiplus objects
typedef ::boost::shared_ptr< Gdiplus::Graphics > GraphicsSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::GraphicsPath > GraphicsPathSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Bitmap > BitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::CachedBitmap > CachedBitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Font > FontSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Brush > BrushSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::TextureBrush > TextureBrushSharedPtr;
/** COM object RAII wrapper
This template wraps a Windows COM object, transparently
handling lifetime issues the C++ way (i.e. releasing the
reference when the object is destroyed)
*/
template< typename T > class COMReference
{
public:
typedef T Wrappee;
COMReference() :
mp( NULL )
{
}
/** Create from raw pointer
@attention This constructor assumes the interface is
already acquired (unless p is NULL), no additional AddRef
is called here.
This caters e.g. for all DirectX factory methods, which
return the created interfaces pre-acquired, into a raw
pointer. Simply pass the pointer to this class, but don't
call Release manually on it!
@example IDirectDrawSurface* pSurface;
pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
mpSurface = COMReference< IDirectDrawSurface >(pSurface);
*/
explicit COMReference( T* p ) :
mp( p )
{
}
COMReference( const COMReference& rNew ) :
mp( NULL )
{
if( rNew.mp == NULL )
return;
rNew.mp->AddRef(); // do that _before_ assigning the
// pointer. Just in case...
mp = rNew.mp;
}
COMReference& operator=( const COMReference& rRHS )
{
COMReference aTmp(rRHS);
::std::swap( mp, aTmp.mp );
return *this;
}
~COMReference()
{
reset();
}
int reset()
{
int refcount = 0;
if( mp )
refcount = mp->Release();
mp = NULL;
return refcount;
}
bool is() const { return mp != NULL; }
T* get() const { return mp; }
T* operator->() const { return mp; }
T& operator*() const { return *mp; }
private:
T* mp;
};
// get_pointer() enables boost::mem_fn to recognize COMReference
template<class T> inline T * get_pointer(COMReference<T> const& p)
{
return p.get();
}
}
#if defined _MSC_VER
#pragma warning(pop)
#endif
#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon
#endif /* _DXCANVAS_WINSTUFF_HXX */
<commit_msg>win32-dxsdk-200908.diff: Build also against DirectX SDK August 2009.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _DXCANVAS_WINSTUFF_HXX
#define _DXCANVAS_WINSTUFF_HXX
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <basegfx/numeric/ftools.hxx>
#ifdef _WINDOWS_
#error someone else included <windows.h>
#endif
// Enabling Direct3D Debug Information Further more, with registry key
// \\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Direct3D\D3D9Debugging\\EnableCreationStack
// set to 1, sets a backtrace each time an object is created to the
// following global variable: LPCWSTR CreationCallStack
#if OSL_DEBUG_LEVEL > 0
# define D3D_DEBUG_INFO
#endif
#ifndef DIRECTX_VERSION
#error please define for which directx version we should compile
#endif
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#define BOOL win32BOOL
#define INT32 win32INT32
#define UINT32 win32UINT32
#define GradientStyle_RECT win32GradientStyle_RECT
#define Polygon win32Polygon
#define PolyPolygon win32PolyPolygon
#undef WB_LEFT
#undef WB_RIGHT
#define WIN32_LEAN_AND_MEAN
#include <windows.h> // TODO(Q1): extract minimal set of required headers for gdiplus
#if DIRECTX_VERSION < 0x0900
#include <multimon.h>
// Be compatible with directdraw 3.0. Lets see how far this takes us
#define DIRECTDRAW_VERSION 0x0300
#include <ddraw.h>
// Be compatible with direct3d 5.0. Lets see how far this takes us
#define DIRECT3D_VERSION 0x0500
#define D3D_OVERLOADS
#include <d3d.h>
typedef IDirectDrawSurface surface_type;
#else
#include <dxsdkver.h>
#include <d3d9.h>
#include <d3dx9.h>
#if _DXSDK_BUILD_MAJOR < 1734 /* Earlier than the August 2009 DXSDK */
#include <dxerr9.h>
#else
#include <dxerr.h>
#endif
typedef IDirect3DSurface9 surface_type;
#endif
#undef DrawText
#ifdef __MINGW32__
using ::std::max;
using ::std::min;
#endif
#include <gdiplus.h>
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
namespace dxcanvas
{
// some shared pointer typedefs to Gdiplus objects
typedef ::boost::shared_ptr< Gdiplus::Graphics > GraphicsSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::GraphicsPath > GraphicsPathSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Bitmap > BitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::CachedBitmap > CachedBitmapSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Font > FontSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::Brush > BrushSharedPtr;
typedef ::boost::shared_ptr< Gdiplus::TextureBrush > TextureBrushSharedPtr;
/** COM object RAII wrapper
This template wraps a Windows COM object, transparently
handling lifetime issues the C++ way (i.e. releasing the
reference when the object is destroyed)
*/
template< typename T > class COMReference
{
public:
typedef T Wrappee;
COMReference() :
mp( NULL )
{
}
/** Create from raw pointer
@attention This constructor assumes the interface is
already acquired (unless p is NULL), no additional AddRef
is called here.
This caters e.g. for all DirectX factory methods, which
return the created interfaces pre-acquired, into a raw
pointer. Simply pass the pointer to this class, but don't
call Release manually on it!
@example IDirectDrawSurface* pSurface;
pDD->CreateSurface(&aSurfaceDesc, &pSurface, NULL);
mpSurface = COMReference< IDirectDrawSurface >(pSurface);
*/
explicit COMReference( T* p ) :
mp( p )
{
}
COMReference( const COMReference& rNew ) :
mp( NULL )
{
if( rNew.mp == NULL )
return;
rNew.mp->AddRef(); // do that _before_ assigning the
// pointer. Just in case...
mp = rNew.mp;
}
COMReference& operator=( const COMReference& rRHS )
{
COMReference aTmp(rRHS);
::std::swap( mp, aTmp.mp );
return *this;
}
~COMReference()
{
reset();
}
int reset()
{
int refcount = 0;
if( mp )
refcount = mp->Release();
mp = NULL;
return refcount;
}
bool is() const { return mp != NULL; }
T* get() const { return mp; }
T* operator->() const { return mp; }
T& operator*() const { return *mp; }
private:
T* mp;
};
// get_pointer() enables boost::mem_fn to recognize COMReference
template<class T> inline T * get_pointer(COMReference<T> const& p)
{
return p.get();
}
}
#if defined _MSC_VER
#pragma warning(pop)
#endif
#undef DELETE
#undef BOOL
#undef INT32
#undef UINT32
#undef PolyPolygon
#endif /* _DXCANVAS_WINSTUFF_HXX */
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "version.h"
const TCHAR* PluginVersionString = _T("0.1.4-alpha");
<commit_msg>Bump plugin version to 0.1.5-alpha<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "version.h"
const TCHAR* PluginVersionString = _T("0.1.5-alpha");
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2006, Lee McColl Sylvester - www.designrealm.co.uk
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT 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 HAXE PROJECT 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 "nsdl.h"
#include "nme.h"
#include <stack>
#include <string.h>
#include <SDL_ttf.h>
#include <windows.h>
#include <gl/GL.h>
using namespace std;
// helper functions
DEFINE_KIND( k_surf );
DEFINE_KIND( k_snd );
DEFINE_KIND( k_mus );
SDL_Surface* nme_loadimage( value file )
{
val_check( file, string );
SDL_Surface* surf;
surf = IMG_Load( val_string( file ) );
if ( !surf )
surf = SDL_LoadBMP( val_string( file ) );
if ( !surf )
return NULL;
//SDL_Surface *surface = SDL_DisplayFormat( surf );
//SDL_FreeSurface( surf );
return surf;
}
// creates a surface with alpha channel
value nme_create_image_32( value flags, value width, value height )
{
val_check( flags, int );
val_check( width, int );
val_check( height, int );
// return alloc_abstract( k_surf, sge_CreateAlphaSurface( val_int( flags ), val_int( width ), val_int( height ) ) );
return alloc_int(0);
}
value nme_copy_surface( value surf )
{
return alloc_int(0);
/*
val_check_kind( surf, k_surf );
SDL_Surface* scr = SURFACE(surf);
return alloc_abstract( k_surf, sge_copy_surface( scr ) );
*/
}
// surface relative functions
static value nme_surface_clear( value surf, value c )
{
val_check_kind( surf, k_surf );
val_check( c, int );
SDL_Surface* scr = SURFACE(surf);
Uint8 r = RRGB( c );
Uint8 g = GRGB( c );
Uint8 b = BRGB( c );
SDL_FillRect( scr, NULL, SDL_MapRGB( scr->format, r, g, b ) );
return alloc_int( 0 );
}
void nme_surface_free( value surface )
{
if ( val_is_kind( surface, k_surf ) )
{
val_gc( surface, NULL );
SDL_Surface* surf = SURFACE( surface );
SDL_FreeSurface( surf );
}
}
value nme_surface_colourkey( value surface, value r, value g, value b )
{
val_check_kind( surface, k_surf );
val_check( r, int );
val_check( g, int );
val_check( b, int );
SDL_Surface* surf = SURFACE( surface );
if( !surf )
return alloc_bool( false );
unsigned int key = SDL_MapRGB( surf->format, val_int( r ), val_int( g ), val_int( b ) );
SDL_SetColorKey( surf, SDL_RLEACCEL | SDL_SRCCOLORKEY, key );
return alloc_bool( true );
}
// screen relative functions
static bool sOpenGL = false;
value nme_delay( value period )
{
val_check( period, int );
SDL_Delay( val_int( period ) );
return alloc_int( 0 );
}
value nme_flipbuffer( value buff )
{
if (sOpenGL)
{
SDL_GL_SwapBuffers();
}
else
{
val_check_kind( buff, k_surf );
SDL_Surface* srf = SURFACE( buff );
SDL_Flip( srf );
SDL_Delay( 1 );
}
return alloc_int( 0 );
}
value nme_swapbuffer()
{
return alloc_int( 0 );
}
value nme_screen_flip()
{
value o = val_this();
val_check( o, object );
nme_flipbuffer( val_field( o, val_id( "screen" ) ) );
return alloc_int( 0 );
}
#define NME_FULLSCREEN 0x0001
#define NME_OPENGL 0x0002
value nme_screen_init( value width, value height, value title, value in_flags, value icon )
{
val_check( in_flags, int );
bool fullscreen = (val_int(in_flags) & NME_FULLSCREEN) != 0;
bool opengl = (val_int(in_flags) & NME_OPENGL) != 0;
sOpenGL = opengl;
Uint32 init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
if (opengl)
init_flags |= SDL_OPENGL;
if ( SDL_Init( init_flags ) == -1 ) failure( SDL_GetError() );
val_check( width, int );
val_check( height, int );
val_check( title, string );
Uint32 flags = opengl ? SDL_HWSURFACE | SDL_OPENGL :
SDL_HWSURFACE | SDL_DOUBLEBUF;
int bpp = 24;
if ( fullscreen )
{
flags |= SDL_FULLSCREEN;
if (!opengl)
bpp = 16;
}
if ( val_is_string( icon ) )
{
SDL_Surface *icn = nme_loadimage( icon );
if ( icn != NULL )
{
SDL_WM_SetIcon( icn, NULL );
}
}
SDL_Surface* screen = 0;
if (opengl)
{
int rgb_size[3];
/* Initialize the display */
switch (bpp)
{
case 8:
rgb_size[0] = 2;
rgb_size[1] = 3;
rgb_size[2] = 3;
break;
case 15:
case 16:
rgb_size[0] = 5;
rgb_size[1] = 5;
rgb_size[2] = 5;
break;
default:
rgb_size[0] = 8;
rgb_size[1] = 8;
rgb_size[2] = 8;
break;
}
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rgb_size[0]);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, rgb_size[1]);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, rgb_size[2]);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, bpp);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
if ( (screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags )) == NULL)
{
fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
SDL_Quit();
exit(1);
}
}
else
{
screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags );
if (!screen) failure( SDL_GetError() );
}
if ( TTF_Init() != 0 )
printf("unable to initialize the truetype font support\n");
SDL_WM_SetCaption( val_string( title ), 0 );
if ( Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096 ) != 0 )
printf("unable to initialize the sound support\n");
return alloc_abstract( k_surf, screen );
}
value nme_event()
{
SDL_Event event;
value evt = alloc_object(NULL);
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_quit ) );
return alloc_object( evt );
}
if (event.type == SDL_KEYDOWN)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_keydown ) );
alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
return alloc_object( evt );
}
if (event.type == SDL_KEYUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_keyup ) );
alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
return alloc_object( evt );
}
if (event.type == SDL_MOUSEMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_motion ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.motion.state ) );
alloc_field( evt, val_id( "x" ), alloc_int( event.motion.x ) );
alloc_field( evt, val_id( "y" ), alloc_int( event.motion.y ) );
alloc_field( evt, val_id( "xrel" ), alloc_int( event.motion.xrel ) );
alloc_field( evt, val_id( "yrel" ), alloc_int( event.motion.yrel ) );
return alloc_object( evt );
}
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_button ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.button.state ) );
alloc_field( evt, val_id( "x" ), alloc_int( event.button.x ) );
alloc_field( evt, val_id( "y" ), alloc_int( event.button.y ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.button.which ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.button.button ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYAXISMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jaxis ) );
alloc_field( evt, val_id( "axis" ), alloc_int( event.jaxis.axis ) );
alloc_field( evt, val_id( "value" ), alloc_int( event.jaxis.value ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jaxis.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_JOYBUTTONUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jbutton ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.jbutton.button ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.jbutton.state ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jbutton.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYHATMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jhat ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.jhat.hat ) );
alloc_field( evt, val_id( "value" ), alloc_int( event.jhat.value ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jhat.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYBALLMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jball ) );
alloc_field( evt, val_id( "ball" ), alloc_int( event.jball.ball ) );
alloc_field( evt, val_id( "xrel" ), alloc_int( event.jball.xrel ) );
alloc_field( evt, val_id( "yrel" ), alloc_int( event.jball.yrel ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jball.which ) );
return alloc_object( evt );
}
}
alloc_field( evt, val_id( "type" ), alloc_int( et_noevent ) );
return evt;
}
value nme_screen_close()
{
Mix_CloseAudio();
//sge_TTF_Quit();
SDL_Quit();
return alloc_int( 0 );
}
DEFINE_PRIM(nme_event, 0);
DEFINE_PRIM(nme_delay, 1);
DEFINE_PRIM(nme_flipbuffer, 1);
DEFINE_PRIM(nme_create_image_32,3);
DEFINE_PRIM(nme_copy_surface,1);
DEFINE_PRIM(nme_screen_init, 5);
DEFINE_PRIM(nme_screen_close, 0);
DEFINE_PRIM(nme_surface_clear, 2);
DEFINE_PRIM(nme_surface_free, 1);
DEFINE_PRIM(nme_surface_colourkey, 4);
<commit_msg>Added width and height<commit_after>/*
* Copyright (c) 2006, Lee McColl Sylvester - www.designrealm.co.uk
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE HAXE PROJECT 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 HAXE PROJECT 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 "nsdl.h"
#include "nme.h"
#include <stack>
#include <string.h>
#include <SDL_ttf.h>
#include <windows.h>
#include <gl/GL.h>
using namespace std;
// helper functions
DEFINE_KIND( k_surf );
DEFINE_KIND( k_snd );
DEFINE_KIND( k_mus );
SDL_Surface* nme_loadimage( value file )
{
val_check( file, string );
SDL_Surface* surf;
surf = IMG_Load( val_string( file ) );
if ( !surf )
surf = SDL_LoadBMP( val_string( file ) );
if ( !surf )
return NULL;
//SDL_Surface *surface = SDL_DisplayFormat( surf );
//SDL_FreeSurface( surf );
return surf;
}
// creates a surface with alpha channel
value nme_create_image_32( value flags, value width, value height )
{
val_check( flags, int );
val_check( width, int );
val_check( height, int );
// return alloc_abstract( k_surf, sge_CreateAlphaSurface( val_int( flags ), val_int( width ), val_int( height ) ) );
return alloc_int(0);
}
value nme_copy_surface( value surf )
{
return alloc_int(0);
/*
val_check_kind( surf, k_surf );
SDL_Surface* scr = SURFACE(surf);
return alloc_abstract( k_surf, sge_copy_surface( scr ) );
*/
}
// surface relative functions
static value nme_surface_clear( value surf, value c )
{
val_check_kind( surf, k_surf );
val_check( c, int );
SDL_Surface* scr = SURFACE(surf);
Uint8 r = RRGB( c );
Uint8 g = GRGB( c );
Uint8 b = BRGB( c );
SDL_FillRect( scr, NULL, SDL_MapRGB( scr->format, r, g, b ) );
return alloc_int( 0 );
}
value nme_surface_width( value surface )
{
val_check_kind( surface, k_surf );
SDL_Surface* surf = SURFACE(surface);
return alloc_int(surf->w);
}
value nme_surface_height( value surface )
{
val_check_kind( surface, k_surf );
SDL_Surface* surf = SURFACE(surface);
return alloc_int(surf->h);
}
void nme_surface_free( value surface )
{
if ( val_is_kind( surface, k_surf ) )
{
val_gc( surface, NULL );
SDL_Surface* surf = SURFACE( surface );
SDL_FreeSurface( surf );
}
}
value nme_surface_colourkey( value surface, value r, value g, value b )
{
val_check_kind( surface, k_surf );
val_check( r, int );
val_check( g, int );
val_check( b, int );
SDL_Surface* surf = SURFACE( surface );
if( !surf )
return alloc_bool( false );
unsigned int key = SDL_MapRGB( surf->format, val_int( r ), val_int( g ), val_int( b ) );
SDL_SetColorKey( surf, SDL_RLEACCEL | SDL_SRCCOLORKEY, key );
return alloc_bool( true );
}
// screen relative functions
static bool sOpenGL = false;
value nme_delay( value period )
{
val_check( period, int );
SDL_Delay( val_int( period ) );
return alloc_int( 0 );
}
value nme_flipbuffer( value buff )
{
if (sOpenGL)
{
SDL_GL_SwapBuffers();
}
else
{
val_check_kind( buff, k_surf );
SDL_Surface* srf = SURFACE( buff );
SDL_Flip( srf );
SDL_Delay( 1 );
}
return alloc_int( 0 );
}
value nme_swapbuffer()
{
return alloc_int( 0 );
}
value nme_screen_flip()
{
value o = val_this();
val_check( o, object );
nme_flipbuffer( val_field( o, val_id( "screen" ) ) );
return alloc_int( 0 );
}
#define NME_FULLSCREEN 0x0001
#define NME_OPENGL 0x0002
value nme_screen_init( value width, value height, value title, value in_flags, value icon )
{
val_check( in_flags, int );
bool fullscreen = (val_int(in_flags) & NME_FULLSCREEN) != 0;
bool opengl = (val_int(in_flags) & NME_OPENGL) != 0;
sOpenGL = opengl;
Uint32 init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
if (opengl)
init_flags |= SDL_OPENGL;
if ( SDL_Init( init_flags ) == -1 ) failure( SDL_GetError() );
val_check( width, int );
val_check( height, int );
val_check( title, string );
Uint32 flags = opengl ? SDL_HWSURFACE | SDL_OPENGL :
SDL_HWSURFACE | SDL_DOUBLEBUF;
int bpp = 24;
if ( fullscreen )
{
flags |= SDL_FULLSCREEN;
if (!opengl)
bpp = 16;
}
if ( val_is_string( icon ) )
{
SDL_Surface *icn = nme_loadimage( icon );
if ( icn != NULL )
{
SDL_WM_SetIcon( icn, NULL );
}
}
SDL_Surface* screen = 0;
if (opengl)
{
int rgb_size[3];
/* Initialize the display */
switch (bpp)
{
case 8:
rgb_size[0] = 2;
rgb_size[1] = 3;
rgb_size[2] = 3;
break;
case 15:
case 16:
rgb_size[0] = 5;
rgb_size[1] = 5;
rgb_size[2] = 5;
break;
default:
rgb_size[0] = 8;
rgb_size[1] = 8;
rgb_size[2] = 8;
break;
}
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, rgb_size[0]);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, rgb_size[1]);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, rgb_size[2]);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, bpp);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
if ( (screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags )) == NULL)
{
fprintf(stderr, "Couldn't set GL mode: %s\n", SDL_GetError());
SDL_Quit();
exit(1);
}
}
else
{
screen = SDL_SetVideoMode( val_int( width ), val_int( height ), bpp, flags );
if (!screen) failure( SDL_GetError() );
}
if ( TTF_Init() != 0 )
printf("unable to initialize the truetype font support\n");
SDL_WM_SetCaption( val_string( title ), 0 );
if ( Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096 ) != 0 )
printf("unable to initialize the sound support\n");
return alloc_abstract( k_surf, screen );
}
value nme_event()
{
SDL_Event event;
value evt = alloc_object(NULL);
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_quit ) );
return alloc_object( evt );
}
if (event.type == SDL_KEYDOWN)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_keydown ) );
alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
return alloc_object( evt );
}
if (event.type == SDL_KEYUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_keyup ) );
alloc_field( evt, val_id( "key" ), alloc_int( event.key.keysym.sym ) );
alloc_field( evt, val_id( "shift" ), alloc_bool( event.key.keysym.mod & KMOD_SHIFT ) );
alloc_field( evt, val_id( "ctrl" ), alloc_bool( event.key.keysym.mod & KMOD_CTRL ) );
alloc_field( evt, val_id( "alt" ), alloc_bool( event.key.keysym.mod & KMOD_ALT ) );
return alloc_object( evt );
}
if (event.type == SDL_MOUSEMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_motion ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.motion.state ) );
alloc_field( evt, val_id( "x" ), alloc_int( event.motion.x ) );
alloc_field( evt, val_id( "y" ), alloc_int( event.motion.y ) );
alloc_field( evt, val_id( "xrel" ), alloc_int( event.motion.xrel ) );
alloc_field( evt, val_id( "yrel" ), alloc_int( event.motion.yrel ) );
return alloc_object( evt );
}
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_button ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.button.state ) );
alloc_field( evt, val_id( "x" ), alloc_int( event.button.x ) );
alloc_field( evt, val_id( "y" ), alloc_int( event.button.y ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.button.which ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.button.button ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYAXISMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jaxis ) );
alloc_field( evt, val_id( "axis" ), alloc_int( event.jaxis.axis ) );
alloc_field( evt, val_id( "value" ), alloc_int( event.jaxis.value ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jaxis.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYBUTTONDOWN || event.type == SDL_JOYBUTTONUP)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jbutton ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.jbutton.button ) );
alloc_field( evt, val_id( "state" ), alloc_int( event.jbutton.state ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jbutton.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYHATMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jhat ) );
alloc_field( evt, val_id( "button" ), alloc_int( event.jhat.hat ) );
alloc_field( evt, val_id( "value" ), alloc_int( event.jhat.value ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jhat.which ) );
return alloc_object( evt );
}
if (event.type == SDL_JOYBALLMOTION)
{
alloc_field( evt, val_id( "type" ), alloc_int( et_jball ) );
alloc_field( evt, val_id( "ball" ), alloc_int( event.jball.ball ) );
alloc_field( evt, val_id( "xrel" ), alloc_int( event.jball.xrel ) );
alloc_field( evt, val_id( "yrel" ), alloc_int( event.jball.yrel ) );
alloc_field( evt, val_id( "which" ), alloc_int( event.jball.which ) );
return alloc_object( evt );
}
}
alloc_field( evt, val_id( "type" ), alloc_int( et_noevent ) );
return evt;
}
value nme_screen_close()
{
Mix_CloseAudio();
//sge_TTF_Quit();
SDL_Quit();
return alloc_int( 0 );
}
DEFINE_PRIM(nme_event, 0);
DEFINE_PRIM(nme_delay, 1);
DEFINE_PRIM(nme_flipbuffer, 1);
DEFINE_PRIM(nme_create_image_32,3);
DEFINE_PRIM(nme_copy_surface,1);
DEFINE_PRIM(nme_screen_init, 5);
DEFINE_PRIM(nme_screen_close, 0);
DEFINE_PRIM(nme_surface_clear, 2);
DEFINE_PRIM(nme_surface_free, 1);
DEFINE_PRIM(nme_surface_width, 1);
DEFINE_PRIM(nme_surface_height, 1);
DEFINE_PRIM(nme_surface_colourkey, 4);
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: makedocs.cc,v 1.11 2002/09/05 04:34:04 verkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
void makedocs(const char *version="Development", const char *where= "./html", Bool_t doTutorial=kFALSE)
{
const char *bfarch= gSystem->Getenv("BFARCH");
TString sourceDir("RELEASE/RooFitCore:RELEASE/tmp/");
sourceDir.Append(bfarch);
sourceDir.Append("/RooFitCore");
gEnv->SetValue("Root.Html.SourceDir",sourceDir.Data());
gEnv->SetValue("Root.Html.OutputDir",where);
gEnv->SetValue("Root.Html.Description","// -- CLASS DESCRIPTION");
gEnv->SetValue("Root.Html.LastUpdate"," * File: $Id: ");
RooHtml docMaker(version);
docMaker.setHeaderColor("#FFFFFF") ;
if (doTutorial) {
docMaker.Convert("intro1.cc","Elementary operations on a gaussian PDF") ;
docMaker.Convert("intro2.cc","Building more complex PDFs via addition") ;
docMaker.Convert("intro3.cc","Adding more dimensions, multiplying PDFs") ;
docMaker.Convert("intro4.cc","Extend PDFs via composition") ;
docMaker.Convert("intro5.cc","Discrete variables") ;
docMaker.Convert("intro6.cc","Convoluted PDFs") ;
docMaker.Convert("intro7.cc","Extended likelihood PDFs") ;
docMaker.Convert("intro8.cc","Dataset operations") ;
docMaker.Convert("intro9.cc","Observables vs parameters") ;
docMaker.Convert("plot1.cc","Using variable binning") ;
docMaker.Convert("plot2.cc","Plotting a PDF projection on a subset of the event sample") ;
docMaker.Convert("plot3.cc","Plotting with a cut on the projected likelihood") ;
docMaker.Convert("plot4.cc","Plotting slices of simultaneous PDFs") ;
docMaker.Convert("mgmt1.cc","BMixing with per-event errors") ;
docMaker.Convert("mgmt2.cc","Using RooSimPdfBuilder to replicate and customize PDFs") ;
docMaker.Convert("mgmt3.cc","Blinding parameters") ;
docMaker.Convert("fitgen1.cc","Interactive MINUIT") ;
docMaker.Convert("fitgen2.cc","Adding penalty functions/Langrange multipliers") ;
docMaker.Convert("fitgen3.cc","NLL versus Chi2 fits") ;
}
docMaker.MakeAll(kTRUE,"Roo*");
docMaker.MakeIndexNew("Roo*");
docMaker.addTopic("PDF","Probability Density functions") ;
docMaker.addTopic("REAL","Real valued functions") ;
docMaker.addTopic("CAT","Discrete valued functions") ;
docMaker.addTopic("DATA","Unbinned and binned data") ;
docMaker.addTopic("PLOT","Plotting and tabulating") ;
docMaker.addTopic("CONT","Container classes") ;
docMaker.addTopic("MISC","Miscellaneous") ;
docMaker.addTopic("USER","Other user classes") ;
docMaker.addTopic("AUX","Auxiliary classes for internal use") ;
docMaker.MakeIndexOfTopics() ;
}
<commit_msg><commit_after>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: makedocs.cc,v 1.12 2002/09/17 06:39:35 verkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
void makedocs(const char *version="Development", const char *where= "./html", Bool_t doTutorial=kFALSE)
{
const char *bfarch= gSystem->Getenv("BFARCH");
TString sourceDir("RELEASE/RooFitCore:RELEASE/tmp/");
sourceDir.Append(bfarch);
sourceDir.Append("/RooFitCore");
gEnv->SetValue("Root.Html.SourceDir",sourceDir.Data());
gEnv->SetValue("Root.Html.OutputDir",where);
gEnv->SetValue("Root.Html.Description","// -- CLASS DESCRIPTION");
gEnv->SetValue("Root.Html.LastUpdate"," * File: $Id: ");
RooHtml docMaker(version);
docMaker.setHeaderColor("#FFFFFF") ;
if (doTutorial) {
docMaker.Convert("intro1.cc","Elementary operations on a gaussian PDF") ;
docMaker.Convert("intro2.cc","Building more complex PDFs via addition") ;
docMaker.Convert("intro3.cc","Adding more dimensions, multiplying PDFs") ;
docMaker.Convert("intro4.cc","Extend PDFs via composition") ;
docMaker.Convert("intro5.cc","Discrete variables") ;
docMaker.Convert("intro6.cc","Convoluted PDFs") ;
docMaker.Convert("intro7.cc","Extended likelihood PDFs") ;
docMaker.Convert("intro8.cc","Dataset operations") ;
docMaker.Convert("intro9.cc","Observables vs parameters") ;
docMaker.Convert("plot1.cc","Using variable binning") ;
docMaker.Convert("plot2.cc","Plotting a PDF projection on a subset of the event sample") ;
docMaker.Convert("plot3.cc","Plotting with a cut on the projected likelihood") ;
docMaker.Convert("plot4.cc","Plotting slices of simultaneous PDFs") ;
docMaker.Convert("mgmt1.cc","BMixing with per-event errors") ;
docMaker.Convert("mgmt2.cc","Using RooSimPdfBuilder to replicate and customize PDFs") ;
docMaker.Convert("mgmt3.cc","Blinding parameters") ;
docMaker.Convert("fitgen1.cc","Interactive MINUIT") ;
docMaker.Convert("fitgen2.cc","Adding penalty functions/Langrange multipliers") ;
docMaker.Convert("fitgen3.cc","NLL versus Chi2 fits") ;
}
docMaker.MakeAll(kTRUE,"Roo*");
docMaker.MakeIndexNew("Roo*");
docMaker.addTopic("PDF","Probability Density functions") ;
docMaker.addTopic("REAL","Real valued functions") ;
docMaker.addTopic("CAT","Discrete valued functions") ;
docMaker.addTopic("DATA","Unbinned and binned data") ;
docMaker.addTopic("PLOT","Plotting and tabulating") ;
docMaker.addTopic("CONT","Container classes") ;
docMaker.addTopic("MISC","Miscellaneous") ;
docMaker.addTopic("USER","Other user classes") ;
docMaker.addTopic("AUX","Auxiliary classes for internal use") ;
docMaker.MakeIndexOfTopics() ;
}
<|endoftext|>
|
<commit_before>#include "shape.hpp"
#include "glm/gtx/rotate_vector.hpp"
#include "utils.hpp"
namespace trac0r {
const glm::vec3 Shape::pos(const Shape &shape) {
return shape.m_pos;
}
void Shape::set_pos(Shape &shape, glm::vec3 new_pos) {
shape.m_pos = new_pos;
}
const glm::vec3 Shape::orientation(const Shape &shape) {
return shape.m_orientation;
}
void Shape::set_orientation(Shape &shape, glm::vec3 new_orientation) {
shape.m_orientation = new_orientation;
}
const glm::vec3 Shape::scale(const Shape &shape) {
return shape.m_scale;
}
void Shape::set_scale(Shape &shape, glm::vec3 new_scale) {
shape.m_scale = new_scale;
}
AABB &Shape::aabb(Shape &shape) {
return shape.m_aabb;
}
const AABB &Shape::aabb(const Shape &shape) {
return shape.m_aabb;
}
std::vector<Triangle> &Shape::triangles(Shape &shape) {
return shape.m_triangles;
}
const std::vector<Triangle> &Shape::triangles(const Shape &shape) {
return shape.m_triangles;
}
void Shape::add_triangle(Shape &shape, const Triangle triangle) {
shape.m_triangles.push_back(triangle);
}
Shape Shape::make_box(glm::vec3 pos, glm::vec3 orientation, glm::vec3 size, Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, glm::normalize(orientation));
Shape::set_scale(new_shape, size);
auto p1 = glm::vec3{-0.5f, 0.5f, -0.5f};
auto p2 = glm::vec3{-0.5f, -0.5f, -0.5f};
auto p3 = glm::vec3{0.5f, -0.5f, -0.5f};
auto p4 = glm::vec3{0.5f, 0.5f, -0.5f};
auto p5 = glm::vec3{-0.5f, 0.5f, 0.5f};
auto p6 = glm::vec3{-0.5f, -0.5f, 0.5f};
auto p7 = glm::vec3{0.5f, -0.5f, 0.5f};
auto p8 = glm::vec3{0.5f, 0.5f, 0.5f};
// front face
auto t1 = Triangle(p2, p1, p3, material);
auto t2 = Triangle(p1, p4, p3, material);
// right face
auto t3 = Triangle(p4, p3, p8, material);
auto t4 = Triangle(p3, p7, p8, material);
// left face
auto t5 = Triangle(p1, p2, p6, material);
auto t6 = Triangle(p5, p1, p6, material);
// back face
auto t7 = Triangle(p5, p6, p8, material);
auto t8 = Triangle(p6, p7, p8, material);
// top face
auto t9 = Triangle(p5, p1, p4, material);
auto t10 = Triangle(p8, p4, p5, material);
// bottom face
auto t11 = Triangle(p2, p3, p6, material);
auto t12 = Triangle(p3, p7, p6, material);
Shape::add_triangle(new_shape, t1);
Shape::add_triangle(new_shape, t2);
Shape::add_triangle(new_shape, t3);
Shape::add_triangle(new_shape, t4);
Shape::add_triangle(new_shape, t5);
Shape::add_triangle(new_shape, t6);
Shape::add_triangle(new_shape, t7);
Shape::add_triangle(new_shape, t8);
Shape::add_triangle(new_shape, t9);
Shape::add_triangle(new_shape, t10);
Shape::add_triangle(new_shape, t11);
Shape::add_triangle(new_shape, t12);
glm::mat4 translation = glm::translate(pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(size);
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
Shape Shape::make_icosphere(glm::vec3 pos, glm::vec3 orientation, float radius, size_t iterations,
Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, glm::normalize(orientation));
Shape::set_scale(new_shape, glm::vec3(radius, radius, radius));
float t = 0.5 + glm::sqrt(5) / 2.f;
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {-t, 0, 1}, {0, 1, t}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {0, 1, t}, {1, t, 0}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {1, t, 0}, {0, 1, -t}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {0, 1, -t}, {-t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {-t, 0, -1}, {-t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{1, t, 0}, {0, 1, t}, {t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, 1, t}, {-t, 0, 1}, {0, -1, t}, material});
triangles(new_shape).push_back(Triangle{{-t, 0, 1}, {-t, 0, -1}, {-1, -t, 0}, material});
triangles(new_shape).push_back(Triangle{{-t, 0, -1}, {0, 1, -t}, {0, -1, -t}, material});
triangles(new_shape).push_back(Triangle{{0, 1, -t}, {1, t, 0}, {t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {t, 0, 1}, {0, -1, t}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {0, -1, t}, {-1, -t, 0}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {-1, -t, 0}, {0, -1, -t}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {0, -1, -t}, {t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {t, 0, -1}, {t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, -1, t}, {t, 0, 1}, {0, 1, t}, material});
triangles(new_shape).push_back(Triangle{{-1, -t, 0}, {0, -1, t}, {-t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, -1, -t}, {-1, -t, 0}, {-t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{t, 0, -1}, {0, -1, -t}, {0, 1, -t}, material});
triangles(new_shape).push_back(Triangle{{t, 0, 1}, {t, 0, -1}, {1, t, 0}, material});
rebuild(new_shape);
for (size_t i = 0; i < iterations; i++) {
std::vector<Triangle> new_triangles;
for (const auto &tri : triangles(new_shape)) {
glm::vec3 a = glm::normalize(get_middle_point(tri.m_v1, tri.m_v2));
glm::vec3 b = glm::normalize(get_middle_point(tri.m_v2, tri.m_v3));
glm::vec3 c = glm::normalize(get_middle_point(tri.m_v3, tri.m_v1));
new_triangles.push_back(Triangle{glm::normalize(tri.m_v1), a, c, material});
new_triangles.push_back(Triangle{glm::normalize(tri.m_v2), b, a, material});
new_triangles.push_back(Triangle{glm::normalize(tri.m_v3), c, b, material});
new_triangles.push_back(Triangle{a, b, c, material});
}
new_shape.m_triangles = new_triangles;
}
glm::mat4 translation = glm::translate(pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(Shape::scale(new_shape));
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
Shape Shape::make_plane(glm::vec3 pos, glm::vec3 orientation, glm::vec2 size, Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, glm::normalize(orientation));
Shape::set_scale(new_shape, glm::vec3(size.x, 0, size.y));
auto p1 = glm::vec3{-0.5f, 0, 0.5f};
auto p2 = glm::vec3{-0.5f, 0, -0.5f};
auto p3 = glm::vec3{0.5f, 0, -0.5f};
auto p4 = glm::vec3{0.5f, 0, 0.5f};
auto triangle_left = Triangle(p2, p1, p3, material);
auto triangle_right = Triangle(p1, p4, p3, material);
Shape::add_triangle(new_shape, triangle_left);
Shape::add_triangle(new_shape, triangle_right);
glm::mat4 translation = glm::translate(pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(Shape::scale(new_shape));
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
void Shape::rebuild(Shape &shape) {
auto &aabb = Shape::aabb(shape);
AABB::reset(aabb);
for (auto &tri : Shape::triangles(shape)) {
AABB::extend(aabb, tri.m_v1);
AABB::extend(aabb, tri.m_v2);
AABB::extend(aabb, tri.m_v3);
}
}
}
<commit_msg>Start matrix fixes<commit_after>#include "shape.hpp"
#include "glm/gtx/rotate_vector.hpp"
#include "utils.hpp"
namespace trac0r {
const glm::vec3 Shape::pos(const Shape &shape) {
return shape.m_pos;
}
void Shape::set_pos(Shape &shape, glm::vec3 new_pos) {
shape.m_pos = new_pos;
}
const glm::vec3 Shape::orientation(const Shape &shape) {
return shape.m_orientation;
}
void Shape::set_orientation(Shape &shape, glm::vec3 new_orientation) {
shape.m_orientation = new_orientation;
}
const glm::vec3 Shape::scale(const Shape &shape) {
return shape.m_scale;
}
void Shape::set_scale(Shape &shape, glm::vec3 new_scale) {
shape.m_scale = new_scale;
}
AABB &Shape::aabb(Shape &shape) {
return shape.m_aabb;
}
const AABB &Shape::aabb(const Shape &shape) {
return shape.m_aabb;
}
std::vector<Triangle> &Shape::triangles(Shape &shape) {
return shape.m_triangles;
}
const std::vector<Triangle> &Shape::triangles(const Shape &shape) {
return shape.m_triangles;
}
void Shape::add_triangle(Shape &shape, const Triangle triangle) {
shape.m_triangles.push_back(triangle);
}
Shape Shape::make_box(glm::vec3 pos, glm::vec3 orientation, glm::vec3 size, Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, orientation);
Shape::set_scale(new_shape, size);
auto p1 = glm::vec3{-0.5f, 0.5f, -0.5f};
auto p2 = glm::vec3{-0.5f, -0.5f, -0.5f};
auto p3 = glm::vec3{0.5f, -0.5f, -0.5f};
auto p4 = glm::vec3{0.5f, 0.5f, -0.5f};
auto p5 = glm::vec3{-0.5f, 0.5f, 0.5f};
auto p6 = glm::vec3{-0.5f, -0.5f, 0.5f};
auto p7 = glm::vec3{0.5f, -0.5f, 0.5f};
auto p8 = glm::vec3{0.5f, 0.5f, 0.5f};
// front face
auto t1 = Triangle(p2, p1, p3, material);
auto t2 = Triangle(p1, p4, p3, material);
// right face
auto t3 = Triangle(p4, p3, p8, material);
auto t4 = Triangle(p3, p7, p8, material);
// left face
auto t5 = Triangle(p1, p2, p6, material);
auto t6 = Triangle(p5, p1, p6, material);
// back face
auto t7 = Triangle(p5, p6, p8, material);
auto t8 = Triangle(p6, p7, p8, material);
// top face
auto t9 = Triangle(p5, p1, p4, material);
auto t10 = Triangle(p8, p4, p5, material);
// bottom face
auto t11 = Triangle(p2, p3, p6, material);
auto t12 = Triangle(p3, p7, p6, material);
Shape::add_triangle(new_shape, t1);
Shape::add_triangle(new_shape, t2);
Shape::add_triangle(new_shape, t3);
Shape::add_triangle(new_shape, t4);
Shape::add_triangle(new_shape, t5);
Shape::add_triangle(new_shape, t6);
Shape::add_triangle(new_shape, t7);
Shape::add_triangle(new_shape, t8);
Shape::add_triangle(new_shape, t9);
Shape::add_triangle(new_shape, t10);
Shape::add_triangle(new_shape, t11);
Shape::add_triangle(new_shape, t12);
glm::mat4 translation = glm::translate(glm::mat4(1.f), pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(glm::mat4(1.f), size);
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
Shape Shape::make_icosphere(glm::vec3 pos, glm::vec3 orientation, float radius, size_t iterations,
Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, glm::normalize(orientation));
Shape::set_scale(new_shape, glm::vec3(radius, radius, radius));
float t = 0.5 + glm::sqrt(5) / 2.f;
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {-t, 0, 1}, {0, 1, t}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {0, 1, t}, {1, t, 0}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {1, t, 0}, {0, 1, -t}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {0, 1, -t}, {-t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{-1, t, 0}, {-t, 0, -1}, {-t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{1, t, 0}, {0, 1, t}, {t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, 1, t}, {-t, 0, 1}, {0, -1, t}, material});
triangles(new_shape).push_back(Triangle{{-t, 0, 1}, {-t, 0, -1}, {-1, -t, 0}, material});
triangles(new_shape).push_back(Triangle{{-t, 0, -1}, {0, 1, -t}, {0, -1, -t}, material});
triangles(new_shape).push_back(Triangle{{0, 1, -t}, {1, t, 0}, {t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {t, 0, 1}, {0, -1, t}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {0, -1, t}, {-1, -t, 0}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {-1, -t, 0}, {0, -1, -t}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {0, -1, -t}, {t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{1, -t, 0}, {t, 0, -1}, {t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, -1, t}, {t, 0, 1}, {0, 1, t}, material});
triangles(new_shape).push_back(Triangle{{-1, -t, 0}, {0, -1, t}, {-t, 0, 1}, material});
triangles(new_shape).push_back(Triangle{{0, -1, -t}, {-1, -t, 0}, {-t, 0, -1}, material});
triangles(new_shape).push_back(Triangle{{t, 0, -1}, {0, -1, -t}, {0, 1, -t}, material});
triangles(new_shape).push_back(Triangle{{t, 0, 1}, {t, 0, -1}, {1, t, 0}, material});
rebuild(new_shape);
for (size_t i = 0; i < iterations; i++) {
std::vector<Triangle> new_triangles;
for (const auto &tri : triangles(new_shape)) {
glm::vec3 a = glm::normalize(get_middle_point(tri.m_v1, tri.m_v2));
glm::vec3 b = glm::normalize(get_middle_point(tri.m_v2, tri.m_v3));
glm::vec3 c = glm::normalize(get_middle_point(tri.m_v3, tri.m_v1));
new_triangles.push_back(Triangle{glm::normalize(tri.m_v1), a, c, material});
new_triangles.push_back(Triangle{glm::normalize(tri.m_v2), b, a, material});
new_triangles.push_back(Triangle{glm::normalize(tri.m_v3), c, b, material});
new_triangles.push_back(Triangle{a, b, c, material});
}
new_shape.m_triangles = new_triangles;
}
glm::mat4 translation = glm::translate(pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(Shape::scale(new_shape));
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
Shape Shape::make_plane(glm::vec3 pos, glm::vec3 orientation, glm::vec2 size, Material material) {
Shape new_shape;
Shape::set_pos(new_shape, pos);
Shape::set_orientation(new_shape, glm::normalize(orientation));
Shape::set_scale(new_shape, glm::vec3(size.x, 0, size.y));
auto p1 = glm::vec3{-0.5f, 0, 0.5f};
auto p2 = glm::vec3{-0.5f, 0, -0.5f};
auto p3 = glm::vec3{0.5f, 0, -0.5f};
auto p4 = glm::vec3{0.5f, 0, 0.5f};
auto triangle_left = Triangle(p2, p1, p3, material);
auto triangle_right = Triangle(p1, p4, p3, material);
Shape::add_triangle(new_shape, triangle_left);
Shape::add_triangle(new_shape, triangle_right);
glm::mat4 translation = glm::translate(pos);
glm::mat4 rotation = glm::orientation(orientation, {0, 1, 0});
glm::mat4 scale = glm::scale(Shape::scale(new_shape));
glm::mat4 model = translation * rotation * scale;
for (auto &tri : triangles(new_shape)) {
tri.m_v1 = glm::vec3(model * glm::vec4(tri.m_v1, 1));
tri.m_v2 = glm::vec3(model * glm::vec4(tri.m_v2, 1));
tri.m_v3 = glm::vec3(model * glm::vec4(tri.m_v3, 1));
tri.rebuild();
}
rebuild(new_shape);
return new_shape;
}
void Shape::rebuild(Shape &shape) {
auto &aabb = Shape::aabb(shape);
AABB::reset(aabb);
for (auto &tri : Shape::triangles(shape)) {
AABB::extend(aabb, tri.m_v1);
AABB::extend(aabb, tri.m_v2);
AABB::extend(aabb, tri.m_v3);
}
}
}
<|endoftext|>
|
<commit_before>#ifndef UTILS_HPP
#define UTILS_HPP
#include <glm/glm.hpp>
#include <SDL.h>
#include <SDL_ttf.h>
#include <cmath>
#include <string>
#include <iostream>
namespace trac0r {
SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,
const SDL_Color &color) {
auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);
auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_FreeSurface(text_surface);
return text_tex;
}
void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {
int tex_width;
int tex_height;
SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);
SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};
SDL_RenderCopy(renderer, texture, 0, &rect);
}
uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
uint32_t new_color = a << 24 | r << 16 | g << 8 | b;
return new_color;
}
uint32_t pack_color_argb(glm::i8vec4 color) {
uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;
return new_color;
}
uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;
return packed_color;
}
uint32_t pack_color_rgba(glm::i8vec4 color) {
uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;
return packed_color;
}
uint32_t pack_color_rgba(glm::vec4 color) {
uint32_t packed_color = int(std::round(color.r * 255)) << 24 |
int(std::round(color.g * 255)) << 16 |
int(std::round(color.b * 255)) << 8 | int(std::round(color.a * 255));
return packed_color;
}
uint32_t pack_color_argb(glm::vec4 color) {
uint32_t packed_color = int(std::round(color.a * 255)) << 24 |
int(std::round(color.r * 255)) << 16 |
int(std::round(color.g * 255)) << 8 | int(std::round(color.b * 255));
return packed_color;
}
glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {
glm::i8vec4 unpacked_color;
unpacked_color.r = packed_color_rgba >> 24 & 0xFF;
unpacked_color.g = packed_color_rgba >> 16 & 0xFF;
unpacked_color.b = packed_color_rgba >> 8 & 0xFF;
unpacked_color.a = packed_color_rgba & 0xFF;
return unpacked_color;
}
glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {
glm::i8vec4 unpacked_color;
unpacked_color.a = packed_color_argb >> 24 & 0xFF;
unpacked_color.r = packed_color_argb >> 16 & 0xFF;
unpacked_color.g = packed_color_argb >> 8 & 0xFF;
unpacked_color.b = packed_color_argb & 0xFF;
return unpacked_color;
}
glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {
glm::i8vec4 unpacked_color;
unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) / 255.f;
unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) / 255.f;
unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) / 255.f;
unpacked_color.a = (packed_color_rgba & 0xFF) / 255.f;
return unpacked_color;
}
glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {
glm::i8vec4 unpacked_color;
unpacked_color.a = (packed_color_argb >> 24 & 0xFF) / 255.f;
unpacked_color.r = (packed_color_argb >> 16 & 0xFF) / 255.f;
unpacked_color.g = (packed_color_argb >> 8 & 0xFF) / 255.f;
unpacked_color.b = (packed_color_argb & 0xFF) / 255.f;
return unpacked_color;
}
}
#endif /* end of include guard: UTILS_HPP */
<commit_msg>Fix typo<commit_after>#ifndef UTILS_HPP
#define UTILS_HPP
#include <glm/glm.hpp>
#include <SDL.h>
#include <SDL_ttf.h>
#include <cmath>
#include <string>
#include <iostream>
namespace trac0r {
SDL_Texture *make_text(SDL_Renderer *renderer, TTF_Font *font, std::string text,
const SDL_Color &color) {
auto text_surface = TTF_RenderText_Blended(font, text.c_str(), color);
auto text_tex = SDL_CreateTextureFromSurface(renderer, text_surface);
SDL_FreeSurface(text_surface);
return text_tex;
}
void render_text(SDL_Renderer *renderer, SDL_Texture *texture, int pos_x, int pos_y) {
int tex_width;
int tex_height;
SDL_QueryTexture(texture, 0, 0, &tex_width, &tex_height);
SDL_Rect rect{pos_x, pos_y, tex_width, tex_height};
SDL_RenderCopy(renderer, texture, 0, &rect);
}
uint32_t pack_color_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b) {
uint32_t new_color = a << 24 | r << 16 | g << 8 | b;
return new_color;
}
uint32_t pack_color_argb(glm::i8vec4 color) {
uint32_t new_color = color.a << 24 | color.r << 16 | color.g << 8 | color.b;
return new_color;
}
uint32_t pack_color_rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
uint32_t packed_color = r << 24 | g << 16 | b << 8 | a;
return packed_color;
}
uint32_t pack_color_rgba(glm::i8vec4 color) {
uint32_t packed_color = color.r << 24 | color.g << 16 | color.b << 8 | color.a;
return packed_color;
}
uint32_t pack_color_rgba(glm::vec4 color) {
uint32_t packed_color = int(std::round(color.r * 255)) << 24 |
int(std::round(color.g * 255)) << 16 |
int(std::round(color.b * 255)) << 8 | int(std::round(color.a * 255));
return packed_color;
}
uint32_t pack_color_argb(glm::vec4 color) {
uint32_t packed_color = int(std::round(color.a * 255)) << 24 |
int(std::round(color.r * 255)) << 16 |
int(std::round(color.g * 255)) << 8 | int(std::round(color.b * 255));
return packed_color;
}
glm::i8vec4 unpack_color_rgba_to_i8vec4(uint32_t packed_color_rgba) {
glm::i8vec4 unpacked_color;
unpacked_color.r = packed_color_rgba >> 24 & 0xFF;
unpacked_color.g = packed_color_rgba >> 16 & 0xFF;
unpacked_color.b = packed_color_rgba >> 8 & 0xFF;
unpacked_color.a = packed_color_rgba & 0xFF;
return unpacked_color;
}
glm::i8vec4 unpack_color_argb_to_i8vec4(uint32_t packed_color_argb) {
glm::i8vec4 unpacked_color;
unpacked_color.a = packed_color_argb >> 24 & 0xFF;
unpacked_color.r = packed_color_argb >> 16 & 0xFF;
unpacked_color.g = packed_color_argb >> 8 & 0xFF;
unpacked_color.b = packed_color_argb & 0xFF;
return unpacked_color;
}
glm::vec4 unpack_color_rgbb_to_vec4(uint32_t packed_color_rgba) {
glm::i8vec4 unpacked_color;
unpacked_color.r = (packed_color_rgba >> 24 & 0xFF) / 255.f;
unpacked_color.g = (packed_color_rgba >> 16 & 0xFF) / 255.f;
unpacked_color.b = (packed_color_rgba >> 8 & 0xFF) / 255.f;
unpacked_color.a = (packed_color_rgba & 0xFF) / 255.f;
return unpacked_color;
}
glm::vec4 unpack_color_argb_to_vec4(uint32_t packed_color_argb) {
glm::vec4 unpacked_color;
unpacked_color.a = (packed_color_argb >> 24 & 0xFF) / 255.f;
unpacked_color.r = (packed_color_argb >> 16 & 0xFF) / 255.f;
unpacked_color.g = (packed_color_argb >> 8 & 0xFF) / 255.f;
unpacked_color.b = (packed_color_argb & 0xFF) / 255.f;
return unpacked_color;
}
}
#endif /* end of include guard: UTILS_HPP */
<|endoftext|>
|
<commit_before>#include "photoeffects.hpp"
#include <math.h>
using namespace cv;
#define MAX_KERNELSIZE 15
int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)
{
CV_Assert(src.type() == CV_8UC3);
dst.create(src.size(), src.type());
Mat image = src.getMat(), outputImage = dst.getMat();
CV_Assert(indentTop >= 0 && indentTop <= (image.rows / 2 - 10));
CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols / 2 - 10));
float halfWidth = (image.cols / 2.0f) * (image.cols / 2.0f);
float halfHeight = (image.rows / 2.0f) * (image.rows / 2.0f);
float a = (image.cols / 2.0f - indentLeft)
* (image.cols / 2.0f - indentLeft);
float b = (image.rows / 2.0f - indentTop)
* (image.rows / 2.0f - indentTop);
int kSizeEdges = halfWidth / a + halfHeight / b;
kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);
Mat bearingImage(image.rows + 2 * kSizeEdges,
image.cols + 2 * kSizeEdges,
CV_8UC3);
copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,
kSizeEdges, kSizeEdges, BORDER_REPLICATE);
for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)
{
for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)
{
int size;
Vec3f sumF;
Vec3b Color;
float sumC = 0.0f, coeff;
float bearHalfWidth = bearingImage.cols / 2.0f;
float bearHalfHeight = bearingImage.rows / 2.0f;
float radius = (bearHalfHeight - i)
* (bearHalfHeight - i)
/ b
+ (bearHalfWidth - j)
* (bearHalfWidth - j)
/ a;
if (radius < 1.0f)
{
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =
bearingImage.at<Vec3b>(i, j);
continue;
}
size = radius;
radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);
size = MIN(size, kSizeEdges);
for (int x = -size; x <= size; x++)
{
for (int y = -size; y <= size; y++)
{
coeff = 1.0f / (CV_PI * radius)
* exp(- (x * x + y * y) / radius);
Color = bearingImage.at<Vec3b>(x + i, y + j);
sumF += coeff * Color;
sumC += coeff;
}
}
sumF *= (1.0f / sumC);
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;
}
}
return 0;
}
<commit_msg>Corrected<commit_after>#include "photoeffects.hpp"
#include <math.h>
using namespace cv;
#define MAX_KERNELSIZE 15
int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)
{
CV_Assert(src.type() == CV_8UC3);
dst.create(src.size(), src.type());
Mat image = src.getMat(), outputImage = dst.getMat();
CV_Assert(indentTop >= 0 && indentTop <= (image.rows / 2 - 10));
CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols / 2 - 10));
float halfWidth = image.cols / 2.0f;
float halfHeight = image.rows / 2.0f;
float a = (image.cols / 2.0f - indentLeft)
* (image.cols / 2.0f - indentLeft);
float b = (image.rows / 2.0f - indentTop)
* (image.rows / 2.0f - indentTop);
int kSizeEdges = halfWidth * halfWidth / a + halfHeight * halfHeight / b;
kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);
Mat bearingImage(image.rows + 2 * kSizeEdges,
image.cols + 2 * kSizeEdges,
CV_8UC3);
copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,
kSizeEdges, kSizeEdges, BORDER_REPLICATE);
for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)
{
for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)
{
int size;
Vec3f sumF;
Vec3b Color;
float sumC = 0.0f, coeff;
float radius = (halfHeight - i)
* (halfHeight- i)
/ b
+ (halfWidth - j)
* (halfHeight - j)
/ a;
if (radius < 1.0f)
{
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =
bearingImage.at<Vec3b>(i, j);
continue;
}
size = radius;
radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);
size = MIN(size, kSizeEdges);
for (int x = -size; x <= size; x++)
{
for (int y = -size; y <= size; y++)
{
coeff = 1.0f / (CV_PI * radius)
* exp(- (x * x + y * y) / radius);
Color = bearingImage.at<Vec3b>(x + i, y + j);
sumF += coeff * (Vec3f)Color;
sumC += coeff;
}
}
sumF *= (1.0f / sumC);
outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 1999 Preston Brown, Ian Dawes
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qkeycode.h>
#include <qcombobox.h>
#include <qdatetime.h>
#include <qlineedit.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <kdebug.h>
#include <klocale.h>
#include "ktimeedit.h"
#include <qvalidator.h>
#include "ktimeedit.moc"
// Validator for a time value with only hours and minutes (no seconds)
// Mostly locale aware. Author: David Faure <faure@kde.org>
class KOTimeValidator : public QValidator
{
public:
KOTimeValidator(QWidget* parent, const char* name=0) : QValidator(parent, name) {}
virtual State validate(QString& str, int& /*cursorPos*/) const
{
int length = str.length();
// empty string is intermediate so one can clear the edit line and start from scratch
if ( length <= 0 )
return Intermediate;
bool ok = false;
/*QTime time =*/ KGlobal::locale()->readTime(str, KLocale::WithoutSeconds, &ok);
if ( ok )
return Acceptable;
// kdDebug(5300)<<"Time "<<str<<" not directly acceptable, trying military format "<<endl;
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = str.toInt( &ok );
if ( ok && ( 0 <= tm ) ) {
if ( ( tm < 2400 ) && ( tm%100 < 60 ) )
return Acceptable;
else
return Intermediate;
}
// kdDebug(5300)<<str<<" not acceptable or intermediate for military format, either "<<str<<endl;
// readTime doesn't help knowing when the string is "Intermediate".
// HACK. Not fully locale aware etc. (esp. the separator is '.' in sv_SE...)
QChar sep = ':';
// I want to allow "HH:", ":MM" and ":" to make editing easier
if ( str[0] == sep )
{
if ( length == 1 ) // just ":"
return Intermediate;
QString minutes = str.mid(1);
int m = minutes.toInt(&ok);
if ( ok && m >= 0 && m < 60 )
return Intermediate;
} else if ( str[str.length()-1] == sep )
{
QString hours = str.left(length-1);
int h = hours.toInt(&ok);
if ( ok && h >= 0 && h < 24 )
return Intermediate;
}
return Invalid;
}
virtual void fixup ( QString & input ) const {
bool ok = false;
KGlobal::locale()->readTime( input, KLocale::WithoutSeconds, &ok );
if ( !ok ) {
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = input.toInt( &ok );
if ( ( 0 <= tm ) && ( tm < 2400 ) && ( tm%100 < 60 ) && ok ) {
input = KGlobal::locale()->formatTime( QTime( tm / 100, tm % 100, 0 ) );
}
}
}
};
// KTimeWidget/QTimeEdit provide nicer editing, but don't provide a combobox.
// Difficult to get all in one...
// But Qt-3.2 will offer QLineEdit::setMask, so a "99:99" mask would help.
KTimeEdit::KTimeEdit( QWidget *parent, QTime qt, const char *name )
: QComboBox( true, parent, name )
{
setInsertionPolicy( NoInsertion );
setValidator( new KOTimeValidator( this ) );
mTime = qt;
// mNoTimeString = i18n("No Time");
// insertItem( mNoTimeString );
// Fill combo box with selection of times in localized format.
QTime timeEntry(0,0,0);
do {
insertItem(KGlobal::locale()->formatTime(timeEntry));
timeEntry = timeEntry.addSecs(60*15);
} while (!timeEntry.isNull());
// Add end of day.
insertItem( KGlobal::locale()->formatTime( QTime( 23, 59, 59 ) ) );
updateText();
setFocusPolicy(QWidget::StrongFocus);
connect(this, SIGNAL(activated(int)), this, SLOT(active(int)));
connect(this, SIGNAL(highlighted(int)), this, SLOT(hilit(int)));
connect(this, SIGNAL(textChanged(const QString&)),this,SLOT(changedText()));
}
KTimeEdit::~KTimeEdit()
{
}
bool KTimeEdit::hasTime() const
{
// Can't happen
if ( currentText().isEmpty() ) return false;
//if ( currentText() == mNoTimeString ) return false;
return true; // always
}
QTime KTimeEdit::getTime() const
{
//kdDebug(5300) << "KTimeEdit::getTime(), currentText() = " << currentText() << endl;
// TODO use KLocale::WithoutSeconds in HEAD
bool ok = false;
QTime time = KGlobal::locale()->readTime( currentText(), KLocale::WithoutSeconds, &ok );
if ( !ok ) {
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = currentText().toInt( &ok );
if ( ( 0 <= tm ) && ( tm < 2400 ) && ( tm%100 < 60 ) && ok ) {
time.setHMS( tm / 100, tm % 100, 0 );
} else {
ok = false;
}
}
kdDebug(5300) << "KTimeEdit::getTime(): " << time.toString() << endl;
return time;
}
QSizePolicy KTimeEdit::sizePolicy() const
{
// Set size policy to Fixed, because edit cannot contain more text than the
// string representing the time. It doesn't make sense to provide more space.
QSizePolicy sizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
return sizePolicy;
}
void KTimeEdit::setTime(QTime newTime)
{
if ( mTime != newTime )
{
kdDebug(5300) << "KTimeEdit::setTime(): " << newTime.toString() << endl;
mTime = newTime;
updateText();
}
}
void KTimeEdit::active(int i)
{
// The last entry, 23:59, is a special case
if( i == count() - 1 )
mTime = QTime( 23, 59, 0 );
else
mTime = QTime(0,0,0).addSecs(i*15*60);
emit timeChanged(mTime);
}
void KTimeEdit::hilit(int )
{
// we don't currently need to do anything here.
}
void KTimeEdit::addTime(QTime qt)
{
// Calculate the new time.
mTime = qt.addSecs(mTime.minute()*60+mTime.hour()*3600);
updateText();
emit timeChanged(mTime);
}
void KTimeEdit::subTime(QTime qt)
{
int h, m;
// Note that we cannot use the same method for determining the new
// time as we did in addTime, because QTime does not handle adding
// negative seconds well at all.
h = mTime.hour()-qt.hour();
m = mTime.minute()-qt.minute();
if(m < 0) {
m += 60;
h -= 1;
}
if(h < 0) {
h += 24;
}
// store the newly calculated time.
mTime.setHMS(h, m, 0);
updateText();
emit timeChanged(mTime);
}
void KTimeEdit::keyPressEvent(QKeyEvent *qke)
{
switch(qke->key()) {
case Key_Down:
addTime(QTime(0,1,0));
break;
case Key_Up:
subTime(QTime(0,1,0));
break;
case Key_Prior:
subTime(QTime(1,0,0));
break;
case Key_Next:
addTime(QTime(1,0,0));
break;
default:
QComboBox::keyPressEvent(qke);
break;
} // switch
}
void KTimeEdit::updateText()
{
// kdDebug(5300) << "KTimeEdit::updateText() " << endl;
QString s = KGlobal::locale()->formatTime(mTime);
// Set the text but without emitting signals, nor losing the cursor position
QLineEdit *line = lineEdit();
line->blockSignals(true);
int pos = line->cursorPosition();
line->setText(s);
line->setCursorPosition(pos);
line->blockSignals(false);
// kdDebug(5300) << "KTimeEdit::updateText(): " << s << endl;
if (!mTime.minute() % 15) {
setCurrentItem((mTime.hour()*4)+(mTime.minute()/15));
}
}
bool KTimeEdit::inputIsValid() const
{
int cursorPos = lineEdit()->cursorPosition();
QString str = currentText();
return validator()->validate( str, cursorPos ) == QValidator::Acceptable;
}
void KTimeEdit::changedText()
{
//kdDebug(5300) << "KTimeEdit::changedText()" << endl;
if ( inputIsValid() )
{
mTime = getTime();
emit timeChanged(mTime);
}
}
<commit_msg>Now that cvs head is open for commits again, apply the patch. It allows all input into time edit widgets until the dialog is closed. Without it, working with am/pm times didnt' work at all.<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 1999 Preston Brown, Ian Dawes
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qkeycode.h>
#include <qcombobox.h>
#include <qdatetime.h>
#include <qlineedit.h>
#include <kmessagebox.h>
#include <kglobal.h>
#include <kdebug.h>
#include <klocale.h>
#include "ktimeedit.h"
#include <qvalidator.h>
#include "ktimeedit.moc"
// Validator for a time value with only hours and minutes (no seconds)
// Mostly locale aware. Author: David Faure <faure@kde.org>
class KOTimeValidator : public QValidator
{
public:
KOTimeValidator(QWidget* parent, const char* name=0) : QValidator(parent, name) {}
virtual State validate(QString& str, int& /*cursorPos*/) const
{
int length = str.length();
// empty string is intermediate so one can clear the edit line and start from scratch
if ( length <= 0 )
return Intermediate;
bool ok = false;
/*QTime time =*/ KGlobal::locale()->readTime(str, KLocale::WithoutSeconds, &ok);
if ( ok )
return Acceptable;
// kdDebug(5300)<<"Time "<<str<<" not directly acceptable, trying military format "<<endl;
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = str.toInt( &ok );
if ( ok && ( 0 <= tm ) ) {
if ( ( tm < 2400 ) && ( tm%100 < 60 ) )
return Acceptable;
else
return Intermediate;
}
// kdDebug(5300)<<str<<" not acceptable or intermediate for military format, either "<<str<<endl;
// readTime doesn't help knowing when the string is "Intermediate".
// HACK. Not fully locale aware etc. (esp. the separator is '.' in sv_SE...)
QChar sep = ':';
// I want to allow "HH:", ":MM" and ":" to make editing easier
if ( str[0] == sep )
{
if ( length == 1 ) // just ":"
return Intermediate;
QString minutes = str.mid(1);
int m = minutes.toInt(&ok);
if ( ok && m >= 0 && m < 60 )
return Intermediate;
} else if ( str[str.length()-1] == sep )
{
QString hours = str.left(length-1);
int h = hours.toInt(&ok);
if ( ok && h >= 0 && h < 24 )
return Intermediate;
}
// return Invalid;
return Intermediate;
}
virtual void fixup ( QString & input ) const {
bool ok = false;
KGlobal::locale()->readTime( input, KLocale::WithoutSeconds, &ok );
if ( !ok ) {
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = input.toInt( &ok );
if ( ( 0 <= tm ) && ( tm < 2400 ) && ( tm%100 < 60 ) && ok ) {
input = KGlobal::locale()->formatTime( QTime( tm / 100, tm % 100, 0 ) );
}
}
}
};
// KTimeWidget/QTimeEdit provide nicer editing, but don't provide a combobox.
// Difficult to get all in one...
// But Qt-3.2 will offer QLineEdit::setMask, so a "99:99" mask would help.
KTimeEdit::KTimeEdit( QWidget *parent, QTime qt, const char *name )
: QComboBox( true, parent, name )
{
setInsertionPolicy( NoInsertion );
setValidator( new KOTimeValidator( this ) );
mTime = qt;
// mNoTimeString = i18n("No Time");
// insertItem( mNoTimeString );
// Fill combo box with selection of times in localized format.
QTime timeEntry(0,0,0);
do {
insertItem(KGlobal::locale()->formatTime(timeEntry));
timeEntry = timeEntry.addSecs(60*15);
} while (!timeEntry.isNull());
// Add end of day.
insertItem( KGlobal::locale()->formatTime( QTime( 23, 59, 59 ) ) );
updateText();
setFocusPolicy(QWidget::StrongFocus);
connect(this, SIGNAL(activated(int)), this, SLOT(active(int)));
connect(this, SIGNAL(highlighted(int)), this, SLOT(hilit(int)));
connect(this, SIGNAL(textChanged(const QString&)),this,SLOT(changedText()));
}
KTimeEdit::~KTimeEdit()
{
}
bool KTimeEdit::hasTime() const
{
// Can't happen
if ( currentText().isEmpty() ) return false;
//if ( currentText() == mNoTimeString ) return false;
return true; // always
}
QTime KTimeEdit::getTime() const
{
//kdDebug(5300) << "KTimeEdit::getTime(), currentText() = " << currentText() << endl;
// TODO use KLocale::WithoutSeconds in HEAD
bool ok = false;
QTime time = KGlobal::locale()->readTime( currentText(), KLocale::WithoutSeconds, &ok );
if ( !ok ) {
// Also try to accept times in "military format", i.e. no delimiter, like 1200
int tm = currentText().toInt( &ok );
if ( ( 0 <= tm ) && ( tm < 2400 ) && ( tm%100 < 60 ) && ok ) {
time.setHMS( tm / 100, tm % 100, 0 );
} else {
ok = false;
}
}
kdDebug(5300) << "KTimeEdit::getTime(): " << time.toString() << endl;
return time;
}
QSizePolicy KTimeEdit::sizePolicy() const
{
// Set size policy to Fixed, because edit cannot contain more text than the
// string representing the time. It doesn't make sense to provide more space.
QSizePolicy sizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
return sizePolicy;
}
void KTimeEdit::setTime(QTime newTime)
{
if ( mTime != newTime )
{
kdDebug(5300) << "KTimeEdit::setTime(): " << newTime.toString() << endl;
mTime = newTime;
updateText();
}
}
void KTimeEdit::active(int i)
{
// The last entry, 23:59, is a special case
if( i == count() - 1 )
mTime = QTime( 23, 59, 0 );
else
mTime = QTime(0,0,0).addSecs(i*15*60);
emit timeChanged(mTime);
}
void KTimeEdit::hilit(int )
{
// we don't currently need to do anything here.
}
void KTimeEdit::addTime(QTime qt)
{
// Calculate the new time.
mTime = qt.addSecs(mTime.minute()*60+mTime.hour()*3600);
updateText();
emit timeChanged(mTime);
}
void KTimeEdit::subTime(QTime qt)
{
int h, m;
// Note that we cannot use the same method for determining the new
// time as we did in addTime, because QTime does not handle adding
// negative seconds well at all.
h = mTime.hour()-qt.hour();
m = mTime.minute()-qt.minute();
if(m < 0) {
m += 60;
h -= 1;
}
if(h < 0) {
h += 24;
}
// store the newly calculated time.
mTime.setHMS(h, m, 0);
updateText();
emit timeChanged(mTime);
}
void KTimeEdit::keyPressEvent(QKeyEvent *qke)
{
switch(qke->key()) {
case Key_Down:
addTime(QTime(0,1,0));
break;
case Key_Up:
subTime(QTime(0,1,0));
break;
case Key_Prior:
subTime(QTime(1,0,0));
break;
case Key_Next:
addTime(QTime(1,0,0));
break;
default:
QComboBox::keyPressEvent(qke);
break;
} // switch
}
void KTimeEdit::updateText()
{
// kdDebug(5300) << "KTimeEdit::updateText() " << endl;
QString s = KGlobal::locale()->formatTime(mTime);
// Set the text but without emitting signals, nor losing the cursor position
QLineEdit *line = lineEdit();
line->blockSignals(true);
int pos = line->cursorPosition();
line->setText(s);
line->setCursorPosition(pos);
line->blockSignals(false);
// kdDebug(5300) << "KTimeEdit::updateText(): " << s << endl;
if (!mTime.minute() % 15) {
setCurrentItem((mTime.hour()*4)+(mTime.minute()/15));
}
}
bool KTimeEdit::inputIsValid() const
{
int cursorPos = lineEdit()->cursorPosition();
QString str = currentText();
return validator()->validate( str, cursorPos ) == QValidator::Acceptable;
}
void KTimeEdit::changedText()
{
//kdDebug(5300) << "KTimeEdit::changedText()" << endl;
if ( inputIsValid() )
{
mTime = getTime();
emit timeChanged(mTime);
}
}
<|endoftext|>
|
<commit_before>// $Id: steepestDescent.C,v 1.2 1999/08/31 22:01:17 oliver Exp $
#include <BALL/MOLMEC/MINIMIZATION/steepestDescent.h>
#include <BALL/COMMON/limits.h>
namespace BALL
{
Size SteepestDescentMinimizer::Default::MAX_STEPS = 6;
float SteepestDescentMinimizer::Default::MAX_GRADIENT = 0.001;
const char* SteepestDescentMinimizer::Option::MAX_STEPS = "max_steps";
const char* SteepestDescentMinimizer::Option::MAX_GRADIENT = "max_gradient";
// default constructor
SteepestDescentMinimizer::SteepestDescentMinimizer()
: EnergyMinimizer()
{
}
// copy constructor
SteepestDescentMinimizer::SteepestDescentMinimizer(const SteepestDescentMinimizer& line_search_minimizer, bool /* deep */)
: EnergyMinimizer(line_search_minimizer)
{
}
// assignment operator
SteepestDescentMinimizer& SteepestDescentMinimizer::operator = (const SteepestDescentMinimizer& line_search_minimizer)
{
EnergyMinimizer::operator = (line_search_minimizer);
return *this;
}
// Constructor initialized with a force field
SteepestDescentMinimizer::SteepestDescentMinimizer(ForceField& force_field)
: EnergyMinimizer()
{
valid_ = setup(force_field);
if (!valid_)
{
Log.level(LogStream::ERROR) << " line search minimizer setup failed! " << endl;
}
}
// Constructor initialized with a force field and a set of options
SteepestDescentMinimizer::SteepestDescentMinimizer(ForceField& force_field, const Options& new_options)
: EnergyMinimizer()
{
valid_ = setup(force_field, new_options);
if (!valid_)
{
Log.level(LogStream::ERROR) << " Line search minimizer setup failed! " << endl;
}
}
// destructor
SteepestDescentMinimizer::~SteepestDescentMinimizer()
{
}
// virtual function for the specific setup of derived classes
bool SteepestDescentMinimizer::specificSetup()
{
max_steps_ = (Size)options.setDefaultInteger(SteepestDescentMinimizer::Option::MAX_STEPS, (long)SteepestDescentMinimizer::Default::MAX_STEPS);
max_gradient_ = options.setDefaultReal(SteepestDescentMinimizer::Option::MAX_GRADIENT, SteepestDescentMinimizer::Default::MAX_GRADIENT);
return true;
}
// Set the parameter max_steps_
void SteepestDescentMinimizer::setMaxSteps(Size max_steps)
{
max_steps_ = max_steps;
}
// Get the parameter max_steps_
Size SteepestDescentMinimizer::getMaxSteps() const
{
return max_steps_;
}
// Set the parameter max_gradient_
void SteepestDescentMinimizer::setMaxGradient(float max_gradient)
{
max_gradient_ = max_gradient;
}
// Get the parameter max_steps_
float SteepestDescentMinimizer::getMaxGradient() const
{
return max_gradient_;
}
/* The minimizer optimizes the energy of the system
using a modified line search algorithm.
*/
bool SteepestDescentMinimizer::minimize(Size steps, bool restart)
{
// define some static variables used for restarting
static float step_size = maximal_shift_; // the current step size
static Size last_update = 1; // last update of gradient (in number of iterations)
static Size same_energy_counter = 0; // number of times the same energy was calculated (in number of iterations)
static float gradient_norm = 0; // norm of the gradient
static float last_energy = 0; // energy of the last iteration
static float min_energy = 0; // minimum energy encountered
static float energy = 0; // last calculated energy
// Checking the minimizer
if (isValid() == false)
{
Log.level(LogStream::ERROR) << "The steepest descent minimizer is not valid!" << endl;
return false;
}
// if there are no atoms to optimize, return immediately - we have found the optimal
// solution!
Size number_of_movable_atoms = force_field_->getNumberOfMovableAtoms();
if (number_of_movable_atoms == 0)
{
return true;
}
vector<Atom*>::const_iterator it;
if (!restart)
{
// reset the step size to its default value
step_size = maximal_shift_;
// calculate initial gradient and gradient norm
force_field_->updateForces();
gradient_norm = 0;
it = force_field_->getAtoms().begin();
for ( ; it != force_field_->getAtoms().end() ; ++it)
{
gradient_norm += (*it)->getForce().getSquareLength();
}
// calculate the RMS gradient (termination condition)
// in units of kJ/(mol A)
gradient_norm = sqrt(gradient_norm / (3.0 * (float)number_of_movable_atoms));
gradient_norm *= Constants::AVOGADRO / 1e13;
// if the gradient norm is zero, return (we are converged)
if (gradient_norm == 0.0)
{
return true;
}
}
float factor;
// Iterate and minimize
Size iteration = 0;
// if no limit to the number of steps is given, ignore it
if (steps == 0)
{
steps = Limits<Size>::max();
}
float energy_change = 0.0;
while ((number_of_iteration_ < maximal_number_of_iterations_) && (iteration < steps))
{
// calculate current energy
energy_change = energy;
energy = force_field_->updateEnergy();
energy_change = energy - energy_change;
// check whether the energy changed
if (fabs((energy - last_energy) / energy) < 1e-9)
{
same_energy_counter++;
if (same_energy_counter == 20)
{
break;
}
} else {
last_energy = energy;
same_energy_counter = 0;
}
// accept a taken step if it results in a lower energy
if ((energy < min_energy) || (number_of_iteration_ == 0)
|| ((restart == false) && (iteration == 0))
|| (last_update > 10))
{
// if the last 10 steps didn't improve energy, we're in trouble
// let's recalculate the gradient and increase the step size to get
// out of here
if (last_update > 10)
{
step_size *= 500;
} else {
min_energy = energy;
}
last_update = 0;
// update gradient and gradient norm
force_field_->updateForces();
gradient_norm = 0;
it = force_field_->getAtoms().begin();
for ( ; it != force_field_->getAtoms().end() ; ++it)
{
gradient_norm += (*it)->getForce().getSquareLength();
}
// calculate the RMS gradient (termination condition)
// in units of kJ/(mol A)
gradient_norm = sqrt(gradient_norm / (3.0 * (float)number_of_movable_atoms));
gradient_norm *= Constants::AVOGADRO / 1.0e13;
// check for convergence
if (gradient_norm <= max_gradient_)
{
break;
}
// increase step_size
step_size *= 1.1;
// calculate factor for atom displacements
factor = Constants::AVOGADRO / 1.0e13 * step_size / gradient_norm;
cout << "+step: " << step_size << " -> ";
} else {
// this step didn't result in a lower energy
// make half a step back and retry
// calculate factor for atom displacements
factor = - Constants::AVOGADRO / 1.0e13 * (step_size * 0.5) / gradient_norm; // half step back
// reduce step size
step_size *= 0.5;
last_update++;
cout << "-step: " << step_size << " -> ";
}
//iterate over all movable atoms
it = force_field_->getAtoms().begin();
for (Size i = 0; i < number_of_movable_atoms ; ++i, ++it)
{
(*it)->setPosition((*it)->getPosition() + factor * (*it)->getForce());
}
// BAUSTELLE: Trajectory and non-bonded vector
// Test if the trajectory has to be updated
if ((number_of_iteration_ % force_field_->getUpdateFrequency()) == 0)
{
force_field_->update();
}
// Test if the energy has to be written
if (number_of_iteration_ % energy_output_frequency_ == 0)
{
Log.info() << "iteration " << number_of_iteration_
<< " energy: " << energy << " kJ/mol"
<< " min_en: " << min_energy << " kJ/mol"
<< " grad: " << gradient_norm / 4.184 << " kcal/(mol A)"
<< " energy_change: " << energy_change << " kJ/mol"
<< endl;
}
// count iterations
iteration++;
number_of_iteration_++;
}
// test whether convergence was reached
return (gradient_norm <= max_gradient_) || (same_energy_counter == 20);
}
} // namespace BALL
<commit_msg>removed some debugging messages<commit_after>// $Id: steepestDescent.C,v 1.3 1999/09/15 08:40:25 len Exp $
#include <BALL/MOLMEC/MINIMIZATION/steepestDescent.h>
#include <BALL/COMMON/limits.h>
namespace BALL
{
Size SteepestDescentMinimizer::Default::MAX_STEPS = 6;
float SteepestDescentMinimizer::Default::MAX_GRADIENT = 0.001;
const char* SteepestDescentMinimizer::Option::MAX_STEPS = "max_steps";
const char* SteepestDescentMinimizer::Option::MAX_GRADIENT = "max_gradient";
// default constructor
SteepestDescentMinimizer::SteepestDescentMinimizer()
: EnergyMinimizer()
{
}
// copy constructor
SteepestDescentMinimizer::SteepestDescentMinimizer(const SteepestDescentMinimizer& line_search_minimizer, bool /* deep */)
: EnergyMinimizer(line_search_minimizer)
{
}
// assignment operator
SteepestDescentMinimizer& SteepestDescentMinimizer::operator = (const SteepestDescentMinimizer& line_search_minimizer)
{
EnergyMinimizer::operator = (line_search_minimizer);
return *this;
}
// Constructor initialized with a force field
SteepestDescentMinimizer::SteepestDescentMinimizer(ForceField& force_field)
: EnergyMinimizer()
{
valid_ = setup(force_field);
if (!valid_)
{
Log.level(LogStream::ERROR) << " line search minimizer setup failed! " << endl;
}
}
// Constructor initialized with a force field and a set of options
SteepestDescentMinimizer::SteepestDescentMinimizer(ForceField& force_field, const Options& new_options)
: EnergyMinimizer()
{
valid_ = setup(force_field, new_options);
if (!valid_)
{
Log.level(LogStream::ERROR) << " Line search minimizer setup failed! " << endl;
}
}
// destructor
SteepestDescentMinimizer::~SteepestDescentMinimizer()
{
}
// virtual function for the specific setup of derived classes
bool SteepestDescentMinimizer::specificSetup()
{
max_steps_ = (Size)options.setDefaultInteger(SteepestDescentMinimizer::Option::MAX_STEPS, (long)SteepestDescentMinimizer::Default::MAX_STEPS);
max_gradient_ = options.setDefaultReal(SteepestDescentMinimizer::Option::MAX_GRADIENT, SteepestDescentMinimizer::Default::MAX_GRADIENT);
return true;
}
// Set the parameter max_steps_
void SteepestDescentMinimizer::setMaxSteps(Size max_steps)
{
max_steps_ = max_steps;
}
// Get the parameter max_steps_
Size SteepestDescentMinimizer::getMaxSteps() const
{
return max_steps_;
}
// Set the parameter max_gradient_
void SteepestDescentMinimizer::setMaxGradient(float max_gradient)
{
max_gradient_ = max_gradient;
}
// Get the parameter max_steps_
float SteepestDescentMinimizer::getMaxGradient() const
{
return max_gradient_;
}
/* The minimizer optimizes the energy of the system
using a modified line search algorithm.
*/
bool SteepestDescentMinimizer::minimize(Size steps, bool restart)
{
// define some static variables used for restarting
static float step_size = maximal_shift_; // the current step size
static Size last_update = 1; // last update of gradient (in number of iterations)
static Size same_energy_counter = 0; // number of times the same energy was calculated (in number of iterations)
static float gradient_norm = 0; // norm of the gradient
static float last_energy = 0; // energy of the last iteration
static float min_energy = 0; // minimum energy encountered
static float energy = 0; // last calculated energy
// Checking the minimizer
if (isValid() == false)
{
Log.level(LogStream::ERROR) << "The steepest descent minimizer is not valid!" << endl;
return false;
}
// if there are no atoms to optimize, return immediately - we have found the optimal
// solution!
Size number_of_movable_atoms = force_field_->getNumberOfMovableAtoms();
if (number_of_movable_atoms == 0)
{
return true;
}
vector<Atom*>::const_iterator it;
if (!restart)
{
// reset the step size to its default value
step_size = maximal_shift_;
// calculate initial gradient and gradient norm
force_field_->updateForces();
gradient_norm = 0;
it = force_field_->getAtoms().begin();
for ( ; it != force_field_->getAtoms().end() ; ++it)
{
gradient_norm += (*it)->getForce().getSquareLength();
}
// calculate the RMS gradient (termination condition)
// in units of kJ/(mol A)
gradient_norm = sqrt(gradient_norm / (3.0 * (float)number_of_movable_atoms));
gradient_norm *= Constants::AVOGADRO / 1e13;
// if the gradient norm is zero, return (we are converged)
if (gradient_norm == 0.0)
{
return true;
}
}
float factor;
// Iterate and minimize
Size iteration = 0;
// if no limit to the number of steps is given, ignore it
if (steps == 0)
{
steps = Limits<Size>::max();
}
float energy_change = 0.0;
while ((number_of_iteration_ < maximal_number_of_iterations_) && (iteration < steps))
{
// calculate current energy
energy_change = energy;
energy = force_field_->updateEnergy();
energy_change = energy - energy_change;
// check whether the energy changed
if (fabs((energy - last_energy) / energy) < 1e-9)
{
same_energy_counter++;
if (same_energy_counter == 20)
{
break;
}
} else {
last_energy = energy;
same_energy_counter = 0;
}
// accept a taken step if it results in a lower energy
if ((energy < min_energy) || (number_of_iteration_ == 0)
|| ((restart == false) && (iteration == 0))
|| (last_update > 10))
{
// if the last 10 steps didn't improve energy, we're in trouble
// let's recalculate the gradient and increase the step size to get
// out of here
if (last_update > 10)
{
step_size *= 500;
} else {
min_energy = energy;
}
last_update = 0;
// update gradient and gradient norm
force_field_->updateForces();
gradient_norm = 0;
it = force_field_->getAtoms().begin();
for ( ; it != force_field_->getAtoms().end() ; ++it)
{
gradient_norm += (*it)->getForce().getSquareLength();
}
// calculate the RMS gradient (termination condition)
// in units of kJ/(mol A)
gradient_norm = sqrt(gradient_norm / (3.0 * (float)number_of_movable_atoms));
gradient_norm *= Constants::AVOGADRO / 1.0e13;
// check for convergence
if (gradient_norm <= max_gradient_)
{
break;
}
// increase step_size
step_size *= 1.1;
// calculate factor for atom displacements
factor = Constants::AVOGADRO / 1.0e13 * step_size / gradient_norm;
} else {
// this step didn't result in a lower energy
// make half a step back and retry
// calculate factor for atom displacements
factor = - Constants::AVOGADRO / 1.0e13 * (step_size * 0.5) / gradient_norm; // half step back
// reduce step size
step_size *= 0.5;
last_update++;
}
//iterate over all movable atoms
it = force_field_->getAtoms().begin();
for (Size i = 0; i < number_of_movable_atoms ; ++i, ++it)
{
(*it)->setPosition((*it)->getPosition() + factor * (*it)->getForce());
}
// BAUSTELLE: Trajectory and non-bonded vector
// Test if the trajectory has to be updated
if ((number_of_iteration_ % force_field_->getUpdateFrequency()) == 0)
{
force_field_->update();
}
// Test if the energy has to be written
if (number_of_iteration_ % energy_output_frequency_ == 0)
{
Log.info() << "iteration " << number_of_iteration_
<< " energy: " << energy << " kJ/mol"
<< " min_en: " << min_energy << " kJ/mol"
<< " grad: " << gradient_norm << " kJ/(mol A)"
<< " energy_change: " << energy_change << " kJ/mol"
<< endl;
}
// count iterations
iteration++;
number_of_iteration_++;
}
// test whether convergence was reached
return (gradient_norm <= max_gradient_) || (same_energy_counter == 20);
}
} // namespace BALL
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
#include "Util.h"
#include "Timer.h"
#include "util/usage.hh"
namespace Moses
{
/***
* Return the total wall time that the timer has been in the "running"
* state since it was first "started".
*/
double Timer::get_elapsed_time() const
{
if (stopped) {
return stop_time - start_time;
}
if (running) {
return util::WallTime() - start_time;
}
return 0;
}
/***
* Start a timer. If it is already running, let it continue running.
* Print an optional message.
*/
void Timer::start(const char* msg)
{
// Print an optional message, something like "Starting timer t";
if (msg) TRACE_ERR( msg << std::endl);
// Return immediately if the timer is already running
if (running && !stopped) return;
// If stopped, recompute start time
if (stopped) {
start_time = util::WallTime() - (stop_time - start_time);
stopped = false;
}
else {
start_time = util::WallTime();
running = true;
}
}
/***
* Stop a timer.
* Print an optional message.
*/
void Timer::stop(const char* msg)
{
// Print an optional message, something like "Stopping timer t";
if (msg) TRACE_ERR( msg << std::endl);
// Return immediately if the timer is not running
if (stopped || !running) return;
// Record stopped time
stop_time = util::WallTime();
// Change timer status to running
stopped = true;
}
/***
* Print out an optional message followed by the current timer timing.
*/
void Timer::check(const char* msg)
{
// Print an optional message, something like "Checking timer t";
if (msg) TRACE_ERR( msg << " : ");
// TRACE_ERR( "[" << std::setiosflags(std::ios::fixed) << std::setprecision(2) << (running ? elapsed_time() : 0) << "] seconds\n");
TRACE_ERR( "[" << (running ? get_elapsed_time() : 0) << "] seconds\n");
}
/***
* Allow timers to be printed to ostreams using the syntax 'os << t'
* for an ostream 'os' and a timer 't'. For example, "cout << t" will
* print out the total amount of time 't' has been "running".
*/
std::ostream& operator<<(std::ostream& os, Timer& t)
{
//os << std::setprecision(2) << std::setiosflags(std::ios::fixed) << (t.running ? t.elapsed_time() : 0);
os << (t.running ? t.get_elapsed_time() : 0);
return os;
}
}
<commit_msg>Timer: no log output if verbosity parameter is 0<commit_after>#include <iostream>
#include <iomanip>
#include "Util.h"
#include "Timer.h"
#include "StaticData.h"
#include "util/usage.hh"
namespace Moses
{
/***
* Return the total wall time that the timer has been in the "running"
* state since it was first "started".
*/
double Timer::get_elapsed_time() const
{
if (stopped) {
return stop_time - start_time;
}
if (running) {
return util::WallTime() - start_time;
}
return 0;
}
/***
* Start a timer. If it is already running, let it continue running.
* Print an optional message.
*/
void Timer::start(const char* msg)
{
// Print an optional message, something like "Starting timer t";
if (msg) VERBOSE(1, msg << std::endl);
// Return immediately if the timer is already running
if (running && !stopped) return;
// If stopped, recompute start time
if (stopped) {
start_time = util::WallTime() - (stop_time - start_time);
stopped = false;
}
else {
start_time = util::WallTime();
running = true;
}
}
/***
* Stop a timer.
* Print an optional message.
*/
void Timer::stop(const char* msg)
{
// Print an optional message, something like "Stopping timer t";
if (msg) VERBOSE(1, msg << std::endl);
// Return immediately if the timer is not running
if (stopped || !running) return;
// Record stopped time
stop_time = util::WallTime();
// Change timer status to running
stopped = true;
}
/***
* Print out an optional message followed by the current timer timing.
*/
void Timer::check(const char* msg)
{
// Print an optional message, something like "Checking timer t";
if (msg) VERBOSE(1, msg << " : ");
// VERBOSE(1, "[" << std::setiosflags(std::ios::fixed) << std::setprecision(2) << (running ? elapsed_time() : 0) << "] seconds\n");
VERBOSE(1, "[" << (running ? get_elapsed_time() : 0) << "] seconds\n");
}
/***
* Allow timers to be printed to ostreams using the syntax 'os << t'
* for an ostream 'os' and a timer 't'. For example, "cout << t" will
* print out the total amount of time 't' has been "running".
*/
std::ostream& operator<<(std::ostream& os, Timer& t)
{
//os << std::setprecision(2) << std::setiosflags(std::ios::fixed) << (t.running ? t.elapsed_time() : 0);
os << (t.running ? t.get_elapsed_time() : 0);
return os;
}
}
<|endoftext|>
|
<commit_before>#include <sal/net/io_service.hpp>
#include <sal/net/internet.hpp>
#include <sal/common.test.hpp>
#if __sal_os_darwin
#include <sal/thread.hpp>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <forward_list>
#include <thread>
using namespace std::chrono_literals;
#endif
namespace {
struct net_io_service
: public sal_test::fixture
{
using datagram_socket_t = sal::net::ip::udp_t::socket_t;
using stream_socket_t = sal::net::ip::tcp_t::socket_t;
using acceptor_t = sal::net::ip::tcp_t::acceptor_t;
sal::net::io_service_t service;
};
TEST_F(net_io_service, make_context)
{
auto ctx = service.make_context();
(void)ctx;
}
TEST_F(net_io_service, make_context_too_small_completion_count)
{
auto ctx = service.make_context(0);
(void)ctx;
}
TEST_F(net_io_service, make_context_too_big_completion_count)
{
auto ctx = service.make_context((std::numeric_limits<size_t>::max)());
(void)ctx;
}
TEST_F(net_io_service, associate_datagram_socket)
{
datagram_socket_t socket(sal::net::ip::udp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_datagram_socket_multiple_times)
{
datagram_socket_t socket(sal::net::ip::udp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_datagram_socket_invalid)
{
datagram_socket_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_stream_socket)
{
stream_socket_t socket(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_stream_socket_multiple_times)
{
stream_socket_t socket(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_stream_socket_invalid)
{
stream_socket_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_acceptor_socket)
{
acceptor_t acceptor(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(acceptor, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_acceptor_socket_multiple_times)
{
acceptor_t acceptor(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(acceptor, error);
EXPECT_TRUE(!error);
service.associate(acceptor, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(acceptor), std::system_error);
}
TEST_F(net_io_service, associate_acceptor_socket_invalid)
{
acceptor_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
#if __sal_os_darwin
using namespace std::chrono;
using namespace std::chrono_literals;
struct kqueue
: public sal_test::fixture
{
int queue;
using socket_t = sal::net::ip::udp_t::socket_t;
const socket_t::endpoint_t endpoint{sal::net::ip::address_v4_t::loopback(), 8192};
socket_t a{endpoint}, b{sal::net::ip::udp_t::v4()};
void SetUp ()
{
queue = ::kqueue();
if (queue == -1)
{
FAIL() << strerror(errno);
}
a.non_blocking(true);
}
void TearDown ()
{
if (queue != -1)
{
::close(queue);
}
}
void send (const std::string &data, bool wait_after_send = true)
{
b.send_to(sal::make_buf(data), endpoint);
if (wait_after_send)
{
std::this_thread::sleep_for(1ms);
}
}
std::string recv (std::error_code &error)
{
char buf[1024];
socket_t::endpoint_t remote_endpoint;
auto size = a.receive_from(sal::make_buf(buf), remote_endpoint, error);
return std::string(buf, size);
}
std::string recv ()
{
return recv(sal::net::throw_on_error("recv"));
}
using string_list = std::vector<std::string>;
string_list drain (std::error_code &error)
{
string_list result;
for (;;)
{
auto packet = recv(error);
if (!error)
{
result.emplace_back(packet);
}
else
{
if (error == std::errc::operation_would_block)
{
error.clear();
}
break;
}
}
return result;
}
string_list drain ()
{
return drain(sal::net::throw_on_error("drain"));
}
void monitor (int filter, int flags)
{
struct ::kevent change;
EV_SET(&change, a.native_handle(), filter, flags, 0, 0, 0);
if (::kevent(queue, &change, 1, nullptr, 0, nullptr) == -1)
{
FAIL() << strerror(errno);
}
}
using event_list = std::vector<struct ::kevent>;
event_list poll (const milliseconds &timeout, std::error_code &error)
{
auto s = duration_cast<seconds>(timeout);
auto ns = duration_cast<nanoseconds>(timeout - s);
struct timespec t = { s.count(), ns.count() };
struct ::kevent events[16];
auto count = ::kevent(queue, nullptr, 0, events, 16, &t);
if (count == -1)
{
error.assign(errno, std::generic_category());
return {};
}
event_list result;
for (auto i = 0; i != count; ++i)
{
result.emplace_back(events[i]);
}
return result;
}
event_list poll (const milliseconds &timeout = 3s)
{
return poll(timeout, sal::net::throw_on_error("poll"));
}
sal::net::socket_base_t::native_handle_t handle (struct ::kevent &ev)
const noexcept
{
return ev.ident;
}
size_t data_size (struct ::kevent &ev) const noexcept
{
return ev.data;
}
};
TEST_F(kqueue, empty)
{
monitor(EVFILT_READ, EV_ADD | EV_CLEAR);
EXPECT_EQ(0U, poll(0ms).size());
}
TEST_F(kqueue, basic)
{
monitor(EVFILT_READ, EV_ADD | EV_CLEAR);
send(case_name);
auto events = poll();
ASSERT_EQ(1U, events.size());
EXPECT_EQ(a.native_handle(), handle(events[0]));
EXPECT_EQ(case_name.size(), data_size(events[0]));
EXPECT_EQ(case_name, recv());
}
TEST_F(kqueue, edge_triggered_no_second_notification)
{
monitor(EVFILT_READ, EV_ADD | EV_CLEAR);
send("one");
auto events = poll();
ASSERT_EQ(1U, events.size());
EXPECT_EQ(3U, data_size(events[0]));
events = poll(0ms);
EXPECT_EQ(0U, events.size());
EXPECT_EQ("one", recv());
}
TEST_F(kqueue, edge_triggered_second_notification_on_new_send)
{
monitor(EVFILT_READ, EV_ADD | EV_CLEAR);
send("one");
auto events = poll();
ASSERT_EQ(1U, events.size());
EXPECT_EQ(3U, data_size(events[0]));
send("two");
events = poll(0ms);
ASSERT_EQ(1U, events.size());
EXPECT_EQ(6U, data_size(events[0]));
string_list packets{"one", "two"};
EXPECT_EQ(packets, drain());
}
TEST_F(kqueue, level_triggered_second_notification)
{
monitor(EVFILT_READ, EV_ADD);
send("one");
auto events = poll();
ASSERT_EQ(1U, events.size());
EXPECT_EQ(3U, data_size(events[0]));
events = poll(0ms);
ASSERT_EQ(1U, events.size());
EXPECT_EQ(3U, data_size(events[0]));
EXPECT_EQ("one", recv());
}
TEST_F(kqueue, level_triggered_second_notification_on_new_send)
{
monitor(EVFILT_READ, EV_ADD);
send("one");
auto events = poll();
ASSERT_EQ(1U, events.size());
EXPECT_EQ(3U, data_size(events[0]));
send("two");
events = poll(0ms);
ASSERT_EQ(1U, events.size());
EXPECT_EQ(6U, data_size(events[0]));
string_list packets{"one", "two"};
EXPECT_EQ(packets, drain());
}
TEST_F(kqueue, single_thread_wakeup)
{
monitor(EVFILT_READ, EV_ADD | EV_CLEAR);
send("one", false);
send("two");
std::atomic<size_t> event_count{};
std::forward_list<std::thread> threads;
for (auto i = 0U; i < std::thread::hardware_concurrency(); ++i)
{
threads.emplace_front([&event_count, this]
{
auto events = poll(1ms);
event_count += events.size();
if (events.size())
{
EXPECT_EQ(6U, data_size(events[0]));
EXPECT_EQ("one", recv());
EXPECT_EQ("two", recv());
}
});
}
for (auto &thread: threads)
{
thread.join();
}
EXPECT_EQ(1U, event_count);
}
#endif // __sal_os_darwin
} // namespace
<commit_msg>net/async: drop kqueue-specific unittests<commit_after>#include <sal/net/io_service.hpp>
#include <sal/net/internet.hpp>
#include <sal/common.test.hpp>
namespace {
struct net_io_service
: public sal_test::fixture
{
using datagram_socket_t = sal::net::ip::udp_t::socket_t;
using stream_socket_t = sal::net::ip::tcp_t::socket_t;
using acceptor_t = sal::net::ip::tcp_t::acceptor_t;
sal::net::io_service_t service;
};
TEST_F(net_io_service, make_context)
{
auto ctx = service.make_context();
(void)ctx;
}
TEST_F(net_io_service, make_context_too_small_completion_count)
{
auto ctx = service.make_context(0);
(void)ctx;
}
TEST_F(net_io_service, make_context_too_big_completion_count)
{
auto ctx = service.make_context((std::numeric_limits<size_t>::max)());
(void)ctx;
}
TEST_F(net_io_service, associate_datagram_socket)
{
datagram_socket_t socket(sal::net::ip::udp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_datagram_socket_multiple_times)
{
datagram_socket_t socket(sal::net::ip::udp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_datagram_socket_invalid)
{
datagram_socket_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_stream_socket)
{
stream_socket_t socket(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_stream_socket_multiple_times)
{
stream_socket_t socket(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(socket, error);
EXPECT_TRUE(!error);
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_stream_socket_invalid)
{
stream_socket_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
TEST_F(net_io_service, associate_acceptor_socket)
{
acceptor_t acceptor(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(acceptor, error);
EXPECT_TRUE(!error);
}
TEST_F(net_io_service, associate_acceptor_socket_multiple_times)
{
acceptor_t acceptor(sal::net::ip::tcp_t::v4());
std::error_code error;
service.associate(acceptor, error);
EXPECT_TRUE(!error);
service.associate(acceptor, error);
EXPECT_FALSE(!error);
EXPECT_EQ(sal::net::socket_errc_t::already_associated, error);
EXPECT_THROW(service.associate(acceptor), std::system_error);
}
TEST_F(net_io_service, associate_acceptor_socket_invalid)
{
acceptor_t socket;
std::error_code error;
service.associate(socket, error);
EXPECT_FALSE(!error);
EXPECT_THROW(service.associate(socket), std::system_error);
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 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 "<WebSig>" 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 apache@apache.org.
*
* 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) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECURIResolverGenericWin32 := A URI Resolver that will work "out of
* the box" with Windows. Re-implements
* much Xerces code, but allows us to
* handle HTTP redirects as is required by
* the DSIG Standard
*
* Author(s): Berin Lautenbach
*
* $Id$
*
* $Log$
* Revision 1.7 2003/09/11 11:11:05 blautenb
* Cleaned up usage of Xerces namespace - no longer inject into global namespace in headers
*
* Revision 1.6 2003/07/28 12:52:46 blautenb
* Fixed a bug with DEBUG_NEW when compiling with Xalan 1.6
*
* Revision 1.5 2003/07/05 10:30:38 blautenb
* Copyright update
*
* Revision 1.4 2003/05/22 11:42:06 blautenb
* Updates so Windows version will compile with Xerces 2.3
*
* Revision 1.3 2003/05/10 07:23:36 blautenb
* Updates to support anonymous references
*
* Revision 1.2 2003/02/17 11:21:45 blautenb
* Work around for Xerces XMLUri bug
*
* Revision 1.1 2003/02/12 09:45:29 blautenb
* Win32 Re-implementation of Xerces URIResolver to support re-directs
*
*
*/
#include "XSECURIResolverGenericWin32.hpp"
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/BinFileInputStream.hpp>
XERCES_CPP_NAMESPACE_USE
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp>
static const XMLCh gFileScheme[] = {
chLatin_f,
chLatin_i,
chLatin_l,
chLatin_e,
chNull
};
static const XMLCh gHttpScheme[] = {
chLatin_h,
chLatin_t,
chLatin_t,
chLatin_p,
chNull
};
#if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3
static const XMLCh DOTDOT_SLASH[] = {
chPeriod,
chPeriod,
chForwardSlash,
chNull
};
#endif
XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() :
mp_baseURI(NULL) {
};
XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
}
// -----------------------------------------------------------------------
// Resolve a URI that is passed in
// -----------------------------------------------------------------------
BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) {
XSEC_USING_XERCES(BinInputStream);
XSEC_USING_XERCES(XMLUri);
XSEC_USING_XERCES(XMLUni);
XSEC_USING_XERCES(Janitor);
XSEC_USING_XERCES(BinFileInputStream);
XMLUri * xmluri;
if (uri == NULL) {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - anonymous references not supported in default URI Resolvers");
}
// Create the appropriate XMLUri objects
if (mp_baseURI != NULL) {
XMLUri * turi;
#if defined(XSEC_XERCES_BROKEN_XMLURI)
// XMLUri relative paths are broken, so we need to strip out ".."
// Doesn't fix the whole problem, but gets us somewhere
XMLCh * b = XMLString::replicate(mp_baseURI);
ArrayJanitor<XMLCh> j_b(b);
XMLCh * r = XMLString::replicate(uri);
ArrayJanitor<XMLCh> j_r(r);
int index = 0;
while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) {
// Strip the last segment of the base
int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash);
if (lastIndex > 0)
b[lastIndex] = 0;
index += 3;
}
XSECnew(turi, XMLUri(b));
Janitor<XMLUri> j_turi(turi);
XSECnew(xmluri, XMLUri(turi, &(r[index])));
#else
turi = new XMLUri(mp_baseURI);
Janitor<XMLUri> j_turi(turi);
xmluri = new XMLUri(turi, uri);
#endif
}
else {
xmluri = new XMLUri(uri);
}
Janitor<XMLUri> j_xmluri(xmluri);
// Determine what kind of URI this is and how to handle it.
if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) {
// This is a file. We only really understand if this is localhost
// XMLUri has already cleaned of escape characters (%xx)
if (xmluri->getHost() == NULL ||
!XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) {
// Localhost
BinFileInputStream* retStrm = new BinFileInputStream(xmluri->getPath());
if (!retStrm->getIsOpen())
{
delete retStrm;
return 0;
}
return retStrm;
}
else {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unable to open non-localhost file");
}
}
// Is the scheme a HTTP?
if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) {
// Pass straight to our local XSECBinHTTPUriInputStream
XSECBinHTTPURIInputStream *ret;
ret = new XSECBinHTTPURIInputStream(*xmluri);
return ret;
}
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unknown URI scheme");
}
// -----------------------------------------------------------------------
// Clone me
// -----------------------------------------------------------------------
XSECURIResolver * XSECURIResolverGenericWin32::clone(void) {
XSECURIResolverGenericWin32 * ret;
ret = new XSECURIResolverGenericWin32();
if (this->mp_baseURI != NULL)
ret->mp_baseURI = XMLString::replicate(this->mp_baseURI);
else
ret->mp_baseURI = NULL;
return ret;
}
// -----------------------------------------------------------------------
// Set a base URI to map any incoming files against
// -----------------------------------------------------------------------
void XSECURIResolverGenericWin32::setBaseURI(const XMLCh * uri) {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
mp_baseURI = XMLString::replicate(uri);
}
<commit_msg>Remove escapes from URI before retrieving a path on the file system<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2002-2003 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 "<WebSig>" 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 apache@apache.org.
*
* 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) 2001, Institute for
* Data Communications Systems, <http://www.nue.et-inf.uni-siegen.de/>.
* The development of this software was partly funded by the European
* Commission in the <WebSig> project in the ISIS Programme.
* For more information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* XSEC
*
* XSECURIResolverGenericWin32 := A URI Resolver that will work "out of
* the box" with Windows. Re-implements
* much Xerces code, but allows us to
* handle HTTP redirects as is required by
* the DSIG Standard
*
* Author(s): Berin Lautenbach
*
* $Id$
*
* $Log$
* Revision 1.8 2004/01/26 00:16:04 blautenb
* Remove escapes from URI before retrieving a path on the file system
*
* Revision 1.7 2003/09/11 11:11:05 blautenb
* Cleaned up usage of Xerces namespace - no longer inject into global namespace in headers
*
* Revision 1.6 2003/07/28 12:52:46 blautenb
* Fixed a bug with DEBUG_NEW when compiling with Xalan 1.6
*
* Revision 1.5 2003/07/05 10:30:38 blautenb
* Copyright update
*
* Revision 1.4 2003/05/22 11:42:06 blautenb
* Updates so Windows version will compile with Xerces 2.3
*
* Revision 1.3 2003/05/10 07:23:36 blautenb
* Updates to support anonymous references
*
* Revision 1.2 2003/02/17 11:21:45 blautenb
* Work around for Xerces XMLUri bug
*
* Revision 1.1 2003/02/12 09:45:29 blautenb
* Win32 Re-implementation of Xerces URIResolver to support re-directs
*
*
*/
#include "XSECURIResolverGenericWin32.hpp"
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUri.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/Janitor.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/BinFileInputStream.hpp>
XERCES_CPP_NAMESPACE_USE
#include <xsec/framework/XSECError.hpp>
#include <xsec/utils/winutils/XSECBinHTTPURIInputStream.hpp>
#include <xsec/utils/XSECDOMUtils.hpp>
static const XMLCh gFileScheme[] = {
chLatin_f,
chLatin_i,
chLatin_l,
chLatin_e,
chNull
};
static const XMLCh gHttpScheme[] = {
chLatin_h,
chLatin_t,
chLatin_t,
chLatin_p,
chNull
};
#if XERCES_VERSION_MAJOR == 2 && XERCES_VERSION_MINOR < 3
static const XMLCh DOTDOT_SLASH[] = {
chPeriod,
chPeriod,
chForwardSlash,
chNull
};
#endif
XSECURIResolverGenericWin32::XSECURIResolverGenericWin32() :
mp_baseURI(NULL) {
};
XSECURIResolverGenericWin32::~XSECURIResolverGenericWin32() {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
}
// -----------------------------------------------------------------------
// Resolve a URI that is passed in
// -----------------------------------------------------------------------
BinInputStream * XSECURIResolverGenericWin32::resolveURI(const XMLCh * uri) {
XSEC_USING_XERCES(BinInputStream);
XSEC_USING_XERCES(XMLUri);
XSEC_USING_XERCES(XMLUni);
XSEC_USING_XERCES(Janitor);
XSEC_USING_XERCES(BinFileInputStream);
XMLUri * xmluri;
if (uri == NULL) {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - anonymous references not supported in default URI Resolvers");
}
// Create the appropriate XMLUri objects
if (mp_baseURI != NULL) {
XMLUri * turi;
#if defined(XSEC_XERCES_BROKEN_XMLURI)
// XMLUri relative paths are broken, so we need to strip out ".."
// Doesn't fix the whole problem, but gets us somewhere
XMLCh * b = XMLString::replicate(mp_baseURI);
ArrayJanitor<XMLCh> j_b(b);
XMLCh * r = XMLString::replicate(uri);
ArrayJanitor<XMLCh> j_r(r);
int index = 0;
while (XMLString::startsWith(&(r[index]), DOTDOT_SLASH)) {
// Strip the last segment of the base
int lastIndex = XMLString::lastIndexOf(b, XERCES_CPP_NAMESPACE_QUALIFIER chForwardSlash);
if (lastIndex > 0)
b[lastIndex] = 0;
index += 3;
}
XSECnew(turi, XMLUri(b));
Janitor<XMLUri> j_turi(turi);
XSECnew(xmluri, XMLUri(turi, &(r[index])));
#else
turi = new XMLUri(mp_baseURI);
Janitor<XMLUri> j_turi(turi);
xmluri = new XMLUri(turi, uri);
#endif
}
else {
xmluri = new XMLUri(uri);
}
Janitor<XMLUri> j_xmluri(xmluri);
// Determine what kind of URI this is and how to handle it.
if (!XMLString::compareIString(xmluri->getScheme(), gFileScheme)) {
// This is a file. We only really understand if this is localhost
if (xmluri->getHost() == NULL || xmluri->getHost()[0] == chNull ||
!XMLString::compareIString(xmluri->getHost(), XMLUni::fgLocalHostString)) {
// Clean hex escapes
XMLCh * realPath = cleanURIEscapes(xmluri->getPath());
ArrayJanitor<XMLCh> j_realPath(realPath);
// Localhost
BinFileInputStream* retStrm = new BinFileInputStream(realPath);
if (!retStrm->getIsOpen())
{
delete retStrm;
return 0;
}
return retStrm;
}
else {
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unable to open non-localhost file");
}
}
// Is the scheme a HTTP?
if (!XMLString::compareIString(xmluri->getScheme(), gHttpScheme)) {
// Pass straight to our local XSECBinHTTPUriInputStream
XSECBinHTTPURIInputStream *ret;
ret = new XSECBinHTTPURIInputStream(*xmluri);
return ret;
}
throw XSECException(XSECException::ErrorOpeningURI,
"XSECURIResolverGenericWin32 - unknown URI scheme");
}
// -----------------------------------------------------------------------
// Clone me
// -----------------------------------------------------------------------
XSECURIResolver * XSECURIResolverGenericWin32::clone(void) {
XSECURIResolverGenericWin32 * ret;
ret = new XSECURIResolverGenericWin32();
if (this->mp_baseURI != NULL)
ret->mp_baseURI = XMLString::replicate(this->mp_baseURI);
else
ret->mp_baseURI = NULL;
return ret;
}
// -----------------------------------------------------------------------
// Set a base URI to map any incoming files against
// -----------------------------------------------------------------------
void XSECURIResolverGenericWin32::setBaseURI(const XMLCh * uri) {
if (mp_baseURI != NULL)
delete[] mp_baseURI;
mp_baseURI = XMLString::replicate(uri);
}
<|endoftext|>
|
<commit_before>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
//
// 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.
//
// Many parts from this (Most of the URScript program) comes from the ur_modern_driver
// Copyright 2017, 2018 Simon Rasmussen (refactor)
// Copyright 2015, 2016 Thomas Timm Andersen (original version)
//
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Mauch mauch@fzi.de
* \date 2019-04-11
*
*/
//----------------------------------------------------------------------
#include "ur_rtde_driver/ur/ur_driver.h"
#include <memory>
namespace ur_driver
{
static const int32_t MULT_JOINTSTATE_ = 1000000;
static const std::string JOINT_STATE_REPLACE("{{JOINT_STATE_REPLACE}}");
static const std::string SERVO_J_REPLACE("{{SERVO_J_REPLACE}}");
static const std::string SERVER_IP_REPLACE("{{SERVER_IP_REPLACE}}");
static const std::string SERVER_PORT_REPLACE("{{SERVER_PORT_REPLACE}}");
static const std::string POSITION_PROGRAM = R"(
def myProg():
global steptime = get_steptime()
textmsg("steptime=", steptime)
MULT_jointstate = {{JOINT_STATE_REPLACE}}
SERVO_IDLE = 0
SERVO_RUNNING = 1
cmd_servo_state = SERVO_IDLE
cmd_servo_q = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
def set_servo_setpoint(q):
enter_critical
cmd_servo_state = SERVO_RUNNING
cmd_servo_q = q
exit_critical
end
thread servoThread():
state = SERVO_IDLE
while True:
enter_critical
q = cmd_servo_q
do_brake = False
if (state == SERVO_RUNNING) and (cmd_servo_state == SERVO_IDLE):
do_brake = True
end
state = cmd_servo_state
cmd_servo_state = SERVO_IDLE
exit_critical
if do_brake:
textmsg("No new setpoint received. Stopping robot.")
stopj(1.0)
sync()
elif state == SERVO_RUNNING:
servoj(q, t=steptime, {{SERVO_J_REPLACE}})
else:
sync()
end
end
end
socket_open("{{SERVER_IP_REPLACE}}", {{SERVER_PORT_REPLACE}}, "reverse_socket")
thread_servo = run servoThread()
keepalive = -2
params_mult = socket_read_binary_integer(6+1, "reverse_socket")
keepalive = params_mult[7]
while keepalive > 0:
params_mult = socket_read_binary_integer(6+1, "reverse_socket", 0.012)
if params_mult[0] > 0:
keepalive = params_mult[7]
q = [params_mult[1] / MULT_jointstate, params_mult[2] / MULT_jointstate, params_mult[3] / MULT_jointstate, params_mult[4] / MULT_jointstate, params_mult[5] / MULT_jointstate, params_mult[6] / MULT_jointstate]
set_servo_setpoint(q)
else:
# TODO: Extrapolation goes here
keepalive = keepalive - 1
end
sync()
end
stopj(1.0)
sleep(.1)
socket_close()
kill thread_servo
end
)";
ur_driver::UrDriver::UrDriver(const std::string& ROBOT_IP)
: servoj_time_(0.008), servoj_gain_(750), servoj_lookahead_time_(0.03)
{
ROS_INFO_STREAM("Initializing RTDE client");
rtde_client_.reset(new rtde_interface::RTDEClient(ROBOT_IP, notifier_));
if (!rtde_client_->init())
{
throw std::runtime_error("initialization went wrong"); // TODO: be less harsh
}
rtde_frequency_ = rtde_client_->getMaxFrequency();
servoj_time_ = 1.0 / rtde_frequency_;
comm::URStream<rtde_interface::PackageHeader> stream(ROBOT_IP, 30001);
stream.connect();
std::string local_ip = stream.getIP();
uint32_t reverse_port = 50001; // TODO: Make this a parameter
std::string prog = POSITION_PROGRAM;
prog.replace(prog.find(JOINT_STATE_REPLACE), JOINT_STATE_REPLACE.length(), std::to_string(MULT_JOINTSTATE_));
std::ostringstream out;
out << "lookahead_time=" << servoj_lookahead_time_ << ", gain=" << servoj_gain_;
prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());
prog.replace(prog.find(SERVER_IP_REPLACE), SERVER_IP_REPLACE.length(), local_ip);
prog.replace(prog.find(SERVER_PORT_REPLACE), SERVER_PORT_REPLACE.length(), std::to_string(reverse_port));
size_t len = prog.size();
const uint8_t* data = reinterpret_cast<const uint8_t*>(prog.c_str());
size_t written;
if (stream.write(data, len, written))
{
LOG_INFO("Sent program to robot");
}
else
{
LOG_ERROR("Could not send program to robot");
}
reverse_interface_.reset(new comm::ReverseInterface(reverse_port));
ROS_INFO_STREAM("Created reverse interface");
rtde_client_->start(); // TODO: Add extra start method (also to HW-Interface)
ROS_INFO_STREAM("Initialization done");
}
std::unique_ptr<rtde_interface::DataPackage> ur_driver::UrDriver::getDataPackage()
{
// TODO: This goes into the rtde_client
std::unique_ptr<comm::URPackage<rtde_interface::PackageHeader>> urpackage;
uint32_t period_ms = (1.0 / rtde_frequency_) * 1000;
// std::chrono::milliseconds timeout(period_ms);
std::chrono::milliseconds timeout(100);
if (rtde_client_->getDataPackage(urpackage, timeout))
{
rtde_interface::DataPackage* tmp = dynamic_cast<rtde_interface::DataPackage*>(urpackage.get());
if (tmp != nullptr)
{
urpackage.release();
return std::unique_ptr<rtde_interface::DataPackage>(tmp);
}
}
return nullptr;
}
bool UrDriver::writeJointCommand(const vector6d_t& values)
{
if (reverse_interface_)
{
reverse_interface_->write(values);
}
else
{
return false;
}
return true;
}
} // namespace ur_driver
<commit_msg>extrapolate on missing packages<commit_after>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
//
// 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.
//
// Many parts from this (Most of the URScript program) comes from the ur_modern_driver
// Copyright 2017, 2018 Simon Rasmussen (refactor)
// Copyright 2015, 2016 Thomas Timm Andersen (original version)
//
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Felix Mauch mauch@fzi.de
* \date 2019-04-11
*
*/
//----------------------------------------------------------------------
#include "ur_rtde_driver/ur/ur_driver.h"
#include <memory>
namespace ur_driver
{
static const int32_t MULT_JOINTSTATE_ = 1000000;
static const std::string JOINT_STATE_REPLACE("{{JOINT_STATE_REPLACE}}");
static const std::string SERVO_J_REPLACE("{{SERVO_J_REPLACE}}");
static const std::string SERVER_IP_REPLACE("{{SERVER_IP_REPLACE}}");
static const std::string SERVER_PORT_REPLACE("{{SERVER_PORT_REPLACE}}");
static const std::string POSITION_PROGRAM = R"(
def myProg():
global steptime = get_steptime()
textmsg("steptime=", steptime)
MULT_jointstate = {{JOINT_STATE_REPLACE}}
SERVO_UNINITIALIZED = -1
SERVO_IDLE = 0
SERVO_RUNNING = 1
cmd_servo_state = SERVO_UNINITIALIZED
cmd_servo_q = get_actual_joint_positions()
cmd_servo_q_last = get_actual_joint_positions()
def set_servo_setpoint(q):
enter_critical
cmd_servo_state = SERVO_RUNNING
cmd_servo_q_last = cmd_servo_q
cmd_servo_q = q
exit_critical
end
def extrapolate():
enter_critical
diff = [cmd_servo_q[0] - cmd_servo_q_last[0], cmd_servo_q[1] - cmd_servo_q_last[1], cmd_servo_q[2] - cmd_servo_q_last[2], cmd_servo_q[3] - cmd_servo_q_last[3], cmd_servo_q[4] - cmd_servo_q_last[4], cmd_servo_q[5] - cmd_servo_q_last[5]]
cmd_servo_q_last = cmd_servo_q
cmd_servo_q = [cmd_servo_q[0] + diff[0], cmd_servo_q[1] + diff[1], cmd_servo_q[2] + diff[2], cmd_servo_q[3] + diff[3], cmd_servo_q[4] + diff[4], cmd_servo_q[5] + diff[5]]
exit_critical
return cmd_servo_q
end
thread servoThread():
state = SERVO_IDLE
while True:
enter_critical
q = cmd_servo_q
do_extrapolate = False
if (cmd_servo_state == SERVO_IDLE):
do_extrapolate = True
end
state = cmd_servo_state
cmd_servo_state = SERVO_IDLE
exit_critical
if do_extrapolate:
textmsg("No new setpoint received. Extrapolating.")
q = extrapolate()
servoj(q, t=steptime, {{SERVO_J_REPLACE}})
elif state == SERVO_RUNNING:
servoj(q, t=steptime, {{SERVO_J_REPLACE}})
else:
textmsg("Should not be here")
sync()
end
end
stopj(0.1)
end
socket_open("{{SERVER_IP_REPLACE}}", {{SERVER_PORT_REPLACE}}, "reverse_socket")
thread_servo = run servoThread()
keepalive = -2
params_mult = socket_read_binary_integer(6+1, "reverse_socket")
keepalive = params_mult[7]
while keepalive > 0:
params_mult = socket_read_binary_integer(6+1, "reverse_socket", steptime)
if params_mult[0] > 0:
keepalive = params_mult[7]
q = [params_mult[1] / MULT_jointstate, params_mult[2] / MULT_jointstate, params_mult[3] / MULT_jointstate, params_mult[4] / MULT_jointstate, params_mult[5] / MULT_jointstate, params_mult[6] / MULT_jointstate]
set_servo_setpoint(q)
else:
# TODO: Extrapolation goes here
keepalive = keepalive - 1
end
end
sleep(.1)
socket_close()
kill thread_servo
end
)";
ur_driver::UrDriver::UrDriver(const std::string& ROBOT_IP)
: servoj_time_(0.008), servoj_gain_(750), servoj_lookahead_time_(0.03)
{
ROS_INFO_STREAM("Initializing RTDE client");
rtde_client_.reset(new rtde_interface::RTDEClient(ROBOT_IP, notifier_));
if (!rtde_client_->init())
{
throw std::runtime_error("initialization went wrong"); // TODO: be less harsh
}
rtde_frequency_ = rtde_client_->getMaxFrequency();
servoj_time_ = 1.0 / rtde_frequency_;
comm::URStream<rtde_interface::PackageHeader> stream(ROBOT_IP, 30001);
stream.connect();
std::string local_ip = stream.getIP();
uint32_t reverse_port = 50001; // TODO: Make this a parameter
std::string prog = POSITION_PROGRAM;
prog.replace(prog.find(JOINT_STATE_REPLACE), JOINT_STATE_REPLACE.length(), std::to_string(MULT_JOINTSTATE_));
std::ostringstream out;
out << "lookahead_time=" << servoj_lookahead_time_ << ", gain=" << servoj_gain_;
prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());
prog.replace(prog.find(SERVO_J_REPLACE), SERVO_J_REPLACE.length(), out.str());
prog.replace(prog.find(SERVER_IP_REPLACE), SERVER_IP_REPLACE.length(), local_ip);
prog.replace(prog.find(SERVER_PORT_REPLACE), SERVER_PORT_REPLACE.length(), std::to_string(reverse_port));
size_t len = prog.size();
const uint8_t* data = reinterpret_cast<const uint8_t*>(prog.c_str());
size_t written;
if (stream.write(data, len, written))
{
LOG_INFO("Sent program to robot");
}
else
{
LOG_ERROR("Could not send program to robot");
}
reverse_interface_.reset(new comm::ReverseInterface(reverse_port));
ROS_INFO_STREAM("Created reverse interface");
rtde_client_->start(); // TODO: Add extra start method (also to HW-Interface)
ROS_INFO_STREAM("Initialization done");
}
std::unique_ptr<rtde_interface::DataPackage> ur_driver::UrDriver::getDataPackage()
{
// TODO: This goes into the rtde_client
std::unique_ptr<comm::URPackage<rtde_interface::PackageHeader>> urpackage;
uint32_t period_ms = (1.0 / rtde_frequency_) * 1000;
// std::chrono::milliseconds timeout(period_ms);
std::chrono::milliseconds timeout(100);
if (rtde_client_->getDataPackage(urpackage, timeout))
{
rtde_interface::DataPackage* tmp = dynamic_cast<rtde_interface::DataPackage*>(urpackage.get());
if (tmp != nullptr)
{
urpackage.release();
return std::unique_ptr<rtde_interface::DataPackage>(tmp);
}
}
return nullptr;
}
bool UrDriver::writeJointCommand(const vector6d_t& values)
{
if (reverse_interface_)
{
reverse_interface_->write(values);
}
else
{
return false;
}
return true;
}
} // namespace ur_driver
<|endoftext|>
|
<commit_before>#include "RansomwareCanary.h"
#include <thread>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../urbackupcommon/glob.h"
#include "../common/miniz.h"
#include "clientdao.h"
#include "database.h"
#ifdef _WIN32
#include <aclapi.h>
#endif
struct SOwner
{
bool has_owner = false;
#ifdef _WIN32
PSID Owner = nullptr;
PSECURITY_DESCRIPTOR sec_d = nullptr;
~SOwner() {
if (sec_d != nullptr)
LocalFree(sec_d);
}
#endif
};
static bool getOwner(const std::string& fn, SOwner& owner)
{
PSID newOwner = nullptr;
PSECURITY_DESCRIPTOR new_sec_d = nullptr;
DWORD rc = GetNamedSecurityInfoW(Server->ConvertToWchar(os_file_prefix(fn)).c_str(),
SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &newOwner, NULL, NULL,
NULL, &new_sec_d);
if (rc == ERROR_SUCCESS)
{
if (owner.sec_d != nullptr)
LocalFree(owner.sec_d);
owner.Owner = newOwner;
owner.sec_d = new_sec_d;
owner.has_owner = true;
}
else if (new_sec_d != nullptr)
{
LocalFree(new_sec_d);
}
return rc == ERROR_SUCCESS;
}
#ifdef _WIN32
HRESULT ModifyPrivilege(
IN LPCTSTR szPrivilege,
IN BOOL fEnable)
{
HRESULT hr = S_OK;
TOKEN_PRIVILEGES NewState;
LUID luid;
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken))
{
return ERROR_FUNCTION_FAILED;
}
if (!LookupPrivilegeValue(NULL,
szPrivilege,
&luid))
{
CloseHandle(hToken);
return ERROR_FUNCTION_FAILED;
}
NewState.PrivilegeCount = 1;
NewState.Privileges[0].Luid = luid;
NewState.Privileges[0].Attributes =
(fEnable ? SE_PRIVILEGE_ENABLED : 0);
if (!AdjustTokenPrivileges(hToken,
FALSE,
&NewState,
0,
NULL,
NULL))
{
hr = ERROR_FUNCTION_FAILED;
}
CloseHandle(hToken);
return hr;
}
#endif
static bool setOwner(const std::string& fn, const SOwner& owner)
{
if (!owner.has_owner || owner.Owner == nullptr)
return false;
HRESULT hr = ModifyPrivilege(SE_TAKE_OWNERSHIP_NAME, TRUE);
if (!SUCCEEDED(hr))
return false;
std::wstring wfn = Server->ConvertToWchar(os_file_prefix(fn)).c_str();
DWORD rc = SetNamedSecurityInfoW(&wfn[0],
SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, owner.Owner, NULL, NULL,
NULL);
return rc == ERROR_SUCCESS;
}
static size_t zipWrite(void* pOpaque, mz_uint64 file_ofs, const void* pBuf, size_t n)
{
IFsFile* out_file = reinterpret_cast<IFsFile*>(pOpaque);
return out_file->Write(file_ofs, reinterpret_cast<const char*>(pBuf), n);
}
static void setupRansomwareCanaryFile(const std::string& curr_path, const std::string& fn_prefix,
const std::string& server_token, SOwner& owner)
{
std::string out_fn = os_file_prefix(curr_path + fn_prefix + "-" + server_token + ".docx");
if (os_get_file_type(out_fn) != 0)
{
Server->Log("Ransomware canary at \"" + out_fn + "\" already exists");
return;
}
if (!curr_path.empty())
{
std::vector<SFile> sib_files = getFiles(curr_path.substr(0, curr_path.size()-1));
for (SFile& sib_file : sib_files)
{
if (getOwner(curr_path + sib_file.name, owner))
break;
}
}
const std::string canary_path = Server->getServerWorkingDir() + os_file_sep() +
"urbackup" + os_file_sep() + "canary.docx";
mz_zip_archive canary_doc = {};
if (!mz_zip_reader_init_file(&canary_doc, canary_path.c_str(), 0))
{
Server->Log("Error opening canary.docx file for extraction", LL_ERROR);
return;
}
ScopedDeleteFn delete_fn(out_fn+".new");
std::unique_ptr<IFsFile> out_file(Server->openFile(out_fn+".new", MODE_WRITE));
if (out_file.get() == nullptr)
{
Server->Log("Error opening canary out at \"" + out_fn + ".new\". " + os_last_error_str(), LL_ERROR);
return;
}
mz_zip_archive canary_doc_out = {};
canary_doc_out.m_pWrite = zipWrite;
canary_doc_out.m_pIO_opaque = out_file.get();
if (!mz_zip_writer_init(&canary_doc_out, 0))
{
Server->Log("Error init zip at \"" + out_fn + ".new\"", LL_ERROR);
return;
}
for (unsigned int i = 0, num_files = mz_zip_reader_get_num_files(&canary_doc); i < num_files; ++i)
{
std::vector<char> buf(100);
mz_zip_reader_get_filename(&canary_doc, i, buf.data(), buf.size());
std::string curr_fn = buf.data();
if (curr_fn == "word/document.xml")
{
size_t fsize;
void* buf = mz_zip_reader_extract_to_heap(&canary_doc, i, &fsize, 0);
if (buf == nullptr)
{
Server->Log("Error extracting word/document.xml", LL_ERROR);
return;
}
std::string bdata(reinterpret_cast<char*>(buf), fsize);
std::string uuid;
uuid.resize(16);
Server->secureRandomFill(&uuid[0], 16);
bdata = greplace("$RAND$", bytesToHex(uuid), bdata);
if (!mz_zip_writer_add_mem(&canary_doc_out, curr_fn.c_str(),
bdata.data(), bdata.size(), MZ_DEFAULT_COMPRESSION))
{
Server->Log("Error adding modified word/document.xml to doc", LL_ERROR);
return;
}
}
else
{
if (!mz_zip_writer_add_from_zip_reader(&canary_doc_out, &canary_doc, i))
{
Server->Log("Error adding file \"" + curr_fn + "\" to canary out doc", LL_ERROR);
return;
}
}
}
delete_fn.release();
out_file->Sync();
out_file.reset();
if (!os_rename_file(out_fn + ".new", out_fn))
{
Server->Log("Error renaming canary " + out_fn + ".new", LL_ERROR);
return;
}
setOwner(out_fn, owner);
}
static std::string getBackupPath(const std::string& name, int facet, int group)
{
ClientDAO clientdao(Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT));
std::vector<SBackupDir> backupdirs = clientdao.getBackupDirs();
for (SBackupDir& bd: backupdirs)
{
if (bd.facet != facet || bd.group != group)
continue;
if (bd.tname == name)
return bd.path;
}
return std::string();
}
static void setupRansomwareCanariesPath(const std::string& curr_path, const std::vector<std::string> path_components, size_t idx,
const std::string& server_token, int facet, int group, SOwner& owner)
{
if (idx >= path_components.size())
return;
bool last_comp = idx + 1 >= path_components.size();
std::string comp = path_components[idx];
bool create = false;
if (comp[0] == '^'
&& comp.find("*") == std::string::npos)
{
create = true;
comp = comp.substr(1);
}
if (idx == 0)
{
comp = getBackupPath(comp, facet, group);
if (comp.empty())
return;
}
if (!last_comp
&& comp.find("*") != std::string::npos)
{
std::vector<SFile> files = getFiles(curr_path);
for (size_t i = 0; i < files.size(); ++i)
{
if (files[i].isdir
&& amatch(files[i].name.c_str(), comp.c_str()))
{
getOwner(curr_path + files[i].name, owner);
setupRansomwareCanariesPath(curr_path + files[i].name + os_file_sep(),
path_components, idx + 1, server_token, facet, group, owner);
}
}
}
else
{
if (!create
&& !last_comp)
{
getOwner(curr_path + comp, owner);
}
if (!last_comp &&
create &&
!os_directory_exists(os_file_prefix(curr_path + comp)))
{
if (!os_create_dir(os_file_prefix(curr_path + comp)))
{
Server->Log("Error creating directory \"" + curr_path + comp +
"\" for ransomware canary. " + os_last_error_str(), LL_ERROR);
}
}
else if (last_comp)
{
setupRansomwareCanaryFile(curr_path,
comp, server_token, owner);
}
if(!last_comp)
setupRansomwareCanariesPath(curr_path + comp + os_file_sep(), path_components,
idx + 1, server_token, facet, group, owner);
}
}
static void setupRansomwareCanariesInt(const std::string& ransomware_canary_paths, const std::string& server_token,
int facet, int group)
{
std::vector<std::string> paths;
Tokenize(ransomware_canary_paths, paths, ";");
for (std::string path : paths)
{
std::vector<std::string> path_components;
Tokenize(path, path_components, "/");
if (!path_components.empty())
{
SOwner owner;
setupRansomwareCanariesPath(std::string(), path_components, 0, server_token, facet, group, owner);
}
}
}
void setupRansomwareCanaries(const std::string& ransomware_canary_paths, const std::string& server_token,
int facet, int group)
{
std::thread t([ransomware_canary_paths, server_token, facet, group]()
{
setupRansomwareCanariesInt(ransomware_canary_paths, server_token, facet, group);
});
t.detach();
}
<commit_msg>Fix docx writing<commit_after>#include "RansomwareCanary.h"
#include <thread>
#include "../stringtools.h"
#include "../urbackupcommon/os_functions.h"
#include "../Interface/Server.h"
#include "../Interface/File.h"
#include "../urbackupcommon/glob.h"
#include "../common/miniz.h"
#include "clientdao.h"
#include "database.h"
#ifdef _WIN32
#include <aclapi.h>
#endif
struct SOwner
{
bool has_owner = false;
#ifdef _WIN32
PSID Owner = nullptr;
PSECURITY_DESCRIPTOR sec_d = nullptr;
~SOwner() {
if (sec_d != nullptr)
LocalFree(sec_d);
}
#endif
};
static bool getOwner(const std::string& fn, SOwner& owner)
{
PSID newOwner = nullptr;
PSECURITY_DESCRIPTOR new_sec_d = nullptr;
DWORD rc = GetNamedSecurityInfoW(Server->ConvertToWchar(os_file_prefix(fn)).c_str(),
SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &newOwner, NULL, NULL,
NULL, &new_sec_d);
if (rc == ERROR_SUCCESS)
{
if (owner.sec_d != nullptr)
LocalFree(owner.sec_d);
owner.Owner = newOwner;
owner.sec_d = new_sec_d;
owner.has_owner = true;
}
else if (new_sec_d != nullptr)
{
LocalFree(new_sec_d);
}
return rc == ERROR_SUCCESS;
}
#ifdef _WIN32
HRESULT ModifyPrivilege(
IN LPCTSTR szPrivilege,
IN BOOL fEnable)
{
HRESULT hr = S_OK;
TOKEN_PRIVILEGES NewState;
LUID luid;
HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken))
{
return ERROR_FUNCTION_FAILED;
}
if (!LookupPrivilegeValue(NULL,
szPrivilege,
&luid))
{
CloseHandle(hToken);
return ERROR_FUNCTION_FAILED;
}
NewState.PrivilegeCount = 1;
NewState.Privileges[0].Luid = luid;
NewState.Privileges[0].Attributes =
(fEnable ? SE_PRIVILEGE_ENABLED : 0);
if (!AdjustTokenPrivileges(hToken,
FALSE,
&NewState,
0,
NULL,
NULL))
{
hr = ERROR_FUNCTION_FAILED;
}
CloseHandle(hToken);
return hr;
}
#endif
static bool setOwner(const std::string& fn, const SOwner& owner)
{
if (!owner.has_owner || owner.Owner == nullptr)
return false;
HRESULT hr = ModifyPrivilege(SE_TAKE_OWNERSHIP_NAME, TRUE);
if (!SUCCEEDED(hr))
return false;
std::wstring wfn = Server->ConvertToWchar(os_file_prefix(fn)).c_str();
DWORD rc = SetNamedSecurityInfoW(&wfn[0],
SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, owner.Owner, NULL, NULL,
NULL);
return rc == ERROR_SUCCESS;
}
static size_t zipWrite(void* pOpaque, mz_uint64 file_ofs, const void* pBuf, size_t n)
{
IFsFile* out_file = reinterpret_cast<IFsFile*>(pOpaque);
return out_file->Write(file_ofs, reinterpret_cast<const char*>(pBuf), n);
}
static void setupRansomwareCanaryFile(const std::string& curr_path, const std::string& fn_prefix,
const std::string& server_token, SOwner& owner)
{
std::string out_fn = os_file_prefix(curr_path + fn_prefix + "-" + server_token + ".docx");
if (os_get_file_type(out_fn) != 0)
{
Server->Log("Ransomware canary at \"" + out_fn + "\" already exists");
return;
}
if (!curr_path.empty())
{
std::vector<SFile> sib_files = getFiles(curr_path.substr(0, curr_path.size()-1));
for (SFile& sib_file : sib_files)
{
if (getOwner(curr_path + sib_file.name, owner))
break;
}
}
const std::string canary_path = Server->getServerWorkingDir() + os_file_sep() +
"urbackup" + os_file_sep() + "canary.docx";
mz_zip_archive canary_doc = {};
if (!mz_zip_reader_init_file(&canary_doc, canary_path.c_str(), 0))
{
Server->Log("Error opening canary.docx file for extraction", LL_ERROR);
return;
}
ScopedDeleteFn delete_fn(out_fn+".new");
std::unique_ptr<IFsFile> out_file(Server->openFile(out_fn+".new", MODE_WRITE));
if (out_file.get() == nullptr)
{
Server->Log("Error opening canary out at \"" + out_fn + ".new\". " + os_last_error_str(), LL_ERROR);
return;
}
mz_zip_archive canary_doc_out = {};
canary_doc_out.m_pWrite = zipWrite;
canary_doc_out.m_pIO_opaque = out_file.get();
if (!mz_zip_writer_init(&canary_doc_out, 0))
{
Server->Log("Error init zip at \"" + out_fn + ".new\"", LL_ERROR);
return;
}
for (unsigned int i = 0, num_files = mz_zip_reader_get_num_files(&canary_doc); i < num_files; ++i)
{
std::vector<char> buf(100);
mz_zip_reader_get_filename(&canary_doc, i, buf.data(), buf.size());
std::string curr_fn = buf.data();
if (curr_fn == "word/document.xml")
{
size_t fsize;
void* buf = mz_zip_reader_extract_to_heap(&canary_doc, i, &fsize, 0);
if (buf == nullptr)
{
Server->Log("Error extracting word/document.xml", LL_ERROR);
return;
}
std::string bdata(reinterpret_cast<char*>(buf), fsize);
std::string uuid;
uuid.resize(16);
Server->secureRandomFill(&uuid[0], 16);
bdata = greplace("$RAND$", bytesToHex(uuid), bdata);
if (!mz_zip_writer_add_mem(&canary_doc_out, curr_fn.c_str(),
bdata.data(), bdata.size(), MZ_DEFAULT_COMPRESSION))
{
Server->Log("Error adding modified word/document.xml to doc", LL_ERROR);
return;
}
}
else
{
if (!mz_zip_writer_add_from_zip_reader(&canary_doc_out, &canary_doc, i))
{
Server->Log("Error adding file \"" + curr_fn + "\" to canary out doc", LL_ERROR);
return;
}
}
}
if (!mz_zip_writer_finalize_archive(&canary_doc_out))
{
Server->Log("Error finalizing archive \"" + out_fn + "\"", LL_ERROR);
return;
}
mz_zip_writer_end(&canary_doc_out);
mz_zip_reader_end(&canary_doc);
delete_fn.release();
out_file->Sync();
out_file.reset();
if (!os_rename_file(out_fn + ".new", out_fn))
{
Server->Log("Error renaming canary " + out_fn + ".new", LL_ERROR);
return;
}
setOwner(out_fn, owner);
}
static std::string getBackupPath(const std::string& name, int facet, int group)
{
ClientDAO clientdao(Server->getDatabase(Server->getThreadID(), URBACKUPDB_CLIENT));
std::vector<SBackupDir> backupdirs = clientdao.getBackupDirs();
for (SBackupDir& bd: backupdirs)
{
if (bd.facet != facet || bd.group != group)
continue;
if (bd.tname == name)
return bd.path;
}
return std::string();
}
static void setupRansomwareCanariesPath(const std::string& curr_path, const std::vector<std::string> path_components, size_t idx,
const std::string& server_token, int facet, int group, SOwner& owner)
{
if (idx >= path_components.size())
return;
bool last_comp = idx + 1 >= path_components.size();
std::string comp = path_components[idx];
bool create = false;
if (comp[0] == '^'
&& comp.find("*") == std::string::npos)
{
create = true;
comp = comp.substr(1);
}
if (idx == 0)
{
comp = getBackupPath(comp, facet, group);
if (comp.empty())
return;
}
if (!last_comp
&& comp.find("*") != std::string::npos)
{
std::vector<SFile> files = getFiles(curr_path);
for (size_t i = 0; i < files.size(); ++i)
{
if (files[i].isdir
&& amatch(files[i].name.c_str(), comp.c_str()))
{
getOwner(curr_path + files[i].name, owner);
setupRansomwareCanariesPath(curr_path + files[i].name + os_file_sep(),
path_components, idx + 1, server_token, facet, group, owner);
}
}
}
else
{
if (!create
&& !last_comp)
{
getOwner(curr_path + comp, owner);
}
if (!last_comp &&
create &&
!os_directory_exists(os_file_prefix(curr_path + comp)))
{
if (!os_create_dir(os_file_prefix(curr_path + comp)))
{
Server->Log("Error creating directory \"" + curr_path + comp +
"\" for ransomware canary. " + os_last_error_str(), LL_ERROR);
}
}
else if (last_comp)
{
setupRansomwareCanaryFile(curr_path,
comp, server_token, owner);
}
if(!last_comp)
setupRansomwareCanariesPath(curr_path + comp + os_file_sep(), path_components,
idx + 1, server_token, facet, group, owner);
}
}
static void setupRansomwareCanariesInt(const std::string& ransomware_canary_paths, const std::string& server_token,
int facet, int group)
{
std::vector<std::string> paths;
Tokenize(ransomware_canary_paths, paths, ";");
for (std::string path : paths)
{
std::vector<std::string> path_components;
Tokenize(path, path_components, "/");
if (!path_components.empty())
{
SOwner owner;
setupRansomwareCanariesPath(std::string(), path_components, 0, server_token, facet, group, owner);
}
}
}
void setupRansomwareCanaries(const std::string& ransomware_canary_paths, const std::string& server_token,
int facet, int group)
{
std::thread t([ransomware_canary_paths, server_token, facet, group]()
{
setupRansomwareCanariesInt(ransomware_canary_paths, server_token, facet, group);
});
t.detach();
}
<|endoftext|>
|
<commit_before>#include "TextureLoader.h"
TextureLoader::TextureLoader(std::string const & url) :
m_objectsTexture(new sf::Texture()),
m_floorTexture(new sf::Texture()),
m_characterTexture(new sf::Texture())
{
loadTexture(url);
}
TextureLoader::~TextureLoader()
{
delete(m_floorTexture);
delete(m_objectsTexture);
delete(m_characterTexture);
}
sf::Texture * TextureLoader::getFloorTexture() const
{
return m_floorTexture;
}
sf::Texture * TextureLoader::getObjectsTexture() const
{
return m_objectsTexture;
}
sf::Texture * TextureLoader::getCharacterTexture() const
{
return m_characterTexture;
}
//On passe l'url du dossier de Textures
void TextureLoader::loadTexture(std::string const & url)
{
if(!m_floorTexture->loadFromFile((url + "floor/tileset.png").c_str()))
{
std::cerr << "Error when loading the texture of the floor" << std::endl;
throw LoadingErrorException;
}
if(!m_objectsTexture->loadFromFile((url + "mobilier/tileset.png").c_str()))
{
std::cerr << "Error when loading the texture of the objects" << std::endl;
throw LoadingErrorException;
}
if(!m_characterTexture->loadFromFile((url + "character/.png").c_str()))
{
std::cerr << "Error when loading the texture of the character" << std::endl;
throw LoadingErrorException;
}
}
<commit_msg>tileset for spooky<commit_after>#include "TextureLoader.h"
TextureLoader::TextureLoader(std::string const & url) :
m_objectsTexture(new sf::Texture()),
m_floorTexture(new sf::Texture()),
m_characterTexture(new sf::Texture())
{
loadTexture(url);
}
TextureLoader::~TextureLoader()
{
delete(m_floorTexture);
delete(m_objectsTexture);
delete(m_characterTexture);
}
sf::Texture * TextureLoader::getFloorTexture() const
{
return m_floorTexture;
}
sf::Texture * TextureLoader::getObjectsTexture() const
{
return m_objectsTexture;
}
sf::Texture * TextureLoader::getCharacterTexture() const
{
return m_characterTexture;
}
//On passe l'url du dossier de Textures
void TextureLoader::loadTexture(std::string const & url)
{
if(!m_floorTexture->loadFromFile((url + "floor/tileset.png").c_str()))
{
std::cerr << "Error when loading the texture of the floor" << std::endl;
throw LoadingErrorException;
}
if(!m_objectsTexture->loadFromFile((url + "mobilier/tileset.png").c_str()))
{
std::cerr << "Error when loading the texture of the objects" << std::endl;
throw LoadingErrorException;
}
if(!m_characterTexture->loadFromFile((url + "spooky/sprite.png").c_str()))
{
std::cerr << "Error when loading the texture of the character" << std::endl;
throw LoadingErrorException;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NameContainer.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-07-25 08:58:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "NameContainer.hxx"
/*
//SvXMLUnitConverter
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
*/
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
using namespace ::com::sun::star;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::rtl::OUString;
//.............................................................................
namespace chart
{
//.............................................................................
NameContainer::NameContainer( const ::com::sun::star::uno::Type& rType, const OUString& rServicename, const OUString& rImplementationName )
: m_aType( rType )
, m_aServicename( rServicename )
, m_aImplementationName( rImplementationName )
, m_aMap()
{
}
NameContainer::NameContainer(
const NameContainer & rOther )
: impl::NameContainer_Base()
, m_aType( rOther.m_aType )
, m_aServicename( rOther.m_aServicename )
, m_aImplementationName( rOther.m_aImplementationName )
, m_aMap( rOther.m_aMap )
{
}
NameContainer::~NameContainer()
{
}
//XServiceInfo
OUString SAL_CALL NameContainer::getImplementationName()
throw( ::com::sun::star::uno::RuntimeException )
{
return m_aImplementationName;
}
sal_Bool SAL_CALL NameContainer::supportsService( const OUString& ServiceName )
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aSNL = getSupportedServiceNames();
const OUString* pArray = aSNL.getArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
{
if( pArray[ i ] == ServiceName )
return sal_True;
}
return sal_False;
}
Sequence< OUString > SAL_CALL NameContainer::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aSNS( 1 );
aSNS.getArray()[ 0 ] = m_aServicename;
return aSNS;
}
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//-----------------------------------------------------------------
// XNameContainer
void SAL_CALL NameContainer::insertByName( const OUString& rName, const Any& rElement )
throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )
{
if( m_aMap.find( rName ) != m_aMap.end() )
throw container::ElementExistException();
m_aMap.insert( tContentMap::value_type( rName, rElement ));
}
void SAL_CALL NameContainer::removeByName( const OUString& Name )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
tContentMap::iterator aIt( m_aMap.find( Name ));
if( aIt == m_aMap.end())
throw container::NoSuchElementException();
m_aMap.erase( aIt );
}
// XNameReplace
void SAL_CALL NameContainer::replaceByName( const OUString& rName, const Any& rElement )
throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
tContentMap::iterator aIt( m_aMap.find( rName ));
if( aIt == m_aMap.end() )
throw container::NoSuchElementException();
aIt->second = rElement;
}
// XNameAccess
Any SAL_CALL NameContainer::getByName( const OUString& rName )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
tContentMap::iterator aIter( m_aMap.find( rName ) );
if( aIter == m_aMap.end() )
throw container::NoSuchElementException();
return aIter->second;
}
Sequence< OUString > SAL_CALL NameContainer::getElementNames()
throw( uno::RuntimeException )
{
sal_Int32 nCount = m_aMap.size();
Sequence< OUString > aSeq(nCount);
sal_Int32 nN = 0;
for( tContentMap::iterator aIter = m_aMap.begin(); aIter != m_aMap.end(), nN < nCount; aIter++, nN++ )
aSeq[nN]=aIter->first;
return aSeq;
}
sal_Bool SAL_CALL NameContainer::hasByName( const OUString& rName )
throw( uno::RuntimeException )
{
return ( m_aMap.find( rName ) != m_aMap.end() );
}
// XElementAccess
sal_Bool SAL_CALL NameContainer::hasElements()
throw( uno::RuntimeException )
{
return ! m_aMap.empty();
}
uno::Type SAL_CALL NameContainer::getElementType()
throw( uno::RuntimeException )
{
return m_aType;
}
// XCloneable
uno::Reference< util::XCloneable > SAL_CALL NameContainer::createClone()
throw ( uno::RuntimeException )
{
return uno::Reference< util::XCloneable >( new NameContainer( *this ));
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.3.94); FILE MERGED 2008/04/01 15:04:23 thb 1.3.94.2: #i85898# Stripping all external header guards 2008/03/28 16:44:23 rt 1.3.94.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NameContainer.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "NameContainer.hxx"
/*
//SvXMLUnitConverter
#include <xmloff/xmluconv.hxx>
*/
#include <com/sun/star/uno/Any.hxx>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::rtl::OUString;
//.............................................................................
namespace chart
{
//.............................................................................
NameContainer::NameContainer( const ::com::sun::star::uno::Type& rType, const OUString& rServicename, const OUString& rImplementationName )
: m_aType( rType )
, m_aServicename( rServicename )
, m_aImplementationName( rImplementationName )
, m_aMap()
{
}
NameContainer::NameContainer(
const NameContainer & rOther )
: impl::NameContainer_Base()
, m_aType( rOther.m_aType )
, m_aServicename( rOther.m_aServicename )
, m_aImplementationName( rOther.m_aImplementationName )
, m_aMap( rOther.m_aMap )
{
}
NameContainer::~NameContainer()
{
}
//XServiceInfo
OUString SAL_CALL NameContainer::getImplementationName()
throw( ::com::sun::star::uno::RuntimeException )
{
return m_aImplementationName;
}
sal_Bool SAL_CALL NameContainer::supportsService( const OUString& ServiceName )
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aSNL = getSupportedServiceNames();
const OUString* pArray = aSNL.getArray();
for( sal_Int32 i = 0; i < aSNL.getLength(); i++ )
{
if( pArray[ i ] == ServiceName )
return sal_True;
}
return sal_False;
}
Sequence< OUString > SAL_CALL NameContainer::getSupportedServiceNames()
throw( ::com::sun::star::uno::RuntimeException )
{
Sequence< OUString > aSNS( 1 );
aSNS.getArray()[ 0 ] = m_aServicename;
return aSNS;
}
//-----------------------------------------------------------------
//-----------------------------------------------------------------
//-----------------------------------------------------------------
// XNameContainer
void SAL_CALL NameContainer::insertByName( const OUString& rName, const Any& rElement )
throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException )
{
if( m_aMap.find( rName ) != m_aMap.end() )
throw container::ElementExistException();
m_aMap.insert( tContentMap::value_type( rName, rElement ));
}
void SAL_CALL NameContainer::removeByName( const OUString& Name )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
tContentMap::iterator aIt( m_aMap.find( Name ));
if( aIt == m_aMap.end())
throw container::NoSuchElementException();
m_aMap.erase( aIt );
}
// XNameReplace
void SAL_CALL NameContainer::replaceByName( const OUString& rName, const Any& rElement )
throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException )
{
tContentMap::iterator aIt( m_aMap.find( rName ));
if( aIt == m_aMap.end() )
throw container::NoSuchElementException();
aIt->second = rElement;
}
// XNameAccess
Any SAL_CALL NameContainer::getByName( const OUString& rName )
throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
{
tContentMap::iterator aIter( m_aMap.find( rName ) );
if( aIter == m_aMap.end() )
throw container::NoSuchElementException();
return aIter->second;
}
Sequence< OUString > SAL_CALL NameContainer::getElementNames()
throw( uno::RuntimeException )
{
sal_Int32 nCount = m_aMap.size();
Sequence< OUString > aSeq(nCount);
sal_Int32 nN = 0;
for( tContentMap::iterator aIter = m_aMap.begin(); aIter != m_aMap.end(), nN < nCount; aIter++, nN++ )
aSeq[nN]=aIter->first;
return aSeq;
}
sal_Bool SAL_CALL NameContainer::hasByName( const OUString& rName )
throw( uno::RuntimeException )
{
return ( m_aMap.find( rName ) != m_aMap.end() );
}
// XElementAccess
sal_Bool SAL_CALL NameContainer::hasElements()
throw( uno::RuntimeException )
{
return ! m_aMap.empty();
}
uno::Type SAL_CALL NameContainer::getElementType()
throw( uno::RuntimeException )
{
return m_aType;
}
// XCloneable
uno::Reference< util::XCloneable > SAL_CALL NameContainer::createClone()
throw ( uno::RuntimeException )
{
return uno::Reference< util::XCloneable >( new NameContainer( *this ));
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>
|
<commit_before>#include <Poco/AutoPtr.h>
#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>
#include "db.h"
#ifdef ENABLE_SQLITE3
extern "C" {
extern DB::Connection *create_sqlite3_connection(void);
};
class SqliteInvalidTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open(".", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
ASSERT_EQ(connection->isConnected(), false);
}
class SqliteDefaultTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
EXPECT_EQ(connection->isConnected(), true);
}
TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}
TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("BYE"), false);
}
TEST_F(SqliteDefaultTest, EscapeCharacters) {
EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}
TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
const char *t = connection->unixtimeToSql((time_t) 1414965631);
EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}
TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
EXPECT_EQ(connection->errorno(), 0);
EXPECT_STREQ(connection->errormsg(), "not an error");
}
TEST_F(SqliteDefaultTest, VersionString) {
const char *v = connection->version();
bool correct = false;
if (strstr(v, "Sqlite3 Driver v0.2")) {
correct = true;
}
EXPECT_EQ(correct, true);
}
class SqliteTransactionTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)"), true);
connection->beginTrans();
}
virtual void TearDown() {
connection->commitTrans();
connection->execute("DROP TABLE testing");
connection->close();
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteTransactionTest, SingleInsert) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}
TEST_F(SqliteTransactionTest, SingleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
EXPECT_EQ(connection->commitTrans(), true);
EXPECT_EQ(connection->beginTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
if (rs) {
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 42);
EXPECT_EQ(rs->getFloat(3), 42.0f);
EXPECT_EQ(rs->getDouble(3), 42.0F);
EXPECT_EQ(rs->getLong(3), 42l);
EXPECT_EQ(rs->getBool(3), false);
EXPECT_EQ(rs->getShort(3), (short) 42);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
EXPECT_EQ(rs->recordCount(), 0);
rs->close();
}
}
TEST_F(SqliteTransactionTest, DoubleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->commitTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
if (rs) {
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 1);
EXPECT_EQ(rs->getFloat(3), 1.0f);
EXPECT_EQ(rs->getDouble(3), 1.0F);
EXPECT_EQ(rs->getLong(3), 1l);
EXPECT_EQ(rs->getBool(3), true);
EXPECT_EQ(rs->getShort(3), (short) 1);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
rs->close();
}
}
TEST_F(SqliteTransactionTest, QueryString) {
connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED);
connection->setTransactionMode(DB::Connection::READ_COMMITTED);
connection->setTransactionMode(DB::Connection::REPEATABLE_READ);
connection->setTransactionMode(DB::Connection::SERIALIZABLE);
DB::Query q(*connection);
q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
q << "," << 42.0f << ");";
EXPECT_EQ(connection->execute(q.str()), true);
unsigned long id = connection->insertId();
EXPECT_EQ(id, 1);
EXPECT_EQ(connection->commitTrans(), true);
}
TEST_F(SqliteTransactionTest, RollbackTransaction) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
EXPECT_EQ(connection->rollbackTrans(), true);
}
TEST_F(SqliteTransactionTest, QueryStringTypes) {
DB::Query q(*connection);
q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
EXPECT_EQ(strlen(q.str()), 80);
}
TEST_F(SqliteTransactionTest, QueryStringTypes2) {
DB::Query q(*connection);
std::stringstream world;
world << " World" << std::ends;
q << std::string("Hello") << world;
EXPECT_EQ(strlen(q.str()), 11);
}
TEST_F(SqliteTransactionTest, QueryNumberTypes) {
DB::Query q(*connection);
double d = 42.2;
short s = 42;
unsigned short su = 42;
q << 42 << " " << d << " " << s << (const unsigned char *) " ";
q << 42u << " " << 42ul << " " << su;
}
#endif
<commit_msg>Fixed schema for older sqlite3.<commit_after>#include <Poco/AutoPtr.h>
#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>
#include "db.h"
#ifdef ENABLE_SQLITE3
extern "C" {
extern DB::Connection *create_sqlite3_connection(void);
};
class SqliteInvalidTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open(".", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
ASSERT_EQ(connection->isConnected(), false);
}
class SqliteDefaultTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
}
virtual void TearDown() {
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
EXPECT_EQ(connection->isConnected(), true);
}
TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}
TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
EXPECT_EQ(connection->execute("BYE"), false);
}
TEST_F(SqliteDefaultTest, EscapeCharacters) {
EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}
TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
const char *t = connection->unixtimeToSql((time_t) 1414965631);
EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}
TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
EXPECT_EQ(connection->errorno(), 0);
EXPECT_STREQ(connection->errormsg(), "not an error");
}
TEST_F(SqliteDefaultTest, VersionString) {
const char *v = connection->version();
bool correct = false;
if (strstr(v, "Sqlite3 Driver v0.2")) {
correct = true;
}
EXPECT_EQ(correct, true);
}
class SqliteTransactionTest : public ::testing::Test {
protected:
virtual void SetUp() {
connection = create_sqlite3_connection();
connection->open("test.db", NULL, 0, NULL, NULL);
EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)"), true);
connection->beginTrans();
}
virtual void TearDown() {
connection->commitTrans();
connection->execute("DROP TABLE testing");
connection->close();
connection->release();
}
Poco::AutoPtr <DB::Connection> connection;
};
TEST_F(SqliteTransactionTest, SingleInsert) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}
TEST_F(SqliteTransactionTest, SingleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
//EXPECT_EQ(connection->commitTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
if (rs) {
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 42);
EXPECT_EQ(rs->getFloat(3), 42.0f);
EXPECT_EQ(rs->getDouble(3), 42.0F);
EXPECT_EQ(rs->getLong(3), 42l);
EXPECT_EQ(rs->getBool(3), false);
EXPECT_EQ(rs->getShort(3), (short) 42);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
EXPECT_EQ(rs->recordCount(), 0);
rs->close();
}
}
TEST_F(SqliteTransactionTest, DoubleSelect) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
EXPECT_EQ(connection->commitTrans(), true);
DB::Query q(*connection);
q << "SELECT * FROM testing;";
DB::ResultSet *rs = connection->executeQuery(q.str());
EXPECT_NE(rs, (DB::ResultSet *) NULL);
if (rs) {
rs->next();
EXPECT_EQ(rs->findColumn("text"), 1);
EXPECT_STREQ(rs->getString(1), "benden");
EXPECT_EQ(rs->findColumn("fl"), 3);
EXPECT_EQ(rs->findColumn("r"), 6);
EXPECT_EQ(rs->getInteger(3), 1);
EXPECT_EQ(rs->getFloat(3), 1.0f);
EXPECT_EQ(rs->getDouble(3), 1.0F);
EXPECT_EQ(rs->getLong(3), 1l);
EXPECT_EQ(rs->getBool(3), true);
EXPECT_EQ(rs->getShort(3), (short) 1);
EXPECT_NE(rs->getUnixTime(4), -1);
EXPECT_EQ(rs->getUnixTime(5), 0);
rs->close();
}
}
TEST_F(SqliteTransactionTest, QueryString) {
connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED);
connection->setTransactionMode(DB::Connection::READ_COMMITTED);
connection->setTransactionMode(DB::Connection::REPEATABLE_READ);
connection->setTransactionMode(DB::Connection::SERIALIZABLE);
DB::Query q(*connection);
q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
q << "," << 42.0f << ");";
EXPECT_EQ(connection->execute(q.str()), true);
unsigned long id = connection->insertId();
EXPECT_EQ(id, 1);
EXPECT_EQ(connection->commitTrans(), true);
}
TEST_F(SqliteTransactionTest, RollbackTransaction) {
EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
EXPECT_EQ(connection->rollbackTrans(), true);
}
TEST_F(SqliteTransactionTest, QueryStringTypes) {
DB::Query q(*connection);
q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
EXPECT_EQ(strlen(q.str()), 80);
}
TEST_F(SqliteTransactionTest, QueryStringTypes2) {
DB::Query q(*connection);
std::stringstream world;
world << " World" << std::ends;
q << std::string("Hello") << world;
EXPECT_EQ(strlen(q.str()), 11);
}
TEST_F(SqliteTransactionTest, QueryNumberTypes) {
DB::Query q(*connection);
double d = 42.2;
short s = 42;
unsigned short su = 42;
q << 42 << " " << d << " " << s << (const unsigned char *) " ";
q << 42u << " " << 42ul << " " << su;
}
#endif
<|endoftext|>
|
<commit_before>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
/// Copyright (C) 2008 Christoph Cullmann <cullmann@kde.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// 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 "katescriptview.h"
#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katehighlight.h"
#include "katescript.h"
KateScriptView::KateScriptView(QObject *parent)
: QObject(parent), m_view(0)
{
}
void KateScriptView::setView (KateView *view)
{
m_view = view;
}
KateView *KateScriptView::view()
{
return m_view;
}
KTextEditor::Cursor KateScriptView::cursorPosition ()
{
return m_view->cursorPosition();
}
void KateScriptView::setCursorPosition(int line, int column)
{
KTextEditor::Cursor c(line, column);
m_view->setCursorPosition(c);
}
void KateScriptView::setCursorPosition (const KTextEditor::Cursor& cursor)
{
m_view->setCursorPosition(cursor);
}
KTextEditor::Cursor KateScriptView::virtualCursorPosition()
{
return m_view->cursorPositionVirtual();
}
void KateScriptView::setVirtualCursorPosition(int line, int column)
{
setVirtualCursorPosition(KTextEditor::Cursor(line, column));
}
void KateScriptView::setVirtualCursorPosition(const KTextEditor::Cursor& cursor)
{
m_view->setCursorPositionVisual(cursor);
}
QString KateScriptView::selectedText()
{
return m_view->selectionText();
}
bool KateScriptView::hasSelection()
{
return m_view->selection();
}
KTextEditor::Range KateScriptView::selection()
{
return m_view->selectionRange();
}
void KateScriptView::setSelection(const KTextEditor::Range& range)
{
m_view->setSelection(range);
}
void KateScriptView::removeSelectedText()
{
m_view->removeSelectedText();
}
void KateScriptView::selectAll()
{
m_view->selectAll();
}
void KateScriptView::clearSelection()
{
m_view->clearSelection();
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>cleanup include<commit_after>/// This file is part of the KDE libraries
/// Copyright (C) 2008 Paul Giannaros <paul@giannaros.org>
/// Copyright (C) 2008 Christoph Cullmann <cullmann@kde.org>
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Library General Public
/// License as published by the Free Software Foundation; either
/// version 2 of the License, or (at your option) version 3.
///
/// 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 "katescriptview.h"
#include "katedocument.h"
#include "kateview.h"
#include "katerenderer.h"
#include "katescript.h"
KateScriptView::KateScriptView(QObject *parent)
: QObject(parent), m_view(0)
{
}
void KateScriptView::setView (KateView *view)
{
m_view = view;
}
KateView *KateScriptView::view()
{
return m_view;
}
KTextEditor::Cursor KateScriptView::cursorPosition ()
{
return m_view->cursorPosition();
}
void KateScriptView::setCursorPosition(int line, int column)
{
KTextEditor::Cursor c(line, column);
m_view->setCursorPosition(c);
}
void KateScriptView::setCursorPosition (const KTextEditor::Cursor& cursor)
{
m_view->setCursorPosition(cursor);
}
KTextEditor::Cursor KateScriptView::virtualCursorPosition()
{
return m_view->cursorPositionVirtual();
}
void KateScriptView::setVirtualCursorPosition(int line, int column)
{
setVirtualCursorPosition(KTextEditor::Cursor(line, column));
}
void KateScriptView::setVirtualCursorPosition(const KTextEditor::Cursor& cursor)
{
m_view->setCursorPositionVisual(cursor);
}
QString KateScriptView::selectedText()
{
return m_view->selectionText();
}
bool KateScriptView::hasSelection()
{
return m_view->selection();
}
KTextEditor::Range KateScriptView::selection()
{
return m_view->selectionRange();
}
void KateScriptView::setSelection(const KTextEditor::Range& range)
{
m_view->setSelection(range);
}
void KateScriptView::removeSelectedText()
{
m_view->removeSelectedText();
}
void KateScriptView::selectAll()
{
m_view->selectAll();
}
void KateScriptView::clearSelection()
{
m_view->clearSelection();
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salgdiutils.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-08-03 14:02:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#include <basebmp/scanlineformats.hxx>
#include <basebmp/color.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <boost/bind.hpp>
#include <vcl/svapp.hxx>
#include "saldata.hxx"
// ----------------------------------------------------------------------
void AquaSalGraphics::SetWindowGraphics( CarbonViewRef rView, CarbonWindowRef rWindow, bool bScreenCompatible )
{
mrView = rView;
mrWindow = rWindow;
mbScreen = bScreenCompatible;
mbWindow = true;
mbPrinter = false;
mbVirDev = false;
}
void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY )
{
mrView = 0;
mbScreen = false;
mbWindow = false;
mbPrinter = true;
mbVirDev = false;
mrContext = xContext;
mnDPIX = nDPIX;
mnDPIY = nDPIY;
if( mrContext )
{
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
}
static void nil_free( void* )
{
}
void AquaSalGraphics::SetVirDevGraphics( CGContextRef xContext, bool bScreenCompatible )
{
mrView = 0;
mbScreen = bScreenCompatible;
mbWindow = false;
mbPrinter = false;
mbVirDev = true;
mrContext = xContext;
sal_uInt8* pMemory = NULL;
if( mrContext )
{
pMemory = reinterpret_cast<sal_uInt8*>(CGBitmapContextGetData( mrContext ));
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
maContextMemory.reset( pMemory, boost::bind( nil_free, _1 ) );
}
// ----------------------------------------------------------------------
void AquaSalGraphics::SetState()
{
CGContextRestoreGState( mrContext );
CGContextSaveGState( mrContext );
// set up clipping area
if( mrClippingPath )
{
CGContextBeginPath( mrContext ); // discard any existing path
CGContextAddPath( mrContext, mrClippingPath ); // set the current path to the clipping path
CGContextClip( mrContext ); // use it for clipping
}
// set RGB colorspace and line and fill colors
CGContextSetFillColor( mrContext, mpFillColor );
CGContextSetStrokeColor( mrContext, mpLineColor );
if( mbXORMode && (mbWindow || mbVirDev) )
{
CGContextSetBlendMode(mrContext, kCGBlendModeDifference);
int nWidth = CGBitmapContextGetWidth(mrContext);
int nHeight = CGBitmapContextGetHeight(mrContext);
if( ! maXORDevice )
{
maXORDevice = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
mbWindow,
basebmp::Format::THIRTYTWO_BIT_TC_MASK_ARGB,
maContextMemory,
basebmp::PaletteMemorySharedVector() );
if( mrClippingPath && maClippingRects.size() == 1 )
{
/*
* optimization: the case with only one clip rectangle is quite common
* in this case it is much cheaper to constrain the XOR device to a smaller
* area than to clip every pixel with the mask
*/
maXORClipMask.reset();
CGRect aBounds( maClippingRects.front() );
basegfx::B2IRange aRect( aBounds.origin.x, aBounds.origin.y,
aBounds.origin.x+aBounds.size.width,
aBounds.origin.y+aBounds.size.height );
maXORDevice = basebmp::subsetBitmapDevice( maXORDevice, aRect );
}
}
if( mrClippingPath )
{
if( ! maXORClipMask && maClippingRects.size() > 1 )
{
maXORClipMask = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
mbWindow,
basebmp::Format::ONE_BIT_MSB_GREY );
maXORClipMask->clear( basebmp::Color(0xffffffff) );
for( std::vector<CGRect>::const_iterator it = maClippingRects.begin(); it != maClippingRects.end(); ++it )
{
basegfx::B2DRectangle aRect( it->origin.x, it->origin.y,
it->origin.x+it->size.width,
it->origin.y+it->size.height );
maXORClipMask->fillPolyPolygon( basegfx::B2DPolyPolygon( basegfx::tools::createPolygonFromRect( aRect ) ),
basebmp::Color( 0 ),
basebmp::DrawMode_PAINT
);
}
}
}
else
maXORClipMask.reset();
}
CGContextSetShouldAntialias( mrContext, false );
}
// ----------------------------------------------------------------------
bool AquaSalGraphics::CheckContext()
{
if( mrWindow != NULL )
{
Rect windowBounds;
GetWindowPortBounds( mrWindow, &windowBounds );
const unsigned int nWidth = windowBounds.right - windowBounds.left;
const unsigned int nHeight = windowBounds.bottom - windowBounds.top;
CGContextRef rReleaseContext = 0;
unsigned int nReleaseContextWidth = 0;
unsigned int nReleaseContextHeight = 0;
boost::shared_array<sal_uInt8> aOldMem;
if( mrContext )
{
nReleaseContextWidth = CGBitmapContextGetWidth(mrContext);
nReleaseContextHeight = CGBitmapContextGetHeight(mrContext);
// check if window size changed and we need to create a new bitmap context
if( (nReleaseContextWidth != nWidth) || (nReleaseContextHeight != nHeight) )
{
rReleaseContext = mrContext;
mrContext = 0;
aOldMem = maContextMemory;
maXORDevice.reset();
maXORClipMask.reset();
}
}
if( !mrContext )
{
maContextMemory.reset( reinterpret_cast<sal_uInt8*>( rtl_allocateMemory( nWidth * 4 * nHeight ) ),
boost::bind( rtl_freeMemory, _1 ) );
if( maContextMemory )
{
mrContext = CGBitmapContextCreate( maContextMemory.get(), nWidth, nHeight, 8, nWidth * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );
if( mrContext )
{
// copy bitmap data to new context
if( rReleaseContext )
{
CGRect aBounds;
aBounds.origin.x = aBounds.origin.y = 0;
aBounds.size.width = nReleaseContextWidth;
aBounds.size.height = nReleaseContextHeight;
CGImageRef xImage = CGBitmapContextCreateImage( rReleaseContext );
CGContextDrawImage( mrContext, aBounds, xImage );
CGImageRelease(xImage);
}
CGContextTranslateCTM( mrContext, 0, nHeight );
CGContextScaleCTM( mrContext, 1.0, -1.0 );
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
else
{
maContextMemory.reset(); // free memory again
}
}
}
if( rReleaseContext ) // released memory runs out of scope and is then freed
CFRelease( rReleaseContext );
}
if( mrContext )
{
if( mbXORMode )
{
if( ! maXORDevice )
SetState();
}
return true;
}
else
{
AquaLog("<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" );
return false;
}
}
void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)
{
if( ! mbWindow ) // view only on Window graphics
return;
AquaLog("-->%s refresh %d - %d - %d - %d\n", __func__, static_cast<int>(lX), static_cast<int>(lY), static_cast<int>(lWidth), static_cast<int>(lHeight));
// Refresh windows rect content
HIRect aHIRect;
aHIRect.origin.x = static_cast<int>(lX);
aHIRect.origin.y = static_cast<int>(lY);
aHIRect.size.width = static_cast<int>(lWidth);
aHIRect.size.height = static_cast<int>(lHeight);
OSStatus retVal = HIViewSetNeedsDisplayInRect(mrView,&aHIRect,true);
if (retVal)
AquaLog( "FIXME: HIViewSetNeedsDisplayInRect returned %d (mrView is %p)\n", (int) retVal, mrView);
Rect aRect;
aRect.left = (short)lX;
aRect.top = (short)lY;
aRect.right = (short)(lX + lWidth );
aRect.bottom = (short)(lY + lHeight );
InvalWindowRect(mrWindow, &aRect);
}
void AquaSalGraphics::Flush()
{
if( mbWindow )
{
UpdateWindow();
}
}
CGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint* pPtAry)
{
AquaLog("-->%s\n",__func__);
CGPoint *CGpoints = new (CGPoint[nPoints]);
if ( CGpoints )
{
for(ULONG i=0;i<nPoints;i++)
{
CGpoints[i].x = (float)(pPtAry[i].mnX);
CGpoints[i].y = (float)(pPtAry[i].mnY);
}
}
return CGpoints;
}
// -----------------------------------------------------------------------
void AquaSalGraphics::UpdateWindow()
{
if( mrContext != NULL && mrWindow != NULL )
{
SetPortWindowPort(mrWindow);
CGContextRef xWindowContext = 0;
if( noErr == QDBeginCGContext (GetWindowPort (mrWindow), &xWindowContext))
{
Rect windowBounds;
GetWindowPortBounds( mrWindow, &windowBounds);
CGImageRef xImage = CGBitmapContextCreateImage( mrContext );
CGContextDrawImage(xWindowContext, CGRectMake(windowBounds.left, windowBounds.top, windowBounds.right - windowBounds.left, windowBounds.bottom - windowBounds.top ), xImage);
CGImageRelease(xImage);
CGContextFlush( xWindowContext );
QDEndCGContext (GetWindowPort(mrWindow), &xWindowContext);
}
}
}
// -----------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS aquavcl03 (1.10.4); FILE MERGED 2007/09/14 15:44:39 pl 1.10.4.4: header cleanup 2007/08/13 11:42:03 hdu 1.10.4.3: Aqua: reintroduce device-resolution 2007/08/07 10:32:49 pl 1.10.4.2: RESYNC: (1.10-1.11); FILE MERGED 2007/07/26 11:02:26 pl 1.10.4.1: #i80025# initial checking for carbon to cocoa migration<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salgdiutils.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:15:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include "salgdi.h"
#include "salframe.h"
#include "basebmp/scanlineformats.hxx"
#include "basebmp/color.hxx"
#include "basegfx/range/b2drectangle.hxx"
#include "basegfx/range/b2irange.hxx"
#include "basegfx/vector/b2ivector.hxx"
#include "basegfx/polygon/b2dpolygon.hxx"
#include "basegfx/polygon/b2dpolygontools.hxx"
#include <boost/bind.hpp>
#include "vcl/svapp.hxx"
#include "saldata.hxx"
// ----------------------------------------------------------------------
void AquaSalGraphics::SetWindowGraphics( AquaSalFrame* pFrame )
{
mpFrame = pFrame;
mbWindow = true;
mbPrinter = false;
mbVirDev = false;
}
void AquaSalGraphics::SetPrinterGraphics( CGContextRef xContext, long nDPIX, long nDPIY, double fScale )
{
mbWindow = false;
mbPrinter = true;
mbVirDev = false;
mrContext = xContext;
mfFakeDPIScale = fScale;
mnRealDPIX = nDPIX;
mnRealDPIY = nDPIY;
if( mrContext )
{
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
}
static void nil_free( void* )
{
}
void AquaSalGraphics::SetVirDevGraphics( CGContextRef xContext, bool bScreenCompatible )
{
mbWindow = false;
mbPrinter = false;
mbVirDev = true;
mrContext = xContext;
sal_uInt8* pMemory = NULL;
if( mrContext )
{
pMemory = reinterpret_cast<sal_uInt8*>(CGBitmapContextGetData( mrContext ));
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
maContextMemory.reset( pMemory, boost::bind( nil_free, _1 ) );
}
// ----------------------------------------------------------------------
void AquaSalGraphics::SetState()
{
CGContextRestoreGState( mrContext );
CGContextSaveGState( mrContext );
// set up clipping area
if( mrClippingPath )
{
CGContextBeginPath( mrContext ); // discard any existing path
CGContextAddPath( mrContext, mrClippingPath ); // set the current path to the clipping path
CGContextClip( mrContext ); // use it for clipping
}
// set RGB colorspace and line and fill colors
CGContextSetFillColor( mrContext, mpFillColor );
CGContextSetStrokeColor( mrContext, mpLineColor );
if( mbXORMode && (mbWindow || mbVirDev) )
{
CGContextSetBlendMode(mrContext, kCGBlendModeDifference);
int nWidth = CGBitmapContextGetWidth(mrContext);
int nHeight = CGBitmapContextGetHeight(mrContext);
if( ! maXORDevice )
{
maXORDevice = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
mbWindow,
basebmp::Format::THIRTYTWO_BIT_TC_MASK_ARGB,
maContextMemory,
basebmp::PaletteMemorySharedVector() );
if( mrClippingPath && maClippingRects.size() == 1 )
{
/*
* optimization: the case with only one clip rectangle is quite common
* in this case it is much cheaper to constrain the XOR device to a smaller
* area than to clip every pixel with the mask
*/
maXORClipMask.reset();
CGRect aBounds( maClippingRects.front() );
basegfx::B2IRange aRect( aBounds.origin.x, aBounds.origin.y,
aBounds.origin.x+aBounds.size.width,
aBounds.origin.y+aBounds.size.height );
maXORDevice = basebmp::subsetBitmapDevice( maXORDevice, aRect );
}
}
if( mrClippingPath )
{
if( ! maXORClipMask && maClippingRects.size() > 1 )
{
maXORClipMask = basebmp::createBitmapDevice( basegfx::B2IVector( nWidth, nHeight ),
mbWindow,
basebmp::Format::ONE_BIT_MSB_GREY );
maXORClipMask->clear( basebmp::Color(0xffffffff) );
for( std::vector<CGRect>::const_iterator it = maClippingRects.begin(); it != maClippingRects.end(); ++it )
{
basegfx::B2DRectangle aRect( it->origin.x, it->origin.y,
it->origin.x+it->size.width,
it->origin.y+it->size.height );
maXORClipMask->fillPolyPolygon( basegfx::B2DPolyPolygon( basegfx::tools::createPolygonFromRect( aRect ) ),
basebmp::Color( 0 ),
basebmp::DrawMode_PAINT
);
}
}
}
else
maXORClipMask.reset();
}
CGContextSetShouldAntialias( mrContext, false );
}
// ----------------------------------------------------------------------
bool AquaSalGraphics::CheckContext()
{
if( mpFrame != NULL )
{
const unsigned int nWidth = mpFrame->maGeometry.nWidth;
const unsigned int nHeight = mpFrame->maGeometry.nHeight;
CGContextRef rReleaseContext = 0;
unsigned int nReleaseContextWidth = 0;
unsigned int nReleaseContextHeight = 0;
boost::shared_array<sal_uInt8> aOldMem;
if( mrContext )
{
nReleaseContextWidth = CGBitmapContextGetWidth(mrContext);
nReleaseContextHeight = CGBitmapContextGetHeight(mrContext);
// check if window size changed and we need to create a new bitmap context
if( (nReleaseContextWidth != nWidth) || (nReleaseContextHeight != nHeight) )
{
rReleaseContext = mrContext;
mrContext = 0;
aOldMem = maContextMemory;
maXORDevice.reset();
maXORClipMask.reset();
}
}
if( !mrContext )
{
maContextMemory.reset( reinterpret_cast<sal_uInt8*>( rtl_allocateMemory( nWidth * 4 * nHeight ) ),
boost::bind( rtl_freeMemory, _1 ) );
if( maContextMemory )
{
mrContext = CGBitmapContextCreate( maContextMemory.get(), nWidth, nHeight, 8, nWidth * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );
if( mrContext )
{
// copy bitmap data to new context
if( rReleaseContext )
{
CGRect aBounds;
aBounds.origin.x = aBounds.origin.y = 0;
aBounds.size.width = nReleaseContextWidth;
aBounds.size.height = nReleaseContextHeight;
CGImageRef xImage = CGBitmapContextCreateImage( rReleaseContext );
CGContextDrawImage( mrContext, aBounds, xImage );
CGImageRelease(xImage);
}
CGContextTranslateCTM( mrContext, 0, nHeight );
CGContextScaleCTM( mrContext, 1.0, -1.0 );
CGContextSetFillColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSetStrokeColorSpace( mrContext, GetSalData()->mxRGBSpace );
CGContextSaveGState( mrContext );
SetState();
}
else
{
maContextMemory.reset(); // free memory again
}
}
}
if( rReleaseContext ) // released memory runs out of scope and is then freed
CFRelease( rReleaseContext );
}
if( mrContext )
{
if( mbXORMode )
{
if( ! maXORDevice )
SetState();
}
return true;
}
else
{
AquaLog("<<<WARNING>>> AquaSalGraphics::CheckContext() FAILED!!!!\n" );
return false;
}
}
void AquaSalGraphics::RefreshRect(float lX, float lY, float lWidth, float lHeight)
{
if( ! mbWindow ) // view only on Window graphics
return;
if( mpFrame )
{
// update a little more around the designated rectangle
// this helps with antialiased rendering
NSRect aRect = { { lX-1, lY-1 }, { lWidth+2, lHeight+2 } };
mpFrame->VCLToCocoa( aRect, false );
[mpFrame->getView() setNeedsDisplayInRect: aRect];
}
}
CGPoint* AquaSalGraphics::makeCGptArray(ULONG nPoints, const SalPoint* pPtAry)
{
AquaLog("-->%s\n",__func__);
CGPoint *CGpoints = new (CGPoint[nPoints]);
if ( CGpoints )
{
for(ULONG i=0;i<nPoints;i++)
{
CGpoints[i].x = (float)(pPtAry[i].mnX);
CGpoints[i].y = (float)(pPtAry[i].mnY);
}
}
return CGpoints;
}
// -----------------------------------------------------------------------
void AquaSalGraphics::UpdateWindow( NSGraphicsContext* pContext )
{
if( mrContext != NULL && mpFrame != NULL && pContext != nil )
{
CGContextRef rCGContext = reinterpret_cast<CGContextRef>([pContext graphicsPort]);
CGRect aBitmapRect = {
{ 0, 0 },
{ CGBitmapContextGetWidth(mrContext), CGBitmapContextGetHeight(mrContext) }
};
CGImageRef xImage = CGBitmapContextCreateImage( mrContext );
CGContextDrawImage( rCGContext, aBitmapRect, xImage );
CGImageRelease( xImage );
CGContextFlush( rCGContext );
}
}
// -----------------------------------------------------------------------
<|endoftext|>
|
<commit_before>
// .\Release\x64\benchmarks.exe --benchmark_repetitions=3 --benchmark_filter=Planetarium // NOLINT(whitespace/line_length)
#include "ksp_plugin/planetarium.hpp"
#include <algorithm>
#include "astronomy/time_scales.hpp"
#include "base/status_utilities.hpp"
#include "benchmark/benchmark.h"
#include "physics/body_centred_non_rotating_dynamic_frame.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/solar_system_factory.hpp"
namespace principia {
namespace geometry {
using astronomy::operator""_UT1;
using astronomy::operator""_TT;
using base::make_not_null_unique;
using base::not_null;
using geometry::Bivector;
using geometry::DeduceSignReversingOrientation;
using geometry::Perspective;
using geometry::RigidTransformation;
using geometry::RP2Lines;
using geometry::Signature;
using geometry::Vector;
using geometry::Velocity;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::Quinlan1999Order8A;
using integrators::methods::QuinlanTremaine1990Order12;
using ksp_plugin::Camera;
using ksp_plugin::Barycentric;
using ksp_plugin::Navigation;
using ksp_plugin::NavigationFrame;
using ksp_plugin::Planetarium;
using ksp_plugin::ScaledSpacePoint;
using ksp_plugin::World;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::KeplerianElements;
using physics::KeplerOrbit;
using physics::MassiveBody;
using physics::MasslessBody;
using physics::SolarSystem;
using quantities::Angle;
using quantities::Cos;
using quantities::Infinity;
using quantities::Length;
using quantities::Sin;
using quantities::Time;
using quantities::si::ArcMinute;
using quantities::si::Day;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::SolarSystemFactory;
namespace {
constexpr Length near = 40'000 * Kilo(Metre);
constexpr Length far = 400'000 * Kilo(Metre);
constexpr Length focal = 1 * Metre;
Perspective<Navigation, Camera> PolarPerspective(
Length const distance_from_earth) {
using LeftNavigation =
Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
return {
RigidTransformation<Navigation, Camera>(
Navigation::origin + Displacement<Navigation>(
{0 * Metre, 0 * Metre, distance_from_earth}),
Camera::origin,
Rotation<LeftNavigation, Camera>(
Vector<double, LeftNavigation>({1, 0, 0}),
Vector<double, LeftNavigation>({0, -1, 0}),
Bivector<double, LeftNavigation>({0, 0, -1}))
.Forget<OrthogonalMap>() *
Signature<Navigation, LeftNavigation>(
Sign::Positive(),
Sign::Positive(),
DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
focal};
}
Perspective<Navigation, Camera> EquatorialPerspective(
Length const distance_from_earth) {
using LeftNavigation =
Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
return {
RigidTransformation<Navigation, Camera>(
Navigation::origin + Displacement<Navigation>(
{0 * Metre, distance_from_earth, 0 * Metre}),
Camera::origin,
Rotation<LeftNavigation, Camera>(
Vector<double, LeftNavigation>({1, 0, 0}),
Vector<double, LeftNavigation>({0, 0, 1}),
Bivector<double, LeftNavigation>({0, -1, 0}))
.Forget<OrthogonalMap>() *
Signature<Navigation, LeftNavigation>(
Sign::Positive(),
Sign::Positive(),
DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
focal};
}
class Satellites {
public:
Satellites()
: solar_system_(make_not_null_unique<SolarSystem<Barycentric>>(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt",
/*ignore_frame=*/true)),
ephemeris_(solar_system_->MakeEphemeris(
/*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
/*geopotential_tolerance=*/0x1p-24},
EphemerisParameters())),
earth_(solar_system_->massive_body(
*ephemeris_,
SolarSystemFactory::name(SolarSystemFactory::Earth))),
earth_centred_inertial_(
make_not_null_unique<
BodyCentredNonRotatingDynamicFrame<Barycentric, Navigation>>(
ephemeris_.get(),
earth_)) {
// Two-line elements for GOES-8:
// 1 23051U 94022A 00004.06628221 -.00000243 00000-0 00000-0 0 9630
// 2 23051 0.4232 97.7420 0004776 192.8349 121.5613 1.00264613 28364
constexpr Instant goes_8_epoch = "JD2451548.56628221"_UT1;
KeplerianElements<Barycentric> goes_8_elements;
goes_8_elements.inclination = 0.4232 * Degree;
goes_8_elements.longitude_of_ascending_node = 97.7420 * Degree;
goes_8_elements.eccentricity = 0.0004776;
goes_8_elements.argument_of_periapsis = 192.8349 * Degree;
goes_8_elements.mean_anomaly = 121.5613 * Degree;
goes_8_elements.mean_motion = 1.00264613 * (2 * π * Radian / Day);
CHECK_OK(ephemeris_->Prolong(goes_8_epoch));
KeplerOrbit<Barycentric> const goes_8_orbit(
*earth_, MasslessBody{}, goes_8_elements, goes_8_epoch);
CHECK_OK(goes_8_trajectory_.Append(
goes_8_epoch,
ephemeris_->trajectory(earth_)->EvaluateDegreesOfFreedom(goes_8_epoch) +
goes_8_orbit.StateVectors(goes_8_epoch)));
auto goes_8_instance = ephemeris_->NewInstance(
{&goes_8_trajectory_},
Ephemeris<Barycentric>::NoIntrinsicAccelerations,
HistoryParameters());
CHECK_OK(ephemeris_->FlowWithFixedStep(goes_8_epoch + 100 * Day,
*goes_8_instance));
}
DiscreteTrajectory<Barycentric> const& goes_8_trajectory() const {
return goes_8_trajectory_;
}
Planetarium MakePlanetarium(
Perspective<Navigation, Camera> const& perspective) const {
// No dark area, human visual acuity, wide field of view.
Planetarium::Parameters parameters(
/*sphere_radius_multiplier=*/1,
/*angular_resolution=*/0.4 * ArcMinute,
/*field_of_view=*/90 * Degree);
return Planetarium(parameters,
perspective,
ephemeris_.get(),
earth_centred_inertial_.get(),
[](Position<Navigation> const& plotted_point) {
return ScaledSpacePoint::FromCoordinates(
((plotted_point - World::origin) *
(1 / (6000 * Metre))).coordinates());
});
}
private:
Ephemeris<Barycentric>::FixedStepParameters EphemerisParameters() {
return Ephemeris<Barycentric>::FixedStepParameters(
SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
Position<Barycentric>>(),
/*step=*/10 * Minute);
}
Ephemeris<Barycentric>::FixedStepParameters HistoryParameters() {
return Ephemeris<Barycentric>::FixedStepParameters(
SymmetricLinearMultistepIntegrator<Quinlan1999Order8A,
Position<Barycentric>>(),
/*step=*/10 * Second);
}
not_null<std::unique_ptr<SolarSystem<Barycentric>>> const solar_system_;
not_null<std::unique_ptr<Ephemeris<Barycentric>>> const ephemeris_;
not_null<MassiveBody const*> const earth_;
not_null<std::unique_ptr<NavigationFrame>> const earth_centred_inertial_;
DiscreteTrajectory<Barycentric> goes_8_trajectory_;
};
} // namespace
void RunBenchmark(benchmark::State& state,
Perspective<Navigation, Camera> const& perspective) {
Satellites satellites;
Planetarium planetarium = satellites.MakePlanetarium(perspective);
RP2Lines<Length, Camera> lines;
int total_lines = 0;
int iterations = 0;
// This is the time of a lunar eclipse in January 2000.
constexpr Instant now = "2000-01-21T04:41:30,5"_TT;
while (state.KeepRunning()) {
lines = planetarium.PlotMethod2(satellites.goes_8_trajectory(),
satellites.goes_8_trajectory().begin(),
satellites.goes_8_trajectory().end(),
now,
/*reverse=*/false);
total_lines += lines.size();
++iterations;
}
Length min_x = Infinity<Length>;
Length min_y = Infinity<Length>;
Length max_x = -Infinity<Length>;
Length max_y = -Infinity<Length>;
int points = 0;
for (auto const& line : lines) {
points += line.size();
for (auto const& point : line) {
min_x = std::min(min_x, point.x());
min_y = std::min(min_y, point.y());
max_x = std::max(max_x, point.x());
max_y = std::max(max_y, point.y());
}
}
state.SetLabel(std::to_string(points) + " points in " +
std::to_string(total_lines / iterations) + " lines within [" +
DebugString(min_x) + ", " + DebugString(max_x) + "] × [" +
DebugString(min_y) + ", " + DebugString(max_y) + "]");
}
void BM_PlanetariumPlotMethod2NearPolarPerspective(benchmark::State& state) {
RunBenchmark(state, PolarPerspective(near));
}
void BM_PlanetariumPlotMethod2FarPolarPerspective(benchmark::State& state) {
RunBenchmark(state, PolarPerspective(far));
}
void BM_PlanetariumPlotMethod2NearEquatorialPerspective(
benchmark::State& state) {
RunBenchmark(state, EquatorialPerspective(near));
}
void BM_PlanetariumPlotMethod2FarEquatorialPerspective(
benchmark::State& state) {
RunBenchmark(state, EquatorialPerspective(far));
}
BENCHMARK(BM_PlanetariumPlotMethod2NearPolarPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2FarPolarPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2NearEquatorialPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2FarEquatorialPerspective);
} // namespace geometry
} // namespace principia
<commit_msg>navigation<commit_after>
// .\Release\x64\benchmarks.exe --benchmark_repetitions=3 --benchmark_filter=Planetarium // NOLINT(whitespace/line_length)
#include "ksp_plugin/planetarium.hpp"
#include <algorithm>
#include "astronomy/time_scales.hpp"
#include "base/status_utilities.hpp"
#include "benchmark/benchmark.h"
#include "physics/body_centred_non_rotating_dynamic_frame.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/solar_system_factory.hpp"
namespace principia {
namespace geometry {
using astronomy::operator""_UT1;
using astronomy::operator""_TT;
using base::make_not_null_unique;
using base::not_null;
using geometry::Bivector;
using geometry::DeduceSignReversingOrientation;
using geometry::Perspective;
using geometry::RigidTransformation;
using geometry::RP2Lines;
using geometry::Signature;
using geometry::Vector;
using geometry::Velocity;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::Quinlan1999Order8A;
using integrators::methods::QuinlanTremaine1990Order12;
using ksp_plugin::Camera;
using ksp_plugin::Barycentric;
using ksp_plugin::Navigation;
using ksp_plugin::NavigationFrame;
using ksp_plugin::Planetarium;
using ksp_plugin::ScaledSpacePoint;
using ksp_plugin::World;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::KeplerianElements;
using physics::KeplerOrbit;
using physics::MassiveBody;
using physics::MasslessBody;
using physics::SolarSystem;
using quantities::Angle;
using quantities::Cos;
using quantities::Infinity;
using quantities::Length;
using quantities::Sin;
using quantities::Time;
using quantities::si::ArcMinute;
using quantities::si::Day;
using quantities::si::Degree;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::SolarSystemFactory;
namespace {
constexpr Length near = 40'000 * Kilo(Metre);
constexpr Length far = 400'000 * Kilo(Metre);
constexpr Length focal = 1 * Metre;
Perspective<Navigation, Camera> PolarPerspective(
Length const distance_from_earth) {
using LeftNavigation =
Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
return {
RigidTransformation<Navigation, Camera>(
Navigation::origin + Displacement<Navigation>(
{0 * Metre, 0 * Metre, distance_from_earth}),
Camera::origin,
Rotation<LeftNavigation, Camera>(
Vector<double, LeftNavigation>({1, 0, 0}),
Vector<double, LeftNavigation>({0, -1, 0}),
Bivector<double, LeftNavigation>({0, 0, -1}))
.Forget<OrthogonalMap>() *
Signature<Navigation, LeftNavigation>(
Sign::Positive(),
Sign::Positive(),
DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
focal};
}
Perspective<Navigation, Camera> EquatorialPerspective(
Length const distance_from_earth) {
using LeftNavigation =
Frame<enum class LeftNavigationTag, Arbitrary, Handedness::Left>;
return {
RigidTransformation<Navigation, Camera>(
Navigation::origin + Displacement<Navigation>(
{0 * Metre, distance_from_earth, 0 * Metre}),
Camera::origin,
Rotation<LeftNavigation, Camera>(
Vector<double, LeftNavigation>({1, 0, 0}),
Vector<double, LeftNavigation>({0, 0, 1}),
Bivector<double, LeftNavigation>({0, -1, 0}))
.Forget<OrthogonalMap>() *
Signature<Navigation, LeftNavigation>(
Sign::Positive(),
Sign::Positive(),
DeduceSignReversingOrientation{}).Forget<OrthogonalMap>()),
focal};
}
class Satellites {
public:
Satellites()
: solar_system_(make_not_null_unique<SolarSystem<Barycentric>>(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2451545_000000000.proto.txt",
/*ignore_frame=*/true)),
ephemeris_(solar_system_->MakeEphemeris(
/*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
/*geopotential_tolerance=*/0x1p-24},
EphemerisParameters())),
earth_(solar_system_->massive_body(
*ephemeris_,
SolarSystemFactory::name(SolarSystemFactory::Earth))),
earth_centred_inertial_(
make_not_null_unique<
BodyCentredNonRotatingDynamicFrame<Barycentric, Navigation>>(
ephemeris_.get(),
earth_)) {
// Two-line elements for GOES-8:
// 1 23051U 94022A 00004.06628221 -.00000243 00000-0 00000-0 0 9630
// 2 23051 0.4232 97.7420 0004776 192.8349 121.5613 1.00264613 28364
constexpr Instant goes_8_epoch = "JD2451548.56628221"_UT1;
KeplerianElements<Barycentric> goes_8_elements;
goes_8_elements.inclination = 0.4232 * Degree;
goes_8_elements.longitude_of_ascending_node = 97.7420 * Degree;
goes_8_elements.eccentricity = 0.0004776;
goes_8_elements.argument_of_periapsis = 192.8349 * Degree;
goes_8_elements.mean_anomaly = 121.5613 * Degree;
goes_8_elements.mean_motion = 1.00264613 * (2 * π * Radian / Day);
CHECK_OK(ephemeris_->Prolong(goes_8_epoch));
KeplerOrbit<Barycentric> const goes_8_orbit(
*earth_, MasslessBody{}, goes_8_elements, goes_8_epoch);
CHECK_OK(goes_8_trajectory_.Append(
goes_8_epoch,
ephemeris_->trajectory(earth_)->EvaluateDegreesOfFreedom(goes_8_epoch) +
goes_8_orbit.StateVectors(goes_8_epoch)));
auto goes_8_instance = ephemeris_->NewInstance(
{&goes_8_trajectory_},
Ephemeris<Barycentric>::NoIntrinsicAccelerations,
HistoryParameters());
CHECK_OK(ephemeris_->FlowWithFixedStep(goes_8_epoch + 100 * Day,
*goes_8_instance));
}
DiscreteTrajectory<Barycentric> const& goes_8_trajectory() const {
return goes_8_trajectory_;
}
Planetarium MakePlanetarium(
Perspective<Navigation, Camera> const& perspective) const {
// No dark area, human visual acuity, wide field of view.
Planetarium::Parameters parameters(
/*sphere_radius_multiplier=*/1,
/*angular_resolution=*/0.4 * ArcMinute,
/*field_of_view=*/90 * Degree);
return Planetarium(parameters,
perspective,
ephemeris_.get(),
earth_centred_inertial_.get(),
[](Position<Navigation> const& plotted_point) {
return ScaledSpacePoint::FromCoordinates(
((plotted_point - Navigation::origin) *
(1 / (6000 * Metre))).coordinates());
});
}
private:
Ephemeris<Barycentric>::FixedStepParameters EphemerisParameters() {
return Ephemeris<Barycentric>::FixedStepParameters(
SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
Position<Barycentric>>(),
/*step=*/10 * Minute);
}
Ephemeris<Barycentric>::FixedStepParameters HistoryParameters() {
return Ephemeris<Barycentric>::FixedStepParameters(
SymmetricLinearMultistepIntegrator<Quinlan1999Order8A,
Position<Barycentric>>(),
/*step=*/10 * Second);
}
not_null<std::unique_ptr<SolarSystem<Barycentric>>> const solar_system_;
not_null<std::unique_ptr<Ephemeris<Barycentric>>> const ephemeris_;
not_null<MassiveBody const*> const earth_;
not_null<std::unique_ptr<NavigationFrame>> const earth_centred_inertial_;
DiscreteTrajectory<Barycentric> goes_8_trajectory_;
};
} // namespace
void RunBenchmark(benchmark::State& state,
Perspective<Navigation, Camera> const& perspective) {
Satellites satellites;
Planetarium planetarium = satellites.MakePlanetarium(perspective);
RP2Lines<Length, Camera> lines;
int total_lines = 0;
int iterations = 0;
// This is the time of a lunar eclipse in January 2000.
constexpr Instant now = "2000-01-21T04:41:30,5"_TT;
while (state.KeepRunning()) {
lines = planetarium.PlotMethod2(satellites.goes_8_trajectory(),
satellites.goes_8_trajectory().begin(),
satellites.goes_8_trajectory().end(),
now,
/*reverse=*/false);
total_lines += lines.size();
++iterations;
}
Length min_x = Infinity<Length>;
Length min_y = Infinity<Length>;
Length max_x = -Infinity<Length>;
Length max_y = -Infinity<Length>;
int points = 0;
for (auto const& line : lines) {
points += line.size();
for (auto const& point : line) {
min_x = std::min(min_x, point.x());
min_y = std::min(min_y, point.y());
max_x = std::max(max_x, point.x());
max_y = std::max(max_y, point.y());
}
}
state.SetLabel(std::to_string(points) + " points in " +
std::to_string(total_lines / iterations) + " lines within [" +
DebugString(min_x) + ", " + DebugString(max_x) + "] × [" +
DebugString(min_y) + ", " + DebugString(max_y) + "]");
}
void BM_PlanetariumPlotMethod2NearPolarPerspective(benchmark::State& state) {
RunBenchmark(state, PolarPerspective(near));
}
void BM_PlanetariumPlotMethod2FarPolarPerspective(benchmark::State& state) {
RunBenchmark(state, PolarPerspective(far));
}
void BM_PlanetariumPlotMethod2NearEquatorialPerspective(
benchmark::State& state) {
RunBenchmark(state, EquatorialPerspective(near));
}
void BM_PlanetariumPlotMethod2FarEquatorialPerspective(
benchmark::State& state) {
RunBenchmark(state, EquatorialPerspective(far));
}
BENCHMARK(BM_PlanetariumPlotMethod2NearPolarPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2FarPolarPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2NearEquatorialPerspective);
BENCHMARK(BM_PlanetariumPlotMethod2FarEquatorialPerspective);
} // namespace geometry
} // namespace principia
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/sysdriv.h"
#include "cstool/initapp.h"
#include "isys/system.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "iengine/engine.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "ivaria/conout.h"
#include "isys/vfs.h"
#include "igraphic/imageio.h"
#include "ivideo/fontserv.h"
#include "imap/parser.h"
#include "isys/plugin.h"
#include "iutil/eventq.h"
#include "iutil/evdefs.h"
#include "iutil/virtclk.h"
#include "iutil/eventq.h"
#include "iutil/cmdline.h"
#include "iutil/cfgmgr.h"
static SysSystemDriver* global_sys = NULL;
static char* global_config_name = NULL;
static int global_argc = 0;
static const char* const * global_argv = 0;
static iEventHandler* installed_event_handler = NULL;
iObjectRegistry* csInitializer::CreateEnvironment ()
{
if (!InitializeSCF ()) return NULL;
iObjectRegistry* object_reg = CreateObjectRegistry ();
if (!object_reg) return NULL;
if (!CreatePluginManager (object_reg)) return NULL;
if (!CreateEventQueue (object_reg)) return NULL;
if (!CreateVirtualClock (object_reg)) return NULL;
if (!CreateCommandLineParser (object_reg)) return NULL;
if (!CreateConfigManager (object_reg)) return NULL;
return object_reg;
}
bool csInitializer::InitializeSCF ()
{
global_sys = new SysSystemDriver ();
return true;
}
iPluginManager* csInitializer::CreatePluginManager (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iPluginManager);
}
iEventQueue* csInitializer::CreateEventQueue (iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iEventQueue);
}
iVirtualClock* csInitializer::CreateVirtualClock (iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iVirtualClock);
}
iCommandLineParser* csInitializer::CreateCommandLineParser (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iCommandLineParser);
}
iConfigManager* csInitializer::CreateConfigManager (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iConfigManager);
}
iObjectRegistry* csInitializer::CreateObjectRegistry ()
{
return global_sys->GetObjectRegistry ();
}
bool csInitializer::RequestPlugins (iObjectRegistry* /*object_reg*/,
const char* config_name,
int argc, const char* const argv[],
...)
{
if (config_name) global_config_name = csStrNew (config_name);
else global_config_name = NULL;
global_argc = argc;
global_argv = argv;
va_list arg;
va_start (arg, argv);
char* plugName = va_arg (arg, char*);
while (plugName != NULL)
{
// scfId and version are unused for now.
int scfId = va_arg (arg, scfInterfaceID);
int version = va_arg (arg, int);
global_sys->RequestPlugin (plugName);
plugName = va_arg (arg, char*);
}
va_end (arg);
return true;
}
bool csInitializer::Initialize (iObjectRegistry* object_reg)
{
bool rc = global_sys->Initialize (global_argc, global_argv,
global_config_name);
if (!rc) return false;
// Setup the object registry.
iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);
iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
iGraphics3D);
if (g3d)
{
object_reg->Register (g3d);
if (g3d->GetDriver2D ())
object_reg->Register (g3d->GetDriver2D ());
g3d->DecRef ();
}
else
{
iGraphics2D* g2d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_CANVAS,
iGraphics2D);
if (g2d) { object_reg->Register (g2d); g2d->DecRef (); }
}
iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
if (engine)
{
object_reg->Register (engine);
engine->DecRef ();
}
iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
if (vfs)
{
object_reg->Register (vfs);
vfs->DecRef ();
}
iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_CONSOLE, iConsoleOutput);
if (console)
{
object_reg->Register (console);
console->DecRef ();
}
iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_LVLLOADER, iLoader);
if (loader)
{
object_reg->Register (loader);
loader->DecRef ();
}
iImageIO* imloader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_IMGLOADER, iImageIO);
if (imloader)
{
object_reg->Register (imloader);
imloader->DecRef ();
}
iFontServer* fntsvr = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_FONTSERVER, iFontServer);
if (fntsvr)
{
object_reg->Register (fntsvr);
fntsvr->DecRef ();
}
iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
iReporter);
if (reporter)
{
object_reg->Register (reporter);
reporter->DecRef ();
}
iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
iStandardReporterListener);
if (stdrep)
{
stdrep->SetDefaults ();
object_reg->Register (stdrep);
stdrep->DecRef ();
}
return true;
}
bool csInitializer::SetupEventHandler (iObjectRegistry* object_reg,
iEventHandler* evhdlr, unsigned int eventmask)
{
iEventQueue* q = CS_QUERY_REGISTRY (object_reg, iEventQueue);
if (q)
{
q->RegisterListener (evhdlr, eventmask);
installed_event_handler = evhdlr;
return true;
}
else return false;
}
class csAppEventHandler : public iEventHandler
{
private:
csEventHandlerFunc* evhdlr;
public:
csAppEventHandler (csEventHandlerFunc* evhdlr)
{
SCF_CONSTRUCT_IBASE (NULL);
csAppEventHandler::evhdlr = evhdlr;
}
SCF_DECLARE_IBASE;
virtual bool HandleEvent (iEvent& ev)
{
return evhdlr (ev);
}
};
SCF_IMPLEMENT_IBASE (csAppEventHandler)
SCF_IMPLEMENTS_INTERFACE (iEventHandler)
SCF_IMPLEMENT_IBASE_END
bool csInitializer::SetupEventHandler (iObjectRegistry* object_reg,
csEventHandlerFunc* evhdlr_func)
{
csAppEventHandler* evhdlr = new csAppEventHandler (evhdlr_func);
return SetupEventHandler (object_reg, evhdlr, CSMASK_Broadcast |
CSMASK_MouseUp | CSMASK_MouseDown | CSMASK_MouseMove |
CSMASK_KeyDown | CSMASK_KeyUp | CSMASK_MouseClick |
CSMASK_MouseDoubleClick | CSMASK_JoystickMove |
CSMASK_JoystickDown | CSMASK_JoystickUp | CSMASK_Nothing);
}
bool csInitializer::OpenApplication (iObjectRegistry* object_reg)
{
return global_sys->Open ();
}
void csInitializer::CloseApplication (iObjectRegistry* object_reg)
{
global_sys->Close ();
}
void csInitializer::DestroyApplication (iObjectRegistry* object_reg)
{
if (installed_event_handler)
{
iEventQueue* q = CS_QUERY_REGISTRY (object_reg, iEventQueue);
q->RemoveListener (installed_event_handler);
}
delete global_sys;
}
bool csInitializeApplication (iObjectRegistry* object_reg, bool use_reporter,
bool use_reporter_listener)
{
iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);
iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
iGraphics3D);
if (g3d)
{
object_reg->Register (g3d);
if (g3d->GetDriver2D ())
object_reg->Register (g3d->GetDriver2D ());
g3d->DecRef ();
}
iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
if (engine)
{
object_reg->Register (engine);
engine->DecRef ();
}
iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
if (vfs)
{
object_reg->Register (vfs);
vfs->DecRef ();
}
iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_CONSOLE, iConsoleOutput);
if (console)
{
object_reg->Register (console);
console->DecRef ();
}
iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_LVLLOADER, iLoader);
if (loader)
{
object_reg->Register (loader);
loader->DecRef ();
}
iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
iReporter);
if (!reporter && use_reporter)
{
reporter = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.reporter",
CS_FUNCID_REPORTER, iReporter);
if (!reporter)
return false;
}
if (reporter)
{
object_reg->Register (reporter);
reporter->DecRef ();
}
iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
iStandardReporterListener);
if (!stdrep && use_reporter_listener)
{
stdrep = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.stdrep",
"StdRep", iStandardReporterListener);
if (!stdrep)
return false;
}
if (stdrep)
{
stdrep->SetDefaults ();
object_reg->Register (stdrep);
stdrep->DecRef ();
}
return true;
}
bool csInitializer::MainLoop (iObjectRegistry* /*object_reg*/)
{
global_sys->Loop ();
return true;
}
<commit_msg>Applied the correct fix.<commit_after>/*
Copyright (C) 2001 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "cssys/sysdriv.h"
#include "cstool/initapp.h"
#include "isys/system.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "iutil/objreg.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "iengine/engine.h"
#include "ivaria/reporter.h"
#include "ivaria/stdrep.h"
#include "ivaria/conout.h"
#include "isys/vfs.h"
#include "igraphic/imageio.h"
#include "ivideo/fontserv.h"
#include "imap/parser.h"
#include "isys/plugin.h"
#include "iutil/eventq.h"
#include "iutil/evdefs.h"
#include "iutil/virtclk.h"
#include "iutil/eventq.h"
#include "iutil/cmdline.h"
#include "iutil/cfgmgr.h"
static SysSystemDriver* global_sys = NULL;
static char* global_config_name = NULL;
static int global_argc = 0;
static const char* const * global_argv = 0;
static iEventHandler* installed_event_handler = NULL;
iObjectRegistry* csInitializer::CreateEnvironment ()
{
if (!InitializeSCF ()) return NULL;
iObjectRegistry* object_reg = CreateObjectRegistry ();
if (!object_reg) return NULL;
if (!CreatePluginManager (object_reg)) return NULL;
if (!CreateEventQueue (object_reg)) return NULL;
if (!CreateVirtualClock (object_reg)) return NULL;
if (!CreateCommandLineParser (object_reg)) return NULL;
if (!CreateConfigManager (object_reg)) return NULL;
return object_reg;
}
bool csInitializer::InitializeSCF ()
{
global_sys = new SysSystemDriver ();
return true;
}
iPluginManager* csInitializer::CreatePluginManager (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iPluginManager);
}
iEventQueue* csInitializer::CreateEventQueue (iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iEventQueue);
}
iVirtualClock* csInitializer::CreateVirtualClock (iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iVirtualClock);
}
iCommandLineParser* csInitializer::CreateCommandLineParser (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iCommandLineParser);
}
iConfigManager* csInitializer::CreateConfigManager (
iObjectRegistry* object_reg)
{
return CS_QUERY_REGISTRY (object_reg, iConfigManager);
}
iObjectRegistry* csInitializer::CreateObjectRegistry ()
{
return global_sys->GetObjectRegistry ();
}
bool csInitializer::RequestPlugins (iObjectRegistry* /*object_reg*/,
const char* config_name,
int argc, const char* const argv[],
...)
{
if (config_name) global_config_name = csStrNew (config_name);
else global_config_name = NULL;
global_argc = argc;
global_argv = argv;
va_list arg;
va_start (arg, argv);
char* plugName = va_arg (arg, char*);
while (plugName != NULL)
{
int scfId = va_arg (arg, scfInterfaceID);
int version = va_arg (arg, int);
// scfId and version are unused for now.
(void)scfId; (void)version;
global_sys->RequestPlugin (plugName);
plugName = va_arg (arg, char*);
}
va_end (arg);
return true;
}
bool csInitializer::Initialize (iObjectRegistry* object_reg)
{
bool rc = global_sys->Initialize (global_argc, global_argv,
global_config_name);
if (!rc) return false;
// Setup the object registry.
iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);
iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
iGraphics3D);
if (g3d)
{
object_reg->Register (g3d);
if (g3d->GetDriver2D ())
object_reg->Register (g3d->GetDriver2D ());
g3d->DecRef ();
}
else
{
iGraphics2D* g2d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_CANVAS,
iGraphics2D);
if (g2d) { object_reg->Register (g2d); g2d->DecRef (); }
}
iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
if (engine)
{
object_reg->Register (engine);
engine->DecRef ();
}
iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
if (vfs)
{
object_reg->Register (vfs);
vfs->DecRef ();
}
iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_CONSOLE, iConsoleOutput);
if (console)
{
object_reg->Register (console);
console->DecRef ();
}
iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_LVLLOADER, iLoader);
if (loader)
{
object_reg->Register (loader);
loader->DecRef ();
}
iImageIO* imloader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_IMGLOADER, iImageIO);
if (imloader)
{
object_reg->Register (imloader);
imloader->DecRef ();
}
iFontServer* fntsvr = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_FONTSERVER, iFontServer);
if (fntsvr)
{
object_reg->Register (fntsvr);
fntsvr->DecRef ();
}
iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
iReporter);
if (reporter)
{
object_reg->Register (reporter);
reporter->DecRef ();
}
iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
iStandardReporterListener);
if (stdrep)
{
stdrep->SetDefaults ();
object_reg->Register (stdrep);
stdrep->DecRef ();
}
return true;
}
bool csInitializer::SetupEventHandler (iObjectRegistry* object_reg,
iEventHandler* evhdlr, unsigned int eventmask)
{
iEventQueue* q = CS_QUERY_REGISTRY (object_reg, iEventQueue);
if (q)
{
q->RegisterListener (evhdlr, eventmask);
installed_event_handler = evhdlr;
return true;
}
else return false;
}
class csAppEventHandler : public iEventHandler
{
private:
csEventHandlerFunc* evhdlr;
public:
csAppEventHandler (csEventHandlerFunc* evhdlr)
{
SCF_CONSTRUCT_IBASE (NULL);
csAppEventHandler::evhdlr = evhdlr;
}
SCF_DECLARE_IBASE;
virtual bool HandleEvent (iEvent& ev)
{
return evhdlr (ev);
}
};
SCF_IMPLEMENT_IBASE (csAppEventHandler)
SCF_IMPLEMENTS_INTERFACE (iEventHandler)
SCF_IMPLEMENT_IBASE_END
bool csInitializer::SetupEventHandler (iObjectRegistry* object_reg,
csEventHandlerFunc* evhdlr_func)
{
csAppEventHandler* evhdlr = new csAppEventHandler (evhdlr_func);
return SetupEventHandler (object_reg, evhdlr, CSMASK_Broadcast |
CSMASK_MouseUp | CSMASK_MouseDown | CSMASK_MouseMove |
CSMASK_KeyDown | CSMASK_KeyUp | CSMASK_MouseClick |
CSMASK_MouseDoubleClick | CSMASK_JoystickMove |
CSMASK_JoystickDown | CSMASK_JoystickUp | CSMASK_Nothing);
}
bool csInitializer::OpenApplication (iObjectRegistry* object_reg)
{
return global_sys->Open ();
}
void csInitializer::CloseApplication (iObjectRegistry* object_reg)
{
global_sys->Close ();
}
void csInitializer::DestroyApplication (iObjectRegistry* object_reg)
{
if (installed_event_handler)
{
iEventQueue* q = CS_QUERY_REGISTRY (object_reg, iEventQueue);
q->RemoveListener (installed_event_handler);
}
delete global_sys;
}
bool csInitializeApplication (iObjectRegistry* object_reg, bool use_reporter,
bool use_reporter_listener)
{
iPluginManager* plugin_mgr = CS_QUERY_REGISTRY (object_reg, iPluginManager);
iGraphics3D* g3d = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VIDEO,
iGraphics3D);
if (g3d)
{
object_reg->Register (g3d);
if (g3d->GetDriver2D ())
object_reg->Register (g3d->GetDriver2D ());
g3d->DecRef ();
}
iEngine* engine = CS_QUERY_PLUGIN (plugin_mgr, iEngine);
if (engine)
{
object_reg->Register (engine);
engine->DecRef ();
}
iVFS* vfs = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_VFS, iVFS);
if (vfs)
{
object_reg->Register (vfs);
vfs->DecRef ();
}
iConsoleOutput* console = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_CONSOLE, iConsoleOutput);
if (console)
{
object_reg->Register (console);
console->DecRef ();
}
iLoader* loader = CS_QUERY_PLUGIN_ID (plugin_mgr,
CS_FUNCID_LVLLOADER, iLoader);
if (loader)
{
object_reg->Register (loader);
loader->DecRef ();
}
iReporter* reporter = CS_QUERY_PLUGIN_ID (plugin_mgr, CS_FUNCID_REPORTER,
iReporter);
if (!reporter && use_reporter)
{
reporter = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.reporter",
CS_FUNCID_REPORTER, iReporter);
if (!reporter)
return false;
}
if (reporter)
{
object_reg->Register (reporter);
reporter->DecRef ();
}
iStandardReporterListener* stdrep = CS_QUERY_PLUGIN (plugin_mgr,
iStandardReporterListener);
if (!stdrep && use_reporter_listener)
{
stdrep = CS_LOAD_PLUGIN (plugin_mgr, "crystalspace.utilities.stdrep",
"StdRep", iStandardReporterListener);
if (!stdrep)
return false;
}
if (stdrep)
{
stdrep->SetDefaults ();
object_reg->Register (stdrep);
stdrep->DecRef ();
}
return true;
}
bool csInitializer::MainLoop (iObjectRegistry* /*object_reg*/)
{
global_sys->Loop ();
return true;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on : Jul 7, 2012
// Last revision: Jul 10, 2014
// Author : Min Yang Jung (myj@jhu.edu)
// Github : https://github.com/minyang/casros
//
#include "event.h"
using namespace SF;
Event::Event(const std::string & name,
unsigned int severity,
const TransitionsType & transitions)
: Name(name), Severity(severity), Transitions(transitions)
{
memset(TransitionMask, 0, TOTAL_NUMBER_OF_STATES * TOTAL_NUMBER_OF_STATES);
#define N 0
#define W 1
#define E 2
// Counters to check if this event has multiple next states for one current state
int fromN = 0, fromW = 0, fromE = 0;
for (size_t i = 0; i < Transitions.size(); ++i) {
switch (Transitions[i]) {
case State::NORMAL_TO_WARNING: TransitionMask[N][W] = true; ++fromN; break;
case State::NORMAL_TO_ERROR : TransitionMask[N][E] = true; ++fromN; break;
case State::WARNING_TO_NORMAL: TransitionMask[W][N] = true; ++fromW; break;
case State::WARNING_TO_ERROR : TransitionMask[W][E] = true; ++fromW; break;
case State::ERROR_TO_WARNING : TransitionMask[E][W] = true; ++fromE; break;
case State::ERROR_TO_NORMAL : TransitionMask[E][N] = true; ++fromE; break;
default: continue;
}
}
if (fromN >= 2 || fromW >= 2 || fromE >= 2) {
SFLOG_ERROR << "Event transition error: event \"" << Name << "\" has multiple next states" << std::endl;
SFLOG_ERROR << (int) TransitionMask[N][N] << " " << (int) TransitionMask[N][W] << " " << (int) TransitionMask[N][E] << std::endl;
SFLOG_ERROR << (int) TransitionMask[W][N] << " " << (int) TransitionMask[W][W] << " " << (int) TransitionMask[W][E] << std::endl;
SFLOG_ERROR << (int) TransitionMask[E][N] << " " << (int) TransitionMask[E][W] << " " << (int) TransitionMask[E][E] << std::endl;
throw("Event error");
}
#undef N
#undef W
#undef E
}
State::TransitionType Event::GetTransition(State::StateType currentState) const
{
switch (currentState) {
case State::NORMAL:
if (TransitionMask[State::NORMAL][State::WARNING])
return State::NORMAL_TO_WARNING;
else if (TransitionMask[State::NORMAL][State::ERROR])
return State::NORMAL_TO_ERROR;
break;
case State::WARNING:
if (TransitionMask[State::WARNING][State::NORMAL])
return State::WARNING_TO_NORMAL;
else if (TransitionMask[State::WARNING][State::ERROR])
return State::WARNING_TO_ERROR;
break;
case State::ERROR:
if (TransitionMask[State::ERROR][State::NORMAL])
return State::ERROR_TO_NORMAL;
else if (TransitionMask[State::ERROR][State::WARNING])
return State::ERROR_TO_WARNING;
break;
default:
return State::INVALID_TRANSITION;
}
}
void Event::ToStream(std::ostream & os) const
{
os << Name << ": " << Severity << ", [ ";
for (size_t i = 0; i < Transitions.size(); ++i) {
switch (Transitions[i]) {
case State::NORMAL_TO_ERROR : os << "N2E "; break;
case State::ERROR_TO_NORMAL : os << "E2N "; break;
case State::NORMAL_TO_WARNING: os << "N2W "; break;
case State::WARNING_TO_NORMAL: os << "W2N "; break;
case State::WARNING_TO_ERROR : os << "W2E "; break;
case State::ERROR_TO_WARNING : os << "E2W "; break;
default: os << "INVALID ";
}
}
os << "], ";
}
<commit_msg>added missing return value for invalid transitions<commit_after>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on : Jul 7, 2012
// Last revision: Jul 10, 2014
// Author : Min Yang Jung (myj@jhu.edu)
// Github : https://github.com/minyang/casros
//
#include "event.h"
using namespace SF;
Event::Event(const std::string & name,
unsigned int severity,
const TransitionsType & transitions)
: Name(name), Severity(severity), Transitions(transitions)
{
memset(TransitionMask, 0, TOTAL_NUMBER_OF_STATES * TOTAL_NUMBER_OF_STATES);
#define N 0
#define W 1
#define E 2
// Counters to check if this event has multiple next states for one current state
int fromN = 0, fromW = 0, fromE = 0;
for (size_t i = 0; i < Transitions.size(); ++i) {
switch (Transitions[i]) {
case State::NORMAL_TO_WARNING: TransitionMask[N][W] = true; ++fromN; break;
case State::NORMAL_TO_ERROR : TransitionMask[N][E] = true; ++fromN; break;
case State::WARNING_TO_NORMAL: TransitionMask[W][N] = true; ++fromW; break;
case State::WARNING_TO_ERROR : TransitionMask[W][E] = true; ++fromW; break;
case State::ERROR_TO_WARNING : TransitionMask[E][W] = true; ++fromE; break;
case State::ERROR_TO_NORMAL : TransitionMask[E][N] = true; ++fromE; break;
default: continue;
}
}
if (fromN >= 2 || fromW >= 2 || fromE >= 2) {
SFLOG_ERROR << "Event transition error: event \"" << Name << "\" has multiple next states" << std::endl;
SFLOG_ERROR << (int) TransitionMask[N][N] << " " << (int) TransitionMask[N][W] << " " << (int) TransitionMask[N][E] << std::endl;
SFLOG_ERROR << (int) TransitionMask[W][N] << " " << (int) TransitionMask[W][W] << " " << (int) TransitionMask[W][E] << std::endl;
SFLOG_ERROR << (int) TransitionMask[E][N] << " " << (int) TransitionMask[E][W] << " " << (int) TransitionMask[E][E] << std::endl;
throw("Event error");
}
#undef N
#undef W
#undef E
}
State::TransitionType Event::GetTransition(State::StateType currentState) const
{
switch (currentState) {
case State::NORMAL:
if (TransitionMask[State::NORMAL][State::WARNING])
return State::NORMAL_TO_WARNING;
else if (TransitionMask[State::NORMAL][State::ERROR])
return State::NORMAL_TO_ERROR;
break;
case State::WARNING:
if (TransitionMask[State::WARNING][State::NORMAL])
return State::WARNING_TO_NORMAL;
else if (TransitionMask[State::WARNING][State::ERROR])
return State::WARNING_TO_ERROR;
break;
case State::ERROR:
if (TransitionMask[State::ERROR][State::NORMAL])
return State::ERROR_TO_NORMAL;
else if (TransitionMask[State::ERROR][State::WARNING])
return State::ERROR_TO_WARNING;
break;
default:
return State::INVALID_TRANSITION;
}
return State::INVALID_TRANSITION;
}
void Event::ToStream(std::ostream & os) const
{
os << Name << ": " << Severity << ", [ ";
for (size_t i = 0; i < Transitions.size(); ++i) {
switch (Transitions[i]) {
case State::NORMAL_TO_ERROR : os << "N2E "; break;
case State::ERROR_TO_NORMAL : os << "E2N "; break;
case State::NORMAL_TO_WARNING: os << "N2W "; break;
case State::WARNING_TO_NORMAL: os << "W2N "; break;
case State::WARNING_TO_ERROR : os << "W2E "; break;
case State::ERROR_TO_WARNING : os << "E2W "; break;
default: os << "INVALID ";
}
}
os << "], ";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For information about interceptions as a whole see
// http://wiki/Main/ChromeSandboxInterceptionDesign
#include <set>
#include "sandbox/src/interception.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "sandbox/src/interception_internal.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_utils.h"
#include "sandbox/src/service_resolver.h"
#include "sandbox/src/target_interceptions.h"
#include "sandbox/src/target_process.h"
#include "sandbox/src/wow64.h"
namespace {
const char kMapViewOfSectionName[] = "NtMapViewOfSection";
const char kUnmapViewOfSectionName[] = "NtUnmapViewOfSection";
} // namespace
namespace sandbox {
SANDBOX_INTERCEPT SharedMemory* g_interceptions;
InterceptionManager::InterceptionManager(TargetProcess* child_process,
bool relaxed)
: child_(child_process), names_used_(false), relaxed_(relaxed) {
child_->AddRef();
}
InterceptionManager::~InterceptionManager() {
child_->Release();
}
bool InterceptionManager::AddToPatchedFunctions(
const wchar_t* dll_name, const char* function_name,
InterceptionType interception_type, const void* replacement_code_address) {
InterceptionData function;
function.type = interception_type;
function.dll = dll_name;
function.function = function_name;
function.interceptor_address = replacement_code_address;
interceptions_.push_back(function);
return true;
}
bool InterceptionManager::AddToPatchedFunctions(
const wchar_t* dll_name, const char* function_name,
InterceptionType interception_type, const char* replacement_function_name) {
InterceptionData function;
function.type = interception_type;
function.dll = dll_name;
function.function = function_name;
function.interceptor = replacement_function_name;
function.interceptor_address = NULL;
interceptions_.push_back(function);
names_used_ = true;
return true;
}
bool InterceptionManager::InitializeInterceptions() {
if (interceptions_.empty())
return true; // Nothing to do here
size_t buffer_bytes = GetBufferSize();
scoped_ptr<char> local_buffer(new char[buffer_bytes]);
if (!SetupConfigBuffer(local_buffer.get(), buffer_bytes))
return false;
void* remote_buffer;
if (!CopyDataToChild(local_buffer.get(), buffer_bytes, &remote_buffer))
return false;
bool hot_patch_needed = (0 != buffer_bytes);
if (!PatchNtdll(hot_patch_needed))
return false;
g_interceptions = reinterpret_cast<SharedMemory*>(remote_buffer);
child_->TransferVariable("sandbox::g_interceptions", &g_interceptions,
sizeof(g_interceptions));
return true;
}
size_t InterceptionManager::GetBufferSize() const {
std::set<std::wstring> dlls;
size_t buffer_bytes = 0;
std::list<InterceptionData>::const_iterator it = interceptions_.begin();
for (; it != interceptions_.end(); ++it) {
// skip interceptions that are performed from the parent
if (!IsInterceptionPerformedByChild(*it))
continue;
if (!dlls.count(it->dll)) {
// NULL terminate the dll name on the structure
size_t dll_name_bytes = (it->dll.size() + 1) * sizeof(wchar_t);
// include the dll related size
buffer_bytes += RoundUpToMultiple(offsetof(DllPatchInfo, dll_name) +
dll_name_bytes, sizeof(size_t));
dlls.insert(it->dll);
}
// we have to NULL terminate the strings on the structure
size_t strings_chars = it->function.size() + it->interceptor.size() + 2;
// a new FunctionInfo is required per function
size_t record_bytes = offsetof(FunctionInfo, function) + strings_chars;
record_bytes = RoundUpToMultiple(record_bytes, sizeof(size_t));
buffer_bytes += record_bytes;
}
if (0 != buffer_bytes)
// add the part of SharedMemory that we have not counted yet
buffer_bytes += offsetof(SharedMemory, dll_list);
return buffer_bytes;
}
// Basically, walk the list of interceptions moving them to the config buffer,
// but keeping together all interceptions that belong to the same dll.
// The config buffer is a local buffer, not the one allocated on the child.
bool InterceptionManager::SetupConfigBuffer(void* buffer, size_t buffer_bytes) {
if (0 == buffer_bytes)
return true;
DCHECK(buffer_bytes > sizeof(SharedMemory));
SharedMemory* shared_memory = reinterpret_cast<SharedMemory*>(buffer);
DllPatchInfo* dll_info = shared_memory->dll_list;
int num_dlls = 0;
shared_memory->interceptor_base = names_used_ ? child_->MainModule() : NULL;
buffer_bytes -= offsetof(SharedMemory, dll_list);
buffer = dll_info;
std::list<InterceptionData>::iterator it = interceptions_.begin();
for (; it != interceptions_.end();) {
// skip interceptions that are performed from the parent
if (!IsInterceptionPerformedByChild(*it)) {
++it;
continue;
}
const std::wstring dll = it->dll;
if (!SetupDllInfo(*it, &buffer, &buffer_bytes))
return false;
// walk the interceptions from this point, saving the ones that are
// performed on this dll, and removing the entry from the list.
// advance the iterator before removing the element from the list
std::list<InterceptionData>::iterator rest = it;
for (; rest != interceptions_.end();) {
if (rest->dll == dll) {
if (!SetupInterceptionInfo(*rest, &buffer, &buffer_bytes, dll_info))
return false;
if (it == rest)
++it;
rest = interceptions_.erase(rest);
} else {
++rest;
}
}
dll_info = reinterpret_cast<DllPatchInfo*>(buffer);
++num_dlls;
}
shared_memory->num_intercepted_dlls = num_dlls;
return true;
}
// Fills up just the part that depends on the dll, not the info that depends on
// the actual interception.
bool InterceptionManager::SetupDllInfo(const InterceptionData& data,
void** buffer,
size_t* buffer_bytes) const {
DCHECK(buffer_bytes);
DCHECK(buffer);
DCHECK(*buffer);
DllPatchInfo* dll_info = reinterpret_cast<DllPatchInfo*>(*buffer);
// the strings have to be zero terminated
size_t required = offsetof(DllPatchInfo, dll_name) +
(data.dll.size() + 1) * sizeof(wchar_t);
required = RoundUpToMultiple(required, sizeof(size_t));
if (*buffer_bytes < required)
return false;
*buffer_bytes -= required;
*buffer = reinterpret_cast<char*>(*buffer) + required;
// set up the dll info to be what we know about it at this time
dll_info->record_bytes = required;
dll_info->offset_to_functions = required;
dll_info->num_functions = 0;
data.dll._Copy_s(dll_info->dll_name, data.dll.size(), data.dll.size());
dll_info->dll_name[data.dll.size()] = L'\0';
return true;
}
bool InterceptionManager::SetupInterceptionInfo(const InterceptionData& data,
void** buffer,
size_t* buffer_bytes,
DllPatchInfo* dll_info) const {
DCHECK(buffer_bytes);
DCHECK(buffer);
DCHECK(*buffer);
FunctionInfo* function = reinterpret_cast<FunctionInfo*>(*buffer);
size_t name_bytes = data.function.size();
size_t interceptor_bytes = data.interceptor.size();
// the strings at the end of the structure are zero terminated
size_t required = offsetof(FunctionInfo, function) +
name_bytes + interceptor_bytes + 2;
required = RoundUpToMultiple(required, sizeof(size_t));
if (*buffer_bytes < required)
return false;
// update the caller's values
*buffer_bytes -= required;
*buffer = reinterpret_cast<char*>(*buffer) + required;
function->record_bytes = required;
function->type = data.type;
function->interceptor_address = data.interceptor_address;
char* names = function->function;
data.function._Copy_s(names, name_bytes, name_bytes);
names += name_bytes;
*names++ = '\0';
// interceptor follows the function_name
data.interceptor._Copy_s(names, interceptor_bytes, interceptor_bytes);
names += interceptor_bytes;
*names++ = '\0';
// update the dll table
dll_info->num_functions++;
dll_info->record_bytes += required;
return true;
}
bool InterceptionManager::CopyDataToChild(const void* local_buffer,
size_t buffer_bytes,
void** remote_buffer) const {
DCHECK(NULL != remote_buffer);
if (0 == buffer_bytes) {
*remote_buffer = NULL;
return true;
}
HANDLE child = child_->Process();
// Allocate memory on the target process without specifying the address
void* remote_data = ::VirtualAllocEx(child, NULL, buffer_bytes,
MEM_COMMIT, PAGE_READWRITE);
if (NULL == remote_data)
return false;
SIZE_T bytes_written;
BOOL success = ::WriteProcessMemory(child, remote_data, local_buffer,
buffer_bytes, &bytes_written);
if (FALSE == success || bytes_written != buffer_bytes) {
::VirtualFreeEx(child, remote_data, 0, MEM_RELEASE);
return false;
}
*remote_buffer = remote_data;
return true;
}
// Only return true if the child should be able to perform this interception.
bool InterceptionManager::IsInterceptionPerformedByChild(
const InterceptionData& data) const {
if (INTERCEPTION_INVALID == data.type)
return false;
if (INTERCEPTION_SERVICE_CALL == data.type)
return false;
if (data.type >= INTERCEPTION_LAST)
return false;
std::wstring ntdll(kNtdllName);
if (ntdll == data.dll)
return false; // ntdll has to be intercepted from the parent
return true;
}
bool InterceptionManager::PatchNtdll(bool hot_patch_needed) {
// Maybe there is nothing to do
if (!hot_patch_needed && interceptions_.empty())
return true;
if (hot_patch_needed) {
#if SANDBOX_EXPORTS
AddToPatchedFunctions(kNtdllName, kMapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
"_TargetNtMapViewOfSection@44");
AddToPatchedFunctions(kNtdllName, kUnmapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
"_TargetNtUnmapViewOfSection@12");
#else
AddToPatchedFunctions(kNtdllName, kMapViewOfSectionName,
INTERCEPTION_SERVICE_CALL, &TargetNtMapViewOfSection);
AddToPatchedFunctions(kNtdllName, kUnmapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
&TargetNtUnmapViewOfSection);
#endif
}
size_t thunk_bytes = interceptions_.size() * sizeof(ThunkData) +
sizeof(DllInterceptionData);
// Allocate memory on the child, without specifying the desired address
HANDLE child = child_->Process();
DllInterceptionData* thunks = reinterpret_cast<DllInterceptionData*>(
::VirtualAllocEx(child, NULL, thunk_bytes,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE));
DllInterceptionData dll_data;
dll_data.data_bytes = thunk_bytes;
dll_data.num_thunks = 0;
dll_data.used_bytes = offsetof(DllInterceptionData, thunks);
// this should write all the individual thunks to the child's memory
if (!PatchClientFunctions(thunks, thunk_bytes, &dll_data))
return false;
// and now write the first part of the table to the child's memory
DWORD written;
bool ok = FALSE != ::WriteProcessMemory(child, thunks, &dll_data,
offsetof(DllInterceptionData, thunks),
&written);
if (!ok || (offsetof(DllInterceptionData, thunks) != written))
return false;
// Attempt to protect all the thunks, but ignore failure
DWORD old_protection;
::VirtualProtectEx(child, thunks, thunk_bytes,
PAGE_EXECUTE_READ, &old_protection);
return true;
}
bool InterceptionManager::PatchClientFunctions(DllInterceptionData* thunks,
size_t thunk_bytes,
DllInterceptionData* dll_data) {
DCHECK(NULL != thunks);
DCHECK(NULL != dll_data);
HMODULE ntdll_base = ::GetModuleHandle(kNtdllName);
if (!ntdll_base)
return false;
// Bypass purify's interception.
wchar_t* loader_get = reinterpret_cast<wchar_t*>(
::GetProcAddress(ntdll_base, "LdrGetDllHandle"));
if (loader_get) {
if (!GetModuleHandleHelper(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
loader_get, &ntdll_base))
return false;
}
Wow64 WowHelper(child_, ntdll_base);
if (!WowHelper.WaitForNtdll(INFINITE))
return false;
char* interceptor_base = NULL;
#if SANDBOX_EXPORTS
interceptor_base = reinterpret_cast<char*>(child_->MainModule());
HMODULE local_interceptor = ::LoadLibrary(child_->Name());
#endif
ServiceResolverThunk* thunk;
if (WowHelper.IsWow64())
thunk = new Wow64ResolverThunk(child_->Process(), relaxed_);
else if (!IsXPSP2OrLater())
thunk = new Win2kResolverThunk(child_->Process(), relaxed_);
else
thunk = new ServiceResolverThunk(child_->Process(), relaxed_);
std::list<InterceptionData>::iterator it = interceptions_.begin();
for (; it != interceptions_.end(); ++it) {
const std::wstring ntdll(kNtdllName);
if (it->dll != ntdll)
break;
if (INTERCEPTION_SERVICE_CALL != it->type)
break;
#if SANDBOX_EXPORTS
// We may be trying to patch by function name.
if (NULL == it->interceptor_address) {
const char* address;
NTSTATUS ret = thunk->ResolveInterceptor(local_interceptor,
it->interceptor.c_str(),
reinterpret_cast<const void**>(
&address));
if (!NT_SUCCESS(ret))
break;
// Translate the local address to an address on the child.
it->interceptor_address = interceptor_base + (address -
reinterpret_cast<char*>(local_interceptor));
}
#endif
NTSTATUS ret = thunk->Setup(ntdll_base,
interceptor_base,
it->function.c_str(),
it->interceptor.c_str(),
it->interceptor_address,
&thunks->thunks[dll_data->num_thunks],
thunk_bytes - dll_data->used_bytes,
NULL);
if (!NT_SUCCESS(ret))
break;
dll_data->num_thunks++;
dll_data->used_bytes += sizeof(ThunkData);
}
delete(thunk);
#if SANDBOX_EXPORTS
if (NULL != local_interceptor)
::FreeLibrary(local_interceptor);
#endif
if (it != interceptions_.end())
return false;
return true;
}
} // namespace sandbox
<commit_msg>For some reasons the linker excludes 2 of our hooks when linking in SANDBOX_EXPORTS mode. Add pragmas to be sure these hooks are included.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// For information about interceptions as a whole see
// http://wiki/Main/ChromeSandboxInterceptionDesign
#include <set>
#include "sandbox/src/interception.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "sandbox/src/interception_internal.h"
#include "sandbox/src/sandbox.h"
#include "sandbox/src/sandbox_utils.h"
#include "sandbox/src/service_resolver.h"
#include "sandbox/src/target_interceptions.h"
#include "sandbox/src/target_process.h"
#include "sandbox/src/wow64.h"
namespace {
const char kMapViewOfSectionName[] = "NtMapViewOfSection";
const char kUnmapViewOfSectionName[] = "NtUnmapViewOfSection";
} // namespace
namespace sandbox {
SANDBOX_INTERCEPT SharedMemory* g_interceptions;
InterceptionManager::InterceptionManager(TargetProcess* child_process,
bool relaxed)
: child_(child_process), names_used_(false), relaxed_(relaxed) {
child_->AddRef();
}
InterceptionManager::~InterceptionManager() {
child_->Release();
}
bool InterceptionManager::AddToPatchedFunctions(
const wchar_t* dll_name, const char* function_name,
InterceptionType interception_type, const void* replacement_code_address) {
InterceptionData function;
function.type = interception_type;
function.dll = dll_name;
function.function = function_name;
function.interceptor_address = replacement_code_address;
interceptions_.push_back(function);
return true;
}
bool InterceptionManager::AddToPatchedFunctions(
const wchar_t* dll_name, const char* function_name,
InterceptionType interception_type, const char* replacement_function_name) {
InterceptionData function;
function.type = interception_type;
function.dll = dll_name;
function.function = function_name;
function.interceptor = replacement_function_name;
function.interceptor_address = NULL;
interceptions_.push_back(function);
names_used_ = true;
return true;
}
bool InterceptionManager::InitializeInterceptions() {
if (interceptions_.empty())
return true; // Nothing to do here
size_t buffer_bytes = GetBufferSize();
scoped_ptr<char> local_buffer(new char[buffer_bytes]);
if (!SetupConfigBuffer(local_buffer.get(), buffer_bytes))
return false;
void* remote_buffer;
if (!CopyDataToChild(local_buffer.get(), buffer_bytes, &remote_buffer))
return false;
bool hot_patch_needed = (0 != buffer_bytes);
if (!PatchNtdll(hot_patch_needed))
return false;
g_interceptions = reinterpret_cast<SharedMemory*>(remote_buffer);
child_->TransferVariable("sandbox::g_interceptions", &g_interceptions,
sizeof(g_interceptions));
return true;
}
size_t InterceptionManager::GetBufferSize() const {
std::set<std::wstring> dlls;
size_t buffer_bytes = 0;
std::list<InterceptionData>::const_iterator it = interceptions_.begin();
for (; it != interceptions_.end(); ++it) {
// skip interceptions that are performed from the parent
if (!IsInterceptionPerformedByChild(*it))
continue;
if (!dlls.count(it->dll)) {
// NULL terminate the dll name on the structure
size_t dll_name_bytes = (it->dll.size() + 1) * sizeof(wchar_t);
// include the dll related size
buffer_bytes += RoundUpToMultiple(offsetof(DllPatchInfo, dll_name) +
dll_name_bytes, sizeof(size_t));
dlls.insert(it->dll);
}
// we have to NULL terminate the strings on the structure
size_t strings_chars = it->function.size() + it->interceptor.size() + 2;
// a new FunctionInfo is required per function
size_t record_bytes = offsetof(FunctionInfo, function) + strings_chars;
record_bytes = RoundUpToMultiple(record_bytes, sizeof(size_t));
buffer_bytes += record_bytes;
}
if (0 != buffer_bytes)
// add the part of SharedMemory that we have not counted yet
buffer_bytes += offsetof(SharedMemory, dll_list);
return buffer_bytes;
}
// Basically, walk the list of interceptions moving them to the config buffer,
// but keeping together all interceptions that belong to the same dll.
// The config buffer is a local buffer, not the one allocated on the child.
bool InterceptionManager::SetupConfigBuffer(void* buffer, size_t buffer_bytes) {
if (0 == buffer_bytes)
return true;
DCHECK(buffer_bytes > sizeof(SharedMemory));
SharedMemory* shared_memory = reinterpret_cast<SharedMemory*>(buffer);
DllPatchInfo* dll_info = shared_memory->dll_list;
int num_dlls = 0;
shared_memory->interceptor_base = names_used_ ? child_->MainModule() : NULL;
buffer_bytes -= offsetof(SharedMemory, dll_list);
buffer = dll_info;
std::list<InterceptionData>::iterator it = interceptions_.begin();
for (; it != interceptions_.end();) {
// skip interceptions that are performed from the parent
if (!IsInterceptionPerformedByChild(*it)) {
++it;
continue;
}
const std::wstring dll = it->dll;
if (!SetupDllInfo(*it, &buffer, &buffer_bytes))
return false;
// walk the interceptions from this point, saving the ones that are
// performed on this dll, and removing the entry from the list.
// advance the iterator before removing the element from the list
std::list<InterceptionData>::iterator rest = it;
for (; rest != interceptions_.end();) {
if (rest->dll == dll) {
if (!SetupInterceptionInfo(*rest, &buffer, &buffer_bytes, dll_info))
return false;
if (it == rest)
++it;
rest = interceptions_.erase(rest);
} else {
++rest;
}
}
dll_info = reinterpret_cast<DllPatchInfo*>(buffer);
++num_dlls;
}
shared_memory->num_intercepted_dlls = num_dlls;
return true;
}
// Fills up just the part that depends on the dll, not the info that depends on
// the actual interception.
bool InterceptionManager::SetupDllInfo(const InterceptionData& data,
void** buffer,
size_t* buffer_bytes) const {
DCHECK(buffer_bytes);
DCHECK(buffer);
DCHECK(*buffer);
DllPatchInfo* dll_info = reinterpret_cast<DllPatchInfo*>(*buffer);
// the strings have to be zero terminated
size_t required = offsetof(DllPatchInfo, dll_name) +
(data.dll.size() + 1) * sizeof(wchar_t);
required = RoundUpToMultiple(required, sizeof(size_t));
if (*buffer_bytes < required)
return false;
*buffer_bytes -= required;
*buffer = reinterpret_cast<char*>(*buffer) + required;
// set up the dll info to be what we know about it at this time
dll_info->record_bytes = required;
dll_info->offset_to_functions = required;
dll_info->num_functions = 0;
data.dll._Copy_s(dll_info->dll_name, data.dll.size(), data.dll.size());
dll_info->dll_name[data.dll.size()] = L'\0';
return true;
}
bool InterceptionManager::SetupInterceptionInfo(const InterceptionData& data,
void** buffer,
size_t* buffer_bytes,
DllPatchInfo* dll_info) const {
DCHECK(buffer_bytes);
DCHECK(buffer);
DCHECK(*buffer);
FunctionInfo* function = reinterpret_cast<FunctionInfo*>(*buffer);
size_t name_bytes = data.function.size();
size_t interceptor_bytes = data.interceptor.size();
// the strings at the end of the structure are zero terminated
size_t required = offsetof(FunctionInfo, function) +
name_bytes + interceptor_bytes + 2;
required = RoundUpToMultiple(required, sizeof(size_t));
if (*buffer_bytes < required)
return false;
// update the caller's values
*buffer_bytes -= required;
*buffer = reinterpret_cast<char*>(*buffer) + required;
function->record_bytes = required;
function->type = data.type;
function->interceptor_address = data.interceptor_address;
char* names = function->function;
data.function._Copy_s(names, name_bytes, name_bytes);
names += name_bytes;
*names++ = '\0';
// interceptor follows the function_name
data.interceptor._Copy_s(names, interceptor_bytes, interceptor_bytes);
names += interceptor_bytes;
*names++ = '\0';
// update the dll table
dll_info->num_functions++;
dll_info->record_bytes += required;
return true;
}
bool InterceptionManager::CopyDataToChild(const void* local_buffer,
size_t buffer_bytes,
void** remote_buffer) const {
DCHECK(NULL != remote_buffer);
if (0 == buffer_bytes) {
*remote_buffer = NULL;
return true;
}
HANDLE child = child_->Process();
// Allocate memory on the target process without specifying the address
void* remote_data = ::VirtualAllocEx(child, NULL, buffer_bytes,
MEM_COMMIT, PAGE_READWRITE);
if (NULL == remote_data)
return false;
SIZE_T bytes_written;
BOOL success = ::WriteProcessMemory(child, remote_data, local_buffer,
buffer_bytes, &bytes_written);
if (FALSE == success || bytes_written != buffer_bytes) {
::VirtualFreeEx(child, remote_data, 0, MEM_RELEASE);
return false;
}
*remote_buffer = remote_data;
return true;
}
// Only return true if the child should be able to perform this interception.
bool InterceptionManager::IsInterceptionPerformedByChild(
const InterceptionData& data) const {
if (INTERCEPTION_INVALID == data.type)
return false;
if (INTERCEPTION_SERVICE_CALL == data.type)
return false;
if (data.type >= INTERCEPTION_LAST)
return false;
std::wstring ntdll(kNtdllName);
if (ntdll == data.dll)
return false; // ntdll has to be intercepted from the parent
return true;
}
bool InterceptionManager::PatchNtdll(bool hot_patch_needed) {
// Maybe there is nothing to do
if (!hot_patch_needed && interceptions_.empty())
return true;
if (hot_patch_needed) {
#if SANDBOX_EXPORTS
// Make sure the functions are not excluded by the linker.
#pragma comment(linker, "/include:_TargetNtMapViewOfSection@44")
#pragma comment(linker, "/include:_TargetNtUnmapViewOfSection@12")
AddToPatchedFunctions(kNtdllName, kMapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
"_TargetNtMapViewOfSection@44");
AddToPatchedFunctions(kNtdllName, kUnmapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
"_TargetNtUnmapViewOfSection@12");
#else
AddToPatchedFunctions(kNtdllName, kMapViewOfSectionName,
INTERCEPTION_SERVICE_CALL, &TargetNtMapViewOfSection);
AddToPatchedFunctions(kNtdllName, kUnmapViewOfSectionName,
INTERCEPTION_SERVICE_CALL,
&TargetNtUnmapViewOfSection);
#endif
}
size_t thunk_bytes = interceptions_.size() * sizeof(ThunkData) +
sizeof(DllInterceptionData);
// Allocate memory on the child, without specifying the desired address
HANDLE child = child_->Process();
DllInterceptionData* thunks = reinterpret_cast<DllInterceptionData*>(
::VirtualAllocEx(child, NULL, thunk_bytes,
MEM_COMMIT,
PAGE_EXECUTE_READWRITE));
DllInterceptionData dll_data;
dll_data.data_bytes = thunk_bytes;
dll_data.num_thunks = 0;
dll_data.used_bytes = offsetof(DllInterceptionData, thunks);
// this should write all the individual thunks to the child's memory
if (!PatchClientFunctions(thunks, thunk_bytes, &dll_data))
return false;
// and now write the first part of the table to the child's memory
DWORD written;
bool ok = FALSE != ::WriteProcessMemory(child, thunks, &dll_data,
offsetof(DllInterceptionData, thunks),
&written);
if (!ok || (offsetof(DllInterceptionData, thunks) != written))
return false;
// Attempt to protect all the thunks, but ignore failure
DWORD old_protection;
::VirtualProtectEx(child, thunks, thunk_bytes,
PAGE_EXECUTE_READ, &old_protection);
return true;
}
bool InterceptionManager::PatchClientFunctions(DllInterceptionData* thunks,
size_t thunk_bytes,
DllInterceptionData* dll_data) {
DCHECK(NULL != thunks);
DCHECK(NULL != dll_data);
HMODULE ntdll_base = ::GetModuleHandle(kNtdllName);
if (!ntdll_base)
return false;
// Bypass purify's interception.
wchar_t* loader_get = reinterpret_cast<wchar_t*>(
::GetProcAddress(ntdll_base, "LdrGetDllHandle"));
if (loader_get) {
if (!GetModuleHandleHelper(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
loader_get, &ntdll_base))
return false;
}
Wow64 WowHelper(child_, ntdll_base);
if (!WowHelper.WaitForNtdll(INFINITE))
return false;
char* interceptor_base = NULL;
#if SANDBOX_EXPORTS
interceptor_base = reinterpret_cast<char*>(child_->MainModule());
HMODULE local_interceptor = ::LoadLibrary(child_->Name());
#endif
ServiceResolverThunk* thunk;
if (WowHelper.IsWow64())
thunk = new Wow64ResolverThunk(child_->Process(), relaxed_);
else if (!IsXPSP2OrLater())
thunk = new Win2kResolverThunk(child_->Process(), relaxed_);
else
thunk = new ServiceResolverThunk(child_->Process(), relaxed_);
std::list<InterceptionData>::iterator it = interceptions_.begin();
for (; it != interceptions_.end(); ++it) {
const std::wstring ntdll(kNtdllName);
if (it->dll != ntdll)
break;
if (INTERCEPTION_SERVICE_CALL != it->type)
break;
#if SANDBOX_EXPORTS
// We may be trying to patch by function name.
if (NULL == it->interceptor_address) {
const char* address;
NTSTATUS ret = thunk->ResolveInterceptor(local_interceptor,
it->interceptor.c_str(),
reinterpret_cast<const void**>(
&address));
if (!NT_SUCCESS(ret))
break;
// Translate the local address to an address on the child.
it->interceptor_address = interceptor_base + (address -
reinterpret_cast<char*>(local_interceptor));
}
#endif
NTSTATUS ret = thunk->Setup(ntdll_base,
interceptor_base,
it->function.c_str(),
it->interceptor.c_str(),
it->interceptor_address,
&thunks->thunks[dll_data->num_thunks],
thunk_bytes - dll_data->used_bytes,
NULL);
if (!NT_SUCCESS(ret))
break;
dll_data->num_thunks++;
dll_data->used_bytes += sizeof(ThunkData);
}
delete(thunk);
#if SANDBOX_EXPORTS
if (NULL != local_interceptor)
::FreeLibrary(local_interceptor);
#endif
if (it != interceptions_.end())
return false;
return true;
}
} // namespace sandbox
<|endoftext|>
|
<commit_before>/**
* \file
* \brief staticThreadBlinker example application
*
* \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/distortosConfiguration.h"
#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
#include "distortos/board/leds.hpp"
#include "distortos/chip/ChipOutputPin.hpp"
#endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
/**
* \brief LED blinking function
*
* Constantly toggles state of \a led and waits for half of \a periodMs.
*
* \param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function
* \param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds
*/
void ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs)
{
while (1)
{
led.set(!led.get()); // invert state of LED
distortos::ThisThread::sleepFor(periodMs / 2);
}
}
#endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
/**
* \brief Boolean variable "blinking" function
*
* Constantly toggles value of \a variable and waits for half of \a periodMs. This function is meant as a demonstration
* for configuration which either has no LEDs or doesn't enable them.
*
* \param [in] variable is a reference to bool variable which will be toggled by this function
* \param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds
*/
void variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs)
{
while (1)
{
variable = !variable; // invert state of variable
distortos::ThisThread::sleepFor(periodMs / 2);
}
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Main code block of staticThreadBlinker application
*
* This example application tries to demonstrate the most basic aspects of static threads:
* - creating and starting them,
* - passing arguments to thread's function by reference and by value,
* - joining them.
*
* If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is
* created - it "blinks" a boolean variable instead of a real LED. Otherwise up to four additional threads are created
* (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was
* passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are
* slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods
* are actually prime numbers, so they create very long "global" period (in which the whole pattern repeats).
*
* Even though all created threads never terminate (their functions have infinite loops and never return), main thread
* calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest
* way to suspend main thread in this example application.
*
* \return doesn't return
*/
int main()
{
bool variable {};
// create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction()
// will get variable by reference and period by value
auto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction,
std::ref(variable), std::chrono::milliseconds{401});
#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
// create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will
// get its own LED by reference and period by value
auto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[0]), std::chrono::milliseconds{397});
# if CONFIG_BOARD_TOTAL_LEDS >= 2
auto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[1]), std::chrono::milliseconds{389});
# if CONFIG_BOARD_TOTAL_LEDS >= 3
auto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[2]), std::chrono::milliseconds{383});
# if CONFIG_BOARD_TOTAL_LEDS >= 4
auto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[3]), std::chrono::milliseconds{379});
ledBlinkerThread3.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 4
ledBlinkerThread2.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 3
ledBlinkerThread1.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 2
ledBlinkerThread0.join();
#endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
variableBlinkerThread.join();
return 0;
}
<commit_msg>Simplify preprocessor conditions in staticThreadBlinker<commit_after>/**
* \file
* \brief staticThreadBlinker example application
*
* \author Copyright (C) 2016-2017 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/distortosConfiguration.h"
#if defined(CONFIG_BOARD_LEDS_ENABLE)
#include "distortos/board/leds.hpp"
#include "distortos/chip/ChipOutputPin.hpp"
#endif // defined(CONFIG_BOARD_LEDS_ENABLE)
#include "distortos/StaticThread.hpp"
#include "distortos/ThisThread.hpp"
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
#if defined(CONFIG_BOARD_LEDS_ENABLE)
/**
* \brief LED blinking function
*
* Constantly toggles state of \a led and waits for half of \a periodMs.
*
* \param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function
* \param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds
*/
void ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs)
{
while (1)
{
led.set(!led.get()); // invert state of LED
distortos::ThisThread::sleepFor(periodMs / 2);
}
}
#endif // defined(CONFIG_BOARD_LEDS_ENABLE)
/**
* \brief Boolean variable "blinking" function
*
* Constantly toggles value of \a variable and waits for half of \a periodMs. This function is meant as a demonstration
* for configuration which either has no LEDs or doesn't enable them.
*
* \param [in] variable is a reference to bool variable which will be toggled by this function
* \param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds
*/
void variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs)
{
while (1)
{
variable = !variable; // invert state of variable
distortos::ThisThread::sleepFor(periodMs / 2);
}
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Main code block of staticThreadBlinker application
*
* This example application tries to demonstrate the most basic aspects of static threads:
* - creating and starting them,
* - passing arguments to thread's function by reference and by value,
* - joining them.
*
* If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is
* created - it "blinks" a boolean variable instead of a real LED. Otherwise up to four additional threads are created
* (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was
* passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are
* slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods
* are actually prime numbers, so they create very long "global" period (in which the whole pattern repeats).
*
* Even though all created threads never terminate (their functions have infinite loops and never return), main thread
* calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest
* way to suspend main thread in this example application.
*
* \return doesn't return
*/
int main()
{
bool variable {};
// create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction()
// will get variable by reference and period by value
auto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction,
std::ref(variable), std::chrono::milliseconds{401});
#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
// create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will
// get its own LED by reference and period by value
auto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[0]), std::chrono::milliseconds{397});
# if CONFIG_BOARD_TOTAL_LEDS >= 2
auto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[1]), std::chrono::milliseconds{389});
# if CONFIG_BOARD_TOTAL_LEDS >= 3
auto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[2]), std::chrono::milliseconds{383});
# if CONFIG_BOARD_TOTAL_LEDS >= 4
auto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,
std::ref(distortos::board::leds[3]), std::chrono::milliseconds{379});
ledBlinkerThread3.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 4
ledBlinkerThread2.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 3
ledBlinkerThread1.join();
# endif // CONFIG_BOARD_TOTAL_LEDS >= 2
ledBlinkerThread0.join();
#endif // defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1
variableBlinkerThread.join();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "browser/linux/libnotify_notification.h"
#include "base/files/file_enumerator.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "browser/notification_delegate.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "common/application_info.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace brightray {
namespace {
LibNotifyLoader libnotify_loader_;
bool HasCapability(const std::string& capability) {
bool result = false;
GList* capabilities = libnotify_loader_.notify_get_server_caps();
if (g_list_find_custom(capabilities, capability.c_str(), (GCompareFunc) g_strcmp0) != NULL)
result = true;
g_list_free_full(capabilities, g_free);
return result;
}
bool NotifierSupportsActions() {
if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER"))
return false;
static bool notify_has_result = false;
static bool notify_result = false;
GList *capabilities = NULL;
if (notify_has_result)
return notify_result;
notify_result = HasCapability("actions");
return notify_result;
}
void log_and_clear_error(GError* error, const char* context) {
LOG(ERROR) << context
<< ": domain=" << error->domain
<< " code=" << error->code
<< " message=\"" << error->message << '"';
g_error_free(error);
}
} // namespace
// static
Notification* Notification::Create(NotificationDelegate* delegate,
NotificationPresenter* presenter) {
return new LibnotifyNotification(delegate, presenter);
}
// static
bool LibnotifyNotification::Initialize() {
if (!libnotify_loader_.Load("libnotify.so.4") &&
!libnotify_loader_.Load("libnotify.so.1") &&
!libnotify_loader_.Load("libnotify.so")) {
return false;
}
if (!libnotify_loader_.notify_is_initted() &&
!libnotify_loader_.notify_init(GetApplicationName().c_str())) {
return false;
}
return true;
}
LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter),
notification_(nullptr) {
}
LibnotifyNotification::~LibnotifyNotification() {
g_signal_handlers_disconnect_by_data(notification_, this);
g_object_unref(notification_);
}
void LibnotifyNotification::Show(const base::string16& title,
const base::string16& body,
const std::string& tag,
const GURL& icon_url,
const SkBitmap& icon,
const bool silent) {
notification_ = libnotify_loader_.notify_notification_new(
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(body).c_str(),
nullptr);
g_signal_connect(
notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this);
// NB: On Unity and on any other DE using Notify-OSD, adding a notification
// action will cause the notification to display as a modal dialog box.
if (NotifierSupportsActions()) {
libnotify_loader_.notify_notification_add_action(
notification_, "default", "View", OnNotificationViewThunk, this,
nullptr);
}
if (!icon.drawsNothing()) {
GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(icon);
libnotify_loader_.notify_notification_set_image_from_pixbuf(
notification_, pixbuf);
libnotify_loader_.notify_notification_set_timeout(
notification_, NOTIFY_EXPIRES_DEFAULT);
g_object_unref(pixbuf);
}
if (!tag.empty()) {
GQuark id = g_quark_from_string(tag.c_str());
g_object_set(G_OBJECT(notification_), "id", id, NULL);
}
GError* error = nullptr;
libnotify_loader_.notify_notification_show(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_show");
NotificationFailed();
return;
}
delegate()->NotificationDisplayed();
}
void LibnotifyNotification::Dismiss() {
GError* error = nullptr;
libnotify_loader_.notify_notification_close(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_close");
Destroy();
}
}
void LibnotifyNotification::OnNotificationClosed(
NotifyNotification* notification) {
delegate()->NotificationClosed();
Destroy();
}
void LibnotifyNotification::OnNotificationView(
NotifyNotification* notification, char* action) {
delegate()->NotificationClick();
Destroy();
}
void LibnotifyNotification::NotificationFailed() {
delegate()->NotificationFailed();
Destroy();
}
} // namespace brightray
<commit_msg>LibnotifyNotification: use "append" when supported<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "browser/linux/libnotify_notification.h"
#include "base/files/file_enumerator.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "browser/notification_delegate.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "common/application_info.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace brightray {
namespace {
LibNotifyLoader libnotify_loader_;
bool HasCapability(const std::string& capability) {
bool result = false;
GList* capabilities = libnotify_loader_.notify_get_server_caps();
if (g_list_find_custom(capabilities, capability.c_str(), (GCompareFunc) g_strcmp0) != NULL)
result = true;
g_list_free_full(capabilities, g_free);
return result;
}
bool NotifierSupportsActions() {
if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER"))
return false;
static bool notify_has_result = false;
static bool notify_result = false;
GList *capabilities = NULL;
if (notify_has_result)
return notify_result;
notify_result = HasCapability("actions");
return notify_result;
}
void log_and_clear_error(GError* error, const char* context) {
LOG(ERROR) << context
<< ": domain=" << error->domain
<< " code=" << error->code
<< " message=\"" << error->message << '"';
g_error_free(error);
}
} // namespace
// static
Notification* Notification::Create(NotificationDelegate* delegate,
NotificationPresenter* presenter) {
return new LibnotifyNotification(delegate, presenter);
}
// static
bool LibnotifyNotification::Initialize() {
if (!libnotify_loader_.Load("libnotify.so.4") &&
!libnotify_loader_.Load("libnotify.so.1") &&
!libnotify_loader_.Load("libnotify.so")) {
return false;
}
if (!libnotify_loader_.notify_is_initted() &&
!libnotify_loader_.notify_init(GetApplicationName().c_str())) {
return false;
}
return true;
}
LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate,
NotificationPresenter* presenter)
: Notification(delegate, presenter),
notification_(nullptr) {
}
LibnotifyNotification::~LibnotifyNotification() {
g_signal_handlers_disconnect_by_data(notification_, this);
g_object_unref(notification_);
}
void LibnotifyNotification::Show(const base::string16& title,
const base::string16& body,
const std::string& tag,
const GURL& icon_url,
const SkBitmap& icon,
const bool silent) {
notification_ = libnotify_loader_.notify_notification_new(
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(body).c_str(),
nullptr);
g_signal_connect(
notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this);
// NB: On Unity and on any other DE using Notify-OSD, adding a notification
// action will cause the notification to display as a modal dialog box.
if (NotifierSupportsActions()) {
libnotify_loader_.notify_notification_add_action(
notification_, "default", "View", OnNotificationViewThunk, this,
nullptr);
}
if (!icon.drawsNothing()) {
GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(icon);
libnotify_loader_.notify_notification_set_image_from_pixbuf(
notification_, pixbuf);
libnotify_loader_.notify_notification_set_timeout(
notification_, NOTIFY_EXPIRES_DEFAULT);
g_object_unref(pixbuf);
}
if (!tag.empty()) {
GQuark id = g_quark_from_string(tag.c_str());
g_object_set(G_OBJECT(notification_), "id", id, NULL);
}
// Always try to append notifications.
// Unique tags can be used to prevent this.
if (HasCapability("append")) {
libnotify_loader_.notify_notification_set_hint_string(
notification_, "append", "true");
} else if (HasCapability("x-canonical-append")) {
libnotify_loader_.notify_notification_set_hint_string(
notification_, "x-canonical-append", "true");
}
GError* error = nullptr;
libnotify_loader_.notify_notification_show(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_show");
NotificationFailed();
return;
}
delegate()->NotificationDisplayed();
}
void LibnotifyNotification::Dismiss() {
GError* error = nullptr;
libnotify_loader_.notify_notification_close(notification_, &error);
if (error) {
log_and_clear_error(error, "notify_notification_close");
Destroy();
}
}
void LibnotifyNotification::OnNotificationClosed(
NotifyNotification* notification) {
delegate()->NotificationClosed();
Destroy();
}
void LibnotifyNotification::OnNotificationView(
NotifyNotification* notification, char* action) {
delegate()->NotificationClick();
Destroy();
}
void LibnotifyNotification::NotificationFailed() {
delegate()->NotificationFailed();
Destroy();
}
} // namespace brightray
<|endoftext|>
|
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "actionmanager.h"
#include "browserframe.h"
#include "browserframe_p.h"
#include "openurlrequest.h"
#include <QAction>
#include <QGridLayout>
#include <QList>
#include <QPoint>
#include <QString>
#include <QWidget>
#include <kaction.h>
#include <kdebug.h>
#include <klibloader.h>
#include <kmenu.h>
#include <kmimetypetrader.h>
#include <ktoolbarpopupaction.h>
#include <kurl.h>
#include <kxmlguiclient.h>
#include <kparts/browserextension.h>
#include <kparts/part.h>
namespace Akregator {
BrowserFrame::BrowserFrame(QWidget* parent) : Frame(parent)
{
d = new BrowserFramePrivate(this);
d->part = 0;
d->extension = 0;
d->lockHistory = false;
d->isLoading = false;
setRemovable(true);
d->current = d->history.end();
d->layout = new QGridLayout( this );
d->layout->setMargin( 0 );
}
BrowserFrame::~BrowserFrame()
{
if (d->part)
d->part->deleteLater();
delete d;
d = 0;
}
KUrl BrowserFrame::url() const
{
return d->part ? d->part->url() : KUrl();
}
bool BrowserFrame::canGoForward() const
{
return !d->history.isEmpty() && d->current != d->history.end()-1 && d->current != d->history.end();
}
bool BrowserFrame::canGoBack() const
{
return !d->history.isEmpty() && d->current != d->history.begin();
}
void BrowserFrame::slotOpenUrlNotify()
{
// TODO: inform the world that a new url was opened
}
void BrowserFrame::slotSetLocationBarUrl(const QString& /*url*/)
{
// TODO: use this to update URLs for dragging (like tab drag etc.)
}
void BrowserFrame::slotSetIconUrl(const KUrl& /*url*/)
{
}
void BrowserFrame::slotSpeedProgress(int /*bytesPerSecond*/)
{
}
void BrowserFrame::slotPopupMenu(
const QPoint& global,
const KUrl& url,
mode_t mode,
const KParts::OpenUrlArguments& args,
const KParts::BrowserArguments& browserArgs,
KParts::BrowserExtension::PopupFlags flags)
{
const bool showReload = (flags & KParts::BrowserExtension::ShowReload) != 0;
const bool showNavigationItems = (flags & KParts::BrowserExtension::ShowNavigationItems) != 0;
const bool isLink = (flags & KParts::BrowserExtension:: IsLink) != 0;
const bool isSelection = (flags & KParts::BrowserExtension::ShowTextSelectionItems) != 0;
bool isFirst = true;
KMenu popup(d->part->widget());
/*
if (showNavigationItems)
{
popup.addAction(ActionManager::getInstance()->action("browser_back"));
popup.addAction(ActionManager::getInstance()->action("browser_forward"));
isFirst = false;
}
if (showReload)
{
popup.addAction(ActionManager::getInstance()->action("browser_reload"));
isFirst = false;
}
if (isLink)
{
if (!isFirst)
popup.addSeparator();
// open link in new tab
// ext browser
popup.addSeparator();
popup.addAction(d->part->action("savelinkas"));
// save link as
// copy link address
isFirst = false;
}
if (isSelection)
{
if (!isFirst)
popup.addSeparator();
popup.addAction(d->part->action("copy"));
isFirst = false;
}
*/
popup.exec(global);
}
void BrowserFrame::slotOpenUrlRequestDelayed(const KUrl& url, const KParts::OpenUrlArguments& args, const KParts::BrowserArguments& browserArgs)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
emit signalOpenUrlRequest(req);
}
void BrowserFrame::slotCreateNewWindow(const KUrl& url, const KParts::OpenUrlArguments& args, const KParts::BrowserArguments& browserArgs)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
req.setOptions(OpenUrlRequest::NewTab);
emit signalOpenUrlRequest(req);
}
void BrowserFrame::slotCreateNewWindow(const KUrl& url,
const KParts::OpenUrlArguments& args,
const KParts::BrowserArguments& browserArgs,
const KParts::WindowArgs& /*windowArgs*/,
KParts::ReadOnlyPart** part)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
req.setOptions(OpenUrlRequest::NewTab);
emit signalOpenUrlRequest(req);
*part = req.part();
}
bool BrowserFrame::openUrl(const OpenUrlRequest& request)
{
QString serviceType = request.args().mimeType();
if (serviceType.isEmpty())
return false;
d->updateHistoryEntry();
if (d->loadPartForMimetype(serviceType))
{
if (d->part)
{
d->part->setArguments(request.args());
}
bool res = false;
if (request.url().isValid())
res = d->part->openUrl(request.url());
if (res)
{
d->appendHistoryEntry(request.url());
d->updateHistoryEntry();
}
return res;
}
else
{
// TODO: show open|save|cancel dialog
}
return false; // TODO: is this correct?
}
KParts::ReadOnlyPart* BrowserFrame::part() const
{
return d->part;
}
void BrowserFrame::slotHistoryBackAboutToShow()
{
QAction* ba = ActionManager::getInstance()->action("browser_back");
QMenu* popup = static_cast<KToolBarPopupAction*>(ba)->menu();
popup->clear();
if (!canGoBack())
return;
QList<BrowserFramePrivate::HistoryEntry>::Iterator it = d->current-1;
int i = 0;
while( i < 10)
{
if ( it == d->history.begin() )
{
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
return;
}
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
++i;
--it;
}
}
void BrowserFrame::slotHistoryForwardAboutToShow()
{
QAction* fw = ActionManager::getInstance()->action("browser_forward");
QMenu* popup = static_cast<KToolBarPopupAction*>(fw)->menu();
popup->clear();
if (!canGoForward())
return;
QList<BrowserFramePrivate::HistoryEntry>::Iterator it = d->current+1;
int i = 0;
while( i < 10)
{
if ( it == d->history.end()-1 )
{
popup->addAction( new BrowserFramePrivate::HistoryAction(it, popup, d));
return;
}
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
++i;
++it;
}
}
void BrowserFrame::slotHistoryForward()
{
if (canGoForward())
d->restoreHistoryEntry(d->current+1);
}
void BrowserFrame::slotHistoryBack()
{
if (canGoBack())
d->restoreHistoryEntry(d->current-1);
}
void BrowserFrame::slotReload()
{
// TODO
//d->lockHistory = true;
//openUrl(d->url, d->mimetype); // this s
//d->lockHistory = false;
}
void BrowserFrame::slotStop()
{
if (d->part)
d->part->closeUrl();
Frame::slotStop();
}
void BrowserFrame::slotPaletteOrFontChanged()
{
}
bool BrowserFrame::isReloadable() const
{
return false; // TODO
}
bool BrowserFrame::isLoading() const
{
return d->isLoading;
}
} // namespace Akregator
#include "browserframe.moc"
<commit_msg>do not crash when part is null<commit_after>/*
This file is part of Akregator.
Copyright (C) 2005 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "actionmanager.h"
#include "browserframe.h"
#include "browserframe_p.h"
#include "openurlrequest.h"
#include <QAction>
#include <QGridLayout>
#include <QList>
#include <QPoint>
#include <QString>
#include <QWidget>
#include <kaction.h>
#include <kdebug.h>
#include <klibloader.h>
#include <kmenu.h>
#include <kmimetypetrader.h>
#include <ktoolbarpopupaction.h>
#include <kurl.h>
#include <kxmlguiclient.h>
#include <kparts/browserextension.h>
#include <kparts/part.h>
namespace Akregator {
BrowserFrame::BrowserFrame(QWidget* parent) : Frame(parent)
{
d = new BrowserFramePrivate(this);
d->part = 0;
d->extension = 0;
d->lockHistory = false;
d->isLoading = false;
setRemovable(true);
d->current = d->history.end();
d->layout = new QGridLayout( this );
d->layout->setMargin( 0 );
}
BrowserFrame::~BrowserFrame()
{
if (d->part)
d->part->deleteLater();
delete d;
d = 0;
}
KUrl BrowserFrame::url() const
{
return d->part ? d->part->url() : KUrl();
}
bool BrowserFrame::canGoForward() const
{
return !d->history.isEmpty() && d->current != d->history.end()-1 && d->current != d->history.end();
}
bool BrowserFrame::canGoBack() const
{
return !d->history.isEmpty() && d->current != d->history.begin();
}
void BrowserFrame::slotOpenUrlNotify()
{
// TODO: inform the world that a new url was opened
}
void BrowserFrame::slotSetLocationBarUrl(const QString& /*url*/)
{
// TODO: use this to update URLs for dragging (like tab drag etc.)
}
void BrowserFrame::slotSetIconUrl(const KUrl& /*url*/)
{
}
void BrowserFrame::slotSpeedProgress(int /*bytesPerSecond*/)
{
}
void BrowserFrame::slotPopupMenu(
const QPoint& global,
const KUrl& url,
mode_t mode,
const KParts::OpenUrlArguments& args,
const KParts::BrowserArguments& browserArgs,
KParts::BrowserExtension::PopupFlags flags)
{
const bool showReload = (flags & KParts::BrowserExtension::ShowReload) != 0;
const bool showNavigationItems = (flags & KParts::BrowserExtension::ShowNavigationItems) != 0;
const bool isLink = (flags & KParts::BrowserExtension:: IsLink) != 0;
const bool isSelection = (flags & KParts::BrowserExtension::ShowTextSelectionItems) != 0;
bool isFirst = true;
KMenu popup(d->part->widget());
/*
if (showNavigationItems)
{
popup.addAction(ActionManager::getInstance()->action("browser_back"));
popup.addAction(ActionManager::getInstance()->action("browser_forward"));
isFirst = false;
}
if (showReload)
{
popup.addAction(ActionManager::getInstance()->action("browser_reload"));
isFirst = false;
}
if (isLink)
{
if (!isFirst)
popup.addSeparator();
// open link in new tab
// ext browser
popup.addSeparator();
popup.addAction(d->part->action("savelinkas"));
// save link as
// copy link address
isFirst = false;
}
if (isSelection)
{
if (!isFirst)
popup.addSeparator();
popup.addAction(d->part->action("copy"));
isFirst = false;
}
*/
popup.exec(global);
}
void BrowserFrame::slotOpenUrlRequestDelayed(const KUrl& url, const KParts::OpenUrlArguments& args, const KParts::BrowserArguments& browserArgs)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
emit signalOpenUrlRequest(req);
}
void BrowserFrame::slotCreateNewWindow(const KUrl& url, const KParts::OpenUrlArguments& args, const KParts::BrowserArguments& browserArgs)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
req.setOptions(OpenUrlRequest::NewTab);
emit signalOpenUrlRequest(req);
}
void BrowserFrame::slotCreateNewWindow(const KUrl& url,
const KParts::OpenUrlArguments& args,
const KParts::BrowserArguments& browserArgs,
const KParts::WindowArgs& /*windowArgs*/,
KParts::ReadOnlyPart** part)
{
OpenUrlRequest req;
req.setFrameId(id());
req.setUrl(url);
req.setArgs(args);
req.setBrowserArgs(browserArgs);
req.setOptions(OpenUrlRequest::NewTab);
emit signalOpenUrlRequest(req);
if ( part )
*part = req.part();
}
bool BrowserFrame::openUrl(const OpenUrlRequest& request)
{
QString serviceType = request.args().mimeType();
if (serviceType.isEmpty())
return false;
d->updateHistoryEntry();
if (d->loadPartForMimetype(serviceType))
{
if (d->part)
{
d->part->setArguments(request.args());
}
bool res = false;
if (request.url().isValid())
res = d->part->openUrl(request.url());
if (res)
{
d->appendHistoryEntry(request.url());
d->updateHistoryEntry();
}
return res;
}
else
{
// TODO: show open|save|cancel dialog
}
return false; // TODO: is this correct?
}
KParts::ReadOnlyPart* BrowserFrame::part() const
{
return d->part;
}
void BrowserFrame::slotHistoryBackAboutToShow()
{
QAction* ba = ActionManager::getInstance()->action("browser_back");
QMenu* popup = static_cast<KToolBarPopupAction*>(ba)->menu();
popup->clear();
if (!canGoBack())
return;
QList<BrowserFramePrivate::HistoryEntry>::Iterator it = d->current-1;
int i = 0;
while( i < 10)
{
if ( it == d->history.begin() )
{
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
return;
}
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
++i;
--it;
}
}
void BrowserFrame::slotHistoryForwardAboutToShow()
{
QAction* fw = ActionManager::getInstance()->action("browser_forward");
QMenu* popup = static_cast<KToolBarPopupAction*>(fw)->menu();
popup->clear();
if (!canGoForward())
return;
QList<BrowserFramePrivate::HistoryEntry>::Iterator it = d->current+1;
int i = 0;
while( i < 10)
{
if ( it == d->history.end()-1 )
{
popup->addAction( new BrowserFramePrivate::HistoryAction(it, popup, d));
return;
}
popup->addAction(new BrowserFramePrivate::HistoryAction(it, popup, d));
++i;
++it;
}
}
void BrowserFrame::slotHistoryForward()
{
if (canGoForward())
d->restoreHistoryEntry(d->current+1);
}
void BrowserFrame::slotHistoryBack()
{
if (canGoBack())
d->restoreHistoryEntry(d->current-1);
}
void BrowserFrame::slotReload()
{
// TODO
//d->lockHistory = true;
//openUrl(d->url, d->mimetype); // this s
//d->lockHistory = false;
}
void BrowserFrame::slotStop()
{
if (d->part)
d->part->closeUrl();
Frame::slotStop();
}
void BrowserFrame::slotPaletteOrFontChanged()
{
}
bool BrowserFrame::isReloadable() const
{
return false; // TODO
}
bool BrowserFrame::isLoading() const
{
return d->isLoading;
}
} // namespace Akregator
#include "browserframe.moc"
<|endoftext|>
|
<commit_before>// Base class for property controlled subsystems
//
// Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#include "PropertyBasedMgr.hxx"
#include <boost/foreach.hpp>
#include <stdexcept>
#include <string>
namespace simgear
{
//----------------------------------------------------------------------------
void PropertyBasedMgr::init()
{
_props->addChangeListener(this);
_props->fireCreatedRecursive();
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::shutdown()
{
_props->removeChangeListener(this);
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::update(double delta_time_sec)
{
for( size_t i = 0; i < _elements.size(); ++i )
if( _elements[i] )
_elements[i]->update(delta_time_sec);
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr
PropertyBasedMgr::createElement(const std::string& name)
{
SGPropertyNode* node = _props->addChild(_name_elements, 0, false);
if( !name.empty() )
node->setStringValue("name", name);
return getElement( node->getIndex() );
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr PropertyBasedMgr::getElement(size_t index) const
{
if( index >= _elements.size() )
return PropertyBasedElementPtr();
return _elements[index];
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr
PropertyBasedMgr::getElement(const std::string& name) const
{
if( name.empty() )
return PropertyBasedElementPtr();
BOOST_FOREACH(PropertyBasedElementPtr el, _elements)
if( el->getProps()->getStringValue("name") == name )
return el;
return PropertyBasedElementPtr();
}
//----------------------------------------------------------------------------
const SGPropertyNode* PropertyBasedMgr::getPropertyRoot() const
{
return _props;
}
//----------------------------------------------------------------------------
PropertyBasedMgr::PropertyBasedMgr( SGPropertyNode_ptr props,
const std::string& name_elements,
ElementFactory element_factory ):
_props( props ),
_name_elements( name_elements ),
_element_factory( element_factory )
{
}
//----------------------------------------------------------------------------
PropertyBasedMgr::~PropertyBasedMgr()
{
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::childAdded( SGPropertyNode * parent,
SGPropertyNode * child )
{
if( parent != _props || child->getNameString() != _name_elements )
return;
size_t index = child->getIndex();
if( index >= _elements.size() )
{
if( index > _elements.size() )
SG_LOG
(
SG_GENERAL,
SG_WARN,
"Skipping unused " << _name_elements << " slot(s)!"
);
_elements.resize(index + 1);
}
else if( _elements[index] )
{
SG_LOG
(
SG_GENERAL,
SG_WARN,
_name_elements << "[" << index << "] already exists!"
);
// Give anything holding a reference to this element to release it
_elements[index]->onDestroy();
}
PropertyBasedElementPtr el = _element_factory(child);
el->setSelf( el );
_elements[index] = el;
elementCreated( el );
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::childRemoved( SGPropertyNode * parent,
SGPropertyNode * child )
{
if( parent != _props )
return child->fireChildrenRemovedRecursive();
else if( child->getNameString() != _name_elements )
return;
size_t index = child->getIndex();
if( index >= _elements.size() )
SG_LOG
(
SG_GENERAL,
SG_WARN,
"can't removed unknown " << _name_elements << "[" << index << "]!"
);
else
{
// remove the element...
_elements[index]->onDestroy();
_elements[index].reset();
}
}
} // namespace simgear
<commit_msg>Canvas: clear elements in shutdown()<commit_after>// Base class for property controlled subsystems
//
// Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#include "PropertyBasedMgr.hxx"
#include <boost/foreach.hpp>
#include <stdexcept>
#include <string>
namespace simgear
{
//----------------------------------------------------------------------------
void PropertyBasedMgr::init()
{
_props->addChangeListener(this);
_props->fireCreatedRecursive();
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::shutdown()
{
_props->removeChangeListener(this);
_elements.clear();
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::update(double delta_time_sec)
{
for( size_t i = 0; i < _elements.size(); ++i )
if( _elements[i] )
_elements[i]->update(delta_time_sec);
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr
PropertyBasedMgr::createElement(const std::string& name)
{
SGPropertyNode* node = _props->addChild(_name_elements, 0, false);
if( !name.empty() )
node->setStringValue("name", name);
return getElement( node->getIndex() );
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr PropertyBasedMgr::getElement(size_t index) const
{
if( index >= _elements.size() )
return PropertyBasedElementPtr();
return _elements[index];
}
//----------------------------------------------------------------------------
PropertyBasedElementPtr
PropertyBasedMgr::getElement(const std::string& name) const
{
if( name.empty() )
return PropertyBasedElementPtr();
BOOST_FOREACH(PropertyBasedElementPtr el, _elements)
if( el->getProps()->getStringValue("name") == name )
return el;
return PropertyBasedElementPtr();
}
//----------------------------------------------------------------------------
const SGPropertyNode* PropertyBasedMgr::getPropertyRoot() const
{
return _props;
}
//----------------------------------------------------------------------------
PropertyBasedMgr::PropertyBasedMgr( SGPropertyNode_ptr props,
const std::string& name_elements,
ElementFactory element_factory ):
_props( props ),
_name_elements( name_elements ),
_element_factory( element_factory )
{
}
//----------------------------------------------------------------------------
PropertyBasedMgr::~PropertyBasedMgr()
{
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::childAdded( SGPropertyNode * parent,
SGPropertyNode * child )
{
if( parent != _props || child->getNameString() != _name_elements )
return;
size_t index = child->getIndex();
if( index >= _elements.size() )
{
if( index > _elements.size() )
SG_LOG
(
SG_GENERAL,
SG_WARN,
"Skipping unused " << _name_elements << " slot(s)!"
);
_elements.resize(index + 1);
}
else if( _elements[index] )
{
SG_LOG
(
SG_GENERAL,
SG_WARN,
_name_elements << "[" << index << "] already exists!"
);
// Give anything holding a reference to this element to release it
_elements[index]->onDestroy();
}
PropertyBasedElementPtr el = _element_factory(child);
el->setSelf( el );
_elements[index] = el;
elementCreated( el );
}
//----------------------------------------------------------------------------
void PropertyBasedMgr::childRemoved( SGPropertyNode * parent,
SGPropertyNode * child )
{
if( parent != _props )
return child->fireChildrenRemovedRecursive();
else if( child->getNameString() != _name_elements )
return;
size_t index = child->getIndex();
if( index >= _elements.size() )
SG_LOG
(
SG_GENERAL,
SG_WARN,
"can't removed unknown " << _name_elements << "[" << index << "]!"
);
else
{
// remove the element...
_elements[index]->onDestroy();
_elements[index].reset();
}
}
} // namespace simgear
<|endoftext|>
|
<commit_before>
#include <boost/asio.hpp>
#include "vtrc-protocol-layer.h"
#include "vtrc-connection-iface.h"
#include "vtrc-common/vtrc-monotonic-timer.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hasher-iface.h"
#include "vtrc-common/vtrc-hasher-impls.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
namespace vtrc { namespace server {
namespace {
static const size_t maximum_message_length = 1024 * 1024;
}
namespace data_queue = common::data_queue;
struct protocol_layer::protocol_layer_impl {
connection_iface *connection_;
protocol_layer *parent_;
boost::shared_ptr<common::hasher_iface> hasher_;
boost::shared_ptr<common::transformer_iface> transformer_;
common::data_queue::queue_base_sptr queue_;
protocol_layer_impl( connection_iface *c )
:connection_(c)
,hasher_(common::hasher::fake::create( ))
,transformer_(common::transformers::none::create( ))
,queue_(data_queue::varint::create_parser(maximum_message_length))
{
}
void init( )
{
vtrc_auth::init_protocol hello_mess;
hello_mess.set_hello_message( "Tervetuloa!" );
hello_mess.add_hash_supported( vtrc_auth::HASH_NONE );
hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR );
std::string data(hello_mess.SerializeAsString( ));
std::string result(queue_->pack_size( data.size( ) ));
result.append( hasher_->get_data_hash( data.c_str( ),
data.size( ) ) );
result.append( data.begin( ), data.end( ) );
transformer_->transform_data( data.empty( ) ? NULL : &data[0],
data.size( ) );
connection_->write( data.c_str( ), data.size( ) );
}
void process_data( const char *data, size_t length )
{
if( length > 0 ) {
std::string next_data(data, data + length);
transformer_->revert_data( &next_data[0],
next_data.size( ) );
queue_->append( &next_data[0], next_data.size( ));
queue_->process( );
}
}
};
protocol_layer::protocol_layer( connection_iface *connection )
:impl_(new protocol_layer_impl(connection))
{
impl_->parent_ = this;
}
protocol_layer::~protocol_layer( )
{
delete impl_;
}
void protocol_layer::init( )
{
impl_->init( );
}
void protocol_layer::process_data( const char *data, size_t length )
{
impl_->process_data( data, length );
}
}}
<commit_msg>protocol<commit_after>
#include <boost/asio.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include "vtrc-protocol-layer.h"
#include "vtrc-connection-iface.h"
#include "vtrc-common/vtrc-monotonic-timer.h"
#include "vtrc-common/vtrc-data-queue.h"
#include "vtrc-common/vtrc-hasher-iface.h"
#include "vtrc-common/vtrc-hasher-impls.h"
#include "vtrc-common/vtrc-transformer-iface.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
namespace vtrc { namespace server {
namespace {
static const size_t maximum_message_length = 1024 * 1024;
enum init_stage_enum {
stage_begin = 1
,stage_client_select = 2
,stage_client_ready = 3
};
}
namespace data_queue = common::data_queue;
struct protocol_layer::protocol_layer_impl {
typedef protocol_layer_impl this_type;
connection_iface *connection_;
protocol_layer *parent_;
boost::shared_ptr<common::hasher_iface> hasher_;
boost::shared_ptr<common::transformer_iface> transformer_;
common::data_queue::queue_base_sptr queue_;
init_stage_enum init_stages_;
typedef boost::function<void (void)> stage_function_type;
stage_function_type stage_function_;
protocol_layer_impl( connection_iface *c )
:connection_(c)
,hasher_(common::hasher::fake::create( ))
,transformer_(common::transformers::none::create( ))
,queue_(data_queue::varint::create_parser(maximum_message_length))
,init_stages_(stage_begin)
{
stage_function_ =
boost::bind( &this_type::on_client_selection, this );
}
void on_timer( boost::system::error_code const &error )
{
}
void on_client_selection( )
{
}
void on_ready( )
{
}
void init( )
{
vtrc_auth::init_protocol hello_mess;
hello_mess.set_hello_message( "Tervetuloa!" );
hello_mess.add_hash_supported( vtrc_auth::HASH_NONE );
hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR );
std::string data(hello_mess.SerializeAsString( ));
std::string result(queue_->pack_size( data.size( ) ));
result.append( hasher_->get_data_hash( data.c_str( ),
data.size( ) ) );
result.append( data.begin( ), data.end( ) );
transformer_->transform_data( data.empty( ) ? NULL : &data[0],
data.size( ) );
connection_->write( data.c_str( ), data.size( ) );
}
void process_data( const char *data, size_t length )
{
if( length > 0 ) {
std::string next_data(data, data + length);
transformer_->revert_data( &next_data[0],
next_data.size( ) );
queue_->append( &next_data[0], next_data.size( ));
queue_->process( );
stage_function_( );
}
}
};
protocol_layer::protocol_layer( connection_iface *connection )
:impl_(new protocol_layer_impl(connection))
{
impl_->parent_ = this;
}
protocol_layer::~protocol_layer( )
{
delete impl_;
}
void protocol_layer::init( )
{
impl_->init( );
}
void protocol_layer::process_data( const char *data, size_t length )
{
impl_->process_data( data, length );
}
}}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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 "texture_manager.hpp"
#include "device.hpp"
#include "stb_image.h"
#include "memory_mapped_texture.hpp"
#include "texture_files.hpp"
#ifdef GRANITE_VULKAN_MT
#include "thread_group.hpp"
#include "thread_id.hpp"
#endif
using namespace std;
namespace Vulkan
{
bool Texture::init_texture()
{
if (!path.empty())
return init();
else
return true;
}
Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_)
: VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_)
{
}
Texture::Texture(Device *device_)
: device(device_), format(VK_FORMAT_UNDEFINED)
{
}
void Texture::set_path(const std::string &path_)
{
path = path_;
}
void Texture::update(std::unique_ptr<Granite::File> file)
{
auto *f = file.release();
auto work = [f, this]() {
#if defined(GRANITE_VULKAN_MT) && defined(VULKAN_DEBUG)
LOGI("Loading texture in thread index: %u\n", get_current_thread_index());
#endif
unique_ptr<Granite::File> updated_file{f};
auto size = updated_file->get_size();
void *mapped = updated_file->map();
if (size && mapped)
{
if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size))
update_gtx(move(updated_file), mapped);
else
update_other(mapped, size);
device->get_texture_manager().notify_updated_texture(path, *this);
}
else
{
LOGE("Failed to map texture file ...\n");
update_checkerboard();
}
};
#ifdef GRANITE_VULKAN_MT
auto &workers = *Granite::Global::thread_group();
// Workaround, cannot copy the lambda because of owning a unique_ptr.
auto task = workers.create_task(move(work));
task->flush();
#else
work();
#endif
}
void Texture::update_checkerboard()
{
LOGE("Failed to load texture: %s, falling back to a checkerboard.\n",
path.c_str());
ImageInitialData initial = {};
static const uint32_t checkerboard[] = {
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
};
initial.data = checkerboard;
auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false);
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
auto image = device->create_image(info, &initial);
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file)
{
if (mapped_file.empty())
{
update_checkerboard();
return;
}
auto &layout = mapped_file.get_layout();
ImageCreateInfo info = ImageCreateInfo::immutable_image(layout);
info.swizzle = swizzle;
info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ?
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0;
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
mapped_file.remap_swizzle(info.swizzle);
if (info.levels == 1 &&
(mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT))
{
info.levels = 0;
info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT;
}
if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
{
LOGE("Format (%u) is not supported!\n", unsigned(info.format));
return;
}
auto staging = device->create_image_staging_buffer(layout);
auto image = device->create_image_from_staging_buffer(info, &staging);
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped)
{
Granite::SceneFormats::MemoryMappedTexture mapped_file;
if (!mapped_file.map_read(move(file), mapped))
{
LOGE("Failed to read texture.\n");
return;
}
update_gtx(mapped_file);
}
void Texture::update_other(const void *data, size_t size)
{
auto tex = Granite::load_texture_from_memory(data, size,
(format == VK_FORMAT_R8G8B8A8_SRGB ||
format == VK_FORMAT_UNDEFINED ||
format == VK_FORMAT_B8G8R8A8_SRGB ||
format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ?
Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear);
update_gtx(tex);
}
void Texture::load()
{
if (!handle.get_nowait())
init();
}
void Texture::unload()
{
deinit();
handle.reset();
}
void Texture::replace_image(ImageHandle handle_)
{
auto old = this->handle.write_object(move(handle_));
if (old)
device->keep_handle_alive(move(old));
if (enable_notification)
device->get_texture_manager().notify_updated_texture(path, *this);
}
Image *Texture::get_image()
{
auto ret = handle.get();
VK_ASSERT(ret);
return ret;
}
void Texture::set_enable_notification(bool enable)
{
enable_notification = enable;
}
TextureManager::TextureManager(Device *device_)
: device(device_)
{
}
Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping)
{
Util::Hasher hasher;
hasher.string(path);
auto deferred_hash = hasher.get();
hasher.u32(format);
hasher.u32(mapping.r);
hasher.u32(mapping.g);
hasher.u32(mapping.b);
hasher.u32(mapping.a);
auto hash = hasher.get();
auto *ret = deferred_textures.find(deferred_hash);
if (ret)
return ret;
ret = textures.find(hash);
if (ret)
return ret;
ret = textures.emplace_yield(hash, device, path, format, mapping);
if (!ret->init_texture())
ret->update_checkerboard();
return ret;
}
void TextureManager::register_texture_update_notification(const std::string &modified_path,
std::function<void(Texture &)> func)
{
Util::Hasher hasher;
hasher.string(modified_path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (ret)
func(*ret);
notifications[modified_path].push_back(move(func));
}
void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture)
{
auto itr = notifications.find(path);
if (itr != end(notifications))
for (auto &f : itr->second)
if (f)
f(texture);
}
Texture *TextureManager::register_deferred_texture(const std::string &path)
{
Util::Hasher hasher;
hasher.string(path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (!ret)
{
auto *texture = deferred_textures.allocate(device);
texture->set_path(path);
texture->set_enable_notification(false);
ret = deferred_textures.insert_yield(hash, texture);
}
return ret;
}
}
<commit_msg>Add fallback decode to texture manager.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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 "texture_manager.hpp"
#include "device.hpp"
#include "stb_image.h"
#include "memory_mapped_texture.hpp"
#include "texture_files.hpp"
#include "texture_decoder.hpp"
#ifdef GRANITE_VULKAN_MT
#include "thread_group.hpp"
#include "thread_id.hpp"
#endif
using namespace std;
namespace Vulkan
{
bool Texture::init_texture()
{
if (!path.empty())
return init();
else
return true;
}
Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_)
: VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_)
{
}
Texture::Texture(Device *device_)
: device(device_), format(VK_FORMAT_UNDEFINED)
{
}
void Texture::set_path(const std::string &path_)
{
path = path_;
}
void Texture::update(std::unique_ptr<Granite::File> file)
{
auto *f = file.release();
auto work = [f, this]() {
#if defined(GRANITE_VULKAN_MT) && defined(VULKAN_DEBUG)
LOGI("Loading texture in thread index: %u\n", get_current_thread_index());
#endif
unique_ptr<Granite::File> updated_file{f};
auto size = updated_file->get_size();
void *mapped = updated_file->map();
if (size && mapped)
{
if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size))
update_gtx(move(updated_file), mapped);
else
update_other(mapped, size);
device->get_texture_manager().notify_updated_texture(path, *this);
}
else
{
LOGE("Failed to map texture file ...\n");
update_checkerboard();
}
};
#ifdef GRANITE_VULKAN_MT
auto &workers = *Granite::Global::thread_group();
// Workaround, cannot copy the lambda because of owning a unique_ptr.
auto task = workers.create_task(move(work));
task->flush();
#else
work();
#endif
}
void Texture::update_checkerboard()
{
LOGE("Failed to load texture: %s, falling back to a checkerboard.\n",
path.c_str());
ImageInitialData initial = {};
static const uint32_t checkerboard[] = {
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
};
initial.data = checkerboard;
auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false);
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
auto image = device->create_image(info, &initial);
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file)
{
if (mapped_file.empty())
{
update_checkerboard();
return;
}
auto &layout = mapped_file.get_layout();
Vulkan::ImageHandle image;
if (!device->image_format_is_supported(layout.get_format(), VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) &&
format_compression_type(layout.get_format()) != FormatCompressionType::Uncompressed)
{
LOGI("Compressed format #%u is not supported, falling back to compute decode of compressed image.\n",
unsigned(layout.get_format()));
auto cmd = device->request_command_buffer(CommandBuffer::Type::AsyncCompute);
image = Granite::decode_compressed_image(*cmd, layout, swizzle);
Semaphore sem;
device->submit(cmd, nullptr, 1, &sem);
device->add_wait_semaphore(CommandBuffer::Type::Generic, sem, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, true);
}
else
{
ImageCreateInfo info = ImageCreateInfo::immutable_image(layout);
info.swizzle = swizzle;
info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ?
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT :
0;
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
mapped_file.remap_swizzle(info.swizzle);
if (info.levels == 1 &&
(mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT))
{
info.levels = 0;
info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT;
}
if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
{
LOGE("Format (%u) is not supported!\n", unsigned(info.format));
return;
}
auto staging = device->create_image_staging_buffer(layout);
image = device->create_image_from_staging_buffer(info, &staging);
}
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped)
{
Granite::SceneFormats::MemoryMappedTexture mapped_file;
if (!mapped_file.map_read(move(file), mapped))
{
LOGE("Failed to read texture.\n");
return;
}
update_gtx(mapped_file);
}
void Texture::update_other(const void *data, size_t size)
{
auto tex = Granite::load_texture_from_memory(data, size,
(format == VK_FORMAT_R8G8B8A8_SRGB ||
format == VK_FORMAT_UNDEFINED ||
format == VK_FORMAT_B8G8R8A8_SRGB ||
format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ?
Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear);
update_gtx(tex);
}
void Texture::load()
{
if (!handle.get_nowait())
init();
}
void Texture::unload()
{
deinit();
handle.reset();
}
void Texture::replace_image(ImageHandle handle_)
{
auto old = this->handle.write_object(move(handle_));
if (old)
device->keep_handle_alive(move(old));
if (enable_notification)
device->get_texture_manager().notify_updated_texture(path, *this);
}
Image *Texture::get_image()
{
auto ret = handle.get();
VK_ASSERT(ret);
return ret;
}
void Texture::set_enable_notification(bool enable)
{
enable_notification = enable;
}
TextureManager::TextureManager(Device *device_)
: device(device_)
{
}
Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping)
{
Util::Hasher hasher;
hasher.string(path);
auto deferred_hash = hasher.get();
hasher.u32(format);
hasher.u32(mapping.r);
hasher.u32(mapping.g);
hasher.u32(mapping.b);
hasher.u32(mapping.a);
auto hash = hasher.get();
auto *ret = deferred_textures.find(deferred_hash);
if (ret)
return ret;
ret = textures.find(hash);
if (ret)
return ret;
ret = textures.emplace_yield(hash, device, path, format, mapping);
if (!ret->init_texture())
ret->update_checkerboard();
return ret;
}
void TextureManager::register_texture_update_notification(const std::string &modified_path,
std::function<void(Texture &)> func)
{
Util::Hasher hasher;
hasher.string(modified_path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (ret)
func(*ret);
notifications[modified_path].push_back(move(func));
}
void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture)
{
auto itr = notifications.find(path);
if (itr != end(notifications))
for (auto &f : itr->second)
if (f)
f(texture);
}
Texture *TextureManager::register_deferred_texture(const std::string &path)
{
Util::Hasher hasher;
hasher.string(path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (!ret)
{
auto *texture = deferred_textures.allocate(device);
texture->set_path(path);
texture->set_enable_notification(false);
ret = deferred_textures.insert_yield(hash, texture);
}
return ret;
}
}
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <thread>
#include <deque>
#include <exception>
#include <mutex>
// #include <condition_variable>
// #include <mutex>
void busywait(int lmax) {
for(int i=0; i<lmax; i++) {
for(int j=0; j<lmax; j++) {
for(int k=0; k<lmax; k++) {
}
}
}
}
bool WAITFOREXIT = true;
bool NOWAITFOREXIT = false;
class StopIteration: public std::exception {
virtual const char* what() const throw() {
return "StopIteration";
}
};
template <class T>
class Queue {
private:
std::deque<T> m_queue;
std::mutex m_mutex;
public:
void put(T item) {
m_queue.push_back(item);
std::cout << "APPEND " << item << std::endl;
}
T get() { // std::cout << "Really ought to check the queue length first" << std::endl;
T result;
m_mutex.lock();
if (m_queue.empty()) {
m_mutex.unlock();
throw StopIteration();
}
result = m_queue.front();
m_queue.pop_front();
m_mutex.unlock();
return result;
}
};
class Actor { // I know this is bad practice. This is a sketch remember?
public:
std::thread m_Thread;
bool m_let_me_finish;
protected:
virtual void main() {
for(int i=0; i<20; i++) {
busywait(350);
std::cout << " Actor::main " << std::this_thread::get_id() << " Executing:" << i << std::endl;
}
}
public:
Actor(): m_Thread(), m_let_me_finish(false) { };
Actor(bool X): m_Thread(), m_let_me_finish(X) { };
void run() {
m_Thread = std::thread(&Actor::main, this);
if (!m_let_me_finish) {
std::cout << "m_let_me_finish:" << m_let_me_finish << std::endl;
m_Thread.detach();
}
}
~Actor() {
if (m_let_me_finish) {
m_Thread.join(); // Probably want to do something different?
}
}
};
class Dramatic : public Actor { // Example Actor
public:
Dramatic(): Actor() { }; // Always initialise cleanly...
Dramatic(bool X): Actor(X) { }; // Always initialise cleanly...
void main() {
for(int i=0; i<20; i++) {
busywait(95);
std::cout << " I am DRAMATIC " << std::this_thread::get_id() << " Executing:" << i << std::endl;
}
}
};
void actortest() {
Actor simple1;
Actor simple2(NOWAITFOREXIT);
// Dramatic Sherlock(WAITFOREXIT);
// Dramatic Sherlock(NOWAITFOREXIT);
Dramatic Sherlock;
simple1.run();
simple2.run();
Sherlock.run();
for(int i=0; i<10; i++) {
busywait(100);
std::cout << " Display From MainThread "<< std::this_thread::get_id() <<" ?:" << i << std::endl;
}
}
int main(int argc, char *argv[]) {
Queue<int> q;
std::cout << "Hello" << std::endl;
std::cout << "World" << std::endl;
for(int i=0; i<10; i++) {
q.put(i);
}
while(true) {
try {
std::cout << "POP: " << q.get() << std::endl;
} catch (StopIteration& e) {
break;
}
}
// actortest();
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}
<commit_msg>Improve queue for threadsafety, usage styles, create producer/consumer example<commit_after>
#include <iostream>
#include <thread>
#include <deque>
#include <exception>
#include <mutex>
#include <chrono>
// #include <condition_variable>
bool WAITFOREXIT = true;
bool NOWAITFOREXIT = false;
void busywait(int lmax) {
for(int i=0; i<lmax; i++) {
for(int j=0; j<lmax; j++) {
for(int k=0; k<lmax; k++) {
}
}
}
}
class EmptyQueue: public std::exception {
virtual const char* what() const throw() {
return "EmptyQueue";
}
};
class EmptyQueueTimeout: public std::exception {
virtual const char* what() const throw() {
return "EmptyQueueTimeout";
}
};
using namespace std::chrono_literals;
template <class T>
class Queue {
std::deque<T> m_queue;
std::mutex m_mutex;
public:
void put(T item) {
m_mutex.lock();
m_queue.push_back(item);
m_mutex.unlock();
}
T get_nowait() {
T result;
m_mutex.lock();
if (m_queue.empty()) {
m_mutex.unlock();
throw EmptyQueue();
}
result = m_queue.front();
m_queue.pop_front();
m_mutex.unlock();
return result;
}
T get() {
return get_timeout(0);
}
T get_timeout(int timeout_ms) {
int so_far_ms = 0;
T result;
while (true) {
m_mutex.lock();
if (!m_queue.empty()) {
break;
}
m_mutex.unlock();
std::this_thread::sleep_for(2ms);
so_far_ms += 2;
if (timeout_ms and so_far_ms > timeout_ms) {
throw EmptyQueueTimeout();
}
}
result = m_queue.front();
m_queue.pop_front();
m_mutex.unlock();
return result;
}
};
class Actor { // I know this is bad practice. This is a sketch remember?
public:
std::thread m_Thread;
bool m_let_me_finish;
protected:
virtual void main() {
for(int i=0; i<20; i++) {
busywait(350);
std::cout << " Actor::main " << std::this_thread::get_id() << " Executing:" << i << std::endl;
}
}
public:
Actor(): m_Thread(), m_let_me_finish(false) { };
Actor(bool X): m_Thread(), m_let_me_finish(X) { };
void run() {
m_Thread = std::thread(&Actor::main, this);
if (!m_let_me_finish) {
m_Thread.detach();
}
}
~Actor() {
if (m_let_me_finish) {
m_Thread.join(); // Appropriate?
}
}
};
class Producer : public Actor {
public:
std::string m_tag;
Queue<int> * q;
Producer(std::string name): Actor(), m_tag(name) {}
Producer(std::string name, Queue<int> * Q): Actor(), m_tag(name), q(Q) {}
void set_outbox(Queue<int> * Q) {
q = Q;
}
void main() {
for(int i=0; i<20; i++) {
busywait(95);
q->put(i);
}
q->put(-1);
}
};
class Consumer : public Actor {
public:
std::string m_tag;
Queue<int> * q;
Consumer(std::string name): Actor(), m_tag(name) {}
Consumer(std::string name, Queue<int> * Q): Actor(), m_tag(name), q(Q) {}
void set_inbox(Queue<int> * Q) {
q = Q;
}
void main() {
while(true) {
int result;
busywait(105);
try {
result = q->get_timeout(10);
} catch (EmptyQueueTimeout& e) {
break;
}
std::cout << "CONSUMER " << m_tag << " " << result << std::endl;
}
std::cout << "CONSUMER " << m_tag << " exitting" << std::endl;
}
};
int main(int argc, char *argv[]) {
Queue<int> q;
Producer P1("P1", &q);
Producer P2("P2");
Consumer C1("C1", &q);
P2.set_outbox(&q);
P1.run();
P2.run();
C1.run();
for(int i=0; i<10; i++) {
busywait(200);
}
std::cout<<"Exit of Main function"<<std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_headers.hxx"
#include "direct.hxx"
#include "RootPool.hxx"
#include "pool.hxx"
#include "istream/istream.hxx"
#include "istream/istream_catch.hxx"
#include "fb_pool.hxx"
#include "system/fd_util.h"
#include "event/Event.hxx"
#include <stdio.h>
#include <stdlib.h>
struct Instance final : HttpServerConnectionHandler {
/* virtual methods from class HttpServerConnectionHandler */
void HandleHttpRequest(struct http_server_request &request,
struct async_operation_ref &async_ref) override;
void LogHttpRequest(struct http_server_request &,
http_status_t, off_t,
uint64_t, uint64_t) override {}
void HttpConnectionError(GError *error) override;
void HttpConnectionClosed() override;
};
static GError *
catch_callback(GError *error, gcc_unused void *ctx)
{
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return nullptr;
}
void
Instance::HandleHttpRequest(struct http_server_request &request,
gcc_unused struct async_operation_ref &async_ref)
{
http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(),
istream_catch_new(request.pool, *request.body,
catch_callback, nullptr));
http_server_connection_close(request.connection);
}
void
Instance::HttpConnectionError(GError *error)
{
g_printerr("%s\n", error->message);
g_error_free(error);
}
void
Instance::HttpConnectionClosed()
{
}
static void
test_catch(EventLoop &event_loop, struct pool *pool)
{
pool = pool_new_libc(pool, "catch");
int fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
perror("socketpair()");
abort();
}
static constexpr char request[] =
"POST / HTTP/1.1\r\nContent-Length: 1024\r\n\r\nfoo";
send(fds[1], request, sizeof(request) - 1, 0);
Instance instance;
HttpServerConnection *connection;
http_server_connection_new(pool, fds[0], FdType::FD_SOCKET,
nullptr, nullptr,
nullptr, nullptr,
true, instance,
&connection);
pool_unref(pool);
event_loop.Dispatch();
close(fds[1]);
}
int main(int argc, char **argv) {
(void)argc;
(void)argv;
direct_global_init();
EventLoop event_loop;
fb_pool_init(false);
test_catch(event_loop, RootPool());
fb_pool_deinit();
}
<commit_msg>test/t_http_server: move pool to struct Instance<commit_after>#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_headers.hxx"
#include "direct.hxx"
#include "RootPool.hxx"
#include "pool.hxx"
#include "istream/istream.hxx"
#include "istream/istream_catch.hxx"
#include "fb_pool.hxx"
#include "system/fd_util.h"
#include "event/Event.hxx"
#include <stdio.h>
#include <stdlib.h>
struct Instance final : HttpServerConnectionHandler {
struct pool *pool;
explicit Instance(struct pool &_pool)
:pool(pool_new_libc(&_pool, "catch")) {}
/* virtual methods from class HttpServerConnectionHandler */
void HandleHttpRequest(struct http_server_request &request,
struct async_operation_ref &async_ref) override;
void LogHttpRequest(struct http_server_request &,
http_status_t, off_t,
uint64_t, uint64_t) override {}
void HttpConnectionError(GError *error) override;
void HttpConnectionClosed() override;
};
static GError *
catch_callback(GError *error, gcc_unused void *ctx)
{
fprintf(stderr, "%s\n", error->message);
g_error_free(error);
return nullptr;
}
void
Instance::HandleHttpRequest(struct http_server_request &request,
gcc_unused struct async_operation_ref &async_ref)
{
http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(),
istream_catch_new(request.pool, *request.body,
catch_callback, nullptr));
http_server_connection_close(request.connection);
}
void
Instance::HttpConnectionError(GError *error)
{
g_printerr("%s\n", error->message);
g_error_free(error);
}
void
Instance::HttpConnectionClosed()
{
}
static void
test_catch(EventLoop &event_loop, struct pool *_pool)
{
int fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
perror("socketpair()");
abort();
}
static constexpr char request[] =
"POST / HTTP/1.1\r\nContent-Length: 1024\r\n\r\nfoo";
send(fds[1], request, sizeof(request) - 1, 0);
Instance instance(*_pool);
HttpServerConnection *connection;
http_server_connection_new(instance.pool, fds[0], FdType::FD_SOCKET,
nullptr, nullptr,
nullptr, nullptr,
true, instance,
&connection);
pool_unref(instance.pool);
event_loop.Dispatch();
close(fds[1]);
}
int main(int argc, char **argv) {
(void)argc;
(void)argv;
direct_global_init();
EventLoop event_loop;
fb_pool_init(false);
test_catch(event_loop, RootPool());
fb_pool_deinit();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.