text
stringlengths 54
60.6k
|
|---|
<commit_before>//
// Copyright (c) 2016 Joy Narical <jnarical@gmail.com> MIT license
//
// display.cpp
//
#include "display.hpp"
#include "strings.hpp"
#include "input.hpp"
#include "battlefield.hpp"
#include "powerup.hpp"
#include "player.hpp"
#include "item.hpp"
#include "monster.hpp"
#include "field.hpp"
#include "game.hpp"
#include <libtcod.hpp>
#include <cassert>
#include <iostream>
//horizontal wall
//std::string Display::HORIZ_WALL = "######################";
std::string Display::HORIZ_WALL = "";
Display::Display(Game * game) :
_game(game),
_frame(Frames::CURRENT)
{
TCODSystem::setFps(MAX_FPS);
TCODConsole::setCustomFont("courier12x12_aa_tc.png",TCOD_FONT_LAYOUT_TCOD);
TCODConsole::initRoot(SCREEN_WIDTH,SCREEN_HEIGHT,GAME_TITLE.c_str(),false);
TCOD_renderer_t ren = TCODSystem::getRenderer();
if (ren == TCOD_RENDERER_SDL) std::cout << "SDL" << std::endl;
TCODConsole::credits();
TCODConsole::root->setDefaultBackground(TCODColor::black);
TCODConsole::root->setDefaultForeground(TCODColor::red);
for (uint8_t i=0; i<BF_SIZE+2; ++i) HORIZ_WALL+="#";
// Make frame counters to zero for every event type
uint8_t list_begin = static_cast<uint8_t>(Events::LVLUP);
uint8_t list_end = static_cast<uint8_t>(Events::EVENTS_END);
for (uint8_t event = list_begin; event < list_end; ++event) _frameCounters[event] = 0;
}
void Display::ShowFrame()
{
TCODConsole::root->clear();
DrawBattlefield();
DrawPlayerInfo();
if (_game->GetPlayer()->HaveTarget()) DrawEnemyInfo();
TCODConsole::flush();
}
void Display::DrawBattlefield()
{
TCODConsole::root->print(BF_MARGIN, BF_ROW, HORIZ_WALL.c_str());
for (uint8_t rowIndex = 1; rowIndex <= BF_SIZE; ++rowIndex)
{
TCODConsole::root->print(BF_MARGIN, BF_ROW + rowIndex, "#\n");
for (uint8_t colIndex = 1; colIndex <= BF_SIZE; ++colIndex)
TCODConsole::root->print(BF_MARGIN + colIndex, BF_ROW + rowIndex, DrawField(rowIndex-1, colIndex-1));
TCODConsole::root->print(BF_MARGIN + BF_SIZE + 1, BF_ROW + rowIndex, "#\n");
}
TCODConsole::root->print(BF_MARGIN, BF_ROW + BF_SIZE + 1, HORIZ_WALL.c_str());
}
void Display::DrawPlayerInfo()
{
Player * plr_copy = nullptr;
Monster * enemy_copy = nullptr;
Player * plr = _game->GetPlayer();
if (plr->HaveTarget())
{
plr_copy = _game->GetBattlefield()->GetPlayerCopy();
enemy_copy = _game->GetBattlefield()->GetEnemyCopy();
}
Item *inv1 = plr->GetInventory(0);
Item *inv2 = plr->GetInventory(1);
Item *inv3 = plr->GetInventory(2);
Item *inv4 = plr->GetInventory(3);
Item *grnd = plr->GetPosition()->GetItem();
Item *sel_item = plr->GetSelectedItem();
if (plr_copy != nullptr && _frame == Frames::FUTURE)
plr = plr_copy;
else
plr = _game->GetPlayer();
std::string str_inv1 = (inv1 != nullptr ? "1. " + inv1->GetName() : "Empty slot");
std::string str_inv2 = (inv2 != nullptr ? "2. " + inv2->GetName() : "Empty slot");
std::string str_inv3 = (inv3 != nullptr ? "3. " + inv3->GetName() : "Empty slot");
std::string str_inv4 = (inv4 != nullptr ? "4. " + inv4->GetName() : "Empty slot");
std::string str_grnd = (grnd != nullptr ? GRND1 + grnd->GetName() + GRND2 : "");
std::string name = plr->GetName();
uint8_t level = plr->GetLevel();
uint16_t damage = plr->GetDamage();
uint16_t HP = plr->GetHP();
uint16_t maxHP = plr->GetMaxHP();
uint16_t mana = plr->GetMana();
uint16_t maxMana = plr->GetMaxMana();
uint16_t exp = plr->GetExp();
uint16_t expMax = plr->GetExpMax();
std::string healthBar = DrawBar(HP, maxHP);
std::string manaBar = DrawBar(mana, maxMana);
std::string expBar = DrawBar(exp, expMax);
std::string exp_line = "Exp "+std::to_string(exp)+" / "+std::to_string(expMax);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 0, exp_line.c_str());
//CheckEvent(MANA_PWRUP);
std::string mana_line = "Mana "+std::to_string(mana)+" / "+std::to_string(maxMana);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 1, mana_line.c_str());
//EndCheck();
if (inv1 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv1 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 3, str_inv1.c_str());
//BoldOff();
if (inv2 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv2 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 4, str_inv2.c_str());
//BoldOff();
if (inv3 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv3 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 5, str_inv3.c_str());
//BoldOff();
if (inv4 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv4 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 6, str_inv4.c_str());
//BoldOff();
if (str_grnd != "") TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 7, str_grnd.c_str());
//CheckEvent(Events::LVLUP);
std::string level_line = name + " - level " + std::to_string(level);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 9, level_line.c_str());
//EndCheck();
//CheckEvent(HP_PWRUP);
std::string health_line = " [+] " + std::to_string(HP) + " / " + std::to_string(maxHP);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 11, health_line.c_str());
//EndCheck();
//CheckEvent(DMG_PWRUP);
std::string damage_line = " [*] " + std::to_string(damage);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 13, damage_line.c_str());
//EndCheck();
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 0, expBar.c_str());
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 1, manaBar.c_str());
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 11, healthBar.c_str());
if (plr_copy != nullptr)
{
std::string prediction;
if (plr_copy->IsAlive() && enemy_copy->IsAlive()) prediction = "SAFE";
else if (plr_copy->IsDead() && enemy_copy->IsAlive()) prediction = "DEATH !!!";
else if (plr_copy->IsAlive() && enemy_copy->IsDead()) prediction = "Victory!";
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 13, prediction.c_str());
}
}
void Display::DrawEnemyInfo()
{
Monster * enemy = nullptr;
if (_game->GetBattlefield()->GetEnemyCopy() != nullptr && _frame == Frames::FUTURE)
enemy = _game->GetBattlefield()->GetEnemyCopy();
else enemy = _game->GetPlayer()->GetTargetField()->GetEnemy();
if (enemy != nullptr)
{
std::string name = enemy->GetName();
uint8_t level = enemy->GetLevel();
uint8_t damage = enemy->GetDamage();
uint8_t HP = enemy->GetHP();
uint8_t maxHP = enemy->GetMaxHP();
std::string healthBar = DrawBar(HP, maxHP);
std::string name_level_line = name + " - level " + std::to_string(level);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 0, name_level_line.c_str());
std::string health_line = " [+] " + std::to_string(HP) + " / " + std::to_string(maxHP);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 2, health_line.c_str());
std::string damage_line = " [*] " + std::to_string(damage);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 4, damage_line.c_str());
TCODConsole::root->print(BAR_MARGIN, ENEMY_ROW + 2, healthBar.c_str());
}
}
const char* Display::DrawField(uint8_t rowIndex, uint8_t colIndex) const
{
Field *playerField = _game->GetPlayer()->GetPosition();
Field *playerTarget = _game->GetPlayer()->GetTargetField();
Field *field = _game->GetBattlefield()->GetField(rowIndex, colIndex);
assert(field != nullptr);
if (!field->IsVisible()) return ".\n";
else
{
if (field->HaveEnemy())
{
if (field == playerTarget)
{
//BoldOn();
//CheckEvent(MNSTR_HIT_1);
//CheckEvent(MNSTR_HIT_2);
if (field->GetEnemy()->GetLevel() == 10) return "Z\n";
else return (std::to_string(field->GetEnemy()->GetLevel()) + "\n").c_str();
//EndCheck();
//BoldOff();
}
else
{
if (field->GetEnemy()->GetLevel() == 10) return "Z\n";
else return (std::to_string(field->GetEnemy()->GetLevel()) + "\n").c_str();
}
}
else if (field != playerField && field->HavePowerup())
{
switch (field->GetPowerup()->GetType())
{
case Powerups::HEALTH:
return "+\n";
break;
case Powerups::MANA:
return "x\n";
break;
case Powerups::DAMAGE:
return "*\n";
}
}
else if (field != playerField && field->HaveItem())
{
return "i\n";
}
else if (field == playerField && field->HaveItem())
{
// BoldOn();
return "@\n";
// BoldOff();
}
else if (field == playerField)
{
// CheckEvent(Events::LVLUP);
// CheckEvent(PLR_HIT_1);
// CheckEvent(PLR_HIT_2);
return "@\n";
// EndCheck();
}
else return " \n";
}
return "S\n";
}
void Display::ReduceCounters()
{
uint8_t list_begin = static_cast<uint8_t>(Events::LVLUP);
uint8_t list_end = static_cast<uint8_t>(Events::EVENTS_END);
for (uint8_t event = list_begin; event < list_end; ++event)
if (_frameCounters[event] > 0) --_frameCounters[event];
}
void Display::SwitchFrameType()
{
_frame = (_frame == Frames::CURRENT ? Frames::FUTURE : Frames::CURRENT);
}
std::string Display::DrawBar(uint16_t current, uint16_t max) const
{
uint16_t num;
std::string result = "[";
num = (current != 0 ? (uint16_t)( (double)current / max * BARWIDTH) : 0);
for (uint16_t i = 0; i < num; ++i) result += '#';
for (uint16_t i = 0; i < BARWIDTH - num; ++i) result += '.';
result += ']';
return result;
}
void Display::SendEvent(Events event)
{
uint8_t num = static_cast<uint8_t>(event);
_frameCounters[num] = EVENT_TIMERS[num];
}
void Display::CheckEvent(Events event)
{
/* switch (event)
{
case Eve.ts::LVLUP:
case HP_PWRUP:
case MANA_PWRUP:
case DMG_PWRUP:
if (_frameCounters[event] > 0 && _frameCounters[event] % 2) BoldOn();
break;
case PLR_HIT//_1:
case MNSTR_H//IT_1:
case PLR_HIT_2:
case MNSTR_HIT_2:
if e\nf; //ameCounters[event] == 1) InvertOn()//;
brea//k;
case Events::EVENTS_END:;
} */
}
void Display::ShowVictoryScreen()
{
/* clear();
TCODConsole::root->print(2,2,"Victory!");
refresh(); */
}
void Display::ShowDefeatScreen()
{
/* clear();
TCODConsole::root->print(2,2,"DEFEAT !");
s \nrfresh(); */
}<commit_msg>return default terminal.png font<commit_after>//
// Copyright (c) 2016 Joy Narical <jnarical@gmail.com> MIT license
//
// display.cpp
//
#include "display.hpp"
#include "strings.hpp"
#include "input.hpp"
#include "battlefield.hpp"
#include "powerup.hpp"
#include "player.hpp"
#include "item.hpp"
#include "monster.hpp"
#include "field.hpp"
#include "game.hpp"
#include <libtcod.hpp>
#include <cassert>
#include <iostream>
//horizontal wall
//std::string Display::HORIZ_WALL = "######################";
std::string Display::HORIZ_WALL = "";
Display::Display(Game * game) :
_game(game),
_frame(Frames::CURRENT)
{
TCODSystem::setFps(MAX_FPS);
// TCODConsole::setCustomFont("courier12x12_aa_tc.png",TCOD_FONT_LAYOUT_TCOD);
TCODConsole::initRoot(SCREEN_WIDTH,SCREEN_HEIGHT,GAME_TITLE.c_str(),false);
TCOD_renderer_t ren = TCODSystem::getRenderer();
if (ren == TCOD_RENDERER_SDL) std::cout << "SDL" << std::endl;
TCODConsole::credits();
TCODConsole::root->setDefaultBackground(TCODColor::black);
TCODConsole::root->setDefaultForeground(TCODColor::red);
for (uint8_t i=0; i<BF_SIZE+2; ++i) HORIZ_WALL+="#";
// Make frame counters to zero for every event type
uint8_t list_begin = static_cast<uint8_t>(Events::LVLUP);
uint8_t list_end = static_cast<uint8_t>(Events::EVENTS_END);
for (uint8_t event = list_begin; event < list_end; ++event) _frameCounters[event] = 0;
}
void Display::ShowFrame()
{
TCODConsole::root->clear();
DrawBattlefield();
DrawPlayerInfo();
if (_game->GetPlayer()->HaveTarget()) DrawEnemyInfo();
TCODConsole::flush();
}
void Display::DrawBattlefield()
{
TCODConsole::root->print(BF_MARGIN, BF_ROW, HORIZ_WALL.c_str());
for (uint8_t rowIndex = 1; rowIndex <= BF_SIZE; ++rowIndex)
{
TCODConsole::root->print(BF_MARGIN, BF_ROW + rowIndex, "#\n");
for (uint8_t colIndex = 1; colIndex <= BF_SIZE; ++colIndex)
TCODConsole::root->print(BF_MARGIN + colIndex, BF_ROW + rowIndex, DrawField(rowIndex-1, colIndex-1));
TCODConsole::root->print(BF_MARGIN + BF_SIZE + 1, BF_ROW + rowIndex, "#\n");
}
TCODConsole::root->print(BF_MARGIN, BF_ROW + BF_SIZE + 1, HORIZ_WALL.c_str());
}
void Display::DrawPlayerInfo()
{
Player * plr_copy = nullptr;
Monster * enemy_copy = nullptr;
Player * plr = _game->GetPlayer();
if (plr->HaveTarget())
{
plr_copy = _game->GetBattlefield()->GetPlayerCopy();
enemy_copy = _game->GetBattlefield()->GetEnemyCopy();
}
Item *inv1 = plr->GetInventory(0);
Item *inv2 = plr->GetInventory(1);
Item *inv3 = plr->GetInventory(2);
Item *inv4 = plr->GetInventory(3);
Item *grnd = plr->GetPosition()->GetItem();
Item *sel_item = plr->GetSelectedItem();
if (plr_copy != nullptr && _frame == Frames::FUTURE)
plr = plr_copy;
else
plr = _game->GetPlayer();
std::string str_inv1 = (inv1 != nullptr ? "1. " + inv1->GetName() : "Empty slot");
std::string str_inv2 = (inv2 != nullptr ? "2. " + inv2->GetName() : "Empty slot");
std::string str_inv3 = (inv3 != nullptr ? "3. " + inv3->GetName() : "Empty slot");
std::string str_inv4 = (inv4 != nullptr ? "4. " + inv4->GetName() : "Empty slot");
std::string str_grnd = (grnd != nullptr ? GRND1 + grnd->GetName() + GRND2 : "");
std::string name = plr->GetName();
uint8_t level = plr->GetLevel();
uint16_t damage = plr->GetDamage();
uint16_t HP = plr->GetHP();
uint16_t maxHP = plr->GetMaxHP();
uint16_t mana = plr->GetMana();
uint16_t maxMana = plr->GetMaxMana();
uint16_t exp = plr->GetExp();
uint16_t expMax = plr->GetExpMax();
std::string healthBar = DrawBar(HP, maxHP);
std::string manaBar = DrawBar(mana, maxMana);
std::string expBar = DrawBar(exp, expMax);
std::string exp_line = "Exp "+std::to_string(exp)+" / "+std::to_string(expMax);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 0, exp_line.c_str());
//CheckEvent(MANA_PWRUP);
std::string mana_line = "Mana "+std::to_string(mana)+" / "+std::to_string(maxMana);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 1, mana_line.c_str());
//EndCheck();
if (inv1 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv1 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 3, str_inv1.c_str());
//BoldOff();
if (inv2 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv2 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 4, str_inv2.c_str());
//BoldOff();
if (inv3 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv3 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 5, str_inv3.c_str());
//BoldOff();
if (inv4 == sel_item && sel_item != nullptr)
{
//BoldOn();
str_inv4 += INV;
}
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 6, str_inv4.c_str());
//BoldOff();
if (str_grnd != "") TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 7, str_grnd.c_str());
//CheckEvent(Events::LVLUP);
std::string level_line = name + " - level " + std::to_string(level);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 9, level_line.c_str());
//EndCheck();
//CheckEvent(HP_PWRUP);
std::string health_line = " [+] " + std::to_string(HP) + " / " + std::to_string(maxHP);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 11, health_line.c_str());
//EndCheck();
//CheckEvent(DMG_PWRUP);
std::string damage_line = " [*] " + std::to_string(damage);
TCODConsole::root->print(INFO_MARGIN, PLAYER_ROW + 13, damage_line.c_str());
//EndCheck();
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 0, expBar.c_str());
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 1, manaBar.c_str());
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 11, healthBar.c_str());
if (plr_copy != nullptr)
{
std::string prediction;
if (plr_copy->IsAlive() && enemy_copy->IsAlive()) prediction = "SAFE";
else if (plr_copy->IsDead() && enemy_copy->IsAlive()) prediction = "DEATH !!!";
else if (plr_copy->IsAlive() && enemy_copy->IsDead()) prediction = "Victory!";
TCODConsole::root->print(BAR_MARGIN, PLAYER_ROW + 13, prediction.c_str());
}
}
void Display::DrawEnemyInfo()
{
Monster * enemy = nullptr;
if (_game->GetBattlefield()->GetEnemyCopy() != nullptr && _frame == Frames::FUTURE)
enemy = _game->GetBattlefield()->GetEnemyCopy();
else enemy = _game->GetPlayer()->GetTargetField()->GetEnemy();
if (enemy != nullptr)
{
std::string name = enemy->GetName();
uint8_t level = enemy->GetLevel();
uint8_t damage = enemy->GetDamage();
uint8_t HP = enemy->GetHP();
uint8_t maxHP = enemy->GetMaxHP();
std::string healthBar = DrawBar(HP, maxHP);
std::string name_level_line = name + " - level " + std::to_string(level);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 0, name_level_line.c_str());
std::string health_line = " [+] " + std::to_string(HP) + " / " + std::to_string(maxHP);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 2, health_line.c_str());
std::string damage_line = " [*] " + std::to_string(damage);
TCODConsole::root->print(INFO_MARGIN, ENEMY_ROW + 4, damage_line.c_str());
TCODConsole::root->print(BAR_MARGIN, ENEMY_ROW + 2, healthBar.c_str());
}
}
const char* Display::DrawField(uint8_t rowIndex, uint8_t colIndex) const
{
Field *playerField = _game->GetPlayer()->GetPosition();
Field *playerTarget = _game->GetPlayer()->GetTargetField();
Field *field = _game->GetBattlefield()->GetField(rowIndex, colIndex);
assert(field != nullptr);
if (!field->IsVisible()) return ".\n";
else
{
if (field->HaveEnemy())
{
if (field == playerTarget)
{
//BoldOn();
//CheckEvent(MNSTR_HIT_1);
//CheckEvent(MNSTR_HIT_2);
if (field->GetEnemy()->GetLevel() == 10) return "Z\n";
else return (std::to_string(field->GetEnemy()->GetLevel()) + "\n").c_str();
//EndCheck();
//BoldOff();
}
else
{
if (field->GetEnemy()->GetLevel() == 10) return "Z\n";
else return (std::to_string(field->GetEnemy()->GetLevel()) + "\n").c_str();
}
}
else if (field != playerField && field->HavePowerup())
{
switch (field->GetPowerup()->GetType())
{
case Powerups::HEALTH:
return "+\n";
break;
case Powerups::MANA:
return "x\n";
break;
case Powerups::DAMAGE:
return "*\n";
}
}
else if (field != playerField && field->HaveItem())
{
return "i\n";
}
else if (field == playerField && field->HaveItem())
{
// BoldOn();
return "@\n";
// BoldOff();
}
else if (field == playerField)
{
// CheckEvent(Events::LVLUP);
// CheckEvent(PLR_HIT_1);
// CheckEvent(PLR_HIT_2);
return "@\n";
// EndCheck();
}
else return " \n";
}
return "S\n";
}
void Display::ReduceCounters()
{
uint8_t list_begin = static_cast<uint8_t>(Events::LVLUP);
uint8_t list_end = static_cast<uint8_t>(Events::EVENTS_END);
for (uint8_t event = list_begin; event < list_end; ++event)
if (_frameCounters[event] > 0) --_frameCounters[event];
}
void Display::SwitchFrameType()
{
_frame = (_frame == Frames::CURRENT ? Frames::FUTURE : Frames::CURRENT);
}
std::string Display::DrawBar(uint16_t current, uint16_t max) const
{
uint16_t num;
std::string result = "[";
num = (current != 0 ? (uint16_t)( (double)current / max * BARWIDTH) : 0);
for (uint16_t i = 0; i < num; ++i) result += '#';
for (uint16_t i = 0; i < BARWIDTH - num; ++i) result += '.';
result += ']';
return result;
}
void Display::SendEvent(Events event)
{
uint8_t num = static_cast<uint8_t>(event);
_frameCounters[num] = EVENT_TIMERS[num];
}
void Display::CheckEvent(Events event)
{
/* switch (event)
{
case Eve.ts::LVLUP:
case HP_PWRUP:
case MANA_PWRUP:
case DMG_PWRUP:
if (_frameCounters[event] > 0 && _frameCounters[event] % 2) BoldOn();
break;
case PLR_HIT//_1:
case MNSTR_H//IT_1:
case PLR_HIT_2:
case MNSTR_HIT_2:
if e\nf; //ameCounters[event] == 1) InvertOn()//;
brea//k;
case Events::EVENTS_END:;
} */
}
void Display::ShowVictoryScreen()
{
/* clear();
TCODConsole::root->print(2,2,"Victory!");
refresh(); */
}
void Display::ShowDefeatScreen()
{
/* clear();
TCODConsole::root->print(2,2,"DEFEAT !");
s \nrfresh(); */
}<|endoftext|>
|
<commit_before>#include <memory>
#include <utility>
#include <vector>
#include "base_test.hpp"
#include "expression/binary_predicate_expression.hpp"
#include "expression/expression_functional.hpp"
#include "operators/get_table.hpp"
#include "operators/table_scan.hpp"
#include "scheduler/current_scheduler.hpp"
#include "scheduler/job_task.hpp"
#include "scheduler/node_queue_scheduler.hpp"
#include "scheduler/operator_task.hpp"
#include "scheduler/topology.hpp"
#include "storage/storage_manager.hpp"
using namespace opossum::expression_functional; // NOLINT
namespace opossum {
class SchedulerTest : public BaseTest {
protected:
void stress_linear_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() {
auto current_value = 0u;
auto successful = counter.compare_exchange_strong(current_value, 1u);
ASSERT_TRUE(successful);
});
auto task2 = std::make_shared<JobTask>([&]() {
auto current_value = 1u;
auto successful = counter.compare_exchange_strong(current_value, 2u);
ASSERT_TRUE(successful);
});
auto task3 = std::make_shared<JobTask>([&]() {
auto current_value = 2u;
auto successful = counter.compare_exchange_strong(current_value, 3u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task2);
task2->set_as_predecessor_of(task3);
task3->schedule();
task1->schedule();
task2->schedule();
}
void stress_multiple_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() { counter += 1u; });
auto task2 = std::make_shared<JobTask>([&]() { counter += 2u; });
auto task3 = std::make_shared<JobTask>([&]() {
auto current_value = 3u;
auto successful = counter.compare_exchange_strong(current_value, 4u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task3);
task2->set_as_predecessor_of(task3);
task3->schedule();
task1->schedule();
task2->schedule();
}
void stress_diamond_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() {
auto current_value = 0u;
auto successful = counter.compare_exchange_strong(current_value, 1u);
ASSERT_TRUE(successful);
});
auto task2 = std::make_shared<JobTask>([&]() { counter += 2u; });
auto task3 = std::make_shared<JobTask>([&]() { counter += 3u; });
auto task4 = std::make_shared<JobTask>([&]() {
auto current_value = 6u;
auto successful = counter.compare_exchange_strong(current_value, 7u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task2);
task1->set_as_predecessor_of(task3);
task2->set_as_predecessor_of(task4);
task3->set_as_predecessor_of(task4);
task4->schedule();
task3->schedule();
task1->schedule();
task2->schedule();
}
void increment_counter_in_subtasks(std::atomic_uint& counter) {
std::vector<std::shared_ptr<AbstractTask>> tasks;
for (size_t i = 0; i < 10; i++) {
auto task = std::make_shared<JobTask>([&]() {
std::vector<std::shared_ptr<AbstractTask>> jobs;
for (size_t j = 0; j < 3; j++) {
auto job = std::make_shared<JobTask>([&]() { counter++; });
job->schedule();
jobs.emplace_back(job);
}
CurrentScheduler::wait_for_tasks(jobs);
});
task->schedule();
tasks.emplace_back(task);
}
}
};
/**
* Schedule some tasks with subtasks, make sure all of them finish
*/
TEST_F(SchedulerTest, BasicTest) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0};
increment_counter_in_subtasks(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 30u);
CurrentScheduler::set(nullptr);
}
TEST_F(SchedulerTest, BasicTestWithoutScheduler) {
std::atomic_uint counter{0};
increment_counter_in_subtasks(counter);
ASSERT_EQ(counter, 30u);
}
TEST_F(SchedulerTest, LinearDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0u};
stress_linear_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 3u);
}
TEST_F(SchedulerTest, MultipleDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0u};
stress_multiple_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 4u);
}
TEST_F(SchedulerTest, DiamondDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0};
stress_diamond_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 7u);
}
TEST_F(SchedulerTest, LinearDependenciesWithoutScheduler) {
std::atomic_uint counter{0u};
stress_linear_dependencies(counter);
ASSERT_EQ(counter, 3u);
}
TEST_F(SchedulerTest, MultipleDependenciesWithoutScheduler) {
std::atomic_uint counter{0u};
stress_multiple_dependencies(counter);
ASSERT_EQ(counter, 4u);
}
TEST_F(SchedulerTest, DiamondDependenciesWithoutScheduler) {
std::atomic_uint counter{0};
stress_diamond_dependencies(counter);
ASSERT_EQ(counter, 7u);
}
TEST_F(SchedulerTest, MultipleOperators) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
auto test_table = load_table("src/test/tables/int_float.tbl", 2);
StorageManager::get().add_table("table", test_table);
auto gt = std::make_shared<GetTable>("table");
auto a = PQPColumnExpression::from_table(*test_table, ColumnID{0});
auto ts = std::make_shared<TableScan>(gt, greater_than_equals_(a, 1234));
auto gt_task = std::make_shared<OperatorTask>(gt, CleanupTemporaries::Yes);
auto ts_task = std::make_shared<OperatorTask>(ts, CleanupTemporaries::Yes);
gt_task->set_as_predecessor_of(ts_task);
gt_task->schedule();
ts_task->schedule();
CurrentScheduler::get()->finish();
auto expected_result = load_table("src/test/tables/int_float_filtered2.tbl", 1);
EXPECT_TABLE_EQ_UNORDERED(ts->get_output(), expected_result);
}
TEST_F(SchedulerTest, VerifyTaskQueueSetup) {
Topology::use_non_numa_topology(8);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(1, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(8);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(8, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(2, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(8, 8);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(1, CurrentScheduler::get()->queues().size());
CurrentScheduler::get()->finish();
}
TEST_F(SchedulerTest, SingleWorkerGuaranteeProgress) {
Topology::use_default_topology(1);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
auto task_done = false;
auto task = std::make_shared<JobTask>([&task_done]() {
auto subtask = std::make_shared<JobTask>([&task_done]() { task_done = true; });
subtask->schedule();
CurrentScheduler::wait_for_tasks(std::vector<std::shared_ptr<AbstractTask>>{subtask});
});
task->schedule();
CurrentScheduler::wait_for_tasks(std::vector<std::shared_ptr<AbstractTask>>{task});
EXPECT_TRUE(task_done);
CurrentScheduler::get()->finish();
}
} // namespace opossum
<commit_msg>Only build a topology of at most 4 nodes, so that it works on 4-core-machines (#1339)<commit_after>#include <memory>
#include <utility>
#include <vector>
#include "base_test.hpp"
#include "expression/binary_predicate_expression.hpp"
#include "expression/expression_functional.hpp"
#include "operators/get_table.hpp"
#include "operators/table_scan.hpp"
#include "scheduler/current_scheduler.hpp"
#include "scheduler/job_task.hpp"
#include "scheduler/node_queue_scheduler.hpp"
#include "scheduler/operator_task.hpp"
#include "scheduler/topology.hpp"
#include "storage/storage_manager.hpp"
using namespace opossum::expression_functional; // NOLINT
namespace opossum {
class SchedulerTest : public BaseTest {
protected:
void stress_linear_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() {
auto current_value = 0u;
auto successful = counter.compare_exchange_strong(current_value, 1u);
ASSERT_TRUE(successful);
});
auto task2 = std::make_shared<JobTask>([&]() {
auto current_value = 1u;
auto successful = counter.compare_exchange_strong(current_value, 2u);
ASSERT_TRUE(successful);
});
auto task3 = std::make_shared<JobTask>([&]() {
auto current_value = 2u;
auto successful = counter.compare_exchange_strong(current_value, 3u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task2);
task2->set_as_predecessor_of(task3);
task3->schedule();
task1->schedule();
task2->schedule();
}
void stress_multiple_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() { counter += 1u; });
auto task2 = std::make_shared<JobTask>([&]() { counter += 2u; });
auto task3 = std::make_shared<JobTask>([&]() {
auto current_value = 3u;
auto successful = counter.compare_exchange_strong(current_value, 4u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task3);
task2->set_as_predecessor_of(task3);
task3->schedule();
task1->schedule();
task2->schedule();
}
void stress_diamond_dependencies(std::atomic_uint& counter) {
auto task1 = std::make_shared<JobTask>([&]() {
auto current_value = 0u;
auto successful = counter.compare_exchange_strong(current_value, 1u);
ASSERT_TRUE(successful);
});
auto task2 = std::make_shared<JobTask>([&]() { counter += 2u; });
auto task3 = std::make_shared<JobTask>([&]() { counter += 3u; });
auto task4 = std::make_shared<JobTask>([&]() {
auto current_value = 6u;
auto successful = counter.compare_exchange_strong(current_value, 7u);
ASSERT_TRUE(successful);
});
task1->set_as_predecessor_of(task2);
task1->set_as_predecessor_of(task3);
task2->set_as_predecessor_of(task4);
task3->set_as_predecessor_of(task4);
task4->schedule();
task3->schedule();
task1->schedule();
task2->schedule();
}
void increment_counter_in_subtasks(std::atomic_uint& counter) {
std::vector<std::shared_ptr<AbstractTask>> tasks;
for (size_t i = 0; i < 10; i++) {
auto task = std::make_shared<JobTask>([&]() {
std::vector<std::shared_ptr<AbstractTask>> jobs;
for (size_t j = 0; j < 3; j++) {
auto job = std::make_shared<JobTask>([&]() { counter++; });
job->schedule();
jobs.emplace_back(job);
}
CurrentScheduler::wait_for_tasks(jobs);
});
task->schedule();
tasks.emplace_back(task);
}
}
};
/**
* Schedule some tasks with subtasks, make sure all of them finish
*/
TEST_F(SchedulerTest, BasicTest) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0};
increment_counter_in_subtasks(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 30u);
CurrentScheduler::set(nullptr);
}
TEST_F(SchedulerTest, BasicTestWithoutScheduler) {
std::atomic_uint counter{0};
increment_counter_in_subtasks(counter);
ASSERT_EQ(counter, 30u);
}
TEST_F(SchedulerTest, LinearDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0u};
stress_linear_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 3u);
}
TEST_F(SchedulerTest, MultipleDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0u};
stress_multiple_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 4u);
}
TEST_F(SchedulerTest, DiamondDependenciesWithScheduler) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
std::atomic_uint counter{0};
stress_diamond_dependencies(counter);
CurrentScheduler::get()->finish();
ASSERT_EQ(counter, 7u);
}
TEST_F(SchedulerTest, LinearDependenciesWithoutScheduler) {
std::atomic_uint counter{0u};
stress_linear_dependencies(counter);
ASSERT_EQ(counter, 3u);
}
TEST_F(SchedulerTest, MultipleDependenciesWithoutScheduler) {
std::atomic_uint counter{0u};
stress_multiple_dependencies(counter);
ASSERT_EQ(counter, 4u);
}
TEST_F(SchedulerTest, DiamondDependenciesWithoutScheduler) {
std::atomic_uint counter{0};
stress_diamond_dependencies(counter);
ASSERT_EQ(counter, 7u);
}
TEST_F(SchedulerTest, MultipleOperators) {
Topology::use_fake_numa_topology(8, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
auto test_table = load_table("src/test/tables/int_float.tbl", 2);
StorageManager::get().add_table("table", test_table);
auto gt = std::make_shared<GetTable>("table");
auto a = PQPColumnExpression::from_table(*test_table, ColumnID{0});
auto ts = std::make_shared<TableScan>(gt, greater_than_equals_(a, 1234));
auto gt_task = std::make_shared<OperatorTask>(gt, CleanupTemporaries::Yes);
auto ts_task = std::make_shared<OperatorTask>(ts, CleanupTemporaries::Yes);
gt_task->set_as_predecessor_of(ts_task);
gt_task->schedule();
ts_task->schedule();
CurrentScheduler::get()->finish();
auto expected_result = load_table("src/test/tables/int_float_filtered2.tbl", 1);
EXPECT_TABLE_EQ_UNORDERED(ts->get_output(), expected_result);
}
TEST_F(SchedulerTest, VerifyTaskQueueSetup) {
Topology::use_non_numa_topology(4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(1, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(4, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(4, 2);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(2, CurrentScheduler::get()->queues().size());
Topology::use_fake_numa_topology(4, 4);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
EXPECT_EQ(1, CurrentScheduler::get()->queues().size());
CurrentScheduler::get()->finish();
}
TEST_F(SchedulerTest, SingleWorkerGuaranteeProgress) {
Topology::use_default_topology(1);
CurrentScheduler::set(std::make_shared<NodeQueueScheduler>());
auto task_done = false;
auto task = std::make_shared<JobTask>([&task_done]() {
auto subtask = std::make_shared<JobTask>([&task_done]() { task_done = true; });
subtask->schedule();
CurrentScheduler::wait_for_tasks(std::vector<std::shared_ptr<AbstractTask>>{subtask});
});
task->schedule();
CurrentScheduler::wait_for_tasks(std::vector<std::shared_ptr<AbstractTask>>{task});
EXPECT_TRUE(task_done);
CurrentScheduler::get()->finish();
}
} // namespace opossum
<|endoftext|>
|
<commit_before>#include <yuni/yuni.h>
#include <yuni/io/file.h>
#include <yuni/core/system/console.h>
#include <yuni/core/getopt.h>
#include "details/grammar/nany.h"
#include <iostream>
#include <vector>
using namespace Yuni;
#ifndef NANY_VERSION
#error define NANY_VERSION is missing
#endif
#define likely(X) YUNI_LIKELY(X)
#define unlikely(X) YUNI_UNLIKELY(X)
namespace {
bool printAST(const AnyString filename, bool unixcolors) {
if (filename.empty())
return false;
ny::AST::Parser parser;
bool success = parser.loadFromFile(filename);
if (parser.root != nullptr) { // the AST might be empty
Clob out;
ny::AST::Node::Export(out, *parser.root, unixcolors);
std::cout.write(out.c_str(), out.size());
}
return success;
}
int printVersion() {
assert(strlen(YUNI_STRINGIZE(NANY_VERSION)) >= 5 and "empty version");
std::cout << YUNI_STRINGIZE(NANY_VERSION) << '\n';
return EXIT_SUCCESS;
}
} // namespace
int main(int argc, char** argv) {
// all input filenames
std::vector<String> filenames;
// no colors
bool noColors = false;
// parse the command
{
// The command line options parser
GetOpt::Parser options;
// Input files
options.add(filenames, 'i', "input", "Input files (or folders)");
options.remainingArguments(filenames);
// OUTPUT
options.addParagraph("\nOutput\n");
// --no-color
options.addFlag(noColors, ' ', "no-color", "Disable color output");
// HELP
// help
options.addParagraph("\nHelp\n");
// version
bool optVersion = false;
options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit");
// Ask to the parser to parse the command line
if (not options(argc, argv)) {
// The program should not continue here
// The user may have requested the help or an error has happened
// If an error has happened, the exit status should be different from 0
if (options.errors()) {
std::cerr << "Abort due to error\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (unlikely(optVersion))
return printVersion();
if (unlikely(filenames.empty())) {
std::cerr << argv[0] << ": no input file\n";
return EXIT_FAILURE;
}
}
// colors
bool withColors = ((not noColors) and System::Console::IsStdoutTTY());
bool success = true;
for (auto& path: filenames)
success &= printAST(path, withColors);
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
<commit_msg>misc: coding style dump-ast<commit_after>#include <yuni/yuni.h>
#include <yuni/io/file.h>
#include <yuni/core/system/console.h>
#include <yuni/core/getopt.h>
#include "details/grammar/nany.h"
#include <iostream>
#include <vector>
using namespace Yuni;
#ifndef NANY_VERSION
#error define NANY_VERSION is missing
#endif
#define likely(X) YUNI_LIKELY(X)
#define unlikely(X) YUNI_UNLIKELY(X)
namespace {
bool printAST(const AnyString filename, bool unixcolors) {
if (filename.empty())
return false;
ny::AST::Parser parser;
bool success = parser.loadFromFile(filename);
if (parser.root != nullptr) { // the AST might be empty
Clob out;
ny::AST::Node::Export(out, *parser.root, unixcolors);
std::cout.write(out.c_str(), out.size());
}
return success;
}
int printVersion() {
assert(strlen(YUNI_STRINGIZE(NANY_VERSION)) >= 5 and "empty version");
std::cout << YUNI_STRINGIZE(NANY_VERSION) << '\n';
return EXIT_SUCCESS;
}
} // namespace
int main(int argc, char** argv) {
// all input filenames
std::vector<String> filenames;
// no colors
bool noColors = false;
// parse the command
{
// The command line options parser
GetOpt::Parser options;
// Input files
options.add(filenames, 'i', "input", "Input files (or folders)");
options.remainingArguments(filenames);
// OUTPUT
options.addParagraph("\nOutput\n");
// --no-color
options.addFlag(noColors, ' ', "no-color", "Disable color output");
// HELP
// help
options.addParagraph("\nHelp\n");
// version
bool optVersion = false;
options.addFlag(optVersion, ' ', "version", "Display the version of the compiler and exit");
// Ask to the parser to parse the command line
if (not options(argc, argv)) {
// The program should not continue here
// The user may have requested the help or an error has happened
// If an error has happened, the exit status should be different from 0
if (options.errors()) {
std::cerr << "Abort due to error\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (unlikely(optVersion))
return printVersion();
if (unlikely(filenames.empty())) {
std::cerr << argv[0] << ": no input file\n";
return EXIT_FAILURE;
}
}
// colors
bool withColors = ((not noColors) and System::Console::IsStdoutTTY());
bool success = true;
for (auto& path : filenames)
success &= printAST(path, withColors);
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before>#ifndef DISSENT_ANONYMITY_SHUFFLE_ROUND_H_GUARD
#define DISSENT_ANONYMITY_SHUFFLE_ROUND_H_GUARD
#include <QBitArray>
#include <QDataStream>
#include <QMetaEnum>
#include <QSharedPointer>
#include "Connections/Network.hpp"
#include "Log.hpp"
#include "Round.hpp"
namespace Dissent {
namespace Anonymity {
/**
* Dissent's shuffling algorithm.
*
* A subset of members, shufflers, provide a pair of public encryption keys
* called inner and outer keys. In the protocol these key pairs are
* distributed first. Some other subset of peers has a message they want to
* share anonymously and those that do not have a null packet. Each member
* encrypts their message first with each inner key and then with each outer
* key. Keys are ordered by the peer Id of the owner from largest to
* smallest largest in Integer format. The resulting message is sent to the
* first member in the shufflers group. Each shuffler removes their outer
* encryption, shuffles (permutes) the message order, and transmits the
* resulting message to the next member. When the last shuffler completes
* their decryption and permutation, the message is broadcasted to all
* members in the group.
*
* Each member broadcasts to a go along with the hash of all broadcast
* messages received thus far if their inner encrypted message is present or
* a no go if not. If all members submit a go and have the same broadcast
* message hash, each shuffler reveals their private keys. Otherwise peers
* begin a blame phase and broadcast their logs to each other. Afterward,
* each peer distributes the hash of the messages and the signature, so that
* each other member can verify they are viewing the same state. Each peer
* will replay the round and determine the faulty peer.
*
* The blame phase is still being evolved.
*/
class ShuffleRound : public Round {
Q_OBJECT
Q_ENUMS(State);
Q_ENUMS(MessageType);
public:
/**
* Various states that the system can be in during the shuffle
*/
enum State {
Offline,
KeySharing,
DataSubmission,
WaitingForShuffle,
Shuffling,
WaitingForEncryptedInnerData,
Verification,
PrivateKeySharing,
Decryption,
BlameInit,
BlameShare,
BlameReviewing,
Finished
};
/**
* Converts an State into a QString
* @param state value to convert
*/
static QString StateToString(State state)
{
int index = staticMetaObject.indexOfEnumerator("State");
return staticMetaObject.enumerator(index).valueToKey(state);
}
/**
* Various message types sent and received
*/
enum MessageType {
PublicKeys,
Data,
ShuffleData,
EncryptedData,
GoMessage,
NoGoMessage,
PrivateKey,
BlameData,
BlameVerification
};
/**
* Converts a MessageType into a QString
* @param mt value to convert
*/
static QString MessageTypeToString(MessageType mt)
{
int index = staticMetaObject.indexOfEnumerator("MessageType");
return staticMetaObject.enumerator(index).valueToKey(mt);
}
/**
* Block size for the cleartext shuffle data
*/
static const int BlockSize = 1024;
/**
* Empty block used for nodes who do not send any data
*/
static const QByteArray DefaultData;
/**
* Constructor
* @param group Group used during this round
* @param ident the local nodes credentials
* @param round_id Unique round id (nonce)
* @param network handles message sending
* @param get_data requests data to share during this session
*/
explicit ShuffleRound(const Group &group,
const PrivateIdentity &ident, const Id &round_id,
QSharedPointer<Network> network, GetDataCallback &get_data);
/**
* Deconstructor
*/
virtual ~ShuffleRound();
/**
* Deletes each individual entry in a QVector of AsymmetricKeys
* @param keys keys to delete
*/
void DeleteKeys(QVector<AsymmetricKey *> &keys);
/**
* Returns the systems current state
*/
inline State GetState() const { return _state; }
/**
* Returns the state at which the system began blame
*/
inline State GetBlameState() const { return _blame_state; }
/**
* Inner and outer public keys are kept in reversed order, this returns
* the public key index for a given group index.
* @param idx the group index
*/
inline int CalculateKidx(int idx) { return _shufflers.Count() - 1 - idx; }
/**
* Returns a list of members who have been blamed in the round
*/
inline virtual const QVector<int> &GetBadMembers() const { return _bad_members; }
/**
* Returns the shufflers group
*/
const Group &GetShufflers() { return _shufflers; }
virtual bool Start();
inline virtual QString ToString() const { return "ShuffleRound: " + GetRoundId().ToString(); }
protected:
virtual void ProcessData(const Id &from, const QByteArray &data);
/**
* Allows direct access to the message parsing without a try / catch
* surrounding it
* @param from the node the data is from
* @param data input data
*/
void ProcessDataBase(const Id &from, const QByteArray &data);
/**
* Parses incoming public key messages
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandlePublicKeys(QDataStream &stream, const Id &id);
/**
* First node receives data from all peers
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleData(QDataStream &stream, const Id &id);
/**
* Each node besides the first receives shuffled data
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleShuffle(QDataStream &stream, const Id &id);
/**
* The inner encrypted only messages sent by the last peer
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleDataBroadcast(QDataStream &stream, const Id &id);
/**
* Each peer sends a go / no go message
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleVerification(QDataStream &stream, bool go, const Id &id);
/**
* Each peer shares with each other their inner private keys
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandlePrivateKey(QDataStream &stream, const Id &id);
/**
* Each peer shares their incoming messages logs with each other in order
* to reconstruct where something bad may have occurred
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleBlame(QDataStream &stream, const Id &id);
/**
* Prior to reviewing the blame data, shares the signatures of the blames
* that they received
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleBlameVerification(QDataStream &stream, const Id &id);
/**
* Broadcasts the nodes inner and outer public keys to all other nodes
*/
virtual void BroadcastPublicKeys();
/**
* Encrypts and submits the data block to the first node
*/
virtual void SubmitData();
/**
* Takes input shuffle data, verifies no duplicate messages, decrypts a
* layer and forwards onward or broadcasts to all nodes if it is the
* final node
*/
virtual void Shuffle();
/**
* After receiving the inner encrypted data, each node will send a go
* or no go message.
*/
virtual void VerifyInnerCiphertext();
/**
* Shares the inner private key with all nodes
*/
virtual void BroadcastPrivateKey();
/**
* After receiving all inner keys, the node will decrypt the data blocks
* and push "real" data into the listener to the round (session)
*/
virtual void Decrypt();
/**
* Shares blame data (message log, outer private key, and a signature of
* the hash of this message) with all other nodes.
*/
virtual void StartBlame();
/**
* Broadcasts the hash and signature of all blame data received to other
* nodes, so all nodes can be certain they are working from teh same
* blame data.
*/
virtual void BroadcastBlameVerification();
/**
* After receiving all blame verifications, begin blame round.
*/
virtual void BlameRound();
/**
* Takes a data block and makes it proper encoding for the shuffle
* @param data data input
*/
QByteArray PrepareData();
/**
* Retrieves from a data block from shuffle data
* @param data shuffle data
*/
QByteArray ParseData(QByteArray data);
/**
* Group of members responsible for providing anonymity
*/
Group _shufflers;
/**
* Is the node a shuffler?
*/
bool _shuffler;
/**
* Local nodes current state
*/
State _state;
/**
* Local nodes last state before blame
*/
State _blame_state;
/**
* All the remote peers inner keys, in reverse order
*/
QVector<AsymmetricKey *> _public_inner_keys;
/**
* All the remote peers outer keys, in reverse order
*/
QVector<AsymmetricKey *> _public_outer_keys;
/**
* Counter for keeping track of keys received
*/
int _keys_received;
/**
* The private inner encrypting key
*/
QScopedPointer<AsymmetricKey> _inner_key;
/**
* The private outer encrypting key
*/
QScopedPointer<AsymmetricKey> _outer_key;
/**
* All the remote peers inner private keys
*/
QVector<AsymmetricKey *> _private_inner_keys;
/**
* All the remote peers outer private keys, used during a blame
*/
QVector<AsymmetricKey *> _private_outer_keys;
/**
* Number of peers to have submitted data to first node or blame phase
*/
int _data_received;
/**
* Number of peers to send a go message
*/
int _go_count;
/**
* Blame verifications received
*/
int _blame_verifications;
/**
* Stores the positively received goes by group index
*/
QBitArray _go_received;
/**
* Stores the positively received goes by group index
*/
QBitArray _go;
/**
* Data pushed into the shuffle
*/
QVector<QByteArray> _shuffle_cleartext;
/**
* Data pulled from the shuffle
*/
QVector<QByteArray> _shuffle_ciphertext;
/**
* Inner encrypted only data
*/
QVector<QByteArray> _encrypted_data;
/**
* Local nodes inner onion ciphertext
*/
QByteArray _inner_ciphertext;
/**
* Local nodes outer onion ciphertext
*/
QByteArray _outer_ciphertext;
/**
* Stores all validated messages that arrived before start was called
*/
Log _offline_log;
/**
* Stores all validated incoming messages
*/
Log _log;
/**
* Locally generated broadcast hash
*/
QByteArray _broadcast_hash;
/**
* Stores peers incoming / outgoing broadcasted components
*/
QVector<QByteArray> _broadcast_hashes;
/**
* Maintains who has and has not sent a blame message yet
*/
QBitArray _blame_received;
/**
* Stores all the in blame logs
*/
QVector<Log> _logs;
/**
* Stores all the shortened blame messages
*/
QVector<QByteArray> _blame_hash;
/**
* Stores all the blame verifications
*/
QVector<QByteArray> _blame_signatures;
typedef QPair<QVector<QByteArray>, QVector<QByteArray> > HashSig;
/**
* Store remote blame hash / signatures until we have received all blame data
*/
QVector<HashSig> _blame_verification_msgs;
/**
* Received a blame verification from the remote peer
*/
QBitArray _received_blame_verification;
/**
* List of the index of all bad peers
*/
QVector<int> _bad_members;
};
}
}
#endif
<commit_msg>Adding note on anonymity to shuffleround<commit_after>#ifndef DISSENT_ANONYMITY_SHUFFLE_ROUND_H_GUARD
#define DISSENT_ANONYMITY_SHUFFLE_ROUND_H_GUARD
#include <QBitArray>
#include <QDataStream>
#include <QMetaEnum>
#include <QSharedPointer>
#include "Connections/Network.hpp"
#include "Log.hpp"
#include "Round.hpp"
namespace Dissent {
namespace Anonymity {
/**
* Dissent's shuffling algorithm.
*
* A subset of members, shufflers, provide a pair of public encryption keys
* called inner and outer keys. In the protocol these key pairs are
* distributed first. Some other subset of peers has a message they want to
* share anonymously and those that do not have a null packet. Each member
* encrypts their message first with each inner key and then with each outer
* key. Keys are ordered by the peer Id of the owner from largest to
* smallest largest in Integer format. The resulting message is sent to the
* first member in the shufflers group. Each shuffler removes their outer
* encryption, shuffles (permutes) the message order, and transmits the
* resulting message to the next member. When the last shuffler completes
* their decryption and permutation, the message is broadcasted to all
* members in the group.
*
* Each member broadcasts to a go along with the hash of all broadcast
* messages received thus far if their inner encrypted message is present or
* a no go if not. If all members submit a go and have the same broadcast
* message hash, each shuffler reveals their private keys. Otherwise peers
* begin a blame phase and broadcast their logs to each other. Afterward,
* each peer distributes the hash of the messages and the signature, so that
* each other member can verify they are viewing the same state. Each peer
* will replay the round and determine the faulty peer.
*
* The blame phase is still being evolved.
*
* @TODO XXX: In the client/server model, the servers should each decrypt
* the ciphertext set and send the signed plaintex messages to the clients
*/
class ShuffleRound : public Round {
Q_OBJECT
Q_ENUMS(State);
Q_ENUMS(MessageType);
public:
/**
* Various states that the system can be in during the shuffle
*/
enum State {
Offline,
KeySharing,
DataSubmission,
WaitingForShuffle,
Shuffling,
WaitingForEncryptedInnerData,
Verification,
PrivateKeySharing,
Decryption,
BlameInit,
BlameShare,
BlameReviewing,
Finished
};
/**
* Converts an State into a QString
* @param state value to convert
*/
static QString StateToString(State state)
{
int index = staticMetaObject.indexOfEnumerator("State");
return staticMetaObject.enumerator(index).valueToKey(state);
}
/**
* Various message types sent and received
*/
enum MessageType {
PublicKeys,
Data,
ShuffleData,
EncryptedData,
GoMessage,
NoGoMessage,
PrivateKey,
BlameData,
BlameVerification
};
/**
* Converts a MessageType into a QString
* @param mt value to convert
*/
static QString MessageTypeToString(MessageType mt)
{
int index = staticMetaObject.indexOfEnumerator("MessageType");
return staticMetaObject.enumerator(index).valueToKey(mt);
}
/**
* Block size for the cleartext shuffle data
*/
static const int BlockSize = 1024;
/**
* Empty block used for nodes who do not send any data
*/
static const QByteArray DefaultData;
/**
* Constructor
* @param group Group used during this round
* @param ident the local nodes credentials
* @param round_id Unique round id (nonce)
* @param network handles message sending
* @param get_data requests data to share during this session
*/
explicit ShuffleRound(const Group &group,
const PrivateIdentity &ident, const Id &round_id,
QSharedPointer<Network> network, GetDataCallback &get_data);
/**
* Deconstructor
*/
virtual ~ShuffleRound();
/**
* Deletes each individual entry in a QVector of AsymmetricKeys
* @param keys keys to delete
*/
void DeleteKeys(QVector<AsymmetricKey *> &keys);
/**
* Returns the systems current state
*/
inline State GetState() const { return _state; }
/**
* Returns the state at which the system began blame
*/
inline State GetBlameState() const { return _blame_state; }
/**
* Inner and outer public keys are kept in reversed order, this returns
* the public key index for a given group index.
* @param idx the group index
*/
inline int CalculateKidx(int idx) { return _shufflers.Count() - 1 - idx; }
/**
* Returns a list of members who have been blamed in the round
*/
inline virtual const QVector<int> &GetBadMembers() const { return _bad_members; }
/**
* Returns the shufflers group
*/
const Group &GetShufflers() { return _shufflers; }
virtual bool Start();
inline virtual QString ToString() const { return "ShuffleRound: " + GetRoundId().ToString(); }
protected:
virtual void ProcessData(const Id &from, const QByteArray &data);
/**
* Allows direct access to the message parsing without a try / catch
* surrounding it
* @param from the node the data is from
* @param data input data
*/
void ProcessDataBase(const Id &from, const QByteArray &data);
/**
* Parses incoming public key messages
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandlePublicKeys(QDataStream &stream, const Id &id);
/**
* First node receives data from all peers
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleData(QDataStream &stream, const Id &id);
/**
* Each node besides the first receives shuffled data
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleShuffle(QDataStream &stream, const Id &id);
/**
* The inner encrypted only messages sent by the last peer
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleDataBroadcast(QDataStream &stream, const Id &id);
/**
* Each peer sends a go / no go message
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleVerification(QDataStream &stream, bool go, const Id &id);
/**
* Each peer shares with each other their inner private keys
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandlePrivateKey(QDataStream &stream, const Id &id);
/**
* Each peer shares their incoming messages logs with each other in order
* to reconstruct where something bad may have occurred
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleBlame(QDataStream &stream, const Id &id);
/**
* Prior to reviewing the blame data, shares the signatures of the blames
* that they received
* @param stream serialized message
* @param id the remote peer sending the message
*/
void HandleBlameVerification(QDataStream &stream, const Id &id);
/**
* Broadcasts the nodes inner and outer public keys to all other nodes
*/
virtual void BroadcastPublicKeys();
/**
* Encrypts and submits the data block to the first node
*/
virtual void SubmitData();
/**
* Takes input shuffle data, verifies no duplicate messages, decrypts a
* layer and forwards onward or broadcasts to all nodes if it is the
* final node
*/
virtual void Shuffle();
/**
* After receiving the inner encrypted data, each node will send a go
* or no go message.
*/
virtual void VerifyInnerCiphertext();
/**
* Shares the inner private key with all nodes
*/
virtual void BroadcastPrivateKey();
/**
* After receiving all inner keys, the node will decrypt the data blocks
* and push "real" data into the listener to the round (session)
*/
virtual void Decrypt();
/**
* Shares blame data (message log, outer private key, and a signature of
* the hash of this message) with all other nodes.
*/
virtual void StartBlame();
/**
* Broadcasts the hash and signature of all blame data received to other
* nodes, so all nodes can be certain they are working from teh same
* blame data.
*/
virtual void BroadcastBlameVerification();
/**
* After receiving all blame verifications, begin blame round.
*/
virtual void BlameRound();
/**
* Takes a data block and makes it proper encoding for the shuffle
* @param data data input
*/
QByteArray PrepareData();
/**
* Retrieves from a data block from shuffle data
* @param data shuffle data
*/
QByteArray ParseData(QByteArray data);
/**
* Group of members responsible for providing anonymity
*/
Group _shufflers;
/**
* Is the node a shuffler?
*/
bool _shuffler;
/**
* Local nodes current state
*/
State _state;
/**
* Local nodes last state before blame
*/
State _blame_state;
/**
* All the remote peers inner keys, in reverse order
*/
QVector<AsymmetricKey *> _public_inner_keys;
/**
* All the remote peers outer keys, in reverse order
*/
QVector<AsymmetricKey *> _public_outer_keys;
/**
* Counter for keeping track of keys received
*/
int _keys_received;
/**
* The private inner encrypting key
*/
QScopedPointer<AsymmetricKey> _inner_key;
/**
* The private outer encrypting key
*/
QScopedPointer<AsymmetricKey> _outer_key;
/**
* All the remote peers inner private keys
*/
QVector<AsymmetricKey *> _private_inner_keys;
/**
* All the remote peers outer private keys, used during a blame
*/
QVector<AsymmetricKey *> _private_outer_keys;
/**
* Number of peers to have submitted data to first node or blame phase
*/
int _data_received;
/**
* Number of peers to send a go message
*/
int _go_count;
/**
* Blame verifications received
*/
int _blame_verifications;
/**
* Stores the positively received goes by group index
*/
QBitArray _go_received;
/**
* Stores the positively received goes by group index
*/
QBitArray _go;
/**
* Data pushed into the shuffle
*/
QVector<QByteArray> _shuffle_cleartext;
/**
* Data pulled from the shuffle
*/
QVector<QByteArray> _shuffle_ciphertext;
/**
* Inner encrypted only data
*/
QVector<QByteArray> _encrypted_data;
/**
* Local nodes inner onion ciphertext
*/
QByteArray _inner_ciphertext;
/**
* Local nodes outer onion ciphertext
*/
QByteArray _outer_ciphertext;
/**
* Stores all validated messages that arrived before start was called
*/
Log _offline_log;
/**
* Stores all validated incoming messages
*/
Log _log;
/**
* Locally generated broadcast hash
*/
QByteArray _broadcast_hash;
/**
* Stores peers incoming / outgoing broadcasted components
*/
QVector<QByteArray> _broadcast_hashes;
/**
* Maintains who has and has not sent a blame message yet
*/
QBitArray _blame_received;
/**
* Stores all the in blame logs
*/
QVector<Log> _logs;
/**
* Stores all the shortened blame messages
*/
QVector<QByteArray> _blame_hash;
/**
* Stores all the blame verifications
*/
QVector<QByteArray> _blame_signatures;
typedef QPair<QVector<QByteArray>, QVector<QByteArray> > HashSig;
/**
* Store remote blame hash / signatures until we have received all blame data
*/
QVector<HashSig> _blame_verification_msgs;
/**
* Received a blame verification from the remote peer
*/
QBitArray _received_blame_verification;
/**
* List of the index of all bad peers
*/
QVector<int> _bad_members;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Generic Win32 window class.
*//*--------------------------------------------------------------------*/
#include "tcuWin32Window.hpp"
namespace tcu
{
namespace win32
{
static LRESULT CALLBACK windowProcCallback (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
Window* window = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (window)
return window->windowProc(uMsg, wParam, lParam);
else
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Window::Window (HINSTANCE instance, int width, int height)
: m_window (DE_NULL)
{
try
{
static const char s_className[] = "dEQP Test Process Class";
static const char s_windowName[] = "dEQP Test Process";
{
WNDCLASS wndClass;
memset(&wndClass, 0, sizeof(wndClass));
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndClass.lpfnWndProc = windowProcCallback;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = instance;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = CreateSolidBrush(RGB(0, 0, 0));
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = s_className;
RegisterClass(&wndClass);
}
m_window = CreateWindow(s_className, s_windowName,
WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
width, height,
NULL, NULL, instance, NULL);
if (!m_window)
TCU_THROW(ResourceError, "Failed to create Win32 window");
// Store this as userdata
SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);
setSize(width, height);
}
catch (...)
{
if (m_window)
DestroyWindow(m_window);
throw;
}
}
Window::~Window (void)
{
if (m_window)
{
// Clear this pointer from windowproc
SetWindowLongPtr(m_window, GWLP_USERDATA, 0);
}
DestroyWindow(m_window);
}
void Window::setVisible (bool visible)
{
ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);
}
void Window::setSize (int width, int height)
{
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = width;
rc.bottom = height;
if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))
TCU_THROW(TestError, "AdjustWindowRect() failed");
if (!SetWindowPos(m_window, NULL, 0, 0,
rc.right - rc.left, rc.bottom - rc.top,
SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))
TCU_THROW(TestError, "SetWindowPos() failed");
}
IVec2 Window::getSize (void) const
{
RECT rc;
if (!GetClientRect(m_window, &rc))
TCU_THROW(TestError, "GetClientRect() failed");
return IVec2(rc.right - rc.left,
rc.bottom - rc.top);
}
void Window::processEvents (void)
{
MSG msg;
while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
}
LRESULT Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
// \todo [2014-03-12 pyry] Handle WM_SIZE?
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
{
PostQuitMessage(0);
return 0;
}
// fall-through
default:
return DefWindowProc(m_window, uMsg, wParam, lParam);
}
}
} // win32
} // tcu
<commit_msg>Change win32 window style to WS_POPUP<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Generic Win32 window class.
*//*--------------------------------------------------------------------*/
#include "tcuWin32Window.hpp"
namespace tcu
{
namespace win32
{
static LRESULT CALLBACK windowProcCallback (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
Window* window = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (window)
return window->windowProc(uMsg, wParam, lParam);
else
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Window::Window (HINSTANCE instance, int width, int height)
: m_window (DE_NULL)
{
try
{
static const char s_className[] = "dEQP Test Process Class";
static const char s_windowName[] = "dEQP Test Process";
{
WNDCLASS wndClass;
memset(&wndClass, 0, sizeof(wndClass));
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndClass.lpfnWndProc = windowProcCallback;
wndClass.cbClsExtra = 0;
wndClass.cbWndExtra = 0;
wndClass.hInstance = instance;
wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndClass.hbrBackground = CreateSolidBrush(RGB(0, 0, 0));
wndClass.lpszMenuName = NULL;
wndClass.lpszClassName = s_className;
RegisterClass(&wndClass);
}
m_window = CreateWindow(s_className, s_windowName,
WS_CLIPCHILDREN | WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT,
width, height,
NULL, NULL, instance, NULL);
if (!m_window)
TCU_THROW(ResourceError, "Failed to create Win32 window");
// Store this as userdata
SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);
setSize(width, height);
}
catch (...)
{
if (m_window)
DestroyWindow(m_window);
throw;
}
}
Window::~Window (void)
{
if (m_window)
{
// Clear this pointer from windowproc
SetWindowLongPtr(m_window, GWLP_USERDATA, 0);
}
DestroyWindow(m_window);
}
void Window::setVisible (bool visible)
{
ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);
}
void Window::setSize (int width, int height)
{
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = width;
rc.bottom = height;
if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))
TCU_THROW(TestError, "AdjustWindowRect() failed");
if (!SetWindowPos(m_window, NULL, 0, 0,
rc.right - rc.left, rc.bottom - rc.top,
SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))
TCU_THROW(TestError, "SetWindowPos() failed");
}
IVec2 Window::getSize (void) const
{
RECT rc;
if (!GetClientRect(m_window, &rc))
TCU_THROW(TestError, "GetClientRect() failed");
return IVec2(rc.right - rc.left,
rc.bottom - rc.top);
}
void Window::processEvents (void)
{
MSG msg;
while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))
DispatchMessage(&msg);
}
LRESULT Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
// \todo [2014-03-12 pyry] Handle WM_SIZE?
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE)
{
PostQuitMessage(0);
return 0;
}
// fall-through
default:
return DefWindowProc(m_window, uMsg, wParam, lParam);
}
}
} // win32
} // tcu
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: saxnamespacefilter.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-02-25 17:55:12 $
*
* 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): _______________________________________
*
*
************************************************************************/
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <stdio.h>
#include <xml/saxnamespacefilter.hxx>
#include <xml/attributelist.hxx>
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
const OUString aXMLAttributeNamespace( RTL_CONSTASCII_USTRINGPARAM( "xmlns" ));
const OUString aXMLAttributeType( RTL_CONSTASCII_USTRINGPARAM( "CDATA" ));
namespace framework{
SaxNamespaceFilter::SaxNamespaceFilter( Reference< XDocumentHandler >& rSax1DocumentHandler ) :
ThreadHelpBase( &Application::GetSolarMutex() ), OWeakObject(),
xDocumentHandler( rSax1DocumentHandler ),
m_xLocator( 0 ),
m_nDepth( 0 )
{
}
SaxNamespaceFilter::~SaxNamespaceFilter()
{
}
Any SAL_CALL SaxNamespaceFilter::queryInterface( const Type & rType ) throw( RuntimeException )
{
Any a = ::cppu::queryInterface(
rType ,
SAL_STATIC_CAST( XDocumentHandler*, this ));
if ( a.hasValue() )
return a;
return OWeakObject::queryInterface( rType );
}
// XDocumentHandler
void SAL_CALL SaxNamespaceFilter::startDocument(void)
throw ( SAXException, RuntimeException )
{
}
void SAL_CALL SaxNamespaceFilter::endDocument(void)
throw( SAXException, RuntimeException )
{
}
void SAL_CALL SaxNamespaceFilter::startElement(
const rtl::OUString& aName, const Reference< XAttributeList > &xAttribs )
throw( SAXException, RuntimeException )
{
XMLNamespaces aXMLNamespaces;
if ( m_aNamespaceStack.size() > 0 )
aXMLNamespaces = m_aNamespaceStack.top();
AttributeListImpl* pNewList = new AttributeListImpl();
// examine all namespaces for this level
::std::vector< int > aAttributeIndexes;
{
for ( int i=0; i< xAttribs->getLength(); i++ )
{
OUString aName = xAttribs->getNameByIndex( i );
if ( aName.compareTo( aXMLAttributeNamespace, aXMLAttributeNamespace.getLength() ) == 0 )
aXMLNamespaces.addNamespace( aName, xAttribs->getValueByIndex( i ));
else
aAttributeIndexes.push_back( i );
}
}
// current namespaces for this level
m_aNamespaceStack.push( aXMLNamespaces );
try
{
// apply namespaces to all remaing attributes
for ( sal_uInt32 i=0; i< aAttributeIndexes.size(); i++ )
{
OUString aAttributeName = xAttribs->getNameByIndex( aAttributeIndexes[i] );
OUString aValue = xAttribs->getValueByIndex( aAttributeIndexes[i] );
OUString aNamespaceAttributeName = aXMLNamespaces.applyNSToAttributeName( aAttributeName );
pNewList->addAttribute( aNamespaceAttributeName, aXMLAttributeType, aValue );
}
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
OUString aNamespaceElementName;
try
{
aNamespaceElementName = aXMLNamespaces.applyNSToElementName( aName );
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
xDocumentHandler->startElement( aNamespaceElementName, pNewList );
}
void SAL_CALL SaxNamespaceFilter::endElement(const rtl::OUString& aName)
throw( SAXException, RuntimeException )
{
XMLNamespaces& aXMLNamespaces = m_aNamespaceStack.top();
OUString aNamespaceElementName;
try
{
aNamespaceElementName = aXMLNamespaces.applyNSToElementName( aName );
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
xDocumentHandler->endElement( aNamespaceElementName );
m_aNamespaceStack.pop();
}
void SAL_CALL SaxNamespaceFilter::characters(const rtl::OUString& aChars)
throw( SAXException, RuntimeException )
{
xDocumentHandler->characters( aChars );
}
void SAL_CALL SaxNamespaceFilter::ignorableWhitespace(const rtl::OUString& aWhitespaces)
throw( SAXException, RuntimeException )
{
xDocumentHandler->ignorableWhitespace( aWhitespaces );
}
void SAL_CALL SaxNamespaceFilter::processingInstruction(
const rtl::OUString& aTarget, const rtl::OUString& aData)
throw( SAXException, RuntimeException )
{
xDocumentHandler->processingInstruction( aTarget, aData );
}
void SAL_CALL SaxNamespaceFilter::setDocumentLocator(
const Reference< XLocator > &xLocator)
throw( SAXException, RuntimeException )
{
m_xLocator = xLocator;
xDocumentHandler->setDocumentLocator( xLocator );
}
OUString SaxNamespaceFilter::getErrorLineString()
{
char buffer[32];
if ( m_xLocator.is() )
{
snprintf( buffer, sizeof(buffer), "Line: %ld - ", m_xLocator->getLineNumber() );
return OUString::createFromAscii( buffer );
}
else
return OUString();
}
} // namespace
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.334); FILE MERGED 2005/09/05 13:07:26 rt 1.2.334.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: saxnamespacefilter.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:04:52 $
*
* 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
*
************************************************************************/
/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
with solaris headers ...
*/
#include <vector>
#include <stdio.h>
#include <xml/saxnamespacefilter.hxx>
#include <xml/attributelist.hxx>
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::uno;
const OUString aXMLAttributeNamespace( RTL_CONSTASCII_USTRINGPARAM( "xmlns" ));
const OUString aXMLAttributeType( RTL_CONSTASCII_USTRINGPARAM( "CDATA" ));
namespace framework{
SaxNamespaceFilter::SaxNamespaceFilter( Reference< XDocumentHandler >& rSax1DocumentHandler ) :
ThreadHelpBase( &Application::GetSolarMutex() ), OWeakObject(),
xDocumentHandler( rSax1DocumentHandler ),
m_xLocator( 0 ),
m_nDepth( 0 )
{
}
SaxNamespaceFilter::~SaxNamespaceFilter()
{
}
Any SAL_CALL SaxNamespaceFilter::queryInterface( const Type & rType ) throw( RuntimeException )
{
Any a = ::cppu::queryInterface(
rType ,
SAL_STATIC_CAST( XDocumentHandler*, this ));
if ( a.hasValue() )
return a;
return OWeakObject::queryInterface( rType );
}
// XDocumentHandler
void SAL_CALL SaxNamespaceFilter::startDocument(void)
throw ( SAXException, RuntimeException )
{
}
void SAL_CALL SaxNamespaceFilter::endDocument(void)
throw( SAXException, RuntimeException )
{
}
void SAL_CALL SaxNamespaceFilter::startElement(
const rtl::OUString& aName, const Reference< XAttributeList > &xAttribs )
throw( SAXException, RuntimeException )
{
XMLNamespaces aXMLNamespaces;
if ( m_aNamespaceStack.size() > 0 )
aXMLNamespaces = m_aNamespaceStack.top();
AttributeListImpl* pNewList = new AttributeListImpl();
// examine all namespaces for this level
::std::vector< int > aAttributeIndexes;
{
for ( int i=0; i< xAttribs->getLength(); i++ )
{
OUString aName = xAttribs->getNameByIndex( i );
if ( aName.compareTo( aXMLAttributeNamespace, aXMLAttributeNamespace.getLength() ) == 0 )
aXMLNamespaces.addNamespace( aName, xAttribs->getValueByIndex( i ));
else
aAttributeIndexes.push_back( i );
}
}
// current namespaces for this level
m_aNamespaceStack.push( aXMLNamespaces );
try
{
// apply namespaces to all remaing attributes
for ( sal_uInt32 i=0; i< aAttributeIndexes.size(); i++ )
{
OUString aAttributeName = xAttribs->getNameByIndex( aAttributeIndexes[i] );
OUString aValue = xAttribs->getValueByIndex( aAttributeIndexes[i] );
OUString aNamespaceAttributeName = aXMLNamespaces.applyNSToAttributeName( aAttributeName );
pNewList->addAttribute( aNamespaceAttributeName, aXMLAttributeType, aValue );
}
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
OUString aNamespaceElementName;
try
{
aNamespaceElementName = aXMLNamespaces.applyNSToElementName( aName );
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
xDocumentHandler->startElement( aNamespaceElementName, pNewList );
}
void SAL_CALL SaxNamespaceFilter::endElement(const rtl::OUString& aName)
throw( SAXException, RuntimeException )
{
XMLNamespaces& aXMLNamespaces = m_aNamespaceStack.top();
OUString aNamespaceElementName;
try
{
aNamespaceElementName = aXMLNamespaces.applyNSToElementName( aName );
}
catch ( SAXException& e )
{
e.Message = OUString( getErrorLineString() + e.Message );
throw e;
}
xDocumentHandler->endElement( aNamespaceElementName );
m_aNamespaceStack.pop();
}
void SAL_CALL SaxNamespaceFilter::characters(const rtl::OUString& aChars)
throw( SAXException, RuntimeException )
{
xDocumentHandler->characters( aChars );
}
void SAL_CALL SaxNamespaceFilter::ignorableWhitespace(const rtl::OUString& aWhitespaces)
throw( SAXException, RuntimeException )
{
xDocumentHandler->ignorableWhitespace( aWhitespaces );
}
void SAL_CALL SaxNamespaceFilter::processingInstruction(
const rtl::OUString& aTarget, const rtl::OUString& aData)
throw( SAXException, RuntimeException )
{
xDocumentHandler->processingInstruction( aTarget, aData );
}
void SAL_CALL SaxNamespaceFilter::setDocumentLocator(
const Reference< XLocator > &xLocator)
throw( SAXException, RuntimeException )
{
m_xLocator = xLocator;
xDocumentHandler->setDocumentLocator( xLocator );
}
OUString SaxNamespaceFilter::getErrorLineString()
{
char buffer[32];
if ( m_xLocator.is() )
{
snprintf( buffer, sizeof(buffer), "Line: %ld - ", m_xLocator->getLineNumber() );
return OUString::createFromAscii( buffer );
}
else
return OUString();
}
} // namespace
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ZipFile.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: hr $ $Date: 2003-03-26 14:13:41 $
*
* 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): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _ZIP_FILE_HXX
#define _ZIP_FILE_HXX
#ifndef _BYTE_GRABBER_HXX_
#include <ByteGrabber.hxx>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _INFLATER_HXX
#include <Inflater.hxx>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPEXCEPTION_HPP_
#include <com/sun/star/packages/zip/ZipException.hpp>
#endif
namespace com { namespace sun { namespace star {
namespace lang { class XMultiServiceFactory; }
namespace ucb { class XProgressHandler; }
} } }
namespace vos
{
template < class T > class ORef;
}
/*
* We impose arbitrary but reasonable limit on ZIP files.
*/
#define ZIP_MAXNAMELEN 512
#define ZIP_MAXEXTRA 256
#define ZIP_MAXENTRIES (0x10000 - 2)
typedef void* rtlCipher;
class ZipEnumeration;
class EncryptionData;
class ZipFile
{
protected:
::rtl::OUString sName; /* zip file name */
::rtl::OUString sComment; /* zip file comment */
EntryHash aEntries;
ByteGrabber aGrabber;
Inflater aInflater;
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
com::sun::star::uno::Reference < com::sun::star::io::XSeekable > xSeek;
const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xFactory;
::com::sun::star::uno::Reference < ::com::sun::star::ucb::XProgressHandler > xProgressHandler;
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createMemoryStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bRawStream,
sal_Bool bDecrypt );
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createFileStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bRawStream,
sal_Bool bDecrypt );
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createUnbufferedStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bRawStream,
sal_Bool bDecrypt );
sal_Bool hasValidPassword ( ZipEntry & rEntry, const vos::ORef < EncryptionData > &rData );
sal_Bool checkSizeAndCRC( const ZipEntry& aEntry );
sal_Int32 getCRC( sal_Int32 nOffset, sal_Int32 nSize );
void getSizeAndCRC( sal_Int32 nOffset, sal_Int32 nCompressedSize, sal_Int32 *nSize, sal_Int32 *nCRC );
public:
ZipFile( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &xInput,
const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > &xNewFactory,
sal_Bool bInitialise
)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
ZipFile( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &xInput,
const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > &xNewFactory,
sal_Bool bInitialise,
sal_Bool bForceRecover,
::com::sun::star::uno::Reference < ::com::sun::star::ucb::XProgressHandler > xProgress
)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
~ZipFile();
void setInputStream ( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xNewStream );
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bDecrypt)
throw(::com::sun::star::io::IOException, ::com::sun::star::packages::zip::ZipException, ::com::sun::star::uno::RuntimeException);
static void StaticGetCipher ( const vos::ORef < EncryptionData > & xEncryptionData, rtlCipher &rCipher );
static void StaticFillHeader ( const vos::ORef < EncryptionData > & rData, sal_Int32 nSize, sal_Int8 * & pHeader );
static sal_Bool StaticFillData ( vos::ORef < EncryptionData > & rData, sal_Int32 &rSize, ::com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &rStream );
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bDecrypt )
throw(::com::sun::star::io::IOException, ::com::sun::star::packages::zip::ZipException, ::com::sun::star::uno::RuntimeException);
::rtl::OUString SAL_CALL getName( )
throw(::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSize( )
throw(::com::sun::star::uno::RuntimeException);
ZipEnumeration * SAL_CALL entries( );
protected:
sal_Bool readLOC ( ZipEntry &rEntry)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 readCEN()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 findEND()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 recover()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS mav05 (1.18.18); FILE MERGED 2003/09/04 07:57:13 mav 1.18.18.3: #i15929# WrongPasswordException.idl is in packages now 2003/07/21 14:14:19 mav 1.18.18.2: #i15929# include MediaType in raw stream header, and other fixes 2003/07/18 14:20:47 mav 1.18.18.1: #i15929# support encryption in storages<commit_after>/*************************************************************************
*
* $RCSfile: ZipFile.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2003-09-11 10:13:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Martin Gallwey (gallwey@sun.com)
*
*
************************************************************************/
#ifndef _ZIP_FILE_HXX
#define _ZIP_FILE_HXX
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPEXCEPTION_HPP_
#include <com/sun/star/packages/zip/ZipException.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPIOEXCEPTION_HPP_
#include <com/sun/star/packages/zip/ZipIOException.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_NOENCRYPTIONEXCEPTION_HPP_
#include <com/sun/star/packages/NoEncryptionException.hpp>
#endif
#ifndef _COM_SUN_STAR_PACKAGES_WRONGPASSWORDEXCEPTION_HPP_
#include <com/sun/star/packages/WrongPasswordException.hpp>
#endif
#ifndef _BYTE_GRABBER_HXX_
#include <ByteGrabber.hxx>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _INFLATER_HXX
#include <Inflater.hxx>
#endif
namespace com { namespace sun { namespace star {
namespace lang { class XMultiServiceFactory; }
namespace ucb { class XProgressHandler; }
} } }
namespace vos
{
template < class T > class ORef;
}
/*
* We impose arbitrary but reasonable limit on ZIP files.
*/
#define ZIP_MAXNAMELEN 512
#define ZIP_MAXEXTRA 256
#define ZIP_MAXENTRIES (0x10000 - 2)
typedef void* rtlCipher;
class ZipEnumeration;
class EncryptionData;
class ZipFile
{
protected:
::rtl::OUString sName; /* zip file name */
::rtl::OUString sComment; /* zip file comment */
EntryHash aEntries;
ByteGrabber aGrabber;
Inflater aInflater;
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream;
com::sun::star::uno::Reference < com::sun::star::io::XSeekable > xSeek;
const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xFactory;
::com::sun::star::uno::Reference < ::com::sun::star::ucb::XProgressHandler > xProgressHandler;
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createMemoryStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bRawStream,
sal_Bool bDecrypt );
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createFileStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bRawStream,
sal_Bool bDecrypt );
// aMediaType parameter is used only for raw stream header creation
com::sun::star::uno::Reference < com::sun::star::io::XInputStream > createUnbufferedStream(
ZipEntry & rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Int8 nStreamMode,
sal_Bool bDecrypt,
::rtl::OUString aMediaType = ::rtl::OUString() );
sal_Bool hasValidPassword ( ZipEntry & rEntry, const vos::ORef < EncryptionData > &rData );
sal_Bool checkSizeAndCRC( const ZipEntry& aEntry );
sal_Int32 getCRC( sal_Int32 nOffset, sal_Int32 nSize );
void getSizeAndCRC( sal_Int32 nOffset, sal_Int32 nCompressedSize, sal_Int32 *nSize, sal_Int32 *nCRC );
public:
ZipFile( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &xInput,
const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > &xNewFactory,
sal_Bool bInitialise
)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
ZipFile( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &xInput,
const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > &xNewFactory,
sal_Bool bInitialise,
sal_Bool bForceRecover,
::com::sun::star::uno::Reference < ::com::sun::star::ucb::XProgressHandler > xProgress
)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
~ZipFile();
void setInputStream ( com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xNewStream );
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawData(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bDecrypt)
throw(::com::sun::star::io::IOException, ::com::sun::star::packages::zip::ZipException, ::com::sun::star::uno::RuntimeException);
static void StaticGetCipher ( const vos::ORef < EncryptionData > & xEncryptionData, rtlCipher &rCipher );
static void StaticFillHeader ( const vos::ORef < EncryptionData > & rData,
sal_Int32 nSize,
const ::rtl::OUString& aMediaType,
sal_Int8 * & pHeader );
static sal_Bool StaticFillData ( vos::ORef < EncryptionData > & rData,
sal_Int32 &rSize,
::rtl::OUString& aMediaType,
::com::sun::star::uno::Reference < com::sun::star::io::XInputStream > &rStream );
static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > StaticGetDataFromRawStream(
const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xStream,
const vos::ORef < EncryptionData > &rData )
throw ( ::com::sun::star::packages::WrongPasswordException,
::com::sun::star::packages::zip::ZipIOException,
::com::sun::star::uno::RuntimeException );
static sal_Bool StaticHasValidPassword ( const ::com::sun::star::uno::Sequence< sal_Int8 > &aReadBuffer,
const vos::ORef < EncryptionData > &rData );
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bDecrypt )
throw(::com::sun::star::io::IOException, ::com::sun::star::packages::zip::ZipException, ::com::sun::star::uno::RuntimeException);
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getDataStream(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
sal_Bool bDecrypt )
throw ( ::com::sun::star::packages::WrongPasswordException,
::com::sun::star::io::IOException,
::com::sun::star::packages::zip::ZipException,
::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getWrappedRawStream(
ZipEntry& rEntry,
const vos::ORef < EncryptionData > &rData,
const ::rtl::OUString& aMediaType )
throw ( ::com::sun::star::packages::NoEncryptionException,
::com::sun::star::io::IOException,
::com::sun::star::packages::zip::ZipException,
::com::sun::star::uno::RuntimeException );
::rtl::OUString SAL_CALL getName( )
throw(::com::sun::star::uno::RuntimeException);
sal_Int32 SAL_CALL getSize( )
throw(::com::sun::star::uno::RuntimeException);
ZipEnumeration * SAL_CALL entries( );
protected:
sal_Bool readLOC ( ZipEntry &rEntry)
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 readCEN()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 findEND()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
sal_Int32 recover()
throw(::com::sun::star::io::IOException, com::sun::star::packages::zip::ZipException, com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief input クラス @n
数値、文字列などの入力クラス
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>
extern "C" {
char sci_getch(void);
};
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 標準入力ファンクタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class def_chainp {
const char* str_;
char last_;
bool unget_;
public:
def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }
void unget() {
unget_ = true;
}
char operator() () {
if(unget_) {
unget_ = false;
} else {
if(str_ == nullptr) {
last_ = sci_getch();
} else {
last_ = *str_;
if(last_ != 0) { ++str_; }
}
}
return last_;
}
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 汎用入力クラス
@param[in] INP 入力クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class INP>
class basic_input {
const char* form_;
INP inp_;
uint32_t bin_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {
a <<= 1;
a += ch - '0';
}
return a;
}
uint32_t oct_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {
a <<= 3;
a += ch - '0';
}
return a;
}
uint32_t dec_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {
a *= 10;
a += ch - '0';
}
return a;
}
uint32_t hex_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0) {
if(ch >= '0' && ch <= '9') {
a <<= 4;
a += ch - '0';
} else if(ch >= 'A' && ch <= 'F') {
a <<= 4;
a += ch - 'A' + 10;
} else if(ch >= 'a' && ch <= 'f') {
a <<= 4;
a += ch - 'a' + 10;
} else {
break;
}
}
return a;
}
enum class mode : uint8_t {
NONE,
BIN,
OCT,
DEC,
HEX,
};
mode mode_;
bool err_;
static uint16_t cnvcnt_;
enum class fmm : uint8_t {
none,
type,
};
void next_()
{
fmm cm = fmm::none;
char ch;
while((ch = *form_++) != 0) {
switch(cm) {
case fmm::none:
if(ch == '[') {
auto a = inp_();
const char* p = form_;
bool ok = false;
while((ch = *p++) != 0 && ch != ']') {
if(ch == a) ok = true;
}
form_ = p;
if(!ok) {
err_ = true;
return;
}
} else if(ch == '%' && *form_ != '%') {
cm = fmm::type;
} else if(ch != inp_()) {
err_ = true;
return;
}
break;
case fmm::type:
if(ch == 'b' || ch == 'B') {
mode_ = mode::BIN;
} else if(ch == 'o' || ch == 'O') {
mode_ = mode::OCT;
} else if(ch == 'd' || ch == 'D') {
mode_ = mode::DEC;
} else if(ch == 'x' || ch == 'X') {
mode_ = mode::HEX;
} else {
err_ = true;
}
return;
}
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] form 入力形式
@param[in] inp 変換文字列(nullptrの場合、sci_getch で取得)
*/
//-----------------------------------------------------------------//
basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),
mode_(mode::NONE), err_(false)
{
cnvcnt_ = 0;
next_();
}
//-----------------------------------------------------------------//
/*!
@brief 正常変換数を取得
@return 正常変換数
*/
//-----------------------------------------------------------------//
static uint16_t get_conversion() { return cnvcnt_; }
//-----------------------------------------------------------------//
/*!
@brief オペレーター「%」(int32_t)
@param[in] val 整数値
@return 自分の参照
*/
//-----------------------------------------------------------------//
basic_input& operator % (int32_t& val)
{
if(err_) return *this;
bool neg = false;
{
auto s = inp_();
if(s == '-') { neg = true; }
else if(s == '+') { neg = false; }
else inp_.unget();
}
uint32_t v = 0;
switch(mode_) {
case mode::BIN:
v = bin_();
break;
case mode::OCT:
v = oct_();
break;
case mode::DEC:
v = dec_();
break;
case mode::HEX:
v = hex_();
break;
default:
err_ = true;
break;
}
if(neg) val = -static_cast<int32_t>(v);
else val = static_cast<int32_t>(v);
if(!err_) {
++cnvcnt_;
inp_.unget();
next_();
}
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief オペレーター「%」(uint32_t)
@param[in] val 整数値
@return 自分の参照
*/
//-----------------------------------------------------------------//
basic_input& operator % (uint32_t& val)
{
if(err_) return *this;
uint32_t v = 0;
switch(mode_) {
case mode::BIN:
v = bin_();
break;
case mode::OCT:
v = oct_();
break;
case mode::DEC:
v = dec_();
break;
case mode::HEX:
v = hex_();
break;
default:
err_ = true;
break;
}
if(!err_) {
++cnvcnt_;
inp_.unget();
next_();
val = v;
}
return *this;
}
};
template<class INP> uint16_t basic_input<INP>::cnvcnt_;
typedef basic_input<def_chainp> input;
}
<commit_msg>update operator<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief input クラス @n
数値、文字列などの入力クラス
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <type_traits>
extern "C" {
char sci_getch(void);
};
namespace utils {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 標準入力ファンクタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class def_chainp {
const char* str_;
char last_;
bool unget_;
public:
def_chainp(const char* str = nullptr) : str_(str), last_(0), unget_(false) { }
void unget() {
unget_ = true;
}
char operator() () {
if(unget_) {
unget_ = false;
} else {
if(str_ == nullptr) {
last_ = sci_getch();
} else {
last_ = *str_;
if(last_ != 0) { ++str_; }
}
}
return last_;
}
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 汎用入力クラス
@param[in] INP 入力クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class INP>
class basic_input {
const char* form_;
INP inp_;
uint32_t bin_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '1') {
a <<= 1;
a += ch - '0';
}
return a;
}
uint32_t oct_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '7') {
a <<= 3;
a += ch - '0';
}
return a;
}
uint32_t dec_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0 && ch >= '0' && ch <= '9') {
a *= 10;
a += ch - '0';
}
return a;
}
uint32_t hex_() {
uint32_t a = 0;
char ch;
while((ch = inp_()) != 0) {
if(ch >= '0' && ch <= '9') {
a <<= 4;
a += ch - '0';
} else if(ch >= 'A' && ch <= 'F') {
a <<= 4;
a += ch - 'A' + 10;
} else if(ch >= 'a' && ch <= 'f') {
a <<= 4;
a += ch - 'a' + 10;
} else {
break;
}
}
return a;
}
enum class mode : uint8_t {
NONE,
BIN,
OCT,
DEC,
HEX,
};
mode mode_;
bool err_;
int num_;
enum class fmm : uint8_t {
none,
type,
};
void next_()
{
fmm cm = fmm::none;
char ch;
while((ch = *form_++) != 0) {
switch(cm) {
case fmm::none:
if(ch == '[') {
auto a = inp_();
const char* p = form_;
bool ok = false;
while((ch = *p++) != 0 && ch != ']') {
if(ch == a) ok = true;
}
form_ = p;
if(!ok) {
err_ = true;
return;
}
} else if(ch == '%' && *form_ != '%') {
cm = fmm::type;
} else if(ch != inp_()) {
err_ = true;
return;
}
break;
case fmm::type:
if(ch == 'b' || ch == 'B') {
mode_ = mode::BIN;
} else if(ch == 'o' || ch == 'O') {
mode_ = mode::OCT;
} else if(ch == 'd' || ch == 'D') {
mode_ = mode::DEC;
} else if(ch == 'x' || ch == 'X') {
mode_ = mode::HEX;
} else {
err_ = true;
}
return;
}
}
if(ch == 0 && inp_() == 0) ;
else {
err_ = true;
}
}
int32_t nb_(bool sign = true)
{
bool neg = false;
if(sign) {
auto s = inp_();
if(s == '-') { neg = true; }
else if(s == '+') { neg = false; }
else inp_.unget();
}
uint32_t v = 0;
switch(mode_) {
case mode::BIN:
v = bin_();
break;
case mode::OCT:
v = oct_();
break;
case mode::DEC:
v = dec_();
break;
case mode::HEX:
v = hex_();
break;
default:
err_ = true;
break;
}
if(!err_) {
inp_.unget();
next_();
if(!err_) ++num_;
}
if(neg) return -static_cast<int32_t>(v);
else return static_cast<int32_t>(v);
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] form 入力形式
@param[in] inp 変換文字列(nullptrの場合、sci_getch で取得)
*/
//-----------------------------------------------------------------//
basic_input(const char* form, const char* inp = nullptr) : form_(form), inp_(inp),
mode_(mode::NONE), err_(false), num_(0)
{
next_();
}
//-----------------------------------------------------------------//
/*!
@brief 正常変換数を取得
@return 正常変換数
*/
//-----------------------------------------------------------------//
int num() const { return num_; }
//-----------------------------------------------------------------//
/*!
@brief テンプレート・オペレーター「%」
@param[in] val 整数型
@return 自分の参照
*/
//-----------------------------------------------------------------//
template <typename T>
basic_input& operator % (T& val)
{
if(err_) return *this;
val = nb_(!std::is_signed<T>::value);
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief オペレーター「=」
*/
//-----------------------------------------------------------------//
basic_input& operator = (const basic_input& in) { return *this; }
};
typedef basic_input<def_chainp> input;
}
<|endoftext|>
|
<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
private:
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
private:
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
void bind_to_texture();
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<commit_msg>Muokattu kommentteja.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
private:
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
private:
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
void bind_to_texture();
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // coordinate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<|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/message_box.h"
namespace atom {
int ShowMessageBox(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail) {
return 0;
}
} // namespace atom
<commit_msg>[Win] Show an empty window for ShowMessageBox.<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/message_box.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/utf_string_conversions.h"
#include "browser/native_window.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/client_view.h"
namespace atom {
namespace {
class MessageDialog : public base::MessageLoop::Dispatcher,
public views::WidgetDelegate,
public views::ButtonListener {
public:
MessageDialog(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail);
virtual ~MessageDialog();
private:
// Overridden from MessageLoop::Dispatcher:
virtual bool Dispatch(const base::NativeEvent& event) OVERRIDE;
// Overridden from views::Widget:
virtual void WindowClosing() OVERRIDE;
virtual views::Widget* GetWidget() OVERRIDE;
virtual const views::Widget* GetWidget() const OVERRIDE;
virtual views::ClientView* CreateClientView(views::Widget* widget) OVERRIDE;
// Overridden from views::ButtonListener:
virtual void ButtonPressed(views::Button* sender,
const ui::Event& event) OVERRIDE;
bool should_close_;
views::Widget* widget_;
views::MessageBoxView* message_box_view_;
DISALLOW_COPY_AND_ASSIGN(MessageDialog);
};
////////////////////////////////////////////////////////////////////////////////
// MessageDialog, public:
MessageDialog::MessageDialog(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail)
: should_close_(false) {
views::MessageBoxView::InitParams params(UTF8ToUTF16(title));
params.message = UTF8ToUTF16(message);
message_box_view_ = new views::MessageBoxView(params);
views::Widget::InitParams widget_params;
widget_params.delegate = this;
if (parent_window)
widget_params.parent = parent_window->GetNativeWindow();
widget_ = new views::Widget;
widget_->Init(widget_params);
widget_->Show();
}
MessageDialog::~MessageDialog() {
}
////////////////////////////////////////////////////////////////////////////////
// MessageDialog, private:
bool MessageDialog::Dispatch(const base::NativeEvent& event) {
TranslateMessage(&event);
DispatchMessage(&event);
return !should_close_;
}
void MessageDialog::WindowClosing() {
should_close_ = true;
}
views::Widget* MessageDialog::GetWidget() {
return widget_;
}
const views::Widget* MessageDialog::GetWidget() const {
return widget_;
}
views::ClientView* MessageDialog::CreateClientView(views::Widget* widget) {
return new views::ClientView(widget, message_box_view_);
}
void MessageDialog::ButtonPressed(views::Button* sender,
const ui::Event& event) {
}
} // namespace
int ShowMessageBox(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail) {
MessageDialog dialog(parent_window, type, buttons, title, message, detail);
{
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoopForUI::current());
base::RunLoop run_loop(&dialog);
run_loop.Run();
}
return 0;
}
} // namespace atom
<|endoftext|>
|
<commit_before>#ifndef SYNCHRONIZE_LOCKS_NUM
# define SYNCHRONIZE_LOCKS_NUM 0x100
#endif
#ifndef READ_SIDE_PARALLELISM
# define READ_SIDE_PARALLELISM 0x8
#endif
#include <iostream>
#include <array>
#include <mutex>
#include <memory>
#include <functional>
#include <algorithm>
#include <thread>
namespace syncope {
namespace detail {
class LockLayerImpl {
enum {
N = SYNCHRONIZE_LOCKS_NUM
};
static_assert((N & (N - 1)) == 0, "N (SYNCHRONIZE_LOCKS_NUM) must be a power of two");
static const int MASK = N - 1;
typedef std::recursive_mutex MutexT;
mutable std::array<MutexT, N> mutexes_;
const char* name_;
public:
LockLayerImpl(const char* name) : name_(name) {}
LockLayerImpl(LockLayerImpl const&) = delete;
LockLayerImpl& operator = (LockLayerImpl const&) = delete;
void lock(size_t hash) const {
size_t ix = hash & MASK;
mutexes_[ix].lock();
}
void unlock(size_t hash) const {
size_t ix = hash & MASK;
mutexes_[ix].unlock();
}
};
} // namespace detail
// namespace locks
template<class Hash, class T>
class LockGuard {
T const* ptr_;
detail::LockLayerImpl& lock_pool_;
Hash hash_;
void lock() const {
lock_pool_.lock(hash_(reinterpret_cast<size_t>(ptr_)));
}
void unlock() const {
lock_pool_.unlock(hash_(reinterpret_cast<size_t>(ptr_)));
}
public:
LockGuard(T const* ptr, detail::LockLayerImpl& lockpool) : ptr_(ptr), lock_pool_(lockpool) {
lock();
}
LockGuard(LockGuard const&) = delete;
LockGuard& operator = (LockGuard const&) = delete;
LockGuard(LockGuard&& other) : ptr_(other.ptr_), lock_pool_(other.lock_pool_) {
other.ptr_ = nullptr;
}
LockGuard& operator = (LockGuard&& other) {
ptr_ = other.ptr_;
other.ptr_ = nullptr;
assert(&lock_pool_ == &other.lock_pool_);
}
~LockGuard() {
if (ptr_ != nullptr) {
unlock();
}
}
};
template<class Hash, int P, typename... T>
class LockGuardMany {
enum {
H = sizeof...(T)*P // hashes array size (can be greater than sizeof...(T))
};
detail::LockLayerImpl& impl_;
std::array<size_t, H> hashes_;
template<int I, int M, int H>
struct fill_hashes
{
void operator () (std::array<size_t, H>& hashes, std::tuple<T const*...> const& items) {
Hash hash;
const auto p = std::get<I>(items);
for (int i = 0; i < P; i++) {
size_t h = hash(reinterpret_cast<size_t>(p), i);
hashes[I*P + i] = h;
}
fill_hashes<I + 1, M, H> fh;
fh(hashes, items);
}
};
template<int M, int H>
struct fill_hashes<M, M, H>{
void operator() (std::array<size_t, H>& hashes, std::tuple<T const*...> const& items) {}
};
void lock() const {
for (auto h: hashes_) {
impl_.lock(h);
}
}
void unlock() const {
for (auto it = hashes_.crbegin(); it != hashes_.crend(); it++) {
impl_.unlock(*it);
}
}
public:
LockGuardMany(detail::LockLayerImpl& impl, T const*... others)
: impl_(impl)
{
auto all = std::tie(others...);
fill_hashes<0, sizeof...(others), H> fill_all;
fill_all(hashes_, all);
std::sort(hashes_.begin(), hashes_.end());
lock();
}
~LockGuardMany() {
unlock();
}
};
namespace detail {
class StaticString {
const char* str_;
public:
StaticString(const char* s) : str_(s) {
// TODO: assert(string is static)
}
const char* str() const { return str_; }
};
//! Simple hash - uses std::hash internally
struct SimpleHash {
size_t operator() (size_t value) const {
std::hash<size_t> hash;
return hash(value);
}
};
//! Simple hash - uses std::hash and ignores bias
struct SimpleHash2 {
size_t operator() (size_t value, int bias) const {
std::hash<size_t> hash;
return hash(value);
}
};
template<int P>
struct BiasedHash {
static_assert((P & (P - 1)) == 0, "P must be a power of two");
size_t operator() (size_t value) const {
std::hash<size_t> hash;
std::hash<std::thread::id> thash;
auto id = std::this_thread::get_id();
size_t bias = thash(id);
return hash(value) + (bias & (P - 1));
}
};
template<int P>
struct BiasedHash2 {
static_assert((P & (P - 1)) == 0, "P must be a power of two");
size_t operator() (size_t value, int bias) const {
std::hash<size_t> hash;
return hash(value) + (bias & (P - 1));
}
};
}
/** Lock hierarchy layer.
*/
class SymmetricLockLayer {
detail::LockLayerImpl impl_;
public:
/** C-tor
* @param name statically initialized string
*/
SymmetricLockLayer(detail::StaticString name) : impl_(name.str()) {}
template<class T>
LockGuard<detail::SimpleHash, T> synchronize(T const* ptr) {
return std::move(LockGuard<detail::SimpleHash, T>(ptr, impl_));
}
template<typename... T>
LockGuardMany<detail::SimpleHash2, 1, T...> synchronize(T const*... args) {
return std::move(LockGuardMany<detail::SimpleHash2, 1, T...>(impl_, args...));
}
};
/** Asymmetric lock hierarchy layer.
*/
class AsymmetricLockLayer {
detail::LockLayerImpl impl_;
enum {
P = READ_SIDE_PARALLELISM // Parallelism factor for readers and writers
};
public:
/** C-tor
* @param name statically initialized string
*/
AsymmetricLockLayer(detail::StaticString name) : impl_(name.str()) {}
template<class T>
LockGuard<detail::BiasedHash<P>, T> read_lock(T const* ptr) {
return std::move(LockGuard<detail::BiasedHash<P>, T>(ptr, impl_));
}
template<typename... T>
LockGuardMany<detail::BiasedHash2<P>, P, T...> write_lock(T const*... args) {
return std::move(LockGuardMany<detail::BiasedHash2<P>, P, T...>(impl_, args...));
}
};
} // namespace syncope
#define STATIC_STRING(x) locks::detail::StaticString(x"")
<commit_msg>Errors fixed<commit_after>#ifndef SYNCHRONIZE_LOCKS_NUM
# define SYNCHRONIZE_LOCKS_NUM 0x100
#endif
#ifndef READ_SIDE_PARALLELISM
# define READ_SIDE_PARALLELISM 0x8
#endif
#include <iostream>
#include <array>
#include <mutex>
#include <memory>
#include <functional>
#include <algorithm>
#include <thread>
namespace syncope {
namespace detail {
class LockLayerImpl {
enum {
N = SYNCHRONIZE_LOCKS_NUM
};
static_assert((N & (N - 1)) == 0, "N (SYNCHRONIZE_LOCKS_NUM) must be a power of two");
static const int MASK = N - 1;
typedef std::recursive_mutex MutexT;
mutable std::array<MutexT, N> mutexes_;
const char* name_;
public:
LockLayerImpl(const char* name) : name_(name) {}
LockLayerImpl(LockLayerImpl const&) = delete;
LockLayerImpl& operator = (LockLayerImpl const&) = delete;
void lock(size_t hash) const {
size_t ix = hash & MASK;
mutexes_[ix].lock();
}
void unlock(size_t hash) const {
size_t ix = hash & MASK;
mutexes_[ix].unlock();
}
};
} // namespace detail
// namespace locks
template<class T>
class LockGuard {
size_t value_;
bool owns_lock_;
detail::LockLayerImpl& lock_pool_;
void lock() {
lock_pool_.lock(value_);
owns_lock_ = true;
}
void unlock() {
lock_pool_.unlock(value_);
owns_lock_ = false;
}
public:
template<typename Hash>
LockGuard(T const* ptr, detail::LockLayerImpl& lockpool, Hash const& hash)
: value_(hash(reinterpret_cast<size_t>(ptr)))
, owns_lock_(false)
, lock_pool_(lockpool)
{
lock();
}
LockGuard(LockGuard const&) = delete;
LockGuard& operator = (LockGuard const&) = delete;
LockGuard(LockGuard&& other)
: value_(other.value_)
, owns_lock_(other.owns_lock_)
, lock_pool_(other.lock_pool_)
{
other.owns_lock_ = false;
}
LockGuard& operator = (LockGuard&& other) {
value_ = other.value_;
other.owns_lock_ = false;
assert(&lock_pool_ == &other.lock_pool_);
}
~LockGuard() {
if (owns_lock_) {
unlock();
}
}
};
template<int P, typename... T>
class LockGuardMany {
enum {
H = sizeof...(T)*P // hashes array size (can be greater than sizeof...(T))
};
detail::LockLayerImpl& impl_;
std::array<size_t, H> hashes_;
bool owns_lock_;
template<int I, int M, int H>
struct fill_hashes
{
template<typename Hash>
void operator () (std::array<size_t, H>& hashes, std::tuple<T const*...> const& items, Hash const& hash) {
const auto p = std::get<I>(items);
for (int i = 0; i < P; i++) {
size_t h = hash(reinterpret_cast<size_t>(p), i);
hashes[I*P + i] = h;
}
fill_hashes<I + 1, M, H> fh;
fh(hashes, items, hash);
}
};
template<int M, int H>
struct fill_hashes<M, M, H>{
template<typename Hash>
void operator() (std::array<size_t, H>& hashes, std::tuple<T const*...> const& items, Hash const& hash) {}
};
void lock() {
for (auto h: hashes_) {
impl_.lock(h);
}
owns_lock_ = true;
}
void unlock() {
for (auto it = hashes_.crbegin(); it != hashes_.crend(); it++) {
impl_.unlock(*it);
}
owns_lock_ = false;
}
public:
template<typename Hash>
LockGuardMany(detail::LockLayerImpl& impl, Hash const& hash, T const*... others)
: impl_(impl)
, owns_lock_(false)
{
auto all = std::tie(others...);
fill_hashes<0, sizeof...(others), H> fill_all;
fill_all(hashes_, all, hash);
std::sort(hashes_.begin(), hashes_.end());
lock();
}
~LockGuardMany() {
unlock();
}
LockGuardMany(LockGuardMany const&) = delete;
LockGuardMany& operator = (LockGuardMany const&) = delete;
LockGuardMany(LockGuardMany&& other)
: impl_(other.impl_)
, owns_lock_(other.owns_lock_)
{
std::swap(hashes_, other.hashes_);
other.owns_lock_ = false;
}
LockGuardMany& operator = (LockGuardMany&& other) {
assert(&other.impl_ == &impl_);
std::swap(hashes_, other.hashes_);
owns_lock_ = other.owns_lock_;
other.owns_lock_ = false;
}
};
namespace detail {
class StaticString {
const char* str_;
public:
StaticString(const char* s) : str_(s) {
// TODO: assert(string is static)
}
const char* str() const { return str_; }
};
//! Simple hash - simply returns it's argument
struct SimpleHash {
size_t operator() (size_t value) const {
return value;
}
};
//! Simple hash
struct SimpleHash2 {
size_t operator() (size_t value, int bias) const {
return value;
}
};
template<int P>
struct BiasedHash {
static_assert((P & (P - 1)) == 0, "P must be a power of two");
size_t operator() (size_t value) const {
std::hash<std::thread::id> hash;
auto id = std::this_thread::get_id();
size_t bias = hash(id);
return value + (bias & (P - 1));
}
};
template<int P>
struct BiasedHash2 {
static_assert((P & (P - 1)) == 0, "P must be a power of two");
size_t operator() (size_t value, int bias) const {
return value + (bias & (P - 1));
}
};
}
/** Lock hierarchy layer.
*/
class SymmetricLockLayer {
detail::LockLayerImpl impl_;
public:
/** C-tor
* @param name statically initialized string
*/
SymmetricLockLayer(detail::StaticString name) : impl_(name.str()) {}
template<class T>
LockGuard<T> synchronize(T const* ptr) {
return std::move(LockGuard<T>(ptr, impl_, detail::SimpleHash()));
}
template<typename... T>
LockGuardMany<1, T...> synchronize(T const*... args) {
return std::move(LockGuardMany<1, T...>(impl_, detail::SimpleHash2(), args...));
}
};
/** Asymmetric lock hierarchy layer.
*/
class AsymmetricLockLayer {
detail::LockLayerImpl impl_;
enum {
P = READ_SIDE_PARALLELISM // Parallelism factor for readers and writers
};
public:
/** C-tor
* @param name statically initialized string
*/
AsymmetricLockLayer(detail::StaticString name) : impl_(name.str()) {}
template<class T>
LockGuard<T> read_lock(T const* ptr) {
return std::move(LockGuard<T>(ptr, impl_, detail::BiasedHash<P>()));
}
template<typename... T>
LockGuardMany<P, T...> write_lock(T const*... args) {
return std::move(LockGuardMany<P, T...>(impl_, detail::BiasedHash2<P>(), args...));
}
};
} // namespace syncope
#define STATIC_STRING(x) syncope::detail::StaticString(x"")
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@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; 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 "engineuwsgi.h"
#include "plugin.h"
#include <Cutelyst/Application>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
using namespace Cutelyst;
static QList<EngineUwsgi *> coreEngines;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
/**
* This function is called as soon as
* the plugin is loaded
*/
extern "C" void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
(void) new QCoreApplication(uwsgi.argc, uwsgi.argv);
if (qEnvironmentVariableIsEmpty("CUTELYST_NO_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
}
extern "C" int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
uwsgi.loop = (char *) "CutelystQtLoop";
return 0;
}
extern "C" void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
extern "C" int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines.at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
#ifdef UWSGI_GO_CHEAP_CODE // Actually we only need uwsgi 2.0.1
static void fsmon_reload(struct uwsgi_fsmon *fs)
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due to file change";
uwsgi_reload(uwsgi.argv);
}
#endif // UWSGI_GO_CHEAP_CODE
/**
* This function is called when the master process is exiting
*/
extern "C" void uwsgi_cutelyst_master_cleanup()
{
qCDebug(CUTELYST_UWSGI) << "Master process finishing" << QCoreApplication::applicationPid();
delete qApp;
qCDebug(CUTELYST_UWSGI) << "Master process finished" << QCoreApplication::applicationPid();
}
/**
* This function is called when the child process is exiting
*/
extern "C" void uwsgi_cutelyst_atexit()
{
uwsgi_log("Child process finishing: %d\n", QCoreApplication::applicationPid());
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
engine->stop();
}
qDeleteAll(coreEngines);
uwsgi_log("Child process finished: %d\n", QCoreApplication::applicationPid());
}
extern "C" void uwsgi_cutelyst_init_apps()
{
QString path(options.app);
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
uwsgi_log("Cutelyst loading application: \"%s\"\n", options.app);
#ifdef UWSGI_GO_CHEAP_CODE
if (options.reload) {
// Register application auto reload
char *file = qstrdup(path.toUtf8().constData());
uwsgi_register_fsmon(file, fsmon_reload, NULL);
}
#endif // UWSGI_GO_CHEAP_CODE
QString config(options.config);
if (!config.isNull()) {
qputenv("CUTELYST_CONFIG", config.toUtf8());
}
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
uwsgi_log("Could not load application: %s\n", loader->errorString().data());
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
uwsgi_log("Could not get a QObject instance: %s\n", loader->errorString().data());
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
uwsgi_log("Could not cast Cutelyst::Application from instance: %s\n", loader->errorString().data());
exit(1);
}
EngineUwsgi *mainEngine = new EngineUwsgi(app);
if (!mainEngine->initApplication(app, false)) {
uwsgi_log("Failed to init application.\n");
exit(1);
}
coreEngines.append(mainEngine);
EngineUwsgi *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1 && i > 0) {
engine = new EngineUwsgi(app);
engine->setThread(new QThread);
// Post fork might fail when on threaded mode
QObject::connect(engine, &EngineUwsgi::engineDisabled,
mainEngine, &EngineUwsgi::reuseEngineRequests);
coreEngines.append(engine);
}
// Add core request
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
engine->addUnusedRequest(wsgi_req);
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
}
}
<commit_msg>uWSGI Engine Wait 2 seconds to the application file to be filed when auto reload is enabled<commit_after>/*
* Copyright (C) 2013-2014 Daniel Nicoletti <dantti12@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; 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 "engineuwsgi.h"
#include "plugin.h"
#include <Cutelyst/Application>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QPluginLoader>
#include <QFileInfo>
using namespace Cutelyst;
static QList<EngineUwsgi *> coreEngines;
void cuteOutput(QtMsgType, const QMessageLogContext &, const QString &);
void uwsgi_cutelyst_loop(void);
/**
* This function is called as soon as
* the plugin is loaded
*/
extern "C" void uwsgi_cutelyst_on_load()
{
uwsgi_register_loop( (char *) "CutelystQtLoop", uwsgi_cutelyst_loop);
(void) new QCoreApplication(uwsgi.argc, uwsgi.argv);
if (qEnvironmentVariableIsEmpty("CUTELYST_NO_UWSGI_LOG")) {
qInstallMessageHandler(cuteOutput);
}
}
extern "C" int uwsgi_cutelyst_init()
{
uwsgi_log("Initializing Cutelyst plugin\n");
uwsgi.loop = (char *) "CutelystQtLoop";
return 0;
}
extern "C" void uwsgi_cutelyst_post_fork()
{
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
if (engine->thread() != qApp->thread()) {
engine->thread()->start();
} else {
Q_EMIT engine->postFork();
}
}
}
extern "C" int uwsgi_cutelyst_request(struct wsgi_request *wsgi_req)
{
// empty request ?
if (!wsgi_req->uh->pktsize) {
qCDebug(CUTELYST_UWSGI) << "Empty request. skip.";
return -1;
}
// get uwsgi variables
if (uwsgi_parse_vars(wsgi_req)) {
qCDebug(CUTELYST_UWSGI) << "Invalid request. skip.";
return -1;
}
coreEngines.at(wsgi_req->async_id)->processRequest(wsgi_req);
return UWSGI_OK;
}
#ifdef UWSGI_GO_CHEAP_CODE // Actually we only need uwsgi 2.0.1
static void fsmon_reload(struct uwsgi_fsmon *fs)
{
qCDebug(CUTELYST_UWSGI) << "Reloading application due to file change";
QFileInfo fileInfo(fs->path);
int count = 0;
// Ugly hack to wait for 2 seconds for the file to be filled
while (fileInfo.size() == 0 && count < 10) {
++count;
qCDebug(CUTELYST_UWSGI) << "Sleeping as the application file is empty" << count;
usleep(200 * 1000);
fileInfo.refresh();
}
uwsgi_reload(uwsgi.argv);
}
#endif // UWSGI_GO_CHEAP_CODE
/**
* This function is called when the master process is exiting
*/
extern "C" void uwsgi_cutelyst_master_cleanup()
{
qCDebug(CUTELYST_UWSGI) << "Master process finishing" << QCoreApplication::applicationPid();
delete qApp;
qCDebug(CUTELYST_UWSGI) << "Master process finished" << QCoreApplication::applicationPid();
}
/**
* This function is called when the child process is exiting
*/
extern "C" void uwsgi_cutelyst_atexit()
{
uwsgi_log("Child process finishing: %d\n", QCoreApplication::applicationPid());
Q_FOREACH (EngineUwsgi *engine, coreEngines) {
engine->stop();
}
qDeleteAll(coreEngines);
uwsgi_log("Child process finished: %d\n", QCoreApplication::applicationPid());
}
extern "C" void uwsgi_cutelyst_init_apps()
{
QString path(options.app);
if (path.isEmpty()) {
uwsgi_log("Cutelyst application name or path was not set\n");
exit(1);
}
uwsgi_log("Cutelyst loading application: \"%s\"\n", options.app);
#ifdef UWSGI_GO_CHEAP_CODE
if (options.reload) {
// Register application auto reload
char *file = qstrdup(path.toUtf8().constData());
uwsgi_register_fsmon(file, fsmon_reload, NULL);
}
#endif // UWSGI_GO_CHEAP_CODE
QString config(options.config);
if (!config.isNull()) {
qputenv("CUTELYST_CONFIG", config.toUtf8());
}
QPluginLoader *loader = new QPluginLoader(path);
if (!loader->load()) {
uwsgi_log("Could not load application: %s\n", loader->errorString().data());
exit(1);
}
QObject *instance = loader->instance();
if (!instance) {
uwsgi_log("Could not get a QObject instance: %s\n", loader->errorString().data());
exit(1);
}
Application *app = qobject_cast<Application *>(instance);
if (!app) {
uwsgi_log("Could not cast Cutelyst::Application from instance: %s\n", loader->errorString().data());
exit(1);
}
EngineUwsgi *mainEngine = new EngineUwsgi(app);
if (!mainEngine->initApplication(app, false)) {
uwsgi_log("Failed to init application.\n");
exit(1);
}
coreEngines.append(mainEngine);
EngineUwsgi *engine = mainEngine;
for (int i = 0; i < uwsgi.cores; ++i) {
// Create the desired threads
// i > 0 the main thread counts as one thread
if (uwsgi.threads > 1 && i > 0) {
engine = new EngineUwsgi(app);
engine->setThread(new QThread);
// Post fork might fail when on threaded mode
QObject::connect(engine, &EngineUwsgi::engineDisabled,
mainEngine, &EngineUwsgi::reuseEngineRequests);
coreEngines.append(engine);
}
// Add core request
struct wsgi_request *wsgi_req = new wsgi_request;
memset(wsgi_req, 0, sizeof(struct wsgi_request));
wsgi_req->async_id = i;
engine->addUnusedRequest(wsgi_req);
}
// register a new app under a specific "mountpoint"
uwsgi_add_app(1, CUTELYST_MODIFIER1, (char *) "", 0, NULL, NULL);
delete loader;
}
void uwsgi_cutelyst_watch_signal(int signalFD)
{
QSocketNotifier *socketNotifier = new QSocketNotifier(signalFD, QSocketNotifier::Read);
QObject::connect(socketNotifier, &QSocketNotifier::activated,
[=](int fd) {
socketNotifier->setEnabled(false);
uwsgi_receive_signal(fd, (char *) "worker", uwsgi.mywid);
socketNotifier->setEnabled(true);
});
}
void uwsgi_cutelyst_loop()
{
// ensure SIGPIPE is ignored
signal(SIGPIPE, SIG_IGN);
// FIX for some reason this is not being set by UWSGI
uwsgi.wait_read_hook = uwsgi_simple_wait_read_hook;
// monitor signals
if (uwsgi.signal_socket > -1) {
uwsgi_cutelyst_watch_signal(uwsgi.signal_socket);
uwsgi_cutelyst_watch_signal(uwsgi.my_signal_socket);
}
// start the qt event loop
qApp->exec();
}
void cuteOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
uwsgi_log("%s[debug] %s\n", context.category, localMsg.constData());
break;
case QtWarningMsg:
uwsgi_log("%s[warn] %s\n", context.category, localMsg.constData());
break;
case QtCriticalMsg:
uwsgi_log("%s[crit] %s\n", context.category, localMsg.constData());
break;
case QtFatalMsg:
uwsgi_log("%s[fatal] %s\n", context.category, localMsg.constData());
abort();
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stack>
using namesspace std;
int evaluateOp(char operator,int numberStack, char operatorStack)
{
int leftValue = numberStack.pop();
int rightValue = numberStack.pop();
int result;
switch(operator)
{
case '+':
result = leftValue + rightValue;
return result;
break;
case '-':
result = leftValue - rightValue;
return result;
break;
}
}
int main()
{
/* code */
return 0;
}
//changes each token
istringstream tokens();
char nextChar;
stack<int> numberStack;
stack<char> operatorStack;
while (tokens >> nextChar){
if (isdigit(nextChar)){
tokens.push() //add to integer stack
int number;
tokens >> number; //converts the characters to ints
numberStack.push(number);
}
else if (isOperator(nextChar)){
int weight = precedenceOfOperator(nextChar);
int stackWeight = precedenceOfOperator(operatorStack.top())
if(weight >= stackWeight)
{
operatorStack.push(nextChar);
}
else
{
}
}
else{
throw caseErrors(" ");
}
}<commit_msg>almost complete evaluateOp<commit_after>#include <iostream>
#include <cmath>
#include <stack>
using namesspace std;
int evaluateOp(char theOperator,int numberStack, char operatorStack)
{
int leftValue = numberStack.pop();
int rightValue = numberStack.pop();
int result;
switch(theOperator)
{
case '+'://adds the two number and returns the value
result = leftValue + rightValue;
return result;
break;
case '-'://subtracts the two number and returns the value
result = leftValue - rightValue;
return result;
break;
case '/'://divides the two number and returns the value
result = leftValue / rightValue;
return result;
break;
case '*'://multiplies the two number and returns the value
result = leftValue * rightValue;
return result;
break;
case'^'://exponent
result = pow(leftValue, rightValue);
return result;
break;
case'%'://mod operator
result = leftValue % rightValue;
return result;
break;
case'!'://logical not
result = 0; //false
return result;
break;
case'A'://increments the left value by one ++
leftValue++;
return leftValue;
break;
case'B'://decrements the left value by one --
leftValue--;
return leftValue;
break;
case'C'://checks to see if two values are equal ==
if (leftValue == rightValue)//if they're equal return 1 for true
{
result = 1;//true
return result;
}
else//else return 0 for false
{
result = 0;//false
return result;
}
break;
case'D'://checks to see if left value is not equal to right value !=
if (leftValue != rightValue)//returns true(1) if they are not equal
{
result = 1;//true
return result;
}
else//if they are equal returns false(0)
{
result = 0;//false
return result;
}
break;
case'E'://logical and operator &&
break;
case'F'://logical or operator ||
result = 1;//true
return result;
break;
case'G'://greater than or equal
if (leftValue >= rightValue)
{
result = 1;//true
return result;
}
else
{
result = 0;//false
return result;
}
break;
case'H'://less than or equal
if (leftValue <= rightValue)
{
result = 1;//true
return result;
}
else
{
result = 0;//false
return result;
}
break;
case'I'://negative
result = leftValue * -1;
return result;
break;
}
}
int main()
{
/* code */
return 0;
}
//changes each token
istringstream tokens();
char nextChar;
stack<int> numberStack;
stack<char> operatorStack;
while (tokens >> nextChar){
if (isdigit(nextChar)){
tokens.push() //add to integer stack
int number;
tokens >> number; //converts the characters to ints
numberStack.push(number);
}
else if (isOperator(nextChar)){
int weight = precedenceOfOperator(nextChar);
int stackWeight = precedenceOfOperator(operatorStack.top())
if(weight >= stackWeight)
{
operatorStack.push(nextChar);
}
else
{
}
}
else{
throw caseErrors(" ");
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "debugutil_p.h"
#include <QEventLoop>
#include <QTimer>
bool QQmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
QObject::connect(receiver, member, &loop, SLOT(quit()));
timer.start(timeout);
loop.exec();
return timer.isActive();
}
QQmlDebugTestClient::QQmlDebugTestClient(const QString &s, QQmlDebugConnection *c)
: QQmlDebugClient(s, c)
{
}
QByteArray QQmlDebugTestClient::waitForResponse()
{
lastMsg.clear();
QQmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));
if (lastMsg.isEmpty()) {
qWarning() << "no response from server!";
return QByteArray();
}
return lastMsg;
}
void QQmlDebugTestClient::stateChanged(State stat)
{
QCOMPARE(stat, state());
emit stateHasChanged();
}
void QQmlDebugTestClient::messageReceived(const QByteArray &ba)
{
lastMsg = ba;
emit serverMessage(ba);
}
QQmlDebugProcess::QQmlDebugProcess(const QString &executable, QObject *parent)
: QObject(parent)
, m_executable(executable)
, m_started(false)
{
m_process.setProcessChannelMode(QProcess::MergedChannels);
m_timer.setSingleShot(true);
m_timer.setInterval(5000);
connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(processAppOutput()));
connect(&m_timer, SIGNAL(timeout()), SLOT(timeout()));
}
QQmlDebugProcess::~QQmlDebugProcess()
{
stop();
}
QString QQmlDebugProcess::state()
{
QString stateStr;
switch (m_process.state()) {
case QProcess::NotRunning: {
stateStr = "not running";
if (m_process.exitStatus() == QProcess::CrashExit)
stateStr += " (crashed!)";
else
stateStr += ", return value" + m_process.exitCode();
break;
}
case QProcess::Starting: stateStr = "starting"; break;
case QProcess::Running: stateStr = "running"; break;
}
return stateStr;
}
void QQmlDebugProcess::start(const QStringList &arguments)
{
m_mutex.lock();
m_process.setEnvironment(m_environment);
m_process.start(m_executable, arguments);
if (!m_process.waitForStarted()) {
qWarning() << "QML Debug Client: Could not launch app " << m_executable
<< ": " << m_process.errorString();
m_eventLoop.quit();
} else {
m_timer.start();
}
m_mutex.unlock();
}
void QQmlDebugProcess::stop()
{
if (m_process.state() != QProcess::NotRunning) {
m_process.kill();
m_process.waitForFinished(5000);
}
}
void QQmlDebugProcess::timeout()
{
qWarning() << "Timeout while waiting for QML debugging messages "
"in application output. Process is in state" << m_process.state() << ".";
m_eventLoop.quit();
}
bool QQmlDebugProcess::waitForSessionStart()
{
if (m_process.state() != QProcess::Running) {
qWarning() << "Could not start up " << m_executable;
return false;
}
m_eventLoop.exec();
return m_started;
}
void QQmlDebugProcess::setEnvironment(const QStringList &environment)
{
m_environment = environment;
}
QString QQmlDebugProcess::output() const
{
return m_output;
}
void QQmlDebugProcess::processAppOutput()
{
m_mutex.lock();
QString newOutput = m_process.readAll();
m_output.append(newOutput);
m_outputBuffer.append(newOutput);
while (true) {
const int nlIndex = m_outputBuffer.indexOf(QLatin1Char('\n'));
if (nlIndex < 0) // no further complete lines
break;
const QString line = m_outputBuffer.left(nlIndex);
m_outputBuffer = m_outputBuffer.right(m_outputBuffer.size() - nlIndex - 1);
if (line.contains("QML Debugger:")) {
if (line.contains("Waiting for connection ")) {
m_timer.stop();
m_started = true;
m_eventLoop.quit();
continue;
}
if (line.contains("Unable to listen")) {
qWarning() << "App was unable to bind to port!";
m_timer.stop();
m_eventLoop.quit();
continue;
}
}
}
m_mutex.unlock();
}
<commit_msg>When declarative debug tests fail in CI, confirm timeout as reason<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "debugutil_p.h"
#include <QEventLoop>
#include <QTimer>
bool QQmlDebugTest::waitForSignal(QObject *receiver, const char *member, int timeout) {
QEventLoop loop;
QTimer timer;
timer.setSingleShot(true);
QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
QObject::connect(receiver, member, &loop, SLOT(quit()));
timer.start(timeout);
loop.exec();
if (!timer.isActive())
qWarning("waitForSignal %s timed out after %d ms", member, timeout);
return timer.isActive();
}
QQmlDebugTestClient::QQmlDebugTestClient(const QString &s, QQmlDebugConnection *c)
: QQmlDebugClient(s, c)
{
}
QByteArray QQmlDebugTestClient::waitForResponse()
{
lastMsg.clear();
QQmlDebugTest::waitForSignal(this, SIGNAL(serverMessage(QByteArray)));
if (lastMsg.isEmpty()) {
qWarning() << "no response from server!";
return QByteArray();
}
return lastMsg;
}
void QQmlDebugTestClient::stateChanged(State stat)
{
QCOMPARE(stat, state());
emit stateHasChanged();
}
void QQmlDebugTestClient::messageReceived(const QByteArray &ba)
{
lastMsg = ba;
emit serverMessage(ba);
}
QQmlDebugProcess::QQmlDebugProcess(const QString &executable, QObject *parent)
: QObject(parent)
, m_executable(executable)
, m_started(false)
{
m_process.setProcessChannelMode(QProcess::MergedChannels);
m_timer.setSingleShot(true);
m_timer.setInterval(5000);
connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(processAppOutput()));
connect(&m_timer, SIGNAL(timeout()), SLOT(timeout()));
}
QQmlDebugProcess::~QQmlDebugProcess()
{
stop();
}
QString QQmlDebugProcess::state()
{
QString stateStr;
switch (m_process.state()) {
case QProcess::NotRunning: {
stateStr = "not running";
if (m_process.exitStatus() == QProcess::CrashExit)
stateStr += " (crashed!)";
else
stateStr += ", return value" + m_process.exitCode();
break;
}
case QProcess::Starting: stateStr = "starting"; break;
case QProcess::Running: stateStr = "running"; break;
}
return stateStr;
}
void QQmlDebugProcess::start(const QStringList &arguments)
{
m_mutex.lock();
m_process.setEnvironment(m_environment);
m_process.start(m_executable, arguments);
if (!m_process.waitForStarted()) {
qWarning() << "QML Debug Client: Could not launch app " << m_executable
<< ": " << m_process.errorString();
m_eventLoop.quit();
} else {
m_timer.start();
}
m_mutex.unlock();
}
void QQmlDebugProcess::stop()
{
if (m_process.state() != QProcess::NotRunning) {
m_process.kill();
m_process.waitForFinished(5000);
}
}
void QQmlDebugProcess::timeout()
{
qWarning() << "Timeout while waiting for QML debugging messages "
"in application output. Process is in state" << m_process.state() << ".";
m_eventLoop.quit();
}
bool QQmlDebugProcess::waitForSessionStart()
{
if (m_process.state() != QProcess::Running) {
qWarning() << "Could not start up " << m_executable;
return false;
}
m_eventLoop.exec();
return m_started;
}
void QQmlDebugProcess::setEnvironment(const QStringList &environment)
{
m_environment = environment;
}
QString QQmlDebugProcess::output() const
{
return m_output;
}
void QQmlDebugProcess::processAppOutput()
{
m_mutex.lock();
QString newOutput = m_process.readAll();
m_output.append(newOutput);
m_outputBuffer.append(newOutput);
while (true) {
const int nlIndex = m_outputBuffer.indexOf(QLatin1Char('\n'));
if (nlIndex < 0) // no further complete lines
break;
const QString line = m_outputBuffer.left(nlIndex);
m_outputBuffer = m_outputBuffer.right(m_outputBuffer.size() - nlIndex - 1);
if (line.contains("QML Debugger:")) {
if (line.contains("Waiting for connection ")) {
m_timer.stop();
m_started = true;
m_eventLoop.quit();
continue;
}
if (line.contains("Unable to listen")) {
qWarning() << "App was unable to bind to port!";
m_timer.stop();
m_eventLoop.quit();
continue;
}
}
}
m_mutex.unlock();
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QDir>
#include <QTextStream>
#include <QTimer>
#include "run-scenario.h"
RunScenario::RunScenario()
{
_rootDir = QDir::currentPath() + QDir::separator() + "dirs";
// Set up model.
_model.setReadOnly(true);
_model.setRootPath(_rootDir);
// In the GUI, we cannot select a file or directory until its parent
// directory has been loaded. This is not a perfect imitation of that
// scenario, but it is better than nothing.
while(needToReadSubdirs(_rootDir))
QCoreApplication::processEvents(0, 100);
}
RunScenario::~RunScenario()
{
}
bool RunScenario::needToReadSubdirs(const QString dirname)
{
bool loadingMore = false;
QModelIndex dir = _model.index(dirname);
// QFileSystemModel::canFetchMore(dir) can apparently lie about whether
// its has finished loading a directory. Alternatively, it might be
// designed to merely report that a directory has been *queued* to be
// read, but not actually read yet, and the Qt docs were simply written
// badly.
// Either way, we must ASSUME that every directory which contains 0 items
// has not finished being read from disk.
if(_model.isDir(dir) && _model.rowCount(dir) == 0)
{
_model.fetchMore(dir);
loadingMore = true;
}
for(int i = 0; i < _model.rowCount(dir); i++)
{
QModelIndex child = dir.child(i, dir.column());
if(_model.isDir(child))
{
if(_model.rowCount(child) == 0)
{
_model.fetchMore(child);
loadingMore = true;
}
if(needToReadSubdirs(_model.filePath(child)))
{
loadingMore = true;
}
}
}
return loadingMore;
}
// The format of these lines in the scenario file is:
// X filename
// where X is a single character, followed by a space.
QString RunScenario::getRelname(const QString line)
{
QString relname = line.right(line.size() - 2);
return relname;
}
QModelIndex RunScenario::getIndex(const QString line)
{
QString relname = getRelname(line);
QString filename = QDir(_rootDir).filePath(relname);
QModelIndex index = _model.index(filename);
return index;
}
int RunScenario::getLineState(const QString line)
{
int state = line[0].digitValue();
return state;
}
int RunScenario::getCheckedStateInt(const QString line)
{
QString relname = line.right(line.size() - 2);
QString filename = QDir(_rootDir).filePath(relname);
QModelIndex index = _model.index(filename);
int state = _model.data(index, Qt::CheckStateRole).toInt();
return state;
}
int RunScenario::processActions(QTextStream &in)
{
while(!in.atEnd())
{
QString line = in.readLine();
// Blank lines and comments.
if((line.size() == 0) || (line[0] == QChar('#')))
continue;
else if(line == "actions:")
continue;
else if(line == "results:")
break;
else if(line[0] == QChar('+'))
_model.setData(getIndex(line), Qt::Checked, Qt::CheckStateRole);
else if(line[0] == QChar('-'))
_model.setData(getIndex(line), Qt::Unchecked, Qt::CheckStateRole);
else
{
QTextStream console(stdout);
console << "ERROR: Scenario file is broken; parsing died on line:"
<< endl
<< line << endl;
// Don't try to recover.
QApplication::exit(1);
}
}
return (0);
}
// Returns 0 if success, 1 if a model error, 2 if an emit error.
int RunScenario::processResults(QTextStream &in)
{
while(!in.atEnd())
{
QString line = in.readLine();
// Blank lines and comments.
if((line.size() == 0) || (line[0] == QChar('#')))
continue;
else if(line == "results:")
continue;
else if((line[0] == QChar('0')) || (line[0] == QChar('1'))
|| (line[0] == QChar('2')))
{
QString lineRelname = getRelname(line);
int desiredState = getLineState(line);
int modelState = getCheckedStateInt(line);
if(desiredState != modelState)
{
// Test failed!
return (1);
}
}
else
{
QTextStream console(stdout);
console << "ERROR: Scenario file is broken; parsing died on line:"
<< endl
<< line << endl;
// Don't try to recover.
QApplication::exit(1);
}
}
return (0);
}
int RunScenario::runScenario(const int num)
{
int result = -1;
_model.reset();
QString scenarioFilename =
QString("scenario-%1.txt").arg(num, 2, 10, QChar('0'));
QFile inputFile(scenarioFilename);
if(inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
processActions(in);
result = processResults(in);
if(result != 0)
{
// Test failed!
QTextStream console(stdout);
console << "--" << endl
<< "Test failed: " << scenarioFilename << endl;
if(result == 1)
{
console << "Model internal state does not match "
<< "desired state. Model data:" << endl;
printModel();
}
console << "--" << endl << endl;
}
}
else
{
QTextStream console(stdout);
console << "ERROR: could not read file: " << scenarioFilename << endl;
// Don't try to recover.
QApplication::exit(1);
}
inputFile.close();
return (result);
}
void RunScenario::printDir(const QString dirname, const int depth)
{
QTextStream console(stdout);
QModelIndex index;
QModelIndex dir;
dir = _model.index(dirname);
for(int i = 0; i < _model.rowCount(dir); i++)
{
index = dir.child(i, dir.column());
console << _model.data(index, Qt::CheckStateRole).toInt() << "\t";
// Add indents to show the directory structure.
for(int j = 0; j < depth; j++)
console << "\t";
console << _model.fileName(index) << endl;
// Recursively print the subdirectory.
if(_model.isDir(index))
{
printDir(_model.filePath(index), depth + 1);
}
}
}
void RunScenario::printModel()
{
printDir(_model.rootPath(), 0);
}
<commit_msg>tests/customfilesystemmodel: use needToReadSubdirs()<commit_after>#include <QApplication>
#include <QDir>
#include <QTextStream>
#include <QTimer>
#include "run-scenario.h"
RunScenario::RunScenario()
{
_rootDir = QDir::currentPath() + QDir::separator() + "dirs";
// Set up model.
_model.setReadOnly(true);
_model.setRootPath(_rootDir);
// In the GUI, we cannot select a file or directory until its parent
// directory has been loaded. This is not a perfect imitation of that
// scenario, but it is better than nothing.
while(_model.needToReadSubdirs(_rootDir))
QCoreApplication::processEvents(0, 100);
}
RunScenario::~RunScenario()
{
}
// The format of these lines in the scenario file is:
// X filename
// where X is a single character, followed by a space.
QString RunScenario::getRelname(const QString line)
{
QString relname = line.right(line.size() - 2);
return relname;
}
QModelIndex RunScenario::getIndex(const QString line)
{
QString relname = getRelname(line);
QString filename = QDir(_rootDir).filePath(relname);
QModelIndex index = _model.index(filename);
return index;
}
int RunScenario::getLineState(const QString line)
{
int state = line[0].digitValue();
return state;
}
int RunScenario::getCheckedStateInt(const QString line)
{
QString relname = line.right(line.size() - 2);
QString filename = QDir(_rootDir).filePath(relname);
QModelIndex index = _model.index(filename);
int state = _model.data(index, Qt::CheckStateRole).toInt();
return state;
}
int RunScenario::processActions(QTextStream &in)
{
while(!in.atEnd())
{
QString line = in.readLine();
// Blank lines and comments.
if((line.size() == 0) || (line[0] == QChar('#')))
continue;
else if(line == "actions:")
continue;
else if(line == "results:")
break;
else if(line[0] == QChar('+'))
_model.setData(getIndex(line), Qt::Checked, Qt::CheckStateRole);
else if(line[0] == QChar('-'))
_model.setData(getIndex(line), Qt::Unchecked, Qt::CheckStateRole);
else
{
QTextStream console(stdout);
console << "ERROR: Scenario file is broken; parsing died on line:"
<< endl
<< line << endl;
// Don't try to recover.
QApplication::exit(1);
}
}
return (0);
}
// Returns 0 if success, 1 if a model error, 2 if an emit error.
int RunScenario::processResults(QTextStream &in)
{
while(!in.atEnd())
{
QString line = in.readLine();
// Blank lines and comments.
if((line.size() == 0) || (line[0] == QChar('#')))
continue;
else if(line == "results:")
continue;
else if((line[0] == QChar('0')) || (line[0] == QChar('1'))
|| (line[0] == QChar('2')))
{
QString lineRelname = getRelname(line);
int desiredState = getLineState(line);
int modelState = getCheckedStateInt(line);
if(desiredState != modelState)
{
// Test failed!
return (1);
}
}
else
{
QTextStream console(stdout);
console << "ERROR: Scenario file is broken; parsing died on line:"
<< endl
<< line << endl;
// Don't try to recover.
QApplication::exit(1);
}
}
return (0);
}
int RunScenario::runScenario(const int num)
{
int result = -1;
_model.reset();
QString scenarioFilename =
QString("scenario-%1.txt").arg(num, 2, 10, QChar('0'));
QFile inputFile(scenarioFilename);
if(inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
processActions(in);
result = processResults(in);
if(result != 0)
{
// Test failed!
QTextStream console(stdout);
console << "--" << endl
<< "Test failed: " << scenarioFilename << endl;
if(result == 1)
{
console << "Model internal state does not match "
<< "desired state. Model data:" << endl;
printModel();
}
console << "--" << endl << endl;
}
}
else
{
QTextStream console(stdout);
console << "ERROR: could not read file: " << scenarioFilename << endl;
// Don't try to recover.
QApplication::exit(1);
}
inputFile.close();
return (result);
}
void RunScenario::printDir(const QString dirname, const int depth)
{
QTextStream console(stdout);
QModelIndex index;
QModelIndex dir;
dir = _model.index(dirname);
for(int i = 0; i < _model.rowCount(dir); i++)
{
index = dir.child(i, dir.column());
console << _model.data(index, Qt::CheckStateRole).toInt() << "\t";
// Add indents to show the directory structure.
for(int j = 0; j < depth; j++)
console << "\t";
console << _model.fileName(index) << endl;
// Recursively print the subdirectory.
if(_model.isDir(index))
{
printDir(_model.filePath(index), depth + 1);
}
}
}
void RunScenario::printModel()
{
printDir(_model.rootPath(), 0);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/trace_database.h"
#include <functional>
namespace perfetto {
namespace trace_processor {
namespace {
constexpr uint32_t kTraceChunkSizeB = 16 * 1024 * 1024; // 16 MB
static const char kUIntColumnName[] = "UNSIGNED INT";
static const char kULongColumnName[] = "UNSIGNED BIG INT";
bool IsColumnUInt(const char* type) {
return strncmp(type, kUIntColumnName, sizeof(kUIntColumnName)) == 0;
}
bool IsColumnULong(const char* type) {
return strncmp(type, kULongColumnName, sizeof(kULongColumnName)) == 0;
}
} // namespace
TraceDatabase::TraceDatabase(base::TaskRunner* task_runner)
: task_runner_(task_runner), weak_factory_(this) {
static_assert(offsetof(TraceDatabase, db_) == 0,
"SQLite database must be the first field.");
sqlite3_open(":memory:", &db_);
// Setup the sched slice table.
static sqlite3_module module = SchedSliceTable::CreateModule();
sqlite3_create_module(db_, "sched", &module, static_cast<void*>(&storage_));
}
TraceDatabase::~TraceDatabase() {
sqlite3_close(db_);
}
void TraceDatabase::LoadTrace(BlobReader* reader,
std::function<void()> callback) {
// Reset storage and start a new trace parsing task.
storage_ = {};
parser_.reset(new TraceParser(reader, &storage_, kTraceChunkSizeB));
LoadTraceChunk(callback);
}
void TraceDatabase::ExecuteQuery(
const protos::RawQueryArgs& args,
std::function<void(protos::RawQueryResult)> callback) {
protos::RawQueryResult proto;
const auto& sql = args.sql_query();
sqlite3_stmt* stmt;
int err = sqlite3_prepare_v2(db_, sql.c_str(), static_cast<int>(sql.size()),
&stmt, nullptr);
if (err) {
callback(std::move(proto));
return;
}
for (int i = 0, size = sqlite3_column_count(stmt); i < size; i++) {
// Setup the descriptors.
auto* descriptor = proto.add_column_descriptors();
descriptor->set_name(sqlite3_column_name(stmt, i));
const char* type = sqlite3_column_decltype(stmt, i);
if (IsColumnUInt(type)) {
descriptor->set_type(protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_INT);
} else if (IsColumnULong(type)) {
descriptor->set_type(
protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_LONG);
} else {
PERFETTO_FATAL("Unexpected column type found in SQL query");
}
// Add the empty column to the proto.
proto.add_columns();
}
int row_count = 0;
for (int r = sqlite3_step(stmt); r == SQLITE_ROW; r = sqlite3_step(stmt)) {
for (int i = 0; i < proto.columns_size(); i++) {
auto* column = proto.mutable_columns(i);
switch (proto.column_descriptors(i).type()) {
case protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_LONG:
column->add_ulong_values(
static_cast<uint64_t>(sqlite3_column_int64(stmt, i)));
break;
case protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_INT:
column->add_uint_values(
static_cast<uint32_t>(sqlite3_column_double(stmt, i)));
break;
case protos::RawQueryResult_ColumnDesc_Type_INT:
case protos::RawQueryResult_ColumnDesc_Type_LONG:
case protos::RawQueryResult_ColumnDesc_Type_STRING:
PERFETTO_FATAL("Unexpected column type found in SQL query");
break;
}
}
row_count++;
}
proto.set_num_records(static_cast<uint64_t>(row_count));
callback(std::move(proto));
}
void TraceDatabase::LoadTraceChunk(std::function<void()> callback) {
bool has_more = parser_->ParseNextChunk();
if (!has_more) {
callback();
return;
}
auto weak_this = weak_factory_.GetWeakPtr();
task_runner_->PostTask([weak_this, callback] {
if (!weak_this)
return;
weak_this->LoadTraceChunk(callback);
});
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>trace_processor: fix build when offsetof was being used on non-POD am: 4ce4cb8263 am: 008381a2d7 am: d8f449b543<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/trace_database.h"
#include <functional>
namespace perfetto {
namespace trace_processor {
namespace {
constexpr uint32_t kTraceChunkSizeB = 16 * 1024 * 1024; // 16 MB
static const char kUIntColumnName[] = "UNSIGNED INT";
static const char kULongColumnName[] = "UNSIGNED BIG INT";
bool IsColumnUInt(const char* type) {
return strncmp(type, kUIntColumnName, sizeof(kUIntColumnName)) == 0;
}
bool IsColumnULong(const char* type) {
return strncmp(type, kULongColumnName, sizeof(kULongColumnName)) == 0;
}
} // namespace
TraceDatabase::TraceDatabase(base::TaskRunner* task_runner)
: task_runner_(task_runner), weak_factory_(this) {
sqlite3_open(":memory:", &db_);
// Setup the sched slice table.
static sqlite3_module module = SchedSliceTable::CreateModule();
sqlite3_create_module(db_, "sched", &module, static_cast<void*>(&storage_));
}
TraceDatabase::~TraceDatabase() {
sqlite3_close(db_);
}
void TraceDatabase::LoadTrace(BlobReader* reader,
std::function<void()> callback) {
// Reset storage and start a new trace parsing task.
storage_ = {};
parser_.reset(new TraceParser(reader, &storage_, kTraceChunkSizeB));
LoadTraceChunk(callback);
}
void TraceDatabase::ExecuteQuery(
const protos::RawQueryArgs& args,
std::function<void(protos::RawQueryResult)> callback) {
protos::RawQueryResult proto;
const auto& sql = args.sql_query();
sqlite3_stmt* stmt;
int err = sqlite3_prepare_v2(db_, sql.c_str(), static_cast<int>(sql.size()),
&stmt, nullptr);
if (err) {
callback(std::move(proto));
return;
}
for (int i = 0, size = sqlite3_column_count(stmt); i < size; i++) {
// Setup the descriptors.
auto* descriptor = proto.add_column_descriptors();
descriptor->set_name(sqlite3_column_name(stmt, i));
const char* type = sqlite3_column_decltype(stmt, i);
if (IsColumnUInt(type)) {
descriptor->set_type(protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_INT);
} else if (IsColumnULong(type)) {
descriptor->set_type(
protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_LONG);
} else {
PERFETTO_FATAL("Unexpected column type found in SQL query");
}
// Add the empty column to the proto.
proto.add_columns();
}
int row_count = 0;
for (int r = sqlite3_step(stmt); r == SQLITE_ROW; r = sqlite3_step(stmt)) {
for (int i = 0; i < proto.columns_size(); i++) {
auto* column = proto.mutable_columns(i);
switch (proto.column_descriptors(i).type()) {
case protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_LONG:
column->add_ulong_values(
static_cast<uint64_t>(sqlite3_column_int64(stmt, i)));
break;
case protos::RawQueryResult_ColumnDesc_Type_UNSIGNED_INT:
column->add_uint_values(
static_cast<uint32_t>(sqlite3_column_double(stmt, i)));
break;
case protos::RawQueryResult_ColumnDesc_Type_INT:
case protos::RawQueryResult_ColumnDesc_Type_LONG:
case protos::RawQueryResult_ColumnDesc_Type_STRING:
PERFETTO_FATAL("Unexpected column type found in SQL query");
break;
}
}
row_count++;
}
proto.set_num_records(static_cast<uint64_t>(row_count));
callback(std::move(proto));
}
void TraceDatabase::LoadTraceChunk(std::function<void()> callback) {
bool has_more = parser_->ParseNextChunk();
if (!has_more) {
callback();
return;
}
auto weak_this = weak_factory_.GetWeakPtr();
task_runner_->PostTask([weak_this, callback] {
if (!weak_this)
return;
weak_this->LoadTraceChunk(callback);
});
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|>
|
<commit_before>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "amd64.h"
#include "cpu.hh"
#include "traps.h"
#include "queue.h"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "kmtrace.hh"
#include "bits.hh"
struct intdesc idt[256] __attribute__((aligned(16)));
// boot.S
extern u64 trapentry[];
void
trap(struct trapframe *tf)
{
writegs(KDSEG);
writemsr(MSR_GS_BASE, (u64)&cpus[cpunum()].cpu);
if (tf->trapno == T_NMI) {
// The only locks that we can acquire during NMI are ones
// we acquire only during NMI.
if (sampintr(tf))
return;
panic("NMI");
}
// XXX(sbw) sysenter/sysexit
if(tf->trapno == T_SYSCALL){
sti();
if(myproc()->killed) {
mtstart(trap, myproc());
exit();
}
myproc()->tf = tf;
syscall();
if(myproc()->killed) {
mtstart(trap, myproc());
exit();
}
return;
}
#if MTRACE
if (myproc()->mtrace_stacks.curr >= 0)
mtpause(myproc());
mtstart(trap, myproc());
#endif
switch(tf->trapno){
case T_IRQ0 + IRQ_TIMER:
if (mycpu()->timer_printpc) {
cprintf("cpu%d: proc %s rip %lx rsp %lx cs %x\n",
mycpu()->id,
myproc() ? myproc()->name : "(none)",
tf->rip, tf->rsp, tf->cs);
if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {
uptr pc[10];
getcallerpcs((void *) tf->rbp, pc, NELEM(pc));
for (int i = 0; i < 10 && pc[i]; i++)
cprintf("cpu%d: %lx\n", mycpu()->id, pc[i]);
}
mycpu()->timer_printpc = 0;
}
if (mycpu()->id == 0)
cv_tick();
lapiceoi();
break;
case T_IRQ0 + IRQ_IDE:
ideintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_IDE+1:
// Bochs generates spurious IDE1 interrupts.
break;
case T_IRQ0 + IRQ_KBD:
kbdintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_COM2:
case T_IRQ0 + IRQ_COM1:
uartintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + 7:
case T_IRQ0 + IRQ_SPURIOUS:
cprintf("cpu%d: spurious interrupt at %x:%lx\n",
mycpu()->id, tf->cs, tf->rip);
lapiceoi();
case T_TLBFLUSH: {
u64 nreq = tlbflush_req.load();
lapiceoi();
lcr3(rcr3());
mycpu()->tlbflush_done = nreq;
break;
}
case T_SAMPCONF:
lapiceoi();
sampconf();
break;
default:
if (tf->trapno == T_IRQ0+e1000irq) {
e1000intr();
lapiceoi();
piceoi();
break;
}
if (myproc() == 0 || (tf->cs&3) == 0)
kerneltrap(tf);
if(tf->trapno == T_PGFLT){
uptr addr = rcr2();
sti();
if(pagefault(myproc()->vmap, addr, tf->err) >= 0){
#if MTRACE
mtstop(myproc());
if (myproc()->mtrace_stacks.curr >= 0)
mtresume(myproc());
#endif
return;
}
cli();
}
// In user space, assume process misbehaved.
cprintf("pid %d %s: trap %lu err %d on cpu %d "
"rip 0x%lx rsp 0x%lx addr 0x%lx--kill proc\n",
myproc()->pid, myproc()->name, tf->trapno, tf->err,
mycpu()->id, tf->rip, tf->rsp, rcr2());
myproc()->killed = 1;
}
// Force process exit if it has been killed and is in user space.
// (If it is still executing in the kernel, let it keep running
// until it gets to the regular system call return.)
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit();
// Force process to give up CPU on clock tick.
// If interrupts were on while locks held, would need to check nlock.
if(myproc() && myproc()->state == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)
yield();
// Check if the process has been killed since we yielded
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit();
#if MTRACE
mtstop(myproc());
if (myproc()->mtrace_stacks.curr >= 0)
mtresume(myproc());
#endif
}
void
inittrap(void)
{
u64 entry;
u8 bits;
int i;
bits = INT_P | SEG_INTR64; // present, interrupt gate
for(i=0; i<256; i++) {
entry = trapentry[i];
idt[i] = INTDESC(KCSEG, entry, bits);
}
entry = trapentry[T_SYSCALL];
idt[T_SYSCALL] = INTDESC(KCSEG, entry, SEG_DPL(3) | SEG_INTR64 |INT_P);
}
void
initseg(void)
{
extern void sysentry(void);
volatile struct desctr dtr;
struct cpu *c;
dtr.limit = sizeof(idt) - 1;
dtr.base = (u64)idt;
lidt((void *)&dtr.limit);
// TLS might not be ready
c = &cpus[cpunum()];
// Load per-CPU GDT
memmove(c->gdt, bootgdt, sizeof(bootgdt));
dtr.limit = sizeof(c->gdt) - 1;
dtr.base = (u64)c->gdt;
lgdt((void *)&dtr.limit);
#if 0
// When executing a syscall instruction the CPU sets the SS selector
// to (star >> 32) + 8 and the CS selector to (star >> 32).
// When executing a sysret instruction the CPU sets the SS selector
// to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.
u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);
writemsr(MSR_STAR, star);
writemsr(MSR_LSTAR, (u64)&sysentry);
writemsr(MSR_SFMASK, FL_TF);
#endif
}
// Pushcli/popcli are like cli/sti except that they are matched:
// it takes two popcli to undo two pushcli. Also, if interrupts
// are off, then pushcli, popcli leaves them off.
void
pushcli(void)
{
u64 rflags;
rflags = readrflags();
cli();
if(mycpu()->ncli++ == 0)
mycpu()->intena = rflags & FL_IF;
}
void
popcli(void)
{
if(readrflags()&FL_IF)
panic("popcli - interruptible");
if(--mycpu()->ncli < 0)
panic("popcli");
if(mycpu()->ncli == 0 && mycpu()->intena)
sti();
}
// Record the current call stack in pcs[] by following the %rbp chain.
void
getcallerpcs(void *v, uptr pcs[], int n)
{
uptr *rbp;
int i;
rbp = (uptr*)v;
for(i = 0; i < n; i++){
if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL))
break;
pcs[i] = rbp[1]; // saved %rip
rbp = (uptr*)rbp[0]; // saved %rbp
}
for(; i < n; i++)
pcs[i] = 0;
}
<commit_msg>lapic error interrupt shows up on real hardware for some reason<commit_after>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "amd64.h"
#include "cpu.hh"
#include "traps.h"
#include "queue.h"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "kmtrace.hh"
#include "bits.hh"
struct intdesc idt[256] __attribute__((aligned(16)));
// boot.S
extern u64 trapentry[];
void
trap(struct trapframe *tf)
{
writegs(KDSEG);
writemsr(MSR_GS_BASE, (u64)&cpus[cpunum()].cpu);
if (tf->trapno == T_NMI) {
// The only locks that we can acquire during NMI are ones
// we acquire only during NMI.
if (sampintr(tf))
return;
panic("NMI");
}
// XXX(sbw) sysenter/sysexit
if(tf->trapno == T_SYSCALL){
sti();
if(myproc()->killed) {
mtstart(trap, myproc());
exit();
}
myproc()->tf = tf;
syscall();
if(myproc()->killed) {
mtstart(trap, myproc());
exit();
}
return;
}
#if MTRACE
if (myproc()->mtrace_stacks.curr >= 0)
mtpause(myproc());
mtstart(trap, myproc());
#endif
switch(tf->trapno){
case T_IRQ0 + IRQ_TIMER:
if (mycpu()->timer_printpc) {
cprintf("cpu%d: proc %s rip %lx rsp %lx cs %x\n",
mycpu()->id,
myproc() ? myproc()->name : "(none)",
tf->rip, tf->rsp, tf->cs);
if (mycpu()->timer_printpc == 2 && tf->rbp > KBASE) {
uptr pc[10];
getcallerpcs((void *) tf->rbp, pc, NELEM(pc));
for (int i = 0; i < 10 && pc[i]; i++)
cprintf("cpu%d: %lx\n", mycpu()->id, pc[i]);
}
mycpu()->timer_printpc = 0;
}
if (mycpu()->id == 0)
cv_tick();
lapiceoi();
break;
case T_IRQ0 + IRQ_IDE:
ideintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_IDE+1:
// Bochs generates spurious IDE1 interrupts.
break;
case T_IRQ0 + IRQ_KBD:
kbdintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + IRQ_COM2:
case T_IRQ0 + IRQ_COM1:
uartintr();
lapiceoi();
piceoi();
break;
case T_IRQ0 + 7:
case T_IRQ0 + IRQ_SPURIOUS:
cprintf("cpu%d: spurious interrupt at %x:%lx\n",
mycpu()->id, tf->cs, tf->rip);
lapiceoi();
break;
case T_IRQ0 + IRQ_ERROR:
cprintf("cpu%d: lapic error?\n", mycpu()->id);
lapiceoi();
break;
case T_TLBFLUSH: {
u64 nreq = tlbflush_req.load();
lapiceoi();
lcr3(rcr3());
mycpu()->tlbflush_done = nreq;
break;
}
case T_SAMPCONF:
lapiceoi();
sampconf();
break;
default:
if (tf->trapno == T_IRQ0+e1000irq) {
e1000intr();
lapiceoi();
piceoi();
break;
}
if (myproc() == 0 || (tf->cs&3) == 0)
kerneltrap(tf);
if(tf->trapno == T_PGFLT){
uptr addr = rcr2();
sti();
if(pagefault(myproc()->vmap, addr, tf->err) >= 0){
#if MTRACE
mtstop(myproc());
if (myproc()->mtrace_stacks.curr >= 0)
mtresume(myproc());
#endif
return;
}
cli();
}
// In user space, assume process misbehaved.
cprintf("pid %d %s: trap %lu err %d on cpu %d "
"rip 0x%lx rsp 0x%lx addr 0x%lx--kill proc\n",
myproc()->pid, myproc()->name, tf->trapno, tf->err,
mycpu()->id, tf->rip, tf->rsp, rcr2());
myproc()->killed = 1;
}
// Force process exit if it has been killed and is in user space.
// (If it is still executing in the kernel, let it keep running
// until it gets to the regular system call return.)
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit();
// Force process to give up CPU on clock tick.
// If interrupts were on while locks held, would need to check nlock.
if(myproc() && myproc()->state == RUNNING && tf->trapno == T_IRQ0+IRQ_TIMER)
yield();
// Check if the process has been killed since we yielded
if(myproc() && myproc()->killed && (tf->cs&3) == 0x3)
exit();
#if MTRACE
mtstop(myproc());
if (myproc()->mtrace_stacks.curr >= 0)
mtresume(myproc());
#endif
}
void
inittrap(void)
{
u64 entry;
u8 bits;
int i;
bits = INT_P | SEG_INTR64; // present, interrupt gate
for(i=0; i<256; i++) {
entry = trapentry[i];
idt[i] = INTDESC(KCSEG, entry, bits);
}
entry = trapentry[T_SYSCALL];
idt[T_SYSCALL] = INTDESC(KCSEG, entry, SEG_DPL(3) | SEG_INTR64 |INT_P);
}
void
initseg(void)
{
extern void sysentry(void);
volatile struct desctr dtr;
struct cpu *c;
dtr.limit = sizeof(idt) - 1;
dtr.base = (u64)idt;
lidt((void *)&dtr.limit);
// TLS might not be ready
c = &cpus[cpunum()];
// Load per-CPU GDT
memmove(c->gdt, bootgdt, sizeof(bootgdt));
dtr.limit = sizeof(c->gdt) - 1;
dtr.base = (u64)c->gdt;
lgdt((void *)&dtr.limit);
#if 0
// When executing a syscall instruction the CPU sets the SS selector
// to (star >> 32) + 8 and the CS selector to (star >> 32).
// When executing a sysret instruction the CPU sets the SS selector
// to (star >> 48) + 8 and the CS selector to (star >> 48) + 16.
u64 star = ((((u64)UCSEG|0x3) - 16)<<48)|((u64)KCSEG<<32);
writemsr(MSR_STAR, star);
writemsr(MSR_LSTAR, (u64)&sysentry);
writemsr(MSR_SFMASK, FL_TF);
#endif
}
// Pushcli/popcli are like cli/sti except that they are matched:
// it takes two popcli to undo two pushcli. Also, if interrupts
// are off, then pushcli, popcli leaves them off.
void
pushcli(void)
{
u64 rflags;
rflags = readrflags();
cli();
if(mycpu()->ncli++ == 0)
mycpu()->intena = rflags & FL_IF;
}
void
popcli(void)
{
if(readrflags()&FL_IF)
panic("popcli - interruptible");
if(--mycpu()->ncli < 0)
panic("popcli");
if(mycpu()->ncli == 0 && mycpu()->intena)
sti();
}
// Record the current call stack in pcs[] by following the %rbp chain.
void
getcallerpcs(void *v, uptr pcs[], int n)
{
uptr *rbp;
int i;
rbp = (uptr*)v;
for(i = 0; i < n; i++){
if(rbp == 0 || rbp < (uptr*)KBASE || rbp == (uptr*)(~0UL))
break;
pcs[i] = rbp[1]; // saved %rip
rbp = (uptr*)rbp[0]; // saved %rbp
}
for(; i < n; i++)
pcs[i] = 0;
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
typedef int errno_t;
#define RANDOM_CACHE_SIZE 8
constexpr int rand_byte_len = sizeof(unsigned int) * RANDOM_CACHE_SIZE;
static union {
char rstack[rand_byte_len];
unsigned int result[RANDOM_CACHE_SIZE];
} random_cache;
static unsigned cache_index(RANDOM_CACHE_SIZE);
class Lock{
static pthread_mutex_t random_generator_mutex;
public:
__attribute__((noinline))
static bool Init()
{
return pthread_mutex_init(&random_generator_mutex, NULL) == 0;
}
__attribute__((noinline))
Lock() {
pthread_mutex_lock(&random_generator_mutex);
}
__attribute__((noinline))
~Lock() {
pthread_mutex_unlock(&random_generator_mutex);
}
};
pthread_mutex_t Lock::random_generator_mutex;
static bool GetRandom(unsigned int *result) noexcept
{
static bool mutex_initialized = Lock::Init();
// Do not put the `if check` into `Init` or replace it with Assert
if(!mutex_initialized) {
fprintf(stderr, "pthread_mutex_init has failed");
abort();
}
Lock lock;
if (cache_index < RANDOM_CACHE_SIZE) {
*result = random_cache.result[cache_index++];
return true;
}
const int rdev = open("/dev/urandom", O_RDONLY);
unsigned len = 0;
do
{
int added = read(rdev, random_cache.rstack + len, rand_byte_len - len);
if (added < 0) {
close(rdev);
return false;
}
len += added;
} while (len < rand_byte_len);
close(rdev);
*result = random_cache.result[0];
cache_index = 1;
return len == rand_byte_len;
}
extern "C"
errno_t __cdecl rand_s(unsigned int* randomValue) noexcept
{
if (randomValue == nullptr) return 1;
if (GetRandom(randomValue))
{
return 0;
}
else
{
*randomValue = 0;
return 1;
}
}
<commit_msg>[2.0>master] [MERGE #2630 @obastemur] xplat: rand_s fallback<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
typedef int errno_t;
#define RANDOM_CACHE_SIZE 8
constexpr int rand_byte_len = sizeof(unsigned int) * RANDOM_CACHE_SIZE;
static union {
char rstack[rand_byte_len];
unsigned int result[RANDOM_CACHE_SIZE];
} random_cache;
static unsigned cache_index(RANDOM_CACHE_SIZE);
class Lock{
static pthread_mutex_t random_generator_mutex;
public:
__attribute__((noinline))
static bool Init()
{
return pthread_mutex_init(&random_generator_mutex, NULL) == 0;
}
__attribute__((noinline))
Lock() {
pthread_mutex_lock(&random_generator_mutex);
}
__attribute__((noinline))
~Lock() {
pthread_mutex_unlock(&random_generator_mutex);
}
};
pthread_mutex_t Lock::random_generator_mutex;
// not needed to be a THREAD_LOCAL. GetRandom acquires a mutex lock
unsigned int WEAK_RANDOM_SEED = 12345;
static void GetRandom(unsigned int *result) noexcept
{
static bool mutex_initialized = Lock::Init();
// Do not put the `if check` into `Init` or replace it with Assert
if(!mutex_initialized) {
fprintf(stderr, "pthread_mutex_init has failed");
abort();
}
Lock lock;
if (cache_index < RANDOM_CACHE_SIZE) {
*result = random_cache.result[cache_index++];
return;
}
const int rdev = open("/dev/urandom", O_RDONLY);
unsigned len = 0;
bool failed = false;
do
{
int added = read(rdev, random_cache.rstack + len, rand_byte_len - len);
if (added < 0) {
close(rdev);
// io starvation ?
failed = true;
goto LEAVE;
}
len += added;
} while (len < rand_byte_len);
close(rdev);
*result = random_cache.result[0];
failed = len != rand_byte_len;
LEAVE:
if (failed) // fallback to weak rnd
{
WEAK_RANDOM_SEED += rand();
*result = rand_r(&WEAK_RANDOM_SEED);
}
else
{
cache_index = 1; // enable cache only when len == rand_byte_len
}
}
extern "C"
errno_t __cdecl rand_s(unsigned int* randomValue) noexcept
{
if (randomValue == nullptr) return 1;
GetRandom(randomValue);
return 0;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs_load_ddr4.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs_load_ddr4.C
/// @brief Run and manage the DDR4 mrs loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
#include <lib/dimm/bcw_load.H>
#include <lib/eff_config/timing.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Sets up MRS CCS instructions
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_data the completed MRS data to send
/// @param[in] i_rank the rank to send to
/// @param[in,out] io_inst a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
fapi2::ReturnCode mrs_engine( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs_data<fapi2::TARGET_TYPE_MCBIST>& i_data,
const uint64_t i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst )
{
FAPI_TRY( mrs_engine(i_target, i_data, i_rank, i_data.iv_delay, io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
namespace ddr4
{
///
/// @brief Perform the mrs_load DDR4 operations - TARGET_TYPE_DIMM specialization
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode mrs_load( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& io_inst)
{
FAPI_INF("ddr4::mrs_load %s", mss::c_str(i_target));
fapi2::buffer<uint16_t> l_cal_steps;
uint64_t tDLLK = 0;
uint8_t l_dimm_type = 0;
static std::vector< mrs_data<TARGET_TYPE_MCBIST> > l_mrs_data =
{
// JEDEC ordering of MRS per DDR4 power on sequence
{ 3, mrs03, mrs03_decode, mss::tmrd() },
{ 6, mrs06, mrs06_decode, mss::tmrd() },
{ 5, mrs05, mrs05_decode, mss::tmrd() },
{ 4, mrs04, mrs04_decode, mss::tmrd() },
{ 2, mrs02, mrs02_decode, mss::tmrd() },
{ 1, mrs01, mrs01_decode, mss::tmrd() },
// We need to wait either tmod or tmrd before zqcl.
{ 0, mrs00, mrs00_decode, std::max(mss::tmrd(), mss::tmod(i_target)) },
};
std::vector< uint64_t > l_ranks;
FAPI_TRY( mss::rank::ranks(i_target, l_ranks) );
FAPI_TRY( mss::tdllk(i_target, tDLLK) );
// Load MRS
for (const auto& d : l_mrs_data)
{
for (const auto& r : l_ranks)
{
FAPI_TRY( mrs_engine(i_target, d, r, io_inst) );
}
}
// Load ZQ Cal Long instruction only if the bit in the cal steps says to do so.
FAPI_TRY( mss::cal_step_enable(i_target, l_cal_steps) );
if (l_cal_steps.getBit<EXT_ZQCAL>() != 0)
{
for (const auto& r : l_ranks)
{
// Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS
ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst_a_side = ccs::zqcl_command<TARGET_TYPE_MCBIST>(i_target, r);
ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst_b_side;
FAPI_TRY( mss::address_mirror(i_target, r, l_inst_a_side) );
l_inst_b_side = mss::address_invert(l_inst_a_side);
l_inst_a_side.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES,
MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(tDLLK + mss::tzqinit());
l_inst_b_side.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES,
MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(tDLLK + mss::tzqinit());
// There's nothing to decode here.
FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d a-side",
l_inst_a_side.arr0, l_inst_a_side.arr1, mss::c_str(i_target), r);
FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d b-side",
l_inst_b_side.arr0, l_inst_b_side.arr1, mss::c_str(i_target), r);
// Add both to the CCS program
io_inst.push_back(l_inst_a_side);
io_inst.push_back(l_inst_b_side);
}
}
// For LRDIMMs, program BCW to send ZQCal Long command to all databuffers
// in broadcast mode
FAPI_TRY( eff_dimm_type(i_target, l_dimm_type) );
if( l_dimm_type == fapi2::ENUM_ATTR_EFF_DIMM_TYPE_LRDIMM )
{
constexpr uint8_t FSPACE = 0;
constexpr uint8_t WORD = 6;
// From the DDR4DB02 Spec: BC06 - Command Space Control Word
// After issuing a data buffer command via writes to BC06 waiting for tMRC(16 tCK)
// is required before the next DRAM command or BCW write can be issued.
FAPI_TRY( function_space_select<0>(i_target, io_inst) );
FAPI_TRY( control_word_engine<BCW_8BIT>(i_target,
cw_data(FSPACE, WORD, eff_dimm_ddr4_bc06, mss::tmrc()),
io_inst) );
}
fapi_try_exit:
return fapi2::current_err;
}
} // ns ddr4
} // ns mss
<commit_msg>Add BCW API for rank presence, buffer training, mrep timing and UTs.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs_load_ddr4.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs_load_ddr4.C
/// @brief Run and manage the DDR4 mrs loading
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
#include <lib/dimm/ddr4/control_word_ddr4.H>
#include <lib/dimm/ddr4/data_buffer_ddr4.H>
#include <lib/eff_config/timing.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Sets up MRS CCS instructions
/// @param[in] i_target a fapi2::Target DIMM
/// @param[in] i_data the completed MRS data to send
/// @param[in] i_rank the rank to send to
/// @param[in,out] io_inst a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< >
fapi2::ReturnCode mrs_engine( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs_data<fapi2::TARGET_TYPE_MCBIST>& i_data,
const uint64_t i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst )
{
FAPI_TRY( mrs_engine(i_target, i_data, i_rank, i_data.iv_delay, io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
namespace ddr4
{
///
/// @brief Perform the mrs_load DDR4 operations - TARGET_TYPE_DIMM specialization
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode mrs_load( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& io_inst)
{
FAPI_INF("ddr4::mrs_load %s", mss::c_str(i_target));
fapi2::buffer<uint16_t> l_cal_steps;
uint64_t tDLLK = 0;
uint8_t l_dimm_type = 0;
static std::vector< mrs_data<TARGET_TYPE_MCBIST> > l_mrs_data =
{
// JEDEC ordering of MRS per DDR4 power on sequence
{ 3, mrs03, mrs03_decode, mss::tmrd() },
{ 6, mrs06, mrs06_decode, mss::tmrd() },
{ 5, mrs05, mrs05_decode, mss::tmrd() },
{ 4, mrs04, mrs04_decode, mss::tmrd() },
{ 2, mrs02, mrs02_decode, mss::tmrd() },
{ 1, mrs01, mrs01_decode, mss::tmrd() },
// We need to wait either tmod or tmrd before zqcl.
{ 0, mrs00, mrs00_decode, std::max(mss::tmrd(), mss::tmod(i_target)) },
};
std::vector< uint64_t > l_ranks;
FAPI_TRY( mss::rank::ranks(i_target, l_ranks) );
FAPI_TRY( mss::tdllk(i_target, tDLLK) );
// Load MRS
for (const auto& d : l_mrs_data)
{
for (const auto& r : l_ranks)
{
FAPI_TRY( mrs_engine(i_target, d, r, io_inst) );
}
}
// Load ZQ Cal Long instruction only if the bit in the cal steps says to do so.
FAPI_TRY( mss::cal_step_enable(i_target, l_cal_steps) );
if (l_cal_steps.getBit<EXT_ZQCAL>() != 0)
{
for (const auto& r : l_ranks)
{
// Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS
ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst_a_side = ccs::zqcl_command<TARGET_TYPE_MCBIST>(i_target, r);
ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst_b_side;
FAPI_TRY( mss::address_mirror(i_target, r, l_inst_a_side) );
l_inst_b_side = mss::address_invert(l_inst_a_side);
l_inst_a_side.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES,
MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(tDLLK + mss::tzqinit());
l_inst_b_side.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES,
MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(tDLLK + mss::tzqinit());
// There's nothing to decode here.
FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d a-side",
l_inst_a_side.arr0, l_inst_a_side.arr1, mss::c_str(i_target), r);
FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d b-side",
l_inst_b_side.arr0, l_inst_b_side.arr1, mss::c_str(i_target), r);
// Add both to the CCS program
io_inst.push_back(l_inst_a_side);
io_inst.push_back(l_inst_b_side);
}
}
// For LRDIMMs, program BCW to send ZQCal Long command to all databuffers
// in broadcast mode
FAPI_TRY( eff_dimm_type(i_target, l_dimm_type) );
if( l_dimm_type == fapi2::ENUM_ATTR_EFF_DIMM_TYPE_LRDIMM )
{
FAPI_TRY( set_command_space(i_target, command::ZQCL, io_inst) );
}
fapi_try_exit:
return fapi2::current_err;
}
} // ns ddr4
} // ns mss
<|endoftext|>
|
<commit_before><commit_msg>Missing const<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2017 Leonid Yuriev <leo@yuriev.ru>
* and other libmdbx authors: please see AUTHORS file.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include "test.h"
static void fflushall() { fflush(nullptr); }
void failure(const char *fmt, ...) {
va_list ap;
fflush(NULL);
va_start(ap, fmt);
logging::output(logging::failure, fmt, ap);
va_end(ap);
fflushall();
exit(EXIT_FAILURE);
}
const char *test_strerror(int errnum) {
static __thread char buf[1024];
return mdbx_strerror_r(errnum, buf, sizeof(buf));
}
void __noreturn failure_perror(const char *what, int errnum) {
failure("%s failed: %s (%d)\n", what, test_strerror(errnum), errnum);
}
//-----------------------------------------------------------------------------
namespace logging {
static std::string prefix;
static std::string suffix;
static loglevel level;
static FILE *last;
void setup(loglevel _level, const std::string &_prefix) {
level = (_level > error) ? failure : _level;
prefix = _prefix;
}
void setup(const std::string &_prefix) { prefix = _prefix; }
const char *level2str(const loglevel level) {
switch (level) {
default:
return "invalid/unknown";
case extra:
return "extra";
case trace:
return "trace";
case verbose:
return "verbose";
case info:
return "info";
case notice:
return "notice";
case warning:
return "warning";
case error:
return "error";
case failure:
return "failure";
}
}
bool output(loglevel priority, const char *format, ...) {
if (priority < level)
return false;
va_list ap;
va_start(ap, format);
output(priority, format, ap);
va_end(ap);
return true;
}
bool output(loglevel priority, const char *format, va_list ap) {
if (last) {
putc('\n', last);
fflush(last);
last = nullptr;
}
if (priority < level)
return false;
chrono::time now = chrono::now_realtime();
struct tm tm;
time_t time = now.utc;
#ifdef _MSC_VER
int rc = _localtime32_s(&tm, (const __time32_t *)&now.utc);
#else
int rc = localtime_r(&time, &tm) ? MDB_SUCCESS : errno;
#endif
if (rc != MDB_SUCCESS)
failure_perror("localtime_r()", rc);
last = (priority >= error) ? stderr : stdout;
fprintf(last,
"[ %02d%02d%02d-%02d:%02d:%02d.%06d_%05u %-10s %.4s ] %s" /* TODO */,
tm.tm_year - 100, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min,
tm.tm_sec, chrono::fractional2us(now.fractional), osal_getpid(),
prefix.c_str(), level2str(priority), suffix.c_str());
vfprintf(last, format, ap);
size_t len = strlen(format);
char end = len ? format[len - 1] : '\0';
switch (end) {
default:
putc('\n', last);
case '\n':
fflush(last);
last = nullptr;
if (priority > info)
fflushall();
case ' ':
case '_':
case ':':
case '|':
case ',':
case '\t':
case '\b':
case '\r':
case '\0':
break;
}
return true;
}
bool feed(const char *format, va_list ap) {
if (!last)
return false;
vfprintf(last, format, ap);
size_t len = strlen(format);
if (len && format[len - 1] == '\n') {
fflush(last);
last = nullptr;
}
return true;
}
bool feed(const char *format, ...) {
if (!last)
return false;
va_list ap;
va_start(ap, format);
feed(format, ap);
va_end(ap);
return true;
}
local_suffix::local_suffix(const char *c_str)
: trim_pos(suffix.size()), indent(0) {
suffix.append(c_str);
}
local_suffix::local_suffix(const std::string &str)
: trim_pos(suffix.size()), indent(0) {
suffix.append(str);
}
void local_suffix::push() {
indent += 1;
suffix.push_back('\t');
}
void local_suffix::pop() {
assert(indent > 0);
if (indent > 0) {
indent -= 1;
suffix.pop_back();
}
}
local_suffix::~local_suffix() { suffix.erase(trim_pos); }
} /* namespace log */
void log_trace(const char *msg, ...) {
if (logging::trace >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::trace, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_verbose(const char *msg, ...) {
if (logging::verbose >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::verbose, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_info(const char *msg, ...) {
if (logging::info >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::info, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_notice(const char *msg, ...) {
if (logging::notice >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::notice, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_warning(const char *msg, ...) {
if (logging::warning >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::warning, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_error(const char *msg, ...) {
if (logging::error >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::error, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_touble(const char *where, const char *what, int errnum) {
log_error("%s: %s %s", where, what, test_strerror(errnum));
}
<commit_msg>test: log error into stdout too.<commit_after>/*
* Copyright 2017 Leonid Yuriev <leo@yuriev.ru>
* and other libmdbx authors: please see AUTHORS file.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include "test.h"
static void fflushall() { fflush(nullptr); }
void failure(const char *fmt, ...) {
va_list ap;
fflush(NULL);
va_start(ap, fmt);
logging::output(logging::failure, fmt, ap);
va_end(ap);
fflushall();
exit(EXIT_FAILURE);
}
const char *test_strerror(int errnum) {
static __thread char buf[1024];
return mdbx_strerror_r(errnum, buf, sizeof(buf));
}
void __noreturn failure_perror(const char *what, int errnum) {
failure("%s failed: %s (%d)\n", what, test_strerror(errnum), errnum);
}
//-----------------------------------------------------------------------------
namespace logging {
static std::string prefix;
static std::string suffix;
static loglevel level;
static FILE *last;
void setup(loglevel _level, const std::string &_prefix) {
level = (_level > error) ? failure : _level;
prefix = _prefix;
}
void setup(const std::string &_prefix) { prefix = _prefix; }
const char *level2str(const loglevel level) {
switch (level) {
default:
return "invalid/unknown";
case extra:
return "extra";
case trace:
return "trace";
case verbose:
return "verbose";
case info:
return "info";
case notice:
return "notice";
case warning:
return "warning";
case error:
return "error";
case failure:
return "failure";
}
}
bool output(loglevel priority, const char *format, ...) {
if (priority < level)
return false;
va_list ap;
va_start(ap, format);
output(priority, format, ap);
va_end(ap);
return true;
}
bool output(loglevel priority, const char *format, va_list ap) {
if (last) {
putc('\n', last);
fflush(last);
last = nullptr;
}
if (priority < level)
return false;
chrono::time now = chrono::now_realtime();
struct tm tm;
time_t time = now.utc;
#ifdef _MSC_VER
int rc = _localtime32_s(&tm, (const __time32_t *)&now.utc);
#else
int rc = localtime_r(&time, &tm) ? MDB_SUCCESS : errno;
#endif
if (rc != MDB_SUCCESS)
failure_perror("localtime_r()", rc);
last = stdout;
fprintf(last,
"[ %02d%02d%02d-%02d:%02d:%02d.%06d_%05u %-10s %.4s ] %s" /* TODO */,
tm.tm_year - 100, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min,
tm.tm_sec, chrono::fractional2us(now.fractional), osal_getpid(),
prefix.c_str(), level2str(priority), suffix.c_str());
vfprintf(last, format, ap);
size_t len = strlen(format);
char end = len ? format[len - 1] : '\0';
switch (end) {
default:
putc('\n', last);
case '\n':
fflush(last);
last = nullptr;
case ' ':
case '_':
case ':':
case '|':
case ',':
case '\t':
case '\b':
case '\r':
case '\0':
break;
}
if (priority >= error && last != stderr) {
fprintf(stderr, "[ %05u %-10s %.4s ] %s", osal_getpid(), prefix.c_str(),
level2str(priority), suffix.c_str());
vfprintf(stderr, format, ap);
if (end != '\n')
putc('\n', stderr);
fflush(stderr);
}
return true;
}
bool feed(const char *format, va_list ap) {
if (!last)
return false;
vfprintf(last, format, ap);
size_t len = strlen(format);
if (len && format[len - 1] == '\n') {
fflush(last);
last = nullptr;
}
return true;
}
bool feed(const char *format, ...) {
if (!last)
return false;
va_list ap;
va_start(ap, format);
feed(format, ap);
va_end(ap);
return true;
}
local_suffix::local_suffix(const char *c_str)
: trim_pos(suffix.size()), indent(0) {
suffix.append(c_str);
}
local_suffix::local_suffix(const std::string &str)
: trim_pos(suffix.size()), indent(0) {
suffix.append(str);
}
void local_suffix::push() {
indent += 1;
suffix.push_back('\t');
}
void local_suffix::pop() {
assert(indent > 0);
if (indent > 0) {
indent -= 1;
suffix.pop_back();
}
}
local_suffix::~local_suffix() { suffix.erase(trim_pos); }
} /* namespace log */
void log_trace(const char *msg, ...) {
if (logging::trace >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::trace, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_verbose(const char *msg, ...) {
if (logging::verbose >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::verbose, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_info(const char *msg, ...) {
if (logging::info >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::info, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_notice(const char *msg, ...) {
if (logging::notice >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::notice, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_warning(const char *msg, ...) {
if (logging::warning >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::warning, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_error(const char *msg, ...) {
if (logging::error >= logging::level) {
va_list ap;
va_start(ap, msg);
logging::output(logging::error, msg, ap);
va_end(ap);
} else
logging::last = nullptr;
}
void log_touble(const char *where, const char *what, int errnum) {
log_error("%s: %s %s", where, what, test_strerror(errnum));
}
<|endoftext|>
|
<commit_before>#include "io.h"
#include <sstream>
#include <fstream>
#include <iomanip>
#include <gflags/gflags.h>
#include "proto/metadata.pb.h"
#include "proto/chunk.pb.h"
DEFINE_string(dataset, "", "Input dataset");
DEFINE_string(output, "", "Path to file where to store calculated PageRank");
/*
* NOTE! It's possible that begin >= chunk_begin, or end < chunk_end.
* The real bounds are intersection of [begin; end] and [chunk_begin; chunk_end].
*/
void ReadPagesFromChunk(int chunk_size, int chunk_id,
int begin, int end, std::vector<pr::Page> &pages) {
int chunk_begin = chunk_id * chunk_size;
int chunk_end = chunk_begin + chunk_size;
if (begin < chunk_begin) begin = chunk_begin;
if (end >= chunk_end) end = chunk_end - 1;
pr::Chunk chunk;
std::ifstream in(FLAGS_dataset + "_" + std::to_string(chunk_id) + ".chnk");
chunk.ParseFromIstream(&in);
int shift = begin - chunk_begin;
int cnt = end - begin + 1;
std::move(chunk.mutable_pages()->begin() + shift,
chunk.mutable_pages()->end(),
std::back_inserter(pages));
}
/*
* Read pages and push them to the back of output vector.
*/
void ReadPages(int chunk_size, int begin, int end,
std::vector<pr::Page> &pages) {
int begin_chunk = begin / chunk_size;
int end_chunk = end / chunk_size;
for (int chunk = begin_chunk; chunk <= end_chunk; chunk++) {
ReadPagesFromChunk(chunk_size, chunk, begin, end, pages);
}
}
void ReadMetadata(int *page_cnt_ptr, int *chunk_size_ptr,
std::vector<int> &out_link_cnts) {
pr::Metadata meta;
std::ifstream in(FLAGS_dataset + ".meta", std::ios::in | std::ios::binary);
meta.ParseFromIstream(&in);
*page_cnt_ptr = meta.page_cnt();
*chunk_size_ptr = meta.chunk_size();
out_link_cnts.clear();
out_link_cnts.reserve(meta.page_cnt());
std::move(meta.mutable_out_link_cnts()->begin(),
meta.mutable_out_link_cnts()->end(),
std::back_inserter(out_link_cnts));
}
void WritePr(const std::vector<double> pr) {
std::ofstream out(FLAGS_output);
for (double x : pr) {
out << std::setprecision(10) << std::fixed << x << std::endl;
}
}
<commit_msg>Add I/O error handling<commit_after>#include "io.h"
#include <sstream>
#include <fstream>
#include <iomanip>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include "proto/metadata.pb.h"
#include "proto/chunk.pb.h"
DEFINE_string(dataset, "", "Input dataset");
DEFINE_string(output, "", "Path to file where to store calculated PageRank");
/*
* NOTE! It's possible that begin >= chunk_begin, or end < chunk_end.
* The real bounds are intersection of [begin; end] and [chunk_begin; chunk_end].
*/
void ReadPagesFromChunk(int chunk_size, int chunk_id,
int begin, int end, std::vector<pr::Page> &pages) {
int chunk_begin = chunk_id * chunk_size;
int chunk_end = chunk_begin + chunk_size;
if (begin < chunk_begin) begin = chunk_begin;
if (end >= chunk_end) end = chunk_end - 1;
pr::Chunk chunk;
std::string filename = FLAGS_dataset + "_" + std::to_string(chunk_id) +
".chnk";
std::ifstream in(filename);
if (!in)
LOG(FATAL) << "Error opening chunk file " + filename + " for reading.";
if (!chunk.ParseFromIstream(&in))
LOG(FATAL) << "Error parsing chunk from file " + filename + ".";
int shift = begin - chunk_begin;
std::move(chunk.mutable_pages()->begin() + shift,
chunk.mutable_pages()->end(),
std::back_inserter(pages));
}
/*
* Read pages and push them to the back of output vector.
*/
void ReadPages(int chunk_size, int begin, int end,
std::vector<pr::Page> &pages) {
int begin_chunk = begin / chunk_size;
int end_chunk = end / chunk_size;
for (int chunk = begin_chunk; chunk <= end_chunk; chunk++) {
ReadPagesFromChunk(chunk_size, chunk, begin, end, pages);
}
}
void ReadMetadata(int *page_cnt_ptr, int *chunk_size_ptr,
std::vector<int> &out_link_cnts) {
pr::Metadata meta;
std::string filename = FLAGS_dataset + ".meta";
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (!in)
LOG(FATAL) << "Error opening metadata file " + filename + " for reading.";
if (!meta.ParseFromIstream(&in))
LOG(FATAL) << "Error parsing metadata from file " + filename + ".";
*page_cnt_ptr = meta.page_cnt();
*chunk_size_ptr = meta.chunk_size();
out_link_cnts.clear();
out_link_cnts.reserve(meta.page_cnt());
std::move(meta.mutable_out_link_cnts()->begin(),
meta.mutable_out_link_cnts()->end(),
std::back_inserter(out_link_cnts));
}
void WritePr(const std::vector<double> pr) {
std::ofstream out(FLAGS_output);
if (!out)
LOG(FATAL) << "Error opening output file " + FLAGS_output +
" for writing.";
for (double x : pr) {
out << std::setprecision(10) << std::fixed << x << std::endl;
}
}
<|endoftext|>
|
<commit_before><commit_msg>update python bindings some more<commit_after><|endoftext|>
|
<commit_before>#ifndef VIENNAFVM_QUANTITY_HPP
#define VIENNAFVM_QUANTITY_HPP
/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
(add your name here)
license: To be discussed, see file LICENSE in the ViennaFVM base directory
======================================================================= */
#include <numeric>
#include "viennafvm/forwards.h"
#include "viennamath/forwards.h"
#include "viennamath/manipulation/substitute.hpp"
#include "viennamath/expression.hpp"
#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/segmentation.hpp"
/** @file quantity.hpp
@brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh
*/
namespace viennafvm
{
namespace traits {
template<typename EleT>
inline std::size_t id(EleT const& elem)
{
return elem.id().get();
}
} // traits
template<typename AssociatedT, typename ValueT = double>
class quantity
{
public:
typedef ValueT value_type;
typedef AssociatedT associated_type;
quantity() {} // to fulfill default constructible concept!
quantity(std::size_t id,
std::string const & quan_name,
std::size_t num_values,
value_type default_value = value_type())
: id_(id),
name_(quan_name),
values_ (num_values, default_value),
boundary_types_ (num_values, BOUNDARY_NONE),
boundary_values_ (num_values, default_value),
unknown_mask_ (num_values, false),
unknowns_indices_(num_values, -1)
{}
std::string get_name() const { return name_; }
ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); }
void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; }
// Dirichlet and Neumann
ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); }
void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; }
boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); }
void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; }
bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); }
void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; }
long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); }
void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; }
std::size_t get_unknown_num() const
{
std::size_t num = 0;
for (std::size_t i=0; i<unknowns_indices_.size(); ++i)
{
if (unknowns_indices_[i] >= 0)
++num;
}
return num;
}
bool are_entries_zero()
{
if( std::fabs(this->get_sum()) < 1.0E-20 ) return true;
else return false;
}
value_type get_sum()
{
return std::accumulate(values_.begin(), values_.end(), 0.0);
}
// possible design flaws:
std::vector<ValueT> const & values() const { return values_; }
std::size_t const& id () const { return id_; }
void set_id(std::size_t id) { id_ = id; }
private:
// std::size_t id(associated_type const elem) const { return elem.id().get(); }
std::size_t id_;
std::string name_;
std::vector<ValueT> values_;
std::vector<boundary_type_id> boundary_types_;
std::vector<ValueT> boundary_values_;
std::vector<bool> unknown_mask_;
std::vector<long> unknowns_indices_;
};
}
#endif
<commit_msg>removed 'are_entries_zero' function<commit_after>#ifndef VIENNAFVM_QUANTITY_HPP
#define VIENNAFVM_QUANTITY_HPP
/* =======================================================================
Copyright (c) 2011, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaFVM - The Vienna Finite Volume Method Library
-----------------
authors: Karl Rupp rupp@iue.tuwien.ac.at
(add your name here)
license: To be discussed, see file LICENSE in the ViennaFVM base directory
======================================================================= */
#include <numeric>
#include "viennafvm/forwards.h"
#include "viennamath/forwards.h"
#include "viennamath/manipulation/substitute.hpp"
#include "viennamath/expression.hpp"
#include "viennagrid/forwards.hpp"
#include "viennagrid/mesh/segmentation.hpp"
/** @file quantity.hpp
@brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh
*/
namespace viennafvm
{
namespace traits {
template<typename EleT>
inline std::size_t id(EleT const& elem)
{
return elem.id().get();
}
} // traits
template<typename AssociatedT, typename ValueT = double>
class quantity
{
public:
typedef ValueT value_type;
typedef AssociatedT associated_type;
quantity() {} // to fulfill default constructible concept!
quantity(std::size_t id,
std::string const & quan_name,
std::size_t num_values,
value_type default_value = value_type())
: id_(id),
name_(quan_name),
values_ (num_values, default_value),
boundary_types_ (num_values, BOUNDARY_NONE),
boundary_values_ (num_values, default_value),
unknown_mask_ (num_values, false),
unknowns_indices_(num_values, -1)
{}
std::string get_name() const { return name_; }
ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); }
void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; }
// Dirichlet and Neumann
ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); }
void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; }
boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); }
void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; }
bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); }
void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; }
long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); }
void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; }
std::size_t get_unknown_num() const
{
std::size_t num = 0;
for (std::size_t i=0; i<unknowns_indices_.size(); ++i)
{
if (unknowns_indices_[i] >= 0)
++num;
}
return num;
}
value_type get_sum()
{
return std::accumulate(values_.begin(), values_.end(), 0.0);
}
// possible design flaws:
std::vector<ValueT> const & values() const { return values_; }
std::size_t const& id () const { return id_; }
void set_id(std::size_t id) { id_ = id; }
private:
// std::size_t id(associated_type const elem) const { return elem.id().get(); }
std::size_t id_;
std::string name_;
std::vector<ValueT> values_;
std::vector<boundary_type_id> boundary_types_;
std::vector<ValueT> boundary_values_;
std::vector<bool> unknown_mask_;
std::vector<long> unknowns_indices_;
};
}
#endif
<|endoftext|>
|
<commit_before>#include "CommunicationInterface.h"
// constructor
CommunicationInterface::CommunicationInterface(void)
:
outputDataBuffer_(""),
placeInBuffer_(false),
dataBufferIndex_(0),
nModules_(0)
{
// Do nothing.
}
// Destructor - make sure to clean up those pointers!
CommunicationInterface::~CommunicationInterface(void)
{
for(long int moduleI=0; moduleI<nModules_; moduleI++)
delete modules_[moduleI];
}
// Initialises the communications and stores pointers to all linked modules
// inside the current instance.
void CommunicationInterface::setup(Module* modulePtrs[], size_t nPtrs)
{
// Copy the pointers to the class container. Necessary to do it this way
// to make sure they are kept even if the original array passed to this function
// gets out of scope.
nModules_ = nPtrs;
modules_ = (Module**) malloc(nModules_ * sizeof(Module*));
for(long int moduleI=0; moduleI<nModules_; moduleI++)
modules_[moduleI] = modulePtrs[moduleI];
#ifdef DEBUG_PRINTOUT
Serial.println("Initialised communications with modules:");
for(long int moduleI=0; moduleI<nModules_; moduleI++)
{
Serial.print(" ");
Serial.print(moduleI);
Serial.print(": ");
Serial.println(modules_[moduleI]->getIdentifier());
}
#endif
}
// Main funciton which calles getSerial() and parseInput() sequentially to
// update the state of all of the connected modules.
void CommunicationInterface::loop(void)
{
getSerial();
parseInput();
}
boolean CommunicationInterface::getSerial(void)
/* Read input from the serial port and store it in the inputDataBuffer buffer.
* The serial input has to conform to a protocol, whereby the messages begin with
* INPUT_START_CHAR and terminate with END_CHAR. The message in between is
* a sequence of strings and integers. Strings represent the destination of the
* command (e.g. engine throttle) and integers are the arguments for the command
* (e.g. throttle value).
*
* @return - true if we've parsed the entire command successfully; false otherwise,
* e.g. when we didn't receive a command.
*/
{
char incomingbyte; // The currently read serial input byte.
while(Serial.available()>0)
{
incomingbyte = Serial.read(); // Read bytes from the serial input one by one.
if(incomingbyte==INPUT_START_CHAR) // A command has been received.
{
dataBufferIndex_ = 0; // We'll be reading the first input value next.
placeInBuffer_ = true; // We should be storing the inputs in the buffer now.
}
if(placeInBuffer_)
{
if(dataBufferIndex_==DATABUFFERSIZE)
{
// Index is pointing to an array element outside our buffer.
// We're done reading this command, so have to start reading the next one from the beginning.
dataBufferIndex_ = 0;
// Exit the while loop, we're done with this command.
break;
}
if(incomingbyte==END_CHAR) // We've reached the end of this command.
{
// Null terminate the C string
inputDataBuffer_[dataBufferIndex_] = 0;
// Don't store anything here any more.
placeInBuffer_ = false;
// Make sure next command gets written to the start of the buffer.
dataBufferIndex_ = 0;
// Say that we've parsed the whole command.
return true;
}
else if (incomingbyte!=INPUT_START_CHAR) // Simply record the telecommand byte.
{
inputDataBuffer_[dataBufferIndex_++] = incomingbyte;
}
}
}
return false; // Something went wrong or we didn't receive an actual command.
}
// Extract commands and corresponding numbers from the inputDataBuffer input buffer.
void CommunicationInterface::parseInput(void)
{
Serial.print("Buffer=");
Serial.println(inputDataBuffer_);
// Holds the tokens used to match passed values to each listening module.
char * token;
// Get the first token. DATA_DELIMITER is a char but need to convert to const char*
token = strtok(inputDataBuffer_, String(DATA_DELIMITER).c_str());
// Parse the entire inputDataBuffer of tokens (commands and their value arguments).
int nextModuleIndex = -1; // Index of the module value for which is sent in this part of the telecommand.
while (token != NULL)
{
Serial.print("Token=");
Serial.println(token);
// If next module index < 0 we have no value to read now
if (nextModuleIndex >= 0)
{
#ifdef DEBUG_PRINTOUT
Serial.print("Trying to set value of module ");
Serial.print(modules_[nextModuleIndex]->getIdentifier());
Serial.print(" to ");
Serial.println( String(int(atof(token))) );
#endif
modules_[nextModuleIndex] -> setValue( int(atof(token)) );
// Indicate that on the next pass there is no value to read.
nextModuleIndex = -1;
}
else
{
// the current token may be a string corresponding to one of the modules
for(long int moduleI=0; moduleI<nModules_; moduleI++)
{
if (strcmp(token, modules_[moduleI]->getIdentifier()) == 0)
{
nextModuleIndex = moduleI;
break;
}
}
}
// Continue to the new token.
// If given a NULL pointer, the funciton continues from the point where
// the previous call finished, thereby moving along the buffer string.
token = strtok(NULL, String(DATA_DELIMITER).c_str());
}
// Reset the buffer as the first token is still in it
memset(&inputDataBuffer_[0], 0, sizeof(inputDataBuffer_));
}
<commit_msg>Added buffer reset in comms module, improved documentation of tare() method in load cell<commit_after>#include "CommunicationInterface.h"
// constructor
CommunicationInterface::CommunicationInterface(void)
:
outputDataBuffer_(""),
placeInBuffer_(false),
dataBufferIndex_(0),
nModules_(0)
{
// Do nothing.
}
// Destructor - make sure to clean up those pointers!
CommunicationInterface::~CommunicationInterface(void)
{
for(long int moduleI=0; moduleI<nModules_; moduleI++)
delete modules_[moduleI];
}
// Initialises the communications and stores pointers to all linked modules
// inside the current instance.
void CommunicationInterface::setup(Module* modulePtrs[], size_t nPtrs)
{
// Copy the pointers to the class container. Necessary to do it this way
// to make sure they are kept even if the original array passed to this function
// gets out of scope.
nModules_ = nPtrs;
modules_ = (Module**) malloc(nModules_ * sizeof(Module*));
for(long int moduleI=0; moduleI<nModules_; moduleI++)
modules_[moduleI] = modulePtrs[moduleI];
#ifdef DEBUG_PRINTOUT
Serial.println("Initialised communications with modules:");
for(long int moduleI=0; moduleI<nModules_; moduleI++)
{
Serial.print(" ");
Serial.print(moduleI);
Serial.print(": ");
Serial.println(modules_[moduleI]->getIdentifier());
}
#endif
}
// Main funciton which calles getSerial() and parseInput() sequentially to
// update the state of all of the connected modules.
void CommunicationInterface::loop(void)
{
getSerial();
parseInput();
}
boolean CommunicationInterface::getSerial(void)
/* Read input from the serial port and store it in the inputDataBuffer buffer.
* The serial input has to conform to a protocol, whereby the messages begin with
* INPUT_START_CHAR and terminate with END_CHAR. The message in between is
* a sequence of strings and integers. Strings represent the destination of the
* command (e.g. engine throttle) and integers are the arguments for the command
* (e.g. throttle value).
*
* @return - true if we've parsed the entire command successfully; false otherwise,
* e.g. when we didn't receive a command.
*/
{
char incomingbyte; // The currently read serial input byte.
while(Serial.available()>0)
{
incomingbyte = Serial.read(); // Read bytes from the serial input one by one.
if(incomingbyte==INPUT_START_CHAR) // A command has been received.
{
dataBufferIndex_ = 0; // We'll be reading the first input value next.
placeInBuffer_ = true; // We should be storing the inputs in the buffer now.
}
if(placeInBuffer_)
{
if(dataBufferIndex_==DATABUFFERSIZE)
{
// Index is pointing to an array element outside our buffer.
// We're done reading this command, so have to start reading the next one from the beginning.
dataBufferIndex_ = 0;
// Exit the while loop, we're done with this command.
break;
}
if(incomingbyte==END_CHAR) // We've reached the end of this command.
{
// Null terminate the C string
inputDataBuffer_[dataBufferIndex_] = 0;
// Don't store anything here any more.
placeInBuffer_ = false;
// Make sure next command gets written to the start of the buffer.
dataBufferIndex_ = 0;
// Say that we've parsed the whole command.
return true;
}
else if (incomingbyte!=INPUT_START_CHAR) // Simply record the telecommand byte.
{
inputDataBuffer_[dataBufferIndex_++] = incomingbyte;
}
}
}
return false; // Something went wrong or we didn't receive an actual command.
}
// Extract commands and corresponding numbers from the inputDataBuffer input buffer.
void CommunicationInterface::parseInput(void)
{
// Serial.print("Buffer=");
// Serial.println(inputDataBuffer_);
// Holds the tokens used to match passed values to each listening module.
char * token;
// Get the first token. DATA_DELIMITER is a char but need to convert to const char*
token = strtok(inputDataBuffer_, String(DATA_DELIMITER).c_str());
// Parse the entire inputDataBuffer of tokens (commands and their value arguments).
int nextModuleIndex = -1; // Index of the module value for which is sent in this part of the telecommand.
while (token != NULL)
{
// Serial.print("Token=");
// Serial.println(token);
// If next module index < 0 we have no value to read now
if (nextModuleIndex >= 0)
{
#ifdef DEBUG_PRINTOUT
Serial.print("Trying to set value of module ");
Serial.print(modules_[nextModuleIndex]->getIdentifier());
Serial.print(" to ");
Serial.println( String(int(atof(token))) );
#endif
modules_[nextModuleIndex] -> setValue( int(atof(token)) );
// Indicate that on the next pass there is no value to read.
nextModuleIndex = -1;
}
else
{
// the current token may be a string corresponding to one of the modules
for(long int moduleI=0; moduleI<nModules_; moduleI++)
{
if (strcmp(token, modules_[moduleI]->getIdentifier()) == 0)
{
nextModuleIndex = moduleI;
break;
}
}
}
// Continue to the new token.
// If given a NULL pointer, the funciton continues from the point where
// the previous call finished, thereby moving along the buffer string.
token = strtok(NULL, String(DATA_DELIMITER).c_str());
}
// Reset the buffer as the first token is still in it
memset(&inputDataBuffer_[0], 0, sizeof(inputDataBuffer_));
}
<|endoftext|>
|
<commit_before>#include "imgui_extra.h"
#include "imgui.h"
#define _USE_MATH_DEFINES
#include <cmath>
namespace imgui
{
bool
Knob(const char* label, float* p_value, float v_min, float v_max)
{
constexpr auto pi = static_cast<float>(M_PI);
constexpr float angle_min = pi * 0.75f;
constexpr float angle_max = pi * 2.25f;
constexpr float radius_outer = 20.0f;
constexpr float radius_inner = radius_outer * 0.40f;
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 center = ImVec2(pos.x + radius_outer, pos.y + radius_outer);
float line_height = ImGui::GetTextLineHeight();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImGui::InvisibleButton(
label,
ImVec2(
radius_outer * 2,
radius_outer * 2 + line_height + style.ItemInnerSpacing.y));
const bool is_active = ImGui::IsItemActive();
const bool is_hovered = ImGui::IsItemHovered();
// changing value
const bool value_changed = is_active && io.MouseDelta.x != 0.0f;
if(value_changed)
{
float step = (v_max - v_min) / 200.0f;
*p_value += io.MouseDelta.x * step;
if(*p_value < v_min)
*p_value = v_min;
if(*p_value > v_max)
*p_value = v_max;
}
const float t = (*p_value - v_min) / (v_max - v_min);
const float angle = angle_min + (angle_max - angle_min) * t;
const float angle_cos = cosf(angle);
const float angle_sin = sinf(angle);
// colors
const auto label_color = ImGui::GetColorU32(ImGuiCol_Text);
const auto outer_circle_color = ImGui::GetColorU32(ImGuiCol_FrameBg);
const auto value_indicator_color =
ImGui::GetColorU32(ImGuiCol_SliderGrabActive);
const auto inner_circle_color = ImGui::GetColorU32(
is_active ? ImGuiCol_FrameBgActive
: is_hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
// visualization
draw_list->AddCircleFilled(center, radius_outer, outer_circle_color, 16);
draw_list->AddLine(
ImVec2(
center.x + angle_cos * radius_inner,
center.y + angle_sin * radius_inner),
ImVec2(
center.x + angle_cos * (radius_outer - 2),
center.y + angle_sin * (radius_outer - 2)),
value_indicator_color,
2.0f);
draw_list->AddCircleFilled(center, radius_inner, inner_circle_color, 16);
draw_list->AddText(
ImVec2(pos.x, pos.y + radius_outer * 2 + style.ItemInnerSpacing.y),
label_color,
label);
// tooltip
if(is_active || is_hovered)
{
ImGui::SetNextWindowPos(ImVec2(
pos.x - style.WindowPadding.x,
pos.y - line_height - style.ItemInnerSpacing.y -
style.WindowPadding.y));
ImGui::BeginTooltip();
ImGui::Text("%.3f", *p_value);
ImGui::EndTooltip();
}
return value_changed;
}
}<commit_msg>improved knob style<commit_after>#include "imgui_extra.h"
#include "imgui.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <sstream>
#include <imgui_internal.h>
namespace imgui
{
bool
Knob(const char* label, float* p_value, float v_min, float v_max)
{
constexpr auto pi = static_cast<float>(M_PI);
constexpr float angle_min = pi * 0.75f;
constexpr float angle_max = pi * 2.25f;
constexpr float angle_step = 20 * (pi / 180);
constexpr float size_outer = 20;
constexpr float peg_max_end = size_outer;
constexpr float peg_end = 19;
constexpr float peg_start = 15;
constexpr float knob_size = 15;
constexpr float knob_mark_start = 15;
constexpr float knob_mark_end = 8;
constexpr int seg = 16;
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const ImVec2 start = ImGui::GetCursorScreenPos();
const ImVec2 center = ImVec2(start.x + size_outer, start.y + size_outer);
const float line_height = ImGui::GetTextLineHeight();
ImGui::InvisibleButton(
label,
ImVec2(
size_outer * 2,
size_outer * 2 + line_height + style.ItemInnerSpacing.y));
const bool is_active = ImGui::IsItemActive();
const bool is_hovered = ImGui::IsItemHovered();
// changing value
const bool value_changed = is_active && io.MouseDelta.x != 0.0f;
if(value_changed)
{
float step = (v_max - v_min) / 200.0f;
*p_value += io.MouseDelta.x * step;
if(*p_value < v_min)
*p_value = v_min;
if(*p_value > v_max)
*p_value = v_max;
}
const float t = (*p_value - v_min) / (v_max - v_min);
const float angle = angle_min + (angle_max - angle_min) * t;
// colors
const auto label_color = ImGui::GetColorU32(ImGuiCol_Text);
const auto fill_color = ImGui::GetColorU32(ImGuiCol_FrameBg);
const auto knob_color = ImGui::GetColorU32(ImGuiCol_SliderGrab);
const auto indicator_color = ImGui::GetColorU32(ImGuiCol_Text);
const auto peg_color_off = ImGui::GetColorU32(ImGuiCol_TextDisabled);
const auto peg_color_max = ImGui::GetColorU32(ImGuiCol_Text);
// util function
const auto Pos = [=](float angle, float rad) -> ImVec2 {
return ImVec2(center.x + cosf(angle) * rad, center.y + sinf(angle) * rad);
};
// ----------------- visualization
// background
draw_list->AddCircleFilled(center, size_outer, fill_color, seg);
// peg indicators
for(float a = angle_min; a <= angle; a += angle_step)
{
draw_list->AddLine(
Pos(a, peg_start), Pos(a, peg_end), peg_color_off, 1.0f);
}
draw_list->AddLine(
Pos(angle_max, peg_start),
Pos(angle_max, peg_max_end),
peg_color_max,
1.0f);
draw_list->AddLine(
Pos(angle_min, peg_start),
Pos(angle_min, peg_max_end),
peg_color_max,
1.0f);
// the knob
draw_list->AddCircleFilled(center, knob_size, knob_color, seg);
draw_list->AddLine(
Pos(angle, knob_mark_start),
Pos(angle, knob_mark_end),
indicator_color,
2.0f);
// knob control name
draw_list->AddText(
ImVec2(start.x, start.y + size_outer * 2 + style.ItemInnerSpacing.y),
label_color,
label);
// tooltip
if(is_active || is_hovered)
{
ImGui::SetNextWindowPos(ImVec2(
start.x - style.WindowPadding.x,
start.y - line_height - style.ItemInnerSpacing.y -
style.WindowPadding.y));
ImGui::BeginTooltip();
ImGui::Text("%.3f", *p_value);
ImGui::EndTooltip();
}
return value_changed;
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details
#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include "CPU.h"
namespace hcc {
struct ROM : public IROM {
unsigned short *data;
static const unsigned int size = 0x8000;
ROM() {
data = new unsigned short[size];
}
virtual ~ROM() {
delete[] data;
}
bool load(const char *filename) {
std::ifstream input(filename);
std::string line;
unsigned int counter = 0;
while (input.good() && counter < size) {
getline(input, line);
if (line.size() == 0)
continue;
if (line.size() != 16)
return false;
unsigned int instruction = 0;
for (unsigned int i = 0; i<16; ++i) {
instruction <<= 1;
switch (line[i]) {
case '0':
break;
case '1':
instruction |= 1;
break;
default:
return false;
}
}
data[counter++] = instruction;
}
// clear the rest
while (counter < size) {
data[counter++] = 0;
}
return true;
}
virtual unsigned short get(unsigned int address) const {
if (address < size) {
return data[address];
} else {
std::cerr << "requested memory at " << address << '\n';
throw std::runtime_error("Memory::get");
}
}
};
} // end namespace
struct GUIEmulatorRAM : public hcc::IRAM {
static const unsigned int CHANNELS = 3;
static const unsigned int SCREEN_WIDTH = 512;
static const unsigned int SCREEN_HEIGHT = 256;
static const unsigned int size = 0x6001;
unsigned short *data;
unsigned char *vram;
GdkPixbuf *pixbuf;
GtkWidget *screen;
void putpixel(unsigned short x, unsigned short y, bool black) {
unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);
for (unsigned int channel = 0; channel<CHANNELS; ++channel) {
vram[offset++] = black ? 0x00 : 0xff;
}
}
public:
GUIEmulatorRAM() {
data = new unsigned short[size];
vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];
pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);
screen = gtk_image_new_from_pixbuf(pixbuf);
}
virtual ~GUIEmulatorRAM() {
delete[] data;
delete[] vram;
}
void keyboard(unsigned short value) {
data[0x6000] = value;
}
GtkWidget* getScreenWidget() {
return screen;
}
virtual void set(unsigned int address, unsigned short value) {
if (address >= size) {
throw std::runtime_error("RAM::set");
}
data[address] = value;
// check if we are writing to video RAM
if (0x4000 <= address && address <0x6000) {
address -= 0x4000;
unsigned short y = address / 32;
unsigned short x = 16*(address % 32);
for (int bit = 0; bit<16; ++bit) {
putpixel(x + bit, y, value & 1);
value = value >> 1;
}
gdk_threads_enter();
gtk_widget_queue_draw(screen);
gdk_threads_leave();
}
}
virtual unsigned short get(unsigned int address) const {
if (address >= size) {
throw std::runtime_error("RAM::get");
}
return data[address];
}
};
hcc::ROM rom;
GUIEmulatorRAM *ram;
hcc::CPU cpu;
bool running = false;
GtkWidget *window;
GtkToolItem *button_load, *button_run, *button_pause;
void load_clicked(GtkButton *button, gpointer user_data)
{
bool loaded = false;
GtkWidget *dialog = gtk_file_chooser_dialog_new(
"Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN,
"gtk-cancel", GTK_RESPONSE_CANCEL,
"gtk-open", GTK_RESPONSE_ACCEPT,
NULL);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
loaded = rom.load(filename);
g_free(filename);
}
gtk_widget_destroy(dialog);
if (!loaded) {
GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window),
GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
"Error loading program");
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
} else {
cpu.reset();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
}
}
gpointer run_thread(gpointer user_data)
{
int steps = 0;
while (running) {
cpu.step(&rom, ram);
if (steps>100) {
g_usleep(10);
steps = 0;
}
++steps;
}
return NULL;
}
void run_clicked()
{
assert(!running);
running = true;
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);
g_thread_create(run_thread, NULL, FALSE, NULL);
}
void pause_clicked()
{
assert(running);
running = false;
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);
}
// Translate special keys. See Figure 5.6 in TECS book.
unsigned short translate(guint keyval)
{
switch (keyval) {
case GDK_KEY_Return: return 128;
case GDK_KEY_BackSpace: return 129;
case GDK_KEY_Left: return 130;
case GDK_KEY_Up: return 131;
case GDK_KEY_Right: return 132;
case GDK_KEY_Down: return 133;
case GDK_KEY_Home: return 134;
case GDK_KEY_End: return 135;
case GDK_KEY_Page_Up: return 136;
case GDK_KEY_Page_Down: return 137;
case GDK_KEY_Insert: return 138;
case GDK_KEY_Delete: return 139;
case GDK_KEY_Escape: return 140;
case GDK_KEY_F1: return 141;
case GDK_KEY_F2: return 142;
case GDK_KEY_F3: return 143;
case GDK_KEY_F4: return 144;
case GDK_KEY_F5: return 145;
case GDK_KEY_F6: return 146;
case GDK_KEY_F7: return 147;
case GDK_KEY_F8: return 148;
case GDK_KEY_F9: return 149;
case GDK_KEY_F10: return 150;
case GDK_KEY_F11: return 151;
case GDK_KEY_F12: return 152;
}
return keyval;
}
gboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
if (event->type == GDK_KEY_RELEASE) {
ram->keyboard(0);
} else {
ram->keyboard(translate(event->keyval));
}
return TRUE;
}
GtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback)
{
GtkToolItem *button = gtk_tool_button_new(NULL, text);
gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id);
gtk_tool_item_set_tooltip_text(button, text);
g_signal_connect(button, "clicked", callback, NULL);
return button;
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
ram = new GUIEmulatorRAM();
/* toolbar buttons */
button_load = create_button("document-open", "Load...", G_CALLBACK(load_clicked));
button_run = create_button("media-playback-start", "Run", G_CALLBACK(run_clicked));
button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(pause_clicked));
GtkToolItem *separator1 = gtk_separator_tool_item_new();
gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
/* toolbar itself */
GtkWidget *toolbar = gtk_toolbar_new();
gtk_widget_set_hexpand(toolbar, TRUE);
gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);
/* keyboard */
GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
g_signal_connect(keyboard, "key-press-event", G_CALLBACK(keyboard_callback), NULL);
g_signal_connect(keyboard, "key-release-event", G_CALLBACK(keyboard_callback), NULL);
/* main layout */
GtkWidget *grid = gtk_grid_new();
gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), ram->getScreenWidget(), 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);
/* main window */
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "HACK emulator");
gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
gtk_window_set_focus(GTK_WINDOW(window), NULL);
g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_container_add(GTK_CONTAINER(window), grid);
gtk_widget_show_all(window);
gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
gtk_main();
return 0;
}
<commit_msg>Got rid of global state<commit_after>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details
#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include "CPU.h"
namespace hcc {
struct ROM : public IROM {
unsigned short *data;
static const unsigned int size = 0x8000;
ROM() {
data = new unsigned short[size];
}
virtual ~ROM() {
delete[] data;
}
bool load(const char *filename) {
std::ifstream input(filename);
std::string line;
unsigned int counter = 0;
while (input.good() && counter < size) {
getline(input, line);
if (line.size() == 0)
continue;
if (line.size() != 16)
return false;
unsigned int instruction = 0;
for (unsigned int i = 0; i<16; ++i) {
instruction <<= 1;
switch (line[i]) {
case '0':
break;
case '1':
instruction |= 1;
break;
default:
return false;
}
}
data[counter++] = instruction;
}
// clear the rest
while (counter < size) {
data[counter++] = 0;
}
return true;
}
virtual unsigned short get(unsigned int address) const {
if (address < size) {
return data[address];
} else {
std::cerr << "requested memory at " << address << '\n';
throw std::runtime_error("Memory::get");
}
}
};
} // end namespace
struct GUIEmulatorRAM : public hcc::IRAM {
static const unsigned int CHANNELS = 3;
static const unsigned int SCREEN_WIDTH = 512;
static const unsigned int SCREEN_HEIGHT = 256;
static const unsigned int size = 0x6001;
unsigned short *data;
unsigned char *vram;
GdkPixbuf *pixbuf;
GtkWidget *screen;
void putpixel(unsigned short x, unsigned short y, bool black) {
unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);
for (unsigned int channel = 0; channel<CHANNELS; ++channel) {
vram[offset++] = black ? 0x00 : 0xff;
}
}
public:
GUIEmulatorRAM() {
data = new unsigned short[size];
vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];
pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);
screen = gtk_image_new_from_pixbuf(pixbuf);
}
virtual ~GUIEmulatorRAM() {
delete[] data;
delete[] vram;
}
void keyboard(unsigned short value) {
data[0x6000] = value;
}
GtkWidget* getScreenWidget() {
return screen;
}
virtual void set(unsigned int address, unsigned short value) {
if (address >= size) {
throw std::runtime_error("RAM::set");
}
data[address] = value;
// check if we are writing to video RAM
if (0x4000 <= address && address <0x6000) {
address -= 0x4000;
unsigned short y = address / 32;
unsigned short x = 16*(address % 32);
for (int bit = 0; bit<16; ++bit) {
putpixel(x + bit, y, value & 1);
value = value >> 1;
}
gdk_threads_enter();
gtk_widget_queue_draw(screen);
gdk_threads_leave();
}
}
virtual unsigned short get(unsigned int address) const {
if (address >= size) {
throw std::runtime_error("RAM::get");
}
return data[address];
}
};
struct emulator {
hcc::ROM rom;
GUIEmulatorRAM ram;
hcc::CPU cpu;
bool running = false;
GtkWidget* window;
GtkToolItem* button_load;
GtkToolItem* button_run;
GtkToolItem* button_pause;
};
void load_clicked(GtkButton *button, gpointer user_data)
{
emulator* e = reinterpret_cast<emulator*>(user_data);
bool loaded = false;
GtkWidget *dialog = gtk_file_chooser_dialog_new(
"Load ROM", GTK_WINDOW(e->window), GTK_FILE_CHOOSER_ACTION_OPEN,
"gtk-cancel", GTK_RESPONSE_CANCEL,
"gtk-open", GTK_RESPONSE_ACCEPT,
NULL);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
loaded = e->rom.load(filename);
g_free(filename);
}
gtk_widget_destroy(dialog);
if (!loaded) {
GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(e->window),
GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
"Error loading program");
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
} else {
e->cpu.reset();
gtk_widget_set_sensitive(GTK_WIDGET(e->button_run), TRUE);
}
}
gpointer run_thread(gpointer user_data)
{
emulator* e = reinterpret_cast<emulator*>(user_data);
int steps = 0;
while (e->running) {
e->cpu.step(&e->rom, &e->ram);
if (steps>100) {
g_usleep(10);
steps = 0;
}
++steps;
}
return NULL;
}
void run_clicked(GtkButton *button, gpointer user_data)
{
emulator* e = reinterpret_cast<emulator*>(user_data);
assert(!e->running);
e->running = true;
gtk_widget_set_sensitive(GTK_WIDGET(e->button_run), FALSE);
gtk_widget_set_visible(GTK_WIDGET(e->button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(e->button_pause), TRUE);
gtk_widget_set_visible(GTK_WIDGET(e->button_pause), TRUE);
g_thread_create(run_thread, e, FALSE, NULL);
}
void pause_clicked(GtkButton *button, gpointer user_data)
{
emulator* e = reinterpret_cast<emulator*>(user_data);
assert(e->running);
e->running = false;
gtk_widget_set_sensitive(GTK_WIDGET(e->button_pause), FALSE);
gtk_widget_set_visible(GTK_WIDGET(e->button_pause), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(e->button_run), TRUE);
gtk_widget_set_visible(GTK_WIDGET(e->button_run), TRUE);
}
// Translate special keys. See Figure 5.6 in TECS book.
unsigned short translate(guint keyval)
{
switch (keyval) {
case GDK_KEY_Return: return 128;
case GDK_KEY_BackSpace: return 129;
case GDK_KEY_Left: return 130;
case GDK_KEY_Up: return 131;
case GDK_KEY_Right: return 132;
case GDK_KEY_Down: return 133;
case GDK_KEY_Home: return 134;
case GDK_KEY_End: return 135;
case GDK_KEY_Page_Up: return 136;
case GDK_KEY_Page_Down: return 137;
case GDK_KEY_Insert: return 138;
case GDK_KEY_Delete: return 139;
case GDK_KEY_Escape: return 140;
case GDK_KEY_F1: return 141;
case GDK_KEY_F2: return 142;
case GDK_KEY_F3: return 143;
case GDK_KEY_F4: return 144;
case GDK_KEY_F5: return 145;
case GDK_KEY_F6: return 146;
case GDK_KEY_F7: return 147;
case GDK_KEY_F8: return 148;
case GDK_KEY_F9: return 149;
case GDK_KEY_F10: return 150;
case GDK_KEY_F11: return 151;
case GDK_KEY_F12: return 152;
}
return keyval;
}
gboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
emulator* e = reinterpret_cast<emulator*>(user_data);
if (event->type == GDK_KEY_RELEASE) {
e->ram.keyboard(0);
} else {
e->ram.keyboard(translate(event->keyval));
}
return TRUE;
}
GtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback, gpointer user_data)
{
GtkToolItem *button = gtk_tool_button_new(NULL, text);
gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id);
gtk_tool_item_set_tooltip_text(button, text);
g_signal_connect(button, "clicked", callback, user_data);
return button;
}
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
emulator e;
/* toolbar buttons */
e.button_load = create_button("document-open", "Load...", G_CALLBACK(load_clicked), &e);
e.button_run = create_button("media-playback-start", "Run", G_CALLBACK(run_clicked), &e);
e.button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(pause_clicked), &e);
GtkToolItem *separator1 = gtk_separator_tool_item_new();
gtk_widget_set_sensitive(GTK_WIDGET(e.button_run), FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(e.button_pause), FALSE);
/* toolbar itself */
GtkWidget *toolbar = gtk_toolbar_new();
gtk_widget_set_hexpand(toolbar, TRUE);
gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), e.button_load, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), e.button_run, -1);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), e.button_pause, -1);
/* keyboard */
GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
g_signal_connect(keyboard, "key-press-event", G_CALLBACK(keyboard_callback), &e);
g_signal_connect(keyboard, "key-release-event", G_CALLBACK(keyboard_callback), &e);
/* main layout */
GtkWidget *grid = gtk_grid_new();
gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), e.ram.getScreenWidget(), 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);
/* main window */
e.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(e.window), "HACK emulator");
gtk_window_set_resizable(GTK_WINDOW(e.window), FALSE);
gtk_window_set_focus(GTK_WINDOW(e.window), NULL);
g_signal_connect(e.window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
gtk_container_add(GTK_CONTAINER(e.window), grid);
gtk_widget_show_all(e.window);
gtk_widget_set_visible(GTK_WIDGET(e.button_pause), FALSE);
gtk_main();
return 0;
}
<|endoftext|>
|
<commit_before>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
*
* 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.
* - The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// }}}
#include "ConnectionPage.h"
#include "ArtProvider.h"
#include "Dubnium.h"
#include "PaneMenu.h"
#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/sizer.h>
#include <wx/toolbar.h>
// {{{ Event table
BEGIN_EVENT_TABLE(ConnectionPage, wxPanel)
EVT_DBGP_STATUSCHANGE(wxID_ANY, ConnectionPage::OnStatusChange)
EVT_DBGP_STDERR(wxID_ANY, ConnectionPage::OnStderr)
EVT_DBGP_STDOUT(wxID_ANY, ConnectionPage::OnStdout)
EVT_TOOL(ID_CONNECTIONPAGE_BREAK, ConnectionPage::OnBreak)
EVT_TOOL(ID_CONNECTIONPAGE_PANES, ConnectionPage::OnPanes)
EVT_TOOL(ID_CONNECTIONPAGE_RUN, ConnectionPage::OnRun)
EVT_TOOL(ID_CONNECTIONPAGE_RUN_TO_CURSOR, ConnectionPage::OnRunToCursor)
EVT_TOOL(ID_CONNECTIONPAGE_STEPINTO, ConnectionPage::OnStepInto)
EVT_TOOL(ID_CONNECTIONPAGE_STEPOUT, ConnectionPage::OnStepOut)
EVT_TOOL(ID_CONNECTIONPAGE_STEPOVER, ConnectionPage::OnStepOver)
END_EVENT_TABLE()
// }}}
// {{{ ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language)
ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language) : wxPanel(parent, ID_CONNECTIONPAGE), conn(conn), language(language), level(level), script(fileURI), unavailable(true) {
config = wxConfigBase::Get();
conn->SetEventHandler(this);
breakSupported = conn->CommandSupported(wxT("break"));
CreateToolBar();
breakpoint = new BreakpointPanel(this);
output = new OutputPanel(this);
properties = new PropertiesPanel(this);
source = new SourcePanel(this);
stack = new StackPanel(this);
SetSource(fileURI);
wxAuiPaneInfo defaultPane;
defaultPane.Floatable(false).CloseButton(true);
mgr = new wxAuiManager(this);
mgr->AddPane(toolbar, wxAuiPaneInfo().ToolbarPane().Top().Position(0).Floatable(false));
mgr->AddPane(output, wxAuiPaneInfo(defaultPane).Bottom().Position(0).Caption(_("Output")).MinSize(wxSize(1, 150)));
mgr->AddPane(breakpoint, wxAuiPaneInfo(defaultPane).Bottom().Position(2).Caption(_("Breakpoints")).MinSize(wxSize(1, 150)));
mgr->AddPane(stack, wxAuiPaneInfo(defaultPane).Right().Position(0).Caption(_("Call Stack")).MinSize(wxSize(200, 1)));
mgr->AddPane(properties, wxAuiPaneInfo(defaultPane).Right().Position(1).Caption(_("Properties")).MinSize(wxSize(200, 1)));
mgr->AddPane(source, wxAuiPaneInfo().CentrePane().Caption(_("Source")).CaptionVisible(true));
#ifdef PERSPECTIVE
wxString perspective(config->Read(wxT("Perspective"), wxEmptyString));
if (perspective.Len() > 0) {
mgr->LoadPerspective(perspective);
}
#endif
mgr->Update();
RestoreStickyBreakpoints();
}
// }}}
// {{{ void ConnectionPage::BreakpointAdd(int line, bool temporary)
void ConnectionPage::BreakpointAdd(int line, bool temporary) {
if (!unavailable) {
DBGp::Breakpoint *bp = conn->CreateBreakpoint();
bp->SetLineType(lastFile, line);
if (temporary) {
bp->SetTemporary(true);
}
bp->Set();
if (temporary) {
conn->Run();
}
else {
breakpoint->Update();
}
}
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(const wxString &file, int line)
void ConnectionPage::BreakpointRemove(const wxString &file, int line) {
source->tc->SetBreakpointStyle(line, false);
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(int line)
void ConnectionPage::BreakpointRemove(int line) {
if (!unavailable) {
DBGp::Breakpoint *bp = breakpoint->GetFileBreakpoint(lastFile, line);
if (bp) {
conn->RemoveBreakpoint(bp);
breakpoint->Update();
}
}
}
// }}}
// {{{ DBGp::Property *ConnectionPage::GetProperty(const wxString &name)
DBGp::Property *ConnectionPage::GetProperty(const wxString &name) {
return properties->GetProperty(name);
}
// }}}
// {{{ wxString ConnectionPage::GetPropertyValue(const wxString &name) const
wxString ConnectionPage::GetPropertyValue(const wxString &name) const {
return properties->GetPropertyValue(name);
}
// }}}
// {{{ void ConnectionPage::SavePerspective()
void ConnectionPage::SavePerspective() {
config->Write(wxT("Perspective"), mgr->SavePerspective());
}
// }}}
// {{{ void ConnectionPage::SetStackLevel(DBGp::StackLevel *level)
void ConnectionPage::SetStackLevel(DBGp::StackLevel *level) {
this->level = level;
properties->SetStackLevel(level);
SetSource(level->GetFileName(), level->GetLineNo());
}
// }}}
// {{{ void ConnectionPage::CreateToolBar()
void ConnectionPage::CreateToolBar() {
wxSize size(ArtProvider::toolbarSize, ArtProvider::toolbarSize);
toolbar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
toolbar->SetToolBitmapSize(size);
toolbar->AddTool(ID_CONNECTIONPAGE_OPEN, _("Open"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, size), _("Open a source file"));
toolbar->AddSeparator();
toolbar->AddTool(ID_CONNECTIONPAGE_RUN, _("Run"), wxArtProvider::GetBitmap(wxT("run"), wxART_TOOLBAR, size), _("Run"));
if (breakSupported) {
toolbar->AddTool(ID_CONNECTIONPAGE_BREAK, _("Break"), wxArtProvider::GetBitmap(wxT("break"), wxART_TOOLBAR, size), _("Break"));
}
toolbar->AddTool(ID_CONNECTIONPAGE_STEPINTO, _("Step Into"), wxArtProvider::GetBitmap(wxT("step-into"), wxART_TOOLBAR, size), _("Step Into"));
toolbar->AddTool(ID_CONNECTIONPAGE_STEPOVER, _("Step Over"), wxArtProvider::GetBitmap(wxT("step-over"), wxART_TOOLBAR, size), _("Step Over"));
toolbar->AddTool(ID_CONNECTIONPAGE_STEPOUT, _("Step Out"), wxArtProvider::GetBitmap(wxT("step-out"), wxART_TOOLBAR, size), _("Step Out"));
toolbar->AddSeparator();
toolbar->AddTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, _("Run to Cursor"), wxArtProvider::GetBitmap(wxT("run-to-cursor"), wxART_TOOLBAR, size), _("Run to Cursor"));
toolbar->AddSeparator();
toolbar->AddTool(ID_CONNECTIONPAGE_PANES, _("Panes"), wxArtProvider::GetBitmap(wxT("panes"), wxART_TOOLBAR, size), _("Toggle which panes are displayed"));
toolbar->Realize();
// Disable the tools that don't make sense at the start.
UpdateToolBar(true, false, true, false, false);
}
// }}}
// {{{ void ConnectionPage::OnBreak(wxCommandEvent &event)
void ConnectionPage::OnBreak(wxCommandEvent &event) {
conn->Break();
}
// }}}
// {{{ void ConnectionPage::OnPanes(wxCommandEvent &event)
void ConnectionPage::OnPanes(wxCommandEvent &event) {
PaneMenu menu(this, _("Panes"), mgr->GetAllPanes());
PopupMenu(&menu);
wxAuiPaneInfo *pane = menu.GetPane();
if (pane) {
pane->Show(!(pane->IsShown()));
mgr->Update();
}
}
// }}}
// {{{ void ConnectionPage::OnRun(wxCommandEvent &event)
void ConnectionPage::OnRun(wxCommandEvent &event) {
UpdateToolBar(false, true, false, false, false);
conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnRunToCursor(wxCommandEvent &event)
void ConnectionPage::OnRunToCursor(wxCommandEvent &event) {
DBGp::Breakpoint *bp;
int line = source->tc->LineFromPosition(source->tc->GetCurrentPos()) + 1;
bp = conn->CreateBreakpoint();
bp->SetLineType(lastFile, line);
bp->SetTemporary(true);
bp->Set();
UpdateToolBar(false, true, false, false, false);
conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event)
void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event) {
if (event.GetStatus() == DBGp::Connection::BREAK) {
UpdateToolBar(true, false, true, true, true);
UpdateStack();
}
else if (event.GetStatus() == DBGp::Connection::RUNNING) {
UpdateToolBar(false, true, false, false, false);
}
else {
UpdateToolBar(false, false, false, false, false);
breakpoint->Enable(false);
stack->SetStack(NULL);
properties->SetStackLevel(NULL);
source->Unavailable(_("No source is available as execution has finished."));
unavailable = true;
}
}
// }}}
// {{{ void ConnectionPage::OnStderr(DBGp::StderrEvent &event)
void ConnectionPage::OnStderr(DBGp::StderrEvent &event) {
output->AppendStderr(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStdout(DBGp::StdoutEvent &event)
void ConnectionPage::OnStdout(DBGp::StdoutEvent &event) {
output->AppendStdout(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStepInto(wxCommandEvent &event)
void ConnectionPage::OnStepInto(wxCommandEvent &event) {
conn->StepInto();
}
// }}}
// {{{ void ConnectionPage::OnStepOut(wxCommandEvent &event)
void ConnectionPage::OnStepOut(wxCommandEvent &event) {
conn->StepOut();
}
// }}}
// {{{ void ConnectionPage::OnStepOver(wxCommandEvent &event)
void ConnectionPage::OnStepOver(wxCommandEvent &event) {
conn->StepOver();
}
// }}}
// {{{ void ConnectionPage::RestoreStickyBreakpoints()
void ConnectionPage::RestoreStickyBreakpoints() {
std::vector<StickyBreakpoint> breakpoints(wxGetApp().GetStickyBreakpoints(script));
wxLogDebug(wxT("Restoring sticky breakpoints for script %s..."), script.c_str());
for (std::vector<StickyBreakpoint>::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
DBGp::Breakpoint *bp = conn->CreateBreakpoint();
switch (i->GetType()) {
case DBGp::Breakpoint::CALL:
wxLogDebug(wxT("Sticky breakpoint of CALL type: %s."), i->GetArgument().c_str());
bp->SetCallType(i->GetArgument());
break;
case DBGp::Breakpoint::EXCEPTION:
wxLogDebug(wxT("Sticky breakpoint of EXCEPTION type: %s."), i->GetArgument().c_str());
bp->SetExceptionType(i->GetArgument());
break;
case DBGp::Breakpoint::RETURN:
wxLogDebug(wxT("Sticky breakpoint of RETURN type: %s."), i->GetArgument().c_str());
bp->SetReturnType(i->GetArgument());
break;
default:
wxLogError(wxT("Sticky breakpoint of unknown type."));
break;
}
bp->Set();
}
breakpoint->Update();
}
// }}}
// {{{ void ConnectionPage::SetSource(const wxString &file, int line)
void ConnectionPage::SetSource(const wxString &file, int line) {
if (file != lastFile) {
try {
source->tc->SetSource(conn->Source(file), line);
source->tc->SetLexerLanguage(language);
lastFile = file;
DBGp::Connection::BreakpointList list(breakpoint->GetFileBreakpoints(file));
for (DBGp::Connection::BreakpointList::const_iterator i = list.begin(); i != list.end(); i++) {
source->tc->SetBreakpointStyle((*i)->GetLineNo(), true);
}
unavailable = false;
}
catch (DBGp::Error e) {
source->Unavailable(_("No source is available for this stack frame."));
unavailable = true;
}
}
else if (line >= 0) {
source->tc->SetLine(line);
}
}
// }}}
// {{{ void ConnectionPage::UpdateStack()
void ConnectionPage::UpdateStack() {
DBGp::Stack stack(conn->StackGet());
this->stack->SetStack(&stack);
SetStackLevel(stack.GetLevel(0));
}
// }}}
// {{{ void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut)
void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut) {
toolbar->EnableTool(ID_CONNECTIONPAGE_RUN, run);
toolbar->EnableTool(ID_CONNECTIONPAGE_BREAK, brk);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPINTO, stepInto);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOVER, stepOver);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOUT, stepOut);
toolbar->EnableTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, run);
}
// }}}
// vim:set fdm=marker ts=8 sw=8 noet cin:
<commit_msg>Disabled the useless open file toolbar button.<commit_after>// {{{ Copyright notice
/* Copyright (c) 2007-2009, Adam Harvey
*
* 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.
* - The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// }}}
#include "ConnectionPage.h"
#include "ArtProvider.h"
#include "Dubnium.h"
#include "PaneMenu.h"
#include <wx/artprov.h>
#include <wx/log.h>
#include <wx/sizer.h>
#include <wx/toolbar.h>
// {{{ Event table
BEGIN_EVENT_TABLE(ConnectionPage, wxPanel)
EVT_DBGP_STATUSCHANGE(wxID_ANY, ConnectionPage::OnStatusChange)
EVT_DBGP_STDERR(wxID_ANY, ConnectionPage::OnStderr)
EVT_DBGP_STDOUT(wxID_ANY, ConnectionPage::OnStdout)
EVT_TOOL(ID_CONNECTIONPAGE_BREAK, ConnectionPage::OnBreak)
EVT_TOOL(ID_CONNECTIONPAGE_PANES, ConnectionPage::OnPanes)
EVT_TOOL(ID_CONNECTIONPAGE_RUN, ConnectionPage::OnRun)
EVT_TOOL(ID_CONNECTIONPAGE_RUN_TO_CURSOR, ConnectionPage::OnRunToCursor)
EVT_TOOL(ID_CONNECTIONPAGE_STEPINTO, ConnectionPage::OnStepInto)
EVT_TOOL(ID_CONNECTIONPAGE_STEPOUT, ConnectionPage::OnStepOut)
EVT_TOOL(ID_CONNECTIONPAGE_STEPOVER, ConnectionPage::OnStepOver)
END_EVENT_TABLE()
// }}}
// {{{ ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language)
ConnectionPage::ConnectionPage(wxWindow *parent, DBGp::Connection *conn, const wxString &fileURI, const wxString &language) : wxPanel(parent, ID_CONNECTIONPAGE), conn(conn), language(language), level(level), script(fileURI), unavailable(true) {
config = wxConfigBase::Get();
conn->SetEventHandler(this);
breakSupported = conn->CommandSupported(wxT("break"));
CreateToolBar();
breakpoint = new BreakpointPanel(this);
output = new OutputPanel(this);
properties = new PropertiesPanel(this);
source = new SourcePanel(this);
stack = new StackPanel(this);
SetSource(fileURI);
wxAuiPaneInfo defaultPane;
defaultPane.Floatable(false).CloseButton(true);
mgr = new wxAuiManager(this);
mgr->AddPane(toolbar, wxAuiPaneInfo().ToolbarPane().Top().Position(0).Floatable(false));
mgr->AddPane(output, wxAuiPaneInfo(defaultPane).Bottom().Position(0).Caption(_("Output")).MinSize(wxSize(1, 150)));
mgr->AddPane(breakpoint, wxAuiPaneInfo(defaultPane).Bottom().Position(2).Caption(_("Breakpoints")).MinSize(wxSize(1, 150)));
mgr->AddPane(stack, wxAuiPaneInfo(defaultPane).Right().Position(0).Caption(_("Call Stack")).MinSize(wxSize(200, 1)));
mgr->AddPane(properties, wxAuiPaneInfo(defaultPane).Right().Position(1).Caption(_("Properties")).MinSize(wxSize(200, 1)));
mgr->AddPane(source, wxAuiPaneInfo().CentrePane().Caption(_("Source")).CaptionVisible(true));
#ifdef PERSPECTIVE
wxString perspective(config->Read(wxT("Perspective"), wxEmptyString));
if (perspective.Len() > 0) {
mgr->LoadPerspective(perspective);
}
#endif
mgr->Update();
RestoreStickyBreakpoints();
}
// }}}
// {{{ void ConnectionPage::BreakpointAdd(int line, bool temporary)
void ConnectionPage::BreakpointAdd(int line, bool temporary) {
if (!unavailable) {
DBGp::Breakpoint *bp = conn->CreateBreakpoint();
bp->SetLineType(lastFile, line);
if (temporary) {
bp->SetTemporary(true);
}
bp->Set();
if (temporary) {
conn->Run();
}
else {
breakpoint->Update();
}
}
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(const wxString &file, int line)
void ConnectionPage::BreakpointRemove(const wxString &file, int line) {
source->tc->SetBreakpointStyle(line, false);
}
// }}}
// {{{ void ConnectionPage::BreakpointRemove(int line)
void ConnectionPage::BreakpointRemove(int line) {
if (!unavailable) {
DBGp::Breakpoint *bp = breakpoint->GetFileBreakpoint(lastFile, line);
if (bp) {
conn->RemoveBreakpoint(bp);
breakpoint->Update();
}
}
}
// }}}
// {{{ DBGp::Property *ConnectionPage::GetProperty(const wxString &name)
DBGp::Property *ConnectionPage::GetProperty(const wxString &name) {
return properties->GetProperty(name);
}
// }}}
// {{{ wxString ConnectionPage::GetPropertyValue(const wxString &name) const
wxString ConnectionPage::GetPropertyValue(const wxString &name) const {
return properties->GetPropertyValue(name);
}
// }}}
// {{{ void ConnectionPage::SavePerspective()
void ConnectionPage::SavePerspective() {
config->Write(wxT("Perspective"), mgr->SavePerspective());
}
// }}}
// {{{ void ConnectionPage::SetStackLevel(DBGp::StackLevel *level)
void ConnectionPage::SetStackLevel(DBGp::StackLevel *level) {
this->level = level;
properties->SetStackLevel(level);
SetSource(level->GetFileName(), level->GetLineNo());
}
// }}}
// {{{ void ConnectionPage::CreateToolBar()
void ConnectionPage::CreateToolBar() {
wxSize size(ArtProvider::toolbarSize, ArtProvider::toolbarSize);
toolbar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL | wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
toolbar->SetToolBitmapSize(size);
#if 0
toolbar->AddTool(ID_CONNECTIONPAGE_OPEN, _("Open"), wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, size), _("Open a source file"));
toolbar->AddSeparator();
#endif
toolbar->AddTool(ID_CONNECTIONPAGE_RUN, _("Run"), wxArtProvider::GetBitmap(wxT("run"), wxART_TOOLBAR, size), _("Run"));
if (breakSupported) {
toolbar->AddTool(ID_CONNECTIONPAGE_BREAK, _("Break"), wxArtProvider::GetBitmap(wxT("break"), wxART_TOOLBAR, size), _("Break"));
}
toolbar->AddTool(ID_CONNECTIONPAGE_STEPINTO, _("Step Into"), wxArtProvider::GetBitmap(wxT("step-into"), wxART_TOOLBAR, size), _("Step Into"));
toolbar->AddTool(ID_CONNECTIONPAGE_STEPOVER, _("Step Over"), wxArtProvider::GetBitmap(wxT("step-over"), wxART_TOOLBAR, size), _("Step Over"));
toolbar->AddTool(ID_CONNECTIONPAGE_STEPOUT, _("Step Out"), wxArtProvider::GetBitmap(wxT("step-out"), wxART_TOOLBAR, size), _("Step Out"));
toolbar->AddSeparator();
toolbar->AddTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, _("Run to Cursor"), wxArtProvider::GetBitmap(wxT("run-to-cursor"), wxART_TOOLBAR, size), _("Run to Cursor"));
toolbar->AddSeparator();
toolbar->AddTool(ID_CONNECTIONPAGE_PANES, _("Panes"), wxArtProvider::GetBitmap(wxT("panes"), wxART_TOOLBAR, size), _("Toggle which panes are displayed"));
toolbar->Realize();
// Disable the tools that don't make sense at the start.
UpdateToolBar(true, false, true, false, false);
}
// }}}
// {{{ void ConnectionPage::OnBreak(wxCommandEvent &event)
void ConnectionPage::OnBreak(wxCommandEvent &event) {
conn->Break();
}
// }}}
// {{{ void ConnectionPage::OnPanes(wxCommandEvent &event)
void ConnectionPage::OnPanes(wxCommandEvent &event) {
PaneMenu menu(this, _("Panes"), mgr->GetAllPanes());
PopupMenu(&menu);
wxAuiPaneInfo *pane = menu.GetPane();
if (pane) {
pane->Show(!(pane->IsShown()));
mgr->Update();
}
}
// }}}
// {{{ void ConnectionPage::OnRun(wxCommandEvent &event)
void ConnectionPage::OnRun(wxCommandEvent &event) {
UpdateToolBar(false, true, false, false, false);
conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnRunToCursor(wxCommandEvent &event)
void ConnectionPage::OnRunToCursor(wxCommandEvent &event) {
DBGp::Breakpoint *bp;
int line = source->tc->LineFromPosition(source->tc->GetCurrentPos()) + 1;
bp = conn->CreateBreakpoint();
bp->SetLineType(lastFile, line);
bp->SetTemporary(true);
bp->Set();
UpdateToolBar(false, true, false, false, false);
conn->Run();
}
// }}}
// {{{ void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event)
void ConnectionPage::OnStatusChange(DBGp::StatusChangeEvent &event) {
if (event.GetStatus() == DBGp::Connection::BREAK) {
UpdateToolBar(true, false, true, true, true);
UpdateStack();
}
else if (event.GetStatus() == DBGp::Connection::RUNNING) {
UpdateToolBar(false, true, false, false, false);
}
else {
UpdateToolBar(false, false, false, false, false);
breakpoint->Enable(false);
stack->SetStack(NULL);
properties->SetStackLevel(NULL);
source->Unavailable(_("No source is available as execution has finished."));
unavailable = true;
}
}
// }}}
// {{{ void ConnectionPage::OnStderr(DBGp::StderrEvent &event)
void ConnectionPage::OnStderr(DBGp::StderrEvent &event) {
output->AppendStderr(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStdout(DBGp::StdoutEvent &event)
void ConnectionPage::OnStdout(DBGp::StdoutEvent &event) {
output->AppendStdout(event.GetData());
}
// }}}
// {{{ void ConnectionPage::OnStepInto(wxCommandEvent &event)
void ConnectionPage::OnStepInto(wxCommandEvent &event) {
conn->StepInto();
}
// }}}
// {{{ void ConnectionPage::OnStepOut(wxCommandEvent &event)
void ConnectionPage::OnStepOut(wxCommandEvent &event) {
conn->StepOut();
}
// }}}
// {{{ void ConnectionPage::OnStepOver(wxCommandEvent &event)
void ConnectionPage::OnStepOver(wxCommandEvent &event) {
conn->StepOver();
}
// }}}
// {{{ void ConnectionPage::RestoreStickyBreakpoints()
void ConnectionPage::RestoreStickyBreakpoints() {
std::vector<StickyBreakpoint> breakpoints(wxGetApp().GetStickyBreakpoints(script));
wxLogDebug(wxT("Restoring sticky breakpoints for script %s..."), script.c_str());
for (std::vector<StickyBreakpoint>::iterator i = breakpoints.begin(); i != breakpoints.end(); i++) {
DBGp::Breakpoint *bp = conn->CreateBreakpoint();
switch (i->GetType()) {
case DBGp::Breakpoint::CALL:
wxLogDebug(wxT("Sticky breakpoint of CALL type: %s."), i->GetArgument().c_str());
bp->SetCallType(i->GetArgument());
break;
case DBGp::Breakpoint::EXCEPTION:
wxLogDebug(wxT("Sticky breakpoint of EXCEPTION type: %s."), i->GetArgument().c_str());
bp->SetExceptionType(i->GetArgument());
break;
case DBGp::Breakpoint::RETURN:
wxLogDebug(wxT("Sticky breakpoint of RETURN type: %s."), i->GetArgument().c_str());
bp->SetReturnType(i->GetArgument());
break;
default:
wxLogError(wxT("Sticky breakpoint of unknown type."));
break;
}
bp->Set();
}
breakpoint->Update();
}
// }}}
// {{{ void ConnectionPage::SetSource(const wxString &file, int line)
void ConnectionPage::SetSource(const wxString &file, int line) {
if (file != lastFile) {
try {
source->tc->SetSource(conn->Source(file), line);
source->tc->SetLexerLanguage(language);
lastFile = file;
DBGp::Connection::BreakpointList list(breakpoint->GetFileBreakpoints(file));
for (DBGp::Connection::BreakpointList::const_iterator i = list.begin(); i != list.end(); i++) {
source->tc->SetBreakpointStyle((*i)->GetLineNo(), true);
}
unavailable = false;
}
catch (DBGp::Error e) {
source->Unavailable(_("No source is available for this stack frame."));
unavailable = true;
}
}
else if (line >= 0) {
source->tc->SetLine(line);
}
}
// }}}
// {{{ void ConnectionPage::UpdateStack()
void ConnectionPage::UpdateStack() {
DBGp::Stack stack(conn->StackGet());
this->stack->SetStack(&stack);
SetStackLevel(stack.GetLevel(0));
}
// }}}
// {{{ void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut)
void ConnectionPage::UpdateToolBar(bool run, bool brk, bool stepInto, bool stepOver, bool stepOut) {
toolbar->EnableTool(ID_CONNECTIONPAGE_RUN, run);
toolbar->EnableTool(ID_CONNECTIONPAGE_BREAK, brk);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPINTO, stepInto);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOVER, stepOver);
toolbar->EnableTool(ID_CONNECTIONPAGE_STEPOUT, stepOut);
toolbar->EnableTool(ID_CONNECTIONPAGE_RUN_TO_CURSOR, run);
}
// }}}
// vim:set fdm=marker ts=8 sw=8 noet cin:
<|endoftext|>
|
<commit_before>class Game
{
unsigned int player_limit;
std::list<char> bunch;
std::map<std::string, Player> players;
sf::Int16 peel_number {0};
bool playing {false};
bool ready_to_peel {false}; // game is ready for next peel
bool waiting {false}; // waiting for clients to acknowledge critical server packets before next peel
bool ready_to_finish {false}; // true if game just finished
bool finished {false};
void try_to_start();
public:
std::string winner;
Game(unsigned int _bunch_num, unsigned int _bunch_den, unsigned int _player_limit);
inline bool has_player(const std::string& id) const
{
return players.count(id) != 0;
}
inline std::map<std::string, Player>& get_players()
{
return players;
}
inline const std::string& get_player_name(const std::string& id) const
{
return players.at(id).get_name();
}
inline sf::Int16 get_remaining() const
{
return bunch.size();
}
inline bool is_full() const
{
return players.size() == player_limit;
}
inline bool in_progress() const
{
return playing;
}
inline bool can_peel() const
{
return ready_to_peel && !waiting;
}
inline bool is_finished() const
{
return finished;
}
inline bool is_ready_to_finish() const
{
return ready_to_finish;
}
inline void finish()
{
ready_to_finish = false;
}
inline bool can_restart() const
{
return finished && !waiting;
}
inline void wait()
{
waiting = true;
}
void check_waiting();
inline bool check_dump(const std::string& id, const sf::Int16& dump_n) const
{
return (dump_n == players.at(id).get_dump() - 1) || (dump_n == players.at(id).get_dump());
}
inline bool check_peel(const sf::Int16& number)
{
if (number == peel_number)
ready_to_peel = true;
return ready_to_peel;
}
inline const sf::Int16& get_peel() const
{
return peel_number;
}
std::string dump(const std::string& id, const sf::Int16& dump_n, char chr);
Player& add_player(const std::string& id, const sf::IpAddress& ip, unsigned short port, const std::string& name);
void remove_player(const std::string& id);
void set_ready(const std::string& id, bool ready);
bool peel();
void start();
void got_ack(const std::string& id, const sf::Int16& ack_num) const;
};
<commit_msg>Don't let game peel after someone wins<commit_after>class Game
{
unsigned int player_limit;
std::list<char> bunch;
std::map<std::string, Player> players;
sf::Int16 peel_number {0};
bool playing {false};
bool ready_to_peel {false}; // game is ready for next peel
bool waiting {false}; // waiting for clients to acknowledge critical server packets before next peel
bool ready_to_finish {false}; // true if game just finished
bool finished {false};
void try_to_start();
public:
std::string winner;
Game(unsigned int _bunch_num, unsigned int _bunch_den, unsigned int _player_limit);
inline bool has_player(const std::string& id) const
{
return players.count(id) != 0;
}
inline std::map<std::string, Player>& get_players()
{
return players;
}
inline const std::string& get_player_name(const std::string& id) const
{
return players.at(id).get_name();
}
inline sf::Int16 get_remaining() const
{
return bunch.size();
}
inline bool is_full() const
{
return players.size() == player_limit;
}
inline bool in_progress() const
{
return playing;
}
inline bool can_peel() const
{
return ready_to_peel && !waiting && !finished;
}
inline bool is_finished() const
{
return finished;
}
inline bool is_ready_to_finish() const
{
return ready_to_finish;
}
inline void finish()
{
ready_to_finish = false;
}
inline bool can_restart() const
{
return finished && !waiting;
}
inline void wait()
{
waiting = true;
}
void check_waiting();
inline bool check_dump(const std::string& id, const sf::Int16& dump_n) const
{
return (dump_n == players.at(id).get_dump() - 1) || (dump_n == players.at(id).get_dump());
}
inline bool check_peel(const sf::Int16& number)
{
if (number == peel_number)
ready_to_peel = true;
return ready_to_peel;
}
inline const sf::Int16& get_peel() const
{
return peel_number;
}
std::string dump(const std::string& id, const sf::Int16& dump_n, char chr);
Player& add_player(const std::string& id, const sf::IpAddress& ip, unsigned short port, const std::string& name);
void remove_player(const std::string& id);
void set_ready(const std::string& id, bool ready);
bool peel();
void start();
void got_ack(const std::string& id, const sf::Int16& ack_num) const;
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: flddropdown.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-06-30 15:50:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <algorithm>
#include <svtools/poolitem.hxx>
#ifndef _UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#include <flddropdown.hxx>
static String aEmptyString;
SwDropDownFieldType::SwDropDownFieldType()
: SwFieldType(RES_DROPDOWN)
{
}
SwDropDownFieldType::~SwDropDownFieldType()
{
}
SwFieldType * SwDropDownFieldType::Copy() const
{
return new SwDropDownFieldType;
}
SwDropDownField::SwDropDownField(SwFieldType * pTyp)
: SwField(pTyp, 0, LANGUAGE_SYSTEM)
{
}
SwDropDownField::SwDropDownField(const SwDropDownField & rSrc)
: SwField(rSrc.GetTyp(), rSrc.GetFormat(), rSrc.GetLanguage()),
aValues(rSrc.aValues), aSelectedItem(rSrc.aSelectedItem),
aName(rSrc.aName)
{
}
SwDropDownField::~SwDropDownField()
{
}
String SwDropDownField::Expand() const
{
String sSelect = GetSelectedItem();
if(!sSelect.Len())
{
vector<String>::const_iterator aIt = aValues.begin();
if ( aIt != aValues.end())
sSelect = *aIt;
}
//if still no list value is available a default text of 10 spaces is to be set
if(!sSelect.Len())
sSelect.AppendAscii ( RTL_CONSTASCII_STRINGPARAM (" "));
return sSelect;
}
SwField * SwDropDownField::Copy() const
{
return new SwDropDownField(*this);
}
const String & SwDropDownField::GetPar1() const
{
return GetSelectedItem();
}
String SwDropDownField::GetPar2() const
{
return GetName();
}
void SwDropDownField::SetPar1(const String & rStr)
{
SetSelectedItem(rStr);
}
void SwDropDownField::SetPar2(const String & rName)
{
SetName(rName);
}
BOOL SwDropDownField::AddItem(const String & rItem)
{
BOOL bResult = FALSE;
if (find(aValues.begin(), aValues.end(), rItem) == aValues.end())
{
String aTmp = GetSelectedItem();
aValues.push_back(rItem);
SetSelectedItem(aTmp);
bResult = TRUE;
}
return bResult;
}
BOOL SwDropDownField::RemoveItem(const String & rItem)
{
BOOL bResult = FALSE;
vector<String>::iterator aIt =
find(aValues.begin(), aValues.end(), rItem);
if ( aIt != aValues.end())
{
aValues.erase(aIt);
if (rItem.Equals(aSelectedItem))
aSelectedItem = aEmptyString;
bResult = TRUE;
}
return bResult;
}
void SwDropDownField::SetItems(const vector<String> & rItems)
{
aValues = rItems;
aSelectedItem = aEmptyString;
}
void SwDropDownField::SetItems(const Sequence<OUString> & rItems)
{
aValues.clear();
sal_Int32 aCount = rItems.getLength();
for (int i = 0; i < aCount; i++)
aValues.push_back(rItems[i]);
aSelectedItem = aEmptyString;
}
Sequence<OUString> SwDropDownField::GetItemSequence() const
{
Sequence<OUString> aSeq( aValues.size() );
OUString* pSeq = aSeq.getArray();
int i = 0;
vector<String>::const_iterator aIt;
for (aIt = aValues.begin(); aIt != aValues.end(); aIt++)
{
pSeq[i] = rtl::OUString(*aIt);
i++;
}
return aSeq;
}
vector<String> SwDropDownField::GetItems() const
{
return aValues;
}
const String & SwDropDownField::GetSelectedItem() const
{
return aSelectedItem;
}
const String & SwDropDownField::GetName() const
{
return aName;
}
BOOL SwDropDownField::SetSelectedItem(const String & rItem)
{
vector<String>::const_iterator aIt =
find(aValues.begin(), aValues.end(), rItem);
if (aIt != aValues.end())
aSelectedItem = *aIt;
else
aSelectedItem = String();
return (aIt != aValues.end());
}
void SwDropDownField::SetName(const String & rName)
{
aName = rName;
}
BOOL SwDropDownField::QueryValue(Any &rVal, BYTE nMId)
const
{
nMId &= ~CONVERT_TWIPS;
switch( nMId )
{
case FIELD_PROP_PAR1:
rVal <<= rtl::OUString(GetSelectedItem());
break;
case FIELD_PROP_PAR2:
rVal <<= rtl::OUString(GetName());
break;
case FIELD_PROP_STRINGS:
rVal <<= GetItemSequence();
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
BOOL SwDropDownField::PutValue(const Any &rVal,
BYTE nMId)
{
nMId &= ~CONVERT_TWIPS;
switch( nMId )
{
case FIELD_PROP_PAR1:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetSelectedItem(aTmpStr);
}
break;
case FIELD_PROP_PAR2:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetName(aTmpStr);
}
break;
case FIELD_PROP_STRINGS:
{
Sequence<OUString> aSeq;
rVal >>= aSeq;
SetItems(aSeq);
}
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
<commit_msg>INTEGRATION: CWS tune05 (1.2.488); FILE MERGED 2004/07/22 10:49:39 cmc 1.2.488.1: #i30554# unused SwDropDownField methods<commit_after>/*************************************************************************
*
* $RCSfile: flddropdown.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-08-12 12:25:13 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <algorithm>
#include <svtools/poolitem.hxx>
#ifndef _UNOFLDMID_H
#include <unofldmid.h>
#endif
#ifndef _UNOPRNMS_HXX
#include <unoprnms.hxx>
#endif
#include <flddropdown.hxx>
static String aEmptyString;
SwDropDownFieldType::SwDropDownFieldType()
: SwFieldType(RES_DROPDOWN)
{
}
SwDropDownFieldType::~SwDropDownFieldType()
{
}
SwFieldType * SwDropDownFieldType::Copy() const
{
return new SwDropDownFieldType;
}
SwDropDownField::SwDropDownField(SwFieldType * pTyp)
: SwField(pTyp, 0, LANGUAGE_SYSTEM)
{
}
SwDropDownField::SwDropDownField(const SwDropDownField & rSrc)
: SwField(rSrc.GetTyp(), rSrc.GetFormat(), rSrc.GetLanguage()),
aValues(rSrc.aValues), aSelectedItem(rSrc.aSelectedItem),
aName(rSrc.aName)
{
}
SwDropDownField::~SwDropDownField()
{
}
String SwDropDownField::Expand() const
{
String sSelect = GetSelectedItem();
if(!sSelect.Len())
{
vector<String>::const_iterator aIt = aValues.begin();
if ( aIt != aValues.end())
sSelect = *aIt;
}
//if still no list value is available a default text of 10 spaces is to be set
if(!sSelect.Len())
sSelect.AppendAscii ( RTL_CONSTASCII_STRINGPARAM (" "));
return sSelect;
}
SwField * SwDropDownField::Copy() const
{
return new SwDropDownField(*this);
}
const String & SwDropDownField::GetPar1() const
{
return GetSelectedItem();
}
String SwDropDownField::GetPar2() const
{
return GetName();
}
void SwDropDownField::SetPar1(const String & rStr)
{
SetSelectedItem(rStr);
}
void SwDropDownField::SetPar2(const String & rName)
{
SetName(rName);
}
void SwDropDownField::SetItems(const vector<String> & rItems)
{
aValues = rItems;
aSelectedItem = aEmptyString;
}
void SwDropDownField::SetItems(const Sequence<OUString> & rItems)
{
aValues.clear();
sal_Int32 aCount = rItems.getLength();
for (int i = 0; i < aCount; i++)
aValues.push_back(rItems[i]);
aSelectedItem = aEmptyString;
}
Sequence<OUString> SwDropDownField::GetItemSequence() const
{
Sequence<OUString> aSeq( aValues.size() );
OUString* pSeq = aSeq.getArray();
int i = 0;
vector<String>::const_iterator aIt;
for (aIt = aValues.begin(); aIt != aValues.end(); aIt++)
{
pSeq[i] = rtl::OUString(*aIt);
i++;
}
return aSeq;
}
const String & SwDropDownField::GetSelectedItem() const
{
return aSelectedItem;
}
const String & SwDropDownField::GetName() const
{
return aName;
}
BOOL SwDropDownField::SetSelectedItem(const String & rItem)
{
vector<String>::const_iterator aIt =
find(aValues.begin(), aValues.end(), rItem);
if (aIt != aValues.end())
aSelectedItem = *aIt;
else
aSelectedItem = String();
return (aIt != aValues.end());
}
void SwDropDownField::SetName(const String & rName)
{
aName = rName;
}
BOOL SwDropDownField::QueryValue(Any &rVal, BYTE nMId)
const
{
nMId &= ~CONVERT_TWIPS;
switch( nMId )
{
case FIELD_PROP_PAR1:
rVal <<= rtl::OUString(GetSelectedItem());
break;
case FIELD_PROP_PAR2:
rVal <<= rtl::OUString(GetName());
break;
case FIELD_PROP_STRINGS:
rVal <<= GetItemSequence();
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
BOOL SwDropDownField::PutValue(const Any &rVal,
BYTE nMId)
{
nMId &= ~CONVERT_TWIPS;
switch( nMId )
{
case FIELD_PROP_PAR1:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetSelectedItem(aTmpStr);
}
break;
case FIELD_PROP_PAR2:
{
String aTmpStr;
::GetString( rVal, aTmpStr );
SetName(aTmpStr);
}
break;
case FIELD_PROP_STRINGS:
{
Sequence<OUString> aSeq;
rVal >>= aSeq;
SetItems(aSeq);
}
break;
default:
DBG_ERROR("illegal property");
}
return sal_True;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdexcept>
template<typename T,typename Alloc>
class vector
{
public:
typedef T value_type;
typedef Alloc alloc_type;
typedef value_type & reference;
typedef value_type * pointer;
typedef const value_type & const_reference;
typedef const value_type * const_pointer;
typedef value_type * iterator;
typedef const value_type * const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
iterator begin()
{
}
const_iterator begin()const
{
}
iterator end()
{
}
const_iterator end()const
{
}
reverse_iterator rbegin()
{
}
const_reverse_iterator rbegin()const
{
}
reverse_iterator rend()
{
}
const_reverse_iterator rend()const
{
}
const_iterator cbegin()const
{
}
const_iterator cend()const
{
}
const_reverse_iterator crbegin()const
{
}
const_reverse_iterator crend()const
{
}
reference front()
{
}
const_reference front()const
{
}
reference back()
{
}
const_reference back()const
{
}
pointer data()
{
}
const_pointer data()const
{
}
reference operator[](size_type ) const
{
}
const_reference operator[](size_type ) const
{
}
reference at(size_type )
{
}
const_reference at(size_type )const
{
}
};
<commit_msg>modify vec<commit_after>#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdexcept>
template<typename T,typename Alloc>
class vector
{
public:
typedef T value_type;
typedef Alloc alloc_type;
typedef value_type & reference;
typedef value_type * pointer;
typedef const value_type & const_reference;
typedef const value_type * const_pointer;
typedef value_type * iterator;
typedef const value_type * const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::size_t size_type;
typedef ptrdiff_t difference_type;
vector()
{
}
explicit vector(const alloc_type &)
{
}
explicit vector(size_type,const alloc_type & = alloc_type() )
{
}
vector(size_type,const value_type v,const alloc_type &=alloc_type() )
{
}
template <typename InputIter>
vector(InputIter begin,InputIter end,const alloc_type & = alloc_type() )
{
}
template<typename U>
vector(std::initialize_list<U>,const alloc_type & = alloc_type() )
{
}
vector(const vector &)
{
}
vector(const vector &,const alloc_type &)
{
}
vector(vector &&)
{
}
vector(vector &&,const alloc_type &)
{
}
~vector()
{
}
iterator begin()
{
}
const_iterator begin()const
{
}
iterator end()
{
}
const_iterator end()const
{
}
reverse_iterator rbegin()
{
}
const_reverse_iterator rbegin()const
{
}
reverse_iterator rend()
{
}
const_reverse_iterator rend()const
{
}
const_iterator cbegin()const
{
}
const_iterator cend()const
{
}
const_reverse_iterator crbegin()const
{
}
const_reverse_iterator crend()const
{
}
reference front()
{
}
const_reference front()const
{
}
reference back()
{
}
const_reference back()const
{
}
pointer data()
{
}
const_pointer data()const
{
}
reference operator[](size_type ) const
{
}
const_reference operator[](size_type ) const
{
}
reference at(size_type )
{
}
const_reference at(size_type )const
{
}
void swap(vector &)noexcept
{
}
};
<|endoftext|>
|
<commit_before>//
// EventBus.hpp
// CatchLib
//
// Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
// Copyright (c) 2012 Catch22. All rights reserved.
//
#include "EEvent.hpp"
#include "IEventListener.hpp"
struct EventListenerArray
{
IEventListener** m_eventListeners;
int m_size;
int m_incrementBy;
int m_index;
EventListenerArray()
{
m_incrementBy = 5;
m_index = 0;
m_size = 0;
m_eventListeners = 0;
}
};
class EventBus
{
public:
static EventBus* getSharedInstance();
void publishEvent(EEvent event, void* source);
void addEventListener(IEventListener* listener);
void removeEventListener(IEventListener* listener);
private:
EventListenerArray* m_listeners;
~EventBus();
EventBus();
};
<commit_msg>Added documentation for our structure<commit_after>//
// EventBus.hpp
// CatchLib
//
// Created by Jesper Persson and Sebastian Odbjer on 2/10-12.
// Copyright (c) 2012 Catch22. All rights reserved.
//
#include "EEvent.hpp"
#include "IEventListener.hpp"
/*
* Structure for organizing our array of eventListeners.
* m_eventListeners -- our array of eventListeners.
* m_size -- the size of our array.
* m_incrementBy -- how much the size of the array should be incremented
* by whenever m_index == m_size.
* m_index -- the index of the last element of the array, it is set to -1
* as default to prevent events to be performed when the array
* is empty.
*/
struct EventListenerArray
{
IEventListener** m_eventListeners;
int m_size;
int m_incrementBy;
int m_index;
EventListenerArray()
{
m_incrementBy = 5;
m_index = -1;
m_size = 0;
m_eventListeners = 0;
}
};
class EventBus
{
public:
static EventBus* getSharedInstance();
void publishEvent(EEvent event, void* source);
void addEventListener(IEventListener* listener);
void removeEventListener(IEventListener* listener);
private:
EventListenerArray* m_listeners;
~EventBus();
EventBus();
};
<|endoftext|>
|
<commit_before>/*************************************************************************
> File Name: Interface.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Interface for Hearthstone Game Agent
> Created Time: 2017/10/24
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Interface/Interface.h>
namespace Hearthstonepp
{
GameInterface::GameInterface(GameAgent& agent)
: m_agent(agent)
, m_bufferCapacity(agent.GetBufferCapacity())
{
m_buffer = new BYTE[m_bufferCapacity];
}
GameResult GameInterface::StartGame()
{
GameResult result;
std::thread *at = m_agent.StartAgent(result);
while (true)
{
int result = HandleMessage();
if (result) break;
}
at->join(); // join agent thread
delete at;
return result;
}
int GameInterface::HandleMessage()
{
m_agent.ReadBuffer(m_buffer, m_bufferCapacity);
if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER))
{
return 1;
}
else if (m_handler.find(m_buffer[0]) != m_handler.end())
{
m_handler[m_buffer[0]](*this);
}
return 0;
}
void GameInterface::LogWriter(std::string& name, std::string message)
{
std::cout << "[*] " << name << " : " << message << std::endl;
}
void GameInterface::BeginFirst()
{
BeginFirstStructure *data = (BeginFirstStructure*)m_buffer;
m_users[0] = data->m_userFirst;
m_users[1] = data->m_userLast;
LogWriter(m_users[0], "Begin First");
LogWriter(m_users[1], "Begin Last");
}
void GameInterface::BeginShuffle()
{
BeginShuffleStructure *data = (BeginShuffleStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Shuffle");
}
void GameInterface::BeginDraw()
{
DrawStructure *data = (DrawStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Draw");
for (int i = 0; i < 3; ++i)
{
std::cout << "[" << data->m_cards[i]->GetCardName() << "] ";
}
std::cout << std::endl;
}
void GameInterface::BeginMulligan()
{
BeginMulliganStructure *data = (BeginMulliganStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Mulligan");
int numMulligan;
while (true)
{
std::cout << "[*] How many cards to mulligan ? (0 ~ 3) ";
std::cin >> numMulligan;
if (numMulligan >= 0 && numMulligan <= 3)
{
break;
}
}
BYTE mulligan[3] = { 0, };
for (int i = 0; i < numMulligan; ++i)
{
while (true)
{
BYTE index = 0;
std::cout << "[*] Input card index " << i+1 << " : ";
std::cin >> index;
if (index >= 0 && index <= 3)
{
mulligan[i] = index;
break;
}
}
}
m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent
m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data
LogWriter(m_users[data->m_userID], "Mulligan Result");
DrawStructure *draw = (DrawStructure*)m_buffer;
for (int i = 0; i < 3; ++i)
{
std::cout << "[" << draw->m_cards[i]->GetCardName() << "] ";
}
std::cout << std::endl;
}
}<commit_msg>Update Interface - Fix Mulligan System reference invalid addr<commit_after>/*************************************************************************
> File Name: Interface.cpp
> Project Name: Hearthstone++
> Author: Young-Joong Kim
> Purpose: Interface for Hearthstone Game Agent
> Created Time: 2017/10/24
> Copyright (c) 2017, Young-Joong Kim
*************************************************************************/
#include <Interface/Interface.h>
namespace Hearthstonepp
{
GameInterface::GameInterface(GameAgent& agent)
: m_agent(agent)
, m_bufferCapacity(agent.GetBufferCapacity())
{
m_buffer = new BYTE[m_bufferCapacity];
}
GameResult GameInterface::StartGame()
{
GameResult result;
std::thread *at = m_agent.StartAgent(result);
while (true)
{
int result = HandleMessage();
if (result) break;
}
at->join(); // join agent thread
delete at;
return result;
}
int GameInterface::HandleMessage()
{
m_agent.ReadBuffer(m_buffer, m_bufferCapacity);
if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER))
{
return 1;
}
else if (m_handler.find(m_buffer[0]) != m_handler.end())
{
m_handler[m_buffer[0]](*this);
}
return 0;
}
void GameInterface::LogWriter(std::string& name, std::string message)
{
std::cout << "[*] " << name << " : " << message << std::endl;
}
void GameInterface::BeginFirst()
{
BeginFirstStructure *data = (BeginFirstStructure*)m_buffer;
m_users[0] = data->m_userFirst;
m_users[1] = data->m_userLast;
LogWriter(m_users[0], "Begin First");
LogWriter(m_users[1], "Begin Last");
}
void GameInterface::BeginShuffle()
{
BeginShuffleStructure *data = (BeginShuffleStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Shuffle");
}
void GameInterface::BeginDraw()
{
DrawStructure *data = (DrawStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Draw");
for (int i = 0; i < 3; ++i)
{
std::cout << "[" << data->m_cards[i]->GetCardName() << "] ";
}
std::cout << std::endl;
}
void GameInterface::BeginMulligan()
{
BeginMulliganStructure *data = (BeginMulliganStructure*)m_buffer;
LogWriter(m_users[data->m_userID], "Begin Mulligan");
int numMulligan;
while (true)
{
std::cout << "[*] How many cards to mulligan ? (0 ~ 3) ";
std::cin >> numMulligan;
if (numMulligan >= 0 && numMulligan <= 3)
{
break;
}
}
BYTE mulligan[3] = { 0, };
for (int i = 0; i < numMulligan; ++i)
{
while (true)
{
int index = 0;
std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : ";
std::cin >> index;
if (index >= 0 && index <= 2)
{
mulligan[i] = index;
break;
}
}
}
m_agent.WriteBuffer(mulligan, numMulligan); // send index to agent
m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); // get new card data
LogWriter(m_users[data->m_userID], "Mulligan Result");
DrawStructure *draw = (DrawStructure*)m_buffer;
for (int i = 0; i < 3; ++i)
{
std::cout << "[" << draw->m_cards[i]->GetCardName() << "] ";
}
std::cout << std::endl;
}
}<|endoftext|>
|
<commit_before>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Actions/Choose.hpp>
#include <hspp/Actions/Generic.hpp>
#include <iostream>
namespace Hearthstonepp::Generic
{
void ChoiceMulligan(Player& player, std::vector<std::size_t> choices)
{
// Block it if player tries to mulligan in a non-mulligan choice
if (player.choice.value().choiceType != +ChoiceType::MULLIGAN)
{
return;
}
// Block it if player tries to mulligan a card that doesn't exist
Choice& choice = player.choice.value();
for (auto& choosedID : choices)
{
if (std::find(choice.choices.begin(), choice.choices.end(),
choosedID) == choice.choices.end())
{
return;
}
}
// Process mulligan by choice action
switch (player.choice.value().choiceAction)
{
case ChoiceAction::HAND:
{
// Process mulligan state
player.mulliganState = Mulligan::DEALING;
auto& hand = player.GetHand();
auto& deck = player.GetDeck();
// Collect cards to redraw
std::vector<Entity*> mulliganList;
for (const auto& entity : hand.GetAllCards())
{
bool isExist = std::find(choices.begin(), choices.end(),
entity->id) == choices.end();
if (isExist && entity->card.id != "GAME_005")
{
mulliganList.push_back(entity);
}
}
// Process redraw
for (const auto& entity : mulliganList)
{
Entity& newCard = deck.RemoveCard(*deck.GetTopCard());
Generic::AddCardToHand(player, &newCard);
hand.SwapCard(*entity, newCard);
Generic::RemoveCardFromHand(player, entity);
deck.AddCard(*entity);
deck.Shuffle();
}
// It's done! - Reset choice
player.choice = std::nullopt;
break;
}
default:
throw std::invalid_argument(
"ChoiceMulligan() - Invalid choice action!");
}
}
void CreateChoice(Player& player, ChoiceType type, ChoiceAction action,
std::vector<std::size_t> choices)
{
// Block it if choice is exist
if (player.choice != std::nullopt)
{
return;
}
// Create a choice for player
Choice choice;
choice.choiceType = type;
choice.choiceAction = action;
choice.choices = choices;
player.choice = choice;
}
} // namespace Hearthstonepp::Generic<commit_msg>fix: Correct type matching (non-reference vs reference)<commit_after>// This code is based on Sabberstone project.
// Copyright (c) 2017-2018 SabberStone Team, darkfriend77 & rnilva
// Hearthstone++ is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
#include <hspp/Actions/Choose.hpp>
#include <hspp/Actions/Generic.hpp>
namespace Hearthstonepp::Generic
{
void ChoiceMulligan(Player& player, std::vector<std::size_t> choices)
{
// Block it if player tries to mulligan in a non-mulligan choice
if (player.choice.value().choiceType != +ChoiceType::MULLIGAN)
{
return;
}
// Block it if player tries to mulligan a card that doesn't exist
Choice& choice = player.choice.value();
for (const auto choosedID : choices)
{
if (std::find(choice.choices.begin(), choice.choices.end(),
choosedID) == choice.choices.end())
{
return;
}
}
// Process mulligan by choice action
switch (player.choice.value().choiceAction)
{
case ChoiceAction::HAND:
{
// Process mulligan state
player.mulliganState = Mulligan::DEALING;
auto& hand = player.GetHand();
auto& deck = player.GetDeck();
// Collect cards to redraw
std::vector<Entity*> mulliganList;
for (const auto entity : hand.GetAllCards())
{
bool isExist = std::find(choices.begin(), choices.end(),
entity->id) == choices.end();
if (isExist && entity->card.id != "GAME_005")
{
mulliganList.push_back(entity);
}
}
// Process redraw
for (const auto& entity : mulliganList)
{
Entity& newCard = deck.RemoveCard(*deck.GetTopCard());
Generic::AddCardToHand(player, &newCard);
hand.SwapCard(*entity, newCard);
Generic::RemoveCardFromHand(player, entity);
deck.AddCard(*entity);
deck.Shuffle();
}
// It's done! - Reset choice
player.choice = std::nullopt;
break;
}
default:
throw std::invalid_argument(
"ChoiceMulligan() - Invalid choice action!");
}
}
void CreateChoice(Player& player, ChoiceType type, ChoiceAction action,
std::vector<std::size_t> choices)
{
// Block it if choice is exist
if (player.choice != std::nullopt)
{
return;
}
// Create a choice for player
Choice choice;
choice.choiceType = type;
choice.choiceAction = action;
choice.choices = choices;
player.choice = choice;
}
} // namespace Hearthstonepp::Generic<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Nagoya University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Autoware nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/tf.h>
#include <iostream>
#include "waypoint_follower/libwaypoint_follower.h"
static geometry_msgs::Twist _current_velocity;
static const std::string SIMULATION_FRAME = "sim_base_link";
static const std::string MAP_FRAME = "map";
static geometry_msgs::Pose _initial_pose;
static std::string _use_pose;
static bool _initial_set = false;
static bool _pose_set = false;
static bool _waypoint_set = false;
static int _closest_waypoint = -1;
//Path _path_og;
WayPoints _current_waypoints;
static void NDTCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
if (_use_pose != "NDT")
return;
if(_initial_set)
return;
_initial_pose = input->pose;
_initial_set = true;
_pose_set = false;
}
static void GNSSCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
if (_use_pose != "GNSS")
return;
if(_initial_set)
return;
_initial_pose = input->pose;
_initial_set = true;
_pose_set = false;
}
static void CmdCallBack(const geometry_msgs::TwistStampedConstPtr &msg)
{
_current_velocity = msg->twist;
}
static void initialposeCallback(const geometry_msgs::PoseWithCovarianceStampedConstPtr &input)
{
if (_use_pose != "Initial Pos")
return;
static tf::TransformListener listener;
tf::StampedTransform transform;
bool tf_flag = false;
while (!tf_flag)
{
try
{
listener.lookupTransform("map", "world", ros::Time(0), transform);
tf_flag = true;
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
}
}
_initial_pose.position.x = input->pose.pose.position.x + transform.getOrigin().x();
_initial_pose.position.y = input->pose.pose.position.y + transform.getOrigin().y();
_initial_pose.position.z = input->pose.pose.position.z + transform.getOrigin().z();
_initial_pose.orientation = input->pose.pose.orientation;
_initial_set = true;
_pose_set = false;
}
static void waypointCallback(const waypoint_follower::laneConstPtr &msg)
{
// _path_og.setPath(msg);
_current_waypoints.setPath(*msg);
_waypoint_set = true;
ROS_INFO_STREAM("waypoint subscribed");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "odom_gen");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
//publish topic
ros::Publisher odometry_publisher = nh.advertise<nav_msgs::Odometry>("odom_pose", 10);
//subscribe topic
ros::Subscriber cmd_subscriber = nh.subscribe("twist_cmd", 10, CmdCallBack);
ros::Subscriber ndt_subscriber = nh.subscribe("control_pose", 10, NDTCallback);
ros::Subscriber initialpose_subscriber = nh.subscribe("initialpose", 10, initialposeCallback);
ros::Subscriber gnss_subscriber = nh.subscribe("gnss_pose", 1000, GNSSCallback);
ros::Subscriber waypoint_subcscriber = nh.subscribe("base_waypoints", 10, waypointCallback);
//transform
tf::TransformBroadcaster odom_broadcaster;
private_nh.getParam("use_pose", _use_pose);
ros::Time current_time, last_time;
current_time = ros::Time::now();
last_time = ros::Time::now();
geometry_msgs::Pose pose;
double th = 0;
ros::Rate loop_rate(50); // 50Hz
while (ros::ok())
{
ros::spinOnce(); //check subscribe topic
if (!_waypoint_set)
continue;
if (!_initial_set)
continue;
if (!_pose_set)
{
pose.position = _initial_pose.position;
pose.orientation = _initial_pose.orientation;
tf::Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
th = yaw;
std::cout << "pose set : (" << pose.position.x << " " << pose.position.y << " " << pose.position.z << " " << th
<< ")" << std::endl << std::endl;
_pose_set = true;
}
/* tf::Transform inverse;
tf::poseMsgToTF(pose, inverse);
_path_og.setTransform(inverse.inverse());
int closest_waypoint = _path_og.getClosestWaypoint();
if (closest_waypoint == -1)
{
ROS_INFO_STREAM("waypoint is not closed");
_initial_set = false;
continue;
}
pose.position.z = _path_og.getWaypointPosition(closest_waypoint).z;
*/
int closest_waypoint = getClosestWaypoint(_current_waypoints.getCurrentWaypoints(),pose);
pose.position.z = _current_waypoints.getWaypointPosition(closest_waypoint).z;
double vx = _current_velocity.linear.x;
double vth = _current_velocity.angular.z;
current_time = ros::Time::now();
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time - last_time).toSec();
double delta_x = (vx * cos(th)) * dt;
double delta_y = (vx * sin(th)) * dt;
double delta_th = vth * dt;
pose.position.x += delta_x;
pose.position.y += delta_y;
th += delta_th;
pose.orientation = tf::createQuaternionMsgFromYaw(th);
// std::cout << "delta (x y th) : (" << delta_x << " " << delta_y << " " << delta_th << ")" << std::endl;
//std::cout << "current_velocity(linear.x angular.z) : (" << _current_velocity.linear.x << " " << _current_velocity.angular.z << ")"<< std::endl;
// std::cout << "current_pose : (" << pose.position.x << " " << pose.position.y<< " " << pose.position.z << " " << th << ")" << std::endl << std::endl;
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.header.frame_id = MAP_FRAME;
odom_trans.child_frame_id = SIMULATION_FRAME;
odom_trans.transform.translation.x = pose.position.x;
odom_trans.transform.translation.y = pose.position.y;
odom_trans.transform.translation.z = pose.position.z;
odom_trans.transform.rotation = pose.orientation;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = MAP_FRAME;
//set the position
odom.pose.pose = pose;
//set the velocity
odom.child_frame_id = SIMULATION_FRAME;
odom.twist.twist.linear.x = vx;
odom.twist.twist.angular.z = vth;
//publish the message
odometry_publisher.publish(odom);
last_time = current_time;
loop_rate.sleep();
}
return 0;
}
<commit_msg>Add sleep<commit_after>/*
* Copyright (c) 2015, Nagoya University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Autoware nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/tf.h>
#include <iostream>
#include "waypoint_follower/libwaypoint_follower.h"
static geometry_msgs::Twist _current_velocity;
static const std::string SIMULATION_FRAME = "sim_base_link";
static const std::string MAP_FRAME = "map";
static geometry_msgs::Pose _initial_pose;
static std::string _use_pose;
static bool _initial_set = false;
static bool _pose_set = false;
static bool _waypoint_set = false;
static int _closest_waypoint = -1;
//Path _path_og;
WayPoints _current_waypoints;
static void NDTCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
if (_use_pose != "NDT")
return;
if(_initial_set)
return;
_initial_pose = input->pose;
_initial_set = true;
_pose_set = false;
}
static void GNSSCallback(const geometry_msgs::PoseStamped::ConstPtr& input)
{
if (_use_pose != "GNSS")
return;
if(_initial_set)
return;
_initial_pose = input->pose;
_initial_set = true;
_pose_set = false;
}
static void CmdCallBack(const geometry_msgs::TwistStampedConstPtr &msg)
{
_current_velocity = msg->twist;
}
static void initialposeCallback(const geometry_msgs::PoseWithCovarianceStampedConstPtr &input)
{
if (_use_pose != "Initial Pos")
return;
static tf::TransformListener listener;
tf::StampedTransform transform;
bool tf_flag = false;
while (!tf_flag)
{
try
{
listener.lookupTransform("map", "world", ros::Time(0), transform);
tf_flag = true;
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
}
}
_initial_pose.position.x = input->pose.pose.position.x + transform.getOrigin().x();
_initial_pose.position.y = input->pose.pose.position.y + transform.getOrigin().y();
_initial_pose.position.z = input->pose.pose.position.z + transform.getOrigin().z();
_initial_pose.orientation = input->pose.pose.orientation;
_initial_set = true;
_pose_set = false;
}
static void waypointCallback(const waypoint_follower::laneConstPtr &msg)
{
// _path_og.setPath(msg);
_current_waypoints.setPath(*msg);
_waypoint_set = true;
ROS_INFO_STREAM("waypoint subscribed");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "odom_gen");
ros::NodeHandle nh;
ros::NodeHandle private_nh("~");
//publish topic
ros::Publisher odometry_publisher = nh.advertise<nav_msgs::Odometry>("odom_pose", 10);
//subscribe topic
ros::Subscriber cmd_subscriber = nh.subscribe("twist_cmd", 10, CmdCallBack);
ros::Subscriber ndt_subscriber = nh.subscribe("control_pose", 10, NDTCallback);
ros::Subscriber initialpose_subscriber = nh.subscribe("initialpose", 10, initialposeCallback);
ros::Subscriber gnss_subscriber = nh.subscribe("gnss_pose", 1000, GNSSCallback);
ros::Subscriber waypoint_subcscriber = nh.subscribe("base_waypoints", 10, waypointCallback);
//transform
tf::TransformBroadcaster odom_broadcaster;
private_nh.getParam("use_pose", _use_pose);
ros::Time current_time, last_time;
current_time = ros::Time::now();
last_time = ros::Time::now();
geometry_msgs::Pose pose;
double th = 0;
ros::Rate loop_rate(50); // 50Hz
while (ros::ok())
{
ros::spinOnce(); //check subscribe topic
if (!_waypoint_set) {
loop_rate.sleep();
continue;
}
if (!_initial_set) {
loop_rate.sleep();
continue;
}
if (!_pose_set)
{
pose.position = _initial_pose.position;
pose.orientation = _initial_pose.orientation;
tf::Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
tf::Matrix3x3 m(q);
double roll, pitch, yaw;
m.getRPY(roll, pitch, yaw);
th = yaw;
std::cout << "pose set : (" << pose.position.x << " " << pose.position.y << " " << pose.position.z << " " << th
<< ")" << std::endl << std::endl;
_pose_set = true;
}
/* tf::Transform inverse;
tf::poseMsgToTF(pose, inverse);
_path_og.setTransform(inverse.inverse());
int closest_waypoint = _path_og.getClosestWaypoint();
if (closest_waypoint == -1)
{
ROS_INFO_STREAM("waypoint is not closed");
_initial_set = false;
continue;
}
pose.position.z = _path_og.getWaypointPosition(closest_waypoint).z;
*/
int closest_waypoint = getClosestWaypoint(_current_waypoints.getCurrentWaypoints(),pose);
pose.position.z = _current_waypoints.getWaypointPosition(closest_waypoint).z;
double vx = _current_velocity.linear.x;
double vth = _current_velocity.angular.z;
current_time = ros::Time::now();
//compute odometry in a typical way given the velocities of the robot
double dt = (current_time - last_time).toSec();
double delta_x = (vx * cos(th)) * dt;
double delta_y = (vx * sin(th)) * dt;
double delta_th = vth * dt;
pose.position.x += delta_x;
pose.position.y += delta_y;
th += delta_th;
pose.orientation = tf::createQuaternionMsgFromYaw(th);
// std::cout << "delta (x y th) : (" << delta_x << " " << delta_y << " " << delta_th << ")" << std::endl;
//std::cout << "current_velocity(linear.x angular.z) : (" << _current_velocity.linear.x << " " << _current_velocity.angular.z << ")"<< std::endl;
// std::cout << "current_pose : (" << pose.position.x << " " << pose.position.y<< " " << pose.position.z << " " << th << ")" << std::endl << std::endl;
//first, we'll publish the transform over tf
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.header.frame_id = MAP_FRAME;
odom_trans.child_frame_id = SIMULATION_FRAME;
odom_trans.transform.translation.x = pose.position.x;
odom_trans.transform.translation.y = pose.position.y;
odom_trans.transform.translation.z = pose.position.z;
odom_trans.transform.rotation = pose.orientation;
//send the transform
odom_broadcaster.sendTransform(odom_trans);
//next, we'll publish the odometry message over ROS
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
odom.header.frame_id = MAP_FRAME;
//set the position
odom.pose.pose = pose;
//set the velocity
odom.child_frame_id = SIMULATION_FRAME;
odom.twist.twist.linear.x = vx;
odom.twist.twist.angular.z = vth;
//publish the message
odometry_publisher.publish(odom);
last_time = current_time;
loop_rate.sleep();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "feStats.h"
const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
bool feStats::operator==(const feStats &rhs) const {
return (hp == rhs.hp
&& str == rhs.str
&& mag == rhs.mag
&& skl == rhs.skl
&& spd == rhs.spd
&& lck == rhs.lck
&& def == rhs.def
&& res == rhs.res
&& con == rhs.con
&& mov == rhs.mov);
}
feStats feStats::operator%(const feStats &rhs) const {
feStats ret = {
hp % rhs.hp,
str % rhs.str,
mag % rhs.mag,
skl % rhs.skl,
spd % rhs.spd,
lck % rhs.lck,
def % rhs.def,
res % rhs.res,
con % rhs.con,
mov % rhs.mov
};
return ret;
}
feStats feStats::operator+(const feStats &rhs) const {
}
feStats feStats::operator-(const feStats &rhs) const {
}
feStats feStats::operator*(const feStats &rhs) const {
}
feStats feStats::operator/(const feStats &rhs) const {
}
feStats &feStats::operator=(const feStats &rhs) {
}
feStats &feStats::operator+=(const feStats &rhs) {
}
feStats &feStats::operator-=(const feStats &rhs) {
}
feStats &feStats::operator*=(const feStats &rhs) {
}
feStats &feStats::operator/=(const feStats &rhs) {
}
<commit_msg>operator overloads for feStats<commit_after>#include "feStats.h"
const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
bool feStats::operator==(const feStats &rhs) const {
return (hp == rhs.hp
&& str == rhs.str
&& mag == rhs.mag
&& skl == rhs.skl
&& spd == rhs.spd
&& lck == rhs.lck
&& def == rhs.def
&& res == rhs.res
&& con == rhs.con
&& mov == rhs.mov);
}
feStats feStats::operator%(const feStats &rhs) const {
feStats ret = {
hp % rhs.hp,
str % rhs.str,
mag % rhs.mag,
skl % rhs.skl,
spd % rhs.spd,
lck % rhs.lck,
def % rhs.def,
res % rhs.res,
con % rhs.con,
mov % rhs.mov
};
return ret;
}
feStats feStats::operator+(const feStats &rhs) const {
feStats sum = {
hp += rhs.hp,
str += rhs.str,
mag += rhs.mag,
skl += rhs.skl,
lck += rhs.lck,
def += rhs.def,
res += rhs.res,
con += rhs.con,
mov += rhs.mov};
return sum;
}
feStats feStats::operator-(const feStats &rhs) const {
feStats diff = {
hp -= rhs.hp,
str -= rhs.str,
mag -= rhs.mag,
skl -= rhs.skl,
lck -= rhs.lck,
def -= rhs.def,
res -= rhs.res,
con -= rhs.con,
mov -= rhs.mov};
return diff;
}
feStats feStats::operator*(const feStats &rhs) const {
feStats prod = {
hp *= rhs.hp,
str *= rhs.str,
mag *= rhs.mag,
skl *= rhs.skl,
lck *= rhs.lck,
def *= rhs.def,
res *= rhs.res,
con *= rhs.con,
mov *= rhs.mov};
return prod;
}
feStats feStats::operator/(const feStats &rhs) const {
feStats sum = {
hp /= rhs.hp,
str /= rhs.str,
mag /= rhs.mag,
skl /= rhs.skl,
lck /= rhs.lck,
def /= rhs.def,
res /= rhs.res,
con /= rhs.con,
mov /= rhs.mov};
return sum;
}
feStats &feStats::operator=(const feStats &rhs) {
this->hp = rhs.hp;
this->str = rhs.str;
this->mag = rhs.mag;
this->skl = rhs.skl;
this->lck = rhs.lck;
this->def = rhs.def;
this->res = rhs.res;
this->con = rhs.con;
this->mov = rhs.mov;
return *this;
}
feStats &feStats::operator+=(const feStats &rhs) {
this->hp += rhs.hp;
this->str += rhs.str;
this->mag += rhs.mag;
this->skl += rhs.skl;
this->lck += rhs.lck;
this->def += rhs.def;
this->res += rhs.res;
this->con += rhs.con;
this->mov += rhs.mov;
return *this;
}
feStats &feStats::operator-=(const feStats &rhs) {
this->hp -= rhs.hp;
this->str -= rhs.str;
this->mag -= rhs.mag;
this->skl -= rhs.skl;
this->lck -= rhs.lck;
this->def -= rhs.def;
this->res -= rhs.res;
this->con -= rhs.con;
this->mov -= rhs.mov;
return *this;
}
feStats &feStats::operator*=(const feStats &rhs) {
this->hp *= rhs.hp;
this->str *= rhs.str;
this->mag *= rhs.mag;
this->skl *= rhs.skl;
this->lck *= rhs.lck;
this->def *= rhs.def;
this->res *= rhs.res;
this->con *= rhs.con;
this->mov *= rhs.mov;
return *this;
}
feStats &feStats::operator/=(const feStats &rhs) {
this->hp /= rhs.hp;
this->str /= rhs.str;
this->mag /= rhs.mag;
this->skl /= rhs.skl;
this->lck /= rhs.lck;
this->def /= rhs.def;
this->res /= rhs.res;
this->con /= rhs.con;
this->mov /= rhs.mov;
return *this;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: chgviset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:27:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_CHGVISET_HXX
#define SC_CHGVISET_HXX
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
enum ScChgsDateMode{ SCDM_DATE_BEFORE=0,SCDM_DATE_SINCE=1,SCDM_DATE_EQUAL=2,
SCDM_DATE_NOTEQUAL=3,SCDM_DATE_BETWEEN=4, SCDM_DATE_SAVE=5,
SCDM_NO_DATEMODE=6};
namespace utl {
class TextSearch;
}
class ScDocument;
class ScChangeViewSettings
{
private:
utl::TextSearch* pCommentSearcher;
DateTime aFirstDateTime;
DateTime aLastDateTime;
String aAuthorToShow;
String aComment;
ScRangeList aRangeList;
ScChgsDateMode eDateMode;
BOOL bShowIt;
BOOL bIsDate;
BOOL bIsAuthor;
BOOL bIsComment;
BOOL bIsRange;
BOOL bEveryoneButMe;
BOOL bShowAccepted;
BOOL bShowRejected;
public:
ScChangeViewSettings()
{
pCommentSearcher=NULL;
bIsDate=FALSE;
bIsAuthor=FALSE;
bIsRange=FALSE;
bIsComment=FALSE;
bShowIt=FALSE;
eDateMode=SCDM_DATE_BEFORE;
bEveryoneButMe=FALSE;
bShowAccepted=FALSE;
bShowRejected=FALSE;
}
ScChangeViewSettings( const ScChangeViewSettings& r );
~ScChangeViewSettings();
BOOL ShowChanges() const {return bShowIt;}
void SetShowChanges(BOOL nFlag=TRUE){bShowIt=nFlag;}
BOOL HasDate() const {return bIsDate;}
void SetHasDate(BOOL nFlag=TRUE) {bIsDate=nFlag;}
void SetTheDateMode(ScChgsDateMode eDatMod){ eDateMode=eDatMod; }
ScChgsDateMode GetTheDateMode() const { return eDateMode; }
void SetTheFirstDateTime(const DateTime& aDateTime) {aFirstDateTime=aDateTime;}
const DateTime& GetTheFirstDateTime()const {return aFirstDateTime;}
void SetTheLastDateTime(const DateTime& aDateTime) {aLastDateTime=aDateTime;}
const DateTime& GetTheLastDateTime()const {return aLastDateTime;}
BOOL HasAuthor() const {return bIsAuthor;}
void SetHasAuthor(BOOL nFlag=TRUE) {bIsAuthor=nFlag;}
String GetTheAuthorToShow()const {return aAuthorToShow;}
void SetTheAuthorToShow(const String& aString){aAuthorToShow=aString;}
BOOL HasComment() const {return bIsComment;}
void SetHasComment(BOOL nFlag=TRUE) {bIsComment=nFlag;}
String GetTheComment()const {return aComment;}
void SetTheComment(const String& aString);
BOOL IsValidComment(const String* pCommentStr) const;
BOOL IsEveryoneButMe() const {return bEveryoneButMe;}
void SetEveryoneButMe(BOOL nFlag=TRUE) {bEveryoneButMe=nFlag;}
BOOL HasRange() const {return bIsRange;}
void SetHasRange(BOOL nFlag=TRUE) {bIsRange=nFlag;}
const ScRangeList& GetTheRangeList()const {return aRangeList;}
void SetTheRangeList(const ScRangeList& aRl){aRangeList=aRl;}
BOOL IsShowAccepted() const { return bShowAccepted; }
void SetShowAccepted( BOOL bVal ) { bShowAccepted = bVal; }
BOOL IsShowRejected() const { return bShowRejected; }
void SetShowRejected( BOOL bVal ) { bShowRejected = bVal; }
void Load( SvStream& rStream, USHORT nVer );
void Store( SvStream& rStream ) const;
ScChangeViewSettings& operator= ( const ScChangeViewSettings& r );
/// Adjust dates according to selected DateMode
void AdjustDateMode( const ScDocument& rDoc );
};
#endif
<commit_msg>INTEGRATION: CWS calcshare_DEV300 (1.4.524); FILE MERGED 2007/12/04 12:59:09 tbe 1.4.524.1: #i8811# Allow multiple users to edit the same spreadsheet through workbook sharing<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: chgviset.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2008-03-07 12:15:05 $
*
* 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 SC_CHGVISET_HXX
#define SC_CHGVISET_HXX
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
enum ScChgsDateMode{ SCDM_DATE_BEFORE=0,SCDM_DATE_SINCE=1,SCDM_DATE_EQUAL=2,
SCDM_DATE_NOTEQUAL=3,SCDM_DATE_BETWEEN=4, SCDM_DATE_SAVE=5,
SCDM_NO_DATEMODE=6};
namespace utl {
class TextSearch;
}
class ScDocument;
class ScChangeViewSettings
{
private:
utl::TextSearch* pCommentSearcher;
DateTime aFirstDateTime;
DateTime aLastDateTime;
String aAuthorToShow;
String aComment;
ScRangeList aRangeList;
ScChgsDateMode eDateMode;
BOOL bShowIt;
BOOL bIsDate;
BOOL bIsAuthor;
BOOL bIsComment;
BOOL bIsRange;
BOOL bEveryoneButMe;
BOOL bShowAccepted;
BOOL bShowRejected;
bool mbIsActionRange;
ULONG mnFirstAction;
ULONG mnLastAction;
public:
ScChangeViewSettings()
{
pCommentSearcher=NULL;
bIsDate=FALSE;
bIsAuthor=FALSE;
bIsRange=FALSE;
bIsComment=FALSE;
bShowIt=FALSE;
eDateMode=SCDM_DATE_BEFORE;
bEveryoneButMe=FALSE;
bShowAccepted=FALSE;
bShowRejected=FALSE;
mbIsActionRange = false;
}
ScChangeViewSettings( const ScChangeViewSettings& r );
~ScChangeViewSettings();
BOOL ShowChanges() const {return bShowIt;}
void SetShowChanges(BOOL nFlag=TRUE){bShowIt=nFlag;}
BOOL HasDate() const {return bIsDate;}
void SetHasDate(BOOL nFlag=TRUE) {bIsDate=nFlag;}
void SetTheDateMode(ScChgsDateMode eDatMod){ eDateMode=eDatMod; }
ScChgsDateMode GetTheDateMode() const { return eDateMode; }
void SetTheFirstDateTime(const DateTime& aDateTime) {aFirstDateTime=aDateTime;}
const DateTime& GetTheFirstDateTime()const {return aFirstDateTime;}
void SetTheLastDateTime(const DateTime& aDateTime) {aLastDateTime=aDateTime;}
const DateTime& GetTheLastDateTime()const {return aLastDateTime;}
BOOL HasAuthor() const {return bIsAuthor;}
void SetHasAuthor(BOOL nFlag=TRUE) {bIsAuthor=nFlag;}
String GetTheAuthorToShow()const {return aAuthorToShow;}
void SetTheAuthorToShow(const String& aString){aAuthorToShow=aString;}
BOOL HasComment() const {return bIsComment;}
void SetHasComment(BOOL nFlag=TRUE) {bIsComment=nFlag;}
String GetTheComment()const {return aComment;}
void SetTheComment(const String& aString);
BOOL IsValidComment(const String* pCommentStr) const;
BOOL IsEveryoneButMe() const {return bEveryoneButMe;}
void SetEveryoneButMe(BOOL nFlag=TRUE) {bEveryoneButMe=nFlag;}
BOOL HasRange() const {return bIsRange;}
void SetHasRange(BOOL nFlag=TRUE) {bIsRange=nFlag;}
const ScRangeList& GetTheRangeList()const {return aRangeList;}
void SetTheRangeList(const ScRangeList& aRl){aRangeList=aRl;}
BOOL IsShowAccepted() const { return bShowAccepted; }
void SetShowAccepted( BOOL bVal ) { bShowAccepted = bVal; }
BOOL IsShowRejected() const { return bShowRejected; }
void SetShowRejected( BOOL bVal ) { bShowRejected = bVal; }
void Load( SvStream& rStream, USHORT nVer );
void Store( SvStream& rStream ) const;
ScChangeViewSettings& operator= ( const ScChangeViewSettings& r );
/// Adjust dates according to selected DateMode
void AdjustDateMode( const ScDocument& rDoc );
bool HasActionRange() const { return mbIsActionRange; }
void SetHasActionRange( bool nFlag = true ) { mbIsActionRange = nFlag; }
void GetTheActionRange( ULONG& nFirst, ULONG& nLast ) const { nFirst = mnFirstAction; nLast = mnLastAction; }
void SetTheActionRange( ULONG nFirst, ULONG nLast ) { mnFirstAction = nFirst; mnLastAction = nLast; }
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conditio.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:28:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;
#define SC_COND_GROW 16
// nOptions Flags
#define SC_COND_NOBLANKS 1
// Reihenfolge von ScConditionMode wie ScQueryOp,
// damit einmal zusammengefasst werden kann:
enum ScConditionMode
{
SC_COND_EQUAL,
SC_COND_LESS,
SC_COND_GREATER,
SC_COND_EQLESS,
SC_COND_EQGREATER,
SC_COND_NOTEQUAL,
SC_COND_BETWEEN,
SC_COND_NOTBETWEEN,
SC_COND_DIRECT,
SC_COND_NONE
};
enum ScConditionValType
{
SC_VAL_VALUE,
SC_VAL_STRING,
SC_VAL_FORMULA
};
class ScConditionEntry
{
// gespeicherte Daten:
ScConditionMode eOp;
USHORT nOptions;
double nVal1; // eingegeben oder berechnet
double nVal2;
String aStrVal1; // eingegeben oder berechnet
String aStrVal2;
BOOL bIsStr1; // um auch leere Strings zu erkennen
BOOL bIsStr2;
ScTokenArray* pFormula1; // eingegebene Formel
ScTokenArray* pFormula2;
ScAddress aSrcPos; // source position for formulas
// temporary data:
String aSrcString; // formula source position as text during XML import
ScFormulaCell* pFCell1;
ScFormulaCell* pFCell2;
ScDocument* pDoc;
BOOL bRelRef1;
BOOL bRelRef2;
BOOL bFirstRun;
void MakeCells( const ScAddress& rPos );
void Compile( const String& rExpr1, const String& rExpr2, BOOL bEnglish,
BOOL bCompileXML, BOOL bTextToReal );
void Interpret( const ScAddress& rPos );
BOOL IsValid( double nArg ) const;
BOOL IsValidStr( const String& rArg ) const;
protected:
ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
void StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
public:
ScConditionEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
BOOL bCompileEnglish, BOOL bCompileXML );
ScConditionEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScConditionEntry( const ScConditionEntry& r ); // flache Kopie der Formeln
// echte Kopie der Formeln (fuer Ref-Undo):
ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
virtual ~ScConditionEntry();
int operator== ( const ScConditionEntry& r ) const;
BOOL IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
ScConditionMode GetOperation() const { return eOp; }
BOOL IsIgnoreBlank() const { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
void SetIgnoreBlank(BOOL bSet);
ScAddress GetSrcPos() const { return aSrcPos; }
ScAddress GetValidSrcPos() const; // adjusted to allow textual representation of expressions
void SetSrcString( const String& rNew ); // for XML import
String GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
BOOL bEnglish = FALSE, BOOL bCompileXML = FALSE,
BOOL bTextToReal = FALSE ) const;
ScTokenArray* CreateTokenArry( USHORT nPos ) const;
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rChanged );
protected:
virtual void DataChanged( const ScRange* pModified ) const;
ScDocument* GetDocument() const { return pDoc; }
};
//
// einzelner Eintrag fuer bedingte Formatierung
//
class ScConditionalFormat;
class ScCondFormatEntry : public ScConditionEntry
{
String aStyleName;
ScConditionalFormat* pParent;
public:
ScCondFormatEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle,
BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
ScCondFormatEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle );
ScCondFormatEntry( const ScCondFormatEntry& r );
ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScCondFormatEntry();
void SetParent( ScConditionalFormat* pNew ) { pParent = pNew; }
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
int operator== ( const ScCondFormatEntry& r ) const;
const String& GetStyle() const { return aStyleName; }
protected:
virtual void DataChanged( const ScRange* pModified ) const;
};
//
// komplette bedingte Formatierung
//
class ScConditionalFormat
{
ScDocument* pDoc;
ScRangeList* pAreas; // Bereiche fuer Paint
ULONG nKey; // Index in Attributen
ScCondFormatEntry** ppEntries;
USHORT nEntryCount;
BOOL bIsUsed; // temporaer beim Speichern
public:
ScConditionalFormat(ULONG nNewKey, ScDocument* pDocument);
ScConditionalFormat(const ScConditionalFormat& r);
ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument);
~ScConditionalFormat();
// echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
void AddEntry( const ScCondFormatEntry& rNew );
BOOL IsEmpty() const { return (nEntryCount == 0); }
USHORT Count() const { return nEntryCount; }
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
const ScCondFormatEntry* GetEntry( USHORT nPos ) const;
const String& GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;
BOOL EqualEntries( const ScConditionalFormat& r ) const;
void DoRepaint( const ScRange* pModified );
void InvalidateArea();
ULONG GetKey() const { return nKey; }
void SetKey(ULONG nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScConditionalFormat& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScConditionalFormat& r ) const { return nKey < r.nKey; }
};
//
// Liste der Bereiche und Formate:
//
typedef ScConditionalFormat* ScConditionalFormatPtr;
SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
SC_COND_GROW, SC_COND_GROW);
class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
ScConditionalFormatList() {}
ScConditionalFormatList(const ScConditionalFormatList& rList);
ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
~ScConditionalFormatList() {}
void InsertNew( ScConditionalFormat* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScConditionalFormat* GetFormat( ULONG nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
BOOL operator==( const ScConditionalFormatList& r ) const; // fuer Ref-Undo
};
#endif
<commit_msg>INTEGRATION: CWS sixtyfour04 (1.8.142); FILE MERGED 2006/03/15 16:14:03 cmc 1.8.142.1: #i63168# make sc 64bit happy<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conditio.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: vg $ $Date: 2006-04-07 08:24: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
*
************************************************************************/
#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;
#define SC_COND_GROW 16
// nOptions Flags
#define SC_COND_NOBLANKS 1
// Reihenfolge von ScConditionMode wie ScQueryOp,
// damit einmal zusammengefasst werden kann:
enum ScConditionMode
{
SC_COND_EQUAL,
SC_COND_LESS,
SC_COND_GREATER,
SC_COND_EQLESS,
SC_COND_EQGREATER,
SC_COND_NOTEQUAL,
SC_COND_BETWEEN,
SC_COND_NOTBETWEEN,
SC_COND_DIRECT,
SC_COND_NONE
};
enum ScConditionValType
{
SC_VAL_VALUE,
SC_VAL_STRING,
SC_VAL_FORMULA
};
class ScConditionEntry
{
// gespeicherte Daten:
ScConditionMode eOp;
USHORT nOptions;
double nVal1; // eingegeben oder berechnet
double nVal2;
String aStrVal1; // eingegeben oder berechnet
String aStrVal2;
BOOL bIsStr1; // um auch leere Strings zu erkennen
BOOL bIsStr2;
ScTokenArray* pFormula1; // eingegebene Formel
ScTokenArray* pFormula2;
ScAddress aSrcPos; // source position for formulas
// temporary data:
String aSrcString; // formula source position as text during XML import
ScFormulaCell* pFCell1;
ScFormulaCell* pFCell2;
ScDocument* pDoc;
BOOL bRelRef1;
BOOL bRelRef2;
BOOL bFirstRun;
void MakeCells( const ScAddress& rPos );
void Compile( const String& rExpr1, const String& rExpr2, BOOL bEnglish,
BOOL bCompileXML, BOOL bTextToReal );
void Interpret( const ScAddress& rPos );
BOOL IsValid( double nArg ) const;
BOOL IsValidStr( const String& rArg ) const;
protected:
ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
void StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
public:
ScConditionEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
BOOL bCompileEnglish, BOOL bCompileXML );
ScConditionEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScConditionEntry( const ScConditionEntry& r ); // flache Kopie der Formeln
// echte Kopie der Formeln (fuer Ref-Undo):
ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
virtual ~ScConditionEntry();
int operator== ( const ScConditionEntry& r ) const;
BOOL IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
ScConditionMode GetOperation() const { return eOp; }
BOOL IsIgnoreBlank() const { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
void SetIgnoreBlank(BOOL bSet);
ScAddress GetSrcPos() const { return aSrcPos; }
ScAddress GetValidSrcPos() const; // adjusted to allow textual representation of expressions
void SetSrcString( const String& rNew ); // for XML import
String GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
BOOL bEnglish = FALSE, BOOL bCompileXML = FALSE,
BOOL bTextToReal = FALSE ) const;
ScTokenArray* CreateTokenArry( USHORT nPos ) const;
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rChanged );
protected:
virtual void DataChanged( const ScRange* pModified ) const;
ScDocument* GetDocument() const { return pDoc; }
};
//
// einzelner Eintrag fuer bedingte Formatierung
//
class ScConditionalFormat;
class ScCondFormatEntry : public ScConditionEntry
{
String aStyleName;
ScConditionalFormat* pParent;
public:
ScCondFormatEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle,
BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
ScCondFormatEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle );
ScCondFormatEntry( const ScCondFormatEntry& r );
ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScCondFormatEntry();
void SetParent( ScConditionalFormat* pNew ) { pParent = pNew; }
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
int operator== ( const ScCondFormatEntry& r ) const;
const String& GetStyle() const { return aStyleName; }
protected:
virtual void DataChanged( const ScRange* pModified ) const;
};
//
// komplette bedingte Formatierung
//
class ScConditionalFormat
{
ScDocument* pDoc;
ScRangeList* pAreas; // Bereiche fuer Paint
sal_uInt32 nKey; // Index in Attributen
ScCondFormatEntry** ppEntries;
USHORT nEntryCount;
BOOL bIsUsed; // temporaer beim Speichern
public:
ScConditionalFormat(sal_uInt32 nNewKey, ScDocument* pDocument);
ScConditionalFormat(const ScConditionalFormat& r);
ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument);
~ScConditionalFormat();
// echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
void AddEntry( const ScCondFormatEntry& rNew );
BOOL IsEmpty() const { return (nEntryCount == 0); }
USHORT Count() const { return nEntryCount; }
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
const ScCondFormatEntry* GetEntry( USHORT nPos ) const;
const String& GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;
BOOL EqualEntries( const ScConditionalFormat& r ) const;
void DoRepaint( const ScRange* pModified );
void InvalidateArea();
sal_uInt32 GetKey() const { return nKey; }
void SetKey(sal_uInt32 nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScConditionalFormat& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScConditionalFormat& r ) const { return nKey < r.nKey; }
};
//
// Liste der Bereiche und Formate:
//
typedef ScConditionalFormat* ScConditionalFormatPtr;
SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
SC_COND_GROW, SC_COND_GROW);
class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
ScConditionalFormatList() {}
ScConditionalFormatList(const ScConditionalFormatList& rList);
ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
~ScConditionalFormatList() {}
void InsertNew( ScConditionalFormat* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScConditionalFormat* GetFormat( sal_uInt32 nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
BOOL operator==( const ScConditionalFormatList& r ) const; // fuer Ref-Undo
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: notesuno.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:44:49 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_NOTESUNO_HXX
#define SC_NOTESUNO_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx" // ScRange, ScAddress
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSHEETANNOTATION_HPP_
#include <com/sun/star/sheet/XSheetAnnotation.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XSIMPLETEXT_HPP_
#include <com/sun/star/text/XSimpleText.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
class ScDocShell;
class SvxUnoText;
class ScAnnotationObj : public cppu::WeakImplHelper4<
com::sun::star::container::XChild,
com::sun::star::text::XSimpleText,
com::sun::star::sheet::XSheetAnnotation,
com::sun::star::lang::XServiceInfo >,
public SfxListener
{
private:
ScDocShell* pDocShell;
ScAddress aCellPos;
SvxUnoText* pUnoText;
private:
SvxUnoText& GetUnoText();
public:
ScAnnotationObj(ScDocShell* pDocSh, const ScAddress& rPos);
virtual ~ScAnnotationObj();
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
// XChild
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
getParent() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface >& Parent )
throw(::com::sun::star::lang::NoSupportException,
::com::sun::star::uno::RuntimeException);
// XSimpleText
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
createTextCursor() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
createTextCursorByRange( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& aTextPosition )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertString( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& xRange,
const ::rtl::OUString& aString, sal_Bool bAbsorb )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertControlCharacter( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& xRange,
sal_Int16 nControlCharacter, sal_Bool bAbsorb )
throw(::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException);
// XTextRange
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL
getText() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
getStart() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
getEnd() throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getString() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( const ::rtl::OUString& aString )
throw(::com::sun::star::uno::RuntimeException);
// XSheetAnnotation
virtual ::com::sun::star::table::CellAddress SAL_CALL getPosition()
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getAuthor() throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getDate() throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getIsVisible() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setIsVisible( sal_Bool bIsVisible )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.1.1.1.346); FILE MERGED 2003/11/28 19:47:24 er 1.1.1.1.346.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
*
* $RCSfile: notesuno.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-06-04 10:11:29 $
*
* 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 SC_NOTESUNO_HXX
#define SC_NOTESUNO_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSHEETANNOTATION_HPP_
#include <com/sun/star/sheet/XSheetAnnotation.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XSIMPLETEXT_HPP_
#include <com/sun/star/text/XSimpleText.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
class ScDocShell;
class SvxUnoText;
class ScAnnotationObj : public cppu::WeakImplHelper4<
com::sun::star::container::XChild,
com::sun::star::text::XSimpleText,
com::sun::star::sheet::XSheetAnnotation,
com::sun::star::lang::XServiceInfo >,
public SfxListener
{
private:
ScDocShell* pDocShell;
ScAddress aCellPos;
SvxUnoText* pUnoText;
private:
SvxUnoText& GetUnoText();
public:
ScAnnotationObj(ScDocShell* pDocSh, const ScAddress& rPos);
virtual ~ScAnnotationObj();
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
// XChild
virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
getParent() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface >& Parent )
throw(::com::sun::star::lang::NoSupportException,
::com::sun::star::uno::RuntimeException);
// XSimpleText
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
createTextCursor() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextCursor > SAL_CALL
createTextCursorByRange( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& aTextPosition )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertString( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& xRange,
const ::rtl::OUString& aString, sal_Bool bAbsorb )
throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL insertControlCharacter( const ::com::sun::star::uno::Reference<
::com::sun::star::text::XTextRange >& xRange,
sal_Int16 nControlCharacter, sal_Bool bAbsorb )
throw(::com::sun::star::lang::IllegalArgumentException,
::com::sun::star::uno::RuntimeException);
// XTextRange
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XText > SAL_CALL
getText() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
getStart() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::text::XTextRange > SAL_CALL
getEnd() throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getString() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setString( const ::rtl::OUString& aString )
throw(::com::sun::star::uno::RuntimeException);
// XSheetAnnotation
virtual ::com::sun::star::table::CellAddress SAL_CALL getPosition()
throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getAuthor() throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getDate() throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getIsVisible() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setIsVisible( sal_Bool bIsVisible )
throw(::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName()
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
throw(::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>
#include <itksys/SystemTools.hxx>
class mitkIOUtilTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
MITK_TEST(TestTempMethods);
MITK_TEST(TestLoadAndSaveImage);
MITK_TEST(TestLoadAndSavePointSet);
MITK_TEST(TestLoadAndSaveSurface);
CPPUNIT_TEST_SUITE_END();
private:
std::string m_ImagePath;
std::string m_SurfacePath;
std::string m_PointSetPath;
public:
void setUp()
{
m_ImagePath = std::string(MITK_DATA_DIR) + "/" + "Pic3D.nrrd";
m_SurfacePath = std::string(MITK_DATA_DIR) + "/" + "binary.stl";
m_PointSetPath = std::string(MITK_DATA_DIR) + "/" + "pointSet.mps";
}
void TestTempMethods()
{
std::string tmpPath = mitk::IOUtil::GetTempPath();
CPPUNIT_ASSERT(!tmpPath.empty());
std::ofstream tmpFile;
std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);
tmpFile.close();
CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);
std::string programPath = mitk::IOUtil::GetProgramPath();
CPPUNIT_ASSERT(!programPath.empty());
std::ofstream tmpFile2;
std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
tmpFile2.close();
CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);
std::ofstream tmpFile3;
std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
"my-XXXXXX.TXT", programPath);
CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
tmpFile3.close();
//CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)
CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);
std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));
std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
}
void TestLoadAndSaveImage()
{
mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
CPPUNIT_ASSERT( img1.IsNotNull());
std::ofstream tmpStream;
std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
tmpStream.close();
std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
tmpStream.close();
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));
//load data which does not exist
CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);
//delete the files after the test is done
std::remove(imagePath.c_str());
std::remove(imagePath2.c_str());
mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
tmpStream.close();
mitk::IOUtil::SaveImage(relativImage, imagePath3);
CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
std::remove(imagePath3.c_str());
}
void TestLoadAndSavePointSet()
{
mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
CPPUNIT_ASSERT( pointset.IsNotNull());
std::ofstream tmpStream;
std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
tmpStream.close();
std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
tmpStream.close();
std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
tmpStream.close();
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));
// test if defaultextension is inserted if no extension is present
CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));
//delete the files after the test is done
std::remove(pointSetPath.c_str());
std::remove(pointSetPathWithDefaultExtension.c_str());
std::remove(pointSetPathWithoutDefaultExtension.c_str());
}
void TestLoadAndSaveSurface()
{
mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
CPPUNIT_ASSERT( surface.IsNotNull());
std::ofstream tmpStream;
std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));
// test if exception is thrown as expected on unknown extsension
CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);
//delete the files after the test is done
std::remove(surfacePath.c_str());
}
};
MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<commit_msg>Use the getTestDataFilePath() method to get absolute paths to test data.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>
#include <mitkIOUtil.h>
#include <mitkImageGenerator.h>
#include <itksys/SystemTools.hxx>
class mitkIOUtilTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkIOUtilTestSuite);
MITK_TEST(TestTempMethods);
MITK_TEST(TestLoadAndSaveImage);
MITK_TEST(TestLoadAndSavePointSet);
MITK_TEST(TestLoadAndSaveSurface);
CPPUNIT_TEST_SUITE_END();
private:
std::string m_ImagePath;
std::string m_SurfacePath;
std::string m_PointSetPath;
public:
void setUp()
{
m_ImagePath = getTestDataFilePath("Pic3D.nrrd");
m_SurfacePath = getTestDataFilePath("binary.stl");
m_PointSetPath = getTestDataFilePath("pointSet.mps");
}
void TestTempMethods()
{
std::string tmpPath = mitk::IOUtil::GetTempPath();
CPPUNIT_ASSERT(!tmpPath.empty());
std::ofstream tmpFile;
std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpFile);
CPPUNIT_ASSERT(tmpFile && tmpFile.is_open());
CPPUNIT_ASSERT(tmpFilePath.size() > tmpPath.size());
CPPUNIT_ASSERT(tmpFilePath.substr(0, tmpPath.size()) == tmpPath);
tmpFile.close();
CPPUNIT_ASSERT(std::remove(tmpFilePath.c_str()) == 0);
std::string programPath = mitk::IOUtil::GetProgramPath();
CPPUNIT_ASSERT(!programPath.empty());
std::ofstream tmpFile2;
std::string tmpFilePath2 = mitk::IOUtil::CreateTemporaryFile(tmpFile2, "my-XXXXXX", programPath);
CPPUNIT_ASSERT(tmpFile2 && tmpFile2.is_open());
CPPUNIT_ASSERT(tmpFilePath2.size() > programPath.size());
CPPUNIT_ASSERT(tmpFilePath2.substr(0, programPath.size()) == programPath);
tmpFile2.close();
CPPUNIT_ASSERT(std::remove(tmpFilePath2.c_str()) == 0);
std::ofstream tmpFile3;
std::string tmpFilePath3 = mitk::IOUtil::CreateTemporaryFile(tmpFile3, std::ios_base::binary,
"my-XXXXXX.TXT", programPath);
CPPUNIT_ASSERT(tmpFile3 && tmpFile3.is_open());
CPPUNIT_ASSERT(tmpFilePath3.size() > programPath.size());
CPPUNIT_ASSERT(tmpFilePath3.substr(0, programPath.size()) == programPath);
CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 13, 3) == "my-");
CPPUNIT_ASSERT(tmpFilePath3.substr(tmpFilePath3.size() - 4) == ".TXT");
tmpFile3.close();
//CPPUNIT_ASSERT(std::remove(tmpFilePath3.c_str()) == 0)
CPPUNIT_ASSERT_THROW(mitk::IOUtil::CreateTemporaryFile(tmpFile2, "XX"), mitk::Exception);
std::string tmpDir = mitk::IOUtil::CreateTemporaryDirectory();
CPPUNIT_ASSERT(tmpDir.size() > tmpPath.size());
CPPUNIT_ASSERT(tmpDir.substr(0, tmpPath.size()) == tmpPath);
CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir.c_str()));
std::string tmpDir2 = mitk::IOUtil::CreateTemporaryDirectory("my-XXXXXX", programPath);
CPPUNIT_ASSERT(tmpDir2.size() > programPath.size());
CPPUNIT_ASSERT(tmpDir2.substr(0, programPath.size()) == programPath);
CPPUNIT_ASSERT(itksys::SystemTools::RemoveADirectory(tmpDir2.c_str()));
}
void TestLoadAndSaveImage()
{
mitk::Image::Pointer img1 = mitk::IOUtil::LoadImage(m_ImagePath);
CPPUNIT_ASSERT( img1.IsNotNull());
std::ofstream tmpStream;
std::string imagePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nrrd");
tmpStream.close();
std::string imagePath2 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffpic3d-XXXXXX.nii.gz");
tmpStream.close();
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SaveImage(img1, imagePath));
CPPUNIT_ASSERT(mitk::IOUtil::SaveBaseData(img1.GetPointer(), imagePath2));
//load data which does not exist
CPPUNIT_ASSERT_THROW(mitk::IOUtil::LoadImage("fileWhichDoesNotExist.nrrd"), mitk::Exception);
//delete the files after the test is done
std::remove(imagePath.c_str());
std::remove(imagePath2.c_str());
mitk::Image::Pointer relativImage = mitk::ImageGenerator::GenerateGradientImage<float>(4,4,4,1);
std::string imagePath3 = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd");
tmpStream.close();
mitk::IOUtil::SaveImage(relativImage, imagePath3);
CPPUNIT_ASSERT_NO_THROW(mitk::IOUtil::LoadImage(imagePath3));
std::remove(imagePath3.c_str());
}
void TestLoadAndSavePointSet()
{
mitk::PointSet::Pointer pointset = mitk::IOUtil::LoadPointSet(m_PointSetPath);
CPPUNIT_ASSERT( pointset.IsNotNull());
std::ofstream tmpStream;
std::string pointSetPath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
tmpStream.close();
std::string pointSetPathWithDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mps");
tmpStream.close();
std::string pointSetPathWithoutDefaultExtension = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.xXx");
tmpStream.close();
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithDefaultExtension));
// test if defaultextension is inserted if no extension is present
CPPUNIT_ASSERT(mitk::IOUtil::SavePointSet(pointset, pointSetPathWithoutDefaultExtension.c_str()));
//delete the files after the test is done
std::remove(pointSetPath.c_str());
std::remove(pointSetPathWithDefaultExtension.c_str());
std::remove(pointSetPathWithoutDefaultExtension.c_str());
}
void TestLoadAndSaveSurface()
{
mitk::Surface::Pointer surface = mitk::IOUtil::LoadSurface(m_SurfacePath);
CPPUNIT_ASSERT( surface.IsNotNull());
std::ofstream tmpStream;
std::string surfacePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "diffsurface-XXXXXX.stl");
// the cases where no exception should be thrown
CPPUNIT_ASSERT(mitk::IOUtil::SaveSurface(surface, surfacePath));
// test if exception is thrown as expected on unknown extsension
CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveSurface(surface,"testSurface.xXx"), mitk::Exception);
//delete the files after the test is done
std::remove(surfacePath.c_str());
}
};
MITK_TEST_SUITE_REGISTRATION(mitkIOUtil)
<|endoftext|>
|
<commit_before>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
TEveElementList* esd_spd_tracklets(Float_t radius=8, Width_t line_width=3,
Float_t dPhiWindow=0.080, Float_t dThetaWindow=0.025,
Float_t dPhiShift05T=0.0045)
{
// radius - cylindrical radius to which the tracklets should be extrapolated
AliESDEvent *esd = AliEveEventManager::AssertESD();
AliESDVertex *pv = esd->GetPrimaryVertexSPD();
AliMultiplicity *mul = esd->GetMultiplicity();
AliMagF *field = AliEveEventManager::AssertMagField();
TEveElementList* cont = new TEveElementList("SPD Tracklets");
gEve->AddElement(cont);
TEveTrackList *tg = new TEveTrackList("Good");
tg->SetMainColor(7);
tg->SetLineWidth(line_width);
cont->AddElement(tg);
TEveTrackPropagator* pg = tg->GetPropagator();
pg->SetMaxR(radius);
TEveTrackList *tb = new TEveTrackList("Bad");
tb->SetMainColor(7);
tb->SetLineWidth(line_width);
cont->AddElement(tb);
TEveTrackPropagator* pb = tb->GetPropagator();
pb->SetMaxR(radius);
const Float_t Bz = TMath::Abs(field->SolenoidField());
const Double_t dPhiShift = dPhiShift05T / 5.0 * Bz;
const Double_t dPhiWindow2 = dPhiWindow * dPhiWindow;
const Double_t dThetaWindow2 = dThetaWindow * dThetaWindow;
for (Int_t i = 0; i < mul->GetNumberOfTracklets(); ++i)
{
Float_t theta = mul->GetTheta(i);
Float_t phi = mul->GetPhi(i);
Float_t dTheta = mul->GetDeltaTheta(i);
Float_t dPhi = mul->GetDeltaPhi(i) - dPhiShift;
Float_t d = dPhi*dPhi/dPhiWindow2 + dTheta*dTheta/dThetaWindow2;
TEveTrackList* tl = (d < 1.0f) ? tg : tb;
AliEveTracklet *t = new AliEveTracklet(i, pv, theta, phi, tl->GetPropagator());
t->SetAttLineAttMarker(tl);
t->SetElementName(Form("Tracklet %d", i));
t->SetElementTitle(Form("Id = %d\nEta=%.3f, Theta=%.3f, dTheta=%.3f\nPhi=%.3f dPhi=%.3f",
i, mul->GetEta(i), theta, dTheta, phi, dPhi));
tl->AddElement(t);
}
tg->MakeTracks();
tg->SetTitle(Form("N=%d", tg->NumChildren()));
tb->MakeTracks();
tb->SetTitle(Form("N=%d", tb->NumChildren()));
if (AliEveTrackCounter::IsActive())
{
AliEveTrackCounter::fgInstance->RegisterTracklets(tg, kTRUE);
AliEveTrackCounter::fgInstance->RegisterTracklets(tb, kFALSE);
}
else
{
tb->SetLineStyle(6);
}
gEve->Redraw3D();
return cont;
}
<commit_msg>SPD trackelts were too thick.<commit_after>// $Id$
// Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007
/**************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
* See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for *
* full copyright notice. *
**************************************************************************/
TEveElementList* esd_spd_tracklets(Float_t radius=8, Width_t line_width=2,
Float_t dPhiWindow=0.080, Float_t dThetaWindow=0.025,
Float_t dPhiShift05T=0.0045)
{
// radius - cylindrical radius to which the tracklets should be extrapolated
AliESDEvent *esd = AliEveEventManager::AssertESD();
AliESDVertex *pv = esd->GetPrimaryVertexSPD();
AliMultiplicity *mul = esd->GetMultiplicity();
AliMagF *field = AliEveEventManager::AssertMagField();
TEveElementList* cont = new TEveElementList("SPD Tracklets");
gEve->AddElement(cont);
TEveTrackList *tg = new TEveTrackList("Good");
tg->SetMainColor(7);
tg->SetLineWidth(line_width);
cont->AddElement(tg);
TEveTrackPropagator* pg = tg->GetPropagator();
pg->SetMaxR(radius);
TEveTrackList *tb = new TEveTrackList("Bad");
tb->SetMainColor(7);
tb->SetLineWidth(line_width);
cont->AddElement(tb);
TEveTrackPropagator* pb = tb->GetPropagator();
pb->SetMaxR(radius);
const Float_t Bz = TMath::Abs(field->SolenoidField());
const Double_t dPhiShift = dPhiShift05T / 5.0 * Bz;
const Double_t dPhiWindow2 = dPhiWindow * dPhiWindow;
const Double_t dThetaWindow2 = dThetaWindow * dThetaWindow;
for (Int_t i = 0; i < mul->GetNumberOfTracklets(); ++i)
{
Float_t theta = mul->GetTheta(i);
Float_t phi = mul->GetPhi(i);
Float_t dTheta = mul->GetDeltaTheta(i);
Float_t dPhi = mul->GetDeltaPhi(i) - dPhiShift;
Float_t d = dPhi*dPhi/dPhiWindow2 + dTheta*dTheta/dThetaWindow2;
TEveTrackList* tl = (d < 1.0f) ? tg : tb;
AliEveTracklet *t = new AliEveTracklet(i, pv, theta, phi, tl->GetPropagator());
t->SetAttLineAttMarker(tl);
t->SetElementName(Form("Tracklet %d", i));
t->SetElementTitle(Form("Id = %d\nEta=%.3f, Theta=%.3f, dTheta=%.3f\nPhi=%.3f dPhi=%.3f",
i, mul->GetEta(i), theta, dTheta, phi, dPhi));
tl->AddElement(t);
}
tg->MakeTracks();
tg->SetTitle(Form("N=%d", tg->NumChildren()));
tb->MakeTracks();
tb->SetTitle(Form("N=%d", tb->NumChildren()));
if (AliEveTrackCounter::IsActive())
{
AliEveTrackCounter::fgInstance->RegisterTracklets(tg, kTRUE);
AliEveTrackCounter::fgInstance->RegisterTracklets(tb, kFALSE);
}
else
{
tb->SetLineStyle(6);
}
gEve->Redraw3D();
return cont;
}
<|endoftext|>
|
<commit_before>//
// upb - a minimalist implementation of protocol buffers.
//
// Copyright (c) 2011 Google Inc. See LICENSE for details.
// Author: Josh Haberman <jhaberman@gmail.com>
// Routines for reading and writing message data to an in-memory structure,
// similar to a C struct.
//
// upb does not define one single message object that everyone must use.
// Rather it defines an abstract interface for reading and writing members
// of a message object, and all of the parsers and serializers use this
// abstract interface. This allows upb's parsers and serializers to be used
// regardless of what memory management scheme or synchronization model the
// application is using.
//
// A standard set of accessors is provided for doing simple reads and writes at
// a known offset into the message. These accessors should be used when
// possible, because they are specially optimized -- for example, the JIT can
// recognize them and emit specialized code instead of having to call the
// function at all. The application can substitute its own accessors when the
// standard accessors are not suitable.
#ifndef UPB_MSG_HPP
#define UPB_MSG_HPP
#include "upb/msg.h"
#include "upb/handlers.hpp"
namespace upb {
typedef upb_accessor_vtbl AccessorVTable;
// Registers handlers for writing into a message of the given type using
// whatever accessors it has defined.
inline MessageHandlers* RegisterWriteHandlers(upb::Handlers* handlers,
const upb::MessageDef* md) {
return MessageHandlers::Cast(
upb_accessors_reghandlers(handlers, md));
}
template <typename T> static FieldHandlers::ValueHandler* GetValueHandler();
// A handy templated function that will retrieve a value handler for a given
// C++ type.
#define GET_VALUE_HANDLER(type, ctype) \
template <> \
FieldHandlers::ValueHandler* GetValueHandler<ctype>() { \
return &upb_stdmsg_set ## type; \
}
GET_VALUE_HANDLER(double, double);
GET_VALUE_HANDLER(float, float);
GET_VALUE_HANDLER(uint64, uint64_t);
GET_VALUE_HANDLER(uint32, uint32_t);
GET_VALUE_HANDLER(int64, int64_t);
GET_VALUE_HANDLER(int32, int32_t);
GET_VALUE_HANDLER(bool, bool);
#undef GET_VALUE_HANDLER
} // namespace
#endif
<commit_msg>Fix duplicate symbol on OS X.<commit_after>//
// upb - a minimalist implementation of protocol buffers.
//
// Copyright (c) 2011 Google Inc. See LICENSE for details.
// Author: Josh Haberman <jhaberman@gmail.com>
// Routines for reading and writing message data to an in-memory structure,
// similar to a C struct.
//
// upb does not define one single message object that everyone must use.
// Rather it defines an abstract interface for reading and writing members
// of a message object, and all of the parsers and serializers use this
// abstract interface. This allows upb's parsers and serializers to be used
// regardless of what memory management scheme or synchronization model the
// application is using.
//
// A standard set of accessors is provided for doing simple reads and writes at
// a known offset into the message. These accessors should be used when
// possible, because they are specially optimized -- for example, the JIT can
// recognize them and emit specialized code instead of having to call the
// function at all. The application can substitute its own accessors when the
// standard accessors are not suitable.
#ifndef UPB_MSG_HPP
#define UPB_MSG_HPP
#include "upb/msg.h"
#include "upb/handlers.hpp"
namespace upb {
typedef upb_accessor_vtbl AccessorVTable;
// Registers handlers for writing into a message of the given type using
// whatever accessors it has defined.
inline MessageHandlers* RegisterWriteHandlers(upb::Handlers* handlers,
const upb::MessageDef* md) {
return MessageHandlers::Cast(
upb_accessors_reghandlers(handlers, md));
}
template <typename T> static FieldHandlers::ValueHandler* GetValueHandler();
// A handy templated function that will retrieve a value handler for a given
// C++ type.
#define GET_VALUE_HANDLER(type, ctype) \
template <> \
inline FieldHandlers::ValueHandler* GetValueHandler<ctype>() { \
return &upb_stdmsg_set ## type; \
}
GET_VALUE_HANDLER(double, double);
GET_VALUE_HANDLER(float, float);
GET_VALUE_HANDLER(uint64, uint64_t);
GET_VALUE_HANDLER(uint32, uint32_t);
GET_VALUE_HANDLER(int64, int64_t);
GET_VALUE_HANDLER(int32, int32_t);
GET_VALUE_HANDLER(bool, bool);
#undef GET_VALUE_HANDLER
} // namespace
#endif
<|endoftext|>
|
<commit_before>#include "directory.hh"
#include "../messages/filelist.hh"
#include "../messages/boost_impl.hh"
#include "../messages/factory.hh"
#include <boost/asio.hpp>
#include <iomanip>
using namespace std;
using namespace eclipse;
using namespace eclipse::messages;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;
boost::asio::io_service iosvc;
tcp::socket* connect (int index) {
tcp::socket* socket = new tcp::socket (iosvc);
Settings setted = Settings().load();
int port = setted.get<int> ("network.port_mapreduce");
vec_str nodes = setted.get<vec_str> ("network.nodes");
string host = nodes[ index ];
tcp::resolver resolver (iosvc);
tcp::resolver::query query (host, to_string(port));
tcp::resolver::iterator it (resolver.resolve(query));
auto ep = new tcp::endpoint (*it);
socket->connect(*ep);
return socket;
}
void send_message (tcp::socket* socket, eclipse::messages::Message* msg) {
string out = save_message(msg);
stringstream ss;
ss << setfill('0') << setw(16) << out.length() << out;
socket->send(boost::asio::buffer(ss.str()));
}
eclipse::messages::FileList* read_reply(tcp::socket* socket) {
char header[16];
socket->receive(boost::asio::buffer(header));
size_t size_of_msg = atoi(header);
char* body = new char[size_of_msg];
socket->receive(boost::asio::buffer(body, size_of_msg));
string recv_msg(body);
eclipse::messages::Message* m = load_message(recv_msg);
return dynamic_cast<eclipse::messages::FileList*>(m);
}
int main(int argc, char* argv[])
{
Context con;
const int NUM_SERVERS = con.settings.get<vector<string>>("network.nodes").size();
vector<string> nodes = con.settings.get<vector<string>>("network.nodes");
vector<string>::iterator nit = nodes.begin();
for(int net_id=0; net_id<NUM_SERVERS; net_id++)
{
FileList file_list;
tcp::socket* socket = connect(net_id);
send_message(socket, &file_list);
auto file_list_reply = read_reply(socket);
socket->close();
cout << *nit << endl;
cout << setw(12) << "Hash Key"
<< setw(12) << "Size"
<< setw(12) << "NumBlocks"
<< setw(12) << "Replicas"
<< "\t" << "FileName" << endl;
nit++;
// client side
for(vector<FileInfo>::iterator it=file_list_reply->data.begin(); it!=file_list_reply->data.end(); it++)
{
cout << setw(12) << it->file_hash_key
<< setw(12) << it->file_size
<< setw(12) << it->num_block
<< setw(12) << it->replica
<< "\t" << it->file_name << endl;
}
delete file_list_reply;
}
return 0;
}
<commit_msg>added pretty printing<commit_after>#include "directory.hh"
#include "../messages/filelist.hh"
#include "../messages/boost_impl.hh"
#include "../messages/factory.hh"
#include <boost/asio.hpp>
#include <iomanip>
using namespace std;
using namespace eclipse;
using namespace eclipse::messages;
using boost::asio::ip::tcp;
using vec_str = std::vector<std::string>;
boost::asio::io_service iosvc;
tcp::socket* connect (int index) {
tcp::socket* socket = new tcp::socket (iosvc);
Settings setted = Settings().load();
int port = setted.get<int> ("network.port_mapreduce");
vec_str nodes = setted.get<vec_str> ("network.nodes");
string host = nodes[ index ];
tcp::resolver resolver (iosvc);
tcp::resolver::query query (host, to_string(port));
tcp::resolver::iterator it (resolver.resolve(query));
auto ep = new tcp::endpoint (*it);
socket->connect(*ep);
return socket;
}
void send_message (tcp::socket* socket, eclipse::messages::Message* msg) {
string out = save_message(msg);
stringstream ss;
ss << setfill('0') << setw(16) << out.length() << out;
socket->send(boost::asio::buffer(ss.str()));
}
eclipse::messages::FileList* read_reply(tcp::socket* socket) {
char header[16];
socket->receive(boost::asio::buffer(header));
size_t size_of_msg = atoi(header);
char* body = new char[size_of_msg];
socket->receive(boost::asio::buffer(body, size_of_msg));
string recv_msg(body);
eclipse::messages::Message* m = load_message(recv_msg);
return dynamic_cast<eclipse::messages::FileList*>(m);
}
int main(int argc, char* argv[])
{
Context con;
const int NUM_SERVERS = con.settings.get<vector<string>>("network.nodes").size();
vector<string> nodes = con.settings.get<vector<string>>("network.nodes");
vector<FileInfo> total;
for(int net_id=0; net_id<NUM_SERVERS; net_id++)
{
FileList file_list;
tcp::socket* socket = connect(net_id);
send_message(socket, &file_list);
auto file_list_reply = read_reply(socket);
socket->close();
std::copy(file_list_reply->data.begin(), file_list_reply->data.end(), back_inserter(total));
delete file_list_reply;
}
std::sort(total.begin(), total.end(), [] (const FileInfo& a, const FileInfo& b) {
return (a.file_name < b.file_name);
});
cout
<< setw(14) << "FileName"
<< setw(14) << "Hash Key"
<< setw(14) << "Size"
<< setw(14) << "NumBlocks"
<< setw(14) << "Host"
<< setw(14) << "Replicas"
<< endl << string(14*6,'-') << endl;
for (auto& fl: total) {
cout
<< setw(14) << fl.file_name
<< setw(14) << fl.file_hash_key
<< setw(14) << fl.file_size
<< setw(14) << fl.num_block
<< setw(14) << nodes[h(fl.file_name) % NUM_SERVERS]
<< setw(14) << fl.replica
<< endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Endless Mobile
*
* 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.
*
* Written by:
* Jasper St. Pierre <jstpierre@mecheye.net>
*/
#include "function.h"
#include "value.h"
#include "gobject.h"
using namespace v8;
namespace GNodeJS {
struct FunctionInfo {
GIFunctionInfo *info;
};
static Handle<Value> FunctionInvoker(const Arguments &args) {
HandleScope scope;
FunctionInfo *func = (FunctionInfo *) External::Unwrap (args.Data ());
GIBaseInfo *info = func->info;
GIFunctionInfo *function_info = (GIFunctionInfo *) info;
GError *error = NULL;
/* XXX: For now, only work on functions without any OUT args at all.
* Just assume everything is an in arg. */
int n_in_args = g_callable_info_get_n_args ((GICallableInfo *) info);
int n_total_args = n_in_args;
if (args.Length() < n_in_args) {
ThrowException (Exception::TypeError (String::New ("Not enough arguments.")));
return scope.Close (Undefined ());
}
gboolean is_method = ((g_function_info_get_flags (info) & GI_FUNCTION_IS_METHOD) != 0 &&
(g_function_info_get_flags (info) & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
if (is_method)
n_total_args++;
GIArgument total_args[n_total_args];
GIArgument *in_args;
if (is_method) {
total_args[0].v_pointer = GObjectFromWrapper (args.This ());
in_args = &total_args[1];
} else {
in_args = &total_args[0];
}
for (int i = 0; i < n_in_args; i++) {
GIArgInfo *arg_info = g_callable_info_get_arg ((GICallableInfo *) info, i);
GITypeInfo type_info;
bool may_be_null = g_arg_info_may_be_null (arg_info);
g_arg_info_load_type (arg_info, &type_info);
V8ToGIArgument (&type_info, &in_args[i], args[i], may_be_null);
g_base_info_unref ((GIBaseInfo *) arg_info);
}
GIArgument return_value;
g_function_info_invoke (function_info,
total_args, n_total_args,
NULL, 0,
&return_value,
&error);
for (int i = 0; i < n_in_args; i++) {
GIArgInfo *arg_info = g_callable_info_get_arg ((GICallableInfo *) info, i);
GITypeInfo type_info;
g_arg_info_load_type (arg_info, &type_info);
FreeGIArgument (&type_info, &in_args[i]);
g_base_info_unref ((GIBaseInfo *) arg_info);
}
if (error) {
ThrowException (Exception::TypeError (String::New (error->message)));
return scope.Close (Undefined ());
}
GITypeInfo return_value_type;
g_callable_info_load_return_type ((GICallableInfo *) info, &return_value_type);
return scope.Close (GIArgumentToV8 (&return_value_type, &return_value));
}
static void FunctionDestroyed(Persistent<Value> object, void *data) {
FunctionInfo *func = (FunctionInfo *) data;
g_base_info_unref (func->info);
g_free (func);
}
Handle<Function> MakeFunction(GIBaseInfo *info) {
FunctionInfo *func = g_new0 (FunctionInfo, 1);
func->info = g_base_info_ref (info);
Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (FunctionInvoker, External::Wrap (func)));
tpl.MakeWeak (func, FunctionDestroyed);
Local<Function> fn = tpl->GetFunction ();
const char *function_name = g_base_info_get_name (info);
fn->SetName (String::NewSymbol (function_name));
return fn;
}
};
<commit_msg>function: Add more support for out pointers<commit_after>/*
* Copyright (C) 2014 Endless Mobile
*
* 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.
*
* Written by:
* Jasper St. Pierre <jstpierre@mecheye.net>
*/
#include "function.h"
#include "value.h"
#include "gobject.h"
#include <girffi.h>
using namespace v8;
namespace GNodeJS {
struct FunctionInfo {
GIFunctionInfo *info;
GIFunctionInvoker invoker;
};
static Handle<Value> FunctionInvoker(const Arguments &args) {
HandleScope scope;
FunctionInfo *func = (FunctionInfo *) External::Unwrap (args.Data ());
GIBaseInfo *info = func->info;
GError *error = NULL;
int n_callable_args = g_callable_info_get_n_args ((GICallableInfo *) info);
int n_total_args = n_callable_args;
int n_in_args = 0;
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
if (g_arg_info_get_direction (&arg_info) == GI_DIRECTION_IN ||
g_arg_info_get_direction (&arg_info) == GI_DIRECTION_INOUT)
n_in_args++;
}
if (args.Length() < n_in_args) {
ThrowException (Exception::TypeError (String::New ("Not enough arguments.")));
return scope.Close (Undefined ());
}
gboolean is_method = ((g_function_info_get_flags (info) & GI_FUNCTION_IS_METHOD) != 0 &&
(g_function_info_get_flags (info) & GI_FUNCTION_IS_CONSTRUCTOR) == 0);
if (is_method)
n_total_args++;
GIArgument total_arg_values[n_total_args];
GIArgument *callable_arg_values;
if (is_method) {
total_arg_values[0].v_pointer = GObjectFromWrapper (args.This ());
callable_arg_values = &total_arg_values[1];
} else {
callable_arg_values = &total_arg_values[0];
}
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info = {};
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
GIDirection direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) {
if (g_arg_info_is_caller_allocates (&arg_info)) {
assert (0);
} else {
callable_arg_values[i].v_pointer = NULL;
}
} else {
bool may_be_null = g_arg_info_may_be_null (&arg_info);
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
V8ToGIArgument (&type_info, &callable_arg_values[i], args[i], may_be_null);
}
}
void *ffi_arg_pointers[n_total_args];
for (int i = 0; i < n_total_args; i++)
ffi_arg_pointers[i] = &total_arg_values[i];
GIArgument return_value;
ffi_call (&func->invoker.cif, FFI_FN (func->invoker.native_address),
&return_value, ffi_arg_pointers);
for (int i = 0; i < n_callable_args; i++) {
GIArgInfo arg_info;
g_callable_info_load_arg ((GICallableInfo *) info, i, &arg_info);
GIDirection direction = g_arg_info_get_direction (&arg_info);
if (direction == GI_DIRECTION_OUT) {
/* XXX: Process out value. */
} else {
GITypeInfo type_info;
g_arg_info_load_type (&arg_info, &type_info);
FreeGIArgument (&type_info, &callable_arg_values[i]);
}
}
if (error) {
ThrowException (Exception::TypeError (String::New (error->message)));
return scope.Close (Undefined ());
}
GITypeInfo return_value_type;
g_callable_info_load_return_type ((GICallableInfo *) info, &return_value_type);
return scope.Close (GIArgumentToV8 (&return_value_type, &return_value));
}
static void FunctionDestroyed(Persistent<Value> object, void *data) {
FunctionInfo *func = (FunctionInfo *) data;
g_base_info_unref (func->info);
g_function_invoker_destroy(&func->invoker);
g_free (func);
}
Handle<Function> MakeFunction(GIBaseInfo *info) {
FunctionInfo *func = g_new0 (FunctionInfo, 1);
func->info = g_base_info_ref (info);
g_function_info_prep_invoker (func->info, &func->invoker, NULL);
Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New (FunctionTemplate::New (FunctionInvoker, External::Wrap (func)));
tpl.MakeWeak (func, FunctionDestroyed);
Local<Function> fn = tpl->GetFunction ();
const char *function_name = g_base_info_get_name (info);
fn->SetName (String::NewSymbol (function_name));
return fn;
}
};
<|endoftext|>
|
<commit_before>/*** Copyright (c), The Regents of the University of California ***
*** For more infophybunation please refer to files in the COPYRIGHT directory ***/
/*
* iphybun - The irods phybun utility
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "phybunUtil.hpp"
void usage();
int
main( int argc, char **argv ) {
int status;
rodsEnv myEnv;
rErrMsg_t errMsg;
rcComm_t *conn;
rodsArguments_t myRodsArgs;
char *optStr;
rodsPathInp_t rodsPathInp;
optStr = "hD:N:KR:S:s:"; // JMC - backport 4528, 4658, 4771
status = parseCmdLineOpt( argc, argv, optStr, 0, &myRodsArgs );
if ( status < 0 ) {
printf( "Use -h for help.\n" );
exit( 1 );
}
if ( myRodsArgs.help == True ) {
usage();
exit( 0 );
}
if ( argc - optind <= 0 ) {
rodsLog( LOG_ERROR, "iphybun: no input" );
printf( "Use -h for help.\n" );
exit( 2 );
}
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
exit( 1 );
}
status = parseCmdLinePath( argc, argv, optind, &myEnv,
UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
printf( "Use -h for help.\n" );
exit( 1 );
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::api_entry_table& api_tbl = irods::get_client_api_table();
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
init_api_table( api_tbl, pk_tbl );
conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 1, &errMsg );
if ( conn == NULL ) {
exit( 2 );
}
status = clientLogin( conn );
if ( status != 0 ) {
rcDisconnect( conn );
exit( 7 );
}
status = phybunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp );
printErrorStack( conn->rError );
rcDisconnect( conn );
if ( status < 0 ) {
exit( 3 );
}
else {
exit( 0 );
}
}
void
usage() {
char *msgs[] = {
"Usage : iphybun [-hK] [-D dataType] [-S srcResource] [-R resource] [-s maxSize_in_GB] [-N numOfSubFiles] collection ... ",
"iphybun allows system admin to physically bundle files in a collection into",
"a number of tar files to make it more efficient to store these files on tape.",
"The tar files are placed into the /myZone/bundle/.... collection with file",
"names - collection.aRandomNumber. A new tar file will be created whenever",
"the number of subfiles exceeds 5120 (default value or the value given by",
"the -N option) or the total size of the subfiles exceeds 4 GBytes (default value or the value given by",
"the -s option).",
"A replica is registered for each bundled sub-files with",
"a fictitious resource - 'bundleResc' and a physical file path pointing to",
"the logical path of the tar bundle file. Whenever this copy of the subfile",
"is accessed, the tar file is untarred and staged automatically to the ",
"'cache' resource. Each extracted file is registered as a replica of its",
"corresponding subfiles.",
" ",
"A tar bundle file can be replicated or trimmed independently from its",
"corresponding subfiles. But it cannot be renamed or moved to trash.",
"It can be removed with the 'irm -f' command. But this will trigger the ",
"staging of the subfiles before the tar file is removed.",
"The -R flag specifies the resource of the bundle tar file. This input is",
"mandatory. The input resource must be a 'cache' type resource."
"Options are:",
" -D dataType - the target struct file dataType. Valid dataTypes are -",
" t|tar|'tar file' for tar file, g|gzip|gzipTar for gziped tar file,",
" b|bzip2|bzip2Tar for bzip2 file, and z|zip|zipFile for archive using",
" 'zip'. If -D is not specified, the default is a tar file type",
" -N numOfSubFiles - maximum number of subfiles that are contained in the",
" tar file. If this option is not given, the default value will be 5120.",
" Note that if this number is too high, it can cause some significant",
" overhead for operations like retrieving a single file within a tar file",
" (stage, untar and register in iRODS lots of files).",
" -R resource - The resource where the bundle file is located",
" -S srcResource - Only files in this resource will be bundled",
" -K compute and register checksum value for the bundled subfiles and the",
" bundle file.",
" -s maxSize_in_GB - maximum size for the tar bundle file. This is given ",
" in GB. If the option is not given, the default value will be 4 GBs.",
" -h this help",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "iphybun" );
}
<commit_msg>[#2212] CID26065:<commit_after>/*** Copyright (c), The Regents of the University of California ***
*** For more infophybunation please refer to files in the COPYRIGHT directory ***/
/*
* iphybun - The irods phybun utility
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rodsClient.hpp"
#include "parseCommandLine.hpp"
#include "rodsPath.hpp"
#include "phybunUtil.hpp"
void usage();
int
main( int argc, char **argv ) {
int status;
rodsEnv myEnv;
rErrMsg_t errMsg;
rcComm_t *conn;
rodsArguments_t myRodsArgs;
char *optStr;
rodsPathInp_t rodsPathInp;
optStr = "hD:N:KR:S:s:"; // JMC - backport 4528, 4658, 4771
status = parseCmdLineOpt( argc, argv, optStr, 0, &myRodsArgs );
if ( status < 0 ) {
printf( "Use -h for help.\n" );
exit( 1 );
}
if ( myRodsArgs.help == True ) {
usage();
exit( 0 );
}
if ( argc - optind <= 0 ) {
rodsLog( LOG_ERROR, "iphybun: no input" );
printf( "Use -h for help.\n" );
exit( 2 );
}
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: getRodsEnv error. " );
exit( 1 );
}
status = parseCmdLinePath( argc, argv, optind, &myEnv,
UNKNOWN_OBJ_T, NO_INPUT_T, 0, &rodsPathInp );
if ( status < 0 ) {
rodsLogError( LOG_ERROR, status, "main: parseCmdLinePath error. " );
printf( "Use -h for help.\n" );
exit( 1 );
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::api_entry_table& api_tbl = irods::get_client_api_table();
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
init_api_table( api_tbl, pk_tbl );
conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 1, &errMsg );
if ( conn == NULL ) {
exit( 2 );
}
status = clientLogin( conn );
if ( status != 0 ) {
rcDisconnect( conn );
exit( 7 );
}
status = phybunUtil( conn, &myEnv, &myRodsArgs, &rodsPathInp );
printErrorStack( conn->rError );
rcDisconnect( conn );
if ( status < 0 ) {
exit( 3 );
}
else {
exit( 0 );
}
}
void
usage() {
char *msgs[] = {
"Usage : iphybun [-hK] [-D dataType] [-S srcResource] [-R resource] [-s maxSize_in_GB] [-N numOfSubFiles] collection ... ",
"iphybun allows system admin to physically bundle files in a collection into",
"a number of tar files to make it more efficient to store these files on tape.",
"The tar files are placed into the /myZone/bundle/.... collection with file",
"names - collection.aRandomNumber. A new tar file will be created whenever",
"the number of subfiles exceeds 5120 (default value or the value given by",
"the -N option) or the total size of the subfiles exceeds 4 GBytes (default value or the value given by",
"the -s option).",
"A replica is registered for each bundled sub-files with",
"a fictitious resource - 'bundleResc' and a physical file path pointing to",
"the logical path of the tar bundle file. Whenever this copy of the subfile",
"is accessed, the tar file is untarred and staged automatically to the ",
"'cache' resource. Each extracted file is registered as a replica of its",
"corresponding subfiles.",
"",
"A tar bundle file can be replicated or trimmed independently from its",
"corresponding subfiles. But it cannot be renamed or moved to trash.",
"It can be removed with the 'irm -f' command. But this will trigger the ",
"staging of the subfiles before the tar file is removed.",
"The -R flag specifies the resource of the bundle tar file. This input is",
"mandatory. The input resource must be a 'cache' type resource.",
"",
"Options are:",
" -D dataType - the target struct file dataType. Valid dataTypes are -",
" t|tar|'tar file' for tar file, g|gzip|gzipTar for gziped tar file,",
" b|bzip2|bzip2Tar for bzip2 file, and z|zip|zipFile for archive using",
" 'zip'. If -D is not specified, the default is a tar file type",
" -N numOfSubFiles - maximum number of subfiles that are contained in the",
" tar file. If this option is not given, the default value will be 5120.",
" Note that if this number is too high, it can cause some significant",
" overhead for operations like retrieving a single file within a tar file",
" (stage, untar and register in iRODS lots of files).",
" -R resource - The resource where the bundle file is located",
" -S srcResource - Only files in this resource will be bundled",
" -K compute and register checksum value for the bundled subfiles and the",
" bundle file.",
" -s maxSize_in_GB - maximum size for the tar bundle file. This is given ",
" in GB. If the option is not given, the default value will be 4 GBs.",
" -h this help",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "iphybun" );
}
<|endoftext|>
|
<commit_before>#include "threads.h"
#include "assert.h"
#if defined(_MSC_VER)
ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
ThreadID id ={};
id.handle = CreateThread(NULL, 0, func, arg, 0, &id.threadId);
return id;
}
void JoinThread(ThreadID thread){
WaitForSingleObject(thread.handle, INFINITE);
}
void CreateMutex(Mutex* mutx){
mutx->handle = CreateMutex(NULL, false, NULL);
}
void LockMutex(Mutex* mutx){
WaitForSingleObject(mutx->handle, INFINITE);
}
void UnlockMutex(Mutex* mutx){
ReleaseMutex(mutx->handle);
}
void DestroyMutex(Mutex* mutx){
CloseHandle(mutx->handle);
mutx->handle = 0;
}
unsigned int IncrementAtomic32(volatile unsigned int* i){
return InterlockedIncrement(i);
}
int AddAtomic32(volatile int* i, int val){
return InterlockedAdd((volatile LONG*)i, val);
}
static_assert(sizeof(LONG) == sizeof(int), "MSVC, why...");
int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
return InterlockedCompareExchange((volatile LONG*)i, oldVal, newVal);
}
#elif defined(__APPLE__)
// Apple specific stuff
#else
ThreadID CreateThreadSimple(ThreadFunc* func, void* arg){
ThreadID tid = {};
int err = pthread_create(&tid.id, NULL, func, arg);
return tid;
}
void JoinThread(ThreadID thread){
pthread_join(thread.id, NULL);
}
void CreateMutex(Mutex* mutx){
pthread_mutex_init(&mutx->mutx, NULL);
}
void LockMutex(Mutex* mutx){
pthread_mutex_lock(&mutx->mutx);
}
void UnlockMutex(Mutex* mutx){
pthread_mutex_unlock(&mutx->mutx);
}
void DestroyMutex(Mutex* mutx){
pthread_mutex_destroy(&mutx->mutx, NULL);
}
int IncrementAtomic32(volatile int* i){
}
int AddAtomic32(volatile int* i, int val){
}
int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
}
#endif
#if defined(THREADS_TEST_MAIN)
int val1 = 0;
int val2 = 0;
THREAD_RET_TYPE ThreadFunc1(void* arg){
int val = (int)arg;
val1 = val;
return 0;
}
THREAD_RET_TYPE ThreadFunc2(void* arg){
int val = (int)arg;
val2 = val;
return 0;
}
static const int counterSize = 1024*32;
unsigned int counter = 0;
THREAD_RET_TYPE ThreadCounterFunc(void* arg){
for (int i = 0; i < counterSize; i++){
IncrementAtomic32(&counter);
}
return 0;
}
int main(){
ASSERT(val1 == 0);
ASSERT(val2 == 0);
ThreadID id1 = CreateThreadSimple(ThreadFunc1, (void*)4);
ThreadID id2 = CreateThreadSimple(ThreadFunc2, (void*)7);
JoinThread(id1);
JoinThread(id2);
ASSERT(val1 == 4);
ASSERT(val2 == 7);
ASSERT(counter == 0);
ThreadID tids[] =
{
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL)
};
for (int i = 0; i < BNS_ARRAY_COUNT(tids); i++){
JoinThread(tids[i]);
}
ASSERT(counter == counterSize * BNS_ARRAY_COUNT(tids));
return 0;
}
#endif
<commit_msg>Threads in linux.<commit_after>#include "threads.h"
#include "assert.h"
#if defined(_MSC_VER)
ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
ThreadID id ={};
id.handle = CreateThread(NULL, 0, func, arg, 0, &id.threadId);
return id;
}
void JoinThread(ThreadID thread){
WaitForSingleObject(thread.handle, INFINITE);
}
void CreateMutex(Mutex* mutx){
mutx->handle = CreateMutex(NULL, false, NULL);
}
void LockMutex(Mutex* mutx){
WaitForSingleObject(mutx->handle, INFINITE);
}
void UnlockMutex(Mutex* mutx){
ReleaseMutex(mutx->handle);
}
void DestroyMutex(Mutex* mutx){
CloseHandle(mutx->handle);
mutx->handle = 0;
}
unsigned int IncrementAtomic32(volatile unsigned int* i){
return InterlockedIncrement(i);
}
int AddAtomic32(volatile int* i, int val){
return InterlockedAdd((volatile LONG*)i, val);
}
static_assert(sizeof(LONG) == sizeof(int), "MSVC, why...");
int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
return InterlockedCompareExchange((volatile LONG*)i, oldVal, newVal);
}
#elif defined(__APPLE__)
// Apple specific stuff
#else
ThreadID CreateThreadSimple(ThreadFunc func, void* arg){
ThreadID tid = {};
int err = pthread_create(&tid.id, NULL, func, arg);
return tid;
}
void JoinThread(ThreadID thread){
pthread_join(thread.id, NULL);
}
void CreateMutex(Mutex* mutx){
pthread_mutex_init(&mutx->mutx, NULL);
}
void LockMutex(Mutex* mutx){
pthread_mutex_lock(&mutx->mutx);
}
void UnlockMutex(Mutex* mutx){
pthread_mutex_unlock(&mutx->mutx);
}
void DestroyMutex(Mutex* mutx){
pthread_mutex_destroy(&mutx->mutx);
}
unsigned int IncrementAtomic32(volatile unsigned int* i){
return __sync_fetch_and_add(i, 1);
}
int AddAtomic32(volatile int* i, int val){
return __sync_fetch_and_add(i, val);
}
int CompareAndSwap32(volatile int* i, int oldVal, int newVal){
return __sync_val_compare_and_swap(i, oldVal, newVal);
}
#endif
#if defined(THREADS_TEST_MAIN)
int val1 = 0;
int val2 = 0;
THREAD_RET_TYPE ThreadFunc1(void* arg){
int val = (int)(size_t)arg;
val1 = val;
return 0;
}
THREAD_RET_TYPE ThreadFunc2(void* arg){
int val = (int)(size_t)arg;
val2 = val;
return 0;
}
static const int counterSize = 1024*32;
unsigned int counter = 0;
THREAD_RET_TYPE ThreadCounterFunc(void* arg){
for (int i = 0; i < counterSize; i++){
IncrementAtomic32(&counter);
}
return 0;
}
int main(){
ASSERT(val1 == 0);
ASSERT(val2 == 0);
ThreadID id1 = CreateThreadSimple(ThreadFunc1, (void*)4);
ThreadID id2 = CreateThreadSimple(ThreadFunc2, (void*)7);
JoinThread(id1);
JoinThread(id2);
ASSERT(val1 == 4);
ASSERT(val2 == 7);
ASSERT(counter == 0);
ThreadID tids[] =
{
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL),
CreateThreadSimple(ThreadCounterFunc, NULL)
};
for (int i = 0; i < BNS_ARRAY_COUNT(tids); i++){
JoinThread(tids[i]);
}
ASSERT(counter == counterSize * BNS_ARRAY_COUNT(tids));
return 0;
}
#endif
<|endoftext|>
|
<commit_before>#ifndef BITOPS_HH
#define BITOPS_HH
#include <limits>
#include <type_traits>
#include <cstdint>
#include <climits>
namespace std {
///////////////////////////
//Basic bitwise operations
///////////////////////////
//Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
template <typename T> constexpr int ctz(T t) noexcept = delete;
template <> constexpr int ctz(unsigned int t) noexcept {
return __builtin_ctz(t);
}
template <> constexpr int ctz(unsigned long t) noexcept {
return __builtin_ctzl(t);
}
template <> constexpr int ctz(unsigned long long t) noexcept {
return __builtin_ctzll(t);
}
template <> constexpr int ctz(unsigned char t) noexcept {
return ctz<unsigned int>(t);
}
template <> constexpr int ctz(unsigned short t) noexcept {
return ctz<unsigned int>(t);
}
//Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
template <typename T> constexpr int clz(T t) noexcept = delete;
template <> constexpr int clz(unsigned int t) noexcept {
return __builtin_clz(t);
}
template <> constexpr int clz(unsigned long t) noexcept {
return __builtin_clzl(t);
}
template <> constexpr int clz(unsigned long long t) noexcept {
return __builtin_clzll(t);
}
template <> constexpr int clz(unsigned char t) noexcept {
return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
template <> constexpr int clz(unsigned short t) noexcept {
return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
//Return position of the first bit set in t.
template <typename T> constexpr int ffs(T t) noexcept = delete;
template <> constexpr int ffs(unsigned int t) noexcept {
return __builtin_ffs(t);
}
template <> constexpr int ffs(unsigned long t) noexcept {
return __builtin_ffsl(t);
}
template <> constexpr int ffs(unsigned long long t) noexcept {
return __builtin_ffsll(t);
}
template <> constexpr int ffs(unsigned char t) noexcept {
return ffs<unsigned int>(t);
}
template <> constexpr int ffs(unsigned short t) noexcept {
return ffs<unsigned int>(t);
}
//Returns position of the last bit set in t
template <typename T> constexpr int fls(T t) noexcept {
static_assert(std::is_unsigned<T>::value, "T must be unsigned!");
return (sizeof(t) * CHAR_BIT) - clz(t);
}
//Returns the number of leading redundant sign bits in x, i.e. the number of bits following the most significant bit that are identical to it. There are no special cases for 0 or other values
template <typename T> constexpr int clrsb(T t) noexcept = delete;
template <> constexpr int clrsb(unsigned int t) noexcept {
return __builtin_clrsb(t);
}
template <> constexpr int clrsb(unsigned long t) noexcept {
return __builtin_clrsbl(t);
}
template <> constexpr int clrsb(unsigned long long t) noexcept {
return __builtin_clrsbll(t);
}
template <> constexpr int clrsb(unsigned char t) noexcept {
return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
template <> constexpr int clrsb(unsigned short t) noexcept {
return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
//Returns the number of 1-bits in x.
template <typename T> constexpr int popcount(T t) noexcept = delete;
template <> constexpr int popcount(unsigned int t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned long t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned long long t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned char t) noexcept {
return popcount<unsigned int>(t);
}
template <> constexpr int popcount(unsigned short t) noexcept {
return popcount<unsigned int>(t);
}
//Returns the parity of x, i.e. the number of 1-bits in x modulo 2.
template <typename T> constexpr int parity(T t) noexcept = delete;
template <> constexpr int parity(unsigned int t) noexcept {
return __builtin_parity(t);
}
template <> constexpr int parity(unsigned long t) noexcept {
return __builtin_parityl(t);
}
template <> constexpr int parity(unsigned long long t) noexcept {
return __builtin_parityll(t);
}
template <> constexpr int parity(unsigned char t) noexcept {
return parity<unsigned int>(t);
}
template <> constexpr int parity(unsigned short t) noexcept {
return parity<unsigned int>(t);
}
///////////////////////////
//Explicit bit shifts
///////////////////////////
//logical shift left
template <typename T>
constexpr auto shl(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t << s;
}
//logical shift right
template <typename T>
constexpr auto shr(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
//For unsigned types, built in right shift is guaranteed to be logical
return t >> s;
}
//logical shift, left if s < 0, otherwise right
template <typename T>
constexpr auto sh(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? shl(t, -s) : shr(t, s);
}
//left shift arithmetic
template <typename T>
constexpr auto sal(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
//Same as logical shift
return shl(t, s);
}
//right shift arithmetic. This implementation assumes right shift on signed types is arithmetic but this cannot be assumed in general
template <typename T>
constexpr auto sar(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return static_cast<typename make_signed<T>::type>(t) >> s;
}
//arithmetic shift, left if s < 0, otherwise right
template <typename T>
constexpr auto sa(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? sal(t, -s) : sar(t, s);
}
//Left rotate shift
template <typename T>
constexpr auto rotl(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return shl(t, s) | shr(t, (sizeof(t) * CHAR_BIT) - s);
}
//Right rotate shift
template <typename T>
constexpr auto rotr(T t, unsigned int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return shr(t, s) | shl(t, (sizeof(t) * CHAR_BIT) - s);
}
//rotate shift, left if s < 0, otherwise right
template <typename T>
constexpr auto rot(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? rotl(t, -s) : rotr(t, s);
}
///////////////////////////
//Alignment manipulation
///////////////////////////
//Returns the smallest number n when n >= val && is_aligned(n, align). align must be a power of 2!
//Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t?
template <typename T>
constexpr T align_up(T val, size_t a) noexcept {
return ((val + (a -1)) & -a);
}
//Returns the largest number n when n <= val && is_aligned(n, align). align must be a power of 2!
//Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t?
template <typename T>
constexpr T align_down(T val, size_t a) noexcept {
return val & -a;
}
//Returns true if t is aligned to a
//Question: Provide a version of this for char* pointers? Or require user to cast to uint_ptr_t?
template <typename T>
constexpr bool is_aligned(T t, size_t a) noexcept {
return ((t & (a-1)) == 0);
}
///////////////////////////
//Power of 2 manipulation
///////////////////////////
//Returns true if t == 0 or t is a power of 2
template <typename T> constexpr bool is_pow2_or_zero(T t) noexcept {
static_assert(is_unsigned<T>::value, "T must be an unsigned type!");
return (t & (t-1)) == 0;
}
//Returns true if t is a power of 2
template <typename T> constexpr bool is_pow2(T t) noexcept {
static_assert(is_unsigned<T>::value, "T must be an unsigned type!");
return (t != 0) && is_pow2_or_zero(t);
}
//Return smallest power of 2 >= t
template <typename T>
constexpr T pow2_ge(T t) noexcept {
static_assert(is_unsigned<T>::value, "T must be an unsigned type!");
return is_pow2(t) ? t : pow2_gt(t);
}
//Return smallest power of 2 > t
template <typename T> constexpr T pow2_gt(T t) noexcept;
//Return smallest power of 2 <= t
template <typename T>
constexpr T pow2_le(T t) noexcept {
return is_pow2(t) ? t : pow2_lt(t);
}
//Return smallest power of 2 < t
template <typename T>
constexpr T pow2_lt(T t) noexcept;
///////////////////////////
//Setting/Resetting bits
///////////////////////////
//Sets bit b of t, no effect if b >= number of bits in t
template <typename T>
constexpr T set_bit(T t, unsigned int b) noexcept {
return t | (1 << b);
}
//Set all bits in t >= b
template <typename T>
constexpr T set_bits_gt(T t, unsigned int b) noexcept {
return t | ~((1 << (b+1)) -1);
}
//Set all bits in t > b
template <typename T>
constexpr T set_bits_ge(T t, unsigned int b) noexcept {
return t | ~((1 << b) -1);
}
//Set all bits in t <= b
template <typename T>
constexpr T set_bits_le(T t, unsigned int b) noexcept {
return t | ((1 << (b+1)) -1);
}
//Set all bits in t < b
template <typename T>
constexpr T set_bits_lt(T t, unsigned int b) noexcept {
return t | ((1 << b) -1);
}
//Resets bit b of t, no effect if b >= number of bits in t
template <typename T>
constexpr T reset_bit(T t, unsigned int b) noexcept {
return t & ~(1 << b);
}
//Reset all bits in t >= b
template <typename T>
constexpr T reset_bits_gt(T t, unsigned int b) noexcept ;
//Reset all bits in t > b
template <typename T>
constexpr T reset_bits_ge(T t, unsigned int b) noexcept ;
//Reset all bits in t <= b
template <typename T>
constexpr T reset_bits_le(T t, unsigned int b) noexcept ;
//Reset all bits in t < b
template <typename T>
constexpr T reset_bits_lt(T t, unsigned int b) noexcept ;
//Resets the least significant bit set
template <typename T>
constexpr T reset_lsb(T t) noexcept {
return t & (t -1);
}
//Resets the most significant bit set
template <typename T>
constexpr T reset_msb(T t);
////////////////////////
//Saturated Arithmetic
////////////////////////
//Saturated addition, like normal addition except on overflow the result will be the maximum value for decltype(L + R).
template <typename L, typename R>
constexpr auto sat_add(L l, R r) -> decltype(l+r) {
typedef decltype(l+r) LR;
return static_cast<LR>(l) > numeric_limits<LR>::max() - static_cast<LR>(r) ?
numeric_limits<LR>::max() : l + r;
}
//Saturated subtraction, like normal subtraction except on overflow the result will be the minimum value for decltype(L - R).
template <typename L, typename R>
constexpr auto sat_sub(L l, R r) -> decltype(l-r) {
typedef decltype(l-r) LR;
return static_cast<LR>(l) < numeric_limits<LR>::min() + static_cast<LR>(r) ?
numeric_limits<LR>::min() : l - r;
}
////////////////////////
//Misc
////////////////////////
//Reverses all of the bits in t
template <typename T>
constexpr T reverse_bits(T t) noexcept ;
//Returns a value whos even bits are set to the even bits of even, and odd bits set to the odd bits of odd.
template <typename T>
constexpr T interleave_bits(T even, T odd);
//Swaps the nibbles (4 bits) of the given byte
constexpr uint8_t swap_nibbles(uint8_t byte) {
return (byte >> 4) | (byte << 4);
}
} //namespace std
#endif
<commit_msg>use int for shift amounts. Implement more functions.<commit_after>#ifndef BITOPS_HH
#define BITOPS_HH
#include <limits>
#include <type_traits>
#include <cstdint>
#include <climits>
namespace std {
///////////////////////////
//Basic bitwise operations
///////////////////////////
//Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
template <typename T> constexpr int ctz(T t) noexcept = delete;
template <> constexpr int ctz(unsigned int t) noexcept {
return __builtin_ctz(t);
}
template <> constexpr int ctz(unsigned long t) noexcept {
return __builtin_ctzl(t);
}
template <> constexpr int ctz(unsigned long long t) noexcept {
return __builtin_ctzll(t);
}
template <> constexpr int ctz(unsigned char t) noexcept {
return ctz<unsigned int>(t);
}
template <> constexpr int ctz(unsigned short t) noexcept {
return ctz<unsigned int>(t);
}
//Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.
template <typename T> constexpr int clz(T t) noexcept = delete;
template <> constexpr int clz(unsigned int t) noexcept {
return __builtin_clz(t);
}
template <> constexpr int clz(unsigned long t) noexcept {
return __builtin_clzl(t);
}
template <> constexpr int clz(unsigned long long t) noexcept {
return __builtin_clzll(t);
}
template <> constexpr int clz(unsigned char t) noexcept {
return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
template <> constexpr int clz(unsigned short t) noexcept {
return clz<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
//Return position of the first bit set in t.
template <typename T> constexpr int ffs(T t) noexcept = delete;
template <> constexpr int ffs(unsigned int t) noexcept {
return __builtin_ffs(t);
}
template <> constexpr int ffs(unsigned long t) noexcept {
return __builtin_ffsl(t);
}
template <> constexpr int ffs(unsigned long long t) noexcept {
return __builtin_ffsll(t);
}
template <> constexpr int ffs(unsigned char t) noexcept {
return ffs<unsigned int>(t);
}
template <> constexpr int ffs(unsigned short t) noexcept {
return ffs<unsigned int>(t);
}
//Returns position of the last bit set in t
template <typename T> constexpr int fls(T t) noexcept {
static_assert(std::is_unsigned<T>::value, "T must be unsigned!");
return (sizeof(t) * CHAR_BIT) - clz(t);
}
//Returns the number of leading redundant sign bits in x, i.e. the number of bits following the most significant bit that are identical to it. There are no special cases for 0 or other values
template <typename T> constexpr int clrsb(T t) noexcept = delete;
template <> constexpr int clrsb(unsigned int t) noexcept {
return __builtin_clrsb(t);
}
template <> constexpr int clrsb(unsigned long t) noexcept {
return __builtin_clrsbl(t);
}
template <> constexpr int clrsb(unsigned long long t) noexcept {
return __builtin_clrsbll(t);
}
template <> constexpr int clrsb(unsigned char t) noexcept {
return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
template <> constexpr int clrsb(unsigned short t) noexcept {
return clrsb<unsigned int>(t) - ((sizeof(unsigned int) - sizeof(t)) * CHAR_BIT);
}
//Returns the number of 1-bits in x.
template <typename T> constexpr int popcount(T t) noexcept = delete;
template <> constexpr int popcount(unsigned int t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned long t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned long long t) noexcept {
return __builtin_popcount(t);
}
template <> constexpr int popcount(unsigned char t) noexcept {
return popcount<unsigned int>(t);
}
template <> constexpr int popcount(unsigned short t) noexcept {
return popcount<unsigned int>(t);
}
//Returns the parity of x, i.e. the number of 1-bits in x modulo 2.
template <typename T> constexpr int parity(T t) noexcept = delete;
template <> constexpr int parity(unsigned int t) noexcept {
return __builtin_parity(t);
}
template <> constexpr int parity(unsigned long t) noexcept {
return __builtin_parityl(t);
}
template <> constexpr int parity(unsigned long long t) noexcept {
return __builtin_parityll(t);
}
template <> constexpr int parity(unsigned char t) noexcept {
return parity<unsigned int>(t);
}
template <> constexpr int parity(unsigned short t) noexcept {
return parity<unsigned int>(t);
}
///////////////////////////
//Explicit bit shifts
///////////////////////////
//logical shift left
template <typename T>
constexpr auto shl(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t << s;
}
//logical shift right
template <typename T>
constexpr auto shr(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
//For unsigned types, built in right shift is guaranteed to be logical
return t >> s;
}
//logical shift, left if s < 0, otherwise right
template <typename T>
constexpr auto sh(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? shl(t, -s) : shr(t, s);
}
//left shift arithmetic
template <typename T>
constexpr auto sal(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
//Same as logical shift
return shl(t, s);
}
//right shift arithmetic.
template <typename T>
constexpr auto sar(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
//This implementation assumes right shift on signed types is arithmetic but this cannot be assumed in general
return static_cast<typename make_signed<T>::type>(t) >> s;
}
//arithmetic shift, left if s < 0, otherwise right
template <typename T>
constexpr auto sa(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? sal(t, -s) : sar(t, s);
}
//Left rotate shift
template <typename T>
constexpr auto rotl(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return shl(t, s) | shr(t, (sizeof(t) * CHAR_BIT) - s);
}
//Right rotate shift
template <typename T>
constexpr auto rotr(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return shr(t, s) | shl(t, (sizeof(t) * CHAR_BIT) - s);
}
//rotate shift, left if s < 0, otherwise right
template <typename T>
constexpr auto rot(T t, int s)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return s < 0 ? rotl(t, -s) : rotr(t, s);
}
///////////////////////////
//Alignment manipulation
///////////////////////////
//Returns the smallest number n when n >= val && is_aligned(n, align). align must be a power of 2!
template <typename T>
constexpr auto align_up(T val, size_t a)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return ((val + (a -1)) & -a);
}
constexpr void* align_up(void* val, size_t a) noexcept {
return (void*)align_up(uintptr_t(val), a);
}
//Returns the largest number n when n <= val && is_aligned(n, align). align must be a power of 2!
template <typename T>
constexpr auto align_down(T val, size_t a)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return val & -a;
}
constexpr void* align_down(void* val, size_t a) noexcept {
return (void*)align_down(uintptr_t(val), a);
}
//Returns true if t is aligned to a
template <typename T>
constexpr auto is_aligned(T t, size_t a)
noexcept -> typename std::enable_if<std::is_integral<T>::value,bool>::type {
return ((t & (a-1)) == 0);
}
constexpr bool is_aligned(void* t, size_t a) noexcept {
return is_aligned(uintptr_t(t), a);
}
///////////////////////////
//Power of 2 manipulation
///////////////////////////
//Returns true if t == 0 or t is a power of 2
template <typename T>
constexpr auto is_pow2_or_zero(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,bool>::type {
return (t & (t-1)) == 0;
}
//Returns true if t is a power of 2
template <typename T>
constexpr auto is_pow2(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,bool>::type {
return (t != 0) && is_pow2_or_zero(t);
}
//Return smallest power of 2 >= t
template <typename T>
constexpr auto pow2_ge(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return is_pow2(t) ? t : pow2_gt(t);
}
//Return smallest power of 2 > t
template <typename T>
constexpr auto pow2_gt(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return (T(1) << (fls(make_unsigned<T>::type(t)) +1));
}
//Return smallest power of 2 <= t
template <typename T>
constexpr auto pow2_le(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return is_pow2(t) ? t : pow2_lt(t);
}
//Return smallest power of 2 < t
template <typename T>
constexpr auto pow2_lt(T t)
noexcept -> typename std::enable_if<std::is_integral<T>::value,T>::type {
return T(1) << fls(make_unsigned<T>::type(t-1));
}
///////////////////////////
//Setting/Resetting bits
///////////////////////////
//Sets bit b of t, no effect if b >= number of bits in t
template <typename T>
constexpr auto set_bit(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t | (1 << b);
}
//Set all bits in t >= b
template <typename T>
constexpr auto set_bits_gt(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t | ~((1 << (b+1)) -1);
}
//Set all bits in t > b
template <typename T>
constexpr auto set_bits_ge(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t | ~((1 << b) -1);
}
//Set all bits in t <= b
template <typename T>
constexpr auto set_bits_le(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t | ((1 << (b+1)) -1);
}
//Set all bits in t < b
template <typename T>
constexpr auto set_bits_lt(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t | ((1 << b) -1);
}
//Resets bit b of t, no effect if b >= number of bits in t
template <typename T>
constexpr auto reset_bit(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ~(1 << b);
}
//Reset all bits in t >= b
template <typename T>
constexpr auto reset_bits_gt(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ~((T(1) << (b+1))-1);
}
//Reset all bits in t > b
template <typename T>
constexpr auto reset_bits_ge(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ~((T(1) << b)-1);
}
//Reset all bits in t <= b
template <typename T>
constexpr auto reset_bits_le(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ((T(1) << (b+1))-1);
}
//Reset all bits in t < b
template <typename T>
constexpr auto reset_bits_lt(T t, int b)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ((T(1) << b)-1);
}
//Resets the least significant bit set
template <typename T>
constexpr auto reset_lsb(T t)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & (t -1);
}
//Resets the most significant bit set
template <typename T>
constexpr auto reset_msb(T t)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type {
return t & ~(T(1) << ((sizeof(t)*8) - clz(t)-1));
}
////////////////////////
//Saturated Arithmetic
////////////////////////
//Saturated addition, like normal addition except on overflow the result will be the maximum value for decltype(L + R).
template <typename L, typename R>
constexpr auto sat_add(L l, R r)
noexcept -> typename std::enable_if<std::is_integral<L>::value && std::is_integral<R>::value,decltype(l+r)>::type {
typedef decltype(l+r) LR;
return static_cast<LR>(l) > numeric_limits<LR>::max() - static_cast<LR>(r) ?
numeric_limits<LR>::max() : l + r;
}
//Saturated subtraction, like normal subtraction except on overflow the result will be the minimum value for decltype(L - R).
template <typename L, typename R>
constexpr auto sat_sub(L l, R r)
noexcept -> typename std::enable_if<std::is_integral<L>::value && std::is_integral<R>::value,decltype(l-r)>::type {
typedef decltype(l-r) LR;
return static_cast<LR>(l) < numeric_limits<LR>::min() + static_cast<LR>(r) ?
numeric_limits<LR>::min() : l - r;
}
////////////////////////
//Misc
////////////////////////
//Reverses all of the bits in t
template <typename T>
constexpr auto reverse_bits(T t)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type;
//Returns a value whos even bits are set to the even bits of even, and odd bits set to the odd bits of odd.
template <typename T>
constexpr auto interleave_bits(T even, T odd)
noexcept -> typename std::enable_if<std::is_unsigned<T>::value,T>::type;
//Swaps the nibbles (4 bits) of the given byte
constexpr uint8_t swap_nibbles(uint8_t byte) {
return (byte >> 4) | (byte << 4);
}
} //namespace std
#endif
<|endoftext|>
|
<commit_before>#include "hornet/java.hh"
#include "hornet/system_error.hh"
#include "hornet/java.hh"
#include "hornet/zip.hh"
#include "hornet/vm.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstring>
#include <fcntl.h>
#include <cstdio>
namespace hornet {
bool verbose_class;
void loader::register_entry(std::string path)
{
struct stat st;
if (stat(path.c_str(), &st) < 0) {
fprintf(stderr, "warning: %s: %s\n", path.c_str(), strerror(errno));
return;
}
if (S_ISDIR(st.st_mode)) {
_entries.push_back(std::make_shared<classpath_dir>(path));
} else {
_entries.push_back(std::make_shared<jar>(path));
}
}
std::shared_ptr<klass> loader::load_class(std::string class_name)
{
std::replace(class_name.begin(), class_name.end(), '.', '/');
if (is_array_type_name(class_name)) {
auto elem_type_name = class_name.substr(1, std::string::npos);
auto elem_type = load_class(elem_type_name);
if (!elem_type) {
hornet::throw_exception(java_lang_NoClassDefFoundError);
return nullptr;
}
auto klass = std::make_shared<array_klass>(class_name, elem_type.get());
hornet::_jvm->register_class(klass);
return klass;
}
auto klass = hornet::_jvm->lookup_class(class_name);
if (klass) {
return klass;
}
klass = try_to_load_class(class_name);
if (!klass) {
hornet::throw_exception(java_lang_NoClassDefFoundError);
return nullptr;
}
if (!klass->verify()) {
throw_exception(java_lang_VerifyError);
return nullptr;
}
return klass;
}
std::shared_ptr<klass> loader::try_to_load_class(std::string class_name)
{
for (auto entry : _entries) {
auto klass = entry->load_class(class_name);
if (klass) {
return klass;
}
}
return nullptr;
}
classpath_dir::classpath_dir(std::string path)
: _path(path)
{
}
classpath_dir::~classpath_dir()
{
}
std::shared_ptr<klass> classpath_dir::load_class(std::string class_name)
{
char pathname[PATH_MAX];
snprintf(pathname, sizeof(pathname), "%s/%s.class", _path.c_str(), class_name.c_str());
auto klass = load_file(pathname);
if (verbose_class && klass) {
printf("[Loaded %s from file:%s]\n", class_name.c_str(), _path.c_str());
}
return klass;
}
std::shared_ptr<klass> classpath_dir::load_file(const char *pathname)
{
auto fd = open(pathname, O_RDONLY);
if (fd < 0) {
return nullptr;
}
struct stat st;
if (fstat(fd, &st) < 0) {
throw_system_error("fstat");
}
auto data = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (data == MAP_FAILED) {
throw_system_error("mmap");
}
auto file = class_file{data, static_cast<size_t>(st.st_size)};
auto klass = file.parse();
if (munmap(data, st.st_size) < 0) {
throw_system_error("munmap");
}
if (close(fd) < 0) {
throw_system_error("close");
}
return klass;
}
jar::jar(std::string filename)
: _filename{filename}
, _zip{zip_open(filename.c_str())}
{
if (verbose_class) {
printf("[Opened %s]\n", _filename.c_str());
}
}
jar::~jar()
{
if (verbose_class) {
printf("[Closed %s]\n", _filename.c_str());
}
zip_close(_zip);
}
std::shared_ptr<klass> jar::load_class(std::string class_name)
{
if (!_zip) {
return nullptr;
}
zip_entry *entry = zip_entry_find_class(_zip, class_name.c_str());
if (!entry) {
return nullptr;
}
char *data = (char*)zip_entry_data(_zip, entry);
auto file = class_file{data, static_cast<size_t>(entry->uncomp_size)};
auto klass = file.parse();
free(data);
if (verbose_class && klass) {
printf("[Loaded %s from %s]\n", class_name.c_str(), _filename.c_str());
}
return klass;
}
}
<commit_msg>java/loader: Fix class cache lookup for array types<commit_after>#include "hornet/java.hh"
#include "hornet/system_error.hh"
#include "hornet/java.hh"
#include "hornet/zip.hh"
#include "hornet/vm.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstring>
#include <fcntl.h>
#include <cstdio>
namespace hornet {
bool verbose_class;
void loader::register_entry(std::string path)
{
struct stat st;
if (stat(path.c_str(), &st) < 0) {
fprintf(stderr, "warning: %s: %s\n", path.c_str(), strerror(errno));
return;
}
if (S_ISDIR(st.st_mode)) {
_entries.push_back(std::make_shared<classpath_dir>(path));
} else {
_entries.push_back(std::make_shared<jar>(path));
}
}
std::shared_ptr<klass> loader::load_class(std::string class_name)
{
std::replace(class_name.begin(), class_name.end(), '.', '/');
auto klass = hornet::_jvm->lookup_class(class_name);
if (klass) {
return klass;
}
if (is_array_type_name(class_name)) {
auto elem_type_name = class_name.substr(1, std::string::npos);
auto elem_type = load_class(elem_type_name);
if (!elem_type) {
hornet::throw_exception(java_lang_NoClassDefFoundError);
return nullptr;
}
auto klass = std::make_shared<array_klass>(class_name, elem_type.get());
hornet::_jvm->register_class(klass);
return klass;
}
klass = try_to_load_class(class_name);
if (!klass) {
hornet::throw_exception(java_lang_NoClassDefFoundError);
return nullptr;
}
if (!klass->verify()) {
throw_exception(java_lang_VerifyError);
return nullptr;
}
return klass;
}
std::shared_ptr<klass> loader::try_to_load_class(std::string class_name)
{
for (auto entry : _entries) {
auto klass = entry->load_class(class_name);
if (klass) {
return klass;
}
}
return nullptr;
}
classpath_dir::classpath_dir(std::string path)
: _path(path)
{
}
classpath_dir::~classpath_dir()
{
}
std::shared_ptr<klass> classpath_dir::load_class(std::string class_name)
{
char pathname[PATH_MAX];
snprintf(pathname, sizeof(pathname), "%s/%s.class", _path.c_str(), class_name.c_str());
auto klass = load_file(pathname);
if (verbose_class && klass) {
printf("[Loaded %s from file:%s]\n", class_name.c_str(), _path.c_str());
}
return klass;
}
std::shared_ptr<klass> classpath_dir::load_file(const char *pathname)
{
auto fd = open(pathname, O_RDONLY);
if (fd < 0) {
return nullptr;
}
struct stat st;
if (fstat(fd, &st) < 0) {
throw_system_error("fstat");
}
auto data = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (data == MAP_FAILED) {
throw_system_error("mmap");
}
auto file = class_file{data, static_cast<size_t>(st.st_size)};
auto klass = file.parse();
if (munmap(data, st.st_size) < 0) {
throw_system_error("munmap");
}
if (close(fd) < 0) {
throw_system_error("close");
}
return klass;
}
jar::jar(std::string filename)
: _filename{filename}
, _zip{zip_open(filename.c_str())}
{
if (verbose_class) {
printf("[Opened %s]\n", _filename.c_str());
}
}
jar::~jar()
{
if (verbose_class) {
printf("[Closed %s]\n", _filename.c_str());
}
zip_close(_zip);
}
std::shared_ptr<klass> jar::load_class(std::string class_name)
{
if (!_zip) {
return nullptr;
}
zip_entry *entry = zip_entry_find_class(_zip, class_name.c_str());
if (!entry) {
return nullptr;
}
char *data = (char*)zip_entry_data(_zip, entry);
auto file = class_file{data, static_cast<size_t>(entry->uncomp_size)};
auto klass = file.parse();
free(data);
if (verbose_class && klass) {
printf("[Loaded %s from %s]\n", class_name.c_str(), _filename.c_str());
}
return klass;
}
}
<|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/test/testing_profile.h"
#include "build/build_config.h"
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/history/history_backend.h"
#include "chrome/common/chrome_constants.h"
#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
using base::Time;
namespace {
// Task used to make sure history has finished processing a request. Intended
// for use with BlockUntilHistoryProcessesPendingRequests.
class QuittingHistoryDBTask : public HistoryDBTask {
public:
QuittingHistoryDBTask() {}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) {
return true;
}
virtual void DoneRunOnMainThread() {
MessageLoop::current()->Quit();
}
private:
DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
};
// BookmarkLoadObserver is used when blocking until the BookmarkModel
// finishes loading. As soon as the BookmarkModel finishes loading the message
// loop is quit.
class BookmarkLoadObserver : public BookmarkModelObserver {
public:
BookmarkLoadObserver() {}
virtual void Loaded(BookmarkModel* model) {
MessageLoop::current()->Quit();
}
virtual void BookmarkNodeMoved(BookmarkModel* model,
const BookmarkNode* old_parent,
int old_index,
const BookmarkNode* new_parent,
int new_index) {}
virtual void BookmarkNodeAdded(BookmarkModel* model,
const BookmarkNode* parent,
int index) {}
virtual void BookmarkNodeRemoved(BookmarkModel* model,
const BookmarkNode* parent,
int old_index,
const BookmarkNode* node) {}
virtual void BookmarkNodeChanged(BookmarkModel* model,
const BookmarkNode* node) {}
virtual void BookmarkNodeChildrenReordered(BookmarkModel* model,
const BookmarkNode* node) {}
virtual void BookmarkNodeFavIconLoaded(BookmarkModel* model,
const BookmarkNode* node) {}
private:
DISALLOW_COPY_AND_ASSIGN(BookmarkLoadObserver);
};
} // namespace
TestingProfile::TestingProfile()
: start_time_(Time::Now()),
created_theme_provider_(false),
has_history_service_(false),
off_the_record_(false),
last_session_exited_cleanly_(true) {
PathService::Get(base::DIR_TEMP, &path_);
path_ = path_.Append(FILE_PATH_LITERAL("TestingProfilePath"));
file_util::Delete(path_, true);
file_util::CreateDirectory(path_);
}
TestingProfile::TestingProfile(int count)
: start_time_(Time::Now()),
has_history_service_(false),
off_the_record_(false),
last_session_exited_cleanly_(true) {
PathService::Get(base::DIR_TEMP, &path_);
path_ = path_.Append(FILE_PATH_LITERAL("TestingProfilePath"));
path_ = path_.AppendASCII(IntToString(count));
file_util::Delete(path_, true);
file_util::CreateDirectory(path_);
}
TestingProfile::~TestingProfile() {
DestroyHistoryService();
file_util::Delete(path_, true);
}
void TestingProfile::CreateHistoryService(bool delete_file) {
if (history_service_.get())
history_service_->Cleanup();
history_service_ = NULL;
if (delete_file) {
FilePath path = GetPath();
path = path.Append(chrome::kHistoryFilename);
file_util::Delete(path, false);
}
history_service_ = new HistoryService(this);
history_service_->Init(GetPath(), bookmark_bar_model_.get());
}
void TestingProfile::DestroyHistoryService() {
if (!history_service_.get())
return;
history_service_->NotifyRenderProcessHostDestruction(0);
history_service_->SetOnBackendDestroyTask(new MessageLoop::QuitTask);
history_service_->Cleanup();
history_service_ = NULL;
// Wait for the backend class to terminate before deleting the files and
// moving to the next test. Note: if this never terminates, somebody is
// probably leaking a reference to the history backend, so it never calls
// our destroy task.
MessageLoop::current()->Run();
// Make sure we don't have any event pending that could disrupt the next
// test.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask);
MessageLoop::current()->Run();
}
void TestingProfile::CreateBookmarkModel(bool delete_file) {
// Nuke the model first, that way we're sure it's done writing to disk.
bookmark_bar_model_.reset(NULL);
if (delete_file) {
FilePath path = GetPath();
path = path.Append(chrome::kBookmarksFileName);
file_util::Delete(path, false);
}
bookmark_bar_model_.reset(new BookmarkModel(this));
if (history_service_.get()) {
history_service_->history_backend_->bookmark_service_ =
bookmark_bar_model_.get();
history_service_->history_backend_->expirer_.bookmark_service_ =
bookmark_bar_model_.get();
}
bookmark_bar_model_->Load();
}
void TestingProfile::BlockUntilBookmarkModelLoaded() {
DCHECK(bookmark_bar_model_.get());
if (bookmark_bar_model_->IsLoaded())
return;
BookmarkLoadObserver observer;
bookmark_bar_model_->AddObserver(&observer);
MessageLoop::current()->Run();
bookmark_bar_model_->RemoveObserver(&observer);
DCHECK(bookmark_bar_model_->IsLoaded());
}
void TestingProfile::CreateTemplateURLModel() {
template_url_model_.reset(new TemplateURLModel(this));
}
void TestingProfile::UseThemeProvider(BrowserThemeProvider* theme_provider) {
theme_provider->Init(this);
created_theme_provider_ = true;
theme_provider_.reset(theme_provider);
}
void TestingProfile::InitThemes() {
if (!created_theme_provider_) {
#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
theme_provider_.reset(new GtkThemeProvider);
#else
theme_provider_.reset(new BrowserThemeProvider);
#endif
theme_provider_->Init(this);
created_theme_provider_ = true;
}
}
void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
DCHECK(history_service_.get());
DCHECK(MessageLoop::current());
CancelableRequestConsumer consumer;
history_service_->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
MessageLoop::current()->Run();
}
<commit_msg>Coverity: initialize created_theme_provider_ in the other constructor.<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/test/testing_profile.h"
#include "build/build_config.h"
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/history/history_backend.h"
#include "chrome/common/chrome_constants.h"
#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
using base::Time;
namespace {
// Task used to make sure history has finished processing a request. Intended
// for use with BlockUntilHistoryProcessesPendingRequests.
class QuittingHistoryDBTask : public HistoryDBTask {
public:
QuittingHistoryDBTask() {}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) {
return true;
}
virtual void DoneRunOnMainThread() {
MessageLoop::current()->Quit();
}
private:
DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
};
// BookmarkLoadObserver is used when blocking until the BookmarkModel
// finishes loading. As soon as the BookmarkModel finishes loading the message
// loop is quit.
class BookmarkLoadObserver : public BookmarkModelObserver {
public:
BookmarkLoadObserver() {}
virtual void Loaded(BookmarkModel* model) {
MessageLoop::current()->Quit();
}
virtual void BookmarkNodeMoved(BookmarkModel* model,
const BookmarkNode* old_parent,
int old_index,
const BookmarkNode* new_parent,
int new_index) {}
virtual void BookmarkNodeAdded(BookmarkModel* model,
const BookmarkNode* parent,
int index) {}
virtual void BookmarkNodeRemoved(BookmarkModel* model,
const BookmarkNode* parent,
int old_index,
const BookmarkNode* node) {}
virtual void BookmarkNodeChanged(BookmarkModel* model,
const BookmarkNode* node) {}
virtual void BookmarkNodeChildrenReordered(BookmarkModel* model,
const BookmarkNode* node) {}
virtual void BookmarkNodeFavIconLoaded(BookmarkModel* model,
const BookmarkNode* node) {}
private:
DISALLOW_COPY_AND_ASSIGN(BookmarkLoadObserver);
};
} // namespace
TestingProfile::TestingProfile()
: start_time_(Time::Now()),
created_theme_provider_(false),
has_history_service_(false),
off_the_record_(false),
last_session_exited_cleanly_(true) {
PathService::Get(base::DIR_TEMP, &path_);
path_ = path_.Append(FILE_PATH_LITERAL("TestingProfilePath"));
file_util::Delete(path_, true);
file_util::CreateDirectory(path_);
}
TestingProfile::TestingProfile(int count)
: start_time_(Time::Now()),
created_theme_provider_(false),
has_history_service_(false),
off_the_record_(false),
last_session_exited_cleanly_(true) {
PathService::Get(base::DIR_TEMP, &path_);
path_ = path_.Append(FILE_PATH_LITERAL("TestingProfilePath"));
path_ = path_.AppendASCII(IntToString(count));
file_util::Delete(path_, true);
file_util::CreateDirectory(path_);
}
TestingProfile::~TestingProfile() {
DestroyHistoryService();
file_util::Delete(path_, true);
}
void TestingProfile::CreateHistoryService(bool delete_file) {
if (history_service_.get())
history_service_->Cleanup();
history_service_ = NULL;
if (delete_file) {
FilePath path = GetPath();
path = path.Append(chrome::kHistoryFilename);
file_util::Delete(path, false);
}
history_service_ = new HistoryService(this);
history_service_->Init(GetPath(), bookmark_bar_model_.get());
}
void TestingProfile::DestroyHistoryService() {
if (!history_service_.get())
return;
history_service_->NotifyRenderProcessHostDestruction(0);
history_service_->SetOnBackendDestroyTask(new MessageLoop::QuitTask);
history_service_->Cleanup();
history_service_ = NULL;
// Wait for the backend class to terminate before deleting the files and
// moving to the next test. Note: if this never terminates, somebody is
// probably leaking a reference to the history backend, so it never calls
// our destroy task.
MessageLoop::current()->Run();
// Make sure we don't have any event pending that could disrupt the next
// test.
MessageLoop::current()->PostTask(FROM_HERE, new MessageLoop::QuitTask);
MessageLoop::current()->Run();
}
void TestingProfile::CreateBookmarkModel(bool delete_file) {
// Nuke the model first, that way we're sure it's done writing to disk.
bookmark_bar_model_.reset(NULL);
if (delete_file) {
FilePath path = GetPath();
path = path.Append(chrome::kBookmarksFileName);
file_util::Delete(path, false);
}
bookmark_bar_model_.reset(new BookmarkModel(this));
if (history_service_.get()) {
history_service_->history_backend_->bookmark_service_ =
bookmark_bar_model_.get();
history_service_->history_backend_->expirer_.bookmark_service_ =
bookmark_bar_model_.get();
}
bookmark_bar_model_->Load();
}
void TestingProfile::BlockUntilBookmarkModelLoaded() {
DCHECK(bookmark_bar_model_.get());
if (bookmark_bar_model_->IsLoaded())
return;
BookmarkLoadObserver observer;
bookmark_bar_model_->AddObserver(&observer);
MessageLoop::current()->Run();
bookmark_bar_model_->RemoveObserver(&observer);
DCHECK(bookmark_bar_model_->IsLoaded());
}
void TestingProfile::CreateTemplateURLModel() {
template_url_model_.reset(new TemplateURLModel(this));
}
void TestingProfile::UseThemeProvider(BrowserThemeProvider* theme_provider) {
theme_provider->Init(this);
created_theme_provider_ = true;
theme_provider_.reset(theme_provider);
}
void TestingProfile::InitThemes() {
if (!created_theme_provider_) {
#if defined(OS_LINUX) && !defined(TOOLKIT_VIEWS)
theme_provider_.reset(new GtkThemeProvider);
#else
theme_provider_.reset(new BrowserThemeProvider);
#endif
theme_provider_->Init(this);
created_theme_provider_ = true;
}
}
void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
DCHECK(history_service_.get());
DCHECK(MessageLoop::current());
CancelableRequestConsumer consumer;
history_service_->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
MessageLoop::current()->Run();
}
<|endoftext|>
|
<commit_before>/* * This file is part of meego-im-framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "glibdbusimserverproxy.h"
#include "minputcontext.h"
#include <QPoint>
#include <QRect>
#include <QString>
#include <QDataStream>
#include <QVariant>
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#include <unistd.h>
#include <sys/types.h>
namespace
{
const char * const DBusPath("/com/meego/inputmethod/uiserver1");
const char * const DBusInterface("com.meego.inputmethod.uiserver1");
const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus";
const int ConnectionRetryInterval(6*1000); // in ms
Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection)
{
return Maliit::DBusGLib::ConnectionRef(connection,
dbus_g_connection_unref);
}
}
GlibDBusIMServerProxy::GlibDBusIMServerProxy(GObject *inputContextAdaptor, const QString &icAdaptorPath)
: glibObjectProxy(NULL),
connection(),
inputContextAdaptor(inputContextAdaptor),
icAdaptorPath(icAdaptorPath),
active(true)
{
dbus_g_thread_init();
connectToDBus();
}
GlibDBusIMServerProxy::~GlibDBusIMServerProxy()
{
active = false;
foreach (DBusGProxyCall *callId, pendingResetCalls) {
dbus_g_proxy_cancel_call(glibObjectProxy, callId);
}
}
// Auxiliary connection handling.............................................
void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData)
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection();
}
void GlibDBusIMServerProxy::connectToDBus()
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
GError *error = NULL;
connection = toRef(dbus_g_connection_open(SocketPath, &error));
if (!connection) {
if (error) {
qWarning("MInputContext: unable to create D-Bus connection: %s", error->message);
g_error_free(error);
}
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
return;
}
glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface);
if (!glibObjectProxy) {
qWarning("MInputContext: unable to find the D-Bus service.");
connection.reset();
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
return;
}
g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline),
this);
dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor);
emit dbusConnected();
}
void GlibDBusIMServerProxy::onDisconnection()
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
glibObjectProxy = 0;
connection.reset();
emit dbusDisconnected();
if (active) {
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
}
}
void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId,
gpointer userData)
{
static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId);
}
void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId)
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID);
pendingResetCalls.remove(callId);
}
// Remote methods............................................................
void GlibDBusIMServerProxy::activateContext()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::showInputMethod()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::hideInputMethod()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit",
G_TYPE_INT, pos.x(),
G_TYPE_INT, pos.y(),
G_TYPE_INT, preeditRect.x(),
G_TYPE_INT, preeditRect.y(),
G_TYPE_INT, preeditRect.width(),
G_TYPE_INT, preeditRect.height(),
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit",
G_TYPE_STRING, text.toUtf8().data(),
G_TYPE_INT, cursorPos,
G_TYPE_INVALID);
}
namespace {
bool encodeVariant(GValue *dest, const QVariant &source)
{
switch (source.type()) {
case QVariant::Bool:
g_value_init(dest, G_TYPE_BOOLEAN);
g_value_set_boolean(dest, source.toBool());
return true;
case QVariant::Int:
g_value_init(dest, G_TYPE_INT);
g_value_set_int(dest, source.toInt());
return true;
case QVariant::UInt:
g_value_init(dest, G_TYPE_UINT);
g_value_set_uint(dest, source.toUInt());
return true;
case QVariant::LongLong:
g_value_init(dest, G_TYPE_INT64);
g_value_set_int64(dest, source.toLongLong());
return true;
case QVariant::ULongLong:
g_value_init(dest, G_TYPE_UINT64);
g_value_set_uint64(dest, source.toULongLong());
return true;
case QVariant::Double:
g_value_init(dest, G_TYPE_DOUBLE);
g_value_set_double(dest, source.toDouble());
return true;
case QVariant::String:
g_value_init(dest, G_TYPE_STRING);
// string is copied by g_value_set_string
g_value_set_string(dest, source.toString().toUtf8().constData());
return true;
case QVariant::Rect:
{
// QRect is encoded as (iiii).
// This is compatible with QDBusArgument encoding. see more in decoder
GType structType = dbus_g_type_get_struct("GValueArray",
G_TYPE_INT, G_TYPE_INT,
G_TYPE_INT, G_TYPE_INT,
G_TYPE_INVALID);
g_value_init(dest, structType);
GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType);
if (!array) {
qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance";
}
g_value_take_boxed(dest, array);
QRect rect = source.toRect();
if (!dbus_g_type_struct_set(dest,
0, rect.left(),
1, rect.top(),
2, rect.width(),
3, rect.height(),
G_MAXUINT)) {
g_value_unset(dest);
qWarning() << Q_FUNC_INFO << "failed to fill Rect instance";
return false;
}
return true;
}
case QMetaType::ULong:
g_value_init(dest, G_TYPE_ULONG);
g_value_set_ulong(dest, source.value<ulong>());
return true;
default:
qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source;
return false;
}
}
void destroyGValue(GValue *value)
{
g_value_unset(value);
g_free(value);
}
GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source)
{
GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal,
&g_free, GDestroyNotify(&destroyGValue));
foreach (QString key, source.keys()) {
GValue *valueVariant = g_new0(GValue, 1);
if (!encodeVariant(valueVariant, source[key])) {
g_free(valueVariant);
g_hash_table_unref(result);
return 0;
}
g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant);
}
return result;
}
}
void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation,
bool focusChanged)
{
if (!glibObjectProxy) {
return;
}
GHashTable *encodedState = encodeVariantMap(stateInformation);
if (encodedState == 0)
return;
GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation",
encodedStateType, encodedState,
G_TYPE_BOOLEAN, focusChanged,
G_TYPE_INVALID);
g_hash_table_unref(encodedState);
}
void GlibDBusIMServerProxy::reset(bool requireSynchronization)
{
if (!glibObjectProxy) {
return;
}
if (requireSynchronization) {
DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset",
resetNotifyTrampoline, this,
0, G_TYPE_INVALID);
pendingResetCalls.insert(resetCall);
} else {
dbus_g_proxy_call_no_reply(glibObjectProxy, "reset",
G_TYPE_INVALID);
}
}
bool GlibDBusIMServerProxy::pendingResets()
{
return (pendingResetCalls.size() > 0);
}
void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange",
G_TYPE_INT, angle,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::appOrientationChanged(int angle)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged",
G_TYPE_INT, angle,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState",
G_TYPE_BOOLEAN, copyAvailable,
G_TYPE_BOOLEAN, pasteAvailable,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode,
Qt::KeyboardModifiers modifiers,
const QString &text, bool autoRepeat, int count,
quint32 nativeScanCode, quint32 nativeModifiers,
unsigned long time)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent",
G_TYPE_INT, static_cast<int>(keyType),
G_TYPE_INT, static_cast<int>(keyCode),
G_TYPE_INT, static_cast<int>(modifiers),
G_TYPE_STRING, text.toUtf8().data(),
G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count,
G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers,
G_TYPE_ULONG, time,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension",
G_TYPE_INT, id,
G_TYPE_STRING, fileName.toUtf8().data(),
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::unregisterAttributeExtension(int id)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension",
G_TYPE_INT, id,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem,
const QString &attribute, const QVariant &value)
{
if (!glibObjectProxy) {
return;
}
GValue valueData = {0, {{0}, {0}}};
if (!encodeVariant(&valueData, value)) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute",
G_TYPE_INT, id,
G_TYPE_STRING, target.toUtf8().data(),
G_TYPE_STRING, targetItem.toUtf8().data(),
G_TYPE_STRING, attribute.toUtf8().data(),
G_TYPE_VALUE, &valueData,
G_TYPE_INVALID);
g_value_unset(&valueData);
}
<commit_msg>Fixes: crash in ut_minputocntextplugin<commit_after>/* * This file is part of meego-im-framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* If you have questions regarding the use of this file, please contact
* Nokia at directui@nokia.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "glibdbusimserverproxy.h"
#include "minputcontext.h"
#include <QPoint>
#include <QRect>
#include <QString>
#include <QDataStream>
#include <QVariant>
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#include <unistd.h>
#include <sys/types.h>
namespace
{
const char * const DBusPath("/com/meego/inputmethod/uiserver1");
const char * const DBusInterface("com.meego.inputmethod.uiserver1");
const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus";
const int ConnectionRetryInterval(6*1000); // in ms
Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection)
{
if (!connection)
return Maliit::DBusGLib::ConnectionRef();
return Maliit::DBusGLib::ConnectionRef(connection,
dbus_g_connection_unref);
}
}
GlibDBusIMServerProxy::GlibDBusIMServerProxy(GObject *inputContextAdaptor, const QString &icAdaptorPath)
: glibObjectProxy(NULL),
connection(),
inputContextAdaptor(inputContextAdaptor),
icAdaptorPath(icAdaptorPath),
active(true)
{
dbus_g_thread_init();
connectToDBus();
}
GlibDBusIMServerProxy::~GlibDBusIMServerProxy()
{
active = false;
foreach (DBusGProxyCall *callId, pendingResetCalls) {
dbus_g_proxy_cancel_call(glibObjectProxy, callId);
}
}
// Auxiliary connection handling.............................................
void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData)
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection();
}
void GlibDBusIMServerProxy::connectToDBus()
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
GError *error = NULL;
connection = toRef(dbus_g_connection_open(SocketPath, &error));
if (!connection) {
if (error) {
qWarning("MInputContext: unable to create D-Bus connection: %s", error->message);
g_error_free(error);
}
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
return;
}
glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface);
if (!glibObjectProxy) {
qWarning("MInputContext: unable to find the D-Bus service.");
connection.reset();
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
return;
}
g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline),
this);
dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor);
emit dbusConnected();
}
void GlibDBusIMServerProxy::onDisconnection()
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
glibObjectProxy = 0;
connection.reset();
emit dbusDisconnected();
if (active) {
QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
}
}
void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId,
gpointer userData)
{
static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId);
}
void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId)
{
if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID);
pendingResetCalls.remove(callId);
}
// Remote methods............................................................
void GlibDBusIMServerProxy::activateContext()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::showInputMethod()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::hideInputMethod()
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod",
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit",
G_TYPE_INT, pos.x(),
G_TYPE_INT, pos.y(),
G_TYPE_INT, preeditRect.x(),
G_TYPE_INT, preeditRect.y(),
G_TYPE_INT, preeditRect.width(),
G_TYPE_INT, preeditRect.height(),
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit",
G_TYPE_STRING, text.toUtf8().data(),
G_TYPE_INT, cursorPos,
G_TYPE_INVALID);
}
namespace {
bool encodeVariant(GValue *dest, const QVariant &source)
{
switch (source.type()) {
case QVariant::Bool:
g_value_init(dest, G_TYPE_BOOLEAN);
g_value_set_boolean(dest, source.toBool());
return true;
case QVariant::Int:
g_value_init(dest, G_TYPE_INT);
g_value_set_int(dest, source.toInt());
return true;
case QVariant::UInt:
g_value_init(dest, G_TYPE_UINT);
g_value_set_uint(dest, source.toUInt());
return true;
case QVariant::LongLong:
g_value_init(dest, G_TYPE_INT64);
g_value_set_int64(dest, source.toLongLong());
return true;
case QVariant::ULongLong:
g_value_init(dest, G_TYPE_UINT64);
g_value_set_uint64(dest, source.toULongLong());
return true;
case QVariant::Double:
g_value_init(dest, G_TYPE_DOUBLE);
g_value_set_double(dest, source.toDouble());
return true;
case QVariant::String:
g_value_init(dest, G_TYPE_STRING);
// string is copied by g_value_set_string
g_value_set_string(dest, source.toString().toUtf8().constData());
return true;
case QVariant::Rect:
{
// QRect is encoded as (iiii).
// This is compatible with QDBusArgument encoding. see more in decoder
GType structType = dbus_g_type_get_struct("GValueArray",
G_TYPE_INT, G_TYPE_INT,
G_TYPE_INT, G_TYPE_INT,
G_TYPE_INVALID);
g_value_init(dest, structType);
GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType);
if (!array) {
qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance";
}
g_value_take_boxed(dest, array);
QRect rect = source.toRect();
if (!dbus_g_type_struct_set(dest,
0, rect.left(),
1, rect.top(),
2, rect.width(),
3, rect.height(),
G_MAXUINT)) {
g_value_unset(dest);
qWarning() << Q_FUNC_INFO << "failed to fill Rect instance";
return false;
}
return true;
}
case QMetaType::ULong:
g_value_init(dest, G_TYPE_ULONG);
g_value_set_ulong(dest, source.value<ulong>());
return true;
default:
qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source;
return false;
}
}
void destroyGValue(GValue *value)
{
g_value_unset(value);
g_free(value);
}
GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source)
{
GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal,
&g_free, GDestroyNotify(&destroyGValue));
foreach (QString key, source.keys()) {
GValue *valueVariant = g_new0(GValue, 1);
if (!encodeVariant(valueVariant, source[key])) {
g_free(valueVariant);
g_hash_table_unref(result);
return 0;
}
g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant);
}
return result;
}
}
void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation,
bool focusChanged)
{
if (!glibObjectProxy) {
return;
}
GHashTable *encodedState = encodeVariantMap(stateInformation);
if (encodedState == 0)
return;
GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation",
encodedStateType, encodedState,
G_TYPE_BOOLEAN, focusChanged,
G_TYPE_INVALID);
g_hash_table_unref(encodedState);
}
void GlibDBusIMServerProxy::reset(bool requireSynchronization)
{
if (!glibObjectProxy) {
return;
}
if (requireSynchronization) {
DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset",
resetNotifyTrampoline, this,
0, G_TYPE_INVALID);
pendingResetCalls.insert(resetCall);
} else {
dbus_g_proxy_call_no_reply(glibObjectProxy, "reset",
G_TYPE_INVALID);
}
}
bool GlibDBusIMServerProxy::pendingResets()
{
return (pendingResetCalls.size() > 0);
}
void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange",
G_TYPE_INT, angle,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::appOrientationChanged(int angle)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged",
G_TYPE_INT, angle,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState",
G_TYPE_BOOLEAN, copyAvailable,
G_TYPE_BOOLEAN, pasteAvailable,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode,
Qt::KeyboardModifiers modifiers,
const QString &text, bool autoRepeat, int count,
quint32 nativeScanCode, quint32 nativeModifiers,
unsigned long time)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent",
G_TYPE_INT, static_cast<int>(keyType),
G_TYPE_INT, static_cast<int>(keyCode),
G_TYPE_INT, static_cast<int>(modifiers),
G_TYPE_STRING, text.toUtf8().data(),
G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count,
G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers,
G_TYPE_ULONG, time,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension",
G_TYPE_INT, id,
G_TYPE_STRING, fileName.toUtf8().data(),
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::unregisterAttributeExtension(int id)
{
if (!glibObjectProxy) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension",
G_TYPE_INT, id,
G_TYPE_INVALID);
}
void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem,
const QString &attribute, const QVariant &value)
{
if (!glibObjectProxy) {
return;
}
GValue valueData = {0, {{0}, {0}}};
if (!encodeVariant(&valueData, value)) {
return;
}
dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute",
G_TYPE_INT, id,
G_TYPE_STRING, target.toUtf8().data(),
G_TYPE_STRING, targetItem.toUtf8().data(),
G_TYPE_STRING, attribute.toUtf8().data(),
G_TYPE_VALUE, &valueData,
G_TYPE_INVALID);
g_value_unset(&valueData);
}
<|endoftext|>
|
<commit_before>#include <sys/ucontext.h>
namespace factor {
// Fault handler information. MacOSX version.
// Copyright (C) 1993-1999, 2002-2003 Bruno Haible <clisp.org at bruno>
// Copyright (C) 2003 Paolo Bonzini <gnu.org at bonzini>
// Used under BSD license with permission from Paolo Bonzini and Bruno Haible,
// 2005-03-10:
// http://sourceforge.net/mailarchive/message.php?msg_name=200503102200.32002.bruno%40clisp.org
// Modified for Factor by Slava Pestov and Daniel Ehrenberg
// Modified for arm64 by Doug Coleman
/*
#define MACH_EXC_STATE_TYPE x86_exception_state64_t
#define MACH_EXC_STATE_FLAVOR x86_EXCEPTION_STATE64
#define MACH_EXC_STATE_COUNT x86_EXCEPTION_STATE64_COUNT
#define MACH_EXC_INTEGER_DIV EXC_I386_DIV
#define MACH_THREAD_STATE_TYPE x86_thread_state64_t
#define MACH_THREAD_STATE_FLAVOR x86_THREAD_STATE64
#define MACH_THREAD_STATE_COUNT MACHINE_THREAD_STATE_COUNT
#define MACH_FLOAT_STATE_TYPE x86_float_state64_t
#define MACH_FLOAT_STATE_FLAVOR x86_FLOAT_STATE64
#define MACH_FLOAT_STATE_COUNT x86_FLOAT_STATE64_COUNT
#if __DARWIN_UNIX03
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->__faultvaddr
#define MACH_STACK_POINTER(thr_state) (thr_state)->__rsp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->__rip
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__fs)
#define MXCSR(float_state) (float_state)->__fpu_mxcsr
#define X87SW(float_state) (float_state)->__fpu_fsw
#else
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->faultvaddr
#define MACH_STACK_POINTER(thr_state) (thr_state)->rsp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->rip
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->fs)
#define MXCSR(float_state) (float_state)->fpu_mxcsr
#define X87SW(float_state) (float_state)->fpu_fsw
#endif
#define UAP_PROGRAM_COUNTER(ucontext) MACH_PROGRAM_COUNTER(UAP_SS(ucontext))
inline static unsigned int mach_fpu_status(x86_float_state64_t* float_state) {
unsigned short x87sw;
memcpy(&x87sw, &X87SW(float_state), sizeof(x87sw));
return MXCSR(float_state) | x87sw;
}
inline static unsigned int uap_fpu_status(void* uap) {
return mach_fpu_status(UAP_FS(uap));
}
inline static void mach_clear_fpu_status(x86_float_state64_t* float_state) {
MXCSR(float_state) &= 0xffffffc0;
memset(&X87SW(float_state), 0, sizeof(X87SW(float_state)));
}
inline static void uap_clear_fpu_status(void* uap) {
mach_clear_fpu_status(UAP_FS(uap));
}
// Must match the stack-frame-size constant in
// basis/bootstrap/assembler/x86.64.unix.factor
static const unsigned JIT_FRAME_SIZE = 32;
*/
#define MACH_EXC_STATE_TYPE _STRUCT_ARM_EXCEPTION_STATE64 // arm_exception_state64_t
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->__far
#define MACH_EXC_STATE_COUNT ARM_EXCEPTION_STATE64_COUNT
#define MACH_EXC_STATE_FLAVOR ARM_EXCEPTION_STATE64
//#define MACH_EXC_INTEGER_DIV undefined on arm? https://opensource.apple.com/source/lldb/lldb-112/source/Plugins/Process/Utility/StopInfoMachException.cpp.auto.html
#define MACH_THREAD_STATE_TYPE _STRUCT_ARM_THREAD_STATE64
#define MACH_THREAD_STATE_COUNT MACHINE_THREAD_STATE_COUNT
#define MACH_THREAD_STATE_FLAVOR ARM_THREAD_STATE64
#define MACH_FLOAT_STATE_TYPE _STRUCT_ARM_NEON_STATE64
#define MACH_FLOAT_STATE_COUNT ARM_NEON_STATE64_COUNT
#define MACH_FLOAT_STATE_FLAVOR ARM_NEON_STATE64
#define MACH_STACK_POINTER(thr_state) (thr_state)->__sp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->__pc
#define UAP_PROGRAM_COUNTER(ucontext) MACH_PROGRAM_COUNTER(UAP_SS(ucontext))
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ns)
// omg
inline static unsigned int mach_fpu_status(_STRUCT_ARM_NEON_STATE64* float_state) {
// unsigned short x87sw;
// memcpy(&x87sw, &X87SW(float_state), sizeof(x87sw));
// return MXCSR(float_state) | x87sw;
return float_state->__fpsr;
}
// omg
inline static unsigned int uap_fpu_status(void* uap) {
return mach_fpu_status(UAP_FS(uap));
}
// omg
inline static void uap_clear_fpu_status(void* uap) {
// mach_clear_fpu_status(UAP_FS(uap));
}
inline static void mach_clear_fpu_status(arm_neon_state64_t* float_state) {
// MXCSR(float_state) &= 0xffffffc0; // omg
// memset(&X87SW(float_state), 0, sizeof(X87SW(float_state))); // omg
}
// omg
inline static unsigned int fpu_status(unsigned int status) {
unsigned int r = 0;
/*
if (status & 0x01)
r |= FP_TRAP_INVALID_OPERATION;
if (status & 0x04)
r |= FP_TRAP_ZERO_DIVIDE;
if (status & 0x08)
r |= FP_TRAP_OVERFLOW;
if (status & 0x10)
r |= FP_TRAP_UNDERFLOW;
if (status & 0x20)
r |= FP_TRAP_INEXACT;
*/
return r;
}
static const unsigned JIT_FRAME_SIZE = 32; // omg
}<commit_msg>vm: use EXC_ARM_FP_DZ on macosx-arm64.<commit_after>#include <sys/ucontext.h>
namespace factor {
// Fault handler information. MacOSX version.
// Copyright (C) 1993-1999, 2002-2003 Bruno Haible <clisp.org at bruno>
// Copyright (C) 2003 Paolo Bonzini <gnu.org at bonzini>
// Used under BSD license with permission from Paolo Bonzini and Bruno Haible,
// 2005-03-10:
// http://sourceforge.net/mailarchive/message.php?msg_name=200503102200.32002.bruno%40clisp.org
// Modified for Factor by Slava Pestov and Daniel Ehrenberg
// Modified for arm64 by Doug Coleman
/*
#define MACH_EXC_STATE_TYPE x86_exception_state64_t
#define MACH_EXC_STATE_FLAVOR x86_EXCEPTION_STATE64
#define MACH_EXC_STATE_COUNT x86_EXCEPTION_STATE64_COUNT
*/
#define MACH_EXC_INTEGER_DIV EXC_ARM_FP_DZ
/*
#define MACH_THREAD_STATE_TYPE x86_thread_state64_t
#define MACH_THREAD_STATE_FLAVOR x86_THREAD_STATE64
#define MACH_THREAD_STATE_COUNT MACHINE_THREAD_STATE_COUNT
#define MACH_FLOAT_STATE_TYPE x86_float_state64_t
#define MACH_FLOAT_STATE_FLAVOR x86_FLOAT_STATE64
#define MACH_FLOAT_STATE_COUNT x86_FLOAT_STATE64_COUNT
#if __DARWIN_UNIX03
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->__faultvaddr
#define MACH_STACK_POINTER(thr_state) (thr_state)->__rsp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->__rip
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__fs)
#define MXCSR(float_state) (float_state)->__fpu_mxcsr
#define X87SW(float_state) (float_state)->__fpu_fsw
#else
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->faultvaddr
#define MACH_STACK_POINTER(thr_state) (thr_state)->rsp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->rip
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->fs)
#define MXCSR(float_state) (float_state)->fpu_mxcsr
#define X87SW(float_state) (float_state)->fpu_fsw
#endif
#define UAP_PROGRAM_COUNTER(ucontext) MACH_PROGRAM_COUNTER(UAP_SS(ucontext))
inline static unsigned int mach_fpu_status(x86_float_state64_t* float_state) {
unsigned short x87sw;
memcpy(&x87sw, &X87SW(float_state), sizeof(x87sw));
return MXCSR(float_state) | x87sw;
}
inline static unsigned int uap_fpu_status(void* uap) {
return mach_fpu_status(UAP_FS(uap));
}
inline static void mach_clear_fpu_status(x86_float_state64_t* float_state) {
MXCSR(float_state) &= 0xffffffc0;
memset(&X87SW(float_state), 0, sizeof(X87SW(float_state)));
}
inline static void uap_clear_fpu_status(void* uap) {
mach_clear_fpu_status(UAP_FS(uap));
}
// Must match the stack-frame-size constant in
// basis/bootstrap/assembler/x86.64.unix.factor
static const unsigned JIT_FRAME_SIZE = 32;
*/
#define MACH_EXC_STATE_TYPE _STRUCT_ARM_EXCEPTION_STATE64 // arm_exception_state64_t
#define MACH_EXC_STATE_FAULT(exc_state) (exc_state)->__far
#define MACH_EXC_STATE_COUNT ARM_EXCEPTION_STATE64_COUNT
#define MACH_EXC_STATE_FLAVOR ARM_EXCEPTION_STATE64
//#define MACH_EXC_INTEGER_DIV undefined on arm? https://opensource.apple.com/source/lldb/lldb-112/source/Plugins/Process/Utility/StopInfoMachException.cpp.auto.html
#define MACH_THREAD_STATE_TYPE _STRUCT_ARM_THREAD_STATE64
#define MACH_THREAD_STATE_COUNT MACHINE_THREAD_STATE_COUNT
#define MACH_THREAD_STATE_FLAVOR ARM_THREAD_STATE64
#define MACH_FLOAT_STATE_TYPE _STRUCT_ARM_NEON_STATE64
#define MACH_FLOAT_STATE_COUNT ARM_NEON_STATE64_COUNT
#define MACH_FLOAT_STATE_FLAVOR ARM_NEON_STATE64
#define MACH_STACK_POINTER(thr_state) (thr_state)->__sp
#define MACH_PROGRAM_COUNTER(thr_state) (thr_state)->__pc
#define UAP_PROGRAM_COUNTER(ucontext) MACH_PROGRAM_COUNTER(UAP_SS(ucontext))
#define UAP_SS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ss)
#define UAP_FS(ucontext) &(((ucontext_t*)(ucontext))->uc_mcontext->__ns)
// omg
inline static unsigned int mach_fpu_status(_STRUCT_ARM_NEON_STATE64* float_state) {
// unsigned short x87sw;
// memcpy(&x87sw, &X87SW(float_state), sizeof(x87sw));
// return MXCSR(float_state) | x87sw;
return float_state->__fpsr;
}
// omg
inline static unsigned int uap_fpu_status(void* uap) {
return mach_fpu_status(UAP_FS(uap));
}
// omg
inline static void uap_clear_fpu_status(void* uap) {
// mach_clear_fpu_status(UAP_FS(uap));
}
inline static void mach_clear_fpu_status(arm_neon_state64_t* float_state) {
// MXCSR(float_state) &= 0xffffffc0; // omg
// memset(&X87SW(float_state), 0, sizeof(X87SW(float_state))); // omg
}
// omg
inline static unsigned int fpu_status(unsigned int status) {
unsigned int r = 0;
/*
if (status & 0x01)
r |= FP_TRAP_INVALID_OPERATION;
if (status & 0x04)
r |= FP_TRAP_ZERO_DIVIDE;
if (status & 0x08)
r |= FP_TRAP_OVERFLOW;
if (status & 0x10)
r |= FP_TRAP_UNDERFLOW;
if (status & 0x20)
r |= FP_TRAP_INEXACT;
*/
return r;
}
static const unsigned JIT_FRAME_SIZE = 32; // omg
}
<|endoftext|>
|
<commit_before>// Copyright 2015 FMAW
#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"
#include <fat.h>
#include <nds.h>
namespace GridMap{
void loadDefaultGridMap( Grid &g ) { loadGridMap("defaultMap", g); }
void loadGridMap( const char* mapName, Grid &g ){
FILE* test = fopen ("./defaultMap", "r");
int rows, cols, aux;
fscanf( test, "%d %d\n", &rows, &cols );
for( int row = 0; row < rows; row++ ){
for( int col = 0; col < cols; col++ ){
if(col < cols-1) fscanf( test, "%d ", &aux );
else fscanf( test, "%d\n", &aux );
IndexPath path {row, col};
g.cellAtIndexPath(path)->setBackgroundType(
static_cast<CellBackgroundType>(aux)
);
g.cellAtIndexPath(path)->renderBackground();
}
}
fclose(test);
}
}
<commit_msg>Fix to prevent crashing if file couldn't be opened.<commit_after>// Copyright 2015 FMAW
#include <fat.h>
#include <nds.h>
#include <iostream>
#include <fstream>
#include "./grid.h"
#include "./gridmap.h"
namespace GridMap {
void loadDefaultGridMap(Grid &g) {
loadGridMap("defaultMap", g);
}
void loadGridMap(const char *mapName, Grid &g) {
FILE *test = fopen("./defaultMap", "r");
if (test != NULL) {
int rows, cols, aux;
fscanf(test, "%d %d\n", &rows, &cols);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (col < cols - 1) {
fscanf(test, "%d ", &aux);
} else {
fscanf(test, "%d\n", &aux);
}
IndexPath path {row, col};
g.cellAtIndexPath(path)->setBackgroundType(
static_cast<CellBackgroundType>(aux));
g.cellAtIndexPath(path)->renderBackground();
}
}
fclose(test);
}
}
} // namespace GridMap
<|endoftext|>
|
<commit_before># include "vtkPointData.h"
# include "vtkPoints.h"
# include "vtkPolyDataMapper.h"
# include "vtkRenderWindow.h"
# include "vtkJPEGReader.h"
# include "vtkOBJReader.h"
# include "vtkProperty.h"
# include "vtkOpenGLHardwareSupport.h"
# include "vtkOpenGLRenderWindow.h"
#include "vtkTexturingHelper.h"
vtkTexturingHelper::vtkTexturingHelper()
{
this->thePolyData_ = NULL;
this->theActor_ = vtkActor::New();
this->geoExtensionsMap_[".obj"] = &vtkTexturingHelper::readOBJFile;
this->imgExtensionsMap_[".jpg"] = &vtkTexturingHelper::readjPEGTexture;
this->TCoordsCount_ = 0;
}
vtkTexturingHelper::~vtkTexturingHelper()
{
}
void vtkTexturingHelper::readjPEGTexture(int index)
{
vtkJPEGReader* jPEGReader = vtkJPEGReader::New();
vtkTexture* newTexture = vtkTexture::New();
jPEGReader->SetFileName(this->texturesFiles_[index].c_str());
jPEGReader->Update();
newTexture->SetInputConnection(jPEGReader->GetOutputPort());
this->textures_.push_back(newTexture);
}
void vtkTexturingHelper::configureTexture(int texIndex)
{
if (texIndex == 0) {
std::cout << "replace tex" << std::endl;
this->textures_[texIndex]->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
} else {
std::cout << "add tex" << std::endl;
this->textures_[texIndex]->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
}
/*this->textures_[texIndex]->RepeatOff();
this->textures_[texIndex]->EdgeClampOn();
this->textures_[texIndex]->InterpolateOn(); */
}
void vtkTexturingHelper::convertImagesToTextures()
{
int texIndex;
for (texIndex = 0; texIndex != this->texturesFiles_.size(); texIndex++)
{
std::string ext = this->texturesFiles_[texIndex].substr(this->texturesFiles_[texIndex].find_last_of("."));
std::cout << "Extension of " << this->texturesFiles_[texIndex] << ": " << ext << std::endl;
if (this->imgExtensionsMap_.find(ext) != this->imgExtensionsMap_.end()) {
(this->*imgExtensionsMap_[ext])(texIndex);
this->configureTexture(texIndex);
} else {
std::cerr << "Unknown extension: " << ext << std::endl;
}
}
}
void vtkTexturingHelper::applyTextures()
{
vtkPolyDataMapper * mapper = vtkPolyDataMapper::New();
this->convertImagesToTextures();
std::cout << "yello" << std::endl;
mapper->SetInput(this->thePolyData_);
bool supported;
int tu = 0;
int textureUnit = vtkProperty::VTK_TEXTURE_UNIT_0;
vtkRenderWindow *tmp = vtkRenderWindow::New();
vtkOpenGLHardwareSupport * hardware =
vtkOpenGLRenderWindow::SafeDownCast(tmp)->GetHardwareSupport();
supported = hardware->GetSupportsMultiTexturing();
if (supported)
{
tu = hardware->GetNumberOfFixedTextureUnits();
std::cout << "Multi-texturing is hardware supported: supports " << tu << " multi textures" << std::endl;
}
if (supported && tu >= 2)
{
std::cout << "Mapping multi-textures" << std::endl;
for (unsigned int texNumber = 0; texNumber <= tu && texNumber < this->TCoordsArrays_.size(); texNumber++) {
std::cout << "Mapping multi-texture " << this->TCoordsArrays_[texNumber]->GetName() << std::endl;
mapper->MapDataArrayToMultiTextureAttribute(
textureUnit, this->TCoordsArrays_[texNumber]->GetName(),
vtkDataObject::FIELD_ASSOCIATION_POINTS);
this->thePolyData_->GetPointData()->AddArray(this->TCoordsArrays_[texNumber]);
textureUnit++;
}
textureUnit = vtkProperty::VTK_TEXTURE_UNIT_0;
for (unsigned int texNumber = 0; texNumber < this->TCoordsArrays_.size(); texNumber++) {
std::cout << "Setting Textures" << std::endl;
this->theActor_->GetProperty()->SetTexture(textureUnit, this->textures_[texNumber]);
textureUnit++;
}
}
else
{
// no multitexturing just show one texture.
this->theActor_->SetTexture(this->textures_[0]);
}
this->theActor_->SetMapper(mapper);
std::cout << "Done Mapping multi-textures" << std::endl;
std::cout << "PolyData arrays = " << this->thePolyData_->GetPointData()->GetNumberOfArrays() << std::endl;
tmp->Delete();
}
void vtkTexturingHelper::insertNewTCoordsArray()
{
vtkFloatArray *newTCoords = vtkFloatArray::New();
std::stringstream ss;
std::string arrayName;
ss << this->TCoordsCount_;
arrayName = "TCoords" + ss.str();
newTCoords->SetName(arrayName.c_str());
newTCoords->SetNumberOfComponents(2);
this->TCoordsCount_++;
for (unsigned int pointNbr = 0; pointNbr < this->thePolyData_->GetPointData()->GetNumberOfTuples(); pointNbr++) {
newTCoords->InsertNextTuple2(-1.0, -1.0);
}
this->TCoordsArrays_.push_back(newTCoords);
}
// Method called after we retrieved the polyData from .obj file with vtkOBJReader.
// VTK doesn't make the differences between the texture coordinates of each image: it just stores everything in one big array.
// So we have to re-read the file by ourselves, to know how many TCoords points are allocated to each image, and then
// create as many smaller arrays than necessary, filling them with the right values at the right place, putting "-1"'s on all the
// points indexes that aren't supposed to be covered by a texture.
// This process also assumes the files are in the right order (i.e. the order in which this->texturesFiles_ has been filled matches
// the order in which the images' texture coordinates are given in the .obj file).
// This may change in the future if this class implements the .mtl file parsing (which would even avoid us to have to specify the
// image files' names manually).
void vtkTexturingHelper::retrieveOBJFileTCoords()
{
std::string prevWord = "";
std::ifstream objFile;
std::string line;
unsigned int texPointsCount = 0;
objFile.open(this->geoFile_);
std::cout << "get lucky opening" << std::endl;
if (!objFile.is_open())
{
std::cerr << "Unable to open OBJ file " << this->geoFile_ << std::endl;
}
while ( objFile.good() )
{
std::stringstream ss;
std::string word;
float x, y;
getline(objFile, line);
ss << line;
ss >> word >> x >> y; // assumes the line is well made (in case of a "vt line" it should be like "vt 42.84 42.84")
if (word == "vt") {
if (prevWord != "vt") {
std::cout << "on " << word << " " << x << " " << y << " with before " << prevWord << std::endl;
insertNewTCoordsArray(); // if we find a vertex texture line and it's the first of a row: create a new TCoords array
}
int arrayNbr;
// In a Obj file, texture coordinates are listed by texture, so we want to put it in the TCoords array of the right texture
// but not in the array of other textures. But every TCoords array musts also have the same number of points than the mesh!
// So to do this we append the coordinates to the concerned TCoords array (the last one created)
// and put (-1.0, -1.0) in the others instead.
for (arrayNbr = 0; arrayNbr != this->TCoordsArrays_.size() - 1; arrayNbr++) {
this->TCoordsArrays_[arrayNbr]->SetTuple2(texPointsCount, -1.0, -1.0);
}
this->TCoordsArrays_[arrayNbr]->SetTuple2(texPointsCount, x, y);
texPointsCount++;
}
prevWord = word;
}
objFile.close();
std::cout << "Object number of points: " << this->thePolyData_->GetPointData()->GetNumberOfTuples() << std::endl;
int arrayNbr;
// In a Obj file, texture coordinates are listed by texture, so we want to put it in the TCoords array of the right texture
// but not in the array of other textures. But every TCoords array musts also have the same number of points than the mesh!
// So to do this we append the coordinates to the concerned TCoords array (the last one created)
// and put (-1.0, -1.0) in the others instead.
for (arrayNbr = 0; arrayNbr != this->TCoordsArrays_.size(); arrayNbr++) {
std::cout << this->TCoordsArrays_[arrayNbr]->GetName() << " number of tuples: " << this->TCoordsArrays_[arrayNbr]->GetNumberOfTuples() << std::endl;
}
}
// Method to obtain a PolyData out of a Wavefront OBJ file
void vtkTexturingHelper::readOBJFile()
{
vtkOBJReader* reader = vtkOBJReader::New();
cout << "Reading obj" << endl;
reader->SetFileName(this->geoFile_.c_str());
reader->Update();
this->thePolyData_ = reader->GetOutput();
std::cout << "Object number of points: " << this->thePolyData_->GetPointData()->GetNumberOfTuples() << std::endl;
//reader->Delete();
std::cout << "Object number of points: " << this->thePolyData_->GetPointData()->GetNumberOfTuples() << std::endl;
cout << "Done reading" << endl;
this->retrieveOBJFileTCoords();
}
void vtkTexturingHelper::addTextureFile(std::string imageFile)
{
this->texturesFiles_.push_back(imageFile);
}
//This method avoids the user to call the addTextureFile function a lot of times, when you have a lot of texture files that follow the
// same naming convention,
// since it permits to simply tell to " get *number* images which name begins by *rootName* ", which will be actually followed by
// an underscore and the number of the image (starting from 0), and ended by the file extension.
// e.g. passing it ("sasha", ".jpg", 3) as parameters will make it add "sasha_0.jpg", "sasha_1.jpg", and "sasha_2.jpg" to the
// list of the texture files to use.
// This is a filename convention since you usually have a geometry file (like "sasha.obj"), and its texture files with the same name,
// an underscore and a number appended to it.
void vtkTexturingHelper::associateTextureFiles(std::string rootName, std::string extension, int numberOfFiles)
{
std::string textureFile;
for (int i = 0; i < numberOfFiles; i++)
{
std::stringstream ss;
ss << i;
textureFile = rootName + "_" + ss.str() + extension;
std::cout << "Adding " << textureFile << std::endl;
this->addTextureFile(textureFile);
}
}
void vtkTexturingHelper::readGeometryFile()
{
std::cout << this->geoFile_ << "?" << std::endl;
int idx = this->geoFile_.rfind('.');
std::cout << "?" << std::endl;
if (idx != std::string::npos) {
std::cerr << "Extension of " << geoFile_ << " is wat" << std::endl;
}
else {
std::cout << "euh" << std::endl;
}
std::string ext = this->geoFile_.substr(geoFile_.find_last_of("."));
if (this->geoExtensionsMap_.find(ext) != this->geoExtensionsMap_.end()) {
(this->*geoExtensionsMap_[ext])();
}
}
void vtkTexturingHelper::clearTexturesList()
{
this->texturesFiles_.clear();
}
vtkPolyData* vtkTexturingHelper::getPolyData() const
{
return this->thePolyData_;
}
vtkActor* vtkTexturingHelper::getActor() const
{
return this->theActor_;
}
void vtkTexturingHelper::setPolyData(vtkPolyData *polyData)
{
this->thePolyData_ = polyData;
}
void vtkTexturingHelper::setGeometryFile(std::string file)
{
this->geoFile_ = file;
}<commit_msg>I forgot to remove some debug output...<commit_after># include "vtkPointData.h"
# include "vtkPoints.h"
# include "vtkPolyDataMapper.h"
# include "vtkRenderWindow.h"
# include "vtkJPEGReader.h"
# include "vtkOBJReader.h"
# include "vtkProperty.h"
# include "vtkOpenGLHardwareSupport.h"
# include "vtkOpenGLRenderWindow.h"
#include "vtkTexturingHelper.h"
vtkTexturingHelper::vtkTexturingHelper()
{
this->thePolyData_ = NULL;
this->theActor_ = vtkActor::New();
this->geoExtensionsMap_[".obj"] = &vtkTexturingHelper::readOBJFile;
this->imgExtensionsMap_[".jpg"] = &vtkTexturingHelper::readjPEGTexture;
this->TCoordsCount_ = 0;
}
vtkTexturingHelper::~vtkTexturingHelper()
{
}
void vtkTexturingHelper::readjPEGTexture(int index)
{
vtkJPEGReader* jPEGReader = vtkJPEGReader::New();
vtkTexture* newTexture = vtkTexture::New();
jPEGReader->SetFileName(this->texturesFiles_[index].c_str());
jPEGReader->Update();
newTexture->SetInputConnection(jPEGReader->GetOutputPort());
this->textures_.push_back(newTexture);
}
void vtkTexturingHelper::configureTexture(int texIndex)
{
if (texIndex == 0) {
this->textures_[texIndex]->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_REPLACE);
} else {
this->textures_[texIndex]->SetBlendingMode(vtkTexture::VTK_TEXTURE_BLENDING_MODE_ADD);
}
}
void vtkTexturingHelper::convertImagesToTextures()
{
int texIndex;
for (texIndex = 0; texIndex != this->texturesFiles_.size(); texIndex++)
{
std::string ext = this->texturesFiles_[texIndex].substr(this->texturesFiles_[texIndex].find_last_of("."));
if (this->imgExtensionsMap_.find(ext) != this->imgExtensionsMap_.end()) {
(this->*imgExtensionsMap_[ext])(texIndex);
this->configureTexture(texIndex);
} else {
std::cerr << "Unknown extension: " << ext << std::endl;
}
}
}
void vtkTexturingHelper::applyTextures()
{
vtkPolyDataMapper * mapper = vtkPolyDataMapper::New();
this->convertImagesToTextures();
mapper->SetInput(this->thePolyData_);
bool supported;
int tu = 0;
int textureUnit = vtkProperty::VTK_TEXTURE_UNIT_0;
vtkRenderWindow *tmp = vtkRenderWindow::New();
vtkOpenGLHardwareSupport * hardware =
vtkOpenGLRenderWindow::SafeDownCast(tmp)->GetHardwareSupport();
supported = hardware->GetSupportsMultiTexturing();
if (supported)
{
tu = hardware->GetNumberOfFixedTextureUnits();
}
if (supported && tu >= 2)
{
for (unsigned int texNumber = 0; texNumber <= tu && texNumber < this->TCoordsArrays_.size(); texNumber++) {
mapper->MapDataArrayToMultiTextureAttribute(
textureUnit, this->TCoordsArrays_[texNumber]->GetName(),
vtkDataObject::FIELD_ASSOCIATION_POINTS);
this->thePolyData_->GetPointData()->AddArray(this->TCoordsArrays_[texNumber]);
textureUnit++;
}
textureUnit = vtkProperty::VTK_TEXTURE_UNIT_0;
for (unsigned int texNumber = 0; texNumber < this->TCoordsArrays_.size(); texNumber++) {
this->theActor_->GetProperty()->SetTexture(textureUnit, this->textures_[texNumber]);
textureUnit++;
}
}
else
{
// no multitexturing just show one texture.
this->theActor_->SetTexture(this->textures_[0]);
}
this->theActor_->SetMapper(mapper);
tmp->Delete();
}
void vtkTexturingHelper::insertNewTCoordsArray()
{
vtkFloatArray *newTCoords = vtkFloatArray::New();
std::stringstream ss;
std::string arrayName;
ss << this->TCoordsCount_;
arrayName = "TCoords" + ss.str();
newTCoords->SetName(arrayName.c_str());
newTCoords->SetNumberOfComponents(2);
this->TCoordsCount_++;
for (unsigned int pointNbr = 0; pointNbr < this->thePolyData_->GetPointData()->GetNumberOfTuples(); pointNbr++) {
newTCoords->InsertNextTuple2(-1.0, -1.0);
}
this->TCoordsArrays_.push_back(newTCoords);
}
// Method called after we retrieved the polyData from .obj file with vtkOBJReader.
// VTK doesn't make the differences between the texture coordinates of each image: it just stores everything in one big array.
// So we have to re-read the file by ourselves, to know how many TCoords points are allocated to each image, and then
// create as many smaller arrays than necessary, filling them with the right values at the right place, putting "-1"'s on all the
// points indexes that aren't supposed to be covered by a texture.
// This process also assumes the files are in the right order (i.e. the order in which this->texturesFiles_ has been filled matches
// the order in which the images' texture coordinates are given in the .obj file).
// This may change in the future if this class implements the .mtl file parsing (which would even avoid us to have to specify the
// image files' names manually).
void vtkTexturingHelper::retrieveOBJFileTCoords()
{
std::string prevWord = "";
std::ifstream objFile;
std::string line;
unsigned int texPointsCount = 0;
objFile.open(this->geoFile_);
if (!objFile.is_open())
{
std::cerr << "Unable to open OBJ file " << this->geoFile_ << std::endl;
}
while ( objFile.good() )
{
std::stringstream ss;
std::string word;
float x, y;
getline(objFile, line);
ss << line;
ss >> word >> x >> y; // assumes the line is well made (in case of a "vt line" it should be like "vt 42.84 42.84")
if (word == "vt") {
if (prevWord != "vt") {
insertNewTCoordsArray(); // if we find a vertex texture line and it's the first of a row: create a new TCoords array
}
int arrayNbr;
// In a Obj file, texture coordinates are listed by texture, so we want to put it in the TCoords array of the right texture
// but not in the array of other textures. But every TCoords array musts also have the same number of points than the mesh!
// So to do this we append the coordinates to the concerned TCoords array (the last one created)
// and put (-1.0, -1.0) in the others instead.
for (arrayNbr = 0; arrayNbr != this->TCoordsArrays_.size() - 1; arrayNbr++) {
this->TCoordsArrays_[arrayNbr]->SetTuple2(texPointsCount, -1.0, -1.0);
}
this->TCoordsArrays_[arrayNbr]->SetTuple2(texPointsCount, x, y);
texPointsCount++;
}
prevWord = word;
}
objFile.close();
}
// Method to obtain a PolyData out of a Wavefront OBJ file
void vtkTexturingHelper::readOBJFile()
{
vtkOBJReader* reader = vtkOBJReader::New();
reader->SetFileName(this->geoFile_.c_str());
reader->Update();
this->thePolyData_ = reader->GetOutput();
this->retrieveOBJFileTCoords();
}
void vtkTexturingHelper::addTextureFile(std::string imageFile)
{
this->texturesFiles_.push_back(imageFile);
}
//This method avoids the user to call the addTextureFile function a lot of times, when you have a lot of texture files that follow the
// same naming convention,
// since it permits to simply tell to " get *number* images which name begins by *rootName* ", which will be actually followed by
// an underscore and the number of the image (starting from 0), and ended by the file extension.
// e.g. passing it ("sasha", ".jpg", 3) as parameters will make it add "sasha_0.jpg", "sasha_1.jpg", and "sasha_2.jpg" to the
// list of the texture files to use.
// This is a filename convention since you usually have a geometry file (like "sasha.obj"), and its texture files with the same name,
// an underscore and a number appended to it.
void vtkTexturingHelper::associateTextureFiles(std::string rootName, std::string extension, int numberOfFiles)
{
std::string textureFile;
for (int i = 0; i < numberOfFiles; i++)
{
std::stringstream ss;
ss << i;
textureFile = rootName + "_" + ss.str() + extension;
this->addTextureFile(textureFile);
}
}
void vtkTexturingHelper::readGeometryFile()
{
std::string ext = this->geoFile_.substr(geoFile_.find_last_of("."));
if (this->geoExtensionsMap_.find(ext) != this->geoExtensionsMap_.end()) {
(this->*geoExtensionsMap_[ext])();
}
}
void vtkTexturingHelper::clearTexturesList()
{
this->texturesFiles_.clear();
}
vtkPolyData* vtkTexturingHelper::getPolyData() const
{
return this->thePolyData_;
}
vtkActor* vtkTexturingHelper::getActor() const
{
return this->theActor_;
}
void vtkTexturingHelper::setPolyData(vtkPolyData *polyData)
{
this->thePolyData_ = polyData;
}
void vtkTexturingHelper::setGeometryFile(std::string file)
{
this->geoFile_ = file;
}<|endoftext|>
|
<commit_before>
#include "HuboRT/Manager.hpp"
int main(int argc, char* argv[])
{
HuboRT::Manager mgr;
mgr.launch();
return 0;
}
<commit_msg>trying to debug the manager launch<commit_after>
#include "HuboRT/Manager.hpp"
#include <syslog.h>
int main(int argc, char* argv[])
{
syslog( LOG_NOTICE, "About to instantiate manager" );
HuboRT::Manager mgr;
syslog( LOG_NOTICE, "About to launch manager" );
// mgr.launch();
mgr.run();
return 0;
}
<|endoftext|>
|
<commit_before>//python3 module for tinyobjloader
//
//usage:
// import tinyobjloader as tol
// model = tol.LoadObj(name)
// print(model["shapes"])
// print(model["materials"]
#include <Python.h>
#include <vector>
#include "../tiny_obj_loader.h"
typedef std::vector<double> vectd;
PyObject*
pyTupleFromfloat3 (float array[3])
{
int i;
PyObject* tuple = PyTuple_New(3);
for(i=0; i<=2 ; i++){
PyTuple_SetItem(tuple, i, PyFloat_FromDouble(array[i]));
}
return tuple;
}
extern "C"
{
static PyObject*
pyLoadObj(PyObject* self, PyObject* args)
{
PyObject *rtndict, *pyshapes, *pymaterials,
*current, *meshobj;
char const* filename;
char *current_name;
vectd vect;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
if(!PyArg_ParseTuple(args, "s", &filename))
return NULL;
tinyobj::LoadObj(shapes, materials, filename);
pyshapes = PyDict_New();
pymaterials = PyDict_New();
rtndict = PyDict_New();
for (std::vector<tinyobj::shape_t>::iterator shape = shapes.begin() ;
shape != shapes.end(); shape++)
{
meshobj = PyDict_New();
tinyobj::mesh_t cm = (*shape).mesh;
for (int i = 0; i <= 4; i++ )
{
current = PyList_New(0);
switch(i) {
case 0:
current_name = "positions";
vect = vectd(cm.positions.begin(), cm.positions.end()); break;
case 1:
current_name = "normals";
vect = vectd(cm.normals.begin(), cm.normals.end()); break;
case 2:
current_name = "texcoords";
vect = vectd(cm.texcoords.begin(), cm.texcoords.end()); break;
case 3:
current_name = "indicies";
vect = vectd(cm.indices.begin(), cm.indices.end()); break;
case 4:
current_name = "material_ids";
vect = vectd(cm.material_ids.begin(), cm.material_ids.end()); break;
}
for (vectd::iterator it = vect.begin() ;
it != vect.end(); it++)
{
PyList_Insert(current, it - vect.begin(), PyFloat_FromDouble(*it));
}
PyDict_SetItemString(meshobj, current_name, current);
}
PyDict_SetItemString(pyshapes, (*shape).name.c_str(), meshobj);
}
for (std::vector<tinyobj::material_t>::iterator mat = materials.begin() ;
mat != materials.end(); mat++)
{
PyObject *matobj = PyDict_New();
PyObject *unknown_parameter = PyDict_New();
for (std::map<std::string, std::string>::iterator p = (*mat).unknown_parameter.begin() ;
p != (*mat).unknown_parameter.end(); ++p)
{
PyDict_SetItemString(unknown_parameter, p->first.c_str(), PyUnicode_FromString(p->second.c_str()));
}
PyDict_SetItemString(matobj, "shininess", PyFloat_FromDouble((*mat).shininess));
PyDict_SetItemString(matobj, "ior", PyFloat_FromDouble((*mat).ior));
PyDict_SetItemString(matobj, "dissolve", PyFloat_FromDouble((*mat).dissolve));
PyDict_SetItemString(matobj, "illum", PyLong_FromLong((*mat).illum));
PyDict_SetItemString(matobj, "ambient_texname", PyUnicode_FromString((*mat).ambient_texname.c_str()));
PyDict_SetItemString(matobj, "diffuse_texname", PyUnicode_FromString((*mat).diffuse_texname.c_str()));
PyDict_SetItemString(matobj, "specular_texname", PyUnicode_FromString((*mat).specular_texname.c_str()));
PyDict_SetItemString(matobj, "specular_highlight_texname", PyUnicode_FromString((*mat).specular_highlight_texname.c_str()));
PyDict_SetItemString(matobj, "bump_texname", PyUnicode_FromString((*mat).bump_texname.c_str()));
PyDict_SetItemString(matobj, "displacement_texname", PyUnicode_FromString((*mat).displacement_texname.c_str()));
PyDict_SetItemString(matobj, "alpha_texname", PyUnicode_FromString((*mat).alpha_texname.c_str()));
PyDict_SetItemString(matobj, "ambient", pyTupleFromfloat3((*mat).ambient));
PyDict_SetItemString(matobj, "diffuse", pyTupleFromfloat3((*mat).diffuse));
PyDict_SetItemString(matobj, "specular", pyTupleFromfloat3((*mat).specular));
PyDict_SetItemString(matobj, "transmittance", pyTupleFromfloat3((*mat).transmittance));
PyDict_SetItemString(matobj, "emission", pyTupleFromfloat3((*mat).emission));
PyDict_SetItemString(matobj, "unknown_parameter", unknown_parameter);
PyDict_SetItemString(pymaterials, (*mat).name.c_str(), matobj);
}
PyDict_SetItemString(rtndict, "shapes", pyshapes);
PyDict_SetItemString(rtndict, "materials", pymaterials);
return rtndict;
}
static PyMethodDef mMethods[] = {
{"LoadObj", pyLoadObj, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"tinyobjloader",
NULL,
-1,
mMethods
};
PyMODINIT_FUNC
PyInit_tinyobjloader(void)
{
return PyModule_Create(&moduledef);
}
}
<commit_msg>Update python binding to match new API.<commit_after>//python3 module for tinyobjloader
//
//usage:
// import tinyobjloader as tol
// model = tol.LoadObj(name)
// print(model["shapes"])
// print(model["materials"]
#include <Python.h>
#include <vector>
#include "../tiny_obj_loader.h"
typedef std::vector<double> vectd;
PyObject*
pyTupleFromfloat3 (float array[3])
{
int i;
PyObject* tuple = PyTuple_New(3);
for(i=0; i<=2 ; i++){
PyTuple_SetItem(tuple, i, PyFloat_FromDouble(array[i]));
}
return tuple;
}
extern "C"
{
static PyObject*
pyLoadObj(PyObject* self, PyObject* args)
{
PyObject *rtndict, *pyshapes, *pymaterials,
*current, *meshobj;
char const* filename;
char *current_name;
vectd vect;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
if(!PyArg_ParseTuple(args, "s", &filename))
return NULL;
std::string err;
tinyobj::LoadObj(shapes, materials, err, filename);
pyshapes = PyDict_New();
pymaterials = PyDict_New();
rtndict = PyDict_New();
for (std::vector<tinyobj::shape_t>::iterator shape = shapes.begin() ;
shape != shapes.end(); shape++)
{
meshobj = PyDict_New();
tinyobj::mesh_t cm = (*shape).mesh;
for (int i = 0; i <= 4; i++ )
{
current = PyList_New(0);
switch(i) {
case 0:
current_name = "positions";
vect = vectd(cm.positions.begin(), cm.positions.end()); break;
case 1:
current_name = "normals";
vect = vectd(cm.normals.begin(), cm.normals.end()); break;
case 2:
current_name = "texcoords";
vect = vectd(cm.texcoords.begin(), cm.texcoords.end()); break;
case 3:
current_name = "indicies";
vect = vectd(cm.indices.begin(), cm.indices.end()); break;
case 4:
current_name = "material_ids";
vect = vectd(cm.material_ids.begin(), cm.material_ids.end()); break;
}
for (vectd::iterator it = vect.begin() ;
it != vect.end(); it++)
{
PyList_Insert(current, it - vect.begin(), PyFloat_FromDouble(*it));
}
PyDict_SetItemString(meshobj, current_name, current);
}
PyDict_SetItemString(pyshapes, (*shape).name.c_str(), meshobj);
}
for (std::vector<tinyobj::material_t>::iterator mat = materials.begin() ;
mat != materials.end(); mat++)
{
PyObject *matobj = PyDict_New();
PyObject *unknown_parameter = PyDict_New();
for (std::map<std::string, std::string>::iterator p = (*mat).unknown_parameter.begin() ;
p != (*mat).unknown_parameter.end(); ++p)
{
PyDict_SetItemString(unknown_parameter, p->first.c_str(), PyUnicode_FromString(p->second.c_str()));
}
PyDict_SetItemString(matobj, "shininess", PyFloat_FromDouble((*mat).shininess));
PyDict_SetItemString(matobj, "ior", PyFloat_FromDouble((*mat).ior));
PyDict_SetItemString(matobj, "dissolve", PyFloat_FromDouble((*mat).dissolve));
PyDict_SetItemString(matobj, "illum", PyLong_FromLong((*mat).illum));
PyDict_SetItemString(matobj, "ambient_texname", PyUnicode_FromString((*mat).ambient_texname.c_str()));
PyDict_SetItemString(matobj, "diffuse_texname", PyUnicode_FromString((*mat).diffuse_texname.c_str()));
PyDict_SetItemString(matobj, "specular_texname", PyUnicode_FromString((*mat).specular_texname.c_str()));
PyDict_SetItemString(matobj, "specular_highlight_texname", PyUnicode_FromString((*mat).specular_highlight_texname.c_str()));
PyDict_SetItemString(matobj, "bump_texname", PyUnicode_FromString((*mat).bump_texname.c_str()));
PyDict_SetItemString(matobj, "displacement_texname", PyUnicode_FromString((*mat).displacement_texname.c_str()));
PyDict_SetItemString(matobj, "alpha_texname", PyUnicode_FromString((*mat).alpha_texname.c_str()));
PyDict_SetItemString(matobj, "ambient", pyTupleFromfloat3((*mat).ambient));
PyDict_SetItemString(matobj, "diffuse", pyTupleFromfloat3((*mat).diffuse));
PyDict_SetItemString(matobj, "specular", pyTupleFromfloat3((*mat).specular));
PyDict_SetItemString(matobj, "transmittance", pyTupleFromfloat3((*mat).transmittance));
PyDict_SetItemString(matobj, "emission", pyTupleFromfloat3((*mat).emission));
PyDict_SetItemString(matobj, "unknown_parameter", unknown_parameter);
PyDict_SetItemString(pymaterials, (*mat).name.c_str(), matobj);
}
PyDict_SetItemString(rtndict, "shapes", pyshapes);
PyDict_SetItemString(rtndict, "materials", pymaterials);
return rtndict;
}
static PyMethodDef mMethods[] = {
{"LoadObj", pyLoadObj, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"tinyobjloader",
NULL,
-1,
mMethods
};
PyMODINIT_FUNC
PyInit_tinyobjloader(void)
{
return PyModule_Create(&moduledef);
}
}
<|endoftext|>
|
<commit_before>//===-- ClangdFuzzer.cpp - Fuzz clangd ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs clangd on a single input.
/// This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "ClangdLSPServer.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include <cstdio>
#include <sstream>
using namespace clang::clangd;
extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
if (size == 0)
return 0;
// fmemopen isn't portable, but I think we only run the fuzzer on Linux.
std::FILE *In = fmemopen(data, size, "r");
auto Transport = newJSONTransport(In, llvm::nulls(),
/*InMirror=*/nullptr, /*Pretty=*/false,
/*Style=*/JSONStreamStyle::Standard);
CodeCompleteOptions CCOpts;
CCOpts.EnableSnippets = false;
ClangdServer::Options Opts;
// Initialize and run ClangdLSPServer.
ClangdLSPServer LSPServer(*Transport, CCOpts, llvm::None, false, Opts);
LSPServer.run();
return 0;
}
<commit_msg>[clangd] Unbreak fuzzer target<commit_after>//===-- ClangdFuzzer.cpp - Fuzz clangd ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs clangd on a single input.
/// This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "ClangdLSPServer.h"
#include "ClangdServer.h"
#include "CodeComplete.h"
#include "FSProvider.h"
#include <cstdio>
#include <sstream>
using namespace clang::clangd;
extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
if (size == 0)
return 0;
// fmemopen isn't portable, but I think we only run the fuzzer on Linux.
std::FILE *In = fmemopen(data, size, "r");
auto Transport = newJSONTransport(In, llvm::nulls(),
/*InMirror=*/nullptr, /*Pretty=*/false,
/*Style=*/JSONStreamStyle::Standard);
RealFileSystemProvider FS;
CodeCompleteOptions CCOpts;
CCOpts.EnableSnippets = false;
ClangdServer::Options Opts;
// Initialize and run ClangdLSPServer.
ClangdLSPServer LSPServer(*Transport, FS, CCOpts, llvm::None, false, Opts);
LSPServer.run();
return 0;
}
<|endoftext|>
|
<commit_before>#include "stats.h"
Stats::Stats() {
this->allocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
void Stats::reset() {
this->allocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
unsigned int Stats::getAllocCount() {
return this->allocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getFenceHitCount() {
return this->fenceHitCount;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
unsigned int Stats::getFenceOverflowHitCount() {
return this->fenceOverflowHitCount;
}
unsigned int Stats::getFenceUnderflowHitCount() {
return this->fenceUnderflowHitCount;
}
void Stats::setAllocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setFenceHitCount(unsigned int count) {
this->fenceHitCount = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFenceOverflowHitCount(unsigned int count) {
this->fenceOverflowHitCount = count;
}
void Stats::setFenceUnderflowHitCount(unsigned int count) {
this->fenceUnderflowHitCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
void Stats::incAllocCount() {
this->allocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incFenceHitCount() {
this->fenceHitCount++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
void Stats::incFenceOverflowHitCount() {
this->fenceOverflowHitCount++;
}
void Stats::incFenceUnderflowHitCount() {
this->fenceUnderflowHitCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->allocCount);
fprintf(fp, "%-20s %d\n", " malloc", 0);
fprintf(fp, "%-20s %d\n", " calloc", 0);
fprintf(fp, "%-20s %d\n", " realloc", 0);
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found: ", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free: ", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free: ", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "fence hit: ", this->fenceHitCount);
fprintf(fp, "%-20s %d\n", " underflow: ", this->fenceUnderflowHitCount);
fprintf(fp, "%-20s %d\n", " overflow: ", this->fenceOverflowHitCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getTotalSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<commit_msg>Added the implementation of the accessor functions and increment functions for mallocCount, callocCount, reallocCount, readFenceOverflow, readFenceUnderflow, writeFenceOverflow, and writeFenceUnderflow.<commit_after>#include "stats.h"
Stats::Stats() {
this->reset();
}
void Stats::reset() {
/* Allocation Stats */
this->allocCount = 0;
this->mallocCount = 0;
this->callocCount = 0;
this->reallocCount = 0;
/* Deallocation Stats */
this->freeCount = 0;
/* Invalid Free Stats*/
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
/* Invalid Read Stats */
this->invalidReadCount = 0;
this->readFenceOverflow = 0;
this->readFenceUnderflow = 0;
/* Invalid Write Stats */
this->invalidWriteCount = 0;
this->writeFenceOverflow = 0;
this->writeFenceUnderflow = 0;
/* Stack Smashing Stats */
this->invalidReturnCount = 0;
}
/* Getters */
unsigned int Stats::getAllocCount() {
return this->allocCount;
}
unsigned int Stats::getMallocCount() {
return this->mallocCount;
}
unsigned int Stats::getCallocCount() {
return this->callocCount;
}
unsigned int Stats::getReallocCount() {
return this->reallocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getReadFenceOverflow() {
return this->readFenceOverflow;
}
unsigned int Stats::getReadFenceUnderflow() {
return this->readFenceUnderflow;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getWriteFenceOverflow() {
return this->writeFenceOverflow;
}
unsigned int Stats::getWriteFenceUnderflow() {
return this->writeFenceUnderflow;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
/* Setters */
void Stats::setAllocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setMallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setCallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setReallocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setReadFenceOverflow(unsigned int count) {
this->readFenceOverflow = count;
}
void Stats::setReadFenceUnderflow(unsigned int count) {
this->readFenceUnderflow = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setWriteFenceOverflow(unsigned int count) {
this->writeFenceOverflow = count;
}
void Stats::setWriteFenceUnderflow(unsigned int count) {
this->writeFenceUnderflow = count;
}
void Stats::setFenceHitCount(unsigned int count) {
this->fenceHitCount = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFenceOverflowHitCount(unsigned int count) {
this->fenceOverflowHitCount = count;
}
void Stats::setFenceUnderflowHitCount(unsigned int count) {
this->fenceUnderflowHitCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
/* Increment Count Functions */
void Stats::incAllocCount() {
this->allocCount++;
}
void Stats::incMallocCount() {
this->mallocCount++;
}
void Stats::incCallocCount() {
this->callocCount++;
}
void Stats::incReallocCount() {
this->reallocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incReadFenceOverflow() {
this->readFenceOverflow++;
}
void Stats::incReadFenceUnderflow() {
this->readFenceUnderflow++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incWriteFenceOverflow() {
this->writeFenceOverflow++;
}
void Stats::incWriteFenceUnderflow() {
this->writeFenceUnderflow++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
/**
* Display All information tracked by the pintool.
*/
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->allocCount);
fprintf(fp, "%-20s %d\n", " malloc", this->mallocCount);
fprintf(fp, "%-20s %d\n", " calloc", this->callocCount);
fprintf(fp, "%-20s %d\n", " realloc", this->reallocCount);
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", " underflow: ", this->readFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow: ", this->readFenceOverflow);
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "%-20s %d\n", " underflow: ", this->writeFenceUnderflow);
fprintf(fp, "%-20s %d\n", " overflow: ", this->writeFenceOverflow);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found: ", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free: ", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free: ", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getTotalSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<|endoftext|>
|
<commit_before>#include "stats.h"
Stats::Stats() {
this->mallocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
void Stats::reset() {
this->mallocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
unsigned int Stats::getMallocCount() {
return this->mallocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getFenceHitCount() {
return this->fenceHitCount;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
unsigned int Stats::getFenceOverflowHitCount() {
return this->fenceOverflowHitCount;
}
unsigned int Stats::getFenceUnderflowHitCount() {
return this->fenceUnderflowHitCount;
}
void Stats::setMallocCount(unsigned int count) {
this->mallocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setFenceHitCount(unsigned int count) {
this->fenceHitCount = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFenceOverflowHitCount(unsigned int count) {
this->fenceOverflowHitCount = count;
}
void Stats::setFenceUnderflowHitCount(unsigned int count) {
this->fenceUnderflowHitCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
void Stats::incMallocCount() {
this->mallocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incFenceHitCount() {
this->fenceHitCount++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
void Stats::incFenceOverflowHitCount() {
this->fenceOverflowHitCount++;
}
void Stats::incFenceUnderflowHitCount() {
this->fenceUnderflowHitCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->mallocCount);
fprintf(fp, "%-20s %d\n", " malloc", 0);
fprintf(fp, "%-20s %d\n", " calloc", 0);
fprintf(fp, "%-20s %d\n", " realloc", 0);
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found: ", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free: ", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free: ", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "fence hit: ", this->fenceHitCount);
fprintf(fp, "%-20s %d\n", " underflow: ", this->fenceUnderflowHitCount);
fprintf(fp, "%-20s %d\n", " overflow: ", this->fenceOverflowHitCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getTotalSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<commit_msg>Adjutsed all mallocCount functions to use allocCount instead in preperation for tracking malloc, calloc, and realloc function calls..<commit_after>#include "stats.h"
Stats::Stats() {
this->allocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
void Stats::reset() {
this->allocCount = 0;
this->freeCount = 0;
this->invalidReadCount = 0;
this->invalidWriteCount = 0;
this->fenceHitCount = 0;
this->invalidFreeCount = 0;
this->midFreeChunkCount = 0;
this->freeNullCount = 0;
this->invalidReturnCount = 0;
this->fenceOverflowHitCount = 0;
this->fenceUnderflowHitCount = 0;
}
unsigned int Stats::getAllocCount() {
return this->allocCount;
}
unsigned int Stats::getFreeCount() {
return this->freeCount;
}
unsigned int Stats::getInvalidReadCount() {
return this->invalidReadCount;
}
unsigned int Stats::getInvalidWriteCount() {
return this->invalidWriteCount;
}
unsigned int Stats::getFenceHitCount() {
return this->fenceHitCount;
}
unsigned int Stats::getInvalidFreeCount() {
return this->invalidFreeCount;
}
unsigned int Stats::getMidFreeChunkCount() {
return this->midFreeChunkCount;
}
unsigned int Stats::getFreeNullCount() {
return this->freeNullCount;
}
unsigned int Stats::getFreeNotFoundCount() {
return this->freeNotFoundCount;
}
unsigned int Stats::getInvalidReturnCount() {
return this->invalidReturnCount;
}
unsigned int Stats::getFenceOverflowHitCount() {
return this->fenceOverflowHitCount;
}
unsigned int Stats::getFenceUnderflowHitCount() {
return this->fenceUnderflowHitCount;
}
void Stats::setAllocCount(unsigned int count) {
this->allocCount = count;
}
void Stats::setFreeCount(unsigned int count) {
this->freeCount = count;
}
void Stats::setInvalidReadCount(unsigned int count) {
this->invalidReadCount = count;
}
void Stats::setInvalidWriteCount(unsigned int count) {
this->invalidWriteCount = count;
}
void Stats::setFenceHitCount(unsigned int count) {
this->fenceHitCount = count;
}
void Stats::setInvalidFreeCount(unsigned int count) {
this->invalidFreeCount = count;
}
void Stats::setMidFreeChunkCount(unsigned int count) {
this->midFreeChunkCount = count;
}
void Stats::setFreeNullCount(unsigned int count) {
this->freeNullCount = count;
}
void Stats::setInvalidReturnCount(unsigned int count) {
this->invalidReturnCount = count;
}
void Stats::setFenceOverflowHitCount(unsigned int count) {
this->fenceOverflowHitCount = count;
}
void Stats::setFenceUnderflowHitCount(unsigned int count) {
this->fenceUnderflowHitCount = count;
}
void Stats::setFreeNotFoundCount(unsigned int count) {
this->freeNotFoundCount = count;
}
void Stats::incAllocCount() {
this->allocCount++;
}
void Stats::incFreeCount() {
this->freeCount++;
}
void Stats::incInvalidReadCount() {
this->invalidReadCount++;
}
void Stats::incInvalidWriteCount() {
this->invalidWriteCount++;
}
void Stats::incFenceHitCount() {
this->fenceHitCount++;
}
void Stats::incInvalidFreeCount() {
this->invalidFreeCount++;
}
void Stats::incMidFreeChunkCount() {
this->midFreeChunkCount++;
}
void Stats::incFreeNullCount() {
this->freeNullCount++;
}
void Stats::incInvalidReturnCount() {
this->invalidReturnCount++;
}
void Stats::incFenceOverflowHitCount() {
this->fenceOverflowHitCount++;
}
void Stats::incFenceUnderflowHitCount() {
this->fenceUnderflowHitCount++;
}
void Stats::incFreeNotFoundCount() {
this->freeNotFoundCount++;
}
void Stats::displayResults(MemList memlist, FILE *fp) {
if(fp == NULL) {
fp = stdin;
}
// Print out the initial object
fprintf(fp, "==================================\n");
fprintf(fp, "%-20s %s\n", "ACTIONS ", "COUNT");
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "allocations: ", this->allocCount);
fprintf(fp, "%-20s %d\n", " malloc", 0);
fprintf(fp, "%-20s %d\n", " calloc", 0);
fprintf(fp, "%-20s %d\n", " realloc", 0);
fprintf(fp, "%-20s %d\n", "deallocations: ", this->freeCount);
fprintf(fp, "%-20s %d\n", " free ", this->freeCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid reads: ", this->invalidReadCount);
fprintf(fp, "%-20s %d\n", "invalid writes: ", this->invalidWriteCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid frees: ", this->invalidFreeCount);
fprintf(fp, "%-20s %d\n", " not found: ", this->freeNotFoundCount);
fprintf(fp, "%-20s %d\n", " null free: ", this->freeNullCount);
fprintf(fp, "%-20s %d\n", " midchunk free: ", this->midFreeChunkCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "fence hit: ", this->fenceHitCount);
fprintf(fp, "%-20s %d\n", " underflow: ", this->fenceUnderflowHitCount);
fprintf(fp, "%-20s %d\n", " overflow: ", this->fenceOverflowHitCount);
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "invalid returns: ", this->invalidReturnCount);
fprintf(fp, "==================================\n");
// Print out the contents of memlist if it was provided.
fprintf(fp, "%-20s\n", "MEMLIST CONTENTS");
char buffer[2048];
int lostMemory = 0;
for(int i = 0; i < memlist.size(); i++) {
MemoryAlloc alloc = memlist.get(i);
fprintf(fp, "%s\n", alloc.toString(buffer, 2048));
lostMemory += alloc.getTotalSize();
}
fprintf(fp, "----------------------------------\n");
fprintf(fp, "%-20s %d\n", "list size: ", memlist.size());
fprintf(fp, "%-20s %d %s\n", "total loss: ", lostMemory, "bytes");
fprintf(fp, "==================================\n");
}
<|endoftext|>
|
<commit_before>/*
kopeteviewmanager.cpp - View Manager
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include <QList>
#include <QTextDocument>
#include <QtAlgorithms>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kplugininfo.h>
#include <knotification.h>
#include <kglobal.h>
#include <kwin.h>
#include "kopetebehaviorsettings.h"
#include "kopeteaccount.h"
#include "kopetepluginmanager.h"
#include "kopeteviewplugin.h"
#include "kopetechatsessionmanager.h"
#include "kopetemetacontact.h"
#include "kopetemessageevent.h"
#include "kopeteview.h"
#include "kopetechatsession.h"
#include "kopetegroup.h"
#include "kopeteviewmanager.h"
typedef QMap<Kopete::ChatSession*,KopeteView*> ManagerMap;
typedef QList<Kopete::MessageEvent*> EventList;
struct KopeteViewManagerPrivate
{
~KopeteViewManagerPrivate()
{
qDeleteAll(managerMap);
managerMap.clear();
qDeleteAll(eventList);
eventList.clear();
}
ManagerMap managerMap;
EventList eventList;
KopeteView *activeView;
bool useQueueOrStack;
bool raiseWindow;
bool queueUnreadMessages;
bool queueOnlyHighlightedMessagesInGroupChats;
bool queueOnlyMessagesOnAnotherDesktop;
bool balloonNotifyIgnoreClosesChatView;
bool foreignMessage;
};
KopeteViewManager *KopeteViewManager::s_viewManager = 0L;
KopeteViewManager *KopeteViewManager::viewManager()
{
if( !s_viewManager )
s_viewManager = new KopeteViewManager();
return s_viewManager;
}
KopeteViewManager::KopeteViewManager()
{
s_viewManager=this;
d = new KopeteViewManagerPrivate;
d->activeView = 0L;
d->foreignMessage=false;
connect( Kopete::BehaviorSettings::self(), SIGNAL( configChanged() ), this, SLOT( slotPrefsChanged() ) );
connect( Kopete::ChatSessionManager::self() , SIGNAL( display( Kopete::Message &, Kopete::ChatSession *) ),
this, SLOT ( messageAppended( Kopete::Message &, Kopete::ChatSession *) ) );
connect( Kopete::ChatSessionManager::self() , SIGNAL( readMessage() ),
this, SLOT ( nextEvent() ) );
slotPrefsChanged();
}
KopeteViewManager::~KopeteViewManager()
{
// kDebug(14000) << k_funcinfo << endl;
//delete all open chatwindow.
ManagerMap::Iterator it;
for ( it = d->managerMap.begin(); it != d->managerMap.end(); ++it )
{
it.value()->closeView( true ); //this does not clean the map, but we don't care
}
delete d;
}
void KopeteViewManager::slotPrefsChanged()
{
d->useQueueOrStack = Kopete::BehaviorSettings::self()->useMessageQueue() || Kopete::BehaviorSettings::self()->useMessageStack();
d->raiseWindow = Kopete::BehaviorSettings::self()->raiseMessageWindow();
d->queueUnreadMessages = Kopete::BehaviorSettings::self()->queueUnreadMessages();
d->queueOnlyHighlightedMessagesInGroupChats = Kopete::BehaviorSettings::self()->queueOnlyHighlightedMessagesInGroupChats();
d->queueOnlyMessagesOnAnotherDesktop = Kopete::BehaviorSettings::self()->queueOnlyMessagesOnAnotherDesktop();
d->balloonNotifyIgnoreClosesChatView = Kopete::BehaviorSettings::self()->balloonNotifyIgnoreClosesChatView();
}
KopeteView *KopeteViewManager::view( Kopete::ChatSession* session, const QString &requestedPlugin )
{
// kDebug(14000) << k_funcinfo << endl;
if( d->managerMap.contains( session ) && d->managerMap[ session ] )
{
return d->managerMap[ session ];
}
else
{
Kopete::PluginManager *pluginManager = Kopete::PluginManager::self();
Kopete::ViewPlugin *viewPlugin = 0L;
QString pluginName = requestedPlugin.isEmpty() ? Kopete::BehaviorSettings::self()->viewPlugin() : requestedPlugin;
if( !pluginName.isEmpty() )
{
viewPlugin = (Kopete::ViewPlugin*)pluginManager->loadPlugin( pluginName );
if( !viewPlugin )
{
kWarning(14000) << "Requested view plugin, " << pluginName
<< ", was not found. Falling back to chat window plugin" << endl;
}
}
if( !viewPlugin )
{
viewPlugin = (Kopete::ViewPlugin*)pluginManager->loadPlugin( QString::fromLatin1("kopete_chatwindow") );
}
if( viewPlugin )
{
KopeteView *newView = viewPlugin->createView(session);
d->foreignMessage = false;
d->managerMap.insert( session, newView );
connect( session, SIGNAL( closing(Kopete::ChatSession *) ),
this, SLOT(slotChatSessionDestroyed(Kopete::ChatSession*)) );
return newView;
}
else
{
kError(14000) << "Could not create a view, no plugins available!" << endl;
return 0L;
}
}
}
void KopeteViewManager::messageAppended( Kopete::Message &msg, Kopete::ChatSession *manager)
{
// kDebug(14000) << k_funcinfo << endl;
bool outgoingMessage = ( msg.direction() == Kopete::Message::Outbound );
if( !outgoingMessage || d->managerMap.contains( manager ) )
{
d->foreignMessage=!outgoingMessage; //let know for the view we are about to create
manager->view(true,msg.requestedPlugin())->appendMessage( msg );
d->foreignMessage=false; //the view is created, reset the flag
bool appendMessageEvent = d->useQueueOrStack;
QWidget *w;
if( d->queueUnreadMessages && ( w = dynamic_cast<QWidget*>(view( manager )) ) )
{
// append msg event to queue if chat window is active but not the chat view in it...
appendMessageEvent = appendMessageEvent && !(w->isActiveWindow() && manager->view() == d->activeView);
// ...and chat window is on another desktop
appendMessageEvent = appendMessageEvent && (!d->queueOnlyMessagesOnAnotherDesktop || !KWin::windowInfo( w->topLevelWidget()->winId(), NET::WMDesktop ).isOnCurrentDesktop());
}
else
{
// append if no chat window exists already
appendMessageEvent = appendMessageEvent && !view( manager )->isVisible();
}
// in group chats always append highlighted messages to queue
appendMessageEvent = appendMessageEvent && (!d->queueOnlyHighlightedMessagesInGroupChats || manager->members().count() == 1 || msg.importance() == Kopete::Message::Highlight);
if( appendMessageEvent )
{
if ( !outgoingMessage )
{
Kopete::MessageEvent *event=new Kopete::MessageEvent(msg,manager);
d->eventList.append( event );
connect(event, SIGNAL(done(Kopete::MessageEvent *)), this, SLOT(slotEventDeleted(Kopete::MessageEvent *)));
Kopete::ChatSessionManager::self()->postNewEvent(event);
}
}
else if( d->eventList.isEmpty() )
{
readMessages( manager, outgoingMessage );
}
if ( !outgoingMessage && ( !manager->account()->isAway() || Kopete::BehaviorSettings::self()->enableEventsWhileAway() ) )
{
QWidget *w=dynamic_cast<QWidget*>(manager->view(false));
if( (!manager->view(false) || !w || manager->view() != d->activeView ||
Kopete::BehaviorSettings::self()->showEventsIfActive() || !w->isActiveWindow())
&& msg.from())
{
QString msgFrom;
msgFrom.clear();
if( msg.from()->metaContact() )
msgFrom = msg.from()->metaContact()->displayName();
else
msgFrom = msg.from()->contactId();
QString msgText = msg.plainBody();
if( msgText.length() > 90 )
msgText = msgText.left(88) + QString::fromLatin1("...");
QString event;
KLocalizedString body = ki18n( "<qt>Incoming message from %1<br>\"%2\"</qt>" );
switch( msg.importance() )
{
case Kopete::Message::Low:
event = QString::fromLatin1( "kopete_contact_lowpriority" );
break;
case Kopete::Message::Highlight:
event = QString::fromLatin1( "kopete_contact_highlight" );
body = ki18n( "<qt>A highlighted message arrived from %1<br>\"%2\"</qt>" );
break;
default:
event = QString::fromLatin1( "kopete_contact_incoming" );
}
KNotification::ContextList contexts;
Kopete::MetaContact *mc= msg.from()->metaContact();
if(mc)
{
contexts.append( qMakePair( QString::fromLatin1("metacontact") , mc->metaContactId()) );
foreach( Kopete::Group *g , mc->groups() )
{
contexts.append( qMakePair( QString::fromLatin1("group") , QString::number(g->groupId())) );
}
}
KNotification *notify=KNotification::event( event,
body.subs( Qt::escape(msgFrom) ).subs( Qt::escape(msgText) ).toString(),
QPixmap(), w, QStringList( i18n( "View" ) ) , contexts );
connect(notify,SIGNAL(activated(unsigned int )), manager , SLOT(raiseView()) );
}
}
}
}
void KopeteViewManager::readMessages( Kopete::ChatSession *manager, bool outgoingMessage, bool activate )
{
// kDebug( 14000 ) << k_funcinfo << endl;
d->foreignMessage=!outgoingMessage; //let know for the view we are about to create
KopeteView *thisView = manager->view( true );
d->foreignMessage=false; //the view is created, reset the flag
if( ( outgoingMessage && !thisView->isVisible() ) || d->raiseWindow || activate )
thisView->raise( activate );
else if( !thisView->isVisible() )
thisView->makeVisible();
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == manager )
{
event->apply();
d->eventList.removeAll(event);
}
}
}
void KopeteViewManager::slotEventDeleted( Kopete::MessageEvent *event )
{
// kDebug(14000) << k_funcinfo << endl;
Kopete::ChatSession *kmm=event->message().manager();
if(!kmm)
return;
// d->eventList.remove( event );
d->eventList.removeAll(event);
if ( event->state() == Kopete::MessageEvent::Applied )
{
readMessages( kmm, false, true );
}
else if ( event->state() == Kopete::MessageEvent::Ignored && d->balloonNotifyIgnoreClosesChatView )
{
bool bAnotherWithThisManager = false;
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == kmm )
{
bAnotherWithThisManager = true;
}
}
if ( !bAnotherWithThisManager && kmm->view( false ) )
kmm->view()->closeView( true );
}
}
void KopeteViewManager::nextEvent()
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->eventList.isEmpty() )
return;
Kopete::MessageEvent* event = d->eventList.first();
if ( event )
event->apply();
}
void KopeteViewManager::slotViewActivated( KopeteView *view )
{
// kDebug( 14000 ) << k_funcinfo << endl;
d->activeView = view;
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == view->msgManager() )
{
event->deleteLater();
}
}
}
void KopeteViewManager::slotViewDestroyed( KopeteView *closingView )
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->managerMap.contains( closingView->msgManager() ) )
{
d->managerMap.remove( closingView->msgManager() );
// closingView->msgManager()->setCanBeDeleted( true );
}
if( closingView == d->activeView )
d->activeView = 0L;
}
void KopeteViewManager::slotChatSessionDestroyed( Kopete::ChatSession *manager )
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->managerMap.contains( manager ) )
{
d->managerMap[ manager ]->closeView( true );
}
}
KopeteView* KopeteViewManager::activeView() const
{
return d->activeView;
}
#include "kopeteviewmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>port to new snapshot<commit_after>/*
kopeteviewmanager.cpp - View Manager
Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@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. *
* *
*************************************************************************
*/
#include <QList>
#include <QTextDocument>
#include <QtAlgorithms>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kplugininfo.h>
#include <knotification.h>
#include <kglobal.h>
#include <kwin.h>
#include "kopetebehaviorsettings.h"
#include "kopeteaccount.h"
#include "kopetepluginmanager.h"
#include "kopeteviewplugin.h"
#include "kopetechatsessionmanager.h"
#include "kopetemetacontact.h"
#include "kopetemessageevent.h"
#include "kopeteview.h"
#include "kopetechatsession.h"
#include "kopetegroup.h"
#include "kopeteviewmanager.h"
typedef QMap<Kopete::ChatSession*,KopeteView*> ManagerMap;
typedef QList<Kopete::MessageEvent*> EventList;
struct KopeteViewManagerPrivate
{
~KopeteViewManagerPrivate()
{
qDeleteAll(managerMap);
managerMap.clear();
qDeleteAll(eventList);
eventList.clear();
}
ManagerMap managerMap;
EventList eventList;
KopeteView *activeView;
bool useQueueOrStack;
bool raiseWindow;
bool queueUnreadMessages;
bool queueOnlyHighlightedMessagesInGroupChats;
bool queueOnlyMessagesOnAnotherDesktop;
bool balloonNotifyIgnoreClosesChatView;
bool foreignMessage;
};
KopeteViewManager *KopeteViewManager::s_viewManager = 0L;
KopeteViewManager *KopeteViewManager::viewManager()
{
if( !s_viewManager )
s_viewManager = new KopeteViewManager();
return s_viewManager;
}
KopeteViewManager::KopeteViewManager()
{
s_viewManager=this;
d = new KopeteViewManagerPrivate;
d->activeView = 0L;
d->foreignMessage=false;
connect( Kopete::BehaviorSettings::self(), SIGNAL( configChanged() ), this, SLOT( slotPrefsChanged() ) );
connect( Kopete::ChatSessionManager::self() , SIGNAL( display( Kopete::Message &, Kopete::ChatSession *) ),
this, SLOT ( messageAppended( Kopete::Message &, Kopete::ChatSession *) ) );
connect( Kopete::ChatSessionManager::self() , SIGNAL( readMessage() ),
this, SLOT ( nextEvent() ) );
slotPrefsChanged();
}
KopeteViewManager::~KopeteViewManager()
{
// kDebug(14000) << k_funcinfo << endl;
//delete all open chatwindow.
ManagerMap::Iterator it;
for ( it = d->managerMap.begin(); it != d->managerMap.end(); ++it )
{
it.value()->closeView( true ); //this does not clean the map, but we don't care
}
delete d;
}
void KopeteViewManager::slotPrefsChanged()
{
d->useQueueOrStack = Kopete::BehaviorSettings::self()->useMessageQueue() || Kopete::BehaviorSettings::self()->useMessageStack();
d->raiseWindow = Kopete::BehaviorSettings::self()->raiseMessageWindow();
d->queueUnreadMessages = Kopete::BehaviorSettings::self()->queueUnreadMessages();
d->queueOnlyHighlightedMessagesInGroupChats = Kopete::BehaviorSettings::self()->queueOnlyHighlightedMessagesInGroupChats();
d->queueOnlyMessagesOnAnotherDesktop = Kopete::BehaviorSettings::self()->queueOnlyMessagesOnAnotherDesktop();
d->balloonNotifyIgnoreClosesChatView = Kopete::BehaviorSettings::self()->balloonNotifyIgnoreClosesChatView();
}
KopeteView *KopeteViewManager::view( Kopete::ChatSession* session, const QString &requestedPlugin )
{
// kDebug(14000) << k_funcinfo << endl;
if( d->managerMap.contains( session ) && d->managerMap[ session ] )
{
return d->managerMap[ session ];
}
else
{
Kopete::PluginManager *pluginManager = Kopete::PluginManager::self();
Kopete::ViewPlugin *viewPlugin = 0L;
QString pluginName = requestedPlugin.isEmpty() ? Kopete::BehaviorSettings::self()->viewPlugin() : requestedPlugin;
if( !pluginName.isEmpty() )
{
viewPlugin = (Kopete::ViewPlugin*)pluginManager->loadPlugin( pluginName );
if( !viewPlugin )
{
kWarning(14000) << "Requested view plugin, " << pluginName
<< ", was not found. Falling back to chat window plugin" << endl;
}
}
if( !viewPlugin )
{
viewPlugin = (Kopete::ViewPlugin*)pluginManager->loadPlugin( QString::fromLatin1("kopete_chatwindow") );
}
if( viewPlugin )
{
KopeteView *newView = viewPlugin->createView(session);
d->foreignMessage = false;
d->managerMap.insert( session, newView );
connect( session, SIGNAL( closing(Kopete::ChatSession *) ),
this, SLOT(slotChatSessionDestroyed(Kopete::ChatSession*)) );
return newView;
}
else
{
kError(14000) << "Could not create a view, no plugins available!" << endl;
return 0L;
}
}
}
void KopeteViewManager::messageAppended( Kopete::Message &msg, Kopete::ChatSession *manager)
{
// kDebug(14000) << k_funcinfo << endl;
bool outgoingMessage = ( msg.direction() == Kopete::Message::Outbound );
if( !outgoingMessage || d->managerMap.contains( manager ) )
{
d->foreignMessage=!outgoingMessage; //let know for the view we are about to create
manager->view(true,msg.requestedPlugin())->appendMessage( msg );
d->foreignMessage=false; //the view is created, reset the flag
bool appendMessageEvent = d->useQueueOrStack;
QWidget *w;
if( d->queueUnreadMessages && ( w = dynamic_cast<QWidget*>(view( manager )) ) )
{
// append msg event to queue if chat window is active but not the chat view in it...
appendMessageEvent = appendMessageEvent && !(w->isActiveWindow() && manager->view() == d->activeView);
// ...and chat window is on another desktop
appendMessageEvent = appendMessageEvent && (!d->queueOnlyMessagesOnAnotherDesktop || !KWin::windowInfo( w->topLevelWidget()->winId(), NET::WMDesktop ).isOnCurrentDesktop());
}
else
{
// append if no chat window exists already
appendMessageEvent = appendMessageEvent && !view( manager )->isVisible();
}
// in group chats always append highlighted messages to queue
appendMessageEvent = appendMessageEvent && (!d->queueOnlyHighlightedMessagesInGroupChats || manager->members().count() == 1 || msg.importance() == Kopete::Message::Highlight);
if( appendMessageEvent )
{
if ( !outgoingMessage )
{
Kopete::MessageEvent *event=new Kopete::MessageEvent(msg,manager);
d->eventList.append( event );
connect(event, SIGNAL(done(Kopete::MessageEvent *)), this, SLOT(slotEventDeleted(Kopete::MessageEvent *)));
Kopete::ChatSessionManager::self()->postNewEvent(event);
}
}
else if( d->eventList.isEmpty() )
{
readMessages( manager, outgoingMessage );
}
if ( !outgoingMessage && ( !manager->account()->isAway() || Kopete::BehaviorSettings::self()->enableEventsWhileAway() ) )
{
QWidget *w=dynamic_cast<QWidget*>(manager->view(false));
if( (!manager->view(false) || !w || manager->view() != d->activeView ||
Kopete::BehaviorSettings::self()->showEventsIfActive() || !w->isActiveWindow())
&& msg.from())
{
QString msgFrom;
msgFrom.clear();
if( msg.from()->metaContact() )
msgFrom = msg.from()->metaContact()->displayName();
else
msgFrom = msg.from()->contactId();
QString msgText = msg.plainBody();
if( msgText.length() > 90 )
msgText = msgText.left(88) + QString::fromLatin1("...");
QString event;
KLocalizedString body = ki18n( "<qt>Incoming message from %1<br>\"%2\"</qt>" );
switch( msg.importance() )
{
case Kopete::Message::Low:
event = QString::fromLatin1( "kopete_contact_lowpriority" );
break;
case Kopete::Message::Highlight:
event = QString::fromLatin1( "kopete_contact_highlight" );
body = ki18n( "<qt>A highlighted message arrived from %1<br>\"%2\"</qt>" );
break;
default:
event = QString::fromLatin1( "kopete_contact_incoming" );
}
KNotification *notify=new KNotification(event, w);
notify->setText(body.subs( Qt::escape(msgFrom) ).subs( Qt::escape(msgText) ).toString());
notify->setActions(QStringList( i18n( "View" ) ));
Kopete::MetaContact *mc= msg.from()->metaContact();
if(mc)
{
notify->addContext( qMakePair( QString::fromLatin1("metacontact") , mc->metaContactId()) );
foreach( Kopete::Group *g , mc->groups() )
{
notify->addContext( qMakePair( QString::fromLatin1("group") , QString::number(g->groupId())) );
}
}
connect(notify,SIGNAL(activated(unsigned int )), manager , SLOT(raiseView()) );
notify->sendEvent();
}
}
}
}
void KopeteViewManager::readMessages( Kopete::ChatSession *manager, bool outgoingMessage, bool activate )
{
// kDebug( 14000 ) << k_funcinfo << endl;
d->foreignMessage=!outgoingMessage; //let know for the view we are about to create
KopeteView *thisView = manager->view( true );
d->foreignMessage=false; //the view is created, reset the flag
if( ( outgoingMessage && !thisView->isVisible() ) || d->raiseWindow || activate )
thisView->raise( activate );
else if( !thisView->isVisible() )
thisView->makeVisible();
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == manager )
{
event->apply();
d->eventList.removeAll(event);
}
}
}
void KopeteViewManager::slotEventDeleted( Kopete::MessageEvent *event )
{
// kDebug(14000) << k_funcinfo << endl;
Kopete::ChatSession *kmm=event->message().manager();
if(!kmm)
return;
// d->eventList.remove( event );
d->eventList.removeAll(event);
if ( event->state() == Kopete::MessageEvent::Applied )
{
readMessages( kmm, false, true );
}
else if ( event->state() == Kopete::MessageEvent::Ignored && d->balloonNotifyIgnoreClosesChatView )
{
bool bAnotherWithThisManager = false;
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == kmm )
{
bAnotherWithThisManager = true;
}
}
if ( !bAnotherWithThisManager && kmm->view( false ) )
kmm->view()->closeView( true );
}
}
void KopeteViewManager::nextEvent()
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->eventList.isEmpty() )
return;
Kopete::MessageEvent* event = d->eventList.first();
if ( event )
event->apply();
}
void KopeteViewManager::slotViewActivated( KopeteView *view )
{
// kDebug( 14000 ) << k_funcinfo << endl;
d->activeView = view;
foreach (Kopete::MessageEvent *event, d->eventList)
{
if ( event->message().manager() == view->msgManager() )
{
event->deleteLater();
}
}
}
void KopeteViewManager::slotViewDestroyed( KopeteView *closingView )
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->managerMap.contains( closingView->msgManager() ) )
{
d->managerMap.remove( closingView->msgManager() );
// closingView->msgManager()->setCanBeDeleted( true );
}
if( closingView == d->activeView )
d->activeView = 0L;
}
void KopeteViewManager::slotChatSessionDestroyed( Kopete::ChatSession *manager )
{
// kDebug( 14000 ) << k_funcinfo << endl;
if( d->managerMap.contains( manager ) )
{
d->managerMap[ manager ]->closeView( true );
}
}
KopeteView* KopeteViewManager::activeView() const
{
return d->activeView;
}
#include "kopeteviewmanager.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>/*
** transport-client.cpp
** Login : <hcuche@hcuche-de>
** Started on Thu Jan 5 15:21:13 2012 Herve Cuche
** $Id$
**
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Herve Cuche
*/
#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>
#include <qi/log.hpp>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <qimessaging/transport_socket.hpp>
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"
#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#include "src/session_p.hpp"
#define MAX_LINE 16384
namespace qi {
class TransportSocketPrivate
{
public:
explicit TransportSocketPrivate(TransportSocket *socket)
: tcd(NULL)
, bev(NULL)
, connected(false)
, fd(-1)
, readHdr(true)
, msg(0)
, _self(socket)
{
}
TransportSocketPrivate(TransportSocket *socket, int fileDesc)
: tcd(NULL)
, bev(NULL)
, connected(false)
, fd(fileDesc)
, readHdr(true)
, msg(0)
, _self(socket)
{
}
~TransportSocketPrivate()
{
}
static void onBufferSent(const void *data, size_t datalen, void *buffer)
{
Buffer *b = static_cast<Buffer *>(buffer);
delete b;
}
static void onMessageSent(const void *data, size_t datalen, void *msg)
{
Message *m = static_cast<Message *>(msg);
delete m;
}
TransportSocketInterface *tcd;
struct bufferevent *bev;
bool connected;
std::map<unsigned int, qi::Message*> msgSend;
boost::mutex mtx;
boost::condition_variable cond;
int fd;
void readcb(struct bufferevent *bev , void *context);
void writecb(struct bufferevent* bev, void* context);
void eventcb(struct bufferevent *bev, short error, void *context);
// data to rebuild message
bool readHdr;
qi::Message *msg;
qi::TransportSocket *_self;
};
static void readcb(struct bufferevent *bev,
void *context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->readcb(bev, context);
}
static void writecb(struct bufferevent* bev,
void* context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->writecb(bev, context);
}
static void eventcb(struct bufferevent *bev,
short error,
void *context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->eventcb(bev, error, context);
}
void TransportSocketPrivate::readcb(struct bufferevent *bev,
void *context)
{
struct evbuffer *input = bufferevent_get_input(bev);
while (true)
{
if (msg == NULL)
{
msg = new qi::Message();
readHdr = true;
}
if (readHdr)
{
if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
return;
evbuffer_remove(input,
msg->_p->getHeader(),
sizeof(MessagePrivate::MessageHeader));
readHdr = false;
}
if (evbuffer_get_length(input) <
static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
return;
/* we have to let the Buffer know we are going to push some data inside */
qi::Buffer buf;
buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
msg->setBuffer(buf);
evbuffer_remove(input,
buf.data(),
buf.size());
assert(msg->isValid());
{
boost::mutex::scoped_lock l(mtx);
msgSend[msg->id()] = msg;
cond.notify_all();
}
if (tcd)
tcd->onSocketReadyRead(_self, msg->id());
msg = NULL;
}
}
void TransportSocketPrivate::writecb(struct bufferevent* bev,
void* context)
{
if (tcd)
tcd->onSocketWriteDone(_self);
}
void TransportSocketPrivate::eventcb(struct bufferevent *bev,
short events,
void *context)
{
if (events & BEV_EVENT_CONNECTED)
{
connected = true;
if (tcd)
tcd->onSocketConnected(_self);
}
else if (events & BEV_EVENT_EOF)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketDisconnected(_self);
// connection has been closed, do any clean up here
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketConnectionError(_self);
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocket") << "Cannnot connect" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl;
}
}
TransportSocketInterface::~TransportSocketInterface() {
}
TransportSocket::TransportSocket()
:_p(new TransportSocketPrivate(this))
{
}
TransportSocket::TransportSocket(int fd, void *data)
:_p(new TransportSocketPrivate(this, fd))
{
struct event_base *base = static_cast<event_base *>(data);
_p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
_p->connected = true;
}
TransportSocket::~TransportSocket()
{
if (isConnected())
{
disconnect();
}
delete _p;
}
bool TransportSocket::connect(qi::Session *session,
const qi::Url &url)
{
const std::string &address = url.host();
unsigned short port = url.port();
if (!isConnected())
{
_p->bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
int result = bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port);
if (result == 0)
{
_p->connected = true;
return true;
}
}
else
{
qiLogError("qimessaging.TransportSocket") << "socket is already connected.";
}
return false;
}
bool TransportSocket::waitForConnected(int msecs)
{
// no timeout
if (msecs < 0)
{
while (!_p->connected)
;
return true;
}
while (!_p->connected && msecs > 0)
{
qi::os::msleep(1);
msecs--;
}
// timeout
if (msecs == 0)
return false;
return true;
}
void TransportSocket::disconnect()
{
if (isConnected())
{
bufferevent_free(_p->bev);
_p->bev = NULL;
_p->connected = false;
}
else
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
}
}
bool TransportSocket::waitForDisconnected(int msecs)
{
// no timeout
if (msecs < 0)
{
while (_p->connected)
;
return true;
}
while (_p->connected && msecs > 0)
{
qi::os::msleep(1);
msecs--;
}
// timeout
if (msecs == 0)
return false;
return true;
}
bool TransportSocket::waitForId(int id, int msecs)
{
std::map<unsigned int, qi::Message*>::iterator it;
{
{
boost::mutex::scoped_lock l(_p->mtx);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
return true;
if (!_p->connected)
return false;
if (msecs > 0)
_p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs));
else
_p->cond.wait(l);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
return true;
}
}
return false;
}
bool TransportSocket::read(int id, qi::Message *msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
return false;
}
std::map<unsigned int, qi::Message*>::iterator it;
{
boost::mutex::scoped_lock l(_p->mtx);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
{
*msg = *it->second;
delete it->second;
_p->msgSend.erase(it);
return true;
}
}
qiLogError("qimessaging.TransportSocket") << "message #" << id
<< " could not be found.";
return false;
}
bool TransportSocket::send(const qi::Message &msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
return false;
}
qi::Message *m = new qi::Message();
*m = msg;
m->_p->complete();
assert(m->isValid());
struct evbuffer *evb = bufferevent_get_output(_p->bev);
// m might be deleted.
qi::Buffer *b = new qi::Buffer(m->buffer());
if (evbuffer_add_reference(evb,
m->_p->getHeader(),
sizeof(qi::MessagePrivate::MessageHeader),
qi::TransportSocketPrivate::onMessageSent,
static_cast<void *>(m)) != 0)
{
return false;
}
if (b->size() &&
evbuffer_add_reference(evb,
b->data(),
b->size(),
qi::TransportSocketPrivate::onBufferSent,
static_cast<void *>(b)) != 0)
{
return false;
}
if (bufferevent_write_buffer(_p->bev, evb) != 0)
{
return false;
}
return true;
}
void TransportSocket::setCallbacks(TransportSocketInterface *delegate)
{
_p->tcd = delegate;
}
bool TransportSocket::isConnected()
{
return _p->connected;
}
}
<commit_msg>Handle unused parameters.<commit_after>/*
** transport-client.cpp
** Login : <hcuche@hcuche-de>
** Started on Thu Jan 5 15:21:13 2012 Herve Cuche
** $Id$
**
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Herve Cuche
*/
#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>
#include <qi/log.hpp>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <qimessaging/transport_socket.hpp>
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"
#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#include "src/session_p.hpp"
#define MAX_LINE 16384
namespace qi {
class TransportSocketPrivate
{
public:
explicit TransportSocketPrivate(TransportSocket *socket)
: tcd(NULL)
, bev(NULL)
, connected(false)
, fd(-1)
, readHdr(true)
, msg(0)
, _self(socket)
{
}
TransportSocketPrivate(TransportSocket *socket, int fileDesc)
: tcd(NULL)
, bev(NULL)
, connected(false)
, fd(fileDesc)
, readHdr(true)
, msg(0)
, _self(socket)
{
}
~TransportSocketPrivate()
{
}
static void onBufferSent(const void *QI_UNUSED(data), size_t QI_UNUSED(datalen), void *buffer)
{
Buffer *b = static_cast<Buffer *>(buffer);
delete b;
}
static void onMessageSent(const void *QI_UNUSED(data), size_t QI_UNUSED(datalen), void *msg)
{
Message *m = static_cast<Message *>(msg);
delete m;
}
TransportSocketInterface *tcd;
struct bufferevent *bev;
bool connected;
std::map<unsigned int, qi::Message*> msgSend;
boost::mutex mtx;
boost::condition_variable cond;
int fd;
void readcb(struct bufferevent *bev , void *context);
void writecb(struct bufferevent* bev, void* context);
void eventcb(struct bufferevent *bev, short error, void *context);
// data to rebuild message
bool readHdr;
qi::Message *msg;
qi::TransportSocket *_self;
};
static void readcb(struct bufferevent *bev,
void *context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->readcb(bev, context);
}
static void writecb(struct bufferevent* bev,
void* context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->writecb(bev, context);
}
static void eventcb(struct bufferevent *bev,
short error,
void *context)
{
TransportSocketPrivate *tc = static_cast<TransportSocketPrivate*>(context);
tc->eventcb(bev, error, context);
}
void TransportSocketPrivate::readcb(struct bufferevent *bev,
void *QI_UNUSED(context))
{
struct evbuffer *input = bufferevent_get_input(bev);
while (true)
{
if (msg == NULL)
{
msg = new qi::Message();
readHdr = true;
}
if (readHdr)
{
if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
return;
evbuffer_remove(input,
msg->_p->getHeader(),
sizeof(MessagePrivate::MessageHeader));
readHdr = false;
}
if (evbuffer_get_length(input) <
static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
return;
/* we have to let the Buffer know we are going to push some data inside */
qi::Buffer buf;
buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
msg->setBuffer(buf);
evbuffer_remove(input,
buf.data(),
buf.size());
assert(msg->isValid());
{
boost::mutex::scoped_lock l(mtx);
msgSend[msg->id()] = msg;
cond.notify_all();
}
if (tcd)
tcd->onSocketReadyRead(_self, msg->id());
msg = NULL;
}
}
void TransportSocketPrivate::writecb(struct bufferevent *QI_UNUSED(bev),
void *QI_UNUSED(context))
{
if (tcd)
tcd->onSocketWriteDone(_self);
}
void TransportSocketPrivate::eventcb(struct bufferevent *bev,
short events,
void *QI_UNUSED(context))
{
if (events & BEV_EVENT_CONNECTED)
{
connected = true;
if (tcd)
tcd->onSocketConnected(_self);
}
else if (events & BEV_EVENT_EOF)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketDisconnected(_self);
// connection has been closed, do any clean up here
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketConnectionError(_self);
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocket") << "Cannnot connect" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl;
}
}
TransportSocketInterface::~TransportSocketInterface() {
}
TransportSocket::TransportSocket()
:_p(new TransportSocketPrivate(this))
{
}
TransportSocket::TransportSocket(int fd, void *data)
:_p(new TransportSocketPrivate(this, fd))
{
struct event_base *base = static_cast<event_base *>(data);
_p->bev = bufferevent_socket_new(base, _p->fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
_p->connected = true;
}
TransportSocket::~TransportSocket()
{
if (isConnected())
{
disconnect();
}
delete _p;
}
bool TransportSocket::connect(qi::Session *session,
const qi::Url &url)
{
const std::string &address = url.host();
unsigned short port = url.port();
if (!isConnected())
{
_p->bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(_p->bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, _p);
bufferevent_setwatermark(_p->bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(_p->bev, EV_READ|EV_WRITE);
int result = bufferevent_socket_connect_hostname(_p->bev, NULL, AF_INET, address.c_str(), port);
if (result == 0)
{
_p->connected = true;
return true;
}
}
else
{
qiLogError("qimessaging.TransportSocket") << "socket is already connected.";
}
return false;
}
bool TransportSocket::waitForConnected(int msecs)
{
// no timeout
if (msecs < 0)
{
while (!_p->connected)
;
return true;
}
while (!_p->connected && msecs > 0)
{
qi::os::msleep(1);
msecs--;
}
// timeout
if (msecs == 0)
return false;
return true;
}
void TransportSocket::disconnect()
{
if (isConnected())
{
bufferevent_free(_p->bev);
_p->bev = NULL;
_p->connected = false;
}
else
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
}
}
bool TransportSocket::waitForDisconnected(int msecs)
{
// no timeout
if (msecs < 0)
{
while (_p->connected)
;
return true;
}
while (_p->connected && msecs > 0)
{
qi::os::msleep(1);
msecs--;
}
// timeout
if (msecs == 0)
return false;
return true;
}
bool TransportSocket::waitForId(int id, int msecs)
{
std::map<unsigned int, qi::Message*>::iterator it;
{
{
boost::mutex::scoped_lock l(_p->mtx);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
return true;
if (!_p->connected)
return false;
if (msecs > 0)
_p->cond.timed_wait(l, boost::posix_time::milliseconds(msecs));
else
_p->cond.wait(l);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
return true;
}
}
return false;
}
bool TransportSocket::read(int id, qi::Message *msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
return false;
}
std::map<unsigned int, qi::Message*>::iterator it;
{
boost::mutex::scoped_lock l(_p->mtx);
it = _p->msgSend.find(id);
if (it != _p->msgSend.end())
{
*msg = *it->second;
delete it->second;
_p->msgSend.erase(it);
return true;
}
}
qiLogError("qimessaging.TransportSocket") << "message #" << id
<< " could not be found.";
return false;
}
bool TransportSocket::send(const qi::Message &msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocket") << "socket is not connected.";
return false;
}
qi::Message *m = new qi::Message();
*m = msg;
m->_p->complete();
assert(m->isValid());
struct evbuffer *evb = bufferevent_get_output(_p->bev);
// m might be deleted.
qi::Buffer *b = new qi::Buffer(m->buffer());
if (evbuffer_add_reference(evb,
m->_p->getHeader(),
sizeof(qi::MessagePrivate::MessageHeader),
qi::TransportSocketPrivate::onMessageSent,
static_cast<void *>(m)) != 0)
{
return false;
}
if (b->size() &&
evbuffer_add_reference(evb,
b->data(),
b->size(),
qi::TransportSocketPrivate::onBufferSent,
static_cast<void *>(b)) != 0)
{
return false;
}
if (bufferevent_write_buffer(_p->bev, evb) != 0)
{
return false;
}
return true;
}
void TransportSocket::setCallbacks(TransportSocketInterface *delegate)
{
_p->tcd = delegate;
}
bool TransportSocket::isConnected()
{
return _p->connected;
}
}
<|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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ANALYSIS task to perrorm TPC calibration //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "TSystem.h"
#include "TTimeStamp.h"
ClassImp(AliTPCAnalysisTaskcalib)
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
:AliAnalysisTask(),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath("")
{
//
// default constructor
//
}
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
:AliAnalysisTask(name,""),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath("")
{
//
// Constructor
//
DefineInput(0, TChain::Class());
DefineOutput(0, TObjArray::Class());
fCalibJobs = new TObjArray(0);
fCalibJobs->SetOwner(kTRUE);
}
AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
//
// destructor
//
printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
fCalibJobs->Delete();
}
void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
//
// Exec function
// Loop over tracks and call Process function
if (!fESD) {
//Printf("ERROR: fESD not available");
return;
}
fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
if (!fESDfriend) {
//Printf("ERROR: fESDfriend not available");
return;
}
Int_t n=fESD->GetNumberOfTracks();
Process(fESD);
Int_t run = fESD->GetRunNumber();
for (Int_t i=0;i<n;++i) {
AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
AliESDtrack *track=fESD->GetTrack(i);
TObject *calibObject=0;
AliTPCseed *seed=0;
if (!friendTrack) continue;
for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
break;
if (track) Process(track, run);
if (seed)
Process(seed);
}
PostData(0,fCalibJobs);
}
void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
//Printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
//Printf("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
//Printf("*** CONNECTED NEW EVENT ****");
}
}
}
void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
//
//
//
//OpenFile(0, "RECREATE");
}
void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
//
// Terminate
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Terminate();
}
}
void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
//
// According description in AliAnalisysTask this method is call
// on the slaves before sending data
//
Terminate("slave");
if(!fDebugOutputPath.IsNull()) {
RegisterDebugOutput();
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
//
// Process ESD event
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) {
job->UpdateEventInfo(event);
if (job->AcceptTrigger())
job->Process(event);
}
}
}
void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
//
// Process TPC track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job)
if (job->AcceptTrigger())
job->Process(track);
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
//
// Process ESD track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job)
if (job->AcceptTrigger())
job->Process(track,run);
}
}
Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
TIterator *i=fCalibJobs->MakeIterator();
AliTPCcalibBase *job;
Long64_t n=0;
while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
n+=job->Merge(li);
return n;
}
void AliTPCAnalysisTaskcalib::Analyze() {
//
// Analyze the content of the task
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Analyze();
}
}
void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
//
//
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
}
TString dsName=GetName();
dsName+=".root";
TFile fff(dsName.Data(),"recreate");
fCalibJobs->Write("TPCCalib",TObject::kSingleKey);
fff.Close();
//
// store - copy debug output to the destination position
// currently ONLY for local copy
TString dsName2=fDebugOutputPath.Data();
gSystem->MakeDirectory(dsName2.Data());
dsName2+=gSystem->HostName();
gSystem->MakeDirectory(dsName2.Data());
dsName2+="/";
TTimeStamp s;
dsName2+=Int_t(s.GetNanoSec());
dsName2+="/";
gSystem->MakeDirectory(dsName2.Data());
dsName2+=dsName;
AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
TFile::Cp(dsName.Data(),dsName2.Data());
}
<commit_msg>removing AnalisysManager warning<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. *
**************************************************************************/
///////////////////////////////////////////////////////////////////////////////
// //
// ANALYSIS task to perrorm TPC calibration //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliTPCAnalysisTaskcalib.h"
#include "TChain.h"
#include "AliTPCcalibBase.h"
#include "AliESDEvent.h"
#include "AliESDfriend.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliTPCseed.h"
#include "AliESDInputHandler.h"
#include "AliAnalysisManager.h"
#include "TFile.h"
#include "TSystem.h"
#include "TTimeStamp.h"
ClassImp(AliTPCAnalysisTaskcalib)
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib()
:AliAnalysisTask(),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath("")
{
//
// default constructor
//
}
AliTPCAnalysisTaskcalib::AliTPCAnalysisTaskcalib(const char *name)
:AliAnalysisTask(name,""),
fCalibJobs(0),
fESD(0),
fESDfriend(0),
fDebugOutputPath("")
{
//
// Constructor
//
DefineInput(0, TChain::Class());
DefineOutput(0, TObjArray::Class());
fCalibJobs = new TObjArray(0);
fCalibJobs->SetOwner(kTRUE);
}
AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib() {
//
// destructor
//
printf("AliTPCAnalysisTaskcalib::~AliTPCAnalysisTaskcalib");
fCalibJobs->Delete();
}
void AliTPCAnalysisTaskcalib::Exec(Option_t *) {
//
// Exec function
// Loop over tracks and call Process function
if (!fESD) {
//Printf("ERROR: fESD not available");
return;
}
fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject("AliESDfriend"));
if (!fESDfriend) {
//Printf("ERROR: fESDfriend not available");
return;
}
Int_t n=fESD->GetNumberOfTracks();
Process(fESD);
Int_t run = fESD->GetRunNumber();
for (Int_t i=0;i<n;++i) {
AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(i);
AliESDtrack *track=fESD->GetTrack(i);
TObject *calibObject=0;
AliTPCseed *seed=0;
if (!friendTrack) continue;
for (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)
if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))
break;
if (track) Process(track, run);
if (seed)
Process(seed);
}
PostData(0,fCalibJobs);
}
void AliTPCAnalysisTaskcalib::ConnectInputData(Option_t *) {
//
//
//
TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
if (!tree) {
//Printf("ERROR: Could not read chain from input slot 0");
}
else {
AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
if (!esdH) {
//Printf("ERROR: Could not get ESDInputHandler");
}
else {
fESD = esdH->GetEvent();
//Printf("*** CONNECTED NEW EVENT ****");
}
}
}
void AliTPCAnalysisTaskcalib::CreateOutputObjects() {
//
//
//
//OpenFile(0, "RECREATE");
PostData(0,fCalibJobs);
}
void AliTPCAnalysisTaskcalib::Terminate(Option_t */*option*/) {
//
// Terminate
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Terminate();
}
}
void AliTPCAnalysisTaskcalib::FinishTaskOutput()
{
//
// According description in AliAnalisysTask this method is call
// on the slaves before sending data
//
Terminate("slave");
if(!fDebugOutputPath.IsNull()) {
RegisterDebugOutput();
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDEvent *event) {
//
// Process ESD event
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) {
job->UpdateEventInfo(event);
if (job->AcceptTrigger())
job->Process(event);
}
}
}
void AliTPCAnalysisTaskcalib::Process(AliTPCseed *track) {
//
// Process TPC track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job)
if (job->AcceptTrigger())
job->Process(track);
}
}
void AliTPCAnalysisTaskcalib::Process(AliESDtrack *track, Int_t run) {
//
// Process ESD track
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job)
if (job->AcceptTrigger())
job->Process(track,run);
}
}
Long64_t AliTPCAnalysisTaskcalib::Merge(TCollection *li) {
TIterator *i=fCalibJobs->MakeIterator();
AliTPCcalibBase *job;
Long64_t n=0;
while ((job=dynamic_cast<AliTPCcalibBase*>(i->Next())))
n+=job->Merge(li);
return n;
}
void AliTPCAnalysisTaskcalib::Analyze() {
//
// Analyze the content of the task
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->Analyze();
}
}
void AliTPCAnalysisTaskcalib::RegisterDebugOutput(){
//
//
//
AliTPCcalibBase *job=0;
Int_t njobs = fCalibJobs->GetEntriesFast();
for (Int_t i=0;i<njobs;i++){
job = (AliTPCcalibBase*)fCalibJobs->UncheckedAt(i);
if (job) job->RegisterDebugOutput(fDebugOutputPath.Data());
}
TString dsName=GetName();
dsName+=".root";
TFile fff(dsName.Data(),"recreate");
fCalibJobs->Write("TPCCalib",TObject::kSingleKey);
fff.Close();
//
// store - copy debug output to the destination position
// currently ONLY for local copy
TString dsName2=fDebugOutputPath.Data();
gSystem->MakeDirectory(dsName2.Data());
dsName2+=gSystem->HostName();
gSystem->MakeDirectory(dsName2.Data());
dsName2+="/";
TTimeStamp s;
dsName2+=Int_t(s.GetNanoSec());
dsName2+="/";
gSystem->MakeDirectory(dsName2.Data());
dsName2+=dsName;
AliInfo(Form("copy %s\t%s\n",dsName.Data(),dsName2.Data()));
printf("copy %s\t%s\n",dsName.Data(),dsName2.Data());
TFile::Cp(dsName.Data(),dsName2.Data());
}
<|endoftext|>
|
<commit_before>/*
* This file is part of meego-keyboard
*
* Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
*
* 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 Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "notificationarea.h"
#include "notificationpanparameters.h"
#include "mplainwindow.h"
#include "notification.h"
#include <QDebug>
#include <QPainter>
#include <QPropertyAnimation>
#include <MSceneManager>
#include <MScalableImage>
#include <float.h>
NotificationArea::NotificationArea(QGraphicsItem *parent)
: MStylableWidget(parent),
outgoingNotification(new Notification(this)),
incomingNotification(new Notification(this)),
assistantNotification(new Notification(this)),
outgoingNotificationParameters(new NotificationPanParameters(this)),
incomingNotificationParameters(new NotificationPanParameters(this)),
assistantNotificationParameters(new NotificationPanParameters(this)),
hideAnimationGroup(this),
showAnimation(this, "opacity")
{
outgoingNotification->connectPanParameters(outgoingNotificationParameters);
incomingNotification->connectPanParameters(incomingNotificationParameters);
assistantNotification->connectPanParameters(assistantNotificationParameters);
connect(&hideAnimationGroup, SIGNAL(finished()),
this, SLOT(onNotificationAnimationFinished()));
connect(&hideAnimationGroup, SIGNAL(finished()),
this, SLOT(reset()));
}
NotificationArea::~NotificationArea()
{
}
void NotificationArea::prepareNotifications(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__;
onNotificationAnimationFinished();
const int screenWidth
= (MPlainWindow::instance()->sceneManager()->orientation() == M::Portrait)
? MPlainWindow::instance()->visibleSceneSize(M::Landscape).height()
: MPlainWindow::instance()->visibleSceneSize(M::Landscape).width();
// prepare notifications
qreal notificationMaximumWidth
= style()->notificationMaximumWidth();
outgoingNotification->setMaximumTextWidth(notificationMaximumWidth);
incomingNotification->setMaximumTextWidth(notificationMaximumWidth);
assistantNotification->setMaximumTextWidth(notificationMaximumWidth);
qreal outgoingNotificationFromScale
= qBound<qreal>(0, qreal(notificationMaximumWidth / outgoingNotification->preferredWidth()), 1.0);
qreal outgoingNotificationToScale
= style()->smallSizeScaleFactor();
QPointF outgoingNotificationFromPos
= QPointF((screenWidth - outgoingNotification->preferredWidth()
* outgoingNotificationFromScale) / 2,
preferredHeight()
- outgoingNotification->preferredHeight()
* outgoingNotificationFromScale);
qreal outgoingNotificationToPosX
= (direction == PanGesture::PanRight)
? screenWidth
: - outgoingNotification->preferredWidth()
* outgoingNotificationToScale;
qreal outgoingNotificationToPosY
= preferredHeight()
- outgoingNotification->preferredHeight() * outgoingNotificationToScale;
QPointF outgoingNotificationToPos
= QPointF(outgoingNotificationToPosX, outgoingNotificationToPosY);
outgoingNotification->updateScale(outgoingNotificationFromScale);
outgoingNotification->updateOpacity(1.0);
outgoingNotification->updatePos(outgoingNotificationFromPos);
outgoingNotification->setVisible(true);
outgoingNotificationParameters->setPositionRange(
outgoingNotificationFromPos, outgoingNotificationToPos);
outgoingNotificationParameters->setScaleRange(outgoingNotificationFromScale,
outgoingNotificationToScale);
outgoingNotificationParameters->setOpacityRange(1.0, 0.0);
outgoingNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
outgoingNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
outgoingNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
qreal leftAndRightSpace
= (outgoingNotification->preferredWidth()
< screenWidth * (1 - style()->initialEdgeMaximumVisibleWidth() * 2))
? screenWidth * style()->initialEdgeMaximumVisibleWidth()
: (screenWidth - notificationMaximumWidth) / 2;
// prepare left and right notifications
if (direction == PanGesture::PanRight) {
incomingNotification->setText(mLeftLayoutTitle);
assistantNotification->setText(mRightLayoutTitle);
} else {
incomingNotification->setText(mRightLayoutTitle);
assistantNotification->setText(mLeftLayoutTitle);
}
qreal incomingNotificationFromScale = outgoingNotificationToScale;
qreal incomingNotificationToScale
= qBound<qreal>(0, qreal(notificationMaximumWidth / incomingNotification->preferredWidth()), 1.0);
qreal incomingNotificationFromPosX = 0;
if (incomingNotification->preferredWidth() * incomingNotificationFromScale
> leftAndRightSpace) {
incomingNotificationFromPosX
= (direction == PanGesture::PanRight)
? leftAndRightSpace
- incomingNotification->preferredWidth() * incomingNotificationFromScale
: screenWidth - leftAndRightSpace;
} else {
incomingNotificationFromPosX
= (direction == PanGesture::PanRight)
? 0
: screenWidth - incomingNotification->preferredWidth() * incomingNotificationFromScale;
}
qreal incomingNotificationFromPosY
= preferredHeight()
- incomingNotification->preferredHeight() * incomingNotificationFromScale;
QPointF incomingNotificationFromPos
= QPointF(incomingNotificationFromPosX, incomingNotificationFromPosY);
QPointF incomingNotificationToPos
= QPointF((screenWidth - incomingNotification->preferredWidth()
* incomingNotificationToScale) / 2,
preferredHeight()
- incomingNotification->preferredHeight()
* incomingNotificationToScale);
incomingNotification->updateScale(incomingNotificationFromScale);
incomingNotification->updatePos(incomingNotificationFromPos);
incomingNotification->updateOpacity(style()->initialEdgeOpacity());
incomingNotification->setVisible(true);
incomingNotificationParameters->setPositionRange(
incomingNotificationFromPos, incomingNotificationToPos);
incomingNotificationParameters->setScaleRange(incomingNotificationFromScale,
incomingNotificationToScale);
incomingNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
1.0);
incomingNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
incomingNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
incomingNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
qreal assistantNotificationFromScale = outgoingNotificationToScale;
qreal assistantNotificationFromPosX = 0;
if (assistantNotification->preferredWidth() * assistantNotificationFromScale
> leftAndRightSpace) {
assistantNotificationFromPosX
= (direction == PanGesture::PanRight)
? screenWidth - leftAndRightSpace
: leftAndRightSpace
- assistantNotification->preferredWidth() * assistantNotificationFromScale;
} else {
assistantNotificationFromPosX
= (direction == PanGesture::PanRight)
? screenWidth - assistantNotification->preferredWidth() * assistantNotificationFromScale
: 0;
}
qreal assistantNotificationFromPosY
= preferredHeight()
- assistantNotification->preferredHeight() * assistantNotificationFromScale;
qreal assistantNotificationToPosY
= preferredHeight()
- assistantNotification->preferredHeight() * outgoingNotificationToScale;
QPointF assistantNotificationFromPos
= QPointF(assistantNotificationFromPosX, assistantNotificationFromPosY);
qreal outgoingNotificationXMoveMent
= outgoingNotificationToPos.x() - outgoingNotificationFromPos.x();
QPointF assistantNotificationToPos
= QPointF(assistantNotificationFromPos.x() + outgoingNotificationXMoveMent,
assistantNotificationToPosY);
assistantNotification->updateScale(assistantNotificationFromScale);
assistantNotification->updateOpacity(style()->initialEdgeOpacity());
assistantNotification->updatePos(assistantNotificationFromPos);
assistantNotification->setVisible(true);
assistantNotificationParameters->setPositionRange(
assistantNotificationFromPos, assistantNotificationToPos);
assistantNotificationParameters->setScaleRange(assistantNotificationFromScale,
assistantNotificationFromScale * outgoingNotificationToScale);
assistantNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
0.0);
assistantNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
assistantNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
assistantNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
}
void NotificationArea::setOutgoingLayoutTitle(const QString &title)
{
mOutgoingLayoutTitle = title;
outgoingNotification->setText(title);
}
QString NotificationArea::outgoingLayoutTitle() const
{
return mOutgoingLayoutTitle;
}
void NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction,
const QString &title)
{
if (direction == PanGesture::PanRight)
mRightLayoutTitle = title;
else
mLeftLayoutTitle = title;
}
QString NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction) const
{
if (direction == PanGesture::PanRight)
return mRightLayoutTitle;
else
return mLeftLayoutTitle;
}
void NotificationArea::playShowAnimation()
{
setOpacity(style()->initialOpacity());
setVisible(true);
showAnimation.start();
}
void NotificationArea::playHideAnimation(PanGesture::PanDirection result)
{
showAnimation.stop();
Notification *resultNotification = incomingNotification;
if (result == PanGesture::PanNone) {
incomingNotification->setVisible(false);
assistantNotification->setVisible(false);
resultNotification = outgoingNotification;
}
setVisible(true);
hideAnimationGroup.clear();
QPropertyAnimation *bgAnimation = new QPropertyAnimation(this);
bgAnimation->setTargetObject(this);
bgAnimation->setPropertyName("opacity");
bgAnimation->setStartValue(1.0);
bgAnimation->setEndValue(0.0);
bgAnimation->setEasingCurve(style()->hideAnimationCurve());
bgAnimation->setDuration(style()->hideAnimationDuration());
QPropertyAnimation *itemAnimation = new QPropertyAnimation(this);
itemAnimation->setTargetObject(resultNotification);
itemAnimation->setPropertyName("opacity");
itemAnimation->setStartValue(this->opacity());
itemAnimation->setEndValue(0.0);
itemAnimation->setEasingCurve(style()->hideAnimationCurve());
itemAnimation->setDuration(style()->hideAnimationDuration());
hideAnimationGroup.addAnimation(bgAnimation);
hideAnimationGroup.addAnimation(itemAnimation);
hideAnimationGroup.start();
}
void NotificationArea::onNotificationAnimationFinished()
{
qDebug() << __PRETTY_FUNCTION__;
showAnimation.stop();
hideAnimationGroup.stop();
hideAnimationGroup.clear();
setVisible(false);
}
void NotificationArea::cancel()
{
onNotificationAnimationFinished();
}
void NotificationArea::setProgress(qreal progress)
{
outgoingNotificationParameters->setProgress(progress);
incomingNotificationParameters->setProgress(progress);
assistantNotificationParameters->setProgress(progress);
}
void NotificationArea::applyStyle()
{
showAnimation.setEasingCurve(style()->showAnimationCurve());
showAnimation.setDuration(style()->showAnimationDuration());
showAnimation.setStartValue(style()->initialOpacity());
showAnimation.setEndValue(style()->visibleOpacity());
}
void NotificationArea::reset()
{
setOutgoingLayoutTitle("");
setIncomingLayoutTitle(PanGesture::PanLeft, "");
setIncomingLayoutTitle(PanGesture::PanRight, "");
}
<commit_msg>Changes: notification can smoothly change animation between hide and show<commit_after>/*
* This file is part of meego-keyboard
*
* Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: Mohammad Anwari <Mohammad.Anwari@nokia.com>
*
* 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 Nokia Corporation nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "notificationarea.h"
#include "notificationpanparameters.h"
#include "mplainwindow.h"
#include "notification.h"
#include <QDebug>
#include <QPainter>
#include <QPropertyAnimation>
#include <MSceneManager>
#include <MScalableImage>
#include <float.h>
NotificationArea::NotificationArea(QGraphicsItem *parent)
: MStylableWidget(parent),
outgoingNotification(new Notification(this)),
incomingNotification(new Notification(this)),
assistantNotification(new Notification(this)),
outgoingNotificationParameters(new NotificationPanParameters(this)),
incomingNotificationParameters(new NotificationPanParameters(this)),
assistantNotificationParameters(new NotificationPanParameters(this)),
hideAnimationGroup(this),
showAnimation(this, "opacity")
{
outgoingNotification->connectPanParameters(outgoingNotificationParameters);
incomingNotification->connectPanParameters(incomingNotificationParameters);
assistantNotification->connectPanParameters(assistantNotificationParameters);
connect(&hideAnimationGroup, SIGNAL(finished()),
this, SLOT(onNotificationAnimationFinished()));
connect(&hideAnimationGroup, SIGNAL(finished()),
this, SLOT(reset()));
setVisible(false);
}
NotificationArea::~NotificationArea()
{
}
void NotificationArea::prepareNotifications(PanGesture::PanDirection direction)
{
qDebug() << __PRETTY_FUNCTION__;
const int screenWidth
= (MPlainWindow::instance()->sceneManager()->orientation() == M::Portrait)
? MPlainWindow::instance()->visibleSceneSize(M::Landscape).height()
: MPlainWindow::instance()->visibleSceneSize(M::Landscape).width();
// prepare notifications
qreal notificationMaximumWidth
= style()->notificationMaximumWidth();
outgoingNotification->setMaximumTextWidth(notificationMaximumWidth);
incomingNotification->setMaximumTextWidth(notificationMaximumWidth);
assistantNotification->setMaximumTextWidth(notificationMaximumWidth);
qreal outgoingNotificationFromScale
= qBound<qreal>(0, qreal(notificationMaximumWidth / outgoingNotification->preferredWidth()), 1.0);
qreal outgoingNotificationToScale
= style()->smallSizeScaleFactor();
QPointF outgoingNotificationFromPos
= QPointF((screenWidth - outgoingNotification->preferredWidth()
* outgoingNotificationFromScale) / 2,
preferredHeight()
- outgoingNotification->preferredHeight()
* outgoingNotificationFromScale);
qreal outgoingNotificationToPosX
= (direction == PanGesture::PanRight)
? screenWidth
: - outgoingNotification->preferredWidth()
* outgoingNotificationToScale;
qreal outgoingNotificationToPosY
= preferredHeight()
- outgoingNotification->preferredHeight() * outgoingNotificationToScale;
QPointF outgoingNotificationToPos
= QPointF(outgoingNotificationToPosX, outgoingNotificationToPosY);
outgoingNotification->updateScale(outgoingNotificationFromScale);
outgoingNotification->updateOpacity(1.0);
outgoingNotification->updatePos(outgoingNotificationFromPos);
outgoingNotification->setVisible(true);
outgoingNotificationParameters->setPositionRange(
outgoingNotificationFromPos, outgoingNotificationToPos);
outgoingNotificationParameters->setScaleRange(outgoingNotificationFromScale,
outgoingNotificationToScale);
outgoingNotificationParameters->setOpacityRange(1.0, 0.0);
outgoingNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
outgoingNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
outgoingNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
qreal leftAndRightSpace
= (outgoingNotification->preferredWidth()
< screenWidth * (1 - style()->initialEdgeMaximumVisibleWidth() * 2))
? screenWidth * style()->initialEdgeMaximumVisibleWidth()
: (screenWidth - notificationMaximumWidth) / 2;
// prepare left and right notifications
if (direction == PanGesture::PanRight) {
incomingNotification->setText(mLeftLayoutTitle);
assistantNotification->setText(mRightLayoutTitle);
} else {
incomingNotification->setText(mRightLayoutTitle);
assistantNotification->setText(mLeftLayoutTitle);
}
qreal incomingNotificationFromScale = outgoingNotificationToScale;
qreal incomingNotificationToScale
= qBound<qreal>(0, qreal(notificationMaximumWidth / incomingNotification->preferredWidth()), 1.0);
qreal incomingNotificationFromPosX = 0;
if (incomingNotification->preferredWidth() * incomingNotificationFromScale
> leftAndRightSpace) {
incomingNotificationFromPosX
= (direction == PanGesture::PanRight)
? leftAndRightSpace
- incomingNotification->preferredWidth() * incomingNotificationFromScale
: screenWidth - leftAndRightSpace;
} else {
incomingNotificationFromPosX
= (direction == PanGesture::PanRight)
? 0
: screenWidth - incomingNotification->preferredWidth() * incomingNotificationFromScale;
}
qreal incomingNotificationFromPosY
= preferredHeight()
- incomingNotification->preferredHeight() * incomingNotificationFromScale;
QPointF incomingNotificationFromPos
= QPointF(incomingNotificationFromPosX, incomingNotificationFromPosY);
QPointF incomingNotificationToPos
= QPointF((screenWidth - incomingNotification->preferredWidth()
* incomingNotificationToScale) / 2,
preferredHeight()
- incomingNotification->preferredHeight()
* incomingNotificationToScale);
incomingNotification->updateScale(incomingNotificationFromScale);
incomingNotification->updatePos(incomingNotificationFromPos);
incomingNotification->updateOpacity(style()->initialEdgeOpacity());
incomingNotification->setVisible(true);
incomingNotificationParameters->setPositionRange(
incomingNotificationFromPos, incomingNotificationToPos);
incomingNotificationParameters->setScaleRange(incomingNotificationFromScale,
incomingNotificationToScale);
incomingNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
1.0);
incomingNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
incomingNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
incomingNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
qreal assistantNotificationFromScale = outgoingNotificationToScale;
qreal assistantNotificationFromPosX = 0;
if (assistantNotification->preferredWidth() * assistantNotificationFromScale
> leftAndRightSpace) {
assistantNotificationFromPosX
= (direction == PanGesture::PanRight)
? screenWidth - leftAndRightSpace
: leftAndRightSpace
- assistantNotification->preferredWidth() * assistantNotificationFromScale;
} else {
assistantNotificationFromPosX
= (direction == PanGesture::PanRight)
? screenWidth - assistantNotification->preferredWidth() * assistantNotificationFromScale
: 0;
}
qreal assistantNotificationFromPosY
= preferredHeight()
- assistantNotification->preferredHeight() * assistantNotificationFromScale;
qreal assistantNotificationToPosY
= preferredHeight()
- assistantNotification->preferredHeight() * outgoingNotificationToScale;
QPointF assistantNotificationFromPos
= QPointF(assistantNotificationFromPosX, assistantNotificationFromPosY);
qreal outgoingNotificationXMoveMent
= outgoingNotificationToPos.x() - outgoingNotificationFromPos.x();
QPointF assistantNotificationToPos
= QPointF(assistantNotificationFromPos.x() + outgoingNotificationXMoveMent,
assistantNotificationToPosY);
assistantNotification->updateScale(assistantNotificationFromScale);
assistantNotification->updateOpacity(style()->initialEdgeOpacity());
assistantNotification->updatePos(assistantNotificationFromPos);
assistantNotification->setVisible(true);
assistantNotificationParameters->setPositionRange(
assistantNotificationFromPos, assistantNotificationToPos);
assistantNotificationParameters->setScaleRange(assistantNotificationFromScale,
assistantNotificationFromScale * outgoingNotificationToScale);
assistantNotificationParameters->setOpacityRange(style()->initialEdgeOpacity(),
0.0);
assistantNotificationParameters->setPositionProgressRange(
style()->positionStartProgress(),
style()->positionEndProgress());
assistantNotificationParameters->setScaleProgressRange(
style()->scaleStartProgress(),
style()->scaleEndProgress());
assistantNotificationParameters->setOpacityProgressRange(
style()->opacityStartProgress(),
style()->opacityEndProgress());
}
void NotificationArea::setOutgoingLayoutTitle(const QString &title)
{
mOutgoingLayoutTitle = title;
outgoingNotification->setText(title);
}
QString NotificationArea::outgoingLayoutTitle() const
{
return mOutgoingLayoutTitle;
}
void NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction,
const QString &title)
{
if (direction == PanGesture::PanRight)
mRightLayoutTitle = title;
else
mLeftLayoutTitle = title;
}
QString NotificationArea::setIncomingLayoutTitle(PanGesture::PanDirection direction) const
{
if (direction == PanGesture::PanRight)
return mRightLayoutTitle;
else
return mLeftLayoutTitle;
}
void NotificationArea::playShowAnimation()
{
if (!isVisible()) {
setVisible(true);
setOpacity(style()->initialOpacity());
}
hideAnimationGroup.stop();
hideAnimationGroup.clear();
// show animation start from current opacity
showAnimation.setStartValue(opacity());
showAnimation.setEndValue(style()->visibleOpacity());
showAnimation.start();
}
void NotificationArea::playHideAnimation(PanGesture::PanDirection result)
{
showAnimation.stop();
Notification *resultNotification = incomingNotification;
if (result == PanGesture::PanNone) {
incomingNotification->setVisible(false);
assistantNotification->setVisible(false);
resultNotification = outgoingNotification;
}
setVisible(true);
hideAnimationGroup.clear();
QPropertyAnimation *bgAnimation = new QPropertyAnimation(this);
bgAnimation->setTargetObject(this);
bgAnimation->setPropertyName("opacity");
bgAnimation->setStartValue(opacity());
bgAnimation->setEndValue(0.0);
bgAnimation->setEasingCurve(style()->hideAnimationCurve());
bgAnimation->setDuration(style()->hideAnimationDuration());
QPropertyAnimation *itemAnimation = new QPropertyAnimation(this);
itemAnimation->setTargetObject(resultNotification);
itemAnimation->setPropertyName("opacity");
itemAnimation->setStartValue(opacity());
itemAnimation->setEndValue(0.0);
itemAnimation->setEasingCurve(style()->hideAnimationCurve());
itemAnimation->setDuration(style()->hideAnimationDuration());
hideAnimationGroup.addAnimation(bgAnimation);
hideAnimationGroup.addAnimation(itemAnimation);
hideAnimationGroup.start();
}
void NotificationArea::onNotificationAnimationFinished()
{
qDebug() << __PRETTY_FUNCTION__;
showAnimation.stop();
hideAnimationGroup.stop();
hideAnimationGroup.clear();
setVisible(false);
}
void NotificationArea::cancel()
{
onNotificationAnimationFinished();
}
void NotificationArea::setProgress(qreal progress)
{
outgoingNotificationParameters->setProgress(progress);
incomingNotificationParameters->setProgress(progress);
assistantNotificationParameters->setProgress(progress);
}
void NotificationArea::applyStyle()
{
showAnimation.setEasingCurve(style()->showAnimationCurve());
showAnimation.setDuration(style()->showAnimationDuration());
showAnimation.setEndValue(style()->visibleOpacity());
}
void NotificationArea::reset()
{
setOutgoingLayoutTitle("");
setIncomingLayoutTitle(PanGesture::PanLeft, "");
setIncomingLayoutTitle(PanGesture::PanRight, "");
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <sal/main.h>
#include <tools/extendapplicationenvironment.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/metric.hxx>
#include <rtl/ustrbuf.hxx>
#include <math.h>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace cppu;
// Forward declaration
void Main();
SAL_IMPLEMENT_MAIN()
{
tools::extendApplicationEnvironment();
Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );
if( !xServiceManager.is() )
Application::Abort( "Failed to bootstrap" );
comphelper::setProcessServiceFactory( xServiceManager );
InitVCL();
::Main();
DeInitVCL();
return 0;
}
class MyWin : public WorkWindow
{
Bitmap m_aBitmap;
public:
MyWin( vcl::Window* pParent, WinBits nWinStyle );
virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
virtual void Resize() SAL_OVERRIDE;
};
void Main()
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( OUString( "VCL - Workbench" ) );
aMainWin.Show();
Application::Execute();
}
MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle ),
m_aBitmap( Size( 256, 256 ), 32 )
{
// prepare an alpha mask
BitmapWriteAccess* pAcc = m_aBitmap.AcquireWriteAccess();
for( int nX = 0; nX < 256; nX++ )
{
for( int nY = 0; nY < 256; nY++ )
{
double fRed = 255.0-1.5*sqrt((double)(nX*nX+nY*nY));
if( fRed < 0.0 )
fRed = 0.0;
double fGreen = 255.0-1.5*sqrt((double)(((255-nX)*(255-nX)+nY*nY)));
if( fGreen < 0.0 )
fGreen = 0.0;
double fBlue = 255.0-1.5*sqrt((double)((128-nX)*(128-nX)+(255-nY)*(255-nY)));
if( fBlue < 0.0 )
fBlue = 0.0;
pAcc->SetPixel( nY, nX, BitmapColor( sal_uInt8(fRed), sal_uInt8(fGreen), sal_uInt8(fBlue) ) );
}
}
m_aBitmap.ReleaseAccess( pAcc );
}
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonDown( rMEvt );
}
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
static Point project( const Point& rPoint )
{
const double angle_x = M_PI / 6.0;
const double angle_z = M_PI / 6.0;
// transform planar coordinates to 3d
double x = rPoint.X();
double y = rPoint.Y();
// rotate around X axis
double x1 = x;
double y1 = y * cos( angle_x );
double z1 = y * sin( angle_x );
// rotate around Z axis
double x2 = x1 * cos( angle_z ) + y1 * sin( angle_z );
//double y2 = y1 * cos( angle_z ) - x1 * sin( angle_z );
double z2 = z1;
return Point( (sal_Int32)x2, (sal_Int32)z2 );
}
static Color approachColor( const Color& rFrom, const Color& rTo )
{
Color aColor;
sal_uInt8 nDiff;
// approach red
if( rFrom.GetRed() < rTo.GetRed() )
{
nDiff = rTo.GetRed() - rFrom.GetRed();
aColor.SetRed( rFrom.GetRed() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetRed() > rTo.GetRed() )
{
nDiff = rFrom.GetRed() - rTo.GetRed();
aColor.SetRed( rFrom.GetRed() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetRed( rFrom.GetRed() );
// approach Green
if( rFrom.GetGreen() < rTo.GetGreen() )
{
nDiff = rTo.GetGreen() - rFrom.GetGreen();
aColor.SetGreen( rFrom.GetGreen() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetGreen() > rTo.GetGreen() )
{
nDiff = rFrom.GetGreen() - rTo.GetGreen();
aColor.SetGreen( rFrom.GetGreen() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetGreen( rFrom.GetGreen() );
// approach blue
if( rFrom.GetBlue() < rTo.GetBlue() )
{
nDiff = rTo.GetBlue() - rFrom.GetBlue();
aColor.SetBlue( rFrom.GetBlue() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetBlue() > rTo.GetBlue() )
{
nDiff = rFrom.GetBlue() - rTo.GetBlue();
aColor.SetBlue( rFrom.GetBlue() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetBlue( rFrom.GetBlue() );
return aColor;
}
#define DELTA 5.0
void MyWin::Paint( const Rectangle& rRect )
{
WorkWindow::Paint( rRect );
Push( PushFlags::ALL );
MapMode aMapMode( MAP_100TH_MM );
SetMapMode( aMapMode );
Size aPaperSize = GetOutputSize();
Point aCenter( aPaperSize.Width()/2-300,
(aPaperSize.Height() - 8400)/2 + 8400 );
Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint;
DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) );
DrawRect( Rectangle( Point( 100,100 ),
Size( aPaperSize.Width()-200,
aPaperSize.Height()-200 ) ) );
DrawRect( Rectangle( Point( 200,200 ),
Size( aPaperSize.Width()-400,
aPaperSize.Height()-400 ) ) );
DrawRect( Rectangle( Point( 300,300 ),
Size( aPaperSize.Width()-600,
aPaperSize.Height()-600 ) ) );
const int nFontCount = GetDevFontCount();
const int nFontSamples = (nFontCount<15) ? nFontCount : 15;
for( int i = 0; i < nFontSamples; ++i )
{
vcl::FontInfo aFont = GetDevFont( (i*nFontCount) / nFontSamples );
aFont.SetHeight( 400 + (i%7) * 100 );
aFont.SetOrientation( i * (3600 / nFontSamples) );
SetFont( aFont );
sal_uInt8 nRed = (i << 6) & 0xC0;
sal_uInt8 nGreen = (i << 4) & 0xC0;
sal_uInt8 nBlue = (i << 2) & 0xC0;
SetTextColor( Color( nRed, nGreen, nBlue ) );
OUStringBuffer aPrintText(1024);
long nMaxWidth = 0;
aPrintText.appendAscii( "SVP test program" );
DrawText( Rectangle( Point( (aPaperSize.Width() - 4000) / 2, 2000 ),
Size( aPaperSize.Width() - 2100 - nMaxWidth,
aPaperSize.Height() - 4000 ) ),
aPrintText.makeStringAndClear(),
TEXT_DRAW_MULTILINE );
}
SetFillColor();
DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ),
Size( 3000,3000 ) ) );
DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ),
Size( 3000,3000 ),
m_aBitmap );
Color aWhite( 0xff, 0xff, 0xff );
Color aBlack( 0, 0, 0 );
Color aLightRed( 0xff, 0, 0 );
Color aDarkRed( 0x40, 0, 0 );
Color aLightBlue( 0, 0, 0xff );
Color aDarkBlue( 0,0,0x40 );
Color aLightGreen( 0, 0xff, 0 );
Color aDarkGreen( 0, 0x40, 0 );
Gradient aGradient( GradientStyle_LINEAR, aBlack, aWhite );
aGradient.SetAngle( 900 );
DrawGradient( Rectangle( Point( 1000, 4500 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkRed );
aGradient.SetEndColor( aLightBlue );
DrawGradient( Rectangle( Point( 1000, 5300 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkBlue );
aGradient.SetEndColor( aLightGreen );
DrawGradient( Rectangle( Point( 1000, 6100 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkGreen );
aGradient.SetEndColor( aLightRed );
DrawGradient( Rectangle( Point( 1000, 6900 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
LineInfo aLineInfo( LINE_SOLID, 200 );
double sind = sin( DELTA*M_PI/180.0 );
double cosd = cos( DELTA*M_PI/180.0 );
double factor = 1 + (DELTA/1000.0);
int n=0;
Color aLineColor( 0, 0, 0 );
Color aApproachColor( 0, 0, 200 );
while ( aP2.X() < aCenter.X() && n++ < 680 )
{
aLineInfo.SetWidth( n/3 );
aLineColor = approachColor( aLineColor, aApproachColor );
SetLineColor( aLineColor );
// switch aproach color
if( aApproachColor.IsRGBEqual( aLineColor ) )
{
if( aApproachColor.GetRed() )
aApproachColor = Color( 0, 0, 200 );
else if( aApproachColor.GetGreen() )
aApproachColor = Color( 200, 0, 0 );
else
aApproachColor = Color( 0, 200, 0 );
}
DrawLine( project( aP1 ) + aCenter,
project( aP2 ) + aCenter,
aLineInfo );
aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor);
aPoint.Y() = (int)((((double)aP1.Y())*cosd + ((double)aP1.X())*sind)*factor);
aP1 = aPoint;
aPoint.X() = (int)((((double)aP2.X())*cosd - ((double)aP2.Y())*sind)*factor);
aPoint.Y() = (int)((((double)aP2.Y())*cosd + ((double)aP2.X())*sind)*factor);
aP2 = aPoint;
}
Pop();
}
void MyWin::Resize()
{
WorkWindow::Resize();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1215391 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <sal/main.h>
#include <tools/extendapplicationenvironment.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/metric.hxx>
#include <rtl/ustrbuf.hxx>
#include <math.h>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace cppu;
// Forward declaration
void Main();
SAL_IMPLEMENT_MAIN()
{
try
{
tools::extendApplicationEnvironment();
Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext();
Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY );
if( !xServiceManager.is() )
Application::Abort( "Failed to bootstrap" );
comphelper::setProcessServiceFactory( xServiceManager );
InitVCL();
::Main();
DeInitVCL();
}
catch (const Exception& e)
{
SAL_WARN("vcl.app", "Fatal exception: " << e.Message);
return 1;
}
return 0;
}
class MyWin : public WorkWindow
{
Bitmap m_aBitmap;
public:
MyWin( vcl::Window* pParent, WinBits nWinStyle );
virtual void MouseMove( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void MouseButtonDown( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void MouseButtonUp( const MouseEvent& rMEvt ) SAL_OVERRIDE;
virtual void KeyInput( const KeyEvent& rKEvt ) SAL_OVERRIDE;
virtual void KeyUp( const KeyEvent& rKEvt ) SAL_OVERRIDE;
virtual void Paint( const Rectangle& rRect ) SAL_OVERRIDE;
virtual void Resize() SAL_OVERRIDE;
};
void Main()
{
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( OUString( "VCL - Workbench" ) );
aMainWin.Show();
Application::Execute();
}
MyWin::MyWin( vcl::Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle ),
m_aBitmap( Size( 256, 256 ), 32 )
{
// prepare an alpha mask
BitmapWriteAccess* pAcc = m_aBitmap.AcquireWriteAccess();
for( int nX = 0; nX < 256; nX++ )
{
for( int nY = 0; nY < 256; nY++ )
{
double fRed = 255.0-1.5*sqrt((double)(nX*nX+nY*nY));
if( fRed < 0.0 )
fRed = 0.0;
double fGreen = 255.0-1.5*sqrt((double)(((255-nX)*(255-nX)+nY*nY)));
if( fGreen < 0.0 )
fGreen = 0.0;
double fBlue = 255.0-1.5*sqrt((double)((128-nX)*(128-nX)+(255-nY)*(255-nY)));
if( fBlue < 0.0 )
fBlue = 0.0;
pAcc->SetPixel( nY, nX, BitmapColor( sal_uInt8(fRed), sal_uInt8(fGreen), sal_uInt8(fBlue) ) );
}
}
m_aBitmap.ReleaseAccess( pAcc );
}
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonDown( rMEvt );
}
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
static Point project( const Point& rPoint )
{
const double angle_x = M_PI / 6.0;
const double angle_z = M_PI / 6.0;
// transform planar coordinates to 3d
double x = rPoint.X();
double y = rPoint.Y();
// rotate around X axis
double x1 = x;
double y1 = y * cos( angle_x );
double z1 = y * sin( angle_x );
// rotate around Z axis
double x2 = x1 * cos( angle_z ) + y1 * sin( angle_z );
//double y2 = y1 * cos( angle_z ) - x1 * sin( angle_z );
double z2 = z1;
return Point( (sal_Int32)x2, (sal_Int32)z2 );
}
static Color approachColor( const Color& rFrom, const Color& rTo )
{
Color aColor;
sal_uInt8 nDiff;
// approach red
if( rFrom.GetRed() < rTo.GetRed() )
{
nDiff = rTo.GetRed() - rFrom.GetRed();
aColor.SetRed( rFrom.GetRed() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetRed() > rTo.GetRed() )
{
nDiff = rFrom.GetRed() - rTo.GetRed();
aColor.SetRed( rFrom.GetRed() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetRed( rFrom.GetRed() );
// approach Green
if( rFrom.GetGreen() < rTo.GetGreen() )
{
nDiff = rTo.GetGreen() - rFrom.GetGreen();
aColor.SetGreen( rFrom.GetGreen() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetGreen() > rTo.GetGreen() )
{
nDiff = rFrom.GetGreen() - rTo.GetGreen();
aColor.SetGreen( rFrom.GetGreen() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetGreen( rFrom.GetGreen() );
// approach blue
if( rFrom.GetBlue() < rTo.GetBlue() )
{
nDiff = rTo.GetBlue() - rFrom.GetBlue();
aColor.SetBlue( rFrom.GetBlue() + ( nDiff < 10 ? nDiff : 10 ) );
}
else if( rFrom.GetBlue() > rTo.GetBlue() )
{
nDiff = rFrom.GetBlue() - rTo.GetBlue();
aColor.SetBlue( rFrom.GetBlue() - ( nDiff < 10 ? nDiff : 10 ) );
}
else
aColor.SetBlue( rFrom.GetBlue() );
return aColor;
}
#define DELTA 5.0
void MyWin::Paint( const Rectangle& rRect )
{
WorkWindow::Paint( rRect );
Push( PushFlags::ALL );
MapMode aMapMode( MAP_100TH_MM );
SetMapMode( aMapMode );
Size aPaperSize = GetOutputSize();
Point aCenter( aPaperSize.Width()/2-300,
(aPaperSize.Height() - 8400)/2 + 8400 );
Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint;
DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) );
DrawRect( Rectangle( Point( 100,100 ),
Size( aPaperSize.Width()-200,
aPaperSize.Height()-200 ) ) );
DrawRect( Rectangle( Point( 200,200 ),
Size( aPaperSize.Width()-400,
aPaperSize.Height()-400 ) ) );
DrawRect( Rectangle( Point( 300,300 ),
Size( aPaperSize.Width()-600,
aPaperSize.Height()-600 ) ) );
const int nFontCount = GetDevFontCount();
const int nFontSamples = (nFontCount<15) ? nFontCount : 15;
for( int i = 0; i < nFontSamples; ++i )
{
vcl::FontInfo aFont = GetDevFont( (i*nFontCount) / nFontSamples );
aFont.SetHeight( 400 + (i%7) * 100 );
aFont.SetOrientation( i * (3600 / nFontSamples) );
SetFont( aFont );
sal_uInt8 nRed = (i << 6) & 0xC0;
sal_uInt8 nGreen = (i << 4) & 0xC0;
sal_uInt8 nBlue = (i << 2) & 0xC0;
SetTextColor( Color( nRed, nGreen, nBlue ) );
OUStringBuffer aPrintText(1024);
long nMaxWidth = 0;
aPrintText.appendAscii( "SVP test program" );
DrawText( Rectangle( Point( (aPaperSize.Width() - 4000) / 2, 2000 ),
Size( aPaperSize.Width() - 2100 - nMaxWidth,
aPaperSize.Height() - 4000 ) ),
aPrintText.makeStringAndClear(),
TEXT_DRAW_MULTILINE );
}
SetFillColor();
DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ),
Size( 3000,3000 ) ) );
DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ),
Size( 3000,3000 ),
m_aBitmap );
Color aWhite( 0xff, 0xff, 0xff );
Color aBlack( 0, 0, 0 );
Color aLightRed( 0xff, 0, 0 );
Color aDarkRed( 0x40, 0, 0 );
Color aLightBlue( 0, 0, 0xff );
Color aDarkBlue( 0,0,0x40 );
Color aLightGreen( 0, 0xff, 0 );
Color aDarkGreen( 0, 0x40, 0 );
Gradient aGradient( GradientStyle_LINEAR, aBlack, aWhite );
aGradient.SetAngle( 900 );
DrawGradient( Rectangle( Point( 1000, 4500 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkRed );
aGradient.SetEndColor( aLightBlue );
DrawGradient( Rectangle( Point( 1000, 5300 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkBlue );
aGradient.SetEndColor( aLightGreen );
DrawGradient( Rectangle( Point( 1000, 6100 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
aGradient.SetStartColor( aDarkGreen );
aGradient.SetEndColor( aLightRed );
DrawGradient( Rectangle( Point( 1000, 6900 ),
Size( aPaperSize.Width() - 2000,
500 ) ), aGradient );
LineInfo aLineInfo( LINE_SOLID, 200 );
double sind = sin( DELTA*M_PI/180.0 );
double cosd = cos( DELTA*M_PI/180.0 );
double factor = 1 + (DELTA/1000.0);
int n=0;
Color aLineColor( 0, 0, 0 );
Color aApproachColor( 0, 0, 200 );
while ( aP2.X() < aCenter.X() && n++ < 680 )
{
aLineInfo.SetWidth( n/3 );
aLineColor = approachColor( aLineColor, aApproachColor );
SetLineColor( aLineColor );
// switch aproach color
if( aApproachColor.IsRGBEqual( aLineColor ) )
{
if( aApproachColor.GetRed() )
aApproachColor = Color( 0, 0, 200 );
else if( aApproachColor.GetGreen() )
aApproachColor = Color( 200, 0, 0 );
else
aApproachColor = Color( 0, 200, 0 );
}
DrawLine( project( aP1 ) + aCenter,
project( aP2 ) + aCenter,
aLineInfo );
aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor);
aPoint.Y() = (int)((((double)aP1.Y())*cosd + ((double)aP1.X())*sind)*factor);
aP1 = aPoint;
aPoint.X() = (int)((((double)aP2.X())*cosd - ((double)aP2.Y())*sind)*factor);
aPoint.Y() = (int)((((double)aP2.Y())*cosd + ((double)aP2.X())*sind)*factor);
aP2 = aPoint;
}
Pop();
}
void MyWin::Resize()
{
WorkWindow::Resize();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vcldemo.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-07-05 15:56:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/introwin.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <unistd.h>
#include <stdio.h>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------
// Forward declaration
void Main();
// -----------------------------------------------------------------------
SAL_IMPLEMENT_MAIN()
{
Reference< XMultiServiceFactory > xMS;
xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );
InitVCL( xMS );
::Main();
DeInitVCL();
return 0;
}
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
public:
MyWin( Window* pParent, WinBits nWinStyle );
void MouseMove( const MouseEvent& rMEvt );
void MouseButtonDown( const MouseEvent& rMEvt );
void MouseButtonUp( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
void KeyUp( const KeyEvent& rKEvt );
void Paint( const Rectangle& rRect );
void Resize();
};
// -----------------------------------------------------------------------
void Main()
{
/*
IntroWindow splash;
splash.Show();
sleep(5);
splash.Hide();
*/
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCLDemo - VCL Workbench" ) ) );
aMainWin.Show();
/*
InfoBox ib(NULL, String((sal_Char*)"Test", sizeof("Test")));
ib.Execute();
*/
Application::Execute();
}
// -----------------------------------------------------------------------
MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle )
{
}
// -----------------------------------------------------------------------
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
Rectangle aRect(0,0,4,4);
aRect.SetPos( rMEvt.GetPosPixel() );
SetFillColor(Color(COL_RED));
DrawRect( aRect );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& rRect )
{
fprintf(stderr, "MyWin::Paint(%ld,%ld,%ld,%ld)\n", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());
Size aSz(GetSizePixel());
Point aPt;
Rectangle r(aPt, aSz);
SetFillColor(Color(COL_BLUE));
SetLineColor(Color(COL_YELLOW));
DrawRect( r );
for(int i=0; i<aSz.Height(); i+=15)
DrawLine( Point(r.nLeft, r.nTop+i), Point(r.nRight, r.nBottom-i) );
for(int i=0; i<aSz.Width(); i+=15)
DrawLine( Point(r.nLeft+i, r.nBottom), Point(r.nRight-i, r.nTop) );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
WorkWindow::Resize();
}
<commit_msg>INTEGRATION: CWS aquavcl03 (1.3.4); FILE MERGED 2007/07/26 11:02:27 pl 1.3.4.1: #i80025# initial checking for carbon to cocoa migration<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vcldemo.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:22:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <sal/main.h>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/introwin.hxx>
#include <vcl/msgbox.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <unistd.h>
#include <stdio.h>
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
// -----------------------------------------------------------------------
// Forward declaration
void Main();
// -----------------------------------------------------------------------
SAL_IMPLEMENT_MAIN()
{
Reference< XMultiServiceFactory > xMS;
xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True );
InitVCL( xMS );
::Main();
DeInitVCL();
return 0;
}
// -----------------------------------------------------------------------
class MyWin : public WorkWindow
{
public:
MyWin( Window* pParent, WinBits nWinStyle );
void MouseMove( const MouseEvent& rMEvt );
void MouseButtonDown( const MouseEvent& rMEvt );
void MouseButtonUp( const MouseEvent& rMEvt );
void KeyInput( const KeyEvent& rKEvt );
void KeyUp( const KeyEvent& rKEvt );
void Paint( const Rectangle& rRect );
void Resize();
};
// -----------------------------------------------------------------------
void Main()
{
/*
IntroWindow splash;
splash.Show();
sleep(5);
splash.Hide();
*/
MyWin aMainWin( NULL, WB_APP | WB_STDWORK );
aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCLDemo - VCL Workbench" ) ) );
aMainWin.Show();
/*
InfoBox ib(NULL, String((sal_Char*)"Test", sizeof("Test")));
ib.Execute();
*/
Application::Execute();
}
// -----------------------------------------------------------------------
MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
WorkWindow( pParent, nWinStyle )
{
}
// -----------------------------------------------------------------------
void MyWin::MouseMove( const MouseEvent& rMEvt )
{
WorkWindow::MouseMove( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonDown( const MouseEvent& rMEvt )
{
Rectangle aRect(0,0,4,4);
aRect.SetPos( rMEvt.GetPosPixel() );
SetFillColor(Color(COL_RED));
DrawRect( aRect );
}
// -----------------------------------------------------------------------
void MyWin::MouseButtonUp( const MouseEvent& rMEvt )
{
WorkWindow::MouseButtonUp( rMEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyInput( const KeyEvent& rKEvt )
{
WorkWindow::KeyInput( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::KeyUp( const KeyEvent& rKEvt )
{
WorkWindow::KeyUp( rKEvt );
}
// -----------------------------------------------------------------------
void MyWin::Paint( const Rectangle& rRect )
{
fprintf(stderr, "MyWin::Paint(%ld,%ld,%ld,%ld)\n", rRect.getX(), rRect.getY(), rRect.getWidth(), rRect.getHeight());
Size aSz(GetSizePixel());
Point aPt;
Rectangle r(aPt, aSz);
SetFillColor(Color(COL_BLUE));
SetLineColor(Color(COL_YELLOW));
DrawRect( r );
for(int i=0; i<aSz.Height(); i+=15)
DrawLine( Point(r.nLeft, r.nTop+i), Point(r.nRight, r.nBottom-i) );
for(int i=0; i<aSz.Width(); i+=15)
DrawLine( Point(r.nLeft+i, r.nBottom), Point(r.nRight-i, r.nTop) );
SetTextColor( Color( COL_WHITE ) );
Font aFont( String( RTL_CONSTASCII_USTRINGPARAM( "Times" ) ), Size( 0, 25 ) );
SetFont( aFont );
DrawText( Point( 20, 30 ), String( RTL_CONSTASCII_USTRINGPARAM( "Just a simple test text" ) ) );
}
// -----------------------------------------------------------------------
void MyWin::Resize()
{
WorkWindow::Resize();
}
<|endoftext|>
|
<commit_before><commit_msg>use different line and fill colors<commit_after><|endoftext|>
|
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <cstdlib>
#include "MemoryOutputStream.hh"
#include "RLEv1.hh"
#include "wrap/orc-proto-wrapper.hh"
#include "wrap/gtest-wrapper.h"
#ifdef __clang__
DIAGNOSTIC_IGNORE("-Wmissing-variable-declarations")
#endif
namespace orc {
using ::testing::TestWithParam;
using ::testing::Values;
const int DEFAULT_MEM_STREAM_SIZE = 1024 * 1024; // 1M
class RleTest : public TestWithParam<bool> {
virtual void SetUp();
protected:
bool alignBitpacking;
std::unique_ptr<RleEncoder> getEncoder(RleVersion version,
MemoryOutputStream& memStream,
bool isSigned);
void runExampleTest(int64_t* inputData, uint64_t inputLength,
unsigned char* expectedOutput, uint64_t outputLength);
void runTest(RleVersion version,
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
bool isSigned,
uint64_t numNulls = 0);
};
void RleTest::SetUp() {
alignBitpacking = GetParam();
}
void generateData(
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
int64_t* data,
uint64_t numNulls = 0,
char* notNull = nullptr) {
if (numNulls != 0 && notNull != nullptr) {
memset(notNull, 1, numValues);
while (numNulls > 0) {
uint64_t pos = static_cast<uint64_t>(std::rand()) % numValues;
if (notNull[pos]) {
notNull[pos] = static_cast<char>(0);
--numNulls;
}
}
}
for (uint64_t i = 0; i < numValues; ++i) {
if (notNull == nullptr || notNull[i])
{
if (!random) {
data[i] = start + delta * static_cast<int64_t>(i);
} else {
data[i] = std::rand();
}
}
}
}
void decodeAndVerify(
RleVersion version,
const MemoryOutputStream& memStream,
int64_t * data,
uint64_t numValues,
const char* notNull,
bool isSinged) {
std::unique_ptr<RleDecoder> decoder = createRleDecoder(
std::unique_ptr<SeekableArrayInputStream>(new SeekableArrayInputStream(
memStream.getData(),
memStream.getLength())),
isSinged, version, *getDefaultPool());
int64_t* decodedData = new int64_t[numValues];
decoder->next(decodedData, numValues, notNull);
for (uint64_t i = 0; i < numValues; ++i) {
if (!notNull || notNull[i]) {
EXPECT_EQ(data[i], decodedData[i]);
}
}
delete [] decodedData;
}
std::unique_ptr<RleEncoder> RleTest::getEncoder(RleVersion version,
MemoryOutputStream& memStream,
bool isSigned)
{
MemoryPool * pool = getDefaultPool();
return createRleEncoder(
std::unique_ptr<BufferedOutputStream>(
new BufferedOutputStream(*pool, &memStream, 500 * 1024, 1024)),
isSigned, version, *pool, alignBitpacking);
}
void RleTest::runExampleTest(int64_t* inputData,
uint64_t inputLength,
unsigned char* expectedOutput,
uint64_t outputLength) {
MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE);
std::unique_ptr<RleEncoder> encoder = getEncoder(RleVersion_2, memStream, false);
encoder->add(inputData, inputLength, nullptr);
encoder->flush();
const char* output = memStream.getData();
for(int i = 0; i < outputLength; i++) {
EXPECT_EQ(expectedOutput[i], static_cast<unsigned char>(output[i]));
}
}
void RleTest::runTest(RleVersion version,
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
bool isSigned,
uint64_t numNulls) {
MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE);
std::unique_ptr<RleEncoder> encoder = getEncoder(version, memStream, isSigned);
char* notNull = numNulls == 0 ? nullptr : new char[numValues];
int64_t* data = new int64_t[numValues];
generateData(numValues, start, delta, random, data, numNulls, notNull);
encoder->add(data, numValues, notNull);
encoder->flush();
decodeAndVerify(version, memStream, data, numValues, notNull, isSigned);
delete [] data;
delete [] notNull;
}
TEST_P(RleTest, RleV1_delta_increasing_sequance_unsigned) {
runTest(RleVersion_1, 1024, 0, 1, false, false);
}
TEST_P(RleTest, RleV1_delta_increasing_sequance_unsigned_null) {
runTest(RleVersion_1, 1024, 0, 1, false, false, 100);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_unsigned) {
runTest(RleVersion_1, 1024, 5000, -3, false, false);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_signed) {
runTest(RleVersion_1, 1024, 100, -3, false, true);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_signed_null) {
runTest(RleVersion_1, 1024, 100, -3, false, true, 500);
}
TEST_P(RleTest, rRleV1_andom_sequance_signed) {
runTest(RleVersion_1, 1024, 0, 0, true, true);
}
TEST_P(RleTest, RleV1_all_null) {
runTest(RleVersion_1, 1024, 100, -3, false, true, 1024);
}
TEST_P(RleTest, RleV2_delta_increasing_sequance_unsigned) {
runTest(RleVersion_2, 1024, 0, 1, false, false);
}
TEST_P(RleTest, RleV2_delta_increasing_sequance_unsigned_null) {
runTest(RleVersion_2, 1024, 0, 1, false, false, 100);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_unsigned) {
runTest(RleVersion_2, 1024, 5000, -3, false, false);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_signed) {
runTest(RleVersion_2, 1024, 100, -3, false, true);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_signed_null) {
runTest(RleVersion_2, 1024, 100, -3, false, true, 500);
}
TEST_P(RleTest, RleV2_random_sequance_signed) {
runTest(RleVersion_2, 1024, 0, 0, true, true);
}
TEST_P(RleTest, RleV2_all_null) {
runTest(RleVersion_2, 1024, 100, -3, false, true, 1024);
}
TEST_P(RleTest, RleV2_delta_zero_unsigned) {
runTest(RleVersion_2, 1024, 123, 0, false, false);
}
TEST_P(RleTest, RleV2_delta_zero_signed) {
runTest(RleVersion_2, 1024, 123, 0, false, true);
}
TEST_P(RleTest, RleV2_short_repeat) {
runTest(RleVersion_2, 8, 123, 0, false, false);
}
TEST_P(RleTest, RleV2_short_repeat_example) {
int64_t data[5] = {10000, 10000, 10000, 10000, 10000};
unsigned char expectedEncoded[3] = {0x0a, 0x27, 0x10};
runExampleTest(data, 5, expectedEncoded, 3);
}
TEST_P(RleTest, RleV2_direct_example) {
int64_t data[4] = {23713, 43806, 57005, 48879};
unsigned char expectedEncoded[10] = {0x5e, 0x03, 0x5c, 0xa1, 0xab, 0x1e, 0xde, 0xad, 0xbe, 0xef};
runExampleTest(data, 4, expectedEncoded, 10);
}
TEST_P(RleTest, RleV2_Patched_base_example) {
int64_t data[20] = {2030, 2000, 2020, 1000000, 2040, 2050, 2060, 2070, 2080,
2090, 2100, 2110, 2120, 2130, 2140, 2150, 2160, 2170, 2180, 2190};
unsigned char expectedEncoded[28] = {0x8e, 0x13, 0x2b, 0x21, 0x07, 0xd0, 0x1e, 0x00, 0x14,
0x70, 0x28, 0x32, 0x3c, 0x46, 0x50, 0x5a, 0x64, 0x6e, 0x78, 0x82, 0x8c,
0x96, 0xa0, 0xaa, 0xb4, 0xbe, 0xfc, 0xe8};
runExampleTest(data, 20, expectedEncoded, 28);
}
TEST_P(RleTest, RleV2_delta_example) {
int64_t data[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
unsigned char expectedEncoded[8] = {0xc6, 0x09, 0x02, 0x02, 0x22, 0x42, 0x42, 0x46};
unsigned char unalignedExpectedEncoded[7] = {0xc4, 0x09, 0x02, 0x02, 0x4A, 0x28, 0xA6};
if (alignBitpacking)
{
runExampleTest(data, 10, expectedEncoded, 8);
}
else
{
runExampleTest(data, 10, unalignedExpectedEncoded, 7);
}
}
TEST_P(RleTest, RleV2_delta_example2) {
int64_t data[7] = {0, 10000, 10001, 10001, 10002, 10003, 10003};
unsigned char expectedEncoded[8] = {0xc2, 0x06, 0x0, 0xa0, 0x9c, 0x01, 0x45, 0x0};
runExampleTest(data, 7, expectedEncoded, 8);
}
TEST_P(RleTest, RleV2_direct_repeat_example2) {
int64_t data[9] = {23713, 43806, 57005, 48879, 10000, 10000, 10000, 10000, 10000};
unsigned char expectedEncoded[13] = {0x5e, 0x03, 0x5c, 0xa1, 0xab, 0x1e, 0xde, 0xad, 0xbe, 0xef, 0x0a, 0x27, 0x10};
runExampleTest(data, 9, expectedEncoded, 13);
}
INSTANTIATE_TEST_CASE_P(OrcTest, RleTest, Values(true, false));
}
<commit_msg>ORC-465: [C++] add a test for PATCHED_BASE with a big gap. (#362)<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <cstdlib>
#include "MemoryOutputStream.hh"
#include "RLEv1.hh"
#include "wrap/orc-proto-wrapper.hh"
#include "wrap/gtest-wrapper.h"
#ifdef __clang__
DIAGNOSTIC_IGNORE("-Wmissing-variable-declarations")
#endif
namespace orc {
using ::testing::TestWithParam;
using ::testing::Values;
const int DEFAULT_MEM_STREAM_SIZE = 1024 * 1024; // 1M
class RleTest : public TestWithParam<bool> {
virtual void SetUp();
protected:
bool alignBitpacking;
std::unique_ptr<RleEncoder> getEncoder(RleVersion version,
MemoryOutputStream& memStream,
bool isSigned);
void runExampleTest(int64_t* inputData, uint64_t inputLength,
unsigned char* expectedOutput, uint64_t outputLength);
void runTest(RleVersion version,
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
bool isSigned,
uint64_t numNulls = 0);
};
void RleTest::SetUp() {
alignBitpacking = GetParam();
}
void generateData(
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
int64_t* data,
uint64_t numNulls = 0,
char* notNull = nullptr) {
if (numNulls != 0 && notNull != nullptr) {
memset(notNull, 1, numValues);
while (numNulls > 0) {
uint64_t pos = static_cast<uint64_t>(std::rand()) % numValues;
if (notNull[pos]) {
notNull[pos] = static_cast<char>(0);
--numNulls;
}
}
}
for (uint64_t i = 0; i < numValues; ++i) {
if (notNull == nullptr || notNull[i])
{
if (!random) {
data[i] = start + delta * static_cast<int64_t>(i);
} else {
data[i] = std::rand();
}
}
}
}
void decodeAndVerify(
RleVersion version,
const MemoryOutputStream& memStream,
int64_t * data,
uint64_t numValues,
const char* notNull,
bool isSinged) {
std::unique_ptr<RleDecoder> decoder = createRleDecoder(
std::unique_ptr<SeekableArrayInputStream>(new SeekableArrayInputStream(
memStream.getData(),
memStream.getLength())),
isSinged, version, *getDefaultPool());
int64_t* decodedData = new int64_t[numValues];
decoder->next(decodedData, numValues, notNull);
for (uint64_t i = 0; i < numValues; ++i) {
if (!notNull || notNull[i]) {
EXPECT_EQ(data[i], decodedData[i]);
}
}
delete [] decodedData;
}
std::unique_ptr<RleEncoder> RleTest::getEncoder(RleVersion version,
MemoryOutputStream& memStream,
bool isSigned)
{
MemoryPool * pool = getDefaultPool();
return createRleEncoder(
std::unique_ptr<BufferedOutputStream>(
new BufferedOutputStream(*pool, &memStream, 500 * 1024, 1024)),
isSigned, version, *pool, alignBitpacking);
}
void RleTest::runExampleTest(int64_t* inputData,
uint64_t inputLength,
unsigned char* expectedOutput,
uint64_t outputLength) {
MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE);
std::unique_ptr<RleEncoder> encoder = getEncoder(RleVersion_2, memStream, false);
encoder->add(inputData, inputLength, nullptr);
encoder->flush();
const char* output = memStream.getData();
for(int i = 0; i < outputLength; i++) {
EXPECT_EQ(expectedOutput[i], static_cast<unsigned char>(output[i]));
}
}
void RleTest::runTest(RleVersion version,
uint64_t numValues,
int64_t start,
int64_t delta,
bool random,
bool isSigned,
uint64_t numNulls) {
MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE);
std::unique_ptr<RleEncoder> encoder = getEncoder(version, memStream, isSigned);
char* notNull = numNulls == 0 ? nullptr : new char[numValues];
int64_t* data = new int64_t[numValues];
generateData(numValues, start, delta, random, data, numNulls, notNull);
encoder->add(data, numValues, notNull);
encoder->flush();
decodeAndVerify(version, memStream, data, numValues, notNull, isSigned);
delete [] data;
delete [] notNull;
}
TEST_P(RleTest, RleV1_delta_increasing_sequance_unsigned) {
runTest(RleVersion_1, 1024, 0, 1, false, false);
}
TEST_P(RleTest, RleV1_delta_increasing_sequance_unsigned_null) {
runTest(RleVersion_1, 1024, 0, 1, false, false, 100);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_unsigned) {
runTest(RleVersion_1, 1024, 5000, -3, false, false);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_signed) {
runTest(RleVersion_1, 1024, 100, -3, false, true);
}
TEST_P(RleTest, RleV1_delta_decreasing_sequance_signed_null) {
runTest(RleVersion_1, 1024, 100, -3, false, true, 500);
}
TEST_P(RleTest, rRleV1_andom_sequance_signed) {
runTest(RleVersion_1, 1024, 0, 0, true, true);
}
TEST_P(RleTest, RleV1_all_null) {
runTest(RleVersion_1, 1024, 100, -3, false, true, 1024);
}
TEST_P(RleTest, RleV2_delta_increasing_sequance_unsigned) {
runTest(RleVersion_2, 1024, 0, 1, false, false);
}
TEST_P(RleTest, RleV2_delta_increasing_sequance_unsigned_null) {
runTest(RleVersion_2, 1024, 0, 1, false, false, 100);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_unsigned) {
runTest(RleVersion_2, 1024, 5000, -3, false, false);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_signed) {
runTest(RleVersion_2, 1024, 100, -3, false, true);
}
TEST_P(RleTest, RleV2_delta_decreasing_sequance_signed_null) {
runTest(RleVersion_2, 1024, 100, -3, false, true, 500);
}
TEST_P(RleTest, RleV2_random_sequance_signed) {
runTest(RleVersion_2, 1024, 0, 0, true, true);
}
TEST_P(RleTest, RleV2_all_null) {
runTest(RleVersion_2, 1024, 100, -3, false, true, 1024);
}
TEST_P(RleTest, RleV2_delta_zero_unsigned) {
runTest(RleVersion_2, 1024, 123, 0, false, false);
}
TEST_P(RleTest, RleV2_delta_zero_signed) {
runTest(RleVersion_2, 1024, 123, 0, false, true);
}
TEST_P(RleTest, RleV2_short_repeat) {
runTest(RleVersion_2, 8, 123, 0, false, false);
}
TEST_P(RleTest, RleV2_short_repeat_example) {
int64_t data[5] = {10000, 10000, 10000, 10000, 10000};
unsigned char expectedEncoded[3] = {0x0a, 0x27, 0x10};
runExampleTest(data, 5, expectedEncoded, 3);
}
TEST_P(RleTest, RleV2_direct_example) {
int64_t data[4] = {23713, 43806, 57005, 48879};
unsigned char expectedEncoded[10] = {0x5e, 0x03, 0x5c, 0xa1, 0xab, 0x1e, 0xde, 0xad, 0xbe, 0xef};
runExampleTest(data, 4, expectedEncoded, 10);
}
TEST_P(RleTest, RleV2_Patched_base_example) {
int64_t data[20] = {2030, 2000, 2020, 1000000, 2040, 2050, 2060, 2070, 2080,
2090, 2100, 2110, 2120, 2130, 2140, 2150, 2160, 2170, 2180, 2190};
unsigned char expectedEncoded[28] = {0x8e, 0x13, 0x2b, 0x21, 0x07, 0xd0, 0x1e, 0x00, 0x14,
0x70, 0x28, 0x32, 0x3c, 0x46, 0x50, 0x5a, 0x64, 0x6e, 0x78, 0x82, 0x8c,
0x96, 0xa0, 0xaa, 0xb4, 0xbe, 0xfc, 0xe8};
runExampleTest(data, 20, expectedEncoded, 28);
}
TEST_P(RleTest, RleV2_Patched_base_big_gap) {
// The input data contains 512 values: data[0...510] are of a repeated pattern of (2, 1), and
// the last value (i.e. data[511]) is equal to 1024. This makes the last value to be the
// only patched value and the gap of this patch is 511.
const int numValues = 512;
int64_t data[512];
for (int i = 0; i < 511; i+=2) {
data[i] = 2;
data[i+1] = 1;
}
data[511] = 1024;
// Invoke the encoder.
const bool isSigned = true;
MemoryOutputStream memStream(DEFAULT_MEM_STREAM_SIZE);
std::unique_ptr<RleEncoder> encoder = getEncoder(RleVersion_2, memStream, isSigned);
encoder->add(data, numValues, nullptr);
encoder->flush();
// Decode and verify.
decodeAndVerify(RleVersion_2, memStream, data, numValues, nullptr, isSigned);
}
TEST_P(RleTest, RleV2_delta_example) {
int64_t data[10] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
unsigned char expectedEncoded[8] = {0xc6, 0x09, 0x02, 0x02, 0x22, 0x42, 0x42, 0x46};
unsigned char unalignedExpectedEncoded[7] = {0xc4, 0x09, 0x02, 0x02, 0x4A, 0x28, 0xA6};
if (alignBitpacking)
{
runExampleTest(data, 10, expectedEncoded, 8);
}
else
{
runExampleTest(data, 10, unalignedExpectedEncoded, 7);
}
}
TEST_P(RleTest, RleV2_delta_example2) {
int64_t data[7] = {0, 10000, 10001, 10001, 10002, 10003, 10003};
unsigned char expectedEncoded[8] = {0xc2, 0x06, 0x0, 0xa0, 0x9c, 0x01, 0x45, 0x0};
runExampleTest(data, 7, expectedEncoded, 8);
}
TEST_P(RleTest, RleV2_direct_repeat_example2) {
int64_t data[9] = {23713, 43806, 57005, 48879, 10000, 10000, 10000, 10000, 10000};
unsigned char expectedEncoded[13] = {0x5e, 0x03, 0x5c, 0xa1, 0xab, 0x1e, 0xde, 0xad, 0xbe, 0xef, 0x0a, 0x27, 0x10};
runExampleTest(data, 9, expectedEncoded, 13);
}
INSTANTIATE_TEST_CASE_P(OrcTest, RleTest, Values(true, false));
}
<|endoftext|>
|
<commit_before>#include "in_memory_tracer.h"
#include <lightstep/tracer.h>
#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>
#include <google/protobuf/util/message_differencer.h>
using namespace lightstep;
using namespace opentracing;
namespace lightstep {
std::shared_ptr<Tracer> make_lightstep_tracer(
std::unique_ptr<Recorder>&& recorder);
collector::KeyValue to_key_value(StringRef key, const Value& value);
} // namespace lightstep
//------------------------------------------------------------------------------
// has_tag
//------------------------------------------------------------------------------
static bool has_tag(const collector::Span& span, StringRef key,
const Value& value) {
auto key_value = to_key_value(key, value);
return std::find_if(
std::begin(span.tags()), std::end(span.tags()),
[&](const collector::KeyValue& other) {
return google::protobuf::util::MessageDifferencer::Equals(
key_value, other);
}) != std::end(span.tags());
}
//------------------------------------------------------------------------------
// has_relationship
//------------------------------------------------------------------------------
static bool has_relationship(SpanReferenceType relationship,
const collector::Span& span_a,
const collector::Span& span_b) {
collector::Reference reference;
switch (relationship) {
case SpanReferenceType::ChildOfRef:
reference.set_relationship(collector::Reference::CHILD_OF);
break;
case SpanReferenceType::FollowsFromRef:
reference.set_relationship(collector::Reference::FOLLOWS_FROM);
break;
}
*reference.mutable_span_context() = span_b.span_context();
return std::find_if(
std::begin(span_a.references()), std::end(span_a.references()),
[&](const collector::Reference& other) {
return google::protobuf::util::MessageDifferencer::Equals(
reference, other);
}) != std::end(span_a.references());
}
//------------------------------------------------------------------------------
// tests
//------------------------------------------------------------------------------
TEST_CASE("in_memory_tracer") {
auto recorder = new InMemoryRecorder();
auto tracer = make_lightstep_tracer(std::unique_ptr<Recorder>(recorder));
SECTION("StartSpan applies the provided tags.") {
{
auto span =
tracer->StartSpan("a", {SetTag("abc", 123), SetTag("xyz", true)});
CHECK(span);
span->Finish();
}
auto span = recorder->top();
CHECK(span.operation_name() == "a");
CHECK(has_tag(span, "abc", 123));
CHECK(has_tag(span, "xyz", true));
}
SECTION("calling Finish a second time does nothing.") {
auto span = tracer->StartSpan("a");
CHECK(span);
span->Finish();
CHECK(recorder->size() == 1);
span->Finish();
CHECK(recorder->size() == 1);
}
SECTION("the operation name can be set after the span is started.") {
auto span = tracer->StartSpan("a");
CHECK(span);
span->SetOperationName("b");
span->Finish();
CHECK(recorder->top().operation_name() == "b");
}
}
<commit_msg>Added test coverage for span references.<commit_after>#include "in_memory_tracer.h"
#include <lightstep/tracer.h>
#define CATCH_CONFIG_MAIN
#include <lightstep/catch/catch.hpp>
#include <google/protobuf/util/message_differencer.h>
using namespace lightstep;
using namespace opentracing;
namespace lightstep {
std::shared_ptr<Tracer> make_lightstep_tracer(
std::unique_ptr<Recorder>&& recorder);
collector::KeyValue to_key_value(StringRef key, const Value& value);
} // namespace lightstep
//------------------------------------------------------------------------------
// has_tag
//------------------------------------------------------------------------------
static bool has_tag(const collector::Span& span, StringRef key,
const Value& value) {
auto key_value = to_key_value(key, value);
return std::find_if(
std::begin(span.tags()), std::end(span.tags()),
[&](const collector::KeyValue& other) {
return google::protobuf::util::MessageDifferencer::Equals(
key_value, other);
}) != std::end(span.tags());
}
//------------------------------------------------------------------------------
// has_relationship
//------------------------------------------------------------------------------
static bool has_relationship(SpanReferenceType relationship,
const collector::Span& span_a,
const collector::Span& span_b) {
collector::Reference reference;
switch (relationship) {
case SpanReferenceType::ChildOfRef:
reference.set_relationship(collector::Reference::CHILD_OF);
break;
case SpanReferenceType::FollowsFromRef:
reference.set_relationship(collector::Reference::FOLLOWS_FROM);
break;
}
*reference.mutable_span_context() = span_b.span_context();
return std::find_if(
std::begin(span_a.references()), std::end(span_a.references()),
[&](const collector::Reference& other) {
return google::protobuf::util::MessageDifferencer::Equals(
reference, other);
}) != std::end(span_a.references());
}
//------------------------------------------------------------------------------
// tests
//------------------------------------------------------------------------------
TEST_CASE("in_memory_tracer") {
auto recorder = new InMemoryRecorder();
auto tracer = make_lightstep_tracer(std::unique_ptr<Recorder>(recorder));
SECTION("StartSpan applies the provided tags.") {
{
auto span =
tracer->StartSpan("a", {SetTag("abc", 123), SetTag("xyz", true)});
CHECK(span);
span->Finish();
}
auto span = recorder->top();
CHECK(span.operation_name() == "a");
CHECK(has_tag(span, "abc", 123));
CHECK(has_tag(span, "xyz", true));
}
SECTION("You can set a single child-of reference when starting a span") {
auto span_a = tracer->StartSpan("a");
CHECK(span_a);
span_a->Finish();
auto span_b = tracer->StartSpan("b", {ChildOf(&span_a->context())});
CHECK(span_b);
span_b->Finish();
auto spans = recorder->spans();
CHECK(spans.at(0).span_context().trace_id() ==
spans.at(1).span_context().trace_id());
CHECK(has_relationship(SpanReferenceType::ChildOfRef, spans.at(1),
spans.at(0)));
}
SECTION("You can set a single follows-from reference when starting a span") {
auto span_a = tracer->StartSpan("a");
CHECK(span_a);
span_a->Finish();
auto span_b = tracer->StartSpan("b", {FollowsFrom(&span_a->context())});
CHECK(span_b);
span_b->Finish();
auto spans = recorder->spans();
CHECK(spans.at(0).span_context().trace_id() ==
spans.at(1).span_context().trace_id());
CHECK(has_relationship(SpanReferenceType::FollowsFromRef, spans.at(1),
spans.at(0)));
}
SECTION("Multiple references are supported when starting a span") {
auto span_a = tracer->StartSpan("a");
CHECK(span_a);
auto span_b = tracer->StartSpan("b");
CHECK(span_b);
auto span_c = tracer->StartSpan(
"c", {ChildOf(&span_a->context()), FollowsFrom(&span_b->context())});
span_a->Finish();
span_b->Finish();
span_c->Finish();
auto spans = recorder->spans();
CHECK(has_relationship(SpanReferenceType::ChildOfRef, spans.at(2),
spans.at(0)));
CHECK(has_relationship(SpanReferenceType::FollowsFromRef, spans.at(2),
spans.at(1)));
}
SECTION("Calling Finish a second time does nothing.") {
auto span = tracer->StartSpan("a");
CHECK(span);
span->Finish();
CHECK(recorder->size() == 1);
span->Finish();
CHECK(recorder->size() == 1);
}
SECTION("The operation name can be changed after the span is started.") {
auto span = tracer->StartSpan("a");
CHECK(span);
span->SetOperationName("b");
span->Finish();
CHECK(recorder->top().operation_name() == "b");
}
SECTION("Tags can be specified.") {
auto span = tracer->StartSpan("a");
CHECK(span);
span->SetTag("abc", 123);
span->Finish();
CHECK(has_tag(recorder->top(), "abc", 123));
}
}
<|endoftext|>
|
<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <list>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>
namespace vigra
{
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1,
typename std::enable_if<(N == 1)>::type *enabled = 0)
{
// Will ignore boundaries initially.
// Then will try adding reflection.
// Rank must be in the range 0 to 1
assert((0 <= rank) && (rank <= 1));
const int rank_pos = round(rank * (2 * half_length));
// The position of the
typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
std::multiset<T1> sorted_window;
std::list< typename std::multiset<T1>::iterator > window_iters;
// Get the initial sorted window.
// Include the reflection.
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
typename std::multiset<T1>::iterator rank_point = sorted_window.begin();
for (int i = 0; i < rank_pos; i++)
{
rank_point++;
}
while ( window_begin < src.size() )
{
dest[window_begin] = *rank_point;
typename std::multiset<T1>::iterator prev_iter(window_iters.front());
T1 prev_value = *prev_iter;
window_iters.pop_front();
window_begin++;
T1 next_value;
if ( window_begin < (src.size() - half_length) )
{
next_value = src[window_begin + half_length];
}
else
{
next_value = src[2 * src.size() - (window_begin + half_length + 2)];
}
if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1,
typename std::enable_if<(N > 1)>::type *enabled = 0)
{
typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;
for (unsigned int i = 0; i < N; i++)
{
transposed_axes[i] = i;
}
std::swap(transposed_axes[N - 1], transposed_axes[axis]);
vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));
vigra::MultiArrayView<N, T1, S1> dest_transposed_view(dest.transpose(transposed_axes));
typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
pos = 0;
bool done = false;
while (!done)
{
lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);
bool carry = true;
for (unsigned int i = 0; ( carry && (i < N) ); i++)
{
if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])
{
carry = false;
}
else
{
pos[N - (i + 1)] = 0;
carry = true;
}
}
done = !carry;
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1)
{
lineRankOrderFilterND(src, dest, half_length, rank, axis);
}
}
#endif //__RANK_FILTER__
<commit_msg>rank_filter.hxx: Changed enable_if arguments back to template arguments.<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <list>
#include <set>
#include <cmath>
#include <cassert>
#include <iostream>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vigra/multi_array.hxx>
#include <vigra/linear_algebra.hxx>
namespace vigra
{
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N == 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1)
{
// Will ignore boundaries initially.
// Then will try adding reflection.
// Rank must be in the range 0 to 1
assert((0 <= rank) && (rank <= 1));
const int rank_pos = round(rank * (2 * half_length));
// The position of the
typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 window_begin(0);
std::multiset<T1> sorted_window;
std::list< typename std::multiset<T1>::iterator > window_iters;
// Get the initial sorted window.
// Include the reflection.
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(half_length); j > 0; j--)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
for (typename vigra::MultiArrayView<N, T1, S1>::difference_type_1 j(0); j <= half_length; j++)
{
window_iters.push_back(sorted_window.insert(src[window_begin + j]));
}
typename std::multiset<T1>::iterator rank_point = sorted_window.begin();
for (int i = 0; i < rank_pos; i++)
{
rank_point++;
}
while ( window_begin < src.size() )
{
dest[window_begin] = *rank_point;
typename std::multiset<T1>::iterator prev_iter(window_iters.front());
T1 prev_value = *prev_iter;
window_iters.pop_front();
window_begin++;
T1 next_value;
if ( window_begin < (src.size() - half_length) )
{
next_value = src[window_begin + half_length];
}
else
{
next_value = src[2 * src.size() - (window_begin + half_length + 2)];
}
if ( ( *rank_point < *prev_iter ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= *prev_iter ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < *prev_iter ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= *prev_iter ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2,
typename std::enable_if<(N > 1), int>::type = 0>
inline void lineRankOrderFilterND(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1)
{
typename vigra::MultiArrayView<N, T1, S1>::difference_type transposed_axes;
for (unsigned int i = 0; i < N; i++)
{
transposed_axes[i] = i;
}
std::swap(transposed_axes[N - 1], transposed_axes[axis]);
vigra::MultiArray<N, T1> src_transposed(src.transpose(transposed_axes));
vigra::MultiArrayView<N, T1, S1> dest_transposed_view(dest.transpose(transposed_axes));
typename vigra::MultiArrayView<N - 1, T1, S1>::difference_type pos;
pos = 0;
bool done = false;
while (!done)
{
lineRankOrderFilter(src_transposed.bindInner(pos), dest_transposed_view.bindInner(pos), half_length, rank);
bool carry = true;
for (unsigned int i = 0; ( carry && (i < N) ); i++)
{
if ( (++pos[N - (i + 1)]) < src.shape()[N - (i + 1)])
{
carry = false;
}
else
{
pos[N - (i + 1)] = 0;
carry = true;
}
}
done = !carry;
}
}
template<unsigned int N,
class T1, class S1,
class T2, class S2>
inline void lineRankOrderFilter(const vigra::MultiArrayView <N, T1, S1> &src,
vigra::MultiArrayView <N, T2, S2> dest,
unsigned int half_length, float rank, unsigned int axis = N - 1)
{
lineRankOrderFilterND(src, dest, half_length, rank, axis);
}
}
#endif //__RANK_FILTER__
<|endoftext|>
|
<commit_before>/*
test_text
Do some simple text drawing
*/
#include "drawproc.h"
#include "guistyle.h"
#include <stdio.h>
static GUIStyle styler;
static const int gMaxMode = 3;
static int gMode = 0;
pb_rgba fb;
pb_rect keyRect = { 0, 0, 34, 34 };
/*
VK_SPACE, 168, 242, 204, 34
*/
//void draw();
void mousePressed()
{
gMode++;
if (gMode >= gMaxMode) {
gMode = 0;
}
}
void mouseMoved()
{
keyRect.x = mouseX - keyRect.width / 2;
keyRect.y = mouseY - keyRect.height / 2;
}
LRESULT CALLBACK keyReleased(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case VK_SPACE:
write_PPM_binary("test_keyboard.ppm", gpb);
break;
case VK_RIGHT: // increase width of keyRect
keyRect.width += 1;
break;
case VK_LEFT:
keyRect.width -= 1;
if (keyRect.width < 4) keyRect.width = 4;
break;
case VK_UP:
keyRect.height += 1;
break;
case VK_DOWN:
keyRect.height -= 1;
if (keyRect.height < 4) keyRect.height = 4;
break;
}
keyRect.x = mouseX - keyRect.width / 2;
keyRect.y = mouseY - keyRect.height / 2;
return 0;
}
// Draw information about the mouse
// location, buttons pressed, etc
void drawMouseInfo()
{
// draw a white banner across the top
noStroke();
fill(pWhite);
rect(0, fb.frame.height + 2, width, 24);
// draw the key rectangle
fill(RGBA(255, 238, 200, 180));
stroke(pDarkGray);
rect(keyRect.x, keyRect.y, keyRect.width, keyRect.height);
// select verdana font
setFont(verdana17);
char infobuff[256];
sprintf_s(infobuff, "Mouse X: %3d Y: %3d Key: (%3d, %3d)(%3d, %3d)", mouseX, mouseY, keyRect.x,
keyRect.y, keyRect.width, keyRect.height);
fill(pBlack);
textAlign(TX_LEFT, TX_TOP);
text(infobuff, 0, fb.frame.height + 2);
}
void draw()
{
background(pLightGray);
backgroundImage(&fb);
drawMouseInfo();
}
void setup()
{
int ret = PPM_read_binary("c:/repos/graphicc/Test/windows-keyboard-60-keys.ppm", &fb);
size(fb.frame.width+4, fb.frame.height+4+30);
background(pLightGray);
//noLoop();
//setOnMousePressedHandler(mousePressed);
//setOnMouseMovedHandler(mouseMoved);
//setOnKeyReleasedHandler(keyReleased);
}
<commit_msg>Changed string format of tracking rectangle information, using float<commit_after>/*
test_text
Do some simple text drawing
*/
#include "drawproc.h"
#include "guistyle.h"
#include <stdio.h>
static GUIStyle styler;
static const int gMaxMode = 3;
static int gMode = 0;
pb_rgba fb;
pb_rect keyRect = { 0, 0, 34, 34 };
/*
VK_SPACE, 168, 242, 204, 34
*/
//void draw();
void mousePressed()
{
gMode++;
if (gMode >= gMaxMode) {
gMode = 0;
}
}
void mouseMoved()
{
keyRect.x = mouseX - keyRect.width / 2;
keyRect.y = mouseY - keyRect.height / 2;
}
LRESULT CALLBACK keyReleased(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (wParam)
{
case VK_SPACE:
write_PPM_binary("test_keyboard.ppm", gpb);
break;
case VK_RIGHT: // increase width of keyRect
keyRect.width += 1;
break;
case VK_LEFT:
keyRect.width -= 1;
if (keyRect.width < 4) keyRect.width = 4;
break;
case VK_UP:
keyRect.height += 1;
break;
case VK_DOWN:
keyRect.height -= 1;
if (keyRect.height < 4) keyRect.height = 4;
break;
}
keyRect.x = mouseX - keyRect.width / 2;
keyRect.y = mouseY - keyRect.height / 2;
return 0;
}
// Draw information about the mouse
// location, buttons pressed, etc
void drawMouseInfo()
{
// draw a white banner across the top
noStroke();
fill(pWhite);
rect(0, fb.frame.height + 2, width, 24);
// draw the key rectangle
fill(RGBA(255, 238, 200, 180));
stroke(pDarkGray);
rect(keyRect.x, keyRect.y, keyRect.width, keyRect.height);
// select verdana font
setFont(verdana17);
char infobuff[256];
sprintf_s(infobuff, "Mouse X: %3d Y: %3d Key: (%3f, %3f)(%3.0f, %3.0f)", mouseX, mouseY, keyRect.x,
keyRect.y, keyRect.width, keyRect.height);
fill(pBlack);
textAlign(TX_LEFT, TX_TOP);
text(infobuff, 0, fb.frame.height + 2);
}
void draw()
{
background(pLightGray);
backgroundImage(&fb);
drawMouseInfo();
}
void setup()
{
int ret = PPM_read_binary("c:/repos/graphicc/Test/windows-keyboard-60-keys.ppm", &fb);
size(fb.frame.width+4, fb.frame.height+4+30);
background(pLightGray);
//noLoop();
//setOnMousePressedHandler(mousePressed);
//setOnMouseMovedHandler(mouseMoved);
//setOnKeyReleasedHandler(keyReleased);
}
<|endoftext|>
|
<commit_before>#include "TestAlgorithm.h"
/**
* @brief TestAlgorithm::TestAlgorithm create new algorithm with given ID
* @param id algorithm ID
*/
TestAlgorithm::TestAlgorithm() {
mId = "default";
mName = "Test algorithm";
mDescription = "dummy algorithm that scores randomly";
}
/**
* @brief TestAlgorithm::run start the search
* @return a list of data packets containing results
*/
QList<DataPacket*> TestAlgorithm::run() {
QList<DataPacket*> list;
SearchResult* result = new SearchResult();
for (QString& datasetPath : mQuery->getDatasets()) {
Dataset dataset(datasetPath);
for (Medium* medium : dataset.getMediaList()) {
SearchObject* object = new SearchObject();
object->setMedium(medium->getPath());
//new result element
SearchResultElement* resultElement = new SearchResultElement();
resultElement->setSearchObject(*object);
resultElement->setScore(std::rand() % 20);
//add to result list
result->addResultElement(*resultElement);
}
}
list.append((DataPacket*)result);
return list;
}
/**
* @brief TestAlgorithm::cancel terminate the algorithm
*/
void TestAlgorithm::cancel() {
}
/**
* @brief TestAlgorithm::setInputs set input for algorithm
* @param inputDataList input data
* @return true if input data is accepted
*/
bool TestAlgorithm::setInputs(const QList<DataPacket*>& inputDataList) {
if (inputDataList.length() < 1) { //illegal number of parameters
return false;
}
DataPacket* packet = inputDataList.value(0);
if (packet->getType() != DataPacket::Type::SEARCHQUERY) { //invalid query
return false;
}
mQuery = dynamic_cast<SearchQuery*>(packet);
return true;
}
/**
* @brief TestAlgorithm::setParameters set algorithm parameters
* @param parameters the parameters
* @return true if the algorithm accepts the parameters
*/
bool TestAlgorithm::setParameters(const QJsonObject& parameters) {
Q_UNUSED(parameters);
return true;
}
/**
* @brief TestAlgorithm::supportsProgressInfo
* @return true if progress information will be sent to application when the search runs
*/
bool TestAlgorithm::supportsProgressInfo() {
return false;
}
<commit_msg>add some optimization for TestAlgorithm<commit_after>#include "TestAlgorithm.h"
/**
* @brief TestAlgorithm::TestAlgorithm create new algorithm with given ID
* @param id algorithm ID
*/
TestAlgorithm::TestAlgorithm() {
mId = "default";
mName = "Test algorithm";
mDescription = "dummy algorithm that scores randomly";
}
/**
* @brief TestAlgorithm::run start the search
* @return a list of data packets containing results
*/
QList<DataPacket*> TestAlgorithm::run() {
QList<DataPacket*> list;
SearchResult* result = new SearchResult();
for (QString& datasetPath : mQuery->getDatasets()) {
Dataset dataset(datasetPath);
for (Medium* medium : dataset.getMediaList()) {
SearchObject* object = new SearchObject();
object->setMedium(medium->getPath());
object->setSourceDataset(dataset.getPath());
//new result element
SearchResultElement* resultElement = new SearchResultElement();
resultElement->setSearchObject(*object);
resultElement->setScore(std::rand() % 20);
//add to result list
result->addResultElement(*resultElement);
}
}
list.append(dynamic_cast<DataPacket*>(result));
return list;
}
/**
* @brief TestAlgorithm::cancel terminate the algorithm
*/
void TestAlgorithm::cancel() {
}
/**
* @brief TestAlgorithm::setInputs set input for algorithm
* @param inputDataList input data
* @return true if input data is accepted
*/
bool TestAlgorithm::setInputs(const QList<DataPacket*>& inputDataList) {
if (inputDataList.length() != 1) { //illegal number of parameters
return false;
}
DataPacket* packet = inputDataList.value(0);
if (packet->getType() != DataPacket::Type::SEARCHQUERY) { //invalid query
return false;
}
mQuery = dynamic_cast<SearchQuery*>(packet);
return true;
}
/**
* @brief TestAlgorithm::setParameters set algorithm parameters
* @param parameters the parameters
* @return true if the algorithm accepts the parameters
*/
bool TestAlgorithm::setParameters(const QJsonObject& parameters) {
Q_UNUSED(parameters);
return true;
}
/**
* @brief TestAlgorithm::supportsProgressInfo
* @return true if progress information will be sent to application when the search runs
*/
bool TestAlgorithm::supportsProgressInfo() {
return false;
}
<|endoftext|>
|
<commit_before>#include "gvki/Logger.h"
#include "gvki/PathSeperator.h"
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <errno.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "string.h"
#include "gvki/Debug.h"
// For mkdir(). FIXME: Make windows compatible
#include <sys/stat.h>
// For opendir(). FIXME: Make windows compatible
#include <dirent.h>
// For getcwd()
#include <unistd.h>
using namespace std;
using namespace gvki;
// Maximum number of files or directories
// that can be created
static const int maxFiles = 10000;
Logger& Logger::Singleton()
{
static Logger l;
return l;
}
Logger::Logger()
{
int count = 0;
bool success= false;
// FIXME: Reading from the environment probably doesn't belong in here
// but it makes implementing the singleton a lot easier
std::string directoryPrefix;
const char* envTemp = getenv("GVKI_ROOT");
if (envTemp)
{
DEBUG_MSG("Using GVKI_ROOT value as destination for directories");
DIR* dh = opendir(envTemp);
if (dh == NULL)
{
ERROR_MSG(strerror(errno) << ". Directory was :" << envTemp);
exit(1);
}
else
closedir(dh);
directoryPrefix = envTemp;
}
else
{
// Use the current working directory
DEBUG_MSG("Using current working directory as destination for directories");
// FIXME: Hard-coding this size is gross
char cwdArray[1024];
char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char));
if (!cwdResult)
{
ERROR_MSG(strerror(errno) << ". Could not read the current working directory");
exit(1);
}
else
directoryPrefix = cwdResult;
}
directoryPrefix += PATH_SEP "gvki";
DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\"");
// Keep trying a directoryPrefix name with a number as suffix
// until we find an available one or we exhaust the maximum
// allowed number
while (count < maxFiles)
{
stringstream ss;
ss << directoryPrefix << "-" << count;
++count;
// Make the directoryPrefix
if (mkdir(ss.str().c_str(), 0770) != 0)
{
if (errno != EEXIST)
{
ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix);
exit(1);
}
// It already exists, try again
continue;
}
this->directory = ss.str();
success = true;
break;
}
if (!success)
{
ERROR_MSG("Exhausted available directory names or couldn't create any");
exit(1);
}
DEBUG_MSG("Directory used for logging is \"" << this->directory << "\"");
openLog();
}
void Logger::openLog()
{
// FIXME: We should use mkstemp() or something
std::stringstream ss;
ss << directory << PATH_SEP << "log.json";
output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);
if (! output->good())
{
ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to");
exit(1);
}
// Start of JSON array
*output << "[" << std::endl;
}
void Logger::closeLog()
{
// End of JSON array
*output << std::endl << "]" << std::endl;
output->close();
}
Logger::~Logger()
{
closeLog();
delete output;
}
void Logger::dump(cl_kernel k)
{
// Output JSON format defined by
// http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html
KernelInfo& ki = kernels[k];
static bool isFirst = true;
if (!isFirst)
{
// Emit array element seperator
// to seperate from previous dump
*output << "," << endl;
}
isFirst = false;
*output << "{" << endl << "\"language\": \"OpenCL\"," << endl;
std::string kernelSourceFile = dumpKernelSource(ki);
*output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl;
// FIXME: Teach GPUVerify how to handle non zero global_offset
// FIXME: Document this json attribute!
// Only emit global_offset if its non zero
bool hasNonZeroGlobalOffset = false;
for (int index=0; index < ki.globalWorkOffset.size() ; ++index)
{
if (ki.globalWorkOffset[index] != 0)
hasNonZeroGlobalOffset = true;
}
if (hasNonZeroGlobalOffset)
{
*output << "\"global_offset\": ";
printJSONArray(ki.globalWorkOffset);
*output << "," << endl;
}
*output << "\"global_size\": ";
printJSONArray(ki.globalWorkSize);
*output << "," << endl;
*output << "\"local_size\": ";
printJSONArray(ki.localWorkSize);
*output << "," << endl;
assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&
(ki.globalWorkSize.size() == ki.localWorkSize.size()) &&
"dimension mismatch");
*output << "\"entry_point\": \"" << ki.entryPointName << "\"";
// entry_point might be the last entry is there were no kernel args
if (ki.arguments.size() == 0)
*output << endl;
else
{
*output << "," << endl << "\"kernel_arguments\": [ " << endl;
for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)
{
printJSONKernelArgumentInfo(ki.arguments[argIndex]);
if (argIndex != (ki.arguments.size() -1))
*output << "," << endl;
}
*output << endl << "]" << endl;
}
*output << "}";
}
void Logger::printJSONArray(std::vector<size_t>& array)
{
*output << "[ ";
for (int index=0; index < array.size(); ++index)
{
*output << array[index];
if (index != (array.size() -1))
*output << ", ";
}
*output << "]";
}
void Logger::printJSONKernelArgumentInfo(ArgInfo& ai)
{
*output << "{";
if (ai.argValue == NULL)
{
// NULL was passed to clSetKernelArg()
// That implies its for unallocated memory
*output << "\"type\": \"array\",";
// If the arg is for local memory
if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))
{
// We assume this means this arguments is for local memory
// where size actually means the sizeof the underlying buffer
// rather than the size of the type.
*output << "\"size\" : " << ai.argSize;
}
*output << "}";
return;
}
// FIXME:
// Eurgh... the spec says
// ```
// If the argument is a buffer object, the arg_value pointer can be NULL or
// point to a NULL value in which case a NULL value will be used as the
// value for the argument declared as a pointer to __global or __constant
// memory in the kernel. ```
//
// This makes it impossible (seeing as we don't know which address space
// the arguments are in) to work out the argument type once derefencing the
// pointer and finding it's equal zero because it could be a scalar constant
// (of value 0) or it could be an unintialised array!
// Hack:
// It's hard to determine what type the argument is.
// We can't dereference the void* to check if
// it points to cl_mem we previously stored
//
// In some implementations cl_mem will be a pointer
// which poses a risk if a scalar parameter of the same size
// as the pointer type.
if (ai.argSize == sizeof(cl_mem))
{
cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);
// We might be reading invalid data now
if (buffers.count(mightBecl_mem) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"array\",";
BufferInfo& bi = buffers[mightBecl_mem];
*output << "\"size\": " << bi.size << "}";
return;
}
}
// Hack: a similar hack of the image types
if (ai.argSize == sizeof(cl_mem))
{
cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);
// We might be reading invalid data now
if (images.count(mightBecl_mem) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"image\"}";
return;
}
}
// Hack: a similar hack for the samplers
if (ai.argSize == sizeof(cl_sampler))
{
cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);
// We might be reading invalid data now
if (samplers.count(mightBecl_sampler) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"sampler\"}";
return;
}
}
// I guess it's scalar???
*output << "\"type\": \"scalar\",";
*output << " \"value\": \"0x";
// Print the value as hex
uint8_t* asByte = (uint8_t*) ai.argValue;
// We assume the host is little endian so to print the values
// we need to go through the array bytes backwards
for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)
{
*output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);
}
*output << "\"" << std::dec; //std::hex is sticky so switch back to decimal
*output << "}";
return;
}
static bool file_exists(std::string& name) {
ifstream f(name.c_str());
bool result = f.good();
f.close();
return result;
}
// Define the strict weak ordering over ProgramInfo instances
// Is this correct?
bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const
{
// Use the fact that a strict-weak order is already defined over std::vector<>
return lhs.sources < rhs.sources;
}
std::string Logger::dumpKernelSource(KernelInfo& ki)
{
ProgramInfo& pi = programs[ki.program];
// See if we can used a file that we already printed.
// This avoid writing duplicate files.
ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);
if ( it != WrittenKernelFileCache.end() )
{
return it->second;
}
int count = 0;
bool success = false;
// FIXME: I really want a std::unique_ptr
std::ofstream* kos = 0;
std::string theKernelPath;
while (count < maxFiles)
{
stringstream ss;
ss << ki.entryPointName << "." << count << ".cl";
++count;
std::string withDir = (directory + PATH_SEP) + ss.str();
if (!file_exists(withDir))
{
kos = new std::ofstream(withDir.c_str());
if (!kos->good())
{
kos->close();
delete kos;
continue;
}
success = true;
theKernelPath = ss.str();
break;
}
}
if (!success)
{
ERROR_MSG("Failed to log kernel output");
return std::string("FIXME");
}
// Write kernel source
for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)
{
*kos << *b;
}
// Urgh this is bad, need RAII!
kos->close();
delete kos;
// Store in cache
assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!");
WrittenKernelFileCache[pi] = theKernelPath;
return theKernelPath;
}
<commit_msg>Modifications to allow this to compile and run under Windows<commit_after>#include "gvki/Logger.h"
#include "gvki/PathSeperator.h"
#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <errno.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include "string.h"
#include "gvki/Debug.h"
#include <sys/stat.h>
#ifndef _WIN32
#include <dirent.h>
#include <unistd.h>
#define MKDIR_FAILS(d) (mkdir(d, 0770) != 0)
#define DIR_ALREADY_EXISTS (errno == EEXIST)
static void checkDirectoryExists(const char* dirName) {
DIR* dh = opendir(dirName);
if (dh != NULL)
{
closedir(dh);
return;
}
ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
exit(1);
}
#else
#include <inttypes.h>
#include <Windows.h>
#define MKDIR_FAILS(d) (CreateDirectory(ss.str().c_str(), NULL) == 0)
#define DIR_ALREADY_EXISTS (GetLastError() == ERROR_ALREADY_EXISTS)
static void checkDirectoryExists(const char* dirName) {
DWORD ftyp = GetFileAttributesA(dirName);
if ((ftyp != INVALID_FILE_ATTRIBUTES) && ftyp & FILE_ATTRIBUTE_DIRECTORY)
return;
ERROR_MSG(strerror(errno) << ". Directory was :" << dirName);
exit(1);
}
#endif
using namespace std;
using namespace gvki;
// Maximum number of files or directories
// that can be created
static const int maxFiles = 10000;
Logger& Logger::Singleton()
{
static Logger l;
return l;
}
Logger::Logger()
{
int count = 0;
bool success= false;
// FIXME: Reading from the environment probably doesn't belong in here
// but it makes implementing the singleton a lot easier
std::string directoryPrefix;
const char* envTemp = getenv("GVKI_ROOT");
if (envTemp)
{
DEBUG_MSG("Using GVKI_ROOT value as destination for directories");
checkDirectoryExists(envTemp);
directoryPrefix = envTemp;
}
else
{
// Use the current working directory
DEBUG_MSG("Using current working directory as destination for directories");
// FIXME: Hard-coding this size is gross
#define MAX_DIR_LENGTH 1024
#ifndef _WIN32
char cwdArray[MAX_DIR_LENGTH];
char* cwdResult = getcwd(cwdArray, sizeof(cwdArray)/sizeof(char));
if (!cwdResult)
#else
char cwdResult[MAX_DIR_LENGTH];
if (GetCurrentDirectory(MAX_DIR_LENGTH, cwdResult) == 0)
#endif
{
ERROR_MSG(strerror(errno) << ". Could not read the current working directory");
exit(1);
}
else
directoryPrefix = cwdResult;
}
directoryPrefix += PATH_SEP "gvki";
DEBUG_MSG("Directory prefix is \"" << directoryPrefix << "\"");
// Keep trying a directoryPrefix name with a number as suffix
// until we find an available one or we exhaust the maximum
// allowed number
while (count < maxFiles)
{
stringstream ss;
ss << directoryPrefix << "-" << count;
++count;
// Make the directoryPrefix
if (MKDIR_FAILS(ss.str().c_str()))
{
if (!DIR_ALREADY_EXISTS)
{
ERROR_MSG(strerror(errno) << ". Directory was :" << directoryPrefix);
exit(1);
}
// It already exists, try again
continue;
}
this->directory = ss.str();
success = true;
break;
}
if (!success)
{
ERROR_MSG("Exhausted available directory names or couldn't create any");
exit(1);
}
DEBUG_MSG("Directory used for logging is \"" << this->directory << "\"");
openLog();
}
void Logger::openLog()
{
// FIXME: We should use mkstemp() or something
std::stringstream ss;
ss << directory << PATH_SEP << "log.json";
output = new std::ofstream(ss.str().c_str(), std::ofstream::out | std::ofstream::ate);
if (! output->good())
{
ERROR_MSG("Failed to create file (" << ss.str() << ") to write log to");
exit(1);
}
// Start of JSON array
*output << "[" << std::endl;
}
void Logger::closeLog()
{
// End of JSON array
*output << std::endl << "]" << std::endl;
output->close();
}
Logger::~Logger()
{
closeLog();
delete output;
}
void Logger::dump(cl_kernel k)
{
// Output JSON format defined by
// http://multicore.doc.ic.ac.uk/tools/GPUVerify/docs/json_format.html
KernelInfo& ki = kernels[k];
static bool isFirst = true;
if (!isFirst)
{
// Emit array element seperator
// to seperate from previous dump
*output << "," << endl;
}
isFirst = false;
*output << "{" << endl << "\"language\": \"OpenCL\"," << endl;
std::string kernelSourceFile = dumpKernelSource(ki);
*output << "\"kernel_file\": \"" << kernelSourceFile << "\"," << endl;
// FIXME: Teach GPUVerify how to handle non zero global_offset
// FIXME: Document this json attribute!
// Only emit global_offset if its non zero
bool hasNonZeroGlobalOffset = false;
for (int index=0; index < ki.globalWorkOffset.size() ; ++index)
{
if (ki.globalWorkOffset[index] != 0)
hasNonZeroGlobalOffset = true;
}
if (hasNonZeroGlobalOffset)
{
*output << "\"global_offset\": ";
printJSONArray(ki.globalWorkOffset);
*output << "," << endl;
}
*output << "\"global_size\": ";
printJSONArray(ki.globalWorkSize);
*output << "," << endl;
*output << "\"local_size\": ";
printJSONArray(ki.localWorkSize);
*output << "," << endl;
assert( (ki.globalWorkOffset.size() == ki.globalWorkSize.size()) &&
(ki.globalWorkSize.size() == ki.localWorkSize.size()) &&
"dimension mismatch");
*output << "\"entry_point\": \"" << ki.entryPointName << "\"";
// entry_point might be the last entry is there were no kernel args
if (ki.arguments.size() == 0)
*output << endl;
else
{
*output << "," << endl << "\"kernel_arguments\": [ " << endl;
for (int argIndex=0; argIndex < ki.arguments.size() ; ++argIndex)
{
printJSONKernelArgumentInfo(ki.arguments[argIndex]);
if (argIndex != (ki.arguments.size() -1))
*output << "," << endl;
}
*output << endl << "]" << endl;
}
*output << "}";
}
void Logger::printJSONArray(std::vector<size_t>& array)
{
*output << "[ ";
for (int index=0; index < array.size(); ++index)
{
*output << array[index];
if (index != (array.size() -1))
*output << ", ";
}
*output << "]";
}
void Logger::printJSONKernelArgumentInfo(ArgInfo& ai)
{
*output << "{";
if (ai.argValue == NULL)
{
// NULL was passed to clSetKernelArg()
// That implies its for unallocated memory
*output << "\"type\": \"array\",";
// If the arg is for local memory
if (ai.argSize != sizeof(cl_mem) && ai.argSize != sizeof(cl_sampler))
{
// We assume this means this arguments is for local memory
// where size actually means the sizeof the underlying buffer
// rather than the size of the type.
*output << "\"size\" : " << ai.argSize;
}
*output << "}";
return;
}
// FIXME:
// Eurgh... the spec says
// ```
// If the argument is a buffer object, the arg_value pointer can be NULL or
// point to a NULL value in which case a NULL value will be used as the
// value for the argument declared as a pointer to __global or __constant
// memory in the kernel. ```
//
// This makes it impossible (seeing as we don't know which address space
// the arguments are in) to work out the argument type once derefencing the
// pointer and finding it's equal zero because it could be a scalar constant
// (of value 0) or it could be an unintialised array!
// Hack:
// It's hard to determine what type the argument is.
// We can't dereference the void* to check if
// it points to cl_mem we previously stored
//
// In some implementations cl_mem will be a pointer
// which poses a risk if a scalar parameter of the same size
// as the pointer type.
if (ai.argSize == sizeof(cl_mem))
{
cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);
// We might be reading invalid data now
if (buffers.count(mightBecl_mem) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"array\",";
BufferInfo& bi = buffers[mightBecl_mem];
*output << "\"size\": " << bi.size << "}";
return;
}
}
// Hack: a similar hack of the image types
if (ai.argSize == sizeof(cl_mem))
{
cl_mem mightBecl_mem = *((cl_mem*) ai.argValue);
// We might be reading invalid data now
if (images.count(mightBecl_mem) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"image\"}";
return;
}
}
// Hack: a similar hack for the samplers
if (ai.argSize == sizeof(cl_sampler))
{
cl_sampler mightBecl_sampler = *((cl_sampler*) ai.argValue);
// We might be reading invalid data now
if (samplers.count(mightBecl_sampler) == 1)
{
// We're going to assume it's cl_mem that we saw before
*output << "\"type\": \"sampler\"}";
return;
}
}
// I guess it's scalar???
*output << "\"type\": \"scalar\",";
*output << " \"value\": \"0x";
// Print the value as hex
uint8_t* asByte = (uint8_t*) ai.argValue;
// We assume the host is little endian so to print the values
// we need to go through the array bytes backwards
for (int byteIndex= ai.argSize -1; byteIndex >=0 ; --byteIndex)
{
*output << std::hex << std::setfill('0') << std::setw(2) << ( (unsigned) asByte[byteIndex]);
}
*output << "\"" << std::dec; //std::hex is sticky so switch back to decimal
*output << "}";
return;
}
static bool file_exists(std::string& name) {
ifstream f(name.c_str());
bool result = f.good();
f.close();
return result;
}
// Define the strict weak ordering over ProgramInfo instances
// Is this correct?
bool ProgramInfoCacheCompare::operator() (const ProgramInfo& lhs, const ProgramInfo& rhs) const
{
// Use the fact that a strict-weak order is already defined over std::vector<>
return lhs.sources < rhs.sources;
}
std::string Logger::dumpKernelSource(KernelInfo& ki)
{
ProgramInfo& pi = programs[ki.program];
// See if we can used a file that we already printed.
// This avoid writing duplicate files.
ProgCacheMapTy::iterator it = WrittenKernelFileCache.find(pi);
if ( it != WrittenKernelFileCache.end() )
{
return it->second;
}
int count = 0;
bool success = false;
// FIXME: I really want a std::unique_ptr
std::ofstream* kos = 0;
std::string theKernelPath;
while (count < maxFiles)
{
stringstream ss;
ss << ki.entryPointName << "." << count << ".cl";
++count;
std::string withDir = (directory + PATH_SEP) + ss.str();
if (!file_exists(withDir))
{
kos = new std::ofstream(withDir.c_str());
if (!kos->good())
{
kos->close();
delete kos;
continue;
}
success = true;
theKernelPath = ss.str();
break;
}
}
if (!success)
{
ERROR_MSG("Failed to log kernel output");
return std::string("FIXME");
}
// Write kernel source
for (vector<string>::const_iterator b = pi.sources.begin(), e = pi.sources.end(); b != e; ++b)
{
*kos << *b;
}
// Urgh this is bad, need RAII!
kos->close();
delete kos;
// Store in cache
assert(WrittenKernelFileCache.count(pi) == 0 && "ProgramInfo already in cache!");
WrittenKernelFileCache[pi] = theKernelPath;
return theKernelPath;
}
<|endoftext|>
|
<commit_before>#ifndef SIMPLE_HERO_CPP_
#define SIMPLE_HERO_CPP_
#include "simple_hero.hpp"
#include <stdlib.h>
#include <queue>
Simple_Hero::Simple_Hero( int type ) : Actor( type ) {
actor_list = vector<Vertex>();
made_graph = false;
}
const char* Simple_Hero::getActorId() {
return "simplehero";
}
const char* Simple_Hero::getNetId() {
return "hammesa";
}
void Simple_Hero::update_vertices( GraphMap* map ) {
int x, y;
actor_list.resize( map->getNumActors() );
for( int i = 0; i < map->getNumActors(); i++ ) {
map->getActorPosition( i, x, y );
actor_list[i] = Vertex( x, y );
}
if( !made_graph ) make_graph( map );
}
void Simple_Hero::make_graph( GraphMap* map ) {
graph_width = map->getWidth();
graph_height = map->getHeight();
graph.reserve( graph_width );
for(int i = 0; i < graph_width; i++ ) {
graph[i].reserve( graph_height );
}
update_vertices( map );
made_graph = true;
}
Vertex& Simple_Hero::get_vertex( int x, int y ) {
if( !made_graph ) {
printf("Called get_vertex without initializing graph\n");
exit(0);
}
return graph[x][y];
}
int Simple_Hero::select_neighbor( GraphMap* map, int x, int y ) {
return 0;
}
int Simple_Hero::where_go( GraphMap* map, int x1, int y1, int x2, int y2 ) {
queue<Vertex> v_q;
Vertex source ( x1, y1 );
Vertex target ( x2, y2 );
Vertex popped, temp;
v_q.push( source );
while( !v_q.empty() ) {
popped = v_q.front();
if( popped == target ) break;
if( popped.visited ) {
v_q.pop();
continue;
}
for( int i = 0; i < map->getNumNeighbors( popped.x, popped.y ); i++ ) {
int a, b;
map->getNeighbor( popped.x, popped.y, i, a, b );
temp = get_vertex( a, b );
temp.prev = &popped;
temp.visited = true;
v_q.push( temp );
}
}
return 0;
}
Simple_Hero::~Simple_Hero() {}
#endif
<commit_msg>Finished Djikstra's Algorithm, added input checking<commit_after>#ifndef SIMPLE_HERO_CPP_
#define SIMPLE_HERO_CPP_
#include "simple_hero.hpp"
#include <stdlib.h>
#include <queue>
Simple_Hero::Simple_Hero( int type ) : Actor( type ) {
actor_list = vector<Vertex>();
made_graph = false;
}
const char* Simple_Hero::getActorId() {
return "simplehero";
}
const char* Simple_Hero::getNetId() {
return "hammesa";
}
void Simple_Hero::update_vertices( GraphMap* map ) {
int x, y;
actor_list.resize( map->getNumActors() );
for( int i = 0; i < map->getNumActors(); i++ ) {
map->getActorPosition( i, x, y );
actor_list[i] = Vertex( x, y );
}
if( !made_graph ) make_graph( map );
}
void Simple_Hero::make_graph( GraphMap* map ) {
graph_width = map->getWidth();
graph_height = map->getHeight();
graph.reserve( graph_width );
for(int i = 0; i < graph_width; i++ ) {
graph[i].reserve( graph_height );
}
update_vertices( map );
made_graph = true;
}
Vertex& Simple_Hero::get_vertex( int x, int y ) {
if( !made_graph ) {
printf( "Called get_vertex without initializing graph\n" );
exit(0);
}
return graph[x][y];
}
int Simple_Hero::select_neighbor( GraphMap* map, int x, int y ) {
return 0;
}
int Simple_Hero::where_go( GraphMap* map, int x1, int y1, int x2, int y2 ) {
queue<Vertex> v_q;
if( x1 < 0 || y1 < 0 ) {
printf( "Invalid coordinates for source vertex in where_go - (%d, %d)\n", x1, y1 );
exit(0);
}
if( x2 < 0 || y2 < 0 ) {
printf( "Invalid coordinates for dest vertex in where_go - (%d, %d)\n", x2, y2 );
exit(0);
}
Vertex source ( x1, y1 );
Vertex target ( x2, y2 );
Vertex popped, temp;
v_q.push( source );
while( !v_q.empty() ) {
popped = v_q.front();
if( popped.visited ) {
v_q.pop();
continue;
}
for( int i = 0; i < map->getNumNeighbors( popped.x, popped.y ); i++ ) {
int a, b;
map->getNeighbor( popped.x, popped.y, i, a, b );
temp = get_vertex( a, b );
temp.prev = &popped;
if( temp == target ) {
break;
}
if( !temp.visited ) {
temp.visited = true;
v_q.push( temp );
}
}
v_q.pop();
}
while( !(*temp.prev == source ) ) {
temp = *temp.prev;
}
for( int i = 0; i < map->getNumNeighbors( temp.prev->x, temp.prev->y ); i++ ) {
int a, b;
map->getNeighbor( temp.prev->x, temp.prev->y, i, a, b );
Vertex check( a, b );
if( check == source ) {
return i;
}
}
return -1;
}
Simple_Hero::~Simple_Hero() {}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 The Brick Authors.
#include "brick/brick_app.h"
#include <unistd.h>
#include <gtk/gtk.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <X11/Xlib.h>
#include <X11/extensions/scrnsaver.h>
#include "third-party/json/json.h"
#include "include/wrapper/cef_helpers.h"
#include "include/cef_app.h"
#include "brick/indicator/indicator.h"
#include "brick/client_handler.h"
#include "brick/client_app.h"
#include "brick/window_util.h"
#include "brick/helper.h"
#include "brick/platform_util.h"
#include "brick/external_interface/dbus_protocol.h"
#undef Status // Definition conflicts with cef_urlrequest.h
#undef Success // Definition conflicts with cef_message_router.h
namespace {
const int kMainWindowWidth = 914;
const int kMainWindowHeight = 454;
const int32 kIdleTimeout = 600000L;
const unsigned long kIdleCheckInterval = 10000;
std::string kAppIcons[] = {"brick16.png", "brick32.png", "brick48.png", "brick128.png", "brick256.png"};
std::string szWorkingDir; // The current working directory
std::string startupLocale;
bool
GetWorkingDir(std::string& dir) {
char buff[1024];
// Retrieve the executable path.
ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len == -1)
return false;
buff[len] = 0;
dir = std::string(buff);
// Remove the executable name from the path.
dir = dir.substr(0, dir.find_last_of("/"));
return true;
}
bool
EnsureSystemDirectoryExists() {
return (
platform_util::MakeDirectory(platform_util::GetCacheDir() + "/" + APP_COMMON_NAME)
&& platform_util::MakeDirectory(platform_util::GetCacheDir() + "/" + APP_COMMON_NAME)
);
}
bool
EnsureSingleInstance() {
std::string lock_file = platform_util::GetCacheDir() + "/" + APP_COMMON_NAME + "/run.lock";
int fd = open(lock_file.c_str(), O_CREAT, 0600);
if (fd == -1)
return true;
return flock(fd, LOCK_EX|LOCK_NB) == 0;
}
gboolean
CheckUserIdle(gpointer data) {
/* Query xscreensaver */
static XScreenSaverInfo *mit_info = NULL;
static int has_extension = -1;
int event_base, error_base;
if (has_extension == -1)
has_extension = XScreenSaverQueryExtension(GDK_DISPLAY(), &event_base, &error_base);
if (!has_extension) {
LOG(WARNING) << "XScreenSaver extension not found, 'auto away' feature is being disabled.";
// Don't call this function anymore
return false;
}
CefRefPtr<ClientHandler> handler = ClientHandler::GetInstance();
if (!handler)
return true;
if (!handler->IsIdlePending())
return true;
if (mit_info == NULL)
mit_info = XScreenSaverAllocInfo();
XScreenSaverQueryInfo(GDK_DISPLAY(), GDK_ROOT_WINDOW(), mit_info);
if (mit_info->idle >= kIdleTimeout && !handler->IsIdle()) {
UserAwayEvent e(true);
EventBus::FireEvent(e);
} else if (mit_info->idle < kIdleTimeout && handler->IsIdle()) {
UserAwayEvent e(false);
EventBus::FireEvent(e);
}
return true;
}
void
GdkEventDispatcher(GdkEvent *event, gpointer data) {
BrowserWindow *window = window_util::LookupBrowserWindow(event);
if (window != NULL) {
// We have event for browser window
window->OnNativeEvent(event);
}
gtk_main_do_event(event);
}
bool
CheckLogFileSize(CefString path) {
std::string file_path = path;
struct stat stat_buf;
int rc = stat(file_path.c_str(), &stat_buf);
if (rc == 0 && stat_buf.st_size > 1024*1024*20) {
unlink(file_path.c_str());
LOG(INFO) << "Runtime log is too big (" << stat_buf.st_size << ") and will be truncated";
}
return true;
}
} // namespace
// static
const char*
BrickApp::GetConfigHome() {
return g_get_user_config_dir();
}
// static
std::string
BrickApp::FindUserConfig(const char* name) {
std::string result = "";
char* filename = g_build_filename(g_get_user_config_dir(), APP_COMMON_NAME, name, NULL);
if (platform_util::IsPathExists(filename))
result = filename;
g_free(filename);
return result;
}
// static
std::string
BrickApp::FindSystemConfig(const char* name) {
std::string result = "";
const gchar* const *dirs = g_get_system_config_dirs();
const gchar* const *dir;
char* filename;
for (dir = dirs; *dir; ++dir) {
filename = g_build_filename(*dir, APP_COMMON_NAME, name, NULL);
if (platform_util::IsPathExists(filename)) {
result = filename;
g_free(filename);
break;
}
g_free(filename);
}
return result;
}
const std::string
BrickApp::GetCurrentLanguage(bool withTags) {
if (startupLocale.empty())
startupLocale = pango_language_to_string(gtk_get_default_language());
std::string::size_type pos;
// withTags = true means returns "en_US" for locale "en_US.UTF-8"
// Otherwise returns only language "en"
if (withTags)
pos = startupLocale.find('.');
else
pos = startupLocale.find_first_of("-_");
std::string result;
if (pos != std::string::npos)
result = startupLocale.substr(0, pos);
else
result = startupLocale;
if (result.empty() || result == "c")
result = withTags ? "en-us" : "en"; // Use "en" by default
// TODO(buglloc): R&D, maybe we may using locale as-is, without stripping?
return result;
}
const std::string
BrickApp::GetAcceptLanguageList() {
std::ostringstream result;
result << GetCurrentLanguage(true) << "," << GetCurrentLanguage(false);
return result.str();
}
void
TerminationSignalHandler(int signatl) {
CefRefPtr<ClientHandler> handler = ClientHandler::GetInstance();
if (handler) {
handler->Shutdown(false);
} else {
CefQuitMessageLoop();
}
}
int main(int argc, char* argv[]) {
// TODO(buglloc): Good refactoring candidate!
setlocale(LC_ALL, "");
CefMainArgs main_args(argc, argv);
CefRefPtr<ClientApp> app(new ClientApp);
// Execute the secondary process, if any.
int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
if (exit_code >= 0)
return exit_code;
if (!EnsureSystemDirectoryExists()) {
printf("Can't create system directories");
return 1;
}
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
command_line->InitFromArgv(argc, (const char* const *) argv);
GetWorkingDir(szWorkingDir);
AppSettings app_settings = AppSettings::InitByJson(
BrickApp::GetSystemConfig()
);
app_settings.UpdateByJson(
BrickApp::GetUserConfig()
);
app_settings.UpdateByCommandLine(
command_line
);
app_settings.resource_dir = helper::BaseDir(szWorkingDir) + "/resources/";
CefSettings cef_settings = BrickApp::GetCefSettings(szWorkingDir, app_settings);
LOG_IF(WARNING,
!CheckLogFileSize(&cef_settings.log_file)) << "Can't check runtie log file size";
// If we have D-BUS - check single running with it (and call App::Present)
// Otherwise - fallback to EnsureSingleInstance with flock
CefRefPtr<DBusProtocol> dbus = NULL;
if (app_settings.external_api) {
dbus = new DBusProtocol;
if (dbus->Init() && !dbus->isSingleInstance()) {
// We already own D-BUS session in another instance
dbus->BringAnotherInstance();
printf("Another instance is already running.");
return 0;
}
} else if (!EnsureSingleInstance()) {
printf("Another instance is already running.");
return 0;
}
CefRefPtr<AccountManager> account_manager(new AccountManager);
account_manager->Init(
std::string(BrickApp::GetConfigHome()) + "/" + APP_COMMON_NAME + "/accounts.json"
);
CefRefPtr<CacheManager> cache_manager(new CacheManager);
cache_manager->Init(
platform_util::GetCacheDir() + "/" + APP_COMMON_NAME + "/app/"
);
// TODO(buglloc): need to be safer?
cache_manager->CleanUpCache();
gtk_init(0, NULL);
// TODO(buglloc): Maybe better to set scale in main_args here?
app->SetDeviceScaleFactor(window_util::GetDeviceScaleFactor());
// Initialize CEF.
CefInitialize(main_args, cef_settings, app.get(), NULL);
gdk_event_handler_set(GdkEventDispatcher, NULL, NULL);
window_util::InitHooks();
if (app_settings.auto_away) {
gtk_timeout_add(kIdleCheckInterval, CheckUserIdle, NULL);
}
// Set default windows icon. Important to do this before any GTK window created!
GList *icons = NULL;
std::string icon_path = app_settings.resource_dir + "/app_icons/";
int icons_count = sizeof(kAppIcons) / sizeof(kAppIcons[0]);
for (int i = 0; i < icons_count; ++i) {
GdkPixbuf *icon = gdk_pixbuf_new_from_file((icon_path + kAppIcons[i]).c_str(), NULL);
if (!icon)
continue;
icons = g_list_append(icons, icon);
}
window_util::SetDefaultIcons(icons);
// Create the handler.
CefRefPtr<ClientHandler> client_handler(new ClientHandler);
client_handler->SetAppSettings(app_settings);
client_handler->SetAccountManager(account_manager);
client_handler->SetNotificationManager(new NotificationManager);
client_handler->SetCacheManager(cache_manager);
// Initialize status icon
CefRefPtr<BrickIndicator> brick_indicator(new BrickIndicator(app_settings.resource_dir + "/indicator/icons/"));
brick_indicator->UseExtendedStatus(app_settings.extended_status);
client_handler->SetIndicatorHandle(brick_indicator);
client_handler->Initialize();
std::string startup_url = account_manager->GetCurrentAccount()->GetBaseUrl();
if (account_manager->GetCurrentAccount()->IsExisted()) {
// Login to our account
startup_url += "internals/web/pages/portal-loader#login=yes";
} else {
// Otherwise let's show error page
startup_url += "internals/web/pages/home";
}
// Setup main window size & positions
CefRect screen_rect = window_util::GetDefaultScreenRect();
CefWindowInfo window_info;
window_info.width = static_cast<unsigned int>(kMainWindowWidth * window_util::GetDeviceScaleFactor());
window_info.height = static_cast<unsigned int>(kMainWindowHeight * window_util::GetDeviceScaleFactor());
window_info.x = screen_rect.x + (screen_rect.width - window_info.width) / 2;
window_info.y = screen_rect.y + (screen_rect.height - window_info.height) / 2;
// Create browser
CefBrowserHost::CreateBrowserSync(
window_info, client_handler.get(),
startup_url, BrickApp::GetBrowserSettings(szWorkingDir, app_settings), NULL);
// Install a signal handler so we clean up after ourselves.
signal(SIGINT, TerminationSignalHandler);
signal(SIGTERM, TerminationSignalHandler);
CefRunMessageLoop();
CefShutdown();
return 0;
}
<commit_msg>Fixed signed and unsigned comparison in AFK timer<commit_after>// Copyright (c) 2015 The Brick Authors.
#include "brick/brick_app.h"
#include <unistd.h>
#include <gtk/gtk.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <X11/Xlib.h>
#include <X11/extensions/scrnsaver.h>
#include "third-party/json/json.h"
#include "include/wrapper/cef_helpers.h"
#include "include/cef_app.h"
#include "brick/indicator/indicator.h"
#include "brick/client_handler.h"
#include "brick/client_app.h"
#include "brick/window_util.h"
#include "brick/helper.h"
#include "brick/platform_util.h"
#include "brick/external_interface/dbus_protocol.h"
#undef Status // Definition conflicts with cef_urlrequest.h
#undef Success // Definition conflicts with cef_message_router.h
namespace {
const int kMainWindowWidth = 914;
const int kMainWindowHeight = 454;
const unsigned long kIdleTimeout = 600000L;
const unsigned long kIdleCheckInterval = 10000L;
std::string kAppIcons[] = {"brick16.png", "brick32.png", "brick48.png", "brick128.png", "brick256.png"};
std::string szWorkingDir; // The current working directory
std::string startupLocale;
bool
GetWorkingDir(std::string& dir) {
char buff[1024];
// Retrieve the executable path.
ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len == -1)
return false;
buff[len] = 0;
dir = std::string(buff);
// Remove the executable name from the path.
dir = dir.substr(0, dir.find_last_of("/"));
return true;
}
bool
EnsureSystemDirectoryExists() {
return (
platform_util::MakeDirectory(platform_util::GetCacheDir() + "/" + APP_COMMON_NAME)
&& platform_util::MakeDirectory(platform_util::GetCacheDir() + "/" + APP_COMMON_NAME)
);
}
bool
EnsureSingleInstance() {
std::string lock_file = platform_util::GetCacheDir() + "/" + APP_COMMON_NAME + "/run.lock";
int fd = open(lock_file.c_str(), O_CREAT, 0600);
if (fd == -1)
return true;
return flock(fd, LOCK_EX|LOCK_NB) == 0;
}
gboolean
CheckUserIdle(gpointer data) {
/* Query xscreensaver */
static XScreenSaverInfo *mit_info = NULL;
static int has_extension = -1;
int event_base, error_base;
if (has_extension == -1)
has_extension = XScreenSaverQueryExtension(GDK_DISPLAY(), &event_base, &error_base);
if (!has_extension) {
LOG(WARNING) << "XScreenSaver extension not found, 'auto away' feature is being disabled.";
// Don't call this function anymore
return false;
}
CefRefPtr<ClientHandler> handler = ClientHandler::GetInstance();
if (!handler)
return true;
if (!handler->IsIdlePending())
return true;
if (mit_info == NULL)
mit_info = XScreenSaverAllocInfo();
XScreenSaverQueryInfo(GDK_DISPLAY(), GDK_ROOT_WINDOW(), mit_info);
if (mit_info->idle >= kIdleTimeout && !handler->IsIdle()) {
UserAwayEvent e(true);
EventBus::FireEvent(e);
} else if (mit_info->idle < kIdleTimeout && handler->IsIdle()) {
UserAwayEvent e(false);
EventBus::FireEvent(e);
}
return true;
}
void
GdkEventDispatcher(GdkEvent *event, gpointer data) {
BrowserWindow *window = window_util::LookupBrowserWindow(event);
if (window != NULL) {
// We have event for browser window
window->OnNativeEvent(event);
}
gtk_main_do_event(event);
}
bool
CheckLogFileSize(CefString path) {
std::string file_path = path;
struct stat stat_buf;
int rc = stat(file_path.c_str(), &stat_buf);
if (rc == 0 && stat_buf.st_size > 1024*1024*20) {
unlink(file_path.c_str());
LOG(INFO) << "Runtime log is too big (" << stat_buf.st_size << ") and will be truncated";
}
return true;
}
} // namespace
// static
const char*
BrickApp::GetConfigHome() {
return g_get_user_config_dir();
}
// static
std::string
BrickApp::FindUserConfig(const char* name) {
std::string result = "";
char* filename = g_build_filename(g_get_user_config_dir(), APP_COMMON_NAME, name, NULL);
if (platform_util::IsPathExists(filename))
result = filename;
g_free(filename);
return result;
}
// static
std::string
BrickApp::FindSystemConfig(const char* name) {
std::string result = "";
const gchar* const *dirs = g_get_system_config_dirs();
const gchar* const *dir;
char* filename;
for (dir = dirs; *dir; ++dir) {
filename = g_build_filename(*dir, APP_COMMON_NAME, name, NULL);
if (platform_util::IsPathExists(filename)) {
result = filename;
g_free(filename);
break;
}
g_free(filename);
}
return result;
}
const std::string
BrickApp::GetCurrentLanguage(bool withTags) {
if (startupLocale.empty())
startupLocale = pango_language_to_string(gtk_get_default_language());
std::string::size_type pos;
// withTags = true means returns "en_US" for locale "en_US.UTF-8"
// Otherwise returns only language "en"
if (withTags)
pos = startupLocale.find('.');
else
pos = startupLocale.find_first_of("-_");
std::string result;
if (pos != std::string::npos)
result = startupLocale.substr(0, pos);
else
result = startupLocale;
if (result.empty() || result == "c")
result = withTags ? "en-us" : "en"; // Use "en" by default
// TODO(buglloc): R&D, maybe we may using locale as-is, without stripping?
return result;
}
const std::string
BrickApp::GetAcceptLanguageList() {
std::ostringstream result;
result << GetCurrentLanguage(true) << "," << GetCurrentLanguage(false);
return result.str();
}
void
TerminationSignalHandler(int signatl) {
CefRefPtr<ClientHandler> handler = ClientHandler::GetInstance();
if (handler) {
handler->Shutdown(false);
} else {
CefQuitMessageLoop();
}
}
int main(int argc, char* argv[]) {
// TODO(buglloc): Good refactoring candidate!
setlocale(LC_ALL, "");
CefMainArgs main_args(argc, argv);
CefRefPtr<ClientApp> app(new ClientApp);
// Execute the secondary process, if any.
int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
if (exit_code >= 0)
return exit_code;
if (!EnsureSystemDirectoryExists()) {
printf("Can't create system directories");
return 1;
}
CefRefPtr<CefCommandLine> command_line = CefCommandLine::CreateCommandLine();
command_line->InitFromArgv(argc, (const char* const *) argv);
GetWorkingDir(szWorkingDir);
AppSettings app_settings = AppSettings::InitByJson(
BrickApp::GetSystemConfig()
);
app_settings.UpdateByJson(
BrickApp::GetUserConfig()
);
app_settings.UpdateByCommandLine(
command_line
);
app_settings.resource_dir = helper::BaseDir(szWorkingDir) + "/resources/";
CefSettings cef_settings = BrickApp::GetCefSettings(szWorkingDir, app_settings);
LOG_IF(WARNING,
!CheckLogFileSize(&cef_settings.log_file)) << "Can't check runtie log file size";
// If we have D-BUS - check single running with it (and call App::Present)
// Otherwise - fallback to EnsureSingleInstance with flock
CefRefPtr<DBusProtocol> dbus = NULL;
if (app_settings.external_api) {
dbus = new DBusProtocol;
if (dbus->Init() && !dbus->isSingleInstance()) {
// We already own D-BUS session in another instance
dbus->BringAnotherInstance();
printf("Another instance is already running.");
return 0;
}
} else if (!EnsureSingleInstance()) {
printf("Another instance is already running.");
return 0;
}
CefRefPtr<AccountManager> account_manager(new AccountManager);
account_manager->Init(
std::string(BrickApp::GetConfigHome()) + "/" + APP_COMMON_NAME + "/accounts.json"
);
CefRefPtr<CacheManager> cache_manager(new CacheManager);
cache_manager->Init(
platform_util::GetCacheDir() + "/" + APP_COMMON_NAME + "/app/"
);
// TODO(buglloc): need to be safer?
cache_manager->CleanUpCache();
gtk_init(0, NULL);
// TODO(buglloc): Maybe better to set scale in main_args here?
app->SetDeviceScaleFactor(window_util::GetDeviceScaleFactor());
// Initialize CEF.
CefInitialize(main_args, cef_settings, app.get(), NULL);
gdk_event_handler_set(GdkEventDispatcher, NULL, NULL);
window_util::InitHooks();
if (app_settings.auto_away) {
gtk_timeout_add(kIdleCheckInterval, CheckUserIdle, NULL);
}
// Set default windows icon. Important to do this before any GTK window created!
GList *icons = NULL;
std::string icon_path = app_settings.resource_dir + "/app_icons/";
int icons_count = sizeof(kAppIcons) / sizeof(kAppIcons[0]);
for (int i = 0; i < icons_count; ++i) {
GdkPixbuf *icon = gdk_pixbuf_new_from_file((icon_path + kAppIcons[i]).c_str(), NULL);
if (!icon)
continue;
icons = g_list_append(icons, icon);
}
window_util::SetDefaultIcons(icons);
// Create the handler.
CefRefPtr<ClientHandler> client_handler(new ClientHandler);
client_handler->SetAppSettings(app_settings);
client_handler->SetAccountManager(account_manager);
client_handler->SetNotificationManager(new NotificationManager);
client_handler->SetCacheManager(cache_manager);
// Initialize status icon
CefRefPtr<BrickIndicator> brick_indicator(new BrickIndicator(app_settings.resource_dir + "/indicator/icons/"));
brick_indicator->UseExtendedStatus(app_settings.extended_status);
client_handler->SetIndicatorHandle(brick_indicator);
client_handler->Initialize();
std::string startup_url = account_manager->GetCurrentAccount()->GetBaseUrl();
if (account_manager->GetCurrentAccount()->IsExisted()) {
// Login to our account
startup_url += "internals/web/pages/portal-loader#login=yes";
} else {
// Otherwise let's show error page
startup_url += "internals/web/pages/home";
}
// Setup main window size & positions
CefRect screen_rect = window_util::GetDefaultScreenRect();
CefWindowInfo window_info;
window_info.width = static_cast<unsigned int>(kMainWindowWidth * window_util::GetDeviceScaleFactor());
window_info.height = static_cast<unsigned int>(kMainWindowHeight * window_util::GetDeviceScaleFactor());
window_info.x = screen_rect.x + (screen_rect.width - window_info.width) / 2;
window_info.y = screen_rect.y + (screen_rect.height - window_info.height) / 2;
// Create browser
CefBrowserHost::CreateBrowserSync(
window_info, client_handler.get(),
startup_url, BrickApp::GetBrowserSettings(szWorkingDir, app_settings), NULL);
// Install a signal handler so we clean up after ourselves.
signal(SIGINT, TerminationSignalHandler);
signal(SIGTERM, TerminationSignalHandler);
CefRunMessageLoop();
CefShutdown();
return 0;
}
<|endoftext|>
|
<commit_before>#include "TestGeneratedProperty.h"
#include "PEG/test.peg.h"
#include "PEG/test2.peg.h"
#include <QtTest/QtTest>
void TestGeneratedProperty::test1()
{
QtnPropertySetTest1 p;
QVERIFY(p.name() == "Test1");
p.a = 2;
QVERIFY(p.a == 2);
p.a = 15;
QVERIFY(p.a.maxValue() == 10);
QVERIFY(p.a == 2);
p.a.incrementValue();
QVERIFY(p.a == 1);
QVERIFY(p.a > 0 && p.a >= 0 && p.a < 2 && p.a <= 1 && p.a != 3);
QVERIFY(p.text == "#^{};");
QVERIFY(p.text.description() == "defrf\"sde\"""deerf3rfderf r g\r\nreg r{}dfrgergfwrewre");
p.text = tr("new value");
QVERIFY(p.text == "new value");
}
void TestGeneratedProperty::test2()
{
QtnPropertySetTest3 n(this);
n.setName("SS");
QVERIFY(n.name() == "SS");
QVERIFY(n.yy.rect == QRect(10, 10, 10, 10));
QVERIFY(!n.s.a);
n.s.a = true;
QVERIFY(n.s.a);
QVERIFY(n.yy.rect == QRect(1, 1, 1, 1));
QVERIFY(n.ww == n.bc && n.bc == false);
n.ww = true;
QVERIFY(n.ww == n.bc && n.ww == true);
n.bc = false;
QVERIFY(n.bc);
n.m_s = false;
n.bc = true;
QVERIFY(n.m_s);
}
void TestGeneratedProperty::testAllPropertyTypes()
{
QtnPropertySetAllPropertyTypes p;
QVERIFY(p.ep == COLOR::BLUE);
p.ep = COLOR::RED;
switch (p.ep)
{
case COLOR::BLUE:
case COLOR::YELLOW:
QFAIL("ep expected as COLOR::RED");
break;
case COLOR::RED:
break;
default:
QFAIL("ep expected as COLOR::RED");
}
}
void TestGeneratedProperty::testLoadSave()
{
{
QtnPropertySetAllPropertyTypes p;
QtnPropertySetA p2;
{
QtnPropertySet allProperties(nullptr);
allProperties.addChildProperty(&p, false);
allProperties.addChildProperty(&p2, false);
QByteArray data;
{
QDataStream s(&data, QIODevice::WriteOnly);
QVERIFY(allProperties.save(s));
}
qInfo(data.toBase64());
QCOMPARE(data.toBase64(), QByteArray("GYQBAAADngABAAAAAAAAAAABAAAADRmEAQAAA1QAAQAAAAAAAAAAAQAAAA4ZhAEAAAALAAEAAAAIAAAAAAAAAAAPGYQBAAAACwABAAAACAAAAAABAAAAEBmEAQAAAA4AAQAAAAgAAAAAAAAAAAAAABEZhAEAAAAOAAEAAAAIAAAAAAAAAAwAAAASGYQBAAAADgABAAAACAAAAAAAAAAAAAAAExmEAQAAAA4AAQAAAAgAAAAAAAAACQAAABQZhAEAAAASAAEAAAAIAAAAAAAAAAAAAAAAAAAAFRmEAQAAABIAAQAAAAgAAAAAP8mZmaAAAAAAAAAWGYQBAAAAEgABAAAACAAAAAAAAAAAAAAAAAAAABcZhAEAAAASAAEAAAAIAAAAAEBAMzMzMzMzAAAAGBmEAQAAAA4AAQAAAAgAAAAA/////wAAABkZhAEAAAAWAAEAAAAIAAAAAAAAAAgAbgBhAG0AZQAAABoZhAEAAAAaAAEAAAAIAAAAAAAAAAAAAAAA//////////8AAAAbGYQBAAAAGgABAAAACAAAAAAAAAAKAAAACgAAABMAAAATAAAAHBmEAQAAABIAAQAAAAgAAAAAAAAAAAAAAAAAAAAdGYQBAAAAEgABAAAACAAAAAAAAAAJAAAAAgAAAB4ZhAEAAAASAAEAAAAIAAAAAP//////////AAAAHxmEAQAAABIAAQAAAAgAAAAAAAAAIQAAABUAAAAgGYQBAAAADgABAAAACAAAAAAAAAAWAAAAIRmEAQAAAA4AAQAAAAgAAAAAAAAACgAAACIZhAEAAAAOAAEAAAAIAAAAAAAAAAUAAAAjGYQBAAAADgABAAAACAAAAAAAAAAFAAAAJBmEAQAAABUAAQAAAAgAAAAAAf//AAAAAP//AAAAAAAlGYQBAAAAFQABAAAACAAAAAAB/////wAAAAAAAAAAACYZhAEAAAA/AAEAAAAIAAAAAAAAAA4AQwBvAHUAcgBpAGUAcv////9AJAAAAAAAAP////8FAAEAMhAAZAEAAAAAAAAAAAAAAAAAJxmEAQAAADsAAQAAAAgAAAAAAAAACgBBAHIAaQBhAGz/////QDMAAAAAAAD/////BQABADIQAGQBAAAAAAAAAAAAAAAAACgZhAEAAAAKAAEAAAAIAAAAAP////8AAAAyGYQBAAAAJQABAAAAAAAAAAABAAAAMxmEAQAAAAsAAQAAAAgAAAAAAf//////////"));
//QCOMPARE(data.size(), 933);
{
QDataStream s(&data, QIODevice::ReadOnly);
QVERIFY(allProperties.load(s));
}
QString result;
QVERIFY(allProperties.toStr(result));
QCOMPARE(result.size(), 925);
}
}
}
void TestGeneratedProperty::testJson()
{
QtnPropertySetAllPropertyTypes p;
QJsonObject o;
QVERIFY(p.toJson(o));
QJsonDocument d(o);
auto res = d.toJson();
QCOMPARE(res.size(), 1321);
res = d.toJson(QJsonDocument::Compact);
QCOMPARE(res.size(), 752);
QVERIFY(p.fromJson(o));
}
<commit_msg>updated tests 2<commit_after>#include "TestGeneratedProperty.h"
#include "PEG/test.peg.h"
#include "PEG/test2.peg.h"
#include <QtTest/QtTest>
void TestGeneratedProperty::test1()
{
QtnPropertySetTest1 p;
QVERIFY(p.name() == "Test1");
p.a = 2;
QVERIFY(p.a == 2);
p.a = 15;
QVERIFY(p.a.maxValue() == 10);
QVERIFY(p.a == 2);
p.a.incrementValue();
QVERIFY(p.a == 1);
QVERIFY(p.a > 0 && p.a >= 0 && p.a < 2 && p.a <= 1 && p.a != 3);
QVERIFY(p.text == "#^{};");
QVERIFY(p.text.description() == "defrf\"sde\"""deerf3rfderf r g\r\nreg r{}dfrgergfwrewre");
p.text = tr("new value");
QVERIFY(p.text == "new value");
}
void TestGeneratedProperty::test2()
{
QtnPropertySetTest3 n(this);
n.setName("SS");
QVERIFY(n.name() == "SS");
QVERIFY(n.yy.rect == QRect(10, 10, 10, 10));
QVERIFY(!n.s.a);
n.s.a = true;
QVERIFY(n.s.a);
QVERIFY(n.yy.rect == QRect(1, 1, 1, 1));
QVERIFY(n.ww == n.bc && n.bc == false);
n.ww = true;
QVERIFY(n.ww == n.bc && n.ww == true);
n.bc = false;
QVERIFY(n.bc);
n.m_s = false;
n.bc = true;
QVERIFY(n.m_s);
}
void TestGeneratedProperty::testAllPropertyTypes()
{
QtnPropertySetAllPropertyTypes p;
QVERIFY(p.ep == COLOR::BLUE);
p.ep = COLOR::RED;
switch (p.ep)
{
case COLOR::BLUE:
case COLOR::YELLOW:
QFAIL("ep expected as COLOR::RED");
break;
case COLOR::RED:
break;
default:
QFAIL("ep expected as COLOR::RED");
}
}
void TestGeneratedProperty::testLoadSave()
{
{
QtnPropertySetAllPropertyTypes p;
QtnPropertySetA p2;
{
QtnPropertySet allProperties(nullptr);
allProperties.addChildProperty(&p, false);
allProperties.addChildProperty(&p2, false);
QByteArray data;
{
QDataStream s(&data, QIODevice::WriteOnly);
QVERIFY(allProperties.save(s));
}
printf(data.toBase64().data());
QCOMPARE(data.toBase64(), QByteArray("GYQBAAADngABAAAAAAAAAAABAAAADRmEAQAAA1QAAQAAAAAAAAAAAQAAAA4ZhAEAAAALAAEAAAAIAAAAAAAAAAAPGYQBAAAACwABAAAACAAAAAABAAAAEBmEAQAAAA4AAQAAAAgAAAAAAAAAAAAAABEZhAEAAAAOAAEAAAAIAAAAAAAAAAwAAAASGYQBAAAADgABAAAACAAAAAAAAAAAAAAAExmEAQAAAA4AAQAAAAgAAAAAAAAACQAAABQZhAEAAAASAAEAAAAIAAAAAAAAAAAAAAAAAAAAFRmEAQAAABIAAQAAAAgAAAAAP8mZmaAAAAAAAAAWGYQBAAAAEgABAAAACAAAAAAAAAAAAAAAAAAAABcZhAEAAAASAAEAAAAIAAAAAEBAMzMzMzMzAAAAGBmEAQAAAA4AAQAAAAgAAAAA/////wAAABkZhAEAAAAWAAEAAAAIAAAAAAAAAAgAbgBhAG0AZQAAABoZhAEAAAAaAAEAAAAIAAAAAAAAAAAAAAAA//////////8AAAAbGYQBAAAAGgABAAAACAAAAAAAAAAKAAAACgAAABMAAAATAAAAHBmEAQAAABIAAQAAAAgAAAAAAAAAAAAAAAAAAAAdGYQBAAAAEgABAAAACAAAAAAAAAAJAAAAAgAAAB4ZhAEAAAASAAEAAAAIAAAAAP//////////AAAAHxmEAQAAABIAAQAAAAgAAAAAAAAAIQAAABUAAAAgGYQBAAAADgABAAAACAAAAAAAAAAWAAAAIRmEAQAAAA4AAQAAAAgAAAAAAAAACgAAACIZhAEAAAAOAAEAAAAIAAAAAAAAAAUAAAAjGYQBAAAADgABAAAACAAAAAAAAAAFAAAAJBmEAQAAABUAAQAAAAgAAAAAAf//AAAAAP//AAAAAAAlGYQBAAAAFQABAAAACAAAAAAB/////wAAAAAAAAAAACYZhAEAAAA/AAEAAAAIAAAAAAAAAA4AQwBvAHUAcgBpAGUAcv////9AJAAAAAAAAP////8FAAEAMhAAZAEAAAAAAAAAAAAAAAAAJxmEAQAAADsAAQAAAAgAAAAAAAAACgBBAHIAaQBhAGz/////QDMAAAAAAAD/////BQABADIQAGQBAAAAAAAAAAAAAAAAACgZhAEAAAAKAAEAAAAIAAAAAP////8AAAAyGYQBAAAAJQABAAAAAAAAAAABAAAAMxmEAQAAAAsAAQAAAAgAAAAAAf//////////"));
//QCOMPARE(data.size(), 933);
{
QDataStream s(&data, QIODevice::ReadOnly);
QVERIFY(allProperties.load(s));
}
QString result;
QVERIFY(allProperties.toStr(result));
QCOMPARE(result.size(), 925);
}
}
}
void TestGeneratedProperty::testJson()
{
QtnPropertySetAllPropertyTypes p;
QJsonObject o;
QVERIFY(p.toJson(o));
QJsonDocument d(o);
auto res = d.toJson();
QCOMPARE(res.size(), 1321);
res = d.toJson(QJsonDocument::Compact);
QCOMPARE(res.size(), 752);
QVERIFY(p.fromJson(o));
}
<|endoftext|>
|
<commit_before>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "ui/Suite.h"
#include "mason/Hud.h"
#include "mason/Common.h"
#include "mason/Config.h"
#include "mason/Assets.h"
#include "mason/Profiling.h"
#include "HudTest.h"
#include "MiscTest.h"
//#include "BlendingTest.h"
#define USE_SECONDARY_SCREEN 1
#define MSAA 4
using namespace ci;
using namespace ci::app;
using namespace std;
class MasonTestsApp : public App {
public:
void setup() override;
void resize() override;
void keyDown( app::KeyEvent event ) override;
void update() override;
void draw() override;
void reload();
ui::SuiteRef mSuite;
bool mDrawHud = true;
bool mDrawProfiling = false;
};
void MasonTestsApp::setup()
{
ma::initialize( ma::getRepoRootPath() );
mSuite = make_shared<ui::Suite>();
mSuite->registerSuiteView<HudTest>( "hud" );
mSuite->registerSuiteView<MiscTest>( "misc" );
//mSuite->registerSuiteView<MotionTest>( "motion" );
reload();
}
void MasonTestsApp::reload()
{
ma::assets()->getFile( app::getAssetPath( "config.json" ), [this]( DataSourceRef dataSource ) {
CI_LOG_I( "config.json reloaded" );
ma::config()->read( dataSource );
size_t testIndex = (size_t)ma::config()->get<int>( "app", "test" );
mSuite->select( testIndex );
} );
}
void MasonTestsApp::keyDown( app::KeyEvent event )
{
if( event.isControlDown() ) {
if( tolower( event.getChar() ) == 'r' ) {
CI_LOG_I( "reloading suite" );
if( event.isShiftDown() ) {
CI_LOG_I( "- clearing variables" );
ma::hud()->clear();
}
mSuite->reload();
}
else if( event.getChar() == 'f' ) {
CI_LOG_I( "toggling fullscreen" );
setFullScreen( ! isFullScreen() );
}
else if( event.getChar() == 'h' ) {
CI_LOG_I( "toggling Hud" );
mDrawHud = ! mDrawHud;
mSuite->setDrawUiEnabled( mDrawHud );
}
else if( event.getChar() == 'l' )
mDrawProfiling = ! mDrawProfiling;
}
}
void MasonTestsApp::resize()
{
CI_LOG_I( "window size: " << getWindowSize() );
}
void MasonTestsApp::update()
{
{
CI_PROFILE_CPU( "Suite update" );
mSuite->update();
}
#if CI_PROFILING
if( mDrawProfiling )
perf::printProfiling();
#endif
}
void MasonTestsApp::draw()
{
CI_PROFILE_CPU( "main draw" );
gl::clear();
{
CI_PROFILE_CPU( "Suite draw" );
mSuite->draw();
}
if( mDrawHud ) {
CI_PROFILE_CPU( "Hud draw" );
ma::hud()->draw();
}
CI_CHECK_GL();
}
void prepareSettings( App::Settings *settings )
{
bool useSecondaryScreen = ( USE_SECONDARY_SCREEN && Display::getDisplays().size() > 1 );
if( useSecondaryScreen ) {
for( const auto &display : Display::getDisplays() ) {
//CI_LOG_I( "display name: " << display->getName() );
if( display->getName() == "Color LCD" ) {
// macbook
settings->setDisplay( display );
settings->setWindowSize( 1280, 720 );
}
else if( display->getName() == "Generic PnP Monitor" ) {
// gechic 1303i 13"touch display
settings->setDisplay( display );
settings->setFullScreen( true );
}
}
}
else {
#if defined( CINDER_MAC )
vec2 windowPos = { 0, 0 };
#else
vec2 windowPos = { 0, 24 };
#endif
settings->setWindowPos( windowPos.x, windowPos.y );
settings->setWindowSize( 960, 565 );
}
}
CINDER_APP( MasonTestsApp, RendererGl( RendererGl::Options().msaa( MSAA ) ), prepareSettings )
<commit_msg>add some gpu profiling and silence warning<commit_after>#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Log.h"
#include "ui/Suite.h"
#include "mason/Hud.h"
#include "mason/Common.h"
#include "mason/Config.h"
#include "mason/Assets.h"
#include "mason/Profiling.h"
#include "HudTest.h"
#include "MiscTest.h"
//#include "BlendingTest.h"
#define USE_SECONDARY_SCREEN 1
#define MSAA 4
using namespace ci;
using namespace ci::app;
using namespace std;
class MasonTestsApp : public App {
public:
void setup() override;
void resize() override;
void keyDown( app::KeyEvent event ) override;
void update() override;
void draw() override;
void reload();
ui::SuiteRef mSuite;
bool mDrawHud = true;
bool mDrawProfiling = false;
};
void MasonTestsApp::setup()
{
ma::initialize( ma::getRepoRootPath() );
mSuite = make_shared<ui::Suite>();
mSuite->registerSuiteView<HudTest>( "hud" );
mSuite->registerSuiteView<MiscTest>( "misc" );
//mSuite->registerSuiteView<MotionTest>( "motion" );
reload();
}
void MasonTestsApp::reload()
{
ma::assets()->getFile( app::getAssetPath( "config.json" ), [this]( DataSourceRef dataSource ) {
CI_LOG_I( "config.json reloaded" );
ma::config()->read( dataSource );
size_t testIndex = (size_t)ma::config()->get<int>( "app", "test" );
mSuite->select( testIndex );
} );
}
void MasonTestsApp::keyDown( app::KeyEvent event )
{
if( event.isControlDown() ) {
if( tolower( event.getChar() ) == 'r' ) {
CI_LOG_I( "reloading suite" );
if( event.isShiftDown() ) {
CI_LOG_I( "- clearing variables" );
ma::hud()->clear();
}
mSuite->reload();
}
else if( event.getChar() == 'f' ) {
CI_LOG_I( "toggling fullscreen" );
setFullScreen( ! isFullScreen() );
}
else if( event.getChar() == 'h' ) {
CI_LOG_I( "toggling Hud" );
mDrawHud = ! mDrawHud;
mSuite->setDrawUiEnabled( mDrawHud );
}
else if( event.getChar() == 'l' )
mDrawProfiling = ! mDrawProfiling;
}
}
void MasonTestsApp::resize()
{
CI_LOG_I( "window size: " << getWindowSize() );
}
void MasonTestsApp::update()
{
{
CI_PROFILE_CPU( "Suite update" );
CI_PROFILE_GPU( "Suite update" );
mSuite->update();
}
#if CI_PROFILING
if( mDrawProfiling )
perf::printProfiling();
#endif
}
void MasonTestsApp::draw()
{
CI_PROFILE_CPU( "main draw" );
CI_PROFILE_GPU( "main draw" );
gl::clear();
{
CI_PROFILE_CPU( "Suite draw" );
CI_PROFILE_GPU( "Suite draw" );
mSuite->draw();
}
if( mDrawHud ) {
CI_PROFILE_CPU( "Hud draw" );
CI_PROFILE_GPU( "Hud draw" );
ma::hud()->draw();
}
CI_CHECK_GL();
}
void prepareSettings( App::Settings *settings )
{
bool useSecondaryScreen = ( USE_SECONDARY_SCREEN && Display::getDisplays().size() > 1 );
if( useSecondaryScreen ) {
for( const auto &display : Display::getDisplays() ) {
//CI_LOG_I( "display name: " << display->getName() );
if( display->getName() == "Color LCD" ) {
// macbook
settings->setDisplay( display );
settings->setWindowSize( 1280, 720 );
}
else if( display->getName() == "Generic PnP Monitor" ) {
// gechic 1303i 13"touch display
settings->setDisplay( display );
settings->setFullScreen( true );
}
}
}
else {
#if defined( CINDER_MAC )
ivec2 windowPos = { 0, 0 };
#else
ivec2 windowPos = { 0, 24 };
#endif
settings->setWindowPos( windowPos.x, windowPos.y );
settings->setWindowSize( 960, 565 );
}
}
CINDER_APP( MasonTestsApp, RendererGl( RendererGl::Options().msaa( MSAA ) ), prepareSettings )
<|endoftext|>
|
<commit_before>#include <GL/glew.h>
#include "Shader.hpp"
Shader::Shader(std::ifstream & ShaderFile,GLuint ProgramID,int Type,std::string name)
{
ShaderFile.seekg(0,std::ios_base::end);
int length=ShaderFile.tellg();
ShaderFile.seekg(0,std::ios_base::beg);
char * Contents=new char[length+1];
ShaderFile.read(Contents,length);
Contents[length]=0;
ID=glCreateShader(Type);
char ** temp=&Contents;
glShaderSource(ID,1,(const char **)temp,NULL);
glCompileShader(ID);
GLint ShaderSuccess;
glGetShaderiv(ID,GL_COMPILE_STATUS,&ShaderSuccess);
if(ShaderSuccess!=GL_TRUE)
{
int LogLen;
glGetShaderiv(ID,GL_INFO_LOG_LENGTH,&LogLen);
GLchar * ShaderLog=new GLchar[LogLen];
glGetShaderInfoLog(ID,LogLen,NULL,ShaderLog);
std::cout<<name<<" failed to compile "<<ShaderLog<<std::endl;
delete [] ShaderLog;
}
else
std::cout<<"Successfully compiled "<<name<<std::endl;
glAttachShader(ProgramID,ID);
delete [] Contents;
}
void Shader::Detach(GLuint ProgramID)
{
glDetachShader(ProgramID,ID);
}
Shader::~Shader()
{
glDeleteShader(ID);
}
const std::string ShaderExtensions[]={".vs.glsl",".tc.glsl",".te.glsl",".gs.glsl",".fs.glsl"};
const int ShaderTypes[]={GL_VERTEX_SHADER,GL_TESS_CONTROL_SHADER,GL_TESS_EVALUATION_SHADER,GL_GEOMETRY_SHADER,GL_FRAGMENT_SHADER};
//const int NumShaderTypes=sizeof(ShaderTypes)/sizeof(ShaderTypes[0]);
GLuint ShaderProgram::GetUniformLocation(std::string name)
{
GLuint ret= glGetUniformLocation(ID,name.c_str());
GLenum ErrorValue = glGetError();
if(ErrorValue!=GL_NO_ERROR)
std::cout<<"failed to get uniform location of "<<name<<" : "<<gluErrorString(ErrorValue)<<std::endl;
return ret;
}
void ShaderProgram::LoadShaders(std::string ShaderNames[])
{
std::ifstream ShaderFile;
for(int i=0;i<NumShaderTypes;i++)
{
ShaderFile.open(("shaders/"+ShaderNames[i]).c_str());
if(ShaderFile.good())
{
Shaders[i]=new Shader(ShaderFile,ID,ShaderTypes[i],ShaderNames[i]);
ShaderFile.close();
}
else
Shaders[i]=0;
}
glLinkProgram(ID);
glUseProgram(ID);
}
ShaderProgram::ShaderProgram(std::string VSName,std::string FSName,std::string GSName, std::string TCSName,std::string TESName)
{
ID=glCreateProgram();
std::string ShaderNames[]={VSName,FSName,GSName,TCSName,TESName};
LoadShaders(ShaderNames);
}
ShaderProgram::ShaderProgram(std::string name)
{
ID=glCreateProgram();
std::string ShaderNames[NumShaderTypes];
for(int i=0;i<NumShaderTypes;i++)
{
ShaderNames[i]=name+ShaderExtensions[i];
}
LoadShaders(ShaderNames);
}
ShaderProgram::~ShaderProgram()
{
glUseProgram(0);//for now, really should fix to only do if in use
for(int i=0;i<NumShaderTypes;i++)
{
if(Shaders[i])
{
Shaders[i]->Detach(ID);
delete Shaders[i];
}
}
glDeleteProgram(ID);
}
<commit_msg>Use the already read shader file length when passing the source to OpenGL.<commit_after>#include <GL/glew.h>
#include "Shader.hpp"
Shader::Shader(std::ifstream & ShaderFile,GLuint ProgramID,int Type,std::string name)
{
ShaderFile.seekg(0,std::ios_base::end);
int length=ShaderFile.tellg();
ShaderFile.seekg(0,std::ios_base::beg);
char * Contents=new char[length+1];
ShaderFile.read(Contents,length);
Contents[length]=0;
ID=glCreateShader(Type);
char ** temp=&Contents;
glShaderSource(ID,1,(const char **)temp,&length);
glCompileShader(ID);
GLint ShaderSuccess;
glGetShaderiv(ID,GL_COMPILE_STATUS,&ShaderSuccess);
if(ShaderSuccess!=GL_TRUE)
{
int LogLen;
glGetShaderiv(ID,GL_INFO_LOG_LENGTH,&LogLen);
GLchar * ShaderLog=new GLchar[LogLen];
glGetShaderInfoLog(ID,LogLen,NULL,ShaderLog);
std::cout<<name<<" failed to compile "<<ShaderLog<<std::endl;
delete [] ShaderLog;
}
else
std::cout<<"Successfully compiled "<<name<<std::endl;
glAttachShader(ProgramID,ID);
delete [] Contents;
}
void Shader::Detach(GLuint ProgramID)
{
glDetachShader(ProgramID,ID);
}
Shader::~Shader()
{
glDeleteShader(ID);
}
const std::string ShaderExtensions[]={".vs.glsl",".tc.glsl",".te.glsl",".gs.glsl",".fs.glsl"};
const int ShaderTypes[]={GL_VERTEX_SHADER,GL_TESS_CONTROL_SHADER,GL_TESS_EVALUATION_SHADER,GL_GEOMETRY_SHADER,GL_FRAGMENT_SHADER};
//const int NumShaderTypes=sizeof(ShaderTypes)/sizeof(ShaderTypes[0]);
GLuint ShaderProgram::GetUniformLocation(std::string name)
{
GLuint ret= glGetUniformLocation(ID,name.c_str());
GLenum ErrorValue = glGetError();
if(ErrorValue!=GL_NO_ERROR)
std::cout<<"failed to get uniform location of "<<name<<" : "<<gluErrorString(ErrorValue)<<std::endl;
return ret;
}
void ShaderProgram::LoadShaders(std::string ShaderNames[])
{
std::ifstream ShaderFile;
for(int i=0;i<NumShaderTypes;i++)
{
ShaderFile.open(("shaders/"+ShaderNames[i]).c_str());
if(ShaderFile.good())
{
Shaders[i]=new Shader(ShaderFile,ID,ShaderTypes[i],ShaderNames[i]);
ShaderFile.close();
}
else
Shaders[i]=0;
}
glLinkProgram(ID);
glUseProgram(ID);
}
ShaderProgram::ShaderProgram(std::string VSName,std::string FSName,std::string GSName, std::string TCSName,std::string TESName)
{
ID=glCreateProgram();
std::string ShaderNames[]={VSName,FSName,GSName,TCSName,TESName};
LoadShaders(ShaderNames);
}
ShaderProgram::ShaderProgram(std::string name)
{
ID=glCreateProgram();
std::string ShaderNames[NumShaderTypes];
for(int i=0;i<NumShaderTypes;i++)
{
ShaderNames[i]=name+ShaderExtensions[i];
}
LoadShaders(ShaderNames);
}
ShaderProgram::~ShaderProgram()
{
glUseProgram(0);//for now, really should fix to only do if in use
for(int i=0;i<NumShaderTypes;i++)
{
if(Shaders[i])
{
Shaders[i]->Detach(ID);
delete Shaders[i];
}
}
glDeleteProgram(ID);
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#ifdef HAVE_CUDA
#include <cuda_runtime_api.h>
void print_info()
{
printf("\n");
#if defined _WIN32
# if defined _WIN64
puts("OS: Windows 64");
# else
puts("OS: Windows 32");
# endif
#elif defined linux
# if defined _LP64
puts("OS: Linux 64");
# else
puts("OS: Linux 32");
# endif
#elif defined __APPLE__
# if defined _LP64
puts("OS: Apple 64");
# else
puts("OS: Apple 32");
# endif
#endif
int deviceCount = cv::gpu::getCudaEnabledDeviceCount();
int driver;
cudaDriverGetVersion(&driver);
printf("CUDA Driver version: %d\n", driver);
printf("CUDA Runtime version: %d\n", CUDART_VERSION);
printf("CUDA device count: %d\n\n", deviceCount);
for (int i = 0; i < deviceCount; ++i)
{
cv::gpu::DeviceInfo info(i);
printf("Device %d:\n", i);
printf(" Name: %s\n", info.name().c_str());
printf(" Compute capability version: %d.%d\n", info.majorVersion(), info.minorVersion());
printf(" Total memory: %d Mb\n", static_cast<int>(static_cast<int>(info.totalMemory() / 1024.0) / 1024.0));
printf(" Free memory: %d Mb\n", static_cast<int>(static_cast<int>(info.freeMemory() / 1024.0) / 1024.0));
if (info.isCompatible())
puts(" This device is compatible with current GPU module build\n");
else
puts(" This device is NOT compatible with current GPU module build\n");
}
puts("GPU module was compiled for the following GPU archs:");
printf(" BIN: %s\n", CUDA_ARCH_BIN);
printf(" PTX: %s\n\n", CUDA_ARCH_PTX);
}
enum OutputLevel
{
OutputLevelNone,
OutputLevelCompact,
OutputLevelFull
};
extern OutputLevel nvidiaTestOutputLevel;
int main(int argc, char** argv)
{
cvtest::TS::ptr()->init("gpu");
testing::InitGoogleTest(&argc, argv);
cv::CommandLineParser parser(argc, (const char**)argv);
std::string outputLevel = parser.get<std::string>("nvtest_output_level", "none");
if (outputLevel == "none")
nvidiaTestOutputLevel = OutputLevelNone;
else if (outputLevel == "compact")
nvidiaTestOutputLevel = OutputLevelCompact;
else if (outputLevel == "full")
nvidiaTestOutputLevel = OutputLevelFull;
print_info();
return RUN_ALL_TESTS();
}
#else // HAVE_CUDA
int main(int argc, char** argv)
{
printf("OpenCV was built without CUDA support\n");
return 0;
}
#endif // HAVE_CUDA
<commit_msg>temporarily fixed #1279<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#ifdef HAVE_CUDA
#include <cuda_runtime_api.h>
void print_info()
{
printf("\n");
#if defined _WIN32
# if defined _WIN64
puts("OS: Windows 64");
# else
puts("OS: Windows 32");
# endif
#elif defined linux
# if defined _LP64
puts("OS: Linux 64");
# else
puts("OS: Linux 32");
# endif
#elif defined __APPLE__
# if defined _LP64
puts("OS: Apple 64");
# else
puts("OS: Apple 32");
# endif
#endif
int deviceCount = cv::gpu::getCudaEnabledDeviceCount();
int driver;
cudaDriverGetVersion(&driver);
printf("CUDA Driver version: %d\n", driver);
printf("CUDA Runtime version: %d\n", CUDART_VERSION);
printf("CUDA device count: %d\n\n", deviceCount);
for (int i = 0; i < deviceCount; ++i)
{
cv::gpu::DeviceInfo info(i);
printf("Device %d:\n", i);
printf(" Name: %s\n", info.name().c_str());
printf(" Compute capability version: %d.%d\n", info.majorVersion(), info.minorVersion());
printf(" Total memory: %d Mb\n", static_cast<int>(static_cast<int>(info.totalMemory() / 1024.0) / 1024.0));
printf(" Free memory: %d Mb\n", static_cast<int>(static_cast<int>(info.freeMemory() / 1024.0) / 1024.0));
if (info.isCompatible())
puts(" This device is compatible with current GPU module build\n");
else
puts(" This device is NOT compatible with current GPU module build\n");
}
puts("GPU module was compiled for the following GPU archs:");
printf(" BIN: %s\n", CUDA_ARCH_BIN);
printf(" PTX: %s\n\n", CUDA_ARCH_PTX);
}
enum OutputLevel
{
OutputLevelNone,
OutputLevelCompact,
OutputLevelFull
};
extern OutputLevel nvidiaTestOutputLevel;
int main(int argc, char** argv)
{
cvtest::TS::ptr()->init("gpu");
testing::InitGoogleTest(&argc, argv);
//cv::CommandLineParser parser(argc, (const char**)argv);
std::string outputLevel = "none";//parser.get<std::string>("nvtest_output_level", "none");
if (outputLevel == "none")
nvidiaTestOutputLevel = OutputLevelNone;
else if (outputLevel == "compact")
nvidiaTestOutputLevel = OutputLevelCompact;
else if (outputLevel == "full")
nvidiaTestOutputLevel = OutputLevelFull;
print_info();
return RUN_ALL_TESTS();
}
#else // HAVE_CUDA
int main(int argc, char** argv)
{
printf("OpenCV was built without CUDA support\n");
return 0;
}
#endif // HAVE_CUDA
<|endoftext|>
|
<commit_before>#include "instance.hh"
#include "chacha20.hh"
namespace ssev{
template <typename protocol>
void instance<protocol>::timer_event(ev::periodic &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::recv_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::send_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::client_recv_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::client_send_event(ev::io &watcher, int revents){
}
template <typename protocol>
instance<protocol>::instance(int fd,const ev::dynamic_loop &l):client_fd(fd),
io_read(l),io_write(l),
client_io_read(l),client_io_write(l),
timer(l){
//io_read.set<instance, &instance<protocol>::recv_event>(this);
client_io_read.set<instance, &instance<protocol>::client_recv_event>(this);
client_io_write.set<instance, &instance<protocol>::client_send_event>(this);
client_io_read.start(client_fd, ev::READ);
io_read.set<instance, &instance<protocol>::recv_event>(this);
io_write.set<instance, &instance<protocol>::send_event>(this);
timer.set<instance, &instance<protocol>::timer_event>(this);
}
template <typename protocol>
instance<protocol>::~instance(){
}
};
template class ssev::instance<ssev::ssocket5<ssev::chacha20>>;
<commit_msg>fcntl<commit_after>#include "instance.hh"
#include "chacha20.hh"
#include <fcntl.h>
namespace ssev{
template <typename protocol>
void instance<protocol>::timer_event(ev::periodic &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::recv_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::send_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::client_recv_event(ev::io &watcher, int revents){
}
template <typename protocol>
void instance<protocol>::client_send_event(ev::io &watcher, int revents){
}
template <typename protocol>
instance<protocol>::instance(int fd,const ev::dynamic_loop &l):client_fd(fd),
io_read(l),io_write(l),
client_io_read(l),client_io_write(l),
timer(l){
//io_read.set<instance, &instance<protocol>::recv_event>(this);
client_io_read.set<instance, &instance<protocol>::client_recv_event>(this);
client_io_write.set<instance, &instance<protocol>::client_send_event>(this);
fcntl(fd, F_SETFL, fcntl(client_fd, F_GETFL, 0) | O_NONBLOCK);
client_io_read.start(client_fd, ev::READ);
io_read.set<instance, &instance<protocol>::recv_event>(this);
io_write.set<instance, &instance<protocol>::send_event>(this);
timer.set<instance, &instance<protocol>::timer_event>(this);
}
template <typename protocol>
instance<protocol>::~instance(){
}
};
template class ssev::instance<ssev::ssocket5<ssev::chacha20>>;
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/pacing/include/paced_sender.h"
#include <assert.h>
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace_event.h"
namespace {
// Time limit in milliseconds between packet bursts.
const int kMinPacketLimitMs = 5;
// Upper cap on process interval, in case process has not been called in a long
// time.
const int kMaxIntervalTimeMs = 30;
// Max time that the first packet in the queue can sit in the queue if no
// packets are sent, regardless of buffer state. In practice only in effect at
// low bitrates (less than 320 kbits/s).
const int kMaxQueueTimeWithoutSendingMs = 30;
} // namespace
namespace webrtc {
bool PacedSender::PacketList::empty() const {
return packet_list_.empty();
}
PacedSender::Packet PacedSender::PacketList::front() const {
return packet_list_.front();
}
void PacedSender::PacketList::pop_front() {
PacedSender::Packet& packet = packet_list_.front();
packet_list_.pop_front();
sequence_number_set_.erase(packet.sequence_number_);
}
void PacedSender::PacketList::push_back(const PacedSender::Packet& packet) {
if (sequence_number_set_.find(packet.sequence_number_) ==
sequence_number_set_.end()) {
// Don't insert duplicates.
packet_list_.push_back(packet);
sequence_number_set_.insert(packet.sequence_number_);
}
}
PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps,
float pace_multiplier)
: callback_(callback),
pace_multiplier_(pace_multiplier),
enable_(false),
paused_(false),
critsect_(CriticalSectionWrapper::CreateCriticalSection()),
target_bitrate_kbytes_per_s_(target_bitrate_kbps >> 3), // Divide by 8.
bytes_remaining_interval_(0),
padding_bytes_remaining_interval_(0),
time_last_update_(TickTime::Now()),
capture_time_ms_last_queued_(0),
capture_time_ms_last_sent_(0) {
UpdateBytesPerInterval(kMinPacketLimitMs);
}
PacedSender::~PacedSender() {
}
void PacedSender::Pause() {
CriticalSectionScoped cs(critsect_.get());
paused_ = true;
}
void PacedSender::Resume() {
CriticalSectionScoped cs(critsect_.get());
paused_ = false;
}
void PacedSender::SetStatus(bool enable) {
CriticalSectionScoped cs(critsect_.get());
enable_ = enable;
}
void PacedSender::UpdateBitrate(int target_bitrate_kbps) {
CriticalSectionScoped cs(critsect_.get());
target_bitrate_kbytes_per_s_ = target_bitrate_kbps >> 3; // Divide by 8.
}
bool PacedSender::SendPacket(Priority priority, uint32_t ssrc,
uint16_t sequence_number, int64_t capture_time_ms, int bytes) {
CriticalSectionScoped cs(critsect_.get());
if (!enable_) {
UpdateState(bytes);
return true; // We can send now.
}
if (capture_time_ms < 0) {
capture_time_ms = TickTime::MillisecondTimestamp();
}
if (paused_) {
// Queue all packets when we are paused.
switch (priority) {
case kHighPriority:
high_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
break;
case kNormalPriority:
if (capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
case kLowPriority:
// Queue the low priority packets in the normal priority queue when we
// are paused to avoid starvation.
normal_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
break;
}
return false;
}
switch (priority) {
case kHighPriority:
if (high_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
high_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
case kNormalPriority:
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
if (capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
normal_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
case kLowPriority:
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
low_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
low_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
}
return false;
}
int PacedSender::QueueInMs() const {
CriticalSectionScoped cs(critsect_.get());
int64_t now_ms = TickTime::MillisecondTimestamp();
int64_t oldest_packet_capture_time = now_ms;
if (!high_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
high_priority_packets_.front().capture_time_ms_);
}
if (!normal_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
normal_priority_packets_.front().capture_time_ms_);
}
if (!low_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
low_priority_packets_.front().capture_time_ms_);
}
return now_ms - oldest_packet_capture_time;
}
int32_t PacedSender::TimeUntilNextProcess() {
CriticalSectionScoped cs(critsect_.get());
int64_t elapsed_time_ms =
(TickTime::Now() - time_last_update_).Milliseconds();
if (elapsed_time_ms <= 0) {
return kMinPacketLimitMs;
}
if (elapsed_time_ms >= kMinPacketLimitMs) {
return 0;
}
return kMinPacketLimitMs - elapsed_time_ms;
}
int32_t PacedSender::Process() {
TickTime now = TickTime::Now();
CriticalSectionScoped cs(critsect_.get());
int elapsed_time_ms = (now - time_last_update_).Milliseconds();
time_last_update_ = now;
if (!paused_ && elapsed_time_ms > 0) {
uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms);
UpdateBytesPerInterval(delta_time_ms);
uint32_t ssrc;
uint16_t sequence_number;
int64_t capture_time_ms;
Priority priority;
bool last_packet;
while (GetNextPacket(&ssrc, &sequence_number, &capture_time_ms,
&priority, &last_packet)) {
if (priority == kNormalPriority) {
if (capture_time_ms > capture_time_ms_last_sent_) {
capture_time_ms_last_sent_ = capture_time_ms;
} else if (capture_time_ms == capture_time_ms_last_sent_ &&
last_packet) {
TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms);
}
}
critsect_->Leave();
callback_->TimeToSendPacket(ssrc, sequence_number, capture_time_ms);
critsect_->Enter();
}
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
low_priority_packets_.empty() &&
padding_bytes_remaining_interval_ > 0) {
critsect_->Leave();
callback_->TimeToSendPadding(padding_bytes_remaining_interval_);
critsect_->Enter();
padding_bytes_remaining_interval_ = 0;
bytes_remaining_interval_ -= padding_bytes_remaining_interval_;
}
}
return 0;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) {
uint32_t bytes_per_interval = target_bitrate_kbytes_per_s_ * delta_time_ms;
if (bytes_remaining_interval_ < 0) {
// We overused last interval, compensate this interval.
bytes_remaining_interval_ += pace_multiplier_ * bytes_per_interval;
} else {
// If we underused last interval we can't use it this interval.
bytes_remaining_interval_ = pace_multiplier_ * bytes_per_interval;
}
if (padding_bytes_remaining_interval_ < 0) {
// We overused last interval, compensate this interval.
padding_bytes_remaining_interval_ += bytes_per_interval;
} else {
// If we underused last interval we can't use it this interval.
padding_bytes_remaining_interval_ = bytes_per_interval;
}
}
// MUST have critsect_ when calling.
bool PacedSender::GetNextPacket(uint32_t* ssrc, uint16_t* sequence_number,
int64_t* capture_time_ms, Priority* priority,
bool* last_packet) {
if (bytes_remaining_interval_ <= 0) {
// All bytes consumed for this interval.
// Check if we have not sent in a too long time.
if ((TickTime::Now() - time_last_send_).Milliseconds() >
kMaxQueueTimeWithoutSendingMs) {
if (!high_priority_packets_.empty()) {
*priority = kHighPriority;
GetNextPacketFromList(&high_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!normal_priority_packets_.empty()) {
*priority = kNormalPriority;
GetNextPacketFromList(&normal_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
}
return false;
}
if (!high_priority_packets_.empty()) {
*priority = kHighPriority;
GetNextPacketFromList(&high_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!normal_priority_packets_.empty()) {
*priority = kNormalPriority;
GetNextPacketFromList(&normal_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!low_priority_packets_.empty()) {
*priority = kLowPriority;
GetNextPacketFromList(&low_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
return false;
}
void PacedSender::GetNextPacketFromList(PacketList* list,
uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms,
bool* last_packet) {
Packet packet = list->front();
UpdateState(packet.bytes_);
*sequence_number = packet.sequence_number_;
*ssrc = packet.ssrc_;
*capture_time_ms = packet.capture_time_ms_;
list->pop_front();
*last_packet = list->empty() ||
list->front().capture_time_ms_ > *capture_time_ms;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateState(int num_bytes) {
time_last_send_ = TickTime::Now();
bytes_remaining_interval_ -= num_bytes;
padding_bytes_remaining_interval_ -= num_bytes;
}
} // namespace webrtc
<commit_msg>Fix crash in pacer.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/pacing/include/paced_sender.h"
#include <assert.h>
#include "webrtc/modules/interface/module_common_types.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace_event.h"
namespace {
// Time limit in milliseconds between packet bursts.
const int kMinPacketLimitMs = 5;
// Upper cap on process interval, in case process has not been called in a long
// time.
const int kMaxIntervalTimeMs = 30;
// Max time that the first packet in the queue can sit in the queue if no
// packets are sent, regardless of buffer state. In practice only in effect at
// low bitrates (less than 320 kbits/s).
const int kMaxQueueTimeWithoutSendingMs = 30;
} // namespace
namespace webrtc {
bool PacedSender::PacketList::empty() const {
return packet_list_.empty();
}
PacedSender::Packet PacedSender::PacketList::front() const {
return packet_list_.front();
}
void PacedSender::PacketList::pop_front() {
PacedSender::Packet& packet = packet_list_.front();
uint16_t sequence_number = packet.sequence_number_;
packet_list_.pop_front();
sequence_number_set_.erase(sequence_number);
}
void PacedSender::PacketList::push_back(const PacedSender::Packet& packet) {
if (sequence_number_set_.find(packet.sequence_number_) ==
sequence_number_set_.end()) {
// Don't insert duplicates.
packet_list_.push_back(packet);
sequence_number_set_.insert(packet.sequence_number_);
}
}
PacedSender::PacedSender(Callback* callback, int target_bitrate_kbps,
float pace_multiplier)
: callback_(callback),
pace_multiplier_(pace_multiplier),
enable_(false),
paused_(false),
critsect_(CriticalSectionWrapper::CreateCriticalSection()),
target_bitrate_kbytes_per_s_(target_bitrate_kbps >> 3), // Divide by 8.
bytes_remaining_interval_(0),
padding_bytes_remaining_interval_(0),
time_last_update_(TickTime::Now()),
capture_time_ms_last_queued_(0),
capture_time_ms_last_sent_(0) {
UpdateBytesPerInterval(kMinPacketLimitMs);
}
PacedSender::~PacedSender() {
}
void PacedSender::Pause() {
CriticalSectionScoped cs(critsect_.get());
paused_ = true;
}
void PacedSender::Resume() {
CriticalSectionScoped cs(critsect_.get());
paused_ = false;
}
void PacedSender::SetStatus(bool enable) {
CriticalSectionScoped cs(critsect_.get());
enable_ = enable;
}
void PacedSender::UpdateBitrate(int target_bitrate_kbps) {
CriticalSectionScoped cs(critsect_.get());
target_bitrate_kbytes_per_s_ = target_bitrate_kbps >> 3; // Divide by 8.
}
bool PacedSender::SendPacket(Priority priority, uint32_t ssrc,
uint16_t sequence_number, int64_t capture_time_ms, int bytes) {
CriticalSectionScoped cs(critsect_.get());
if (!enable_) {
UpdateState(bytes);
return true; // We can send now.
}
if (capture_time_ms < 0) {
capture_time_ms = TickTime::MillisecondTimestamp();
}
if (paused_) {
// Queue all packets when we are paused.
switch (priority) {
case kHighPriority:
high_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
break;
case kNormalPriority:
if (capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
case kLowPriority:
// Queue the low priority packets in the normal priority queue when we
// are paused to avoid starvation.
normal_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
break;
}
return false;
}
switch (priority) {
case kHighPriority:
if (high_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
high_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
case kNormalPriority:
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
if (capture_time_ms > capture_time_ms_last_queued_) {
capture_time_ms_last_queued_ = capture_time_ms;
TRACE_EVENT_ASYNC_BEGIN1("webrtc_rtp", "PacedSend", capture_time_ms,
"capture_time_ms", capture_time_ms);
}
normal_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
case kLowPriority:
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
low_priority_packets_.empty() &&
bytes_remaining_interval_ > 0) {
UpdateState(bytes);
return true; // We can send now.
}
low_priority_packets_.push_back(
Packet(ssrc, sequence_number, capture_time_ms, bytes));
return false;
}
return false;
}
int PacedSender::QueueInMs() const {
CriticalSectionScoped cs(critsect_.get());
int64_t now_ms = TickTime::MillisecondTimestamp();
int64_t oldest_packet_capture_time = now_ms;
if (!high_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
high_priority_packets_.front().capture_time_ms_);
}
if (!normal_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
normal_priority_packets_.front().capture_time_ms_);
}
if (!low_priority_packets_.empty()) {
oldest_packet_capture_time = std::min(
oldest_packet_capture_time,
low_priority_packets_.front().capture_time_ms_);
}
return now_ms - oldest_packet_capture_time;
}
int32_t PacedSender::TimeUntilNextProcess() {
CriticalSectionScoped cs(critsect_.get());
int64_t elapsed_time_ms =
(TickTime::Now() - time_last_update_).Milliseconds();
if (elapsed_time_ms <= 0) {
return kMinPacketLimitMs;
}
if (elapsed_time_ms >= kMinPacketLimitMs) {
return 0;
}
return kMinPacketLimitMs - elapsed_time_ms;
}
int32_t PacedSender::Process() {
TickTime now = TickTime::Now();
CriticalSectionScoped cs(critsect_.get());
int elapsed_time_ms = (now - time_last_update_).Milliseconds();
time_last_update_ = now;
if (!paused_ && elapsed_time_ms > 0) {
uint32_t delta_time_ms = std::min(kMaxIntervalTimeMs, elapsed_time_ms);
UpdateBytesPerInterval(delta_time_ms);
uint32_t ssrc;
uint16_t sequence_number;
int64_t capture_time_ms;
Priority priority;
bool last_packet;
while (GetNextPacket(&ssrc, &sequence_number, &capture_time_ms,
&priority, &last_packet)) {
if (priority == kNormalPriority) {
if (capture_time_ms > capture_time_ms_last_sent_) {
capture_time_ms_last_sent_ = capture_time_ms;
} else if (capture_time_ms == capture_time_ms_last_sent_ &&
last_packet) {
TRACE_EVENT_ASYNC_END0("webrtc_rtp", "PacedSend", capture_time_ms);
}
}
critsect_->Leave();
callback_->TimeToSendPacket(ssrc, sequence_number, capture_time_ms);
critsect_->Enter();
}
if (high_priority_packets_.empty() &&
normal_priority_packets_.empty() &&
low_priority_packets_.empty() &&
padding_bytes_remaining_interval_ > 0) {
critsect_->Leave();
callback_->TimeToSendPadding(padding_bytes_remaining_interval_);
critsect_->Enter();
padding_bytes_remaining_interval_ = 0;
bytes_remaining_interval_ -= padding_bytes_remaining_interval_;
}
}
return 0;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateBytesPerInterval(uint32_t delta_time_ms) {
uint32_t bytes_per_interval = target_bitrate_kbytes_per_s_ * delta_time_ms;
if (bytes_remaining_interval_ < 0) {
// We overused last interval, compensate this interval.
bytes_remaining_interval_ += pace_multiplier_ * bytes_per_interval;
} else {
// If we underused last interval we can't use it this interval.
bytes_remaining_interval_ = pace_multiplier_ * bytes_per_interval;
}
if (padding_bytes_remaining_interval_ < 0) {
// We overused last interval, compensate this interval.
padding_bytes_remaining_interval_ += bytes_per_interval;
} else {
// If we underused last interval we can't use it this interval.
padding_bytes_remaining_interval_ = bytes_per_interval;
}
}
// MUST have critsect_ when calling.
bool PacedSender::GetNextPacket(uint32_t* ssrc, uint16_t* sequence_number,
int64_t* capture_time_ms, Priority* priority,
bool* last_packet) {
if (bytes_remaining_interval_ <= 0) {
// All bytes consumed for this interval.
// Check if we have not sent in a too long time.
if ((TickTime::Now() - time_last_send_).Milliseconds() >
kMaxQueueTimeWithoutSendingMs) {
if (!high_priority_packets_.empty()) {
*priority = kHighPriority;
GetNextPacketFromList(&high_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!normal_priority_packets_.empty()) {
*priority = kNormalPriority;
GetNextPacketFromList(&normal_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
}
return false;
}
if (!high_priority_packets_.empty()) {
*priority = kHighPriority;
GetNextPacketFromList(&high_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!normal_priority_packets_.empty()) {
*priority = kNormalPriority;
GetNextPacketFromList(&normal_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
if (!low_priority_packets_.empty()) {
*priority = kLowPriority;
GetNextPacketFromList(&low_priority_packets_, ssrc, sequence_number,
capture_time_ms, last_packet);
return true;
}
return false;
}
void PacedSender::GetNextPacketFromList(PacketList* list,
uint32_t* ssrc, uint16_t* sequence_number, int64_t* capture_time_ms,
bool* last_packet) {
Packet packet = list->front();
UpdateState(packet.bytes_);
*sequence_number = packet.sequence_number_;
*ssrc = packet.ssrc_;
*capture_time_ms = packet.capture_time_ms_;
list->pop_front();
*last_packet = list->empty() ||
list->front().capture_time_ms_ > *capture_time_ms;
}
// MUST have critsect_ when calling.
void PacedSender::UpdateState(int num_bytes) {
time_last_send_ = TickTime::Now();
bytes_remaining_interval_ -= num_bytes;
padding_bytes_remaining_interval_ -= num_bytes;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: metaOutput.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_WIN32) || defined(__CYGWIN__)
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "metaOutput.h"
#include <itksys/SystemTools.hxx>
#include "zlib/zlib.h"
#include <typeinfo>
#if (METAIO_USE_NAMESPACE)
namespace METAIO_NAMESPACE {
#endif
/** Constructor */
MetaOutput::MetaOutput()
{
m_MetaCommand = 0;
m_CurrentVersion = "0.1";
}
/** Destructor */
MetaOutput::~MetaOutput()
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
itStream = m_StreamVector.erase(itStream);
}
}
/** Add a field */
bool MetaOutput::AddField(METAIO_STL::string name,
METAIO_STL::string description,
TypeEnumType type,
METAIO_STL::string value,
METAIO_STL::string rangeMin,
METAIO_STL::string rangeMax
)
{
Field field;
field.name = name;
field.description = description;
field.value = value;
field.type = type;
field.rangeMin = rangeMin;
field.rangeMax = rangeMax;
m_FieldVector.push_back(field);
return true;
}
/** Add a float field */
bool MetaOutput::AddFloatField(METAIO_STL::string name,
METAIO_STL::string description,
float value,
METAIO_STL::string rangeMin,
METAIO_STL::string rangeMax
)
{
char* val = new char[10];
sprintf(val,"%f",value);
this->AddField(name,description,FLOAT,val,rangeMin,rangeMax);
delete [] val;
return true;
}
/** Add meta command */
void MetaOutput::SetMetaCommand(MetaCommand* metaCommand)
{
m_MetaCommand = metaCommand;
m_MetaCommand->SetOption("GenerateMetaOutput","generateMetaOutput",
false,"Generate MetaOutput");
m_MetaCommand->SetOption("GenerateXMLMetaOutput","oxml",
false,"Generate XML MetaOutput to the console");
}
/** Get the username */
METAIO_STL::string MetaOutput::GetUsername()
{
#if defined (_WIN32) || defined(__CYGWIN__)
static char buf[1024];
DWORD size = sizeof(buf);
buf[0] = '\0';
GetUserName( buf, &size);
return buf;
#else // not _WIN32
struct passwd *pw = getpwuid(getuid());
if ( pw == NULL )
{
METAIO_STL::cout << "getpwuid() failed " << METAIO_STL::endl;
}
return pw->pw_name;
#endif // not _WIN32
}
METAIO_STL::string MetaOutput::GetHostname()
{
#if defined (_WIN32) || defined(__CYGWIN__)
WSADATA WsaData;
int err = WSAStartup (0x0101, &WsaData); // Init Winsock
if(err!=0)
{
return "";
}
#endif
char nameBuffer[1024];
gethostname(nameBuffer, 1024);
METAIO_STL::string hostName(nameBuffer);
return hostName;
}
METAIO_STL::string MetaOutput::GetHostip()
{
#if defined (_WIN32) || defined(__CYGWIN__)
WSADATA WsaData;
int err = WSAStartup (0x0101, &WsaData); // Init Winsock
if(err!=0)
return "";
#endif
struct hostent *phe = gethostbyname(GetHostname().c_str());
if (phe == 0)
return "";
struct in_addr addr;
char** address = phe->h_addr_list;
int m_numaddrs = 0;
while (*address)
{
m_numaddrs++;
address++;
}
METAIO_STL::string m_ip = "";
if (m_numaddrs != 0)
{
memcpy(&addr, phe->h_addr_list[m_numaddrs-1], sizeof(struct in_addr));
m_ip = inet_ntoa(addr);
}
return m_ip;
}
/** Return the string representation of a type */
METAIO_STL::string MetaOutput::TypeToString(TypeEnumType type)
{
switch(type)
{
case INT:
return "int";
case FLOAT:
return "float";
case STRING:
return "string";
case LIST:
return "list";
case FLAG:
return "flag";
case BOOL:
return "boolean";
default:
return "not defined";
}
return "not defined";
}
/** Private function to fill in the buffer */
METAIO_STL::string MetaOutput::GenerateXML(const char* filename)
{
METAIO_STL::string buffer;
buffer = "<?xml version=\"1.0\"?>\n";
buffer += "<MetaOutputFile ";
if(filename)
{
METAIO_STL::string filenamestr = filename;
buffer += "name=\"" +filenamestr+"\"";
}
buffer += " version=\""+m_CurrentVersion+"\">\n";
buffer += "<Creation date=\"" + itksys::SystemTools::GetCurrentDateTime("%Y%m%d") + "\"";
buffer += " time=\"" + itksys::SystemTools::GetCurrentDateTime("%H%M%S") + "\"";
buffer += " hostname=\""+this->GetHostname() +"\"";
buffer += " hostIP=\""+this->GetHostip() +"\"";
buffer += " user=\"" + this->GetUsername() + "\"/>\n";
buffer += "<Executable name=\"" + m_MetaCommand->GetApplicationName() + "\"";
buffer += " version=\"" + m_MetaCommand->GetVersion() + "\"";
buffer += " author=\"" + m_MetaCommand->GetAuthor() + "\"";
buffer += " description=\"" + m_MetaCommand->GetDescription() + "\"/>\n";
buffer += "<Inputs>\n";
const MetaCommand::OptionVector options = m_MetaCommand->GetParsedOptions();
MetaCommand::OptionVector::const_iterator itInput = options.begin();
while(itInput != options.end())
{
if((*itInput).name == "GenerateMetaOutput")
{
itInput++;
continue;
}
typedef METAIO_STL::vector<MetaCommand::Field> FieldVector;
FieldVector::const_iterator itField = (*itInput).fields.begin();
while(itField != (*itInput).fields.end())
{
if((*itInput).fields.size() == 1)
{
buffer += " <Input name=\"" + (*itInput).name +"\"";;
}
else
{
buffer += " <Input name=\"" + (*itInput).name + "." + (*itField).name +"\"";
}
buffer += " description=\"" + (*itInput).description + "\"";
if((*itField).required)
{
buffer += " required=\"true\"";
}
buffer += " value=\"" + (*itField).value + "\"";
buffer += " type=\"" + m_MetaCommand->TypeToString((*itField).type) + "\"";
if((*itField).rangeMin != "")
{
buffer += " rangeMin=\"" + (*itField).rangeMin + "\"";
}
if((*itField).rangeMax != "")
{
buffer += " rangeMax=\"" + (*itField).rangeMax + "\"";
}
if((*itField).externaldata == MetaCommand::DATA_IN)
{
buffer += " externalData=\"in\"";
}
else if((*itField).externaldata == MetaCommand::DATA_OUT)
{
buffer += " externalData=\"out\"";
}
buffer += "/>\n";
itField++;
}
itInput++;
}
buffer += "</Inputs>\n";
// Output
buffer += "<Outputs>\n";
FieldVector::const_iterator itOutput = m_FieldVector.begin();
while(itOutput != m_FieldVector.end())
{
buffer += " <Output name=\""+ (*itOutput).name + "\"";
buffer += " description=\""+ (*itOutput).description + "\"";
buffer += " value=\""+ (*itOutput).value + "\"";
buffer += " type=\""+ this->TypeToString((*itOutput).type) + "\"";
itOutput++;
}
buffer += "/>\n";
buffer += "</Outputs>\n";
// CRC32
unsigned long crc = crc32(0L,(Bytef*)buffer.c_str(),buffer.size());
char * crcstring = new char[10];
sprintf(crcstring,"%ul",crc);
// Compute the crc
buffer += "<CRC32>";
buffer += crcstring;
buffer += "</CRC32>\n";
buffer += "</MetaOutputFile>\n";
delete [] crcstring;
return buffer;
}
/** Write the output to the connected streams */
void MetaOutput::Write()
{
if(m_MetaCommand && m_MetaCommand->GetOptionWasSet("GenerateXMLMetaOutput"))
{
METAIO_STL::cout << this->GenerateXML().c_str() << METAIO_STL::endl;
}
if(m_MetaCommand && !m_MetaCommand->GetOptionWasSet("GenerateMetaOutput"))
{
return;
}
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!(*itStream)->IsEnable())
{
itStream++;
continue;
}
(*itStream)->SetMetaOutput(this);
if(!(*itStream)->Open())
{
METAIO_STL::cout << "MetaOutput ERROR: cannot open stream" << METAIO_STL::endl;
return;
}
FieldVector::const_iterator it = m_FieldVector.begin();
while(it != m_FieldVector.end())
{
if(typeid(*(*itStream)) == typeid(MetaFileOutputStream))
{
METAIO_STL::string filename = dynamic_cast<MetaFileOutputStream*>(*itStream)->GetFileName().c_str();
(*itStream)->Write(this->GenerateXML(filename.c_str()).c_str());
}
else
{
(*itStream)->Write(this->GenerateXML().c_str());
}
it++;
}
if(!(*itStream)->Close())
{
METAIO_STL::cout << "MetaOutput ERROR: cannot close stream" << METAIO_STL::endl;
return;
}
itStream++;
}
}
/** Add a stream */
void MetaOutput::AddStream(const char* name,METAIO_STL::ostream & stdstream)
{
MetaOutputStream* stream = new MetaOutputStream;
stream->SetName(name);
stream->SetStdStream(&stdstream);
m_StreamVector.push_back(stream);
}
void MetaOutput::AddStream(const char* name,MetaOutputStream * stream)
{
stream->SetName(name);
m_StreamVector.push_back(stream);
}
/** Add a stream file. Helper function */
void MetaOutput::AddStreamFile(const char* name,const char* filename)
{
MetaFileOutputStream* stream = new MetaFileOutputStream(filename);
this->AddStream(name,stream);
}
/** Enable a stream */
void MetaOutput::EnableStream(const char* name)
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!strcmp((*itStream)->GetName().c_str(),name))
{
(*itStream)->Enable();
}
itStream++;
}
}
/** Disable a stream */
void MetaOutput::DisableStream(const char* name)
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!strcmp((*itStream)->GetName().c_str(),name))
{
(*itStream)->Disable();
}
itStream++;
}
}
#if (METAIO_USE_NAMESPACE)
};
#endif
<commit_msg>ENH: Added WriteXMLFile() function<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: metaOutput.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_WIN32) || defined(__CYGWIN__)
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "metaOutput.h"
#include <itksys/SystemTools.hxx>
#include "zlib/zlib.h"
#include <typeinfo>
#if (METAIO_USE_NAMESPACE)
namespace METAIO_NAMESPACE {
#endif
/** Constructor */
MetaOutput::MetaOutput()
{
m_MetaCommand = 0;
m_CurrentVersion = "0.1";
}
/** Destructor */
MetaOutput::~MetaOutput()
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
itStream = m_StreamVector.erase(itStream);
}
}
/** Add a field */
bool MetaOutput::AddField(METAIO_STL::string name,
METAIO_STL::string description,
TypeEnumType type,
METAIO_STL::string value,
METAIO_STL::string rangeMin,
METAIO_STL::string rangeMax
)
{
Field field;
field.name = name;
field.description = description;
field.value = value;
field.type = type;
field.rangeMin = rangeMin;
field.rangeMax = rangeMax;
m_FieldVector.push_back(field);
return true;
}
/** Add a float field */
bool MetaOutput::AddFloatField(METAIO_STL::string name,
METAIO_STL::string description,
float value,
METAIO_STL::string rangeMin,
METAIO_STL::string rangeMax
)
{
char* val = new char[10];
sprintf(val,"%f",value);
this->AddField(name,description,FLOAT,val,rangeMin,rangeMax);
delete [] val;
return true;
}
/** Add meta command */
void MetaOutput::SetMetaCommand(MetaCommand* metaCommand)
{
m_MetaCommand = metaCommand;
m_MetaCommand->SetOption("GenerateMetaOutput","generateMetaOutput",
false,"Generate MetaOutput");
m_MetaCommand->SetOption("GenerateXMLMetaOutput","oxml",
false,"Generate XML MetaOutput to the console");
m_MetaCommand->SetOption("GenerateXMLFile","ofxml",
false,"Generate XML MetaOutput to a file",MetaCommand::STRING,"",
MetaCommand::DATA_OUT);
}
/** Get the username */
METAIO_STL::string MetaOutput::GetUsername()
{
#if defined (_WIN32) || defined(__CYGWIN__)
static char buf[1024];
DWORD size = sizeof(buf);
buf[0] = '\0';
GetUserName( buf, &size);
return buf;
#else // not _WIN32
struct passwd *pw = getpwuid(getuid());
if ( pw == NULL )
{
METAIO_STL::cout << "getpwuid() failed " << METAIO_STL::endl;
}
return pw->pw_name;
#endif // not _WIN32
}
METAIO_STL::string MetaOutput::GetHostname()
{
#if defined (_WIN32) || defined(__CYGWIN__)
WSADATA WsaData;
int err = WSAStartup (0x0101, &WsaData); // Init Winsock
if(err!=0)
{
return "";
}
#endif
char nameBuffer[1024];
gethostname(nameBuffer, 1024);
METAIO_STL::string hostName(nameBuffer);
return hostName;
}
METAIO_STL::string MetaOutput::GetHostip()
{
#if defined (_WIN32) || defined(__CYGWIN__)
WSADATA WsaData;
int err = WSAStartup (0x0101, &WsaData); // Init Winsock
if(err!=0)
return "";
#endif
struct hostent *phe = gethostbyname(GetHostname().c_str());
if (phe == 0)
return "";
struct in_addr addr;
char** address = phe->h_addr_list;
int m_numaddrs = 0;
while (*address)
{
m_numaddrs++;
address++;
}
METAIO_STL::string m_ip = "";
if (m_numaddrs != 0)
{
memcpy(&addr, phe->h_addr_list[m_numaddrs-1], sizeof(struct in_addr));
m_ip = inet_ntoa(addr);
}
return m_ip;
}
/** Return the string representation of a type */
METAIO_STL::string MetaOutput::TypeToString(TypeEnumType type)
{
switch(type)
{
case INT:
return "int";
case FLOAT:
return "float";
case STRING:
return "string";
case LIST:
return "list";
case FLAG:
return "flag";
case BOOL:
return "boolean";
default:
return "not defined";
}
return "not defined";
}
/** Private function to fill in the buffer */
METAIO_STL::string MetaOutput::GenerateXML(const char* filename)
{
METAIO_STL::string buffer;
buffer = "<?xml version=\"1.0\"?>\n";
buffer += "<MetaOutputFile ";
if(filename)
{
METAIO_STL::string filenamestr = filename;
buffer += "name=\"" +filenamestr+"\"";
}
buffer += " version=\""+m_CurrentVersion+"\">\n";
buffer += "<Creation date=\"" + itksys::SystemTools::GetCurrentDateTime("%Y%m%d") + "\"";
buffer += " time=\"" + itksys::SystemTools::GetCurrentDateTime("%H%M%S") + "\"";
buffer += " hostname=\""+this->GetHostname() +"\"";
buffer += " hostIP=\""+this->GetHostip() +"\"";
buffer += " user=\"" + this->GetUsername() + "\"/>\n";
buffer += "<Executable name=\"" + m_MetaCommand->GetApplicationName() + "\"";
buffer += " version=\"" + m_MetaCommand->GetVersion() + "\"";
buffer += " author=\"" + m_MetaCommand->GetAuthor() + "\"";
buffer += " description=\"" + m_MetaCommand->GetDescription() + "\"/>\n";
buffer += "<Inputs>\n";
const MetaCommand::OptionVector options = m_MetaCommand->GetParsedOptions();
MetaCommand::OptionVector::const_iterator itInput = options.begin();
while(itInput != options.end())
{
if((*itInput).name == "GenerateMetaOutput")
{
itInput++;
continue;
}
typedef METAIO_STL::vector<MetaCommand::Field> FieldVector;
FieldVector::const_iterator itField = (*itInput).fields.begin();
while(itField != (*itInput).fields.end())
{
if((*itInput).fields.size() == 1)
{
buffer += " <Input name=\"" + (*itInput).name +"\"";;
}
else
{
buffer += " <Input name=\"" + (*itInput).name + "." + (*itField).name +"\"";
}
buffer += " description=\"" + (*itInput).description + "\"";
if((*itField).required)
{
buffer += " required=\"true\"";
}
buffer += " value=\"" + (*itField).value + "\"";
buffer += " type=\"" + m_MetaCommand->TypeToString((*itField).type) + "\"";
if((*itField).rangeMin != "")
{
buffer += " rangeMin=\"" + (*itField).rangeMin + "\"";
}
if((*itField).rangeMax != "")
{
buffer += " rangeMax=\"" + (*itField).rangeMax + "\"";
}
if((*itField).externaldata == MetaCommand::DATA_IN)
{
buffer += " externalData=\"in\"";
}
else if((*itField).externaldata == MetaCommand::DATA_OUT)
{
buffer += " externalData=\"out\"";
}
buffer += "/>\n";
itField++;
}
itInput++;
}
buffer += "</Inputs>\n";
// Output
buffer += "<Outputs>\n";
FieldVector::const_iterator itOutput = m_FieldVector.begin();
while(itOutput != m_FieldVector.end())
{
buffer += " <Output name=\""+ (*itOutput).name + "\"";
buffer += " description=\""+ (*itOutput).description + "\"";
buffer += " value=\""+ (*itOutput).value + "\"";
buffer += " type=\""+ this->TypeToString((*itOutput).type) + "\"";
itOutput++;
}
buffer += "/>\n";
buffer += "</Outputs>\n";
// CRC32
unsigned long crc = crc32(0L,(Bytef*)buffer.c_str(),buffer.size());
char * crcstring = new char[10];
sprintf(crcstring,"%ul",crc);
// Compute the crc
buffer += "<CRC32>";
buffer += crcstring;
buffer += "</CRC32>\n";
buffer += "</MetaOutputFile>\n";
delete [] crcstring;
return buffer;
}
/** Write the output to the connected streams */
void MetaOutput::Write()
{
if(m_MetaCommand && m_MetaCommand->GetOptionWasSet("GenerateXMLMetaOutput"))
{
METAIO_STL::cout << this->GenerateXML().c_str() << METAIO_STL::endl;
}
if(m_MetaCommand && m_MetaCommand->GetOptionWasSet("GenerateXMLFile"))
{
//this->GenerateXML();
METAIO_STL::string filename = m_MetaCommand->GetValueAsString("GenerateXMLFile");
METAIO_STL::ofstream fileStream;
fileStream.open(filename.c_str(), METAIO_STL::ios::binary | METAIO_STL::ios::out);
if(fileStream.is_open())
{
fileStream << this->GenerateXML(filename.c_str()).c_str();
fileStream.close();
}
}
if(m_MetaCommand && !m_MetaCommand->GetOptionWasSet("GenerateMetaOutput"))
{
return;
}
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!(*itStream)->IsEnable())
{
itStream++;
continue;
}
(*itStream)->SetMetaOutput(this);
if(!(*itStream)->Open())
{
METAIO_STL::cout << "MetaOutput ERROR: cannot open stream" << METAIO_STL::endl;
return;
}
FieldVector::const_iterator it = m_FieldVector.begin();
while(it != m_FieldVector.end())
{
if(typeid(*(*itStream)) == typeid(MetaFileOutputStream))
{
METAIO_STL::string filename = dynamic_cast<MetaFileOutputStream*>(*itStream)->GetFileName().c_str();
(*itStream)->Write(this->GenerateXML(filename.c_str()).c_str());
}
else
{
(*itStream)->Write(this->GenerateXML().c_str());
}
it++;
}
if(!(*itStream)->Close())
{
METAIO_STL::cout << "MetaOutput ERROR: cannot close stream" << METAIO_STL::endl;
return;
}
itStream++;
}
}
/** Add a stream */
void MetaOutput::AddStream(const char* name,METAIO_STL::ostream & stdstream)
{
MetaOutputStream* stream = new MetaOutputStream;
stream->SetName(name);
stream->SetStdStream(&stdstream);
m_StreamVector.push_back(stream);
}
void MetaOutput::AddStream(const char* name,MetaOutputStream * stream)
{
stream->SetName(name);
m_StreamVector.push_back(stream);
}
/** Add a stream file. Helper function */
void MetaOutput::AddStreamFile(const char* name,const char* filename)
{
MetaFileOutputStream* stream = new MetaFileOutputStream(filename);
this->AddStream(name,stream);
}
/** Enable a stream */
void MetaOutput::EnableStream(const char* name)
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!strcmp((*itStream)->GetName().c_str(),name))
{
(*itStream)->Enable();
}
itStream++;
}
}
/** Disable a stream */
void MetaOutput::DisableStream(const char* name)
{
StreamVector::iterator itStream = m_StreamVector.begin();
while(itStream != m_StreamVector.end())
{
if(!strcmp((*itStream)->GetName().c_str(),name))
{
(*itStream)->Disable();
}
itStream++;
}
}
#if (METAIO_USE_NAMESPACE)
};
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: gdcm
Module: gdcmDict.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
l'Image). All rights reserved. See Doc/License.txt or
http://www.creatis.insa-lyon.fr/Public/Gdcm/License.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 "gdcmDict.h"
#include "gdcmUtil.h"
#include "gdcmDebug.h"
#include <fstream>
#include <iostream>
#include <iomanip>
#include <itksys/ios/sstream>
namespace gdcm
{
void FillDefaultDataDict(Dict *d);
//-----------------------------------------------------------------------------
// Constructor / Destructor
/**
* \brief Construtor
* @param filename from which to build the dictionary.
*/
Dict::Dict(std::string const & filename)
{
uint16_t group;
uint16_t element;
TagName vr;
TagName fourth;
TagName name;
std::ifstream from( filename.c_str() );
if( !from )
{
dbg.Verbose(2,"Dict::Dict: can't open dictionary", filename.c_str());
// Using default embeded one:
FillDefaultDataDict( this );
}
else
{
while (!from.eof())
{
from >> std::hex;
from >> group;
from >> element;
from >> vr;
from >> fourth;
from >> std::ws; //remove white space
std::getline(from, name);
const DictEntry newEntry(group, element, vr, fourth, name);
AddNewEntry(newEntry);
}
from.close();
Filename = filename;
}
}
/**
* \brief Destructor
*/
Dict::~Dict()
{
// Since AddNewEntry adds symetrical in both KeyHt and NameHT we can
// assume all the pointed DictEntries are already cleaned-up when
// we cleaned KeyHt.
KeyHt.clear();
NameHt.clear();
}
//-----------------------------------------------------------------------------
// Print
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by tag i.e. the couple (group, element).
* @param os The output stream to be written to.
*/
void Dict::Print(std::ostream &os)
{
os << "Dict file name : " << Filename << std::endl;
PrintByKey(os);
}
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by tag i.e. the couple (group, element).
* @param os The output stream to be written to.
*/
void Dict::PrintByKey(std::ostream &os)
{
itksys_ios::ostringstream s;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
s << "Entry : ";
s << "(" << std::hex << std::setw(4) << tag->second.GetGroup() << ',';
s << std::hex << std::setw(4) << tag->second.GetElement() << ") = "
<< std::dec;
s << tag->second.GetVR() << ", ";
s << tag->second.GetFourth() << ", ";
s << tag->second.GetName() << "." << std::endl;
}
os << s.str();
}
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by the name of the dictionary entries.
* \warning AVOID USING IT : the name IS NOT an identifier;
* unpredictable result
* @param os The output stream to be written to.
*/
void Dict::PrintByName(std::ostream& os)
{
std::ostringstream s;
for (TagNameHT::iterator tag = NameHt.begin(); tag != NameHt.end(); ++tag)
{
s << "Entry : ";
s << tag->second.GetName() << ",";
s << tag->second.GetVR() << ", ";
s << tag->second.GetFourth() << ", ";
s << "(" << std::hex << std::setw(4) << tag->second.GetGroup() << ',';
s << std::hex << std::setw(4) << tag->second.GetElement() << ") = ";
s << std::dec << std::endl;
}
os << s.str();
}
//-----------------------------------------------------------------------------
// Public
/**
* \ingroup Dict
* \brief adds a new Dicom Dictionary Entry
* @param newEntry entry to add
* @return false if Dicom Element already exists
*/
bool Dict::AddNewEntry(DictEntry const & newEntry)
{
const TagKey & key = newEntry.GetKey();
if(KeyHt.count(key) == 1)
{
dbg.Verbose(1, "Dict::AddNewEntry already present", key.c_str());
return false;
}
else
{
KeyHt.insert(
std::map<TagKey, DictEntry>::value_type
(newEntry.GetKey(), newEntry));
NameHt.insert(
std::map<TagName, DictEntry>::value_type
(newEntry.GetName(), newEntry ));
return true;
}
}
/**
* \ingroup Dict
* \brief replaces an already existing Dicom Element by a new one
* @param newEntry new entry (overwrites any previous one with same tag)
* @return false if Dicom Element doesn't exist
*/
bool Dict::ReplaceEntry(DictEntry const & newEntry)
{
if ( RemoveEntry(newEntry.GetKey()) )
{
KeyHt.insert(
std::map<TagKey, DictEntry>::value_type
(newEntry.GetKey(), newEntry));
NameHt.insert(
std::map<TagName, DictEntry>::value_type
(newEntry.GetName(), newEntry ));
return true;
}
return false;
}
/**
* \ingroup Dict
* \brief removes an already existing Dicom Dictionary Entry,
* identified by its Tag
* @param key (group|element)
* @return false if Dicom Dictionary Entry doesn't exist
*/
bool Dict::RemoveEntry (TagKey const & key)
{
TagKeyHT::const_iterator it = KeyHt.find(key);
if(it != KeyHt.end())
{
const DictEntry & entryToDelete = it->second;
NameHt.erase(entryToDelete.GetName());
KeyHt.erase(key);
return true;
}
else
{
dbg.Verbose(1, "Dict::RemoveEntry unfound entry", key.c_str());
return false;
}
}
/**
* \brief removes an already existing Dicom Dictionary Entry,
* identified by its group,element number
* @param group Dicom group number of the Dicom Element
* @param element Dicom element number of the Dicom Element
* @return false if Dicom Dictionary Entry doesn't exist
*/
bool Dict::RemoveEntry (uint16_t group, uint16_t element)
{
return RemoveEntry(DictEntry::TranslateToKey(group, element));
}
/**
* \brief Get the dictionnary entry identified by it's name.
* @param name element of the ElVal to modify
* \warning : NEVER use it !
* the 'name' IS NOT an identifier within the Dicom Dictionary
* the name MAY CHANGE between two versions !
* @return the corresponding dictionnary entry when existing, NULL otherwise
*/
DictEntry* Dict::GetDictEntryByName(TagName const & name)
{
TagNameHT::iterator it = NameHt.find(name);
if ( it == NameHt.end() )
{
return 0;
}
return &(it->second);
}
/**
* \brief Get the dictionnary entry identified by a given tag (group,element)
* @param group group of the entry to be found
* @param element element of the entry to be found
* @return the corresponding dictionnary entry when existing, NULL otherwise
*/
DictEntry* Dict::GetDictEntryByNumber(uint16_t group, uint16_t element)
{
TagKey key = DictEntry::TranslateToKey(group, element);
TagKeyHT::iterator it = KeyHt.find(key);
if ( it == KeyHt.end() )
{
return 0;
}
return &(it->second);
}
/**
* \brief Consider all the entries of the public dicom dictionnary.
* Build all list of all the tag names of all those entries.
* \sa DictSet::GetPubDictTagNamesByCategory
* @return A list of all entries of the public dicom dictionnary.
*/
EntryNamesList* Dict::GetDictEntryNames()
{
EntryNamesList *result = new EntryNamesList;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
result->push_back( tag->second.GetName() );
}
return result;
}
/**
* \ingroup Dict
* \brief Consider all the entries of the public dicom dictionnary.
* Build an hashtable whose keys are the names of the groups
* (fourth field in each line of dictionary) and whose corresponding
* values are lists of all the dictionnary entries among that
* group. Note that apparently the Dicom standard doesn't explicitely
* define a name (as a string) for each group.
* A typical usage of this method would be to enable a dynamic
* configuration of a Dicom file browser: the admin/user can
* select in the interface which Dicom tags should be displayed.
* \warning Dicom *doesn't* define any name for any 'categorie'
* (the dictionnary fourth field was formerly NIH defined
* - and no longer he is-
* and will be removed when Dicom provides us a text file
* with the 'official' Dictionnary, that would be more friendly
* than asking us to perform a line by line check of the dictionnary
* at the beginning of each year to -try to- guess the changes)
* Therefore : please NEVER use that fourth field :-(
*
* @return An hashtable: whose keys are the names of the groups and whose
* corresponding values are lists of all the dictionnary entries
* among that group.
*/
EntryNamesByCatMap *Dict::GetDictEntryNamesByCategory()
{
EntryNamesByCatMap *result = new EntryNamesByCatMap;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
(*result)[tag->second.GetFourth()].push_back(tag->second.GetName());
}
return result;
}
//-----------------------------------------------------------------------------
// Protected
//-----------------------------------------------------------------------------
// Private
//-----------------------------------------------------------------------------
} // end namespace gdcm
<commit_msg>COMP: Fix remaining ref to std::ostringstream, should use itksys_ios::ostringstream instead<commit_after>/*=========================================================================
Program: gdcm
Module: gdcmDict.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
l'Image). All rights reserved. See Doc/License.txt or
http://www.creatis.insa-lyon.fr/Public/Gdcm/License.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 "gdcmDict.h"
#include "gdcmUtil.h"
#include "gdcmDebug.h"
#include <fstream>
#include <iostream>
#include <iomanip>
#include <itksys/ios/sstream>
namespace gdcm
{
void FillDefaultDataDict(Dict *d);
//-----------------------------------------------------------------------------
// Constructor / Destructor
/**
* \brief Construtor
* @param filename from which to build the dictionary.
*/
Dict::Dict(std::string const & filename)
{
uint16_t group;
uint16_t element;
TagName vr;
TagName fourth;
TagName name;
std::ifstream from( filename.c_str() );
if( !from )
{
dbg.Verbose(2,"Dict::Dict: can't open dictionary", filename.c_str());
// Using default embeded one:
FillDefaultDataDict( this );
}
else
{
while (!from.eof())
{
from >> std::hex;
from >> group;
from >> element;
from >> vr;
from >> fourth;
from >> std::ws; //remove white space
std::getline(from, name);
const DictEntry newEntry(group, element, vr, fourth, name);
AddNewEntry(newEntry);
}
from.close();
Filename = filename;
}
}
/**
* \brief Destructor
*/
Dict::~Dict()
{
// Since AddNewEntry adds symetrical in both KeyHt and NameHT we can
// assume all the pointed DictEntries are already cleaned-up when
// we cleaned KeyHt.
KeyHt.clear();
NameHt.clear();
}
//-----------------------------------------------------------------------------
// Print
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by tag i.e. the couple (group, element).
* @param os The output stream to be written to.
*/
void Dict::Print(std::ostream &os)
{
os << "Dict file name : " << Filename << std::endl;
PrintByKey(os);
}
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by tag i.e. the couple (group, element).
* @param os The output stream to be written to.
*/
void Dict::PrintByKey(std::ostream &os)
{
itksys_ios::ostringstream s;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
s << "Entry : ";
s << "(" << std::hex << std::setw(4) << tag->second.GetGroup() << ',';
s << std::hex << std::setw(4) << tag->second.GetElement() << ") = "
<< std::dec;
s << tag->second.GetVR() << ", ";
s << tag->second.GetFourth() << ", ";
s << tag->second.GetName() << "." << std::endl;
}
os << s.str();
}
/**
* \brief Print all the dictionary entries contained in this dictionary.
* Entries will be sorted by the name of the dictionary entries.
* \warning AVOID USING IT : the name IS NOT an identifier;
* unpredictable result
* @param os The output stream to be written to.
*/
void Dict::PrintByName(std::ostream& os)
{
itksys_ios::ostringstream s;
for (TagNameHT::iterator tag = NameHt.begin(); tag != NameHt.end(); ++tag)
{
s << "Entry : ";
s << tag->second.GetName() << ",";
s << tag->second.GetVR() << ", ";
s << tag->second.GetFourth() << ", ";
s << "(" << std::hex << std::setw(4) << tag->second.GetGroup() << ',';
s << std::hex << std::setw(4) << tag->second.GetElement() << ") = ";
s << std::dec << std::endl;
}
os << s.str();
}
//-----------------------------------------------------------------------------
// Public
/**
* \ingroup Dict
* \brief adds a new Dicom Dictionary Entry
* @param newEntry entry to add
* @return false if Dicom Element already exists
*/
bool Dict::AddNewEntry(DictEntry const & newEntry)
{
const TagKey & key = newEntry.GetKey();
if(KeyHt.count(key) == 1)
{
dbg.Verbose(1, "Dict::AddNewEntry already present", key.c_str());
return false;
}
else
{
KeyHt.insert(
std::map<TagKey, DictEntry>::value_type
(newEntry.GetKey(), newEntry));
NameHt.insert(
std::map<TagName, DictEntry>::value_type
(newEntry.GetName(), newEntry ));
return true;
}
}
/**
* \ingroup Dict
* \brief replaces an already existing Dicom Element by a new one
* @param newEntry new entry (overwrites any previous one with same tag)
* @return false if Dicom Element doesn't exist
*/
bool Dict::ReplaceEntry(DictEntry const & newEntry)
{
if ( RemoveEntry(newEntry.GetKey()) )
{
KeyHt.insert(
std::map<TagKey, DictEntry>::value_type
(newEntry.GetKey(), newEntry));
NameHt.insert(
std::map<TagName, DictEntry>::value_type
(newEntry.GetName(), newEntry ));
return true;
}
return false;
}
/**
* \ingroup Dict
* \brief removes an already existing Dicom Dictionary Entry,
* identified by its Tag
* @param key (group|element)
* @return false if Dicom Dictionary Entry doesn't exist
*/
bool Dict::RemoveEntry (TagKey const & key)
{
TagKeyHT::const_iterator it = KeyHt.find(key);
if(it != KeyHt.end())
{
const DictEntry & entryToDelete = it->second;
NameHt.erase(entryToDelete.GetName());
KeyHt.erase(key);
return true;
}
else
{
dbg.Verbose(1, "Dict::RemoveEntry unfound entry", key.c_str());
return false;
}
}
/**
* \brief removes an already existing Dicom Dictionary Entry,
* identified by its group,element number
* @param group Dicom group number of the Dicom Element
* @param element Dicom element number of the Dicom Element
* @return false if Dicom Dictionary Entry doesn't exist
*/
bool Dict::RemoveEntry (uint16_t group, uint16_t element)
{
return RemoveEntry(DictEntry::TranslateToKey(group, element));
}
/**
* \brief Get the dictionnary entry identified by it's name.
* @param name element of the ElVal to modify
* \warning : NEVER use it !
* the 'name' IS NOT an identifier within the Dicom Dictionary
* the name MAY CHANGE between two versions !
* @return the corresponding dictionnary entry when existing, NULL otherwise
*/
DictEntry* Dict::GetDictEntryByName(TagName const & name)
{
TagNameHT::iterator it = NameHt.find(name);
if ( it == NameHt.end() )
{
return 0;
}
return &(it->second);
}
/**
* \brief Get the dictionnary entry identified by a given tag (group,element)
* @param group group of the entry to be found
* @param element element of the entry to be found
* @return the corresponding dictionnary entry when existing, NULL otherwise
*/
DictEntry* Dict::GetDictEntryByNumber(uint16_t group, uint16_t element)
{
TagKey key = DictEntry::TranslateToKey(group, element);
TagKeyHT::iterator it = KeyHt.find(key);
if ( it == KeyHt.end() )
{
return 0;
}
return &(it->second);
}
/**
* \brief Consider all the entries of the public dicom dictionnary.
* Build all list of all the tag names of all those entries.
* \sa DictSet::GetPubDictTagNamesByCategory
* @return A list of all entries of the public dicom dictionnary.
*/
EntryNamesList* Dict::GetDictEntryNames()
{
EntryNamesList *result = new EntryNamesList;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
result->push_back( tag->second.GetName() );
}
return result;
}
/**
* \ingroup Dict
* \brief Consider all the entries of the public dicom dictionnary.
* Build an hashtable whose keys are the names of the groups
* (fourth field in each line of dictionary) and whose corresponding
* values are lists of all the dictionnary entries among that
* group. Note that apparently the Dicom standard doesn't explicitely
* define a name (as a string) for each group.
* A typical usage of this method would be to enable a dynamic
* configuration of a Dicom file browser: the admin/user can
* select in the interface which Dicom tags should be displayed.
* \warning Dicom *doesn't* define any name for any 'categorie'
* (the dictionnary fourth field was formerly NIH defined
* - and no longer he is-
* and will be removed when Dicom provides us a text file
* with the 'official' Dictionnary, that would be more friendly
* than asking us to perform a line by line check of the dictionnary
* at the beginning of each year to -try to- guess the changes)
* Therefore : please NEVER use that fourth field :-(
*
* @return An hashtable: whose keys are the names of the groups and whose
* corresponding values are lists of all the dictionnary entries
* among that group.
*/
EntryNamesByCatMap *Dict::GetDictEntryNamesByCategory()
{
EntryNamesByCatMap *result = new EntryNamesByCatMap;
for (TagKeyHT::iterator tag = KeyHt.begin(); tag != KeyHt.end(); ++tag)
{
(*result)[tag->second.GetFourth()].push_back(tag->second.GetName());
}
return result;
}
//-----------------------------------------------------------------------------
// Protected
//-----------------------------------------------------------------------------
// Private
//-----------------------------------------------------------------------------
} // end namespace gdcm
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DATE_HPP
#define DATE_HPP
#include <ctime>
#include "utils.hpp"
namespace budget {
using date_type = unsigned short;
class date_exception: public std::exception {
protected:
std::string _message;
public:
date_exception(std::string message) : _message(message){}
/*!
* Return the error message.
* \return The error message.
*/
const std::string& message() const {
return _message;
}
virtual const char* what() const throw() {
return _message.c_str();
}
};
struct day {
date_type value;
day(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct month {
date_type value;
month(date_type value) : value(value) {}
operator date_type() const { return value; }
std::string as_short_string() const {
static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
return months[value-1];
}
std::string as_long_string() const {
static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return months[value-1];
}
};
struct year {
date_type value;
year(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct days {
date_type value;
explicit days(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct months {
date_type value;
explicit months(date_type value) : value(value) {}
operator date_type() const { return value; }
months& operator=(date_type value){
this->value = value;
return *this;
}
};
struct years {
date_type value;
explicit years(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct date;
std::ostream& operator<<(std::ostream& stream, const month& month);
std::ostream& operator<<(std::ostream& stream, const date& date);
struct date {
date_type _year;
date_type _month;
date_type _day;
explicit date(){}
date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){
if(year < 1400){
throw date_exception("Year not in the valid range");
}
if(month == 0 || month > 12){
throw date_exception("Invalid month");
}
if(day == 0 || day > days_month(year, month)){
throw date_exception("Invalid day");
}
}
date(const date& d) : _year(d._year), _month(d._month), _day(d._day) {
//Nothing else
}
budget::year year() const {
return _year;
}
budget::month month() const {
return _month;
}
budget::day day() const {
return _day;
}
static date_type days_month(date_type year, date_type month){
static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
if(month == 2){
return is_leap(year) ? 29 : 28;
} else {
return month_days[month - 1];
}
}
static bool is_leap(date_type year){
return
((year % 4 == 0) && year % 100 != 0)
|| year % 400 == 0;
}
bool is_leap() const {
return is_leap(_year);
}
date end_of_month(){
return {_year, _month, days_month(_year, _month)};
}
date& operator+=(years years){
if(years >= std::numeric_limits<date_type>::max() - _year){
throw date_exception("Year too high (will overflow)");
}
_year += years;
return *this;
}
date& operator+=(months months){
// Handle the NOP addition
if(months == 0){
return *this;
}
// First add several years if necessary
if (months >= 12) {
*this += years(months.value / 12);
months = months.value % 12;
}
// Add the remaining months
_month += months;
// Update the year if necessary
if(_month > 12){
*this += years((_month - 1) / 12);
_month = (_month) % 12;
}
// Update the day of month, if necessary
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator+=(days d){
while(d > 0){
++_day;
if(_day > days_month(_year, _month)){
_day = 1;
++_month;
if(_month > 12){
_month = 1;
++_year;
}
}
d = days(d - 1);
}
return *this;
}
date& operator-=(years years){
if(_year < years){
throw date_exception("Year too low");
}
_year -= years;
return *this;
}
date& operator-=(months months){
if(_month == months){
*this -= years(1);
_month = 12;
} else if(_month < months){
*this -= years(months / 12);
_month -= months % 12;
} else {
_month -= months;
}
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator-=(days d){
while(d > 0){
--_day;
if(_day == 0){
--_month;
if(_month == 0){
--_year;
_month = 12;
}
_day = days_month(_year, _month);
}
d = days(d - 1);
}
return *this;
}
date operator+(years years) const {
date d(*this);
d += years;
return d;
}
date operator+(months months) const {
date d(*this);
d += months;
return d;
}
date operator+(days days) const {
date d(*this);
d += days;
return d;
}
date operator-(years years) const {
date d(*this);
d -= years;
return d;
}
date operator-(months months) const {
date d(*this);
d -= months;
return d;
}
date operator-(days days) const {
date d(*this);
d -= days;
return d;
}
bool operator==(const date& rhs) const {
return _year == rhs._year && _month == rhs._month && _day == rhs._day;
}
bool operator!=(const date& rhs) const {
return !(*this == rhs);
}
bool operator<(const date& rhs) const {
if(_year < rhs._year){
return true;
} else if(_year == rhs._year){
if(_month < rhs._month){
return true;
} else if(_month == rhs._month){
return _day < rhs._day;
}
}
return false;
}
bool operator<=(const date& rhs) const {
return (*this == rhs) || (*this < rhs);
}
bool operator>(const date& rhs) const {
if(_year > rhs._year){
return true;
} else if(_year == rhs._year){
if(_month > rhs._month){
return true;
} else if(_month == rhs._month){
return _day > rhs._day;
}
}
return false;
}
bool operator>=(const date& rhs) const {
return (*this == rhs) || (*this > rhs);
}
date_type operator-(const date& rhs) const {
if(*this == rhs){
return 0;
}
if(rhs > *this){
return -(rhs - *this);
}
auto x = *this;
size_t d = 0;
while(x != rhs){
x -= days(1);
++d;
}
return d;
}
};
date local_day();
date from_string(const std::string& str);
date from_iso_string(const std::string& str);
std::string date_to_string(date date);
template<>
inline std::string to_string(budget::date date){
return date_to_string(date);
}
unsigned short start_year();
unsigned short start_month(budget::year year);
} //end of namespace budget
#endif
<commit_msg>New operators for month and year<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef DATE_HPP
#define DATE_HPP
#include <ctime>
#include "utils.hpp"
namespace budget {
using date_type = unsigned short;
class date_exception: public std::exception {
protected:
std::string _message;
public:
date_exception(std::string message) : _message(message){}
/*!
* Return the error message.
* \return The error message.
*/
const std::string& message() const {
return _message;
}
virtual const char* what() const throw() {
return _message.c_str();
}
};
struct day {
date_type value;
day(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct month {
date_type value;
month(date_type value) : value(value) {}
operator date_type() const { return value; }
month& operator=(date_type value){
this->value = value;
return *this;
}
std::string as_short_string() const {
static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
return months[value-1];
}
std::string as_long_string() const {
static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return months[value-1];
}
};
struct year {
date_type value;
year(date_type value) : value(value) {}
operator date_type() const { return value; }
year& operator=(date_type value){
this->value = value;
return *this;
}
};
struct days {
date_type value;
explicit days(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct months {
date_type value;
explicit months(date_type value) : value(value) {}
operator date_type() const { return value; }
months& operator=(date_type value){
this->value = value;
return *this;
}
};
struct years {
date_type value;
explicit years(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct date;
std::ostream& operator<<(std::ostream& stream, const month& month);
std::ostream& operator<<(std::ostream& stream, const date& date);
struct date {
date_type _year;
date_type _month;
date_type _day;
explicit date(){}
date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){
if(year < 1400){
throw date_exception("Year not in the valid range");
}
if(month == 0 || month > 12){
throw date_exception("Invalid month");
}
if(day == 0 || day > days_month(year, month)){
throw date_exception("Invalid day");
}
}
date(const date& d) : _year(d._year), _month(d._month), _day(d._day) {
//Nothing else
}
budget::year year() const {
return _year;
}
budget::month month() const {
return _month;
}
budget::day day() const {
return _day;
}
static date_type days_month(date_type year, date_type month){
static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
if(month == 2){
return is_leap(year) ? 29 : 28;
} else {
return month_days[month - 1];
}
}
static bool is_leap(date_type year){
return
((year % 4 == 0) && year % 100 != 0)
|| year % 400 == 0;
}
bool is_leap() const {
return is_leap(_year);
}
date end_of_month(){
return {_year, _month, days_month(_year, _month)};
}
date& operator+=(years years){
if(years >= std::numeric_limits<date_type>::max() - _year){
throw date_exception("Year too high (will overflow)");
}
_year += years;
return *this;
}
date& operator+=(months months){
// Handle the NOP addition
if(months == 0){
return *this;
}
// First add several years if necessary
if (months >= 12) {
*this += years(months.value / 12);
months = months.value % 12;
}
// Add the remaining months
_month += months;
// Update the year if necessary
if(_month > 12){
*this += years((_month - 1) / 12);
_month = (_month) % 12;
}
// Update the day of month, if necessary
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator+=(days d){
while(d > 0){
++_day;
if(_day > days_month(_year, _month)){
_day = 1;
++_month;
if(_month > 12){
_month = 1;
++_year;
}
}
d = days(d - 1);
}
return *this;
}
date& operator-=(years years){
if(_year < years){
throw date_exception("Year too low");
}
_year -= years;
return *this;
}
date& operator-=(months months){
if(_month == months){
*this -= years(1);
_month = 12;
} else if(_month < months){
*this -= years(months / 12);
_month -= months % 12;
} else {
_month -= months;
}
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator-=(days d){
while(d > 0){
--_day;
if(_day == 0){
--_month;
if(_month == 0){
--_year;
_month = 12;
}
_day = days_month(_year, _month);
}
d = days(d - 1);
}
return *this;
}
date operator+(years years) const {
date d(*this);
d += years;
return d;
}
date operator+(months months) const {
date d(*this);
d += months;
return d;
}
date operator+(days days) const {
date d(*this);
d += days;
return d;
}
date operator-(years years) const {
date d(*this);
d -= years;
return d;
}
date operator-(months months) const {
date d(*this);
d -= months;
return d;
}
date operator-(days days) const {
date d(*this);
d -= days;
return d;
}
bool operator==(const date& rhs) const {
return _year == rhs._year && _month == rhs._month && _day == rhs._day;
}
bool operator!=(const date& rhs) const {
return !(*this == rhs);
}
bool operator<(const date& rhs) const {
if(_year < rhs._year){
return true;
} else if(_year == rhs._year){
if(_month < rhs._month){
return true;
} else if(_month == rhs._month){
return _day < rhs._day;
}
}
return false;
}
bool operator<=(const date& rhs) const {
return (*this == rhs) || (*this < rhs);
}
bool operator>(const date& rhs) const {
if(_year > rhs._year){
return true;
} else if(_year == rhs._year){
if(_month > rhs._month){
return true;
} else if(_month == rhs._month){
return _day > rhs._day;
}
}
return false;
}
bool operator>=(const date& rhs) const {
return (*this == rhs) || (*this > rhs);
}
date_type operator-(const date& rhs) const {
if(*this == rhs){
return 0;
}
if(rhs > *this){
return -(rhs - *this);
}
auto x = *this;
size_t d = 0;
while(x != rhs){
x -= days(1);
++d;
}
return d;
}
};
date local_day();
date from_string(const std::string& str);
date from_iso_string(const std::string& str);
std::string date_to_string(date date);
template<>
inline std::string to_string(budget::date date){
return date_to_string(date);
}
unsigned short start_year();
unsigned short start_month(budget::year year);
} //end of namespace budget
#endif
<|endoftext|>
|
<commit_before>#ifndef hSDK_HeaderPlusPlus
#define hSDK_HeaderPlusPlus
#include <string>
#include <tuple>
class mv;
namespace hSDK
{
static_assert(sizeof(void *) == 4 && sizeof(std::size_t) == 4, "MMF2 only supports 32-bit extensions");
#ifdef UNICODE
using char_t = wchar_t;
#define T_ L
#else
using char_t = char;
#define T_
#endif
using string = std::basic_string<char_t>;
struct ED;
struct RD;
struct tuple_unpack final
{
template<int...> struct seq {};
template<int N, int... S> struct gens : gens<N-1, N-1, S...> {};
template<int... S> struct gens<0, S...>
{
using type = seq<S...>;
};
};
template<typename T>
struct identity final
{
using type = T;
};
template<typename T, typename... V>
struct RAII_Set_impl final
{
T &t;
std::tuple<typename identity<V T::*>::type...> mop;
std::tuple<V...> ds;
RAII_Set_impl(T &t_, std::tuple<V T::*, V, V>... sets)
: t(t_)
, mop(std::get<0>(sets)...)
, ds(std::get<2>(sets)...)
{
set(std::get<1>(sets)...);
}
~RAII_Set_impl()
{
unset(typename tuple_unpack::gens<sizeof...(V)>::type());
}
template<typename... U>
void set(U... u)
{
do_set<0, U...>(u...);
}
template<std::size_t i, typename First, typename... Rest>
void do_set(First first, Rest... rest)
{
t.*std::get<i>(mop) = first;
do_set<i+1, Rest...>(rest...);
}
template<std::size_t i, typename Last>
void do_set(Last last)
{
t.*std::get<i>(mop) = last;
}
template<std::size_t i>
void do_set()
{
}
template<std::size_t... S>
void unset(tuple_unpack::seq<S...>)
{
set(std::get<S>(ds)...);
}
};
template<typename T, typename... V>
auto RAII_Set(T &t, std::tuple<V T::*, V, V>... sets)
-> RAII_Set_impl<T, V...>
{
return RAII_Set_impl<T, V...>(t, sets...);
}
}
#endif
<commit_msg>Fix over-indentation in hSDK.hpp<commit_after>#ifndef hSDK_HeaderPlusPlus
#define hSDK_HeaderPlusPlus
#include <string>
#include <tuple>
class mv;
namespace hSDK
{
static_assert(sizeof(void *) == 4 && sizeof(std::size_t) == 4, "MMF2 only supports 32-bit extensions");
#ifdef UNICODE
using char_t = wchar_t;
#define T_ L
#else
using char_t = char;
#define T_
#endif
using string = std::basic_string<char_t>;
struct ED;
struct RD;
struct tuple_unpack final
{
template<int...> struct seq {};
template<int N, int... S> struct gens : gens<N-1, N-1, S...> {};
template<int... S> struct gens<0, S...>
{
using type = seq<S...>;
};
};
template<typename T>
struct identity final
{
using type = T;
};
template<typename T, typename... V>
struct RAII_Set_impl final
{
T &t;
std::tuple<typename identity<V T::*>::type...> mop;
std::tuple<V...> ds;
RAII_Set_impl(T &t_, std::tuple<V T::*, V, V>... sets)
: t(t_)
, mop(std::get<0>(sets)...)
, ds(std::get<2>(sets)...)
{
set(std::get<1>(sets)...);
}
~RAII_Set_impl()
{
unset(typename tuple_unpack::gens<sizeof...(V)>::type());
}
template<typename... U>
void set(U... u)
{
do_set<0, U...>(u...);
}
template<std::size_t i, typename First, typename... Rest>
void do_set(First first, Rest... rest)
{
t.*std::get<i>(mop) = first;
do_set<i+1, Rest...>(rest...);
}
template<std::size_t i, typename Last>
void do_set(Last last)
{
t.*std::get<i>(mop) = last;
}
template<std::size_t i>
void do_set()
{
}
template<std::size_t... S>
void unset(tuple_unpack::seq<S...>)
{
set(std::get<S>(ds)...);
}
};
template<typename T, typename... V>
auto RAII_Set(T &t, std::tuple<V T::*, V, V>... sets)
-> RAII_Set_impl<T, V...>
{
return RAII_Set_impl<T, V...>(t, sets...);
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <array>
#include <tuple>
#include "common.hpp"
#include "components/command_line.hpp"
namespace bookwyrm {
/* Default value: "this value is empty". */
enum { empty = -1 };
/*
* For --year:
* -y 2157 : list items from 2157 (equal)
* -y =>2157 : list items from 2157 and later (eq_gt)
* -y =<2157 : list items from 2157 and earlier (eq_lt)
* -y >2157 : list items from later than 2157 (gt)
* -y <2157 : list items from earlier than 2157 (lt)
*/
enum class year_mod { equal, eq_gt, eq_lt, lt, gt };
struct exacts_t {
/*
* A POD with added index operator.
* Useful in item::matches() where we want to
* iterate over these values and check if they match.
*
* We can then get a field value by name, which we'll
* want when printing the stuff out.
*
* Fields are set to "empty" (-1) during construction.
* This makes us able to bool-check (since -1 is false)
* whether or not a field is empty or not.
*/
explicit exacts_t(const std::unique_ptr<cliparser> &cli);
explicit exacts_t(const std::map<string, int> &dict);
year_mod ymod;
int year,
edition,
format, // unused for now
volume,
number,
pages, // missing flag
lang; // unused for now
constexpr static int size = 7;
std::array<int, size> store = {
year, edition, format,
volume, number, pages
};
int operator[](int i) const
{
return store[i];
}
};
struct nonexacts_t {
/*
* As the typename suggests, this POD contains
* data that we're not going to match exacly match
* exactly with the wanted field. Instead, we use
* fuzzy-matching.
*/
explicit nonexacts_t(const std::unique_ptr<cliparser> &cli);
explicit nonexacts_t(const std::map<string, string> &dict, const vector<string> &authors);
vector<string> authors;
string title;
string serie;
string publisher;
string journal;
};
struct misc_t {
/*
* The POD for everything else and undecided
* fields.
*/
vector<string> isbns;
vector<string> mirrors;
};
class item {
public:
explicit item(const std::unique_ptr<cliparser> &cli)
: nonexacts(cli), exacts(cli) {};
/* Construct an item from a pybind11::tuple. */
explicit item(const std::tuple<nonexacts_t, exacts_t> &tuple)
: nonexacts(std::get<0>(tuple)), exacts(std::get<1>(tuple)) {};
bool matches(const item &wanted);
friend std::ostream& operator<<(std::ostream &os, item const &i)
{
os << "test printout: " + i.nonexacts.serie;
return os;
}
const string& menu_order(int i) const
{
return menu_order_[i % menu_order_.size()]; // just in case
}
const nonexacts_t nonexacts;
const exacts_t exacts;
misc_t misc;
private:
// TODO: we're wasting space here, I think. Investigate.
const std::vector<string> menu_order_ = {
nonexacts.title,
std::to_string(exacts.year),
nonexacts.serie,
"authors",
nonexacts.publisher,
"format",
};
};
/* ns bookwyrm */
}
<commit_msg>item: stringify nonexacts.authors<commit_after>/*
* Copyright (C) 2017 Tmplt <tmplt@dragons.rocks>
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <array>
#include <tuple>
#include "common.hpp"
#include "utils.hpp"
#include "components/command_line.hpp"
namespace bookwyrm {
/* Default value: "this value is empty". */
enum { empty = -1 };
/*
* For --year:
* -y 2157 : list items from 2157 (equal)
* -y =>2157 : list items from 2157 and later (eq_gt)
* -y =<2157 : list items from 2157 and earlier (eq_lt)
* -y >2157 : list items from later than 2157 (gt)
* -y <2157 : list items from earlier than 2157 (lt)
*/
enum class year_mod { equal, eq_gt, eq_lt, lt, gt };
struct exacts_t {
/*
* A POD with added index operator.
* Useful in item::matches() where we want to
* iterate over these values and check if they match.
*
* We can then get a field value by name, which we'll
* want when printing the stuff out.
*
* Fields are set to "empty" (-1) during construction.
* This makes us able to bool-check (since -1 is false)
* whether or not a field is empty or not.
*/
explicit exacts_t(const std::unique_ptr<cliparser> &cli);
explicit exacts_t(const std::map<string, int> &dict);
year_mod ymod;
int year,
edition,
format, // unused for now
volume,
number,
pages, // missing flag
lang; // unused for now
constexpr static int size = 7;
std::array<int, size> store = {
year, edition, format,
volume, number, pages
};
int operator[](int i) const
{
return store[i];
}
};
struct nonexacts_t {
/*
* As the typename suggests, this POD contains
* data that we're not going to match exacly match
* exactly with the wanted field. Instead, we use
* fuzzy-matching.
*/
explicit nonexacts_t(const std::unique_ptr<cliparser> &cli);
explicit nonexacts_t(const std::map<string, string> &dict, const vector<string> &authors);
vector<string> authors;
string title;
string serie;
string publisher;
string journal;
};
struct misc_t {
/*
* The POD for everything else and undecided
* fields.
*/
vector<string> isbns;
vector<string> mirrors;
};
class item {
public:
explicit item(const std::unique_ptr<cliparser> &cli)
: nonexacts(cli), exacts(cli) {};
/* Construct an item from a pybind11::tuple. */
explicit item(const std::tuple<nonexacts_t, exacts_t> &tuple)
: nonexacts(std::get<0>(tuple)), exacts(std::get<1>(tuple)) {};
bool matches(const item &wanted);
friend std::ostream& operator<<(std::ostream &os, item const &i)
{
os << "test printout: " + i.nonexacts.serie;
return os;
}
const string& menu_order(int i) const
{
return menu_order_[i % menu_order_.size()]; // just in case
}
const nonexacts_t nonexacts;
const exacts_t exacts;
misc_t misc;
private:
// TODO: we're wasting space here, I think. Investigate.
const std::vector<string> menu_order_ = {
nonexacts.title,
std::to_string(exacts.year),
nonexacts.serie,
utils::vector_to_string(nonexacts.authors),
nonexacts.publisher,
"format (TODO)",
};
};
/* ns bookwyrm */
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <map>
#include "numpy_import.h"
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include "numpy/arrayobject.h"
#include "Python.h"
#include "datarobot2d.h"
#include "utils.h"
#define ARGS_NUM_CHECK(NUM) if (PyTuple_GET_SIZE(cpp_args) != NUM) { \
PyErr_SetString(kageext_error, "need NUM args"); \
return NULL; \
}
const std::string EXT_VERSION = "0.1";
static PyObject *kageext_error;
static std::map<std::string, std::shared_ptr<DataRobot2D> > datarobot2ds_map;
// get cpp extension's version
static PyObject *
show_ext_version(PyObject *self, PyObject *args)
{
return PyUnicode_FromString(EXT_VERSION.c_str());
}
static PyObject *s_parse_vector_to_pyobj(std::vector<std::string> v) {
PyObject *pyobj = PyTuple_New(v.size());
std::vector<std::string>::size_type index = 0;
for (auto s : v) {
PyObject *item = Py_BuildValue("s", s.c_str());
PyTuple_SetItem(pyobj, index, item);
index++;
}
return pyobj;
}
static std::vector<std::string> s_parse_tuple_to_vector(PyObject *tuple) {
std::vector<std::string> result;
if (!PyTuple_Check(tuple)) {
PyErr_SetString(kageext_error, "Need tuple");
return result;
}
auto tuple_size = PyTuple_GET_SIZE(tuple);
for(auto i=0; i<tuple_size; i++) {
PyObject *t_item = PyTuple_GET_ITEM(tuple, i);
const char *t_value;
if (!PyArg_Parse(t_item, "s", &t_value)) {
PyErr_SetString(kageext_error, "Need string");
return result;
}
result.push_back(std::string(t_value));
}
return result;
}
static std::shared_ptr<DataRobot2D> get_datarobot2d_from_pyobj(PyObject *id) {
const char *datarobot2d_s;
if(!PyArg_Parse(id, "s", &datarobot2d_s)) {
PyErr_SetString(kageext_error, "get_datarobot2d_content with no valid obj_id");
return NULL;
}
std::string datarobot2d_id(datarobot2d_s);
if (datarobot2ds_map.find(datarobot2d_id) == datarobot2ds_map.end()) {
PyErr_SetString(kageext_error, "no such obj_id");
return NULL;
}
std::shared_ptr<DataRobot2D> dataRobot2D = datarobot2ds_map[datarobot2d_id];
return dataRobot2D;
}
// function mapping from Python to CPP
static PyObject *
call(PyObject *self, PyObject *args)
{
PyObject *cpp_args = nullptr;
const char *function;
if (!PyArg_ParseTuple(args, "sO", &function, &cpp_args)) {
PyErr_SetString(kageext_error, "PyArg Error");
return NULL;
}
if (!PyTuple_Check(cpp_args)) {
PyErr_SetString(kageext_error, "CPP Arg not a tuple");
return NULL;
}
if (strcmp(function, "create_datarobot2d") == 0) {
// cpp_args: data(2darray), columns(list), index(list)
PyObject *data;
PyObject *columns;
PyObject *index;
ARGS_NUM_CHECK(3)
data = PyTuple_GET_ITEM(cpp_args, 0);
columns = PyTuple_GET_ITEM(cpp_args, 1);
index = PyTuple_GET_ITEM(cpp_args, 2);
std::vector<std::string> v_columns = s_parse_tuple_to_vector(columns);
std::vector<std::string> v_index = s_parse_tuple_to_vector(index);
if (v_columns.empty()) {
PyErr_SetString(kageext_error, "columns is empty");
return NULL;
}
if (v_index.empty()) {
PyErr_SetString(kageext_error, "index is empty");
return NULL;
}
PyArrayObject *array = (PyArrayObject *)data;
std::shared_ptr<DataRobot2D> dataRobot2D = std::make_shared<DataRobot2D>(array, v_columns, v_index);
std::string uuid = get_uuid();
datarobot2ds_map[uuid] = dataRobot2D;
return PyUnicode_FromString(uuid.c_str());
} else if (strcmp(function, "get_datarobot2d_content") == 0) {
PyObject *datarobot2d_id_obj;
ARGS_NUM_CHECK(1)
datarobot2d_id_obj = PyTuple_GET_ITEM(cpp_args, 0);
std::shared_ptr<DataRobot2D> dataRobot2D = get_datarobot2d_from_pyobj(datarobot2d_id_obj);
if (dataRobot2D == NULL) return NULL;
std::vector<std::string> columns = dataRobot2D->get_columns();
std::vector<std::string> index = dataRobot2D->get_index();
PyObject *p_columns = s_parse_vector_to_pyobj(columns);
PyObject *p_index = s_parse_vector_to_pyobj(index);
PyObject *array = (PyObject *)dataRobot2D->get_array();
return Py_BuildValue("(OOO)", array, p_columns, p_index);
} else if (strcmp(function, "deconstruct_datarobot2d") == 0) {
PyObject *datarobot2d_id_obj;
ARGS_NUM_CHECK(1)
datarobot2d_id_obj = PyTuple_GET_ITEM(cpp_args, 0);
std::shared_ptr<DataRobot2D> dataRobot2D = get_datarobot2d_from_pyobj(datarobot2d_id_obj);
dataRobot2D->dec_array_ref();
// tianhuan(todo) datarobot2d still live in datarobot2ds now.
Py_RETURN_NONE;
}
Py_RETURN_NONE;
}
static PyMethodDef KageExtMethods[] = {
{"eversion", show_ext_version, METH_VARARGS, "Get extension's version."},
{"call", call, METH_VARARGS, "Function call entrance."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef kageextmodule = {
PyModuleDef_HEAD_INIT,
"kageext",
NULL,
-1,
KageExtMethods
};
PyMODINIT_FUNC
PyInit_kageext(void)
{
PyObject *m;
m = PyModule_Create(&kageextmodule);
if (m == NULL)
return NULL;
kageext_error = PyErr_NewException("kageext.error", NULL, NULL);
Py_INCREF(kageext_error);
PyModule_AddObject(m, "error", kageext_error);
import_array();
return m;
}<commit_msg>remove unused obj<commit_after>#include <iostream>
#include <vector>
#include <map>
#include "numpy_import.h"
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include "numpy/arrayobject.h"
#include "Python.h"
#include "datarobot2d.h"
#include "utils.h"
#define ARGS_NUM_CHECK(NUM) if (PyTuple_GET_SIZE(cpp_args) != NUM) { \
PyErr_SetString(kageext_error, "need NUM args"); \
return NULL; \
}
const std::string EXT_VERSION = "0.1";
static PyObject *kageext_error;
static std::map<std::string, std::shared_ptr<DataRobot2D> > datarobot2ds_map;
// get cpp extension's version
static PyObject *
show_ext_version(PyObject *self, PyObject *args)
{
return PyUnicode_FromString(EXT_VERSION.c_str());
}
static PyObject *s_parse_vector_to_pyobj(std::vector<std::string> v) {
PyObject *pyobj = PyTuple_New(v.size());
std::vector<std::string>::size_type index = 0;
for (auto s : v) {
PyObject *item = Py_BuildValue("s", s.c_str());
PyTuple_SetItem(pyobj, index, item);
index++;
}
return pyobj;
}
static std::vector<std::string> s_parse_tuple_to_vector(PyObject *tuple) {
std::vector<std::string> result;
if (!PyTuple_Check(tuple)) {
PyErr_SetString(kageext_error, "Need tuple");
return result;
}
auto tuple_size = PyTuple_GET_SIZE(tuple);
for(auto i=0; i<tuple_size; i++) {
PyObject *t_item = PyTuple_GET_ITEM(tuple, i);
const char *t_value;
if (!PyArg_Parse(t_item, "s", &t_value)) {
PyErr_SetString(kageext_error, "Need string");
return result;
}
result.push_back(std::string(t_value));
}
return result;
}
static std::shared_ptr<DataRobot2D> get_datarobot2d_from_pyobj(PyObject *id) {
const char *datarobot2d_s;
if(!PyArg_Parse(id, "s", &datarobot2d_s)) {
PyErr_SetString(kageext_error, "get_datarobot2d_content with no valid obj_id");
return NULL;
}
std::string datarobot2d_id(datarobot2d_s);
if (datarobot2ds_map.find(datarobot2d_id) == datarobot2ds_map.end()) {
PyErr_SetString(kageext_error, "no such obj_id");
return NULL;
}
std::shared_ptr<DataRobot2D> dataRobot2D = datarobot2ds_map[datarobot2d_id];
return dataRobot2D;
}
// function mapping from Python to CPP
static PyObject *
call(PyObject *self, PyObject *args)
{
PyObject *cpp_args = nullptr;
const char *function;
if (!PyArg_ParseTuple(args, "sO", &function, &cpp_args)) {
PyErr_SetString(kageext_error, "PyArg Error");
return NULL;
}
if (!PyTuple_Check(cpp_args)) {
PyErr_SetString(kageext_error, "CPP Arg not a tuple");
return NULL;
}
if (strcmp(function, "create_datarobot2d") == 0) {
// cpp_args: data(2darray), columns(list), index(list)
PyObject *data;
PyObject *columns;
PyObject *index;
ARGS_NUM_CHECK(3)
data = PyTuple_GET_ITEM(cpp_args, 0);
columns = PyTuple_GET_ITEM(cpp_args, 1);
index = PyTuple_GET_ITEM(cpp_args, 2);
std::vector<std::string> v_columns = s_parse_tuple_to_vector(columns);
std::vector<std::string> v_index = s_parse_tuple_to_vector(index);
if (v_columns.empty()) {
PyErr_SetString(kageext_error, "columns is empty");
return NULL;
}
if (v_index.empty()) {
PyErr_SetString(kageext_error, "index is empty");
return NULL;
}
PyArrayObject *array = (PyArrayObject *)data;
std::shared_ptr<DataRobot2D> dataRobot2D = std::make_shared<DataRobot2D>(array, v_columns, v_index);
std::string uuid = get_uuid();
datarobot2ds_map[uuid] = dataRobot2D;
return PyUnicode_FromString(uuid.c_str());
} else if (strcmp(function, "get_datarobot2d_content") == 0) {
PyObject *datarobot2d_id_obj;
ARGS_NUM_CHECK(1)
datarobot2d_id_obj = PyTuple_GET_ITEM(cpp_args, 0);
std::shared_ptr<DataRobot2D> dataRobot2D = get_datarobot2d_from_pyobj(datarobot2d_id_obj);
if (dataRobot2D == NULL) return NULL;
std::vector<std::string> columns = dataRobot2D->get_columns();
std::vector<std::string> index = dataRobot2D->get_index();
PyObject *p_columns = s_parse_vector_to_pyobj(columns);
PyObject *p_index = s_parse_vector_to_pyobj(index);
PyObject *array = (PyObject *)dataRobot2D->get_array();
return Py_BuildValue("(OOO)", array, p_columns, p_index);
} else if (strcmp(function, "deconstruct_datarobot2d") == 0) {
PyObject *datarobot2d_id_obj;
ARGS_NUM_CHECK(1)
datarobot2d_id_obj = PyTuple_GET_ITEM(cpp_args, 0);
std::shared_ptr<DataRobot2D> dataRobot2D = get_datarobot2d_from_pyobj(datarobot2d_id_obj);
dataRobot2D->dec_array_ref();
const char *datarobot2d_s;
if(!PyArg_Parse(datarobot2d_id_obj, "s", &datarobot2d_s)) {
PyErr_SetString(kageext_error, "deconstruct_datarobot2d with no valid obj_id");
return NULL;
}
std::string datarobot2d_id(datarobot2d_s);
datarobot2ds_map.erase(datarobot2d_id);
Py_RETURN_NONE;
}
Py_RETURN_NONE;
}
static PyMethodDef KageExtMethods[] = {
{"eversion", show_ext_version, METH_VARARGS, "Get extension's version."},
{"call", call, METH_VARARGS, "Function call entrance."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef kageextmodule = {
PyModuleDef_HEAD_INIT,
"kageext",
NULL,
-1,
KageExtMethods
};
PyMODINIT_FUNC
PyInit_kageext(void)
{
PyObject *m;
m = PyModule_Create(&kageextmodule);
if (m == NULL)
return NULL;
kageext_error = PyErr_NewException("kageext.error", NULL, NULL);
Py_INCREF(kageext_error);
PyModule_AddObject(m, "error", kageext_error);
import_array();
return m;
}<|endoftext|>
|
<commit_before>#pragma once
// Include most Rack headers for convenience
#include <common.hpp>
#include <math.hpp>
#include <string.hpp>
#include <system.hpp>
#include <random.hpp>
#include <network.hpp>
#include <asset.hpp>
#include <window.hpp>
#include <app.hpp>
#include <midi.hpp>
#include <helpers.hpp>
#include <componentlibrary.hpp>
#include <widget/Widget.hpp>
#include <widget/TransparentWidget.hpp>
#include <widget/OpaqueWidget.hpp>
#include <widget/TransformWidget.hpp>
#include <widget/ZoomWidget.hpp>
#include <widget/SvgWidget.hpp>
#include <widget/FramebufferWidget.hpp>
#include <widget/OpenGlWidget.hpp>
#include <ui/SequentialLayout.hpp>
#include <ui/Label.hpp>
#include <ui/List.hpp>
#include <ui/MenuOverlay.hpp>
#include <ui/Tooltip.hpp>
#include <ui/TextField.hpp>
#include <ui/PasswordField.hpp>
#include <ui/ScrollWidget.hpp>
#include <ui/Slider.hpp>
#include <ui/Menu.hpp>
#include <ui/MenuEntry.hpp>
#include <ui/MenuSeparator.hpp>
#include <ui/MenuLabel.hpp>
#include <ui/MenuItem.hpp>
#include <ui/Button.hpp>
#include <ui/IconButton.hpp>
#include <ui/ChoiceButton.hpp>
#include <ui/RadioButton.hpp>
#include <ui/ProgressBar.hpp>
#include <app/AudioWidget.hpp>
#include <app/CircularShadow.hpp>
#include <app/Knob.hpp>
#include <app/LedDisplay.hpp>
#include <app/LightWidget.hpp>
#include <app/MidiWidget.hpp>
#include <app/ModuleLightWidget.hpp>
#include <app/ModuleWidget.hpp>
#include <app/MultiLightWidget.hpp>
#include <app/ParamWidget.hpp>
#include <app/PortWidget.hpp>
#include <app/RackRail.hpp>
#include <app/Scene.hpp>
#include <app/RackScrollWidget.hpp>
#include <app/RackWidget.hpp>
#include <app/SvgButton.hpp>
#include <app/SvgKnob.hpp>
#include <app/SvgPanel.hpp>
#include <app/SvgPort.hpp>
#include <app/SvgScrew.hpp>
#include <app/SvgSlider.hpp>
#include <app/SvgSwitch.hpp>
#include <app/MenuBar.hpp>
#include <app/CableWidget.hpp>
#include <engine/Engine.hpp>
#include <engine/Param.hpp>
#include <engine/Port.hpp>
#include <engine/Module.hpp>
#include <engine/Param.hpp>
#include <engine/Cable.hpp>
#include <plugin/Plugin.hpp>
#include <plugin/Model.hpp>
#include <plugin/callbacks.hpp>
#include <dsp/common.hpp>
#include <dsp/digital.hpp>
#include <dsp/fft.hpp>
#include <dsp/filter.hpp>
#include <dsp/fir.hpp>
#include <dsp/midi.hpp>
#include <dsp/minblep.hpp>
#include <dsp/ode.hpp>
#include <dsp/resampler.hpp>
#include <dsp/ringbuffer.hpp>
#include <dsp/vumeter.hpp>
#include <dsp/window.hpp>
#include <dsp/approx.hpp>
#include <simd/vector.hpp>
#include <simd/functions.hpp>
namespace rack {
/** Define this macro before including this header to prevent common namespaces from being included in the main `rack::` namespace. */
#ifndef RACK_FLATTEN_NAMESPACES
// Import some namespaces for convenience
using namespace logger;
using namespace math;
using namespace widget;
using namespace ui;
using namespace app;
using plugin::Plugin;
using plugin::Model;
using namespace engine;
using namespace componentlibrary;
// Import namespace recursively to solve the problem of calling `rack::DEBUG(...)` which expands to `rack::rack::logger(...)`.
namespace rack = rack;
#endif
} // namespace rack
<commit_msg>Remove RACK_FLATTEN_NAMESPACES since it is not known to be used.<commit_after>#pragma once
// Include most Rack headers for convenience
#include <common.hpp>
#include <math.hpp>
#include <string.hpp>
#include <system.hpp>
#include <random.hpp>
#include <network.hpp>
#include <asset.hpp>
#include <window.hpp>
#include <app.hpp>
#include <midi.hpp>
#include <helpers.hpp>
#include <componentlibrary.hpp>
#include <widget/Widget.hpp>
#include <widget/TransparentWidget.hpp>
#include <widget/OpaqueWidget.hpp>
#include <widget/TransformWidget.hpp>
#include <widget/ZoomWidget.hpp>
#include <widget/SvgWidget.hpp>
#include <widget/FramebufferWidget.hpp>
#include <widget/OpenGlWidget.hpp>
#include <ui/SequentialLayout.hpp>
#include <ui/Label.hpp>
#include <ui/List.hpp>
#include <ui/MenuOverlay.hpp>
#include <ui/Tooltip.hpp>
#include <ui/TextField.hpp>
#include <ui/PasswordField.hpp>
#include <ui/ScrollWidget.hpp>
#include <ui/Slider.hpp>
#include <ui/Menu.hpp>
#include <ui/MenuEntry.hpp>
#include <ui/MenuSeparator.hpp>
#include <ui/MenuLabel.hpp>
#include <ui/MenuItem.hpp>
#include <ui/Button.hpp>
#include <ui/IconButton.hpp>
#include <ui/ChoiceButton.hpp>
#include <ui/RadioButton.hpp>
#include <ui/ProgressBar.hpp>
#include <app/AudioWidget.hpp>
#include <app/CircularShadow.hpp>
#include <app/Knob.hpp>
#include <app/LedDisplay.hpp>
#include <app/LightWidget.hpp>
#include <app/MidiWidget.hpp>
#include <app/ModuleLightWidget.hpp>
#include <app/ModuleWidget.hpp>
#include <app/MultiLightWidget.hpp>
#include <app/ParamWidget.hpp>
#include <app/PortWidget.hpp>
#include <app/RackRail.hpp>
#include <app/Scene.hpp>
#include <app/RackScrollWidget.hpp>
#include <app/RackWidget.hpp>
#include <app/SvgButton.hpp>
#include <app/SvgKnob.hpp>
#include <app/SvgPanel.hpp>
#include <app/SvgPort.hpp>
#include <app/SvgScrew.hpp>
#include <app/SvgSlider.hpp>
#include <app/SvgSwitch.hpp>
#include <app/MenuBar.hpp>
#include <app/CableWidget.hpp>
#include <engine/Engine.hpp>
#include <engine/Param.hpp>
#include <engine/Port.hpp>
#include <engine/Module.hpp>
#include <engine/Param.hpp>
#include <engine/Cable.hpp>
#include <plugin/Plugin.hpp>
#include <plugin/Model.hpp>
#include <plugin/callbacks.hpp>
#include <dsp/common.hpp>
#include <dsp/digital.hpp>
#include <dsp/fft.hpp>
#include <dsp/filter.hpp>
#include <dsp/fir.hpp>
#include <dsp/midi.hpp>
#include <dsp/minblep.hpp>
#include <dsp/ode.hpp>
#include <dsp/resampler.hpp>
#include <dsp/ringbuffer.hpp>
#include <dsp/vumeter.hpp>
#include <dsp/window.hpp>
#include <dsp/approx.hpp>
#include <simd/vector.hpp>
#include <simd/functions.hpp>
namespace rack {
// Import some namespaces for convenience
using namespace logger;
using namespace math;
using namespace widget;
using namespace ui;
using namespace app;
using plugin::Plugin;
using plugin::Model;
using namespace engine;
using namespace componentlibrary;
// Import namespace recursively to solve the problem of calling `rack::DEBUG(...)` which expands to `rack::rack::logger(...)`.
namespace rack = rack;
} // namespace rack
<|endoftext|>
|
<commit_before>/**
* binary search tree class
* created by lisovskey
*/
#ifndef TREE_H
#define TREE_H
#define RZD_BEGIN namespace rzd {
#define RZD_END }
#define ANYWAY
#define THEN
#include <list>
#include <memory>
#include <ostream>
#include <optional>
RZD_BEGIN
using std::list;
using std::ostream;
using std::optional;
using std::make_optional;
// binary search tree
template <typename T>
class Tree
{
// prototype
struct Node;
// aliases
using pointer = std::shared_ptr<Node>;
using pair = std::pair<int, T>;
// unit of tree
struct Node {
pair data;
pointer left;
pointer right;
Node(pair data) : data{ data }, left{ nullptr }, right{ nullptr } {}
};
// start point
pointer root;
// IF CONDITION ACTION
pointer _insert(pointer leaf, const pair data)
{
if (!leaf) return leaf = pointer(new Node(data));
else if (data.first < leaf->data.first) leaf->left = _insert(leaf->left, data);
else if (data.first > leaf->data.first) leaf->right = _insert(leaf->right, data);
else leaf->data.first = data.first;
ANYWAY return leaf;
}
pointer _find(const pointer leaf, const int key) const
{
if (!leaf || leaf->data.first == key) return leaf;
else if (key < leaf->data.first) return _find(leaf->left, key);
else return _find(leaf->right, key);
}
pointer _min(const pointer leaf) const
{
if (leaf->left) return _min(leaf->left);
else return leaf;
}
pointer _remove(pointer leaf, const int key)
{
if (!leaf) return leaf;
else if (key < leaf->data.first) leaf->left = _remove(leaf->left, key);
else if (key > leaf->data.first) leaf->right = _remove(leaf->right, key);
else if (leaf->left && leaf->right) {
THEN leaf->data.first = (_min(leaf->right))->data.first;
THEN leaf->right = _remove(leaf->right, leaf->data.first);
}
else if (leaf->left) leaf = leaf->left;
else if (leaf->right) leaf = leaf->right;
else leaf = nullptr;
ANYWAY return leaf;
}
int _size(const pointer leaf) const
{
if (leaf) return _size(leaf->left) + 1 + _size(leaf->right);
else return 0;
}
ostream& _view(const pointer leaf, ostream& os) const
{
if (leaf) {
THEN _view(leaf->left, os);
THEN os << leaf->data.second << "\n";
THEN _view(leaf->right, os);
}
ANYWAY return os;
}
list<pair>& _get_list(const pointer leaf, list<pair>& list) const
{
if (leaf) {
THEN _get_list(leaf->left, list);
THEN list.push_back(leaf->data);
THEN _get_list(leaf->right, list);
}
ANYWAY return list;
}
public:
// operators
optional<T> operator[](const int key)
{
ANYWAY return find(key);
}
friend ostream& operator<<(ostream& os, const Tree& tree)
{
ANYWAY return tree._view(tree.root, os);
}
// constructors
Tree() : root{ nullptr } {}
Tree(const int key, const T value) : root{ new Node(pair(key, value)) } {}
// usable methods
// inserts new node with key and value
void insert(const int key, const T value)
{
ANYWAY root = _insert(root, pair(key, value));
}
// returns optional value by key
optional<T> find(const int key) const
{
ANYWAY pointer leaf = _find(root, key);
if (leaf) return make_optional(leaf->data.second);
else return {};
}
// removes node by key
void remove(const int key)
{
ANYWAY root = _remove(root, key);
}
// returns number of nodes
int size() const
{
ANYWAY return _size(root);
}
// returns sorted list
list<pair> get_list() const
{
ANYWAY list<pair> list;
ANYWAY return _get_list(root, list);
}
};
RZD_END
#endif<commit_msg>clear, pass by ref<commit_after>/**
* binary search tree class
* created by lisovskey
*/
#ifndef TREE_H
#define TREE_H
#define RZD_BEGIN namespace rzd {
#define RZD_END }
#define ANYWAY
#define THEN
#include <list>
#include <memory>
#include <optional>
RZD_BEGIN
using std::list;
using std::optional;
// binary search tree
template <typename T>
class Tree
{
// prototype
struct Node;
// aliases
using pointer = std::shared_ptr<Node>;
using pair = std::pair<int, T>;
// unit of tree
struct Node {
pair data;
pointer left;
pointer right;
Node(pair data) : data{ data }, left{ nullptr }, right{ nullptr } {}
};
// start point
pointer root;
// IF CONDITION ACTION
void insert(pointer& leaf, const pair data)
{
if (!leaf) leaf = pointer{ new Node{ data } };
else if (data.first < leaf->data.first) insert(leaf->left, data);
else if (data.first > leaf->data.first) insert(leaf->right, data);
else leaf->data.first = data.first;
}
pointer find(const pointer& leaf, const int key) const
{
if (!leaf || leaf->data.first == key) return leaf;
else if (key < leaf->data.first) return find(leaf->left, key);
else return find(leaf->right, key);
}
pointer minimum(const pointer& leaf) const
{
if (leaf->left) return minimum(leaf->left);
else return leaf;
}
void remove(pointer& leaf, const int key)
{
if (!leaf) return;
else if (key < leaf->data.first) remove(leaf->left, key);
else if (key > leaf->data.first) remove(leaf->right, key);
else if (leaf->left && leaf->right) {
THEN leaf->data.first = minimum(leaf->right)->data.first;
THEN remove(leaf->right, leaf->data.first);
}
else if (leaf->left) leaf = leaf->left;
else if (leaf->right) leaf = leaf->right;
else leaf = nullptr;
}
void clear(pointer& leaf)
{
if (leaf) {
THEN clear(leaf->left);
THEN clear(leaf->right);
THEN leaf = nullptr;
}
}
int size(const pointer& leaf) const
{
if (leaf) return size(leaf->left) + 1 + size(leaf->right);
else return 0;
}
list<pair>& get_list(const pointer& leaf, list<pair>& list) const
{
if (leaf) {
THEN get_list(leaf->left, list);
THEN list.push_back(leaf->data);
THEN get_list(leaf->right, list);
}
ANYWAY return list;
}
public:
// inserts new node with key and value
inline void insert(const int key, const T& value)
{
ANYWAY insert(root, pair{ key, value });
}
// returns optional value by key
inline optional<T> find(const int key) const
{
if (pointer leaf = find(root, key)) return { leaf->data.second };
else return {};
}
// removes node by key
inline void remove(const int key)
{
ANYWAY remove(root, key);
}
inline void clear()
{
ANYWAY clear(root);
}
// returns number of nodes
inline int size() const
{
ANYWAY return size(root);
}
// returns sorted list
inline list<pair> get_list() const
{
ANYWAY return get_list(root, list<pair>());
}
// returns optional value by key
inline optional<T> operator[](const int key)
{
ANYWAY return find(key);
}
// constructors
Tree() : root{ nullptr } {}
Tree(const int key, const T& value) : root{ new Node{ pair{ key, value } } } {}
};
RZD_END
#endif<|endoftext|>
|
<commit_before>#include "util/bitmap.h"
#include <math.h>
#include <iostream>
#include "level/utils.h"
#include "network/messages.h"
#include "loading.h"
#include "util/file-system.h"
#include "util/font.h"
#include "util/funcs.h"
#include "globals.h"
#include <vector>
#include <pthread.h>
#include "util/message-queue.h"
#include "init.h"
using namespace std;
typedef struct pair{
int x, y;
} ppair;
class Info{
public:
Info(){
Global::registerInfo(&messages);
}
bool transferMessages(Messages & box){
bool did = false;
while (messages.hasAny()){
const string & str = messages.get();
box.addMessage(str);
did = true;
}
return did;
}
~Info(){
Global::unregisterInfo(&messages);
}
private:
MessageQueue messages;
};
void * loadingScreen( void * arg ){
const int load_x = 80;
const int load_y = 220;
const int infobox_width = 200;
const int infobox_height = 150;
Info info;
string name = Filesystem::find("/fonts/arial.ttf");
const Font & myFont = Font::getFont( name, 24, 24 );
const Font & infoFont = Font::getFont(name, 24, 24);
Level::LevelInfo levelInfo;
if (arg != NULL){
levelInfo = *(Level::LevelInfo*) arg;
}
// const char * the_string = (arg != NULL) ? (const char *) arg : "Loading...";
int load_width = myFont.textLength(levelInfo.loadingMessage().c_str());
int load_height = myFont.getHeight(levelInfo.loadingMessage().c_str());
const int infobox_x = load_x;
const int infobox_y = load_y + load_height * 2;
Global::debug( 2 ) << "loading screen" << endl;
Bitmap work( load_width, load_height );
Bitmap letters( load_width, load_height );
Messages infobox(infobox_width, infobox_height);
Bitmap infoWork(infobox_width, infobox_height);
Bitmap infoBackground(infobox_width, infobox_height);
letters.fill( Bitmap::MaskColor );
myFont.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), letters, levelInfo.loadingMessage().c_str(), 0 );
vector< ppair > pairs;
/* store every pixel we need to draw */
for ( int x = 0; x < letters.getWidth(); x++ ){
for ( int y = 0; y < letters.getHeight(); y++ ){
int pixel = letters.getPixel( x, y );
if ( pixel != Bitmap::MaskColor ){
ppair p;
p.x = x;
p.y = y;
pairs.push_back( p );
}
}
}
const int MAX_COLOR = 200;
int colors[ MAX_COLOR ];
int c1 = Bitmap::makeColor( 16, 16, 16 );
int c2 = Bitmap::makeColor( 192, 8, 8 );
/* blend from dark grey to light red */
Util::blend_palette( colors, MAX_COLOR / 2, c1, c2 );
Util::blend_palette( colors + MAX_COLOR / 2, MAX_COLOR / 2, c2, c1 );
Global::speed_counter = 0;
{ /* force scoping */
Bitmap background(levelInfo.loadingBackground());
background.Blit( load_x, load_y, load_width, load_height, 0, 0, work );
Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2 - Font::getDefaultFont().getHeight(), Bitmap::makeColor( 192, 192, 192 ), background, "Paintown version %s", 0, Global::getVersionString().c_str());
Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2, Bitmap::makeColor( 192, 192, 192 ), background, "Made by Jon Rafkind", 0 );
background.BlitToScreen();
background.Blit(infobox_x, infobox_y, infoBackground.getWidth(), infoBackground.getHeight(), 0, 0, infoBackground);
}
bool quit = false;
/* keeps the colors moving */
static unsigned mover = 0;
while ( ! quit ){
bool draw = false;
bool drawInfo = false;
if ( Global::speed_counter > 0 ){
double think = Global::speed_counter;
Global::speed_counter = 0;
draw = true;
while ( think > 0 ){
mover = (mover + 1) % MAX_COLOR;
think -= 1;
}
drawInfo = info.transferMessages(infobox);
} else {
Util::rest( 1 );
}
if ( draw ){
for ( vector< ppair >::iterator it = pairs.begin(); it != pairs.end(); it++ ){
int color = colors[ (it->x - mover + MAX_COLOR) % MAX_COLOR ];
work.putPixel( it->x, it->y, color );
}
if (drawInfo){
infoBackground.Blit(infoWork);
infobox.draw(0, 0, infoWork, infoFont);
infoWork.BlitAreaToScreen(infobox_x, infobox_y);
}
/* work already contains the correct background */
// work.Blit( load_x, load_y, *Bitmap::Screen );
work.BlitAreaToScreen( load_x, load_y );
}
pthread_mutex_lock( &Global::loading_screen_mutex );
quit = Global::done_loading;
pthread_mutex_unlock( &Global::loading_screen_mutex );
}
return NULL;
}
<commit_msg>make info font smaller<commit_after>#include "util/bitmap.h"
#include <math.h>
#include <iostream>
#include "level/utils.h"
#include "network/messages.h"
#include "loading.h"
#include "util/file-system.h"
#include "util/font.h"
#include "util/funcs.h"
#include "globals.h"
#include <vector>
#include <pthread.h>
#include "util/message-queue.h"
#include "init.h"
using namespace std;
typedef struct pair{
int x, y;
} ppair;
class Info{
public:
Info(){
Global::registerInfo(&messages);
}
bool transferMessages(Messages & box){
bool did = false;
while (messages.hasAny()){
const string & str = messages.get();
box.addMessage(str);
did = true;
}
return did;
}
~Info(){
Global::unregisterInfo(&messages);
}
private:
MessageQueue messages;
};
void * loadingScreen( void * arg ){
const int load_x = 80;
const int load_y = 220;
const int infobox_width = 300;
const int infobox_height = 150;
Info info;
string fontName = Filesystem::find("/fonts/arial.ttf");
const Font & myFont = Font::getFont(fontName, 24, 24);
const Font & infoFont = Font::getFont(fontName, 24, 24);
Level::LevelInfo levelInfo;
if (arg != NULL){
levelInfo = *(Level::LevelInfo*) arg;
}
// const char * the_string = (arg != NULL) ? (const char *) arg : "Loading...";
int load_width = myFont.textLength(levelInfo.loadingMessage().c_str());
int load_height = myFont.getHeight(levelInfo.loadingMessage().c_str());
const int infobox_x = load_x;
const int infobox_y = load_y + load_height * 2;
Global::debug( 2 ) << "loading screen" << endl;
Bitmap work( load_width, load_height );
Bitmap letters( load_width, load_height );
Messages infobox(infobox_width, infobox_height);
Bitmap infoWork(infobox_width, infobox_height);
Bitmap infoBackground(infobox_width, infobox_height);
letters.fill( Bitmap::MaskColor );
myFont.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), letters, levelInfo.loadingMessage().c_str(), 0 );
vector< ppair > pairs;
/* store every pixel we need to draw */
for ( int x = 0; x < letters.getWidth(); x++ ){
for ( int y = 0; y < letters.getHeight(); y++ ){
int pixel = letters.getPixel( x, y );
if ( pixel != Bitmap::MaskColor ){
ppair p;
p.x = x;
p.y = y;
pairs.push_back( p );
}
}
}
const int MAX_COLOR = 200;
int colors[ MAX_COLOR ];
int c1 = Bitmap::makeColor( 16, 16, 16 );
int c2 = Bitmap::makeColor( 192, 8, 8 );
/* blend from dark grey to light red */
Util::blend_palette( colors, MAX_COLOR / 2, c1, c2 );
Util::blend_palette( colors + MAX_COLOR / 2, MAX_COLOR / 2, c2, c1 );
Global::speed_counter = 0;
{ /* force scoping */
Bitmap background(levelInfo.loadingBackground());
background.Blit( load_x, load_y, load_width, load_height, 0, 0, work );
Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2 - Font::getDefaultFont().getHeight(), Bitmap::makeColor( 192, 192, 192 ), background, "Paintown version %s", 0, Global::getVersionString().c_str());
Font::getDefaultFont().printf( 400, 480 - Font::getDefaultFont().getHeight() * 5 / 2, Bitmap::makeColor( 192, 192, 192 ), background, "Made by Jon Rafkind", 0 );
background.BlitToScreen();
background.Blit(infobox_x, infobox_y, infoBackground.getWidth(), infoBackground.getHeight(), 0, 0, infoBackground);
}
bool quit = false;
/* keeps the colors moving */
static unsigned mover = 0;
while ( ! quit ){
bool draw = false;
bool drawInfo = false;
if ( Global::speed_counter > 0 ){
double think = Global::speed_counter;
Global::speed_counter = 0;
draw = true;
while ( think > 0 ){
mover = (mover + 1) % MAX_COLOR;
think -= 1;
}
drawInfo = info.transferMessages(infobox);
} else {
Util::rest( 1 );
}
if ( draw ){
for ( vector< ppair >::iterator it = pairs.begin(); it != pairs.end(); it++ ){
int color = colors[ (it->x - mover + MAX_COLOR) % MAX_COLOR ];
work.putPixel( it->x, it->y, color );
}
if (drawInfo){
infoBackground.Blit(infoWork);
/* cheesy hack to change the font size. the font
* should store the size and change it on its own
*/
Font::getFont(fontName, 13, 13);
infobox.draw(0, 0, infoWork, infoFont);
Font::getFont(fontName, 24, 24);
infoWork.BlitAreaToScreen(infobox_x, infobox_y);
}
/* work already contains the correct background */
// work.Blit( load_x, load_y, *Bitmap::Screen );
work.BlitAreaToScreen( load_x, load_y );
}
pthread_mutex_lock( &Global::loading_screen_mutex );
quit = Global::done_loading;
pthread_mutex_unlock( &Global::loading_screen_mutex );
}
return NULL;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <cstdio>
#include <QApplication>
#include <QtUiTools>
#include "med.hpp"
using namespace std;
class MainUi : public QObject {
Q_OBJECT
public:
MainUi() {
loadUiFiles();
}
Med med;
private slots:
void onProcessClicked() {
med.listProcesses();
processDialog->show();
//Get the tree widget
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
procTreeWidget->clear(); //Remove all items
//Add all the process into the tree widget
for(int i=med.processes.size()-1;i>=0;i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(procTreeWidget);
item->setText(0, med.processes[i].pid.c_str());
item->setText(1, med.processes[i].cmdline.c_str());
}
}
void onProcItemDblClicked(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
med.selectedProcess = med.processes[med.processes.size() -1 - index];
//Make changes to the selectedProc and hide the window
QLineEdit* line = this->mainWindow->findChild<QLineEdit*>("selectedProc");
line->setText(QString::fromLatin1((med.selectedProcess.pid + " " + med.selectedProcess.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void onScanClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if(med.selectedProcess.pid == "") {
cerr << "No process seelcted " <<endl;
return;
}
try {
med.scanEqual(scanValue, scanType);
} catch(string e) {
cerr << "scan: "<<e<<endl;
}
if(med.scanAddresses.size() <= 800) {
addressToScanTreeWidget(med, scanType, scanTreeWidget);
}
updateNumberOfAddresses(mainWindow);
}
void onFilterClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
med.scanFilter(scanValue, scanType);
if(med.scanAddresses.size() <= 800)
addressToScanTreeWidget(med, scanType, scanTreeWidget);
updateNumberOfAddresses(mainWindow);
}
void onClearClicked() {
mainWindow->findChild<QTreeWidget*>("scanTreeWidget")->clear();
med.scanAddresses.clear();
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage("Scan cleared");
}
void onScanAddClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
QTreeWidgetItem* item = scanTreeWidget->currentItem();
int index = scanTreeWidget->indexOfTopLevelItem(item);
//TODO: Write this to a function
MedAddress medAddress;
medAddress.address = med.scanAddresses[index].address;
medAddress.scanType = med.scanAddresses[index].scanType;
med.addresses.push_back(medAddress);
//Add to AddressTreeWidget
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* itemToAdd = new QTreeWidgetItem(addressTreeWidget);
itemToAdd->setText(0, "Your description");
itemToAdd->setText(1, intToHex(medAddress.address).c_str());
itemToAdd->setText(3, med.getAddressValueByIndex(med.addresses.size()-1).c_str());
itemToAdd->setText(4, "false");
itemToAdd->setFlags(itemToAdd->flags() | Qt::ItemIsEditable);
//Add combo box
QComboBox* combo = createTypeComboBox(addressTreeWidget, medAddress.getScanType());
combo->setProperty("tree-row", addressTreeWidget->indexOfTopLevelItem(itemToAdd));
addressTreeWidget->setItemWidget(itemToAdd, 2, combo);
//Add signal
QObject::connect(combo,
SIGNAL(currentTextChanged(QString)),
this,
SLOT(onAddressTypeChanged(QString)));
}
//TODO: Complete this one
void onScanAddAllClicked() {
}
void onScanItemChanged(QTreeWidgetItem* item, int column) {
switch(column) {
case 1: //Not available, because the 2nd column is combobox
break;
case 2:
editScanValue(item, column);
break;
}
}
void onScanTypeChanged(QString text) {
QComboBox* combo = qobject_cast<QComboBox*>(sender());
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
QTreeWidgetItem* item = scanTreeWidget->topLevelItem(combo->property("tree-row").toInt());
scanTreeWidget->setCurrentItem(item);
editScanType(item, text.toStdString());
}
void onAddressTypeChanged(QString text) {
QComboBox* combo = qobject_cast<QComboBox*>(sender());
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* item = addressTreeWidget->topLevelItem(combo->property("tree-row").toInt());
addressTreeWidget->setCurrentItem(item);
editAddressType(item, text.toStdString());
}
private:
QWidget* mainWindow;
QWidget* chooseProc;
QDialog* processDialog;
void loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
chooseProc = loader.load(&processFile, processDialog);
processFile.close();
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(chooseProc);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Statusbar message
QStatusBar* statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
//Add signal
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
QObject::connect(procTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcItemDblClicked(QTreeWidgetItem*, int)));
procTreeWidget->installEventFilter(this);
//TODO: center
mainWindow->show();
//Add signal to the process
QWidget* process = mainWindow->findChild<QWidget*>("process");
QObject::connect(process, SIGNAL(clicked()), this, SLOT(onProcessClicked()));
//Add signal to scan
QWidget* scanButton = mainWindow->findChild<QWidget*>("scanButton");
QObject::connect(scanButton, SIGNAL(clicked()), this, SLOT(onScanClicked()));
QWidget* filterButton = mainWindow->findChild<QWidget*>("filterButton");
QObject::connect(filterButton, SIGNAL(clicked()), this, SLOT(onFilterClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onClearClicked())
);
//Add signal
QObject::connect(mainWindow->findChild<QTreeWidget*>("scanTreeWidget"),
SIGNAL(itemChanged(QTreeWidgetItem*, int)),
this,
SLOT(onScanItemChanged(QTreeWidgetItem*, int))
);
QObject::connect(mainWindow->findChild<QPushButton*>("scanAddAll"),
SIGNAL(clicked()),
this,
SLOT(onScanAddAllClicked())
);
QObject:: connect(mainWindow->findChild<QPushButton*>("scanAdd"),
SIGNAL(clicked()),
this,
SLOT(onScanAddClicked())
);
}
bool eventFilter(QObject* obj, QEvent* ev) {
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
if(obj == procTreeWidget && ev->type() == QEvent::KeyRelease) {
if(static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Return) { //Use Return instead of Enter
onProcItemDblClicked(procTreeWidget->currentItem(), 0); //Just use the first column
}
}
}
void addressToScanTreeWidget(Med med, string scanType, QTreeWidget* scanTreeWidget) {
for(int i=0;i<med.scanAddresses.size();i++) {
char address[32];
sprintf(address, "%p", (void*)(med.scanAddresses[i].address));
//Get the value from address and type
string value = med.getScanAddressValueByIndex(i, scanType);
QTreeWidgetItem* item = new QTreeWidgetItem(scanTreeWidget);
item->setText(0, address);
item->setText(2, value.c_str());
item->setFlags(item->flags() | (Qt::ItemIsEditable));
}
//This is how to add combobox to the item
QTreeWidgetItemIterator it(scanTreeWidget);
while(*it) {
QComboBox* combo = createTypeComboBox(scanTreeWidget, scanType);
//Add property to the combobox, so that can be used to select the tree widget's row
// http://stackoverflow.com/questions/30484784/how-to-work-with-signals-from-qtablewidget-cell-with-cellwidget-set
combo->setProperty("tree-row", scanTreeWidget->indexOfTopLevelItem(*it));
scanTreeWidget->setItemWidget(*it, 1, combo);
//Add signal
QObject::connect(combo,
SIGNAL(currentTextChanged(QString)),
this,
SLOT(onScanTypeChanged(QString)));
it++;
}
}
void updateNumberOfAddresses(QWidget* mainWindow) {
char message[128];
sprintf(message, "%ld addresses found", med.scanAddresses.size());
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage(message);
}
void editScanValue(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = item->text(column).toStdString();
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.setValueByAddress(med.scanAddresses[index].address,
text,
med.scanAddresses[index].getScanType());
} catch(string e) {
cerr << "editScanValue: "<<e<<endl;
}
}
void editScanType(QTreeWidgetItem* item, string type) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = type;
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.scanAddresses[index].setScanType(text);
string value2 = med.getValueByAddress(med.scanAddresses[index].address, text);
item->setText(2, value2.c_str());
} catch(string e) {
cerr << "editScanType: "<<e<<endl;
}
}
void editAddressType(QTreeWidgetItem* item, string type) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = type;
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.addresses[index].setScanType(text);
string value2 = med.getValueByAddress(med.addresses[index].address, text);
item->setText(3, value2.c_str());
} catch(string e) {
cerr << "editScanType: "<<e<<endl;
}
}
QComboBox* createTypeComboBox(QTreeWidget* widget, string type) {
QComboBox* combo = new QComboBox(widget);
combo->addItems(QStringList() <<
"int8" <<
"int16" <<
"int32" <<
"float32" <<
"float64");
combo->setCurrentText(type.c_str());
return combo;
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainUi* mainUi = new MainUi();
return app.exec();
}
#include "main-qt.moc"
<commit_msg>Qt update value in address widget; add new address; delete address<commit_after>#include <iostream>
#include <cstdio>
#include <QApplication>
#include <QtUiTools>
#include "med.hpp"
using namespace std;
class MainUi : public QObject {
Q_OBJECT
public:
MainUi() {
loadUiFiles();
}
Med med;
private slots:
void onProcessClicked() {
med.listProcesses();
processDialog->show();
//Get the tree widget
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
procTreeWidget->clear(); //Remove all items
//Add all the process into the tree widget
for(int i=med.processes.size()-1;i>=0;i--) {
QTreeWidgetItem* item = new QTreeWidgetItem(procTreeWidget);
item->setText(0, med.processes[i].pid.c_str());
item->setText(1, med.processes[i].cmdline.c_str());
}
}
void onProcItemDblClicked(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item); //Get the current row index
med.selectedProcess = med.processes[med.processes.size() -1 - index];
//Make changes to the selectedProc and hide the window
QLineEdit* line = this->mainWindow->findChild<QLineEdit*>("selectedProc");
line->setText(QString::fromLatin1((med.selectedProcess.pid + " " + med.selectedProcess.cmdline).c_str())); //Do not use fromStdString(), it will append with some unknown characters
processDialog->hide();
}
void onScanClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
if(med.selectedProcess.pid == "") {
cerr << "No process seelcted " <<endl;
return;
}
try {
med.scanEqual(scanValue, scanType);
} catch(string e) {
cerr << "scan: "<<e<<endl;
}
if(med.scanAddresses.size() <= 800) {
addressToScanTreeWidget(med, scanType, scanTreeWidget);
}
updateNumberOfAddresses(mainWindow);
}
void onFilterClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
scanTreeWidget->clear();
//Get scanned type
string scanType = mainWindow->findChild<QComboBox*>("scanType")->currentText().toStdString();
string scanValue = mainWindow->findChild<QLineEdit*>("scanEntry")->text().toStdString();
med.scanFilter(scanValue, scanType);
if(med.scanAddresses.size() <= 800)
addressToScanTreeWidget(med, scanType, scanTreeWidget);
updateNumberOfAddresses(mainWindow);
}
void onClearClicked() {
mainWindow->findChild<QTreeWidget*>("scanTreeWidget")->clear();
med.scanAddresses.clear();
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage("Scan cleared");
}
void onScanAddClicked() {
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
QTreeWidgetItem* item = scanTreeWidget->currentItem();
int index = scanTreeWidget->indexOfTopLevelItem(item);
//TODO: Write this to a function
MedAddress medAddress;
medAddress.address = med.scanAddresses[index].address;
medAddress.scanType = med.scanAddresses[index].scanType;
med.addresses.push_back(medAddress);
//Add to AddressTreeWidget
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* itemToAdd = new QTreeWidgetItem(addressTreeWidget);
itemToAdd->setText(0, "Your description");
itemToAdd->setText(1, intToHex(medAddress.address).c_str());
itemToAdd->setText(3, med.getAddressValueByIndex(med.addresses.size()-1).c_str());
itemToAdd->setText(4, "false");
itemToAdd->setFlags(itemToAdd->flags() | Qt::ItemIsEditable);
//Add combo box
QComboBox* combo = createTypeComboBox(addressTreeWidget, medAddress.getScanType());
combo->setProperty("tree-row", addressTreeWidget->indexOfTopLevelItem(itemToAdd));
addressTreeWidget->setItemWidget(itemToAdd, 2, combo);
//Add signal
QObject::connect(combo,
SIGNAL(currentTextChanged(QString)),
this,
SLOT(onAddressTypeChanged(QString)));
}
//TODO: Complete this one
void onScanAddAllClicked() {
}
void onScanItemChanged(QTreeWidgetItem* item, int column) {
switch(column) {
case 1: //Not available, because the 2nd column is combobox
break;
case 2:
editScanValue(item, column);
break;
}
}
void onScanTypeChanged(QString text) {
QComboBox* combo = qobject_cast<QComboBox*>(sender());
QTreeWidget* scanTreeWidget = mainWindow->findChild<QTreeWidget*>("scanTreeWidget");
QTreeWidgetItem* item = scanTreeWidget->topLevelItem(combo->property("tree-row").toInt());
scanTreeWidget->setCurrentItem(item);
editScanType(item, text.toStdString());
}
void onAddressTypeChanged(QString text) {
QComboBox* combo = qobject_cast<QComboBox*>(sender());
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* item = addressTreeWidget->topLevelItem(combo->property("tree-row").toInt());
addressTreeWidget->setCurrentItem(item);
editAddressType(item, text.toStdString());
}
void onAddressItemChanged(QTreeWidgetItem* item, int column) {
switch(column) {
case 2: //Not available, because the 2nd column is combobox
break;
case 3:
editAddressValue(item, column);
break;
}
}
void onAddressNewClicked() {
MedAddress medAddress;
medAddress.description = "Your description";
medAddress.address = 0;
medAddress.setScanType("int8");
medAddress.lock = false;
med.addresses.push_back(medAddress);
//Add to AddressTreeWidget
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* itemToAdd = new QTreeWidgetItem(addressTreeWidget); itemToAdd->setText(0, medAddress.description.c_str());
itemToAdd->setText(1, "0");
itemToAdd->setText(4, "false");
itemToAdd->setFlags(itemToAdd->flags() | Qt::ItemIsEditable);
//Add combo box
QComboBox* combo = createTypeComboBox(addressTreeWidget, medAddress.getScanType());
combo->setProperty("tree-row", addressTreeWidget->indexOfTopLevelItem(itemToAdd));
addressTreeWidget->setItemWidget(itemToAdd, 2, combo);
//Add signal
QObject::connect(combo,
SIGNAL(currentTextChanged(QString)),
this,
SLOT(onAddressTypeChanged(QString)));
}
void onAddressDeleteClicked() {
QTreeWidget* addressTreeWidget = mainWindow->findChild<QTreeWidget*>("addressTreeWidget");
QTreeWidgetItem* item = addressTreeWidget->currentItem();
delete item;
}
private:
QWidget* mainWindow;
QWidget* chooseProc;
QDialog* processDialog;
void loadUiFiles() {
QUiLoader loader;
QFile file("./main-qt.ui");
file.open(QFile::ReadOnly);
mainWindow = loader.load(&file);
file.close();
//Cannot put the followings to another method
processDialog = new QDialog(mainWindow); //If put this to another method, then I cannot set the mainWindow as the parent
QFile processFile("./process.ui");
processFile.open(QFile::ReadOnly);
chooseProc = loader.load(&processFile, processDialog);
processFile.close();
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(chooseProc);
processDialog->setLayout(layout);
processDialog->setModal(true);
processDialog->resize(400, 400);
//Statusbar message
QStatusBar* statusBar = mainWindow->findChild<QStatusBar*>("statusbar");
statusBar->showMessage("Tips: Left panel is scanned address. Right panel is stored address.");
//Add signal
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
QObject::connect(procTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(onProcItemDblClicked(QTreeWidgetItem*, int)));
procTreeWidget->installEventFilter(this);
//TODO: center
mainWindow->show();
//Add signal to the process
QWidget* process = mainWindow->findChild<QWidget*>("process");
QObject::connect(process, SIGNAL(clicked()), this, SLOT(onProcessClicked()));
//Add signal to scan
QWidget* scanButton = mainWindow->findChild<QWidget*>("scanButton");
QObject::connect(scanButton, SIGNAL(clicked()), this, SLOT(onScanClicked()));
QWidget* filterButton = mainWindow->findChild<QWidget*>("filterButton");
QObject::connect(filterButton, SIGNAL(clicked()), this, SLOT(onFilterClicked()));
QObject::connect(mainWindow->findChild<QWidget*>("scanClear"),
SIGNAL(clicked()),
this,
SLOT(onClearClicked())
);
//Add signal
QObject::connect(mainWindow->findChild<QTreeWidget*>("scanTreeWidget"),
SIGNAL(itemChanged(QTreeWidgetItem*, int)),
this,
SLOT(onScanItemChanged(QTreeWidgetItem*, int))
);
QObject::connect(mainWindow->findChild<QPushButton*>("scanAddAll"),
SIGNAL(clicked()),
this,
SLOT(onScanAddAllClicked())
);
QObject::connect(mainWindow->findChild<QPushButton*>("scanAdd"),
SIGNAL(clicked()),
this,
SLOT(onScanAddClicked())
);
QObject::connect(mainWindow->findChild<QTreeWidget*>("addressTreeWidget"),
SIGNAL(itemChanged(QTreeWidgetItem*, int)),
this,
SLOT(onAddressItemChanged(QTreeWidgetItem*, int))
);
QObject::connect(mainWindow->findChild<QPushButton*>("addressNew"),
SIGNAL(clicked()),
this,
SLOT(onAddressNewClicked()));
QObject::connect(mainWindow->findChild<QPushButton*>("addressDelete"),
SIGNAL(clicked()),
this,
SLOT(onAddressDeleteClicked()));
}
bool eventFilter(QObject* obj, QEvent* ev) {
QTreeWidget* procTreeWidget = chooseProc->findChild<QTreeWidget*>("procTreeWidget");
if(obj == procTreeWidget && ev->type() == QEvent::KeyRelease) {
if(static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Return) { //Use Return instead of Enter
onProcItemDblClicked(procTreeWidget->currentItem(), 0); //Just use the first column
}
}
}
void addressToScanTreeWidget(Med med, string scanType, QTreeWidget* scanTreeWidget) {
for(int i=0;i<med.scanAddresses.size();i++) {
char address[32];
sprintf(address, "%p", (void*)(med.scanAddresses[i].address));
//Get the value from address and type
string value = med.getScanAddressValueByIndex(i, scanType);
QTreeWidgetItem* item = new QTreeWidgetItem(scanTreeWidget);
item->setText(0, address);
item->setText(2, value.c_str());
item->setFlags(item->flags() | (Qt::ItemIsEditable));
}
//This is how to add combobox to the item
QTreeWidgetItemIterator it(scanTreeWidget);
while(*it) {
QComboBox* combo = createTypeComboBox(scanTreeWidget, scanType);
//Add property to the combobox, so that can be used to select the tree widget's row
// http://stackoverflow.com/questions/30484784/how-to-work-with-signals-from-qtablewidget-cell-with-cellwidget-set
combo->setProperty("tree-row", scanTreeWidget->indexOfTopLevelItem(*it));
scanTreeWidget->setItemWidget(*it, 1, combo);
//Add signal
QObject::connect(combo,
SIGNAL(currentTextChanged(QString)),
this,
SLOT(onScanTypeChanged(QString)));
it++;
}
}
void updateNumberOfAddresses(QWidget* mainWindow) {
char message[128];
sprintf(message, "%ld addresses found", med.scanAddresses.size());
mainWindow->findChild<QStatusBar*>("statusbar")->showMessage(message);
}
void editScanValue(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = item->text(column).toStdString();
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.setValueByAddress(med.scanAddresses[index].address,
text,
med.scanAddresses[index].getScanType());
} catch(string e) {
cerr << "editScanValue: "<<e<<endl;
}
}
//TODO: Combine with editScanValue
void editAddressValue(QTreeWidgetItem* item, int column) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = item->text(column).toStdString();
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.setValueByAddress(med.addresses[index].address,
text,
med.addresses[index].getScanType());
} catch(string e) {
cerr << "editAddressValue: "<<e<<endl;
}
}
void editScanType(QTreeWidgetItem* item, string type) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = type;
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.scanAddresses[index].setScanType(text);
string value2 = med.getValueByAddress(med.scanAddresses[index].address, text);
item->setText(2, value2.c_str());
} catch(string e) {
cerr << "editScanType: "<<e<<endl;
}
}
void editAddressType(QTreeWidgetItem* item, string type) {
int index = item->treeWidget()->indexOfTopLevelItem(item);
string text = type;
if(med.selectedProcess.pid == "") {
cerr<< "No PID" <<endl;
return;
}
try {
med.addresses[index].setScanType(text);
string value2 = med.getValueByAddress(med.addresses[index].address, text);
item->setText(3, value2.c_str());
} catch(string e) {
cerr << "editScanType: "<<e<<endl;
}
}
QComboBox* createTypeComboBox(QTreeWidget* widget, string type) {
QComboBox* combo = new QComboBox(widget);
combo->addItems(QStringList() <<
"int8" <<
"int16" <<
"int32" <<
"float32" <<
"float64");
combo->setCurrentText(type.c_str());
return combo;
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainUi* mainUi = new MainUi();
return app.exec();
}
#include "main-qt.moc"
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: vmware4.cc,v 1.1 2006/12/17 08:17:28 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
/*
* This file provides support for VMWare's virtual disk image
* format version 4 and above.
*
* Author: Sharvil Nanavati
* Contact: snrrrub@gmail.com
*
* Copyright (C) 2006 Sharvil Nanavati.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#define NO_DEVICE_INCLUDES
#include "iodev.h"
#include "hdimage.h"
#include "vmware4.h"
#define LOG_THIS bx_devices.pluginHardDrive->
const off_t vmware4_image_t::INVALID_OFFSET = (off_t)-1;
const int vmware4_image_t::SECTOR_SIZE = 512;
vmware4_image_t::vmware4_image_t()
: file_descriptor(-1),
tlb(0),
tlb_offset(INVALID_OFFSET),
current_offset(INVALID_OFFSET),
is_dirty(false)
{
}
vmware4_image_t::~vmware4_image_t()
{
close();
}
int vmware4_image_t::open(const char * pathname)
{
close();
int flags = O_RDWR;
#ifdef O_BINARY
flags |= O_BINARY;
#endif
file_descriptor = ::open(pathname, flags);
if(!is_open())
return -1;
if(!read_header())
BX_PANIC(("unable to read vmware4 virtual disk header from file '%s'", pathname));
tlb = new Bit8u [header.tlb_size_sectors * SECTOR_SIZE];
if(tlb == 0)
BX_PANIC(("unable to allocate %lld bytes for vmware4 image's tlb", header.tlb_size_sectors * SECTOR_SIZE));
tlb_offset = INVALID_OFFSET;
current_offset = 0;
is_dirty = false;
hd_size = header.total_sectors * SECTOR_SIZE;
cylinders = hd_size / (16 * 63);
heads = 16;
sectors = 63;
BX_DEBUG(("VMware 4 disk geometry:"));
BX_DEBUG((" .size = %lld", hd_size));
BX_DEBUG((" .cylinders = %d", cylinders));
BX_DEBUG((" .heads = %d", heads));
BX_DEBUG((" .sectors = %d", sectors));
return 1;
}
void vmware4_image_t::close()
{
if(file_descriptor == -1)
return;
flush();
delete [] tlb, tlb = 0;
::close(file_descriptor);
file_descriptor = -1;
}
Bit64s vmware4_image_t::lseek(Bit64s offset, int whence)
{
switch(whence)
{
case SEEK_SET:
current_offset = (off_t)offset;
return current_offset;
case SEEK_CUR:
current_offset += (off_t)offset;
return current_offset;
case SEEK_END:
current_offset = header.total_sectors * SECTOR_SIZE + (off_t)offset;
return current_offset;
default:
BX_DEBUG(("unknown 'whence' value (%d) when trying to seek vmware4 image", whence));
return INVALID_OFFSET;
}
}
ssize_t vmware4_image_t::read(void * buf, size_t count)
{
ssize_t total = 0;
while(count > 0)
{
off_t readable = perform_seek();
if(readable == INVALID_OFFSET)
{
BX_DEBUG(("vmware4 disk image read failed on %d bytes at " FMT_LL "d", count, current_offset));
return -1;
}
off_t copysize = (count > readable) ? readable : count;
memcpy(buf, tlb + current_offset - tlb_offset, copysize);
current_offset += copysize;
total += copysize;
count -= copysize;
}
return total;
}
ssize_t vmware4_image_t::write(const void * buf, size_t count)
{
ssize_t total = 0;
while(count > 0)
{
off_t writable = perform_seek();
if(writable == INVALID_OFFSET)
{
BX_DEBUG(("vmware4 disk image write failed on %d bytes at " FMT_LL "d", count, current_offset));
return -1;
}
off_t writesize = (count > writable) ? writable : count;
memcpy(tlb + current_offset - tlb_offset, buf, writesize);
current_offset += writesize;
total += writesize;
count -= writesize;
is_dirty = true;
}
return total;
}
bool vmware4_image_t::is_open() const
{
return (file_descriptor != -1);
}
bool vmware4_image_t::is_valid_header() const
{
if(header.id[0] != 'K' || header.id[1] != 'D' || header.id[2] != 'M' ||
header.id[3] != 'V')
{
BX_DEBUG(("not a vmware4 image"));
return false;
}
if(header.version != 1)
{
BX_DEBUG(("unsupported vmware4 image version"));
return false;
}
return true;
}
bool vmware4_image_t::read_header()
{
if(!is_open())
BX_PANIC(("attempt to read vmware4 header from a closed file"));
if(::read(file_descriptor, &header, sizeof(VM4_Header)) != sizeof(VM4_Header))
return false;
header.version = dtoh32(header.version);
header.flags = dtoh32(header.flags);
header.total_sectors = dtoh64(header.total_sectors);
header.tlb_size_sectors = dtoh64(header.tlb_size_sectors);
header.description_offset_sectors = dtoh64(header.description_offset_sectors);
header.description_size_sectors = dtoh64(header.description_size_sectors);
header.slb_count = dtoh32(header.slb_count);
header.flb_offset_sectors = dtoh64(header.flb_offset_sectors);
header.flb_copy_offset_sectors = dtoh64(header.flb_copy_offset_sectors);
header.tlb_offset_sectors = dtoh64(header.tlb_offset_sectors);
if(!is_valid_header())
BX_PANIC(("invalid vmware4 virtual disk image"));
BX_DEBUG(("VM4_Header (size=%d)", sizeof(VM4_Header)));
BX_DEBUG((" .version = %d", header.version));
BX_DEBUG((" .flags = %d", header.flags));
BX_DEBUG((" .total_sectors = %lld", header.total_sectors));
BX_DEBUG((" .tlb_size_sectors = %lld", header.tlb_size_sectors));
BX_DEBUG((" .description_offset_sectors = %lld", header.description_offset_sectors));
BX_DEBUG((" .description_size_sectors = %lld", header.description_size_sectors));
BX_DEBUG((" .slb_count = %d", header.slb_count));
BX_DEBUG((" .flb_offset_sectors = %lld", header.flb_offset_sectors));
BX_DEBUG((" .flb_copy_offset_sectors = %lld", header.flb_copy_offset_sectors));
BX_DEBUG((" .tlb_offset_sectors = %lld", header.tlb_offset_sectors));
return true;
}
//
// Returns the number of bytes that can be read from the current offset before needing
// to perform another seek.
//
off_t vmware4_image_t::perform_seek()
{
if(current_offset == INVALID_OFFSET)
{
BX_DEBUG(("invalid offset specified in vmware4 seek"));
return INVALID_OFFSET;
}
//
// The currently loaded tlb can service the request.
//
if(tlb_offset / (header.tlb_size_sectors * SECTOR_SIZE) == current_offset / (header.tlb_size_sectors * SECTOR_SIZE))
return (header.tlb_size_sectors * SECTOR_SIZE) - (current_offset - tlb_offset);
flush();
Bit64u index = current_offset / (header.tlb_size_sectors * SECTOR_SIZE);
Bit32u slb_index = (Bit32u)(index % header.slb_count);
Bit32u flb_index = (Bit32u)(index / header.slb_count);
Bit32u slb_sector = read_block_index(header.flb_offset_sectors, flb_index);
Bit32u slb_copy_sector = read_block_index(header.flb_copy_offset_sectors, flb_index);
if(slb_sector == 0 && slb_copy_sector == 0)
{
BX_DEBUG(("loaded vmware4 disk image requires un-implemented feature"));
return INVALID_OFFSET;
}
if(slb_sector == 0)
slb_sector = slb_copy_sector;
Bit32u tlb_sector = read_block_index(slb_sector, slb_index);
tlb_offset = index * header.tlb_size_sectors * SECTOR_SIZE;
if(tlb_sector == 0)
{
//
// Allocate a new tlb
//
memset(tlb, 0, header.tlb_size_sectors * SECTOR_SIZE);
//
// Instead of doing a write to increase the file size, we could use
// ftruncate but it is not portable.
//
off_t eof = ((::lseek(file_descriptor, 0, SEEK_END) + SECTOR_SIZE - 1) / SECTOR_SIZE) * SECTOR_SIZE;
::write(file_descriptor, tlb, header.tlb_size_sectors * SECTOR_SIZE);
tlb_sector = eof / SECTOR_SIZE;
write_block_index(slb_sector, slb_index, tlb_sector);
write_block_index(slb_copy_sector, slb_index, tlb_sector);
::lseek(file_descriptor, eof, SEEK_SET);
}
else
{
::lseek(file_descriptor, tlb_sector * SECTOR_SIZE, SEEK_SET);
::read(file_descriptor, tlb, header.tlb_size_sectors * SECTOR_SIZE);
::lseek(file_descriptor, tlb_sector * SECTOR_SIZE, SEEK_SET);
}
return (header.tlb_size_sectors * SECTOR_SIZE) - (current_offset - tlb_offset);
}
void vmware4_image_t::flush()
{
if(!is_dirty)
return;
//
// Write dirty sectors to disk first. Assume that the file is already at the
// position for the current tlb.
//
::write(file_descriptor, tlb, header.tlb_size_sectors * SECTOR_SIZE);
is_dirty = false;
}
Bit32u vmware4_image_t::read_block_index(Bit64u sector, Bit32u index)
{
Bit32u ret;
::lseek(file_descriptor, sector * SECTOR_SIZE + index * sizeof(Bit32u), SEEK_SET);
::read(file_descriptor, &ret, sizeof(Bit32u));
return dtoh32(ret);
}
void vmware4_image_t::write_block_index(Bit64u sector, Bit32u index, Bit32u block_sector)
{
block_sector = htod32(block_sector);
::lseek(file_descriptor, sector * SECTOR_SIZE + index * sizeof(Bit32u), SEEK_SET);
::write(file_descriptor, &block_sector, sizeof(Bit32u));
}
<commit_msg>- fixed several MSVC warnings<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: vmware4.cc,v 1.2 2006/12/19 16:42:27 vruppert Exp $
/////////////////////////////////////////////////////////////////////////
/*
* This file provides support for VMWare's virtual disk image
* format version 4 and above.
*
* Author: Sharvil Nanavati
* Contact: snrrrub@gmail.com
*
* Copyright (C) 2006 Sharvil Nanavati.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#define NO_DEVICE_INCLUDES
#include "iodev.h"
#include "hdimage.h"
#include "vmware4.h"
#define LOG_THIS bx_devices.pluginHardDrive->
const off_t vmware4_image_t::INVALID_OFFSET = (off_t)-1;
const int vmware4_image_t::SECTOR_SIZE = 512;
vmware4_image_t::vmware4_image_t()
: file_descriptor(-1),
tlb(0),
tlb_offset(INVALID_OFFSET),
current_offset(INVALID_OFFSET),
is_dirty(false)
{
}
vmware4_image_t::~vmware4_image_t()
{
close();
}
int vmware4_image_t::open(const char * pathname)
{
close();
int flags = O_RDWR;
#ifdef O_BINARY
flags |= O_BINARY;
#endif
file_descriptor = ::open(pathname, flags);
if(!is_open())
return -1;
if(!read_header())
BX_PANIC(("unable to read vmware4 virtual disk header from file '%s'", pathname));
tlb = new Bit8u[(unsigned)header.tlb_size_sectors * SECTOR_SIZE];
if(tlb == 0)
BX_PANIC(("unable to allocate %lld bytes for vmware4 image's tlb", header.tlb_size_sectors * SECTOR_SIZE));
tlb_offset = INVALID_OFFSET;
current_offset = 0;
is_dirty = false;
hd_size = header.total_sectors * SECTOR_SIZE;
cylinders = (unsigned)hd_size / (16 * 63);
heads = 16;
sectors = 63;
BX_DEBUG(("VMware 4 disk geometry:"));
BX_DEBUG((" .size = %lld", hd_size));
BX_DEBUG((" .cylinders = %d", cylinders));
BX_DEBUG((" .heads = %d", heads));
BX_DEBUG((" .sectors = %d", sectors));
return 1;
}
void vmware4_image_t::close()
{
if(file_descriptor == -1)
return;
flush();
delete [] tlb, tlb = 0;
::close(file_descriptor);
file_descriptor = -1;
}
Bit64s vmware4_image_t::lseek(Bit64s offset, int whence)
{
switch(whence)
{
case SEEK_SET:
current_offset = (off_t)offset;
return current_offset;
case SEEK_CUR:
current_offset += (off_t)offset;
return current_offset;
case SEEK_END:
current_offset = header.total_sectors * SECTOR_SIZE + (off_t)offset;
return current_offset;
default:
BX_DEBUG(("unknown 'whence' value (%d) when trying to seek vmware4 image", whence));
return INVALID_OFFSET;
}
}
ssize_t vmware4_image_t::read(void * buf, size_t count)
{
ssize_t total = 0;
while(count > 0)
{
off_t readable = perform_seek();
if(readable == INVALID_OFFSET)
{
BX_DEBUG(("vmware4 disk image read failed on %d bytes at " FMT_LL "d", count, current_offset));
return -1;
}
off_t copysize = (count > readable) ? readable : count;
memcpy(buf, tlb + current_offset - tlb_offset, (size_t)copysize);
current_offset += copysize;
total += (long)copysize;
count -= (size_t)copysize;
}
return total;
}
ssize_t vmware4_image_t::write(const void * buf, size_t count)
{
ssize_t total = 0;
while(count > 0)
{
off_t writable = perform_seek();
if(writable == INVALID_OFFSET)
{
BX_DEBUG(("vmware4 disk image write failed on %d bytes at " FMT_LL "d", count, current_offset));
return -1;
}
off_t writesize = (count > writable) ? writable : count;
memcpy(tlb + current_offset - tlb_offset, buf, (size_t)writesize);
current_offset += writesize;
total += (long)writesize;
count -= (size_t)writesize;
is_dirty = true;
}
return total;
}
bool vmware4_image_t::is_open() const
{
return (file_descriptor != -1);
}
bool vmware4_image_t::is_valid_header() const
{
if(header.id[0] != 'K' || header.id[1] != 'D' || header.id[2] != 'M' ||
header.id[3] != 'V')
{
BX_DEBUG(("not a vmware4 image"));
return false;
}
if(header.version != 1)
{
BX_DEBUG(("unsupported vmware4 image version"));
return false;
}
return true;
}
bool vmware4_image_t::read_header()
{
if(!is_open())
BX_PANIC(("attempt to read vmware4 header from a closed file"));
if(::read(file_descriptor, &header, sizeof(VM4_Header)) != sizeof(VM4_Header))
return false;
header.version = dtoh32(header.version);
header.flags = dtoh32(header.flags);
header.total_sectors = dtoh64(header.total_sectors);
header.tlb_size_sectors = dtoh64(header.tlb_size_sectors);
header.description_offset_sectors = dtoh64(header.description_offset_sectors);
header.description_size_sectors = dtoh64(header.description_size_sectors);
header.slb_count = dtoh32(header.slb_count);
header.flb_offset_sectors = dtoh64(header.flb_offset_sectors);
header.flb_copy_offset_sectors = dtoh64(header.flb_copy_offset_sectors);
header.tlb_offset_sectors = dtoh64(header.tlb_offset_sectors);
if(!is_valid_header())
BX_PANIC(("invalid vmware4 virtual disk image"));
BX_DEBUG(("VM4_Header (size=%d)", sizeof(VM4_Header)));
BX_DEBUG((" .version = %d", header.version));
BX_DEBUG((" .flags = %d", header.flags));
BX_DEBUG((" .total_sectors = %lld", header.total_sectors));
BX_DEBUG((" .tlb_size_sectors = %lld", header.tlb_size_sectors));
BX_DEBUG((" .description_offset_sectors = %lld", header.description_offset_sectors));
BX_DEBUG((" .description_size_sectors = %lld", header.description_size_sectors));
BX_DEBUG((" .slb_count = %d", header.slb_count));
BX_DEBUG((" .flb_offset_sectors = %lld", header.flb_offset_sectors));
BX_DEBUG((" .flb_copy_offset_sectors = %lld", header.flb_copy_offset_sectors));
BX_DEBUG((" .tlb_offset_sectors = %lld", header.tlb_offset_sectors));
return true;
}
//
// Returns the number of bytes that can be read from the current offset before needing
// to perform another seek.
//
off_t vmware4_image_t::perform_seek()
{
if(current_offset == INVALID_OFFSET)
{
BX_DEBUG(("invalid offset specified in vmware4 seek"));
return INVALID_OFFSET;
}
//
// The currently loaded tlb can service the request.
//
if(tlb_offset / (header.tlb_size_sectors * SECTOR_SIZE) == current_offset / (header.tlb_size_sectors * SECTOR_SIZE))
return (header.tlb_size_sectors * SECTOR_SIZE) - (current_offset - tlb_offset);
flush();
Bit64u index = current_offset / (header.tlb_size_sectors * SECTOR_SIZE);
Bit32u slb_index = (Bit32u)(index % header.slb_count);
Bit32u flb_index = (Bit32u)(index / header.slb_count);
Bit32u slb_sector = read_block_index(header.flb_offset_sectors, flb_index);
Bit32u slb_copy_sector = read_block_index(header.flb_copy_offset_sectors, flb_index);
if(slb_sector == 0 && slb_copy_sector == 0)
{
BX_DEBUG(("loaded vmware4 disk image requires un-implemented feature"));
return INVALID_OFFSET;
}
if(slb_sector == 0)
slb_sector = slb_copy_sector;
Bit32u tlb_sector = read_block_index(slb_sector, slb_index);
tlb_offset = index * header.tlb_size_sectors * SECTOR_SIZE;
if(tlb_sector == 0)
{
//
// Allocate a new tlb
//
memset(tlb, 0, (size_t)header.tlb_size_sectors * SECTOR_SIZE);
//
// Instead of doing a write to increase the file size, we could use
// ftruncate but it is not portable.
//
off_t eof = ((::lseek(file_descriptor, 0, SEEK_END) + SECTOR_SIZE - 1) / SECTOR_SIZE) * SECTOR_SIZE;
::write(file_descriptor, tlb, (unsigned)header.tlb_size_sectors * SECTOR_SIZE);
tlb_sector = (Bit32u)eof / SECTOR_SIZE;
write_block_index(slb_sector, slb_index, tlb_sector);
write_block_index(slb_copy_sector, slb_index, tlb_sector);
::lseek(file_descriptor, eof, SEEK_SET);
}
else
{
::lseek(file_descriptor, tlb_sector * SECTOR_SIZE, SEEK_SET);
::read(file_descriptor, tlb, (unsigned)header.tlb_size_sectors * SECTOR_SIZE);
::lseek(file_descriptor, tlb_sector * SECTOR_SIZE, SEEK_SET);
}
return (header.tlb_size_sectors * SECTOR_SIZE) - (current_offset - tlb_offset);
}
void vmware4_image_t::flush()
{
if(!is_dirty)
return;
//
// Write dirty sectors to disk first. Assume that the file is already at the
// position for the current tlb.
//
::write(file_descriptor, tlb, (unsigned)header.tlb_size_sectors * SECTOR_SIZE);
is_dirty = false;
}
Bit32u vmware4_image_t::read_block_index(Bit64u sector, Bit32u index)
{
Bit32u ret;
::lseek(file_descriptor, sector * SECTOR_SIZE + index * sizeof(Bit32u), SEEK_SET);
::read(file_descriptor, &ret, sizeof(Bit32u));
return dtoh32(ret);
}
void vmware4_image_t::write_block_index(Bit64u sector, Bit32u index, Bit32u block_sector)
{
block_sector = htod32(block_sector);
::lseek(file_descriptor, sector * SECTOR_SIZE + index * sizeof(Bit32u), SEEK_SET);
::write(file_descriptor, &block_sector, sizeof(Bit32u));
}
<|endoftext|>
|
<commit_before>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 03/05/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../AppleII/Target.hpp"
#include "../Oric/Target.hpp"
#include "../Disassembler/6502.hpp"
#include "../Disassembler/AddressMapper.hpp"
#include "../../../Storage/Disk/Track/TrackSerialiser.hpp"
#include "../../../Storage/Disk/Encodings/AppleGCR/SegmentParser.hpp"
namespace {
Analyser::Static::Target *AppleTarget(const Storage::Encodings::AppleGCR::Sector *sector_zero) {
using Target = Analyser::Static::AppleII::Target;
auto *target = new Target;
target->machine = Analyser::Machine::AppleII;
if(sector_zero && sector_zero->encoding == Storage::Encodings::AppleGCR::Sector::Encoding::FiveAndThree) {
target->disk_controller = Target::DiskController::ThirteenSector;
} else {
target->disk_controller = Target::DiskController::SixteenSector;
}
return target;
}
Analyser::Static::Target *OricTarget(const Storage::Encodings::AppleGCR::Sector *sector_zero) {
using Target = Analyser::Static::Oric::Target;
auto *target = new Target;
target->machine = Analyser::Machine::Oric;
// TODO: configure the Oric as a Pravetz 8D with 8DOS.
return target;
}
}
Analyser::Static::TargetList Analyser::Static::DiskII::GetTargets(const Media &media, const std::string &file_name, TargetPlatform::IntType potential_platforms) {
// This analyser can comprehend disks only.
if(media.disks.empty()) return {};
// Grab track 0, sector 0: the boot sector.
auto track_zero = media.disks.front()->get_track_at_position(Storage::Disk::Track::Address(0, 0));
auto sector_map = Storage::Encodings::AppleGCR::sectors_from_segment(
Storage::Disk::track_serialisation(*track_zero, Storage::Time(1, 50000)));
const Storage::Encodings::AppleGCR::Sector *sector_zero = nullptr;
for(const auto &pair: sector_map) {
if(!pair.second.address.sector) {
sector_zero = &pair.second;
break;
}
}
// If there's no boot sector then if there are also no sectors at all,
// decline to nominate a machine. Otherwise go with an Apple as the default.
TargetList targets;
if(!sector_zero) {
if(sector_map.empty()) {
return targets;
} else {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(AppleTarget(nullptr)));
return targets;
}
}
// If the boot sector looks like it's intended for the Oric, create an Oric.
// Otherwise go with the Apple II.
auto disassembly = Analyser::Static::MOS6502::Disassemble(sector_zero->data, Analyser::Static::Disassembler::OffsetMapper(0xb800), {0xb800});
bool did_read_shift_register = false;
bool is_oric = false;
// Look for a tight BPL loop reading the Oric's shift register address of 0x31c. The Apple II just has RAM there,
// so the probability of such a loop is infinitesimal.
for(const auto &instruction: disassembly.instructions_by_address) {
// Is this a read of the shift register?
if(
(
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDA) ||
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDX) ||
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDY)
) &&
instruction.second.addressing_mode == Analyser::Static::MOS6502::Instruction::Absolute &&
instruction.second.address == 0x031c) {
did_read_shift_register = true;
continue;
}
if(did_read_shift_register) {
if(
instruction.second.operation == Analyser::Static::MOS6502::Instruction::BPL &&
instruction.second.address == 0xfb) {
is_oric = true;
break;
}
did_read_shift_register = false;
}
}
// Check also for calls into the 0x3xx page above 0x320, as that's where the Oric's boot ROM is.
for(const auto address: disassembly.outward_calls) {
is_oric |= address >= 0x320 && address < 0x400;
}
if(is_oric) {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(OricTarget(sector_zero)));
} else {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(AppleTarget(sector_zero)));
}
return targets;
}
<commit_msg>Ensures media is passed on from the Disk II analyser.<commit_after>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 03/05/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../AppleII/Target.hpp"
#include "../Oric/Target.hpp"
#include "../Disassembler/6502.hpp"
#include "../Disassembler/AddressMapper.hpp"
#include "../../../Storage/Disk/Track/TrackSerialiser.hpp"
#include "../../../Storage/Disk/Encodings/AppleGCR/SegmentParser.hpp"
namespace {
Analyser::Static::Target *AppleTarget(const Storage::Encodings::AppleGCR::Sector *sector_zero) {
using Target = Analyser::Static::AppleII::Target;
auto *target = new Target;
target->machine = Analyser::Machine::AppleII;
if(sector_zero && sector_zero->encoding == Storage::Encodings::AppleGCR::Sector::Encoding::FiveAndThree) {
target->disk_controller = Target::DiskController::ThirteenSector;
} else {
target->disk_controller = Target::DiskController::SixteenSector;
}
return target;
}
Analyser::Static::Target *OricTarget(const Storage::Encodings::AppleGCR::Sector *sector_zero) {
using Target = Analyser::Static::Oric::Target;
auto *target = new Target;
target->machine = Analyser::Machine::Oric;
// TODO: configure the Oric as a Pravetz 8D with 8DOS.
return target;
}
}
Analyser::Static::TargetList Analyser::Static::DiskII::GetTargets(const Media &media, const std::string &file_name, TargetPlatform::IntType potential_platforms) {
// This analyser can comprehend disks only.
if(media.disks.empty()) return {};
// Grab track 0, sector 0: the boot sector.
auto track_zero = media.disks.front()->get_track_at_position(Storage::Disk::Track::Address(0, 0));
auto sector_map = Storage::Encodings::AppleGCR::sectors_from_segment(
Storage::Disk::track_serialisation(*track_zero, Storage::Time(1, 50000)));
const Storage::Encodings::AppleGCR::Sector *sector_zero = nullptr;
for(const auto &pair: sector_map) {
if(!pair.second.address.sector) {
sector_zero = &pair.second;
break;
}
}
// If there's no boot sector then if there are also no sectors at all,
// decline to nominate a machine. Otherwise go with an Apple as the default.
TargetList targets;
if(!sector_zero) {
if(sector_map.empty()) {
return targets;
} else {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(AppleTarget(nullptr)));
targets.back()->media = media;
return targets;
}
}
// If the boot sector looks like it's intended for the Oric, create an Oric.
// Otherwise go with the Apple II.
auto disassembly = Analyser::Static::MOS6502::Disassemble(sector_zero->data, Analyser::Static::Disassembler::OffsetMapper(0xb800), {0xb800});
bool did_read_shift_register = false;
bool is_oric = false;
// Look for a tight BPL loop reading the Oric's shift register address of 0x31c. The Apple II just has RAM there,
// so the probability of such a loop is infinitesimal.
for(const auto &instruction: disassembly.instructions_by_address) {
// Is this a read of the shift register?
if(
(
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDA) ||
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDX) ||
(instruction.second.operation == Analyser::Static::MOS6502::Instruction::LDY)
) &&
instruction.second.addressing_mode == Analyser::Static::MOS6502::Instruction::Absolute &&
instruction.second.address == 0x031c) {
did_read_shift_register = true;
continue;
}
if(did_read_shift_register) {
if(
instruction.second.operation == Analyser::Static::MOS6502::Instruction::BPL &&
instruction.second.address == 0xfb) {
is_oric = true;
break;
}
did_read_shift_register = false;
}
}
// Check also for calls into the 0x3xx page above 0x320, as that's where the Oric's boot ROM is.
for(const auto address: disassembly.outward_calls) {
is_oric |= address >= 0x320 && address < 0x400;
}
if(is_oric) {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(OricTarget(sector_zero)));
} else {
targets.push_back(std::unique_ptr<Analyser::Static::Target>(AppleTarget(sector_zero)));
}
targets.back()->media = media;
return targets;
}
<|endoftext|>
|
<commit_before>#include "natives.hpp"
#include "LogManager.hpp"
#include "PluginLog.hpp"
#include <fmt/format.h>
// native Logger:CreateLog(const name[], bool:debuginfo = true);
AMX_DECLARE_NATIVE(Native::CreateLog)
{
ScopedDebugInfo dbg_info(amx, "CreateLog", params, "sd");
const char *name = nullptr;
amx_StrParam(amx, params[1], name);
if (name == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid logger name");
return 0;
}
auto ret_val = static_cast<cell>(LogManager::Get()->Create(name, params[2] != 0));
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native DestroyLog(Logger:logger);
AMX_DECLARE_NATIVE(Native::DestroyLog)
{
ScopedDebugInfo dbg_info(amx, "DestroyLog", params, "d");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
cell ret_val = LogManager::Get()->Destroy(logid) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native bool:IsLogLevel(Logger:logger, E_LOGLEVEL:level);
AMX_DECLARE_NATIVE(Native::IsLogLevel)
{
ScopedDebugInfo dbg_info(amx, "IsLogLevel", params, "dd");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
cell ret_val = LogManager::Get()->GetLogger(logid).
IsLogLevel(static_cast<samplog::LogLevel>(params[2])) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native Log(Logger:logger, E_LOGLEVEL:level, const msg[], {Float,_}:...);
AMX_DECLARE_NATIVE(Native::Log)
{
ScopedDebugInfo dbg_info(amx, "Log", params, "dds");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
auto &logger = LogManager::Get()->GetLogger(logid);
const samplog::LogLevel loglevel = static_cast<decltype(loglevel)>(params[2]);
if (!logger.IsLogLevel(loglevel))
{
PluginLog::Get()->LogNative(LogLevel::DEBUG,
"log level not set, not logging message");
return 0;
}
std::string format_str = amx_GetCppString(amx, params[3]);
const unsigned int
first_param_idx = 4,
num_args = (params[0] / sizeof(cell)),
num_dyn_args = num_args - (first_param_idx - 1);
unsigned int param_counter = 0;
fmt::memory_buffer str_writer;
size_t
spec_pos = std::string::npos,
spec_offset = 0;
while ((spec_pos = format_str.find('%', spec_offset)) != std::string::npos)
{
if (spec_pos == (format_str.length() - 1))
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"invalid specifier at string end");
return 0;
}
fmt::format_to(str_writer, "{:s}",
format_str.substr(spec_offset, spec_pos - spec_offset));
spec_offset = spec_pos + 2; // 2 = '%' + char specifier (like 'd' or 's')
const char format_spec = format_str.at(spec_pos + 1);
if (format_spec == '%')
{
str_writer.push_back('%');
continue;
}
if (param_counter >= num_dyn_args)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"format specifier at position {} has no argument passed", spec_pos);
return 0;
}
cell
*param_addr = nullptr,
¶m = params[first_param_idx + param_counter++];
switch (format_spec)
{
case 's': // string
fmt::format_to(str_writer, "{:s}", amx_GetCppString(amx, param));
break;
case 'd': // decimal
case 'i': // integer
if (amx_GetAddr(amx, param, ¶m_addr) != AMX_ERR_NONE || param_addr == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"error while retrieving AMX address");
return 0;
}
fmt::format_to(str_writer, "{:d}", static_cast<int>(*param_addr));
break;
case 'f': // float
if (amx_GetAddr(amx, param, ¶m_addr) != AMX_ERR_NONE || param_addr == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"error while retrieving AMX address");
return 0;
}
fmt::format_to(str_writer, "{:f}", amx_ctof(*param_addr));
break;
default:
PluginLog::Get()->LogNative(LogLevel::ERROR,
"invalid format specifier '%{:c}'", format_spec); // TODO test "c"
return 0;
}
}
// copy rest of format string
fmt::format_to(str_writer, "{:s}", format_str.substr(spec_offset));
cell ret_val = logger.Log(loglevel, fmt::to_string(str_writer), amx) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
<commit_msg>add more format specifiers<commit_after>#include "natives.hpp"
#include "LogManager.hpp"
#include "PluginLog.hpp"
#include <fmt/format.h>
// native Logger:CreateLog(const name[], bool:debuginfo = true);
AMX_DECLARE_NATIVE(Native::CreateLog)
{
ScopedDebugInfo dbg_info(amx, "CreateLog", params, "sd");
const char *name = nullptr;
amx_StrParam(amx, params[1], name);
if (name == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid logger name");
return 0;
}
auto ret_val = static_cast<cell>(LogManager::Get()->Create(name, params[2] != 0));
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native DestroyLog(Logger:logger);
AMX_DECLARE_NATIVE(Native::DestroyLog)
{
ScopedDebugInfo dbg_info(amx, "DestroyLog", params, "d");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
cell ret_val = LogManager::Get()->Destroy(logid) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native bool:IsLogLevel(Logger:logger, E_LOGLEVEL:level);
AMX_DECLARE_NATIVE(Native::IsLogLevel)
{
ScopedDebugInfo dbg_info(amx, "IsLogLevel", params, "dd");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
cell ret_val = LogManager::Get()->GetLogger(logid).
IsLogLevel(static_cast<samplog::LogLevel>(params[2])) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
// native Log(Logger:logger, E_LOGLEVEL:level, const msg[], {Float,_}:...);
AMX_DECLARE_NATIVE(Native::Log)
{
ScopedDebugInfo dbg_info(amx, "Log", params, "dds");
const Logger::Id logid = params[1];
if (LogManager::Get()->IsValid(logid) == false)
{
PluginLog::Get()->LogNative(LogLevel::ERROR, "invalid log id '{}'", logid);
return 0;
}
auto &logger = LogManager::Get()->GetLogger(logid);
const samplog::LogLevel loglevel = static_cast<decltype(loglevel)>(params[2]);
if (!logger.IsLogLevel(loglevel))
{
PluginLog::Get()->LogNative(LogLevel::DEBUG,
"log level not set, not logging message");
return 0;
}
std::string format_str = amx_GetCppString(amx, params[3]);
const unsigned int
first_param_idx = 4,
num_args = (params[0] / sizeof(cell)),
num_dyn_args = num_args - (first_param_idx - 1);
unsigned int param_counter = 0;
fmt::memory_buffer str_writer;
size_t
spec_pos = std::string::npos,
spec_offset = 0;
while ((spec_pos = format_str.find('%', spec_offset)) != std::string::npos)
{
if (spec_pos == (format_str.length() - 1))
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"invalid specifier at string end");
return 0;
}
fmt::format_to(str_writer, "{:s}",
format_str.substr(spec_offset, spec_pos - spec_offset));
spec_offset = spec_pos + 2; // 2 = '%' + char specifier (like 'd' or 's')
const char format_spec = format_str.at(spec_pos + 1);
if (format_spec == '%')
{
str_writer.push_back('%');
continue;
}
if (param_counter >= num_dyn_args)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"format specifier at position {} has no argument passed", spec_pos);
return 0;
}
cell
*param_addr = nullptr,
¶m = params[first_param_idx + param_counter++];
auto fmt_str = fmt::format("{{:{:c}}}", format_spec == 'i' ? 'd' : format_spec);
switch (format_spec)
{
case 's': // string
fmt::format_to(str_writer, fmt_str, amx_GetCppString(amx, param));
break;
case 'd': // decimal
case 'i': // custom decimal alias
case 'o': // octal
case 'x': // hex lowercase
case 'X': // hex uppercase
case 'b': // binary
if (amx_GetAddr(amx, param, ¶m_addr) != AMX_ERR_NONE || param_addr == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"error while retrieving AMX address");
return 0;
}
fmt::format_to(str_writer, fmt_str, static_cast<int>(*param_addr));
break;
case 'f': // float
case 'F': // float with uppercase 'NAN' and 'INF'
case 'e': // exponent notation
case 'E': // exponent notation (uppercase 'E')
case 'g': // general format (combination of 'f' and 'e')
case 'G': // general format (uppercase)
if (amx_GetAddr(amx, param, ¶m_addr) != AMX_ERR_NONE || param_addr == nullptr)
{
PluginLog::Get()->LogNative(LogLevel::ERROR,
"error while retrieving AMX address");
return 0;
}
fmt::format_to(str_writer, fmt_str, amx_ctof(*param_addr));
break;
default:
PluginLog::Get()->LogNative(LogLevel::ERROR,
"invalid format specifier '%{:c}'", format_spec);
return 0;
}
}
// copy rest of format string
fmt::format_to(str_writer, "{:s}", format_str.substr(spec_offset));
cell ret_val = logger.Log(loglevel, fmt::to_string(str_writer), amx) ? 1 : 0;
PluginLog::Get()->LogNative(LogLevel::DEBUG, "return value: '{}'", ret_val);
return ret_val;
}
<|endoftext|>
|
<commit_before>#define DEBUG // Allow debugging
#define DEBUG2 // Allow debug lvl 2
#include <os>
#include <net/ip4.hpp>
#include <net/ip4/packet_ip4.hpp>
#include <net/packet.hpp>
using namespace net;
int IP4::bottom(Packet_ptr pckt){
debug2("<IP4 handler> got the data. \n");
const uint8_t* data = pckt->buffer();
ip_header* hdr = &((full_header*)data)->ip_hdr;
debug2("\t Source IP: %s Dest.IP: %s type: ",
hdr->saddr.str().c_str(), hdr->daddr.str().c_str() );
switch(hdr->protocol){
case IP4_ICMP:
debug2("\t ICMP \n");
icmp_handler_(pckt);
break;
case IP4_UDP:
debug2("\t UDP \n");
udp_handler_(pckt);
break;
case IP4_TCP:
tcp_handler_(pckt);
debug2("\t TCP \n");
break;
default:
debug("\t UNKNOWN %i \n", hdr->protocol);
break;
}
return -1;
};
uint16_t IP4::checksum(ip_header* hdr)
{
return net::checksum((uint16_t*) hdr, sizeof(ip_header));
}
int IP4::transmit(Packet_ptr pckt)
{
//DEBUG Issue #102 :
// Now _local_ip fails first, while _netmask fails if we remove local ip
assert(pckt->size() > sizeof(IP4::full_header));
full_header* full_hdr = (full_header*) pckt->buffer();
ip_header* hdr = &full_hdr->ip_hdr;
/*
hdr->version_ihl = 0x45; // IPv.4, Size 5 x 32-bit
hdr->tos = 0; // Unused
hdr->tot_len = __builtin_bswap16(pckt->size() - sizeof(Ethernet::header));
hdr->id = 0; // Fragment ID (we don't fragment yet)
hdr->frag_off_flags = 0x40; // "No fragment" flag set, nothing else
hdr->ttl = 64; // What Linux / netcat does
// Checksum is 0 while calculating
hdr->check = 0;
hdr->check = checksum(hdr);
// Make sure it's right
//assert(checksum(hdr) == 0);
// Calculate next-hop
//assert(pckt->next_hop().whole == 0);
// Set destination address to "my ip"
// @TODO Don't know if this is good for routing...
hdr->saddr.whole = local_ip_.whole;
//ASSERT(! hdr->saddr.whole)
std::shared_ptr<PacketIP4> p4 =
std::static_pointer_cast<PacketIP4> (pckt);
debug2("<IP4 TOP> Dest: %s, Source: %s\n",
p4->dst().str().c_str(),
p4->src().str().c_str());
*/
// create local and target subnets
addr target, local;
target.whole = hdr->daddr.whole & netmask_.whole;
local.whole = local_ip_.whole & netmask_.whole;
// compare subnets to know where to send packet
pckt->next_hop(target == local ? hdr->daddr : gateway_);
debug2("<IP4 TOP> Next hop for %s, (netmask %s, local IP: %s, gateway: %s) == %s\n",
hdr->daddr.str().c_str(),
netmask_.str().c_str(),
local_ip_.str().c_str(),
gateway_.str().c_str(),
target == local ? "DIRECT" : "GATEWAY");
debug2("<IP4 transmit> my ip: %s, Next hop: %s\n",
local_ip_.str().c_str(),
pckt->next_hop().str().c_str());
return linklayer_out_(pckt);
}
/** Empty handler for delegates initialization */
int net::ignore_ip4_up(std::shared_ptr<Packet> UNUSED(pckt)){
debug("<IP4> Empty handler. Ignoring.\n");
return -1;
}
int net::ignore_ip4_down(std::shared_ptr<Packet> UNUSED(pckt)){
debug("<IP4->Link layer> No handler - DROP!\n");
return 0;
}
IP4::IP4(Inet<LinkLayer, IP4>& inet) :
local_ip_(inet.ip_addr()),
netmask_(inet.netmask())
{
// Default gateway is addr 1 in the subnet.
const uint32_t DEFAULT_GATEWAY = __builtin_bswap32(1);
gateway_.whole = (local_ip_.whole & netmask_.whole) | DEFAULT_GATEWAY;
debug("<IP4> Local IP @ %p, Netmask @ %p \n",
(void*) &local_ip_,
(void*) &netmask_);
}
<commit_msg>Added back IP4 checksumming<commit_after>#define DEBUG // Allow debugging
#define DEBUG2 // Allow debug lvl 2
#include <os>
#include <net/ip4.hpp>
#include <net/ip4/packet_ip4.hpp>
#include <net/packet.hpp>
using namespace net;
int IP4::bottom(Packet_ptr pckt){
debug2("<IP4 handler> got the data. \n");
const uint8_t* data = pckt->buffer();
ip_header* hdr = &((full_header*)data)->ip_hdr;
debug2("\t Source IP: %s Dest.IP: %s type: ",
hdr->saddr.str().c_str(), hdr->daddr.str().c_str() );
switch(hdr->protocol){
case IP4_ICMP:
debug2("\t ICMP \n");
icmp_handler_(pckt);
break;
case IP4_UDP:
debug2("\t UDP \n");
udp_handler_(pckt);
break;
case IP4_TCP:
tcp_handler_(pckt);
debug2("\t TCP \n");
break;
default:
debug("\t UNKNOWN %i \n", hdr->protocol);
break;
}
return -1;
};
uint16_t IP4::checksum(ip_header* hdr)
{
return net::checksum((uint16_t*) hdr, sizeof(ip_header));
}
int IP4::transmit(Packet_ptr pckt)
{
//DEBUG Issue #102 :
// Now _local_ip fails first, while _netmask fails if we remove local ip
assert(pckt->size() > sizeof(IP4::full_header));
full_header* full_hdr = (full_header*) pckt->buffer();
ip_header* hdr = &full_hdr->ip_hdr;
/*
hdr->version_ihl = 0x45; // IPv.4, Size 5 x 32-bit
hdr->tos = 0; // Unused
hdr->tot_len = __builtin_bswap16(pckt->size() - sizeof(Ethernet::header));
hdr->id = 0; // Fragment ID (we don't fragment yet)
hdr->frag_off_flags = 0x40; // "No fragment" flag set, nothing else
hdr->ttl = 64; // What Linux / netcat does
*/
// Checksum is 0 while calculating
hdr->check = 0;
hdr->check = checksum(hdr);
/*
// Make sure it's right
//assert(checksum(hdr) == 0);
// Calculate next-hop
//assert(pckt->next_hop().whole == 0);
// Set destination address to "my ip"
// @TODO Don't know if this is good for routing...
hdr->saddr.whole = local_ip_.whole;
//ASSERT(! hdr->saddr.whole)
std::shared_ptr<PacketIP4> p4 =
std::static_pointer_cast<PacketIP4> (pckt);
debug2("<IP4 TOP> Dest: %s, Source: %s\n",
p4->dst().str().c_str(),
p4->src().str().c_str());
*/
// create local and target subnets
addr target, local;
target.whole = hdr->daddr.whole & netmask_.whole;
local.whole = local_ip_.whole & netmask_.whole;
// compare subnets to know where to send packet
pckt->next_hop(target == local ? hdr->daddr : gateway_);
debug2("<IP4 TOP> Next hop for %s, (netmask %s, local IP: %s, gateway: %s) == %s\n",
hdr->daddr.str().c_str(),
netmask_.str().c_str(),
local_ip_.str().c_str(),
gateway_.str().c_str(),
target == local ? "DIRECT" : "GATEWAY");
debug2("<IP4 transmit> my ip: %s, Next hop: %s\n",
local_ip_.str().c_str(),
pckt->next_hop().str().c_str());
return linklayer_out_(pckt);
}
/** Empty handler for delegates initialization */
int net::ignore_ip4_up(std::shared_ptr<Packet> UNUSED(pckt)){
debug("<IP4> Empty handler. Ignoring.\n");
return -1;
}
int net::ignore_ip4_down(std::shared_ptr<Packet> UNUSED(pckt)){
debug("<IP4->Link layer> No handler - DROP!\n");
return 0;
}
IP4::IP4(Inet<LinkLayer, IP4>& inet) :
local_ip_(inet.ip_addr()),
netmask_(inet.netmask())
{
// Default gateway is addr 1 in the subnet.
const uint32_t DEFAULT_GATEWAY = __builtin_bswap32(1);
gateway_.whole = (local_ip_.whole & netmask_.whole) | DEFAULT_GATEWAY;
debug("<IP4> Local IP @ %p, Netmask @ %p \n",
(void*) &local_ip_,
(void*) &netmask_);
}
<|endoftext|>
|
<commit_before>void readCDB (TObject *task1);
//_____________________________________________________________________________
AliAnalysisTask *AddTaskT0Calib(Int_t runNumber)
{
//
// add calibration task
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskT0Calib", "No analysis manager to connect to.");
return NULL;
}
// check the input handler
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskT0Calib", "This task requires an input event handler");
return NULL;
}
// set TPC OCDB parameters
//ConfigOCDB(runNumber);
// setup task
AliT0CalibOffsetChannelsTask *task1 = new AliT0CalibOffsetChannelsTask("CalibObjectsTrain1");
readCDB(task1, runNumber);
mgr->AddTask(task1);
// AliT0AnalysisTaskQA * task2 = new AliT0AnalysisTaskQA("QA task");
// mgr->AddTask(task2);
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
if (!cinput1) cinput1 = mgr->CreateContainer("cchain",TChain::Class(),
AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("T0Calib",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");
mgr->ConnectInput(task1,0,cinput1);
mgr->ConnectOutput(task1,1,coutput1);
return task1;
}
//_____________________________________________________________________________
void readCDB (TObject *task1, Int_t runNumber) {
Float_t zero_timecdb[24]={0};
Float_t *timecdb = zero_timecdb;
Float_t cfdvalue[24][5];
for(Int_t i=0; i<24; i++)
for (Int_t i0=0; i0<5; i0++)
cfdvalue[i][i0] = 0;
Float_t zero_shiftcdb[4]={0};
Float_t *shiftcdb = zero_shiftcdb;
AliT0CalibOffsetChannelsTask *mytask = (AliT0CalibOffsetChannelsTask*)task1;
AliCDBManager* man = AliCDBManager::Instance();
AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/CTP/CTPtiming");
if (!entry) AliFatal("CTP timing parameters are not found in OCDB !");
AliCTPTimeParams *ctpParams = (AliCTPTimeParams*)entry->GetObject();
Float_t l1Delay = (Float_t)ctpParams->GetDelayL1L0()*25.0;
AliCDBEntry *entry1 = AliCDBManager::Instance()->Get("GRP/CTP/TimeAlign");
if (!entry1) AliFatal("CTP time-alignment is not found in OCDB !");
AliCTPTimeParams *ctpTimeAlign = (AliCTPTimeParams*)entry1->GetObject();
l1Delay += ((Float_t)ctpTimeAlign->GetDelayL1L0()*25.0);
AliCDBEntry *entry4 = AliCDBManager::Instance()->Get("GRP/Calib/LHCClockPhase");
if (!entry4) AliFatal("LHC clock-phase shift is not found in OCDB !");
AliLHCClockPhase *phase = (AliLHCClockPhase*)entry4->GetObject();
Float_t fGRPdelays = l1Delay - phase->GetMeanPhase();
AliCDBEntry* entry5 = AliCDBManager::Instance()->Get("GRP/GRP/Data");
AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry5->GetObject());
if (!grpData) {
::Error("AddTaskT0Calib","Failed to get GRP data for run %d",runNumber);
return;
}
TString LHCperiod = grpData->GetLHCPeriod();
Bool_t isLHC10b = LHCperiod.Contains("LHC10b");
Bool_t isLHC10c = LHCperiod.Contains("LHC10c");
::Info("AddTaskT0Calib","LHCperiod:%s ---> isLHC10b:%d isLHC10c:%d",
LHCperiod.Data(),(Int_t)isLHC10b, (Int_t)isLHC10c);
if(isLHC10b || isLHC10c) mytask-> SetRefPMT(12,2);
AliCDBEntry *entryCalib0 = man->Get("T0/Calib/Latency");
if(!entryCalib0) {
::Error("AddTastT0Calib","Cannot find any AliCDBEntry for [Calib, Latency]!");
return;
}
AliT0CalibLatency *calibda=(AliT0CalibLatency*)entryCalib0->GetObject();
Float_t fLatencyL1 = calibda->GetLatencyL1();
Float_t fLatencyHPTDC = calibda->GetLatencyHPTDC();
AliCDBEntry *entryCalib1 = man->Get("T0/Calib/TimeDelay");
if(!entryCalib1) {
::Error("AddTaskT0Calib","Cannot find any AliCDBEntry for [Calib, TimeDelay]!");
return;
}
else
{
AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entryCalib1->GetObject();
timecdb = clb->GetTimeEq();
for(Int_t i=0; i<24; i++)
for (Int_t i0=0; i0<5; i0++){
cfdvalue[i][i0] = clb->GetCFDvalue(i, i0);
}
}
for (Int_t i=0; i<24; i++) {
Float_t cfdmean = cfdvalue[i][0];
if( cfdvalue[i][0] < 500 || cfdvalue[i][0] > 50000) cfdmean = ( 1000.*fLatencyHPTDC - 1000.*fLatencyL1 + 1000.*fGRPdelays)/24.4;
mytask->SetCFDvalue(i, cfdmean);
mytask->SetTimeEq(i, timecdb[i]);
}
AliCDBEntry *entryCalib2 = man->Get("T0/Calib/TimeAdjust");
if(!entryCalib2) {
::Error("AddTaskT0Calib","Cannot find any AliCDBEntry for [Calib, TimeAdjust]!");
}
else
{
AliT0CalibSeasonTimeShift *clb1 = (AliT0CalibSeasonTimeShift*)entryCalib2->GetObject();
shiftcdb = clb1->GetT0Means();
}
for (Int_t i=0; i<4; i++) mytask->SetT0Means(i,shiftcdb[i]);
}
<commit_msg>Revert "set refrence PMT=2 if LHC10bc"<commit_after>
void readCDB (TObject *task1);
//_____________________________________________________________________________
AliAnalysisTask *AddTaskT0Calib(Int_t runNumber)
{
//
// add calibration task
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskT0Calib", "No analysis manager to connect to.");
return NULL;
}
// check the input handler
if (!mgr->GetInputEventHandler()) {
::Error("AddTaskT0Calib", "This task requires an input event handler");
return NULL;
}
// set TPC OCDB parameters
//ConfigOCDB(runNumber);
// setup task
AliT0CalibOffsetChannelsTask *task1 = new AliT0CalibOffsetChannelsTask("CalibObjectsTrain1");
readCDB(task1, runNumber);
mgr->AddTask(task1);
// AliT0AnalysisTaskQA * task2 = new AliT0AnalysisTaskQA("QA task");
// mgr->AddTask(task2);
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
if (!cinput1) cinput1 = mgr->CreateContainer("cchain",TChain::Class(),
AliAnalysisManager::kInputContainer);
AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("T0Calib",TObjArray::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");
mgr->ConnectInput(task1,0,cinput1);
mgr->ConnectOutput(task1,1,coutput1);
return task1;
}
//_____________________________________________________________________________
void readCDB (TObject *task1, Int_t runNumber) {
Float_t zero_timecdb[24]={0};
Float_t *timecdb = zero_timecdb;
Float_t cfdvalue[24][5];
for(Int_t i=0; i<24; i++)
for (Int_t i0=0; i0<5; i0++)
cfdvalue[i][i0] = 0;
Float_t zero_shiftcdb[4]={0};
Float_t *shiftcdb = zero_shiftcdb;
AliT0CalibOffsetChannelsTask *mytask = (AliT0CalibOffsetChannelsTask*)task1;
AliCDBManager* man = AliCDBManager::Instance();
AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/CTP/CTPtiming");
if (!entry) AliFatal("CTP timing parameters are not found in OCDB !");
AliCTPTimeParams *ctpParams = (AliCTPTimeParams*)entry->GetObject();
Float_t l1Delay = (Float_t)ctpParams->GetDelayL1L0()*25.0;
AliCDBEntry *entry1 = AliCDBManager::Instance()->Get("GRP/CTP/TimeAlign");
if (!entry1) AliFatal("CTP time-alignment is not found in OCDB !");
AliCTPTimeParams *ctpTimeAlign = (AliCTPTimeParams*)entry1->GetObject();
l1Delay += ((Float_t)ctpTimeAlign->GetDelayL1L0()*25.0);
AliCDBEntry *entry4 = AliCDBManager::Instance()->Get("GRP/Calib/LHCClockPhase");
if (!entry4) AliFatal("LHC clock-phase shift is not found in OCDB !");
AliLHCClockPhase *phase = (AliLHCClockPhase*)entry4->GetObject();
Float_t fGRPdelays = l1Delay - phase->GetMeanPhase();
AliCDBEntry* entry5 = AliCDBManager::Instance()->Get("GRP/GRP/Data");
AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry5->GetObject());
if (!grpData) {
::Error("AddTaskT0Calib","Failed to get GRP data for run %d",runNumber);
return;
}
TString LHCperiod = grpData->GetLHCPeriod();
Bool_t isLHC10b = LHCperiod.Contains("LHC10b");
Bool_t isLHC10c = LHCperiod.Contains("LHC10c");
::Info("AddTaskT0Calib","LHCperiod:%s ---> isLHC10b:%d isLHC10c:%d",
LHCperiod.Data(),(Int_t)isLHC10b, (Int_t)isLHC10c);
if(isLHC10b || isLHC10c) mytask-> SetRefPMT(12,2);
AliCDBEntry *entryCalib0 = man->Get("T0/Calib/Latency");
if(!entryCalib0) {
::Error("AddTastT0Calib","Cannot find any AliCDBEntry for [Calib, Latency]!");
return;
}
AliT0CalibLatency *calibda=(AliT0CalibLatency*)entryCalib0->GetObject();
Float_t fLatencyL1 = calibda->GetLatencyL1();
Float_t fLatencyHPTDC = calibda->GetLatencyHPTDC();
AliCDBEntry *entryCalib1 = man->Get("T0/Calib/TimeDelay");
if(!entryCalib1) {
::Error("AddTaskT0Calib","Cannot find any AliCDBEntry for [Calib, TimeDelay]!");
return;
}
else
{
AliT0CalibTimeEq *clb = (AliT0CalibTimeEq*)entryCalib1->GetObject();
timecdb = clb->GetTimeEq();
for(Int_t i=0; i<24; i++)
for (Int_t i0=0; i0<5; i0++){
cfdvalue[i][i0] = clb->GetCFDvalue(i, i0);
}
}
for (Int_t i=0; i<24; i++) {
Float_t cfdmean = cfdvalue[i][0];
if( cfdvalue[i][0] < 500 || cfdvalue[i][0] > 50000) cfdmean = ( 1000.*fLatencyHPTDC - 1000.*fLatencyL1 + 1000.*fGRPdelays)/24.4;
mytask->SetCFDvalue(i, cfdmean);
mytask->SetTimeEq(i, timecdb[i]);
}
AliCDBEntry *entryCalib2 = man->Get("T0/Calib/TimeAdjust");
if(!entryCalib2) {
::Error("AddTaskT0Calib","Cannot find any AliCDBEntry for [Calib, TimeAdjust]!");
}
else
{
AliT0CalibSeasonTimeShift *clb1 = (AliT0CalibSeasonTimeShift*)entryCalib2->GetObject();
shiftcdb = clb1->GetT0Means();
}
for (Int_t i=0; i<4; i++) mytask->SetT0Means(i,shiftcdb[i]);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestAMRBox.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAMRBox.h"
int TestAMRBox(int , char *[])
{
// Equality.
{
vtkAMRBox A(-8,-8,-8,-4,-4,-4);
vtkAMRBox B(-8,-8,-8,-4,-4,-4);
vtkAMRBox C(-8,-8,-8,-1,-1,-1);
vtkAMRBox D;
vtkAMRBox E(-8,-8,-4,-4);
vtkAMRBox F(-8,-8,-4,-4);
vtkAMRBox G(-12,-12,-4,-4);
if ( !(A==A)
|| !(A==B)
|| A==C
|| A==D
|| D==A
|| A==E
|| E==A
|| !(E==E)
|| !(E==F)
|| E==G)
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
E.Print(cerr) << endl;
F.Print(cerr) << endl;
G.Print(cerr) << endl;
cerr << "Failed testing operator===." << endl;
return 1;
}
}
// Coarsen then refine.
{
vtkAMRBox A0(-8,-8,-8,7,7,7);
vtkAMRBox B0(-8,-8,-8,8,8,8); // can't coarsen
vtkAMRBox C(-1,-1,-1,0,0,0);
vtkAMRBox A1(A0);
A1.Coarsen(8); // ==C
vtkAMRBox A2(A1);
A2.Refine(8); // ==A0
vtkAMRBox B1(B0);
B1.Coarsen(8); // ==B0
vtkAMRBox D0(-8,-8,7,7);
vtkAMRBox E0(-8,-8,8,8); // can't coarsen
vtkAMRBox F(-1,-1,0,0);
vtkAMRBox D1(D0);
D1.Coarsen(8); // ==F
vtkAMRBox D2(D1);
D2.Refine(8); // ==D0
vtkAMRBox E1(E0);
E1.Coarsen(8); // ==E0
if ( !(A1==C)
|| !(B1==B0)
|| !(A2==A0)
|| !(D1==F)
|| !(D2==D0)
|| !(E1==E0))
{
A0.Print(cerr) << endl;
B0.Print(cerr) << endl;
C.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
B1.Print(cerr) << endl;
D0.Print(cerr) << endl;
E0.Print(cerr) << endl;
F.Print(cerr) << endl;
D1.Print(cerr) << endl;
D2.Print(cerr) << endl;
E1.Print(cerr) << endl;
cerr << "Failed testing refine coarsened." << endl;
return 1;
}
}
// Refine then coarsen.
{
vtkAMRBox A0(-1,-1,-1,0,0,0);
vtkAMRBox B(-8,-8,-8,7,7,7);
vtkAMRBox A1(A0);
A1.Refine(8); // ==B
vtkAMRBox A2(A1);
A2.Coarsen(8); // ==A0
vtkAMRBox D0(-1,-1,0,0);
vtkAMRBox E(-8,-8,7,7);
vtkAMRBox D1(D0);
D1.Refine(8); // ==E
vtkAMRBox D2(D1);
D2.Coarsen(8); // ==D0
if ( !(A1==B)
|| !(A2==A0)
|| !(D1==E)
|| !(D2==D0))
{
A0.Print(cerr) << endl;
B.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
D0.Print(cerr) << endl;
E.Print(cerr) << endl;
D1.Print(cerr) << endl;
D2.Print(cerr) << endl;
cerr << "Failed testing coarsen refined." << endl;
return 1;
}
}
// Shift.
{
vtkAMRBox A(-2,-2,-2,2,2,2);
vtkAMRBox B(A);
B.Shift(100,0,0);
B.Shift(0,100,0);
B.Shift(0,0,100);
B.Shift(-200,-200,-200);
B.Shift(100,0,0);
B.Shift(0,100,0);
B.Shift(0,0,100); // ==A
vtkAMRBox C(-2,-2,2,2);
vtkAMRBox D(C);
D.Shift(100,0,0);
D.Shift(0,100,0);
D.Shift(0,0,100);
D.Shift(-200,-200,-200);
D.Shift(100,0,0);
D.Shift(0,100,0);
D.Shift(0,0,100); // ==C
if ( !(B==A)
|| !(D==C))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
cerr << "Failed testing shift." << endl;
return 1;
}
}
// Grow/shrink.
{
vtkAMRBox A(-2,-2,-2,2,2,2);
vtkAMRBox B(-4,-4,-4,4,4,4);
vtkAMRBox A1(A);
A1.Grow(2); // ==B
vtkAMRBox A2(A1);
A2.Shrink(2); // ==A
vtkAMRBox C(-2,-2,2,2);
vtkAMRBox D(-4,-4,4,4);
vtkAMRBox C1(C);
C1.Grow(2); // ==D
vtkAMRBox C2(C1);
C2.Shrink(2); // ==C
if ( !(A2==A)
|| !(A1==B)
|| !(C2==C)
|| !(C1==D))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
C1.Print(cerr) << endl;
C2.Print(cerr) << endl;
cerr << "Failed tetsing grow/shrink." << endl;
return 1;
}
}
// Intersect.
{
vtkAMRBox A(-4,-4,-4,4,4,4);
vtkAMRBox B(-4,-4,-4,-1,-1,-1);
vtkAMRBox C(1,1,1,4,4,4);
vtkAMRBox AA(A);
AA&=A; // ==A
vtkAMRBox AB(A);
AB&=B; // ==B
vtkAMRBox BA(B);
BA&=A; // ==B
vtkAMRBox AC(A);
AC&=C; // ==C
vtkAMRBox CA(C);
CA&=A; // ==C
vtkAMRBox BC(B);
BC&=C; // ==NULL
vtkAMRBox CB(C);
CB&=B; // ==NULL
vtkAMRBox D(-4,-4,4,4);
vtkAMRBox E(-4,-4,-1,-1);
vtkAMRBox F(1,1,4,4);
vtkAMRBox DD(D);
DD&=D; // ==D
vtkAMRBox DE(D);
DE&=E; // ==E
vtkAMRBox ED(E);
ED&=D; // ==E
vtkAMRBox DF(D);
DF&=F; // ==F
vtkAMRBox FD(F);
FD&=D; // ==F
vtkAMRBox EF(E);
EF&=F; // ==NULL
vtkAMRBox FE(F);
FE&=E; // ==NULL
vtkAMRBox AD(A);
AD&=D; // ==NULL
vtkAMRBox DA(D);
DA&=A; // ==NULL
if (!(AA==A)
|| !(AB==B) || !(BA==AB)
|| !(AC==C) || !(AC==CA)
|| !BC.Empty() || !CB.Empty()
|| !(DD==D)
|| !(DE==E) || !(DE==ED)
|| !(DF==F) || !(DF==FD)
|| !EF.Empty() || !FE.Empty()
|| !(AD==A)
|| !(DA==D))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
AA.Print(cerr) << endl;
AB.Print(cerr) << endl;
BA.Print(cerr) << endl;
AC.Print(cerr) << endl;
CA.Print(cerr) << endl;
BC.Print(cerr) << endl;
CB.Print(cerr) << endl;
D.Print(cerr) << endl;
E.Print(cerr) << endl;
F.Print(cerr) << endl;
DD.Print(cerr) << endl;
DE.Print(cerr) << endl;
ED.Print(cerr) << endl;
DF.Print(cerr) << endl;
FD.Print(cerr) << endl;
FE.Print(cerr) << endl;
EF.Print(cerr) << endl;
AD.Print(cerr) << endl;
DA.Print(cerr) << endl;
cerr << "Failed testing operator&=." << endl;
return 1;
}
}
// Serialize/Deserialize
{
vtkAMRBox A( 0,0,0, 9,9,9 );
unsigned char *buffer = NULL;
size_t bytesize = 0;
A.Serialize( buffer, bytesize );
if( (buffer == NULL) || (bytesize == 0) )
{
std::cerr << "Failed serializing AMR box." << std::endl;
return 1;
}
size_t expectedByteSize = sizeof( int )+( 6*sizeof(double) );
if( bytesize != expectedByteSize )
{
std::cerr << "Bytesize of buffer did not match expected size.\n";
return 1;
}
vtkAMRBox B;
B.Deserialize( buffer, bytesize );
if( !(A == B) )
{
std::cerr << "Deserialization of AMR box did not match initial box.\n";
return 1;
}
}
return 0;
}
<commit_msg>ENH: Updated Serialization/Deserialization test<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestAMRBox.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkAMRBox.h"
int TestAMRBox(int , char *[])
{
// Equality.
{
vtkAMRBox A(-8,-8,-8,-4,-4,-4);
vtkAMRBox B(-8,-8,-8,-4,-4,-4);
vtkAMRBox C(-8,-8,-8,-1,-1,-1);
vtkAMRBox D;
vtkAMRBox E(-8,-8,-4,-4);
vtkAMRBox F(-8,-8,-4,-4);
vtkAMRBox G(-12,-12,-4,-4);
if ( !(A==A)
|| !(A==B)
|| A==C
|| A==D
|| D==A
|| A==E
|| E==A
|| !(E==E)
|| !(E==F)
|| E==G)
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
E.Print(cerr) << endl;
F.Print(cerr) << endl;
G.Print(cerr) << endl;
cerr << "Failed testing operator===." << endl;
return 1;
}
}
// Coarsen then refine.
{
vtkAMRBox A0(-8,-8,-8,7,7,7);
vtkAMRBox B0(-8,-8,-8,8,8,8); // can't coarsen
vtkAMRBox C(-1,-1,-1,0,0,0);
vtkAMRBox A1(A0);
A1.Coarsen(8); // ==C
vtkAMRBox A2(A1);
A2.Refine(8); // ==A0
vtkAMRBox B1(B0);
B1.Coarsen(8); // ==B0
vtkAMRBox D0(-8,-8,7,7);
vtkAMRBox E0(-8,-8,8,8); // can't coarsen
vtkAMRBox F(-1,-1,0,0);
vtkAMRBox D1(D0);
D1.Coarsen(8); // ==F
vtkAMRBox D2(D1);
D2.Refine(8); // ==D0
vtkAMRBox E1(E0);
E1.Coarsen(8); // ==E0
if ( !(A1==C)
|| !(B1==B0)
|| !(A2==A0)
|| !(D1==F)
|| !(D2==D0)
|| !(E1==E0))
{
A0.Print(cerr) << endl;
B0.Print(cerr) << endl;
C.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
B1.Print(cerr) << endl;
D0.Print(cerr) << endl;
E0.Print(cerr) << endl;
F.Print(cerr) << endl;
D1.Print(cerr) << endl;
D2.Print(cerr) << endl;
E1.Print(cerr) << endl;
cerr << "Failed testing refine coarsened." << endl;
return 1;
}
}
// Refine then coarsen.
{
vtkAMRBox A0(-1,-1,-1,0,0,0);
vtkAMRBox B(-8,-8,-8,7,7,7);
vtkAMRBox A1(A0);
A1.Refine(8); // ==B
vtkAMRBox A2(A1);
A2.Coarsen(8); // ==A0
vtkAMRBox D0(-1,-1,0,0);
vtkAMRBox E(-8,-8,7,7);
vtkAMRBox D1(D0);
D1.Refine(8); // ==E
vtkAMRBox D2(D1);
D2.Coarsen(8); // ==D0
if ( !(A1==B)
|| !(A2==A0)
|| !(D1==E)
|| !(D2==D0))
{
A0.Print(cerr) << endl;
B.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
D0.Print(cerr) << endl;
E.Print(cerr) << endl;
D1.Print(cerr) << endl;
D2.Print(cerr) << endl;
cerr << "Failed testing coarsen refined." << endl;
return 1;
}
}
// Shift.
{
vtkAMRBox A(-2,-2,-2,2,2,2);
vtkAMRBox B(A);
B.Shift(100,0,0);
B.Shift(0,100,0);
B.Shift(0,0,100);
B.Shift(-200,-200,-200);
B.Shift(100,0,0);
B.Shift(0,100,0);
B.Shift(0,0,100); // ==A
vtkAMRBox C(-2,-2,2,2);
vtkAMRBox D(C);
D.Shift(100,0,0);
D.Shift(0,100,0);
D.Shift(0,0,100);
D.Shift(-200,-200,-200);
D.Shift(100,0,0);
D.Shift(0,100,0);
D.Shift(0,0,100); // ==C
if ( !(B==A)
|| !(D==C))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
cerr << "Failed testing shift." << endl;
return 1;
}
}
// Grow/shrink.
{
vtkAMRBox A(-2,-2,-2,2,2,2);
vtkAMRBox B(-4,-4,-4,4,4,4);
vtkAMRBox A1(A);
A1.Grow(2); // ==B
vtkAMRBox A2(A1);
A2.Shrink(2); // ==A
vtkAMRBox C(-2,-2,2,2);
vtkAMRBox D(-4,-4,4,4);
vtkAMRBox C1(C);
C1.Grow(2); // ==D
vtkAMRBox C2(C1);
C2.Shrink(2); // ==C
if ( !(A2==A)
|| !(A1==B)
|| !(C2==C)
|| !(C1==D))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
A1.Print(cerr) << endl;
A2.Print(cerr) << endl;
C.Print(cerr) << endl;
D.Print(cerr) << endl;
C1.Print(cerr) << endl;
C2.Print(cerr) << endl;
cerr << "Failed tetsing grow/shrink." << endl;
return 1;
}
}
// Intersect.
{
vtkAMRBox A(-4,-4,-4,4,4,4);
vtkAMRBox B(-4,-4,-4,-1,-1,-1);
vtkAMRBox C(1,1,1,4,4,4);
vtkAMRBox AA(A);
AA&=A; // ==A
vtkAMRBox AB(A);
AB&=B; // ==B
vtkAMRBox BA(B);
BA&=A; // ==B
vtkAMRBox AC(A);
AC&=C; // ==C
vtkAMRBox CA(C);
CA&=A; // ==C
vtkAMRBox BC(B);
BC&=C; // ==NULL
vtkAMRBox CB(C);
CB&=B; // ==NULL
vtkAMRBox D(-4,-4,4,4);
vtkAMRBox E(-4,-4,-1,-1);
vtkAMRBox F(1,1,4,4);
vtkAMRBox DD(D);
DD&=D; // ==D
vtkAMRBox DE(D);
DE&=E; // ==E
vtkAMRBox ED(E);
ED&=D; // ==E
vtkAMRBox DF(D);
DF&=F; // ==F
vtkAMRBox FD(F);
FD&=D; // ==F
vtkAMRBox EF(E);
EF&=F; // ==NULL
vtkAMRBox FE(F);
FE&=E; // ==NULL
vtkAMRBox AD(A);
AD&=D; // ==NULL
vtkAMRBox DA(D);
DA&=A; // ==NULL
if (!(AA==A)
|| !(AB==B) || !(BA==AB)
|| !(AC==C) || !(AC==CA)
|| !BC.Empty() || !CB.Empty()
|| !(DD==D)
|| !(DE==E) || !(DE==ED)
|| !(DF==F) || !(DF==FD)
|| !EF.Empty() || !FE.Empty()
|| !(AD==A)
|| !(DA==D))
{
A.Print(cerr) << endl;
B.Print(cerr) << endl;
C.Print(cerr) << endl;
AA.Print(cerr) << endl;
AB.Print(cerr) << endl;
BA.Print(cerr) << endl;
AC.Print(cerr) << endl;
CA.Print(cerr) << endl;
BC.Print(cerr) << endl;
CB.Print(cerr) << endl;
D.Print(cerr) << endl;
E.Print(cerr) << endl;
F.Print(cerr) << endl;
DD.Print(cerr) << endl;
DE.Print(cerr) << endl;
ED.Print(cerr) << endl;
DF.Print(cerr) << endl;
FD.Print(cerr) << endl;
FE.Print(cerr) << endl;
EF.Print(cerr) << endl;
AD.Print(cerr) << endl;
DA.Print(cerr) << endl;
cerr << "Failed testing operator&=." << endl;
return 1;
}
}
// Serialize/Deserialize
{
vtkAMRBox A( 0,0,0, 9,9,9 );
unsigned char *buffer = NULL;
size_t bytesize = 0;
A.Serialize( buffer, bytesize );
if( (buffer == NULL) || (bytesize == 0) )
{
std::cerr << "Failed serializing AMR box." << std::endl;
return 1;
}
size_t expectedByteSize = vtkAMRBox::GetBytesize();
if( bytesize != expectedByteSize )
{
std::cerr << "Bytesize of buffer did not match expected size.\n";
return 1;
}
vtkAMRBox B;
B.Deserialize( buffer, bytesize );
if( !(A == B) )
{
std::cerr << "Deserialization of AMR box did not match initial box.\n";
return 1;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>//==============================================================================
// CellML annotation view CellML details widget
//==============================================================================
#include "borderedwidget.h"
#include "cellmlannotationviewcellmldetailswidget.h"
#include "cellmlannotationviewmetadatabiomodelsdotnetviewdetailswidget.h"
#include "cellmlannotationviewwidget.h"
#include "cellmlannotationviewmetadataviewdetailswidget.h"
#include "coreutils.h"
//==============================================================================
#include "ui_cellmlannotationviewcellmldetailswidget.h"
//==============================================================================
#include <QComboBox>
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QWebView>
//==============================================================================
#include <QJsonParser>
//==============================================================================
namespace OpenCOR {
namespace CellMLAnnotationView {
//==============================================================================
CellmlAnnotationViewCellmlDetailsWidget::CellmlAnnotationViewCellmlDetailsWidget(CellmlAnnotationViewWidget *pParent) :
QSplitter(pParent),
CommonWidget(pParent),
mParent(pParent),
mGui(new Ui::CellmlAnnotationViewCellmlDetailsWidget)
{
// Set up the GUI
mGui->setupUi(this);
// Create our details widgets
mCellmlElementDetails = new CellmlAnnotationViewCellmlElementDetailsWidget(pParent);
mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent);
mWebView = new QWebView(pParent);
// A connection to handle the looking up of a resource and a resource id
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(qualifierLookupRequested(const QString &, const bool &)),
this, SLOT(qualifierLookupRequested(const QString &, const bool &)));
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceLookupRequested(const QString &, const bool &)),
this, SLOT(resourceLookupRequested(const QString &, const bool &)));
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceIdLookupRequested(const QString &, const QString &, const bool &)),
this, SLOT(resourceIdLookupRequested(const QString &, const QString &, const bool &)));
// Add our details widgets to our splitter
addWidget(new Core::BorderedWidget(mCellmlElementDetails,
false, true, true, false));
addWidget(new Core::BorderedWidget(mMetadataViewDetails,
true, true, true, false));
addWidget(new Core::BorderedWidget(mWebView,
true, true, false, false));
// Keep track of our splitter being moved
connect(this, SIGNAL(splitterMoved(int,int)),
this, SLOT(emitSplitterMoved()));
// Retrieve the output template
QFile qualifierInformationFile(":qualifierInformation");
qualifierInformationFile.open(QIODevice::ReadOnly);
mQualifierInformationTemplate = QString(qualifierInformationFile.readAll());
qualifierInformationFile.close();
// Retrieve the SVG diagrams
QFile modelQualifierFile(":modelQualifier");
QFile biologyQualifierFile(":biologyQualifier");
modelQualifierFile.open(QIODevice::ReadOnly);
biologyQualifierFile.open(QIODevice::ReadOnly);
mModelQualifierSvg = QString(modelQualifierFile.readAll());
mBiologyQualifierSvg = QString(biologyQualifierFile.readAll());
modelQualifierFile.close();
biologyQualifierFile.close();
}
//==============================================================================
CellmlAnnotationViewCellmlDetailsWidget::~CellmlAnnotationViewCellmlDetailsWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::retranslateUi()
{
// Retranslate our GUI
// Note: we must also update the connection for our cmeta:id widget since it
// gets recreated as a result of the retranslation...
if (mCellmlElementDetails->cmetaIdValue())
disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
mGui->retranslateUi(this);
mCellmlElementDetails->retranslateUi();
mMetadataViewDetails->retranslateUi();
if (mCellmlElementDetails->cmetaIdValue())
connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::updateGui(const CellmlAnnotationViewCellmlElementDetailsWidget::Items &pItems)
{
// Stop tracking changes to the cmeta:id value of our CellML element
if (mCellmlElementDetails->cmetaIdValue())
disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
// 'Clean up' our web view
mWebView->setUrl(QString());
// Update our CellML element details GUI
mCellmlElementDetails->updateGui(pItems);
// Re-track changes to the cmeta:id value of our CellML element and update
// our metadata details GUI
if (mCellmlElementDetails->cmetaIdValue()) {
connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText());
}
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::updateSizes(const QList<int> &pSizes)
{
// The splitter of another CellmlAnnotationViewCellmlDetailsWidget object
// has been moved, so update our sizes
setSizes(pSizes);
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::emitSplitterMoved()
{
// Let whoever know that our splitter has been moved
emit splitterMoved(sizes());
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::newCmetaId(const QString &pCmetaId)
{
// Retrieve the RDF triples for the cmeta:id
CellMLSupport::CellmlFileRdfTriples rdfTriples = pCmetaId.isEmpty()?
CellMLSupport::CellmlFileRdfTriples():
mParent->cellmlFile()->rdfTriples(pCmetaId);
// Check that we are not dealing with the same RDF triples
// Note: this may happen when manually typing the name of a cmeta:id and the
// QComboBox suggesting something for you, e.g. you start typing "C_"
// and the QComboBox suggests "C_C" (which will get us here) and then
// you finish typing "C_C" (which will also get us here)
static CellMLSupport::CellmlFileRdfTriples oldRdfTriples = CellMLSupport::CellmlFileRdfTriples(mParent->cellmlFile());
if (rdfTriples == oldRdfTriples)
return;
oldRdfTriples = rdfTriples;
// 'Clean up' our web view
mWebView->setUrl(QString());
// Update its metadata details
mMetadataViewDetails->updateGui(rdfTriples);
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::qualifierLookupRequested(const QString &pQualifier,
const bool &pRetranslate)
{
Q_UNUSED(pRetranslate);
// The user requested a qualifier to be looked up, so generate a web page
// containing some information about the qualifier
// Note: ideally, there would be a way to refer to a particular qualifier
// using http://biomodels.net/qualifiers/, but that would require
// anchors and they don't have any, so instead we use the information
// which can be found on that site and present it to the user in the
// form of a web page...
if (pQualifier.isEmpty())
return;
// Generate the web page containing some information about the qualifier
QString qualifierSvg;
QString shortDescription;
QString longDescription;
if (!pQualifier.compare("model:is")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Identity");
longDescription = tr("The modelling object represented by the model element is identical with the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link an encoded model to a database of models.");
} else if (!pQualifier.compare("model:isDerivedFrom")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Origin");
longDescription = tr("The modelling object represented by the model element is derived from the modelling object represented by the referenced resource (\"Modelling Object B\"). This relation may be used, for instance, to express a refinement or adaptation in usage for a previously described modelling component.");
} else if (!pQualifier.compare("model:isDescribedBy")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Description");
longDescription = tr("The modelling object represented by the model element is described by the subject of the referenced resource (\"Modelling Object B\"). This relation might be used to link a model or a kinetic law to the literature that describes it.");
} else if (!pQualifier.compare("bio:encodes")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Encodement");
longDescription = tr("The biological entity represented by the model element encodes, directly or transitively, the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a specific DNA sequence encodes a particular protein.");
} else if (!pQualifier.compare("bio:hasPart")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Part");
longDescription = tr("The biological entity represented by the model element includes the subject of the referenced resource (\"Biological Entity B\"), either physically or logically. This relation might be used to link a complex to the description of its components.");
} else if (!pQualifier.compare("bio:hasProperty")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Property");
longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a property of the biological entity represented by the model element. This relation might be used when a biological entity exhibits a certain enzymatic activity or exerts a specific function.");
} else if (!pQualifier.compare("bio:hasVersion")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Version");
longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a version or an instance of the biological entity represented by the model element. This relation may be used to represent an isoform or modified form of a biological entity.");
} else if (!pQualifier.compare("bio:is")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Indentity");
longDescription = tr("The biological entity represented by the model element has identity with the subject of the referenced resource (\"Biological Entity B\"). This relation might be used to link a reaction to its exact counterpart in a database, for instance.");
} else if (!pQualifier.compare("bio:isDescribedBy")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Description");
longDescription = tr("The biological entity represented by the model element is described by the subject of the referenced resource (\"Biological Entity B\"). This relation should be used, for instance, to link a species or a parameter to the literature that describes the concentration of that species or the value of that parameter.");
} else if (!pQualifier.compare("bio:isEncodedBy")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Encoder");
longDescription = tr("The biological entity represented by the model element is encoded, directly or transitively, by the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a protein is encoded by a specific DNA sequence.");
} else if (!pQualifier.compare("bio:isHomologTo")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Homolog");
longDescription = tr("The biological entity represented by the model element is homologous to the subject of the referenced resource (\"Biological Entity B\"). This relation can be used to represent biological entities that share a common ancestor.");
} else if (!pQualifier.compare("bio:isPartOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Parthood");
longDescription = tr("The biological entity represented by the model element is a physical or logical part of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to link a model component to a description of the complex in which it is a part.");
} else if (!pQualifier.compare("bio:isPropertyOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Property bearer");
longDescription = tr("The biological entity represented by the model element is a property of the referenced resource (\"Biological Entity B\").");
} else if (!pQualifier.compare("bio:isVersionOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Hypernym");
longDescription = tr("The biological entity represented by the model element is a version or an instance of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to represent, for example, the 'superclass' or 'parent' form of a particular biological entity.");
} else if (!pQualifier.compare("bio:occursIn")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Container");
longDescription = tr("The biological entity represented by the model element is physically limited to a location, which is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a compartmental location, within which a reaction takes place.");
} else if (!pQualifier.compare("bio:hasTaxon")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Taxon");
longDescription = tr("The biological entity represented by the model element is taxonomically restricted, where the restriction is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a species restriction to a biochemical reaction.");
} else {
qualifierSvg = "";
shortDescription = tr("Unknown");
longDescription = tr("Unknown");
}
// Show the information
mWebView->setHtml(mQualifierInformationTemplate.arg(pQualifier,
qualifierSvg,
shortDescription,
longDescription,
Core::copyright()));
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::resourceLookupRequested(const QString &pResource,
const bool &pRetranslate)
{
// The user requested a resource to be looked up, so retrieve it using
// identifiers.org, but only if we are not retranslating since the looking
// up would already be correct
if (!pRetranslate)
mWebView->setUrl("http://identifiers.org/"+pResource+"/?redirect=true");
//---GRY--- NOTE THAT redirect=true DOESN'T WORK AT THE MOMENT, SO WE DO
// END UP WITH A FRAME, BUT THE identifiers.org GUYS ARE GOING
// TO 'FIX' THAT, SO WE SHOULD BE READY FOR WHEN IT'S DONE...
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::resourceIdLookupRequested(const QString &pResource,
const QString &pId,
const bool &pRetranslate)
{
// The user requested a resource id to be looked up, so retrieve it using
// identifiers.org, but only if we are not retranslating since the looking
// up would already be correct
if (!pRetranslate)
mWebView->setUrl("http://identifiers.org/"+pResource+"/"+pId+"?profile=most_reliable&redirect=true");
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::metadataUpdated()
{
// Some metadata has been updated, so we need to update the metadata
// information we show to the user
if (mCellmlElementDetails->cmetaIdValue())
newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText());
}
//==============================================================================
} // namespace CellMLAnnotationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Display the model-level metadata (i.e. cmeta:id == "") when there is no cmeta:id for a CellML element.<commit_after>//==============================================================================
// CellML annotation view CellML details widget
//==============================================================================
#include "borderedwidget.h"
#include "cellmlannotationviewcellmldetailswidget.h"
#include "cellmlannotationviewmetadatabiomodelsdotnetviewdetailswidget.h"
#include "cellmlannotationviewwidget.h"
#include "cellmlannotationviewmetadataviewdetailswidget.h"
#include "coreutils.h"
//==============================================================================
#include "ui_cellmlannotationviewcellmldetailswidget.h"
//==============================================================================
#include <QComboBox>
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QWebView>
//==============================================================================
#include <QJsonParser>
//==============================================================================
namespace OpenCOR {
namespace CellMLAnnotationView {
//==============================================================================
CellmlAnnotationViewCellmlDetailsWidget::CellmlAnnotationViewCellmlDetailsWidget(CellmlAnnotationViewWidget *pParent) :
QSplitter(pParent),
CommonWidget(pParent),
mParent(pParent),
mGui(new Ui::CellmlAnnotationViewCellmlDetailsWidget)
{
// Set up the GUI
mGui->setupUi(this);
// Create our details widgets
mCellmlElementDetails = new CellmlAnnotationViewCellmlElementDetailsWidget(pParent);
mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent);
mWebView = new QWebView(pParent);
// A connection to handle the looking up of a resource and a resource id
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(qualifierLookupRequested(const QString &, const bool &)),
this, SLOT(qualifierLookupRequested(const QString &, const bool &)));
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceLookupRequested(const QString &, const bool &)),
this, SLOT(resourceLookupRequested(const QString &, const bool &)));
connect(mMetadataViewDetails->bioModelsDotNetView(), SIGNAL(resourceIdLookupRequested(const QString &, const QString &, const bool &)),
this, SLOT(resourceIdLookupRequested(const QString &, const QString &, const bool &)));
// Add our details widgets to our splitter
addWidget(new Core::BorderedWidget(mCellmlElementDetails,
false, true, true, false));
addWidget(new Core::BorderedWidget(mMetadataViewDetails,
true, true, true, false));
addWidget(new Core::BorderedWidget(mWebView,
true, true, false, false));
// Keep track of our splitter being moved
connect(this, SIGNAL(splitterMoved(int,int)),
this, SLOT(emitSplitterMoved()));
// Retrieve the output template
QFile qualifierInformationFile(":qualifierInformation");
qualifierInformationFile.open(QIODevice::ReadOnly);
mQualifierInformationTemplate = QString(qualifierInformationFile.readAll());
qualifierInformationFile.close();
// Retrieve the SVG diagrams
QFile modelQualifierFile(":modelQualifier");
QFile biologyQualifierFile(":biologyQualifier");
modelQualifierFile.open(QIODevice::ReadOnly);
biologyQualifierFile.open(QIODevice::ReadOnly);
mModelQualifierSvg = QString(modelQualifierFile.readAll());
mBiologyQualifierSvg = QString(biologyQualifierFile.readAll());
modelQualifierFile.close();
biologyQualifierFile.close();
}
//==============================================================================
CellmlAnnotationViewCellmlDetailsWidget::~CellmlAnnotationViewCellmlDetailsWidget()
{
// Delete the GUI
delete mGui;
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::retranslateUi()
{
// Retranslate our GUI
// Note: we must also update the connection for our cmeta:id widget since it
// gets recreated as a result of the retranslation...
if (mCellmlElementDetails->cmetaIdValue())
disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
mGui->retranslateUi(this);
mCellmlElementDetails->retranslateUi();
mMetadataViewDetails->retranslateUi();
if (mCellmlElementDetails->cmetaIdValue())
connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::updateGui(const CellmlAnnotationViewCellmlElementDetailsWidget::Items &pItems)
{
// Stop tracking changes to the cmeta:id value of our CellML element
if (mCellmlElementDetails->cmetaIdValue())
disconnect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
// 'Clean up' our web view
mWebView->setUrl(QString());
// Update our CellML element details GUI
mCellmlElementDetails->updateGui(pItems);
// Re-track changes to the cmeta:id value of our CellML element and update
// our metadata details GUI
if (mCellmlElementDetails->cmetaIdValue()) {
connect(mCellmlElementDetails->cmetaIdValue(), SIGNAL(editTextChanged(const QString &)),
this, SLOT(newCmetaId(const QString &)));
newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText());
}
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::updateSizes(const QList<int> &pSizes)
{
// The splitter of another CellmlAnnotationViewCellmlDetailsWidget object
// has been moved, so update our sizes
setSizes(pSizes);
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::emitSplitterMoved()
{
// Let whoever know that our splitter has been moved
emit splitterMoved(sizes());
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::newCmetaId(const QString &pCmetaId)
{
// Retrieve the RDF triples for the cmeta:id
CellMLSupport::CellmlFileRdfTriples rdfTriples = mParent->cellmlFile()->rdfTriples(pCmetaId);
// Check that we are not dealing with the same RDF triples
// Note: this may happen when manually typing the name of a cmeta:id and the
// QComboBox suggesting something for you, e.g. you start typing "C_"
// and the QComboBox suggests "C_C" (which will get us here) and then
// you finish typing "C_C" (which will also get us here)
static CellMLSupport::CellmlFileRdfTriples oldRdfTriples = CellMLSupport::CellmlFileRdfTriples(mParent->cellmlFile());
if (rdfTriples == oldRdfTriples)
return;
oldRdfTriples = rdfTriples;
// 'Clean up' our web view
mWebView->setUrl(QString());
// Update its metadata details
mMetadataViewDetails->updateGui(rdfTriples);
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::qualifierLookupRequested(const QString &pQualifier,
const bool &pRetranslate)
{
Q_UNUSED(pRetranslate);
// The user requested a qualifier to be looked up, so generate a web page
// containing some information about the qualifier
// Note: ideally, there would be a way to refer to a particular qualifier
// using http://biomodels.net/qualifiers/, but that would require
// anchors and they don't have any, so instead we use the information
// which can be found on that site and present it to the user in the
// form of a web page...
if (pQualifier.isEmpty())
return;
// Generate the web page containing some information about the qualifier
QString qualifierSvg;
QString shortDescription;
QString longDescription;
if (!pQualifier.compare("model:is")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Identity");
longDescription = tr("The modelling object represented by the model element is identical with the subject of the referenced resource (\"Modelling Object B\"). For instance, this qualifier might be used to link an encoded model to a database of models.");
} else if (!pQualifier.compare("model:isDerivedFrom")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Origin");
longDescription = tr("The modelling object represented by the model element is derived from the modelling object represented by the referenced resource (\"Modelling Object B\"). This relation may be used, for instance, to express a refinement or adaptation in usage for a previously described modelling component.");
} else if (!pQualifier.compare("model:isDescribedBy")) {
qualifierSvg = mModelQualifierSvg;
shortDescription = tr("Description");
longDescription = tr("The modelling object represented by the model element is described by the subject of the referenced resource (\"Modelling Object B\"). This relation might be used to link a model or a kinetic law to the literature that describes it.");
} else if (!pQualifier.compare("bio:encodes")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Encodement");
longDescription = tr("The biological entity represented by the model element encodes, directly or transitively, the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a specific DNA sequence encodes a particular protein.");
} else if (!pQualifier.compare("bio:hasPart")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Part");
longDescription = tr("The biological entity represented by the model element includes the subject of the referenced resource (\"Biological Entity B\"), either physically or logically. This relation might be used to link a complex to the description of its components.");
} else if (!pQualifier.compare("bio:hasProperty")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Property");
longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a property of the biological entity represented by the model element. This relation might be used when a biological entity exhibits a certain enzymatic activity or exerts a specific function.");
} else if (!pQualifier.compare("bio:hasVersion")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Version");
longDescription = tr("The subject of the referenced resource (\"Biological Entity B\") is a version or an instance of the biological entity represented by the model element. This relation may be used to represent an isoform or modified form of a biological entity.");
} else if (!pQualifier.compare("bio:is")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Indentity");
longDescription = tr("The biological entity represented by the model element has identity with the subject of the referenced resource (\"Biological Entity B\"). This relation might be used to link a reaction to its exact counterpart in a database, for instance.");
} else if (!pQualifier.compare("bio:isDescribedBy")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Description");
longDescription = tr("The biological entity represented by the model element is described by the subject of the referenced resource (\"Biological Entity B\"). This relation should be used, for instance, to link a species or a parameter to the literature that describes the concentration of that species or the value of that parameter.");
} else if (!pQualifier.compare("bio:isEncodedBy")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Encoder");
longDescription = tr("The biological entity represented by the model element is encoded, directly or transitively, by the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to express, for example, that a protein is encoded by a specific DNA sequence.");
} else if (!pQualifier.compare("bio:isHomologTo")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Homolog");
longDescription = tr("The biological entity represented by the model element is homologous to the subject of the referenced resource (\"Biological Entity B\"). This relation can be used to represent biological entities that share a common ancestor.");
} else if (!pQualifier.compare("bio:isPartOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Parthood");
longDescription = tr("The biological entity represented by the model element is a physical or logical part of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to link a model component to a description of the complex in which it is a part.");
} else if (!pQualifier.compare("bio:isPropertyOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Property bearer");
longDescription = tr("The biological entity represented by the model element is a property of the referenced resource (\"Biological Entity B\").");
} else if (!pQualifier.compare("bio:isVersionOf")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Hypernym");
longDescription = tr("The biological entity represented by the model element is a version or an instance of the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to represent, for example, the 'superclass' or 'parent' form of a particular biological entity.");
} else if (!pQualifier.compare("bio:occursIn")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Container");
longDescription = tr("The biological entity represented by the model element is physically limited to a location, which is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a compartmental location, within which a reaction takes place.");
} else if (!pQualifier.compare("bio:hasTaxon")) {
qualifierSvg = mBiologyQualifierSvg;
shortDescription = tr("Taxon");
longDescription = tr("The biological entity represented by the model element is taxonomically restricted, where the restriction is the subject of the referenced resource (\"Biological Entity B\"). This relation may be used to ascribe a species restriction to a biochemical reaction.");
} else {
qualifierSvg = "";
shortDescription = tr("Unknown");
longDescription = tr("Unknown");
}
// Show the information
mWebView->setHtml(mQualifierInformationTemplate.arg(pQualifier,
qualifierSvg,
shortDescription,
longDescription,
Core::copyright()));
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::resourceLookupRequested(const QString &pResource,
const bool &pRetranslate)
{
// The user requested a resource to be looked up, so retrieve it using
// identifiers.org, but only if we are not retranslating since the looking
// up would already be correct
if (!pRetranslate)
mWebView->setUrl("http://identifiers.org/"+pResource+"/?redirect=true");
//---GRY--- NOTE THAT redirect=true DOESN'T WORK AT THE MOMENT, SO WE DO
// END UP WITH A FRAME, BUT THE identifiers.org GUYS ARE GOING
// TO 'FIX' THAT, SO WE SHOULD BE READY FOR WHEN IT'S DONE...
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::resourceIdLookupRequested(const QString &pResource,
const QString &pId,
const bool &pRetranslate)
{
// The user requested a resource id to be looked up, so retrieve it using
// identifiers.org, but only if we are not retranslating since the looking
// up would already be correct
if (!pRetranslate)
mWebView->setUrl("http://identifiers.org/"+pResource+"/"+pId+"?profile=most_reliable&redirect=true");
}
//==============================================================================
void CellmlAnnotationViewCellmlDetailsWidget::metadataUpdated()
{
// Some metadata has been updated, so we need to update the metadata
// information we show to the user
if (mCellmlElementDetails->cmetaIdValue())
newCmetaId(mCellmlElementDetails->cmetaIdValue()->currentText());
}
//==============================================================================
} // namespace CellMLAnnotationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>#include "VXGI.h"
#include "BindIndexInfo.h"
#include "ShaderFactory.hpp"
#include "MainRenderer.h"
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Light;
using namespace Rendering::Shadow;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Rendering::View;
using namespace Rendering::GI;
using namespace Rendering::Shader;
using namespace Rendering::Factory;
using namespace Rendering::Renderer;
void VXGI::InitializeClearVoxelMap(DirectX& dx, ShaderManager& shaderMgr, uint dimension)
{
ShaderFactory factory(&shaderMgr);
_clearVoxelMap = *factory.LoadComputeShader(dx, "ClearVoxelMap", "CS", nullptr, "@ClearVoxelMap");
}
void VXGI::ClearInjectColorVoxelMap(DirectX& dx)
{
auto Clear = [&dx, &shader = _clearVoxelMap](UnorderedAccessView& uav, uint sideLength, bool isAnisotropic)
{
auto ComputeThreadGroupSideLength = [](uint sideLength)
{
return static_cast<uint>( static_cast<float>(sideLength + 8 - 1) / 8.0f );
};
ComputeShader::BindUnorderedAccessView(dx, UAVBindIndex(0), uav);
uint yz = ComputeThreadGroupSideLength(sideLength);
shader.Dispatch(dx, ComputeShader::ThreadGroup(ComputeThreadGroupSideLength(sideLength * (isAnisotropic ? (uint)VoxelMap::Direction::Num : 1)), yz, yz));
ComputeShader::UnBindUnorderedAccessView(dx, UAVBindIndex(0));
};
Clear(_injectionSourceMap.GetSourceMapUAV(), _staticInfo.dimension, false);
Clear(_mipmappedInjectionMap.GetSourceMapUAV(), _staticInfo.dimension / 2, true);
}
void VXGI::Initialize(DirectX& dx, ShaderManager& shaderMgr, const Size<uint>& renderSize, const VXGIStaticInfo&& info)
{
// Setting Infos
{
_staticInfo = info;
_infoCB.staticInfoCB.Initialize(dx);
_infoCB.staticInfoCB.UpdateSubResource(dx, info);
_infoCB.dynamicInfoCB.Initialize(dx);
UpdateGIDynamicInfoCB(dx);
}
// Init Voxelization
_voxelization.Initialize(dx, shaderMgr, _staticInfo.dimension, _staticInfo.voxelSize);
// Injection
{
_injectionSourceMap.Initialize(dx, _staticInfo.dimension, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1, false);
_mipmappedInjectionMap.Initialize(dx, _staticInfo.dimension / 2, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, uint(_staticInfo.maxMipLevel) - 1, true);
_injectPointLight.Initialize(dx, shaderMgr, _staticInfo.dimension);
_injectSpotLight.Initialize(dx, shaderMgr, _staticInfo.dimension);
}
// Mipmap
_mipmap.Initialize(dx, shaderMgr);
// Voxel Cone Tracing
_voxelConeTracing.Initialize(dx, shaderMgr, renderSize);
InitializeClearVoxelMap(dx, shaderMgr, _staticInfo.dimension);
_indirectColorMap.Initialize(dx, renderSize, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, 0, 1);
}
void VXGI::Run(DirectX& dx, const VXGI::Param&& param)
{
ClearInjectColorVoxelMap(dx);
const auto& lightMgr = param.lightMgr;
const auto& tbrCB = param.main.renderer.GetTBRParamCB();
// 1. Voxelization Pass
{
// Clear Voxel Map and voxelize
_voxelization.Voxelize(dx, _injectionSourceMap,
Voxelization::Param{_dynamicInfo.startCenterWorldPos, _infoCB, lightMgr, param.shadowParam,
tbrCB, param.cullParam, param.meshRenderParam, param.materialMgr}
);
}
// 2. Injection Pass
{
InjectRadianceFormUtility::BindParam injParam{
_infoCB, _voxelization, tbrCB, param.shadowParam.manager.GetGlobalCB()
};
if(lightMgr.GetLightCount<PointLight>() > 0)
_injectPointLight.Inject(dx, _injectionSourceMap, lightMgr, param.shadowParam, injParam);
if(lightMgr.GetLightCount<SpotLight>() > 0)
_injectSpotLight.Inject(dx, _injectionSourceMap, lightMgr, param.shadowParam, injParam);
}
// 3. Mipmap Pass
_mipmap.Mipmapping(dx, _injectionSourceMap, _mipmappedInjectionMap);
// 4. Voxel Cone Tracing Pass
_indirectColorMap.Clear(dx, Color::Clear());
_voxelConeTracing.Run(dx, _indirectColorMap, {_injectionSourceMap, _mipmappedInjectionMap, _infoCB, param.main});
}
void VXGI::UpdateGIDynamicInfoCB(DirectX& dx)
{
_infoCB.dynamicInfoCB.UpdateSubResource(dx, _dynamicInfo);
_dirty = false;
}<commit_msg>VXGI - Clear할때 ComputeShader::Bind가 아닌 AutoBinder를 사용하도록 함<commit_after>#include "VXGI.h"
#include "BindIndexInfo.h"
#include "ShaderFactory.hpp"
#include "MainRenderer.h"
#include "AutoBinder.hpp"
using namespace Device;
using namespace Core;
using namespace Rendering;
using namespace Rendering::Light;
using namespace Rendering::Shadow;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Rendering::View;
using namespace Rendering::GI;
using namespace Rendering::Shader;
using namespace Rendering::Factory;
using namespace Rendering::Renderer;
void VXGI::InitializeClearVoxelMap(DirectX& dx, ShaderManager& shaderMgr, uint dimension)
{
ShaderFactory factory(&shaderMgr);
_clearVoxelMap = *factory.LoadComputeShader(dx, "ClearVoxelMap", "CS", nullptr, "@ClearVoxelMap");
}
void VXGI::ClearInjectColorVoxelMap(DirectX& dx)
{
auto Clear = [&dx, &shader = _clearVoxelMap](UnorderedAccessView& uav, uint sideLength, bool isAnisotropic)
{
auto ComputeThreadGroupSideLength = [](uint sideLength)
{
return static_cast<uint>( static_cast<float>(sideLength + 8 - 1) / 8.0f );
};
AutoBinderUAV outUAV(dx, UAVBindIndex(0), uav);
uint yz = ComputeThreadGroupSideLength(sideLength);
shader.Dispatch(dx, ComputeShader::ThreadGroup(ComputeThreadGroupSideLength(sideLength * (isAnisotropic ? (uint)VoxelMap::Direction::Num : 1)), yz, yz));
};
Clear(_injectionSourceMap.GetSourceMapUAV(), _staticInfo.dimension, false);
Clear(_mipmappedInjectionMap.GetSourceMapUAV(), _staticInfo.dimension / 2, true);
}
void VXGI::Initialize(DirectX& dx, ShaderManager& shaderMgr, const Size<uint>& renderSize, const VXGIStaticInfo&& info)
{
// Setting Infos
{
_staticInfo = info;
_infoCB.staticInfoCB.Initialize(dx);
_infoCB.staticInfoCB.UpdateSubResource(dx, info);
_infoCB.dynamicInfoCB.Initialize(dx);
UpdateGIDynamicInfoCB(dx);
}
// Init Voxelization
_voxelization.Initialize(dx, shaderMgr, _staticInfo.dimension, _staticInfo.voxelSize);
// Injection
{
_injectionSourceMap.Initialize(dx, _staticInfo.dimension, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, 1, false);
_mipmappedInjectionMap.Initialize(dx, _staticInfo.dimension / 2, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R32_UINT, uint(_staticInfo.maxMipLevel) - 1, true);
_injectPointLight.Initialize(dx, shaderMgr, _staticInfo.dimension);
_injectSpotLight.Initialize(dx, shaderMgr, _staticInfo.dimension);
}
// Mipmap
_mipmap.Initialize(dx, shaderMgr);
// Voxel Cone Tracing
_voxelConeTracing.Initialize(dx, shaderMgr, renderSize);
InitializeClearVoxelMap(dx, shaderMgr, _staticInfo.dimension);
_indirectColorMap.Initialize(dx, renderSize, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, 0, 1);
}
void VXGI::Run(DirectX& dx, const VXGI::Param&& param)
{
ClearInjectColorVoxelMap(dx);
const auto& lightMgr = param.lightMgr;
const auto& tbrCB = param.main.renderer.GetTBRParamCB();
// 1. Voxelization Pass
{
// Clear Voxel Map and voxelize
_voxelization.Voxelize(dx, _injectionSourceMap,
Voxelization::Param{_dynamicInfo.startCenterWorldPos, _infoCB, lightMgr, param.shadowParam,
tbrCB, param.cullParam, param.meshRenderParam, param.materialMgr}
);
}
// 2. Injection Pass
{
InjectRadianceFormUtility::BindParam injParam{
_infoCB, _voxelization, tbrCB, param.shadowParam.manager.GetGlobalCB()
};
if(lightMgr.GetLightCount<PointLight>() > 0)
_injectPointLight.Inject(dx, _injectionSourceMap, lightMgr, param.shadowParam, injParam);
if(lightMgr.GetLightCount<SpotLight>() > 0)
_injectSpotLight.Inject(dx, _injectionSourceMap, lightMgr, param.shadowParam, injParam);
}
// 3. Mipmap Pass
_mipmap.Mipmapping(dx, _injectionSourceMap, _mipmappedInjectionMap);
// 4. Voxel Cone Tracing Pass
_indirectColorMap.Clear(dx, Color::Clear());
_voxelConeTracing.Run(dx, _indirectColorMap, {_injectionSourceMap, _mipmappedInjectionMap, _infoCB, param.main});
}
void VXGI::UpdateGIDynamicInfoCB(DirectX& dx)
{
_infoCB.dynamicInfoCB.UpdateSubResource(dx, _dynamicInfo);
_dirty = false;
}<|endoftext|>
|
<commit_before>#ifndef __OPERANDS_HH__
#define __OPERANDS_HH__
#include <memory>
#include <stack>
#include <string>
#include "exprtoken.hh"
// fwd decl
namespace Evaluators
{
class Visitor;
} // namespace Evaluators
namespace Operands
{
typedef double NumericType;
class Operand: public ExpressionToken
{
public:
typedef std::shared_ptr< Operand > Ptr;
};
/**
* class Bool
*/
class Bool
: public Operand
, public std::enable_shared_from_this< Bool >
{
public:
typedef std::shared_ptr< Bool > Ptr;
public:
Bool(): iValue(0)
{}
Bool( bool aValue ): iValue( aValue )
{}
public:
bool getValue() const { return iValue; }
void setValue( bool aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
bool iValue;
};
/**
* class Numeric
*/
class Numeric
: public Operand
, public std::enable_shared_from_this< Numeric >
{
public:
typedef std::shared_ptr< Numeric > Ptr;
public:
Numeric(): iValue(0)
{}
Numeric( NumericType aValue ): iValue( aValue )
{}
public:
NumericType getValue() const { return iValue; }
void setValue( NumericType aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
NumericType iValue;
};
/**
* class Text
*/
class Text
: public Operand
, public std::enable_shared_from_this< Text >
{
public:
typedef std::shared_ptr< Text > Ptr;
public:
Text()
{}
Text( const std::string & aValue ): iValue( aValue )
{}
public:
const std::string & getValue() const { return iValue; }
void setValue( const std::string & aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
std::string iValue;
};
typedef std::shared_ptr< Operand > OperandPtr;
typedef std::shared_ptr< Bool > BoolPtr;
typedef std::shared_ptr< Numeric > NumericPtr;
typedef std::shared_ptr< Text > TextPtr;
typedef std::stack< OperandPtr > OperandsStack;
} // namespace Operands
#endif // __OPERANDS_HH__
<commit_msg>Class Variable added<commit_after>#ifndef __OPERANDS_HH__
#define __OPERANDS_HH__
#include <memory>
#include <stack>
#include <string>
#include "exprtoken.hh"
// fwd decl
namespace Evaluators
{
class Visitor;
} // namespace Evaluators
namespace Operands
{
typedef double NumericType;
class Operand: public ExpressionToken
{
public:
typedef std::shared_ptr< Operand > Ptr;
};
/**
* class Bool
*/
class Bool
: public Operand
, public std::enable_shared_from_this< Bool >
{
public:
typedef std::shared_ptr< Bool > Ptr;
public:
Bool(): iValue(0)
{}
Bool( bool aValue ): iValue( aValue )
{}
public:
bool getValue() const { return iValue; }
void setValue( bool aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
bool iValue;
};
/**
* class Numeric
*/
class Numeric
: public Operand
, public std::enable_shared_from_this< Numeric >
{
public:
typedef std::shared_ptr< Numeric > Ptr;
public:
Numeric(): iValue(0)
{}
Numeric( NumericType aValue ): iValue( aValue )
{}
public:
NumericType getValue() const { return iValue; }
void setValue( NumericType aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
NumericType iValue;
};
/**
* class Text
*/
class Text
: public Operand
, public std::enable_shared_from_this< Text >
{
public:
typedef std::shared_ptr< Text > Ptr;
public:
Text()
{}
Text( const std::string & aValue ): iValue( aValue )
{}
public:
const std::string & getValue() const { return iValue; }
void setValue( const std::string & aValue ) { iValue = aValue; }
public:
void accept( Evaluators::Visitor & );
private:
std::string iValue;
};
/**
* class Variable
*/
class Variable
: public Operand
, public std::enable_shared_from_this< Variable >
{
public:
typedef std::shared_ptr< Variable > Ptr;
};
typedef std::shared_ptr< Operand > OperandPtr;
typedef std::shared_ptr< Bool > BoolPtr;
typedef std::shared_ptr< Numeric > NumericPtr;
typedef std::shared_ptr< Text > TextPtr;
typedef std::stack< OperandPtr > OperandsStack;
} // namespace Operands
#endif // __OPERANDS_HH__
<|endoftext|>
|
<commit_before>// Copyright 2018 Global Phasing Ltd.
#define GEMMI_PROG na
#include "options.h"
#include <cstdio> // for fprintf, fopen
#include <cstdlib> // for strtol, strtod, exit
#include <cstring> // for strcmp, strchr
#include <gemmi/fileutil.hpp> // for expand_if_pdb_code, file_open_or
#include <gemmi/version.hpp> // for GEMMI_VERSION
#include <gemmi/util.hpp> // for trim_str
#include <gemmi/model.hpp> // for gemmi::CoorFormat
#include <gemmi/atox.hpp> // for skip_blank
using std::fprintf;
const option::Descriptor CommonUsage[] = {
{ 0, 0, 0, 0, 0, 0 }, // this makes CommonUsage[Help] return Help item, etc
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Version, 0, "V", "version", Arg::None,
" -V, --version \tPrint version and exit." },
{ Verbose, 0, "v", "verbose", Arg::None,
" -v, --verbose \tVerbose output." }
};
std::vector<int> parse_comma_separated_ints(const char* arg) {
std::vector<int> result;
char* endptr = nullptr;
do {
result.push_back(std::strtol(endptr ? endptr + 1 : arg, &endptr, 10));
} while (*endptr == ',');
if (*endptr != '\0')
result.clear();
return result;
}
option::ArgStatus Arg::Required(const option::Option& option, bool msg) {
if (option.arg != nullptr)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%s' requires an argument\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Char(const option::Option& option, bool msg) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
if (option.arg[0] != '\0' || option.arg[1] == '\0')
return option::ARG_OK;
if (msg)
fprintf(stderr, "Argument of '%s' must be one character\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Choice(const option::Option& option, bool msg,
std::vector<const char*> choices) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
for (const char* a : choices)
if (std::strcmp(option.arg, a) == 0)
return option::ARG_OK;
if (msg)
// option.name here is a string "--option=arg"
fprintf(stderr, "Invalid argument for %.*s: %s\n",
option.namelen, option.name, option.arg);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::ColonPair(const option::Option& option, bool msg) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
const char* sep = std::strchr(option.arg, ':');
if (sep != nullptr && std::strchr(sep+1, ':') == nullptr)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%.*s' requires two colon-separated names "
"as an argument,\n for example: %.*s=A:B\n",
option.namelen, option.name, option.namelen, option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Int(const option::Option& option, bool msg) {
if (option.arg) {
char* endptr = nullptr;
std::strtol(option.arg, &endptr, 10);
if (endptr != option.arg && *endptr == '\0')
return option::ARG_OK;
}
if (msg)
fprintf(stderr, "Option '%s' requires an integer argument\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Int3(const option::Option& option, bool msg) {
if (option.arg && parse_comma_separated_ints(option.arg).size() == 3)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%.*s' requires three comma-separated integers "
"as an argument,\n for example: %.*s=11,12,13\n",
option.namelen, option.name, option.namelen, option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Float(const option::Option& option, bool msg) {
if (option.arg) {
char* endptr = nullptr;
std::strtod(option.arg, &endptr);
if (endptr != option.arg && *endptr == '\0')
return option::ARG_OK;
}
if (msg)
fprintf(stderr, "Option '%s' requires a numeric argument\n", option.name);
return option::ARG_ILLEGAL;
}
// we wrap fwrite because passing it directly may cause warning
// "ignoring attributes on template argument" [-Wignored-attributes]
static
size_t write_func(const void *ptr, size_t size, size_t nmemb, FILE *stream) {
return fwrite(ptr, size, nmemb, stream);
}
void OptParser::simple_parse(int argc, char** argv,
const option::Descriptor usage[]) {
if (argc < 1)
std::exit(2);
option::Stats stats(/*reordering*/true, usage, argc-1, argv+1);
options.resize(stats.options_max);
buffer.resize(stats.buffer_max);
parse(usage, argc-1, argv+1, options.data(), buffer.data());
if (error())
std::exit(2);
if (options[Help]) {
option::printUsage(write_func, stdout, usage);
std::exit(0);
}
if (options[Version]) {
print_version(program_name);
std::exit(0);
}
if (options[NoOp]) {
fprintf(stderr, "Invalid option.\n");
option::printUsage(write_func, stderr, usage);
std::exit(2);
}
}
void OptParser::check_exclusive_group(const std::vector<int>& group) {
int first = -1;
for (int opt : group)
if (options[opt]) {
if (first == -1)
first = opt;
else
exit_exclusive(first, opt);
}
}
void OptParser::print_try_help_and_exit(const char* msg) {
fprintf(stderr, "%s\nTry '%s --help' for more information.\n",
msg, program_name);
std::exit(2);
}
void OptParser::require_positional_args(int n) {
if (nonOptionsCount() != n) {
fprintf(stderr, "%s requires %d arguments but got %d.",
program_name, n, nonOptionsCount());
print_try_help_and_exit("");
}
}
void OptParser::require_input_files_as_args(int other_args) {
if (nonOptionsCount() <= other_args)
print_try_help_and_exit("No input files. Nothing to do.");
}
void OptParser::exit_exclusive(int opt1, int opt2) {
std::fprintf(stderr, "Options -%s and -%s cannot be used together.\n",
given_name(opt1), given_name(opt2));
std::exit(1);
}
std::string OptParser::coordinate_input_file(int n, char pdb_code_type) {
return gemmi::expand_if_pdb_code(nonOption(n), pdb_code_type);
}
bool starts_with_pdb_code(const std::string& s) {
return (s.length() == 4 && gemmi::is_pdb_code(s)) ||
(s.length() > 4 && std::strchr(" \t\r\n:,;|", s[4]) &&
gemmi::is_pdb_code(s.substr(0, 4)));
}
std::vector<std::string>
OptParser::paths_from_args_or_file(int opt, int other) {
std::vector<std::string> paths;
const option::Option& file_option = options[opt];
if (file_option) {
if (nonOptionsCount() > other)
print_try_help_and_exit("Error: File arguments together with option -f.");
std::FILE *f = std::fopen(file_option.arg, "r");
if (!f) {
std::perror(file_option.arg);
std::exit(2);
}
char buf[512];
while (std::fgets(buf, 512, f)) {
std::string s = gemmi::trim_str(buf);
if (!s.empty())
paths.emplace_back(s);
}
std::fclose(f);
} else {
require_input_files_as_args(other);
for (int i = other; i < nonOptionsCount(); ++i)
paths.emplace_back(nonOption(i));
}
return paths;
}
gemmi::CoorFormat coor_format_as_enum(const option::Option& format_in) {
gemmi::CoorFormat format = gemmi::CoorFormat::Unknown;
if (format_in) {
if (strcmp(format_in.arg, "cif") == 0)
format = gemmi::CoorFormat::Mmcif;
else if (strcmp(format_in.arg, "pdb") == 0)
format = gemmi::CoorFormat::Pdb;
else if (strcmp(format_in.arg, "json") == 0)
format = gemmi::CoorFormat::Mmjson;
else if (strcmp(format_in.arg, "chemcomp") == 0)
format = gemmi::CoorFormat::ChemComp;
}
return format;
}
void print_version(const char* program_name) {
std::printf("%s " GEMMI_VERSION
#ifdef GEMMI_VERSION_INFO
" (" GEMMI_XSTRINGIZE(GEMMI_VERSION_INFO) ")"
#endif
"\n", program_name);
}
void read_spec_file(const char* path, std::vector<std::string>& output) {
char buf[256];
gemmi::fileptr_t f_spec = gemmi::file_open_or(path, "r", stdin);
while (std::fgets(buf, sizeof(buf), f_spec.get()) != NULL) {
const char* start = gemmi::skip_blank(buf);
if (*start != '\0' && *start != '\r' && *start != '\n' && *start != '#')
output.emplace_back(start);
}
}
<commit_msg>src/options.cpp: print allowed options in Choice<commit_after>// Copyright 2018 Global Phasing Ltd.
#define GEMMI_PROG na
#include "options.h"
#include <cstdio> // for fprintf, fopen
#include <cstdlib> // for strtol, strtod, exit
#include <cstring> // for strcmp, strchr
#include <gemmi/fileutil.hpp> // for expand_if_pdb_code, file_open_or
#include <gemmi/version.hpp> // for GEMMI_VERSION
#include <gemmi/util.hpp> // for trim_str
#include <gemmi/model.hpp> // for gemmi::CoorFormat
#include <gemmi/atox.hpp> // for skip_blank
using std::fprintf;
const option::Descriptor CommonUsage[] = {
{ 0, 0, 0, 0, 0, 0 }, // this makes CommonUsage[Help] return Help item, etc
{ Help, 0, "h", "help", Arg::None, " -h, --help \tPrint usage and exit." },
{ Version, 0, "V", "version", Arg::None,
" -V, --version \tPrint version and exit." },
{ Verbose, 0, "v", "verbose", Arg::None,
" -v, --verbose \tVerbose output." }
};
std::vector<int> parse_comma_separated_ints(const char* arg) {
std::vector<int> result;
char* endptr = nullptr;
do {
result.push_back(std::strtol(endptr ? endptr + 1 : arg, &endptr, 10));
} while (*endptr == ',');
if (*endptr != '\0')
result.clear();
return result;
}
option::ArgStatus Arg::Required(const option::Option& option, bool msg) {
if (option.arg != nullptr)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%s' requires an argument\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Char(const option::Option& option, bool msg) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
if (option.arg[0] != '\0' || option.arg[1] == '\0')
return option::ARG_OK;
if (msg)
fprintf(stderr, "Argument of '%s' must be one character\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Choice(const option::Option& option, bool msg,
std::vector<const char*> choices) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
for (const char* a : choices)
if (std::strcmp(option.arg, a) == 0)
return option::ARG_OK;
if (msg) {
// option.name here is a string "--option=arg"
fprintf(stderr, "Invalid argument for %.*s: %s\nAllowed arguments:",
option.namelen, option.name, option.arg);
for (const char* a : choices)
fprintf(stderr, " %s", a);
fprintf(stderr, "\n");
}
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::ColonPair(const option::Option& option, bool msg) {
if (Required(option, msg) == option::ARG_ILLEGAL)
return option::ARG_ILLEGAL;
const char* sep = std::strchr(option.arg, ':');
if (sep != nullptr && std::strchr(sep+1, ':') == nullptr)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%.*s' requires two colon-separated names "
"as an argument,\n for example: %.*s=A:B\n",
option.namelen, option.name, option.namelen, option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Int(const option::Option& option, bool msg) {
if (option.arg) {
char* endptr = nullptr;
std::strtol(option.arg, &endptr, 10);
if (endptr != option.arg && *endptr == '\0')
return option::ARG_OK;
}
if (msg)
fprintf(stderr, "Option '%s' requires an integer argument\n", option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Int3(const option::Option& option, bool msg) {
if (option.arg && parse_comma_separated_ints(option.arg).size() == 3)
return option::ARG_OK;
if (msg)
fprintf(stderr, "Option '%.*s' requires three comma-separated integers "
"as an argument,\n for example: %.*s=11,12,13\n",
option.namelen, option.name, option.namelen, option.name);
return option::ARG_ILLEGAL;
}
option::ArgStatus Arg::Float(const option::Option& option, bool msg) {
if (option.arg) {
char* endptr = nullptr;
std::strtod(option.arg, &endptr);
if (endptr != option.arg && *endptr == '\0')
return option::ARG_OK;
}
if (msg)
fprintf(stderr, "Option '%s' requires a numeric argument\n", option.name);
return option::ARG_ILLEGAL;
}
// we wrap fwrite because passing it directly may cause warning
// "ignoring attributes on template argument" [-Wignored-attributes]
static
size_t write_func(const void *ptr, size_t size, size_t nmemb, FILE *stream) {
return fwrite(ptr, size, nmemb, stream);
}
void OptParser::simple_parse(int argc, char** argv,
const option::Descriptor usage[]) {
if (argc < 1)
std::exit(2);
option::Stats stats(/*reordering*/true, usage, argc-1, argv+1);
options.resize(stats.options_max);
buffer.resize(stats.buffer_max);
parse(usage, argc-1, argv+1, options.data(), buffer.data());
if (error())
std::exit(2);
if (options[Help]) {
option::printUsage(write_func, stdout, usage);
std::exit(0);
}
if (options[Version]) {
print_version(program_name);
std::exit(0);
}
if (options[NoOp]) {
fprintf(stderr, "Invalid option.\n");
option::printUsage(write_func, stderr, usage);
std::exit(2);
}
}
void OptParser::check_exclusive_group(const std::vector<int>& group) {
int first = -1;
for (int opt : group)
if (options[opt]) {
if (first == -1)
first = opt;
else
exit_exclusive(first, opt);
}
}
void OptParser::print_try_help_and_exit(const char* msg) {
fprintf(stderr, "%s\nTry '%s --help' for more information.\n",
msg, program_name);
std::exit(2);
}
void OptParser::require_positional_args(int n) {
if (nonOptionsCount() != n) {
fprintf(stderr, "%s requires %d arguments but got %d.",
program_name, n, nonOptionsCount());
print_try_help_and_exit("");
}
}
void OptParser::require_input_files_as_args(int other_args) {
if (nonOptionsCount() <= other_args)
print_try_help_and_exit("No input files. Nothing to do.");
}
void OptParser::exit_exclusive(int opt1, int opt2) {
std::fprintf(stderr, "Options -%s and -%s cannot be used together.\n",
given_name(opt1), given_name(opt2));
std::exit(1);
}
std::string OptParser::coordinate_input_file(int n, char pdb_code_type) {
return gemmi::expand_if_pdb_code(nonOption(n), pdb_code_type);
}
bool starts_with_pdb_code(const std::string& s) {
return (s.length() == 4 && gemmi::is_pdb_code(s)) ||
(s.length() > 4 && std::strchr(" \t\r\n:,;|", s[4]) &&
gemmi::is_pdb_code(s.substr(0, 4)));
}
std::vector<std::string>
OptParser::paths_from_args_or_file(int opt, int other) {
std::vector<std::string> paths;
const option::Option& file_option = options[opt];
if (file_option) {
if (nonOptionsCount() > other)
print_try_help_and_exit("Error: File arguments together with option -f.");
std::FILE *f = std::fopen(file_option.arg, "r");
if (!f) {
std::perror(file_option.arg);
std::exit(2);
}
char buf[512];
while (std::fgets(buf, 512, f)) {
std::string s = gemmi::trim_str(buf);
if (!s.empty())
paths.emplace_back(s);
}
std::fclose(f);
} else {
require_input_files_as_args(other);
for (int i = other; i < nonOptionsCount(); ++i)
paths.emplace_back(nonOption(i));
}
return paths;
}
gemmi::CoorFormat coor_format_as_enum(const option::Option& format_in) {
gemmi::CoorFormat format = gemmi::CoorFormat::Unknown;
if (format_in) {
if (strcmp(format_in.arg, "cif") == 0)
format = gemmi::CoorFormat::Mmcif;
else if (strcmp(format_in.arg, "pdb") == 0)
format = gemmi::CoorFormat::Pdb;
else if (strcmp(format_in.arg, "json") == 0)
format = gemmi::CoorFormat::Mmjson;
else if (strcmp(format_in.arg, "chemcomp") == 0)
format = gemmi::CoorFormat::ChemComp;
}
return format;
}
void print_version(const char* program_name) {
std::printf("%s " GEMMI_VERSION
#ifdef GEMMI_VERSION_INFO
" (" GEMMI_XSTRINGIZE(GEMMI_VERSION_INFO) ")"
#endif
"\n", program_name);
}
void read_spec_file(const char* path, std::vector<std::string>& output) {
char buf[256];
gemmi::fileptr_t f_spec = gemmi::file_open_or(path, "r", stdin);
while (std::fgets(buf, sizeof(buf), f_spec.get()) != NULL) {
const char* start = gemmi::skip_blank(buf);
if (*start != '\0' && *start != '\r' && *start != '\n' && *start != '#')
output.emplace_back(start);
}
}
<|endoftext|>
|
<commit_before>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop
TEST_MODULE_INITIALIZE(ModuleInitialize) {
int argc = 1;
char *argv[] = { "You.exe" };
app = new QApplication(argc, argv);
}
// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
app->quit();
delete app;
}
TEST_CLASS(MainWindowTests) {
public:
TEST_METHOD(isMainWindowVisible) {
MainWindow w;
Assert::IsTrue(w.isVisible());
}
TEST_METHOD(isCentralWidgetVisible) {
MainWindow w;
Assert::IsTrue(w.ui.centralWidget->isVisible());
}
TEST_METHOD(isTaskPanelVisible) {
MainWindow w;
Assert::IsTrue(w.ui.taskTreePanel->isVisible());
}
TEST_METHOD(isCommandEnterButtonVisible) {
MainWindow w;
Assert::IsTrue(w.ui.commandEnterButton->isVisible());
}
TEST_METHOD(isCommandInputBoxVisible) {
MainWindow w;
Assert::IsTrue(w.ui.commandInputBox->isVisible());
}
TEST_METHOD(isStatusBarVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusBar->isVisible());
}
TEST_METHOD(isStatusIconVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusIcon->isVisible());
}
TEST_METHOD(isStatusMessageVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusMessage->isVisible());
}
TEST_METHOD(isMainToolBarHidden) {
MainWindow w;
Assert::IsFalse(w.ui.mainToolBar->isVisible());
}
TEST_METHOD(isMenuBarHidden) {
MainWindow w;
Assert::IsFalse(w.ui.menuBar->isVisible());
}
TEST_METHOD(addSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
TEST_METHOD(addSingleTaskContent) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 2099"));
w.commandEnterPressed();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("test"));
int column3 = QString::compare(
item.text(3), QString("More than a month away (2099-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue((column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
TEST_METHOD(testDueToday1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
TEST_METHOD(testDueToday2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
TEST_METHOD(testDueToday3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Test if is past due, 1 minute before
TEST_METHOD(testPastDue1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= boost::posix_time::minutes(1);
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, 1 day and 1 minute before
TEST_METHOD(testPastDue2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, on the same time
TEST_METHOD(testPastDue3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, with deadline 1 minute after
TEST_METHOD(testPastDue4) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
TEST_METHOD(deleteSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
TEST_METHOD(deleteSingleTaskFind) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->findItems(
QString("1"), Qt::MatchExactly, 1).size() == 0);
}
};
} // namespace UnitTests
} // namespace GUI
} // namespace You
<commit_msg>Updated unit tests.<commit_after>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop
TEST_MODULE_INITIALIZE(ModuleInitialize) {
int argc = 1;
char *argv[] = { "You.exe" };
app = new QApplication(argc, argv);
}
// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
app->quit();
delete app;
}
TEST_CLASS(MainWindowTests) {
public:
TEST_METHOD(isMainWindowVisible) {
MainWindow w;
Assert::IsTrue(w.isVisible());
}
TEST_METHOD(isCentralWidgetVisible) {
MainWindow w;
Assert::IsTrue(w.ui.centralWidget->isVisible());
}
TEST_METHOD(isTaskPanelVisible) {
MainWindow w;
Assert::IsTrue(w.ui.taskTreePanel->isVisible());
}
TEST_METHOD(isCommandEnterButtonVisible) {
MainWindow w;
Assert::IsTrue(w.ui.commandEnterButton->isVisible());
}
TEST_METHOD(isCommandInputBoxVisible) {
MainWindow w;
Assert::IsTrue(w.ui.commandInputBox->isVisible());
}
TEST_METHOD(isStatusBarVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusBar->isVisible());
}
TEST_METHOD(isStatusIconVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusIcon->isVisible());
}
TEST_METHOD(isStatusMessageVisible) {
MainWindow w;
Assert::IsTrue(w.ui.statusMessage->isVisible());
}
TEST_METHOD(isMainToolBarHidden) {
MainWindow w;
Assert::IsFalse(w.ui.mainToolBar->isVisible());
}
TEST_METHOD(isMenuBarHidden) {
MainWindow w;
Assert::IsFalse(w.ui.menuBar->isVisible());
}
TEST_METHOD(addSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
TEST_METHOD(addSingleTaskContent) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 2099"));
w.commandEnterPressed();
QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
int column1 = QString::compare(item.text(1), QString("0"));
int column2 = QString::compare(item.text(2), QString("test"));
int column3 = QString::compare(
item.text(3),
QString("More than a month away (2099-Nov-01 00:00:00)"));
int column4 = QString::compare(item.text(4), QString("Normal"));
Assert::IsTrue((column1 == 0) && (column2 == 0) &&
(column3 == 0) && (column4 == 0));
}
TEST_METHOD(testDueToday1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
TEST_METHOD(testDueToday2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
TEST_METHOD(testDueToday3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
}
/// Test if is past due, 1 minute before
TEST_METHOD(testPastDue1) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= boost::posix_time::minutes(1);
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, 1 day and 1 minute before
TEST_METHOD(testPastDue2) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, on the same time
TEST_METHOD(testPastDue3) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
/// Test if is past due, with deadline 1 minute after
TEST_METHOD(testPastDue4) {
MainWindow w;
Task::Time dl = boost::posix_time::second_clock::local_time();
dl += boost::posix_time::minutes(1);
Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
}
TEST_METHOD(deleteSingleTaskCount) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
}
TEST_METHOD(deleteSingleTaskFind) {
MainWindow w;
w.clearTasks();
w.ui.commandInputBox->setText(QString("/add test by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/add test2 by Nov 20"));
w.commandEnterPressed();
w.ui.commandInputBox->setText(QString("/delete 1"));
w.commandEnterPressed();
Assert::IsTrue(w.ui.taskTreePanel->findItems(
QString("1"), Qt::MatchExactly, 1).size() == 0);
}
};
} // namespace UnitTests
} // namespace GUI
} // namespace You
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.