text
stringlengths 54
60.6k
|
---|
<commit_before>/* Copyright (C) 2015 Cotton Seed
This file is part of arachne-pnr. Arachne-pnr is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License version 2 as published by the Free Software
Foundation.
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/>. */
#include "netlist.hh"
#include "global.hh"
#include "chipdb.hh"
#include "casting.hh"
#include "util.hh"
#include "designstate.hh"
#include <queue>
#include <cassert>
#include <set>
class Promoter
{
std::vector<uint8_t> global_classes;
static const char *global_class_name(uint8_t gc);
DesignState &ds;
const ChipDB *chipdb;
Design *d;
Model *top;
const Models ⊧
std::map<Instance *, uint8_t, IdLess> &gb_inst_gc;
Net *const0;
uint8_t port_gc(Port *conn, bool indirect);
void pll_pass_through(Instance *inst, int cell, const char *p_name);
bool routable(int g, Port *p);
void make_routable(Net *n, int g);
public:
Promoter(DesignState &ds_);
void promote(bool do_promote);
};
const char *
Promoter::global_class_name(uint8_t gc)
{
switch(gc)
{
case gc_clk: return "clk";
case gc_cen: return "cen/wclke";
case gc_sr: return "sr/we";
case gc_rclke: return "rclke";
case gc_re: return "re";
default:
abort();
return nullptr;
}
}
Promoter::Promoter(DesignState &ds_)
: global_classes{
gc_clk, gc_cen, gc_sr, gc_rclke, gc_re,
},
ds(ds_),
chipdb(ds.chipdb),
d(ds.d),
top(ds.top),
models(ds.models),
gb_inst_gc(ds.gb_inst_gc),
const0(nullptr)
{
for (const auto &p : top->nets())
{
if (p.second->is_constant()
&& p.second->constant() == Value::ZERO)
{
const0 = p.second;
break;
}
}
// will prune
if (!const0)
{
const0 = top->add_net("$false");
const0->set_is_constant(true);
const0->set_constant(Value::ZERO);
}
}
uint8_t
Promoter::port_gc(Port *conn, bool indirect)
{
Instance *inst = dyn_cast<Instance>(conn->node());
assert(inst);
if (models.is_lc(inst))
{
if (conn->name() == "CLK")
return gc_clk;
else if (conn->name() == "CEN")
return gc_cen;
else if (conn->name() == "SR")
return gc_sr;
else if (indirect
&& (conn->name() == "I0"
|| conn->name() == "I1"
|| conn->name() == "I2"
|| conn->name() == "I3"))
return gc_clk;
}
else if (models.is_ioX(inst))
{
if (conn->name() == "INPUT_CLOCK"
|| conn->name() == "OUTPUT_CLOCK")
return gc_clk;
}
else if (models.is_gb(inst)
|| models.is_warmboot(inst)
|| models.is_pllX(inst))
;
else
{
assert(models.is_ramX(inst));
if (conn->name() == "WCLK"
|| conn->name() == "WCLKN"
|| conn->name() == "RCLK"
|| conn->name() == "RCLKN")
return gc_clk;
else if (conn->name() == "WCLKE")
return gc_wclke;
else if (conn->name() == "WE")
return gc_we;
else if (conn->name() == "RCLKE")
return gc_rclke;
else if (conn->name() == "RE")
return gc_re;
}
return 0;
}
bool
Promoter::routable(int gc, Port *p)
{
return (bool)((port_gc(p, true) & gc) == gc);
}
void
Promoter::pll_pass_through(Instance *inst, int cell, const char *p_name)
{
Port *p = inst->find_port(p_name);
Net *n = p->connection();
if (!n)
return;
Net *t = top->add_net(n);
p->connect(t);
Instance *pass_inst = top->add_instance(models.lc);
pass_inst->find_port("I0")->connect(t);
pass_inst->find_port("I1")->connect(const0);
pass_inst->find_port("I2")->connect(const0);
pass_inst->find_port("I3")->connect(const0);
pass_inst->set_param("LUT_INIT", BitVector(2, 2));
pass_inst->find_port("O")->connect(n);
const auto &p2 = chipdb->cell_mfvs.at(cell).at(p_name);
int pass_cell = chipdb->loc_cell(Location(p2.first, 0));
extend(ds.placement, pass_inst, pass_cell);
}
void
Promoter::make_routable(Net *n, int gc)
{
Net *internal = nullptr;
for (auto i = n->connections().begin();
i != n->connections().end();)
{
Port *p = *i;
++i;
if (!p->is_input())
continue;
if (routable(gc, p))
continue;
if (!internal)
{
internal = top->add_net(n);
Instance *pass_inst = top->add_instance(models.lc);
pass_inst->find_port("I0")->connect(n);
pass_inst->find_port("I1")->connect(const0);
pass_inst->find_port("I2")->connect(const0);
pass_inst->find_port("I3")->connect(const0);
pass_inst->set_param("LUT_INIT", BitVector(2, 2));
pass_inst->find_port("O")->connect(internal);
}
p->connect(internal);
}
}
void
Promoter::promote(bool do_promote)
{
std::vector<Net *> nets;
std::map<Net *, int, IdLess> net_idx;
std::tie(nets, net_idx) = top->index_nets();
int n_nets = nets.size();
int n_global = 0;
std::map<uint8_t, int> gc_global;
std::map<uint8_t, int> gc_used;
for (uint8_t gc : global_classes)
{
extend(gc_global, gc, 0);
extend(gc_used, gc, 0);
}
std::vector<std::pair<Instance *, int>> plls;
for (const auto &p : ds.placement)
{
Instance *inst = p.first;
int c = p.second;
if (models.is_gb_io(inst))
{
Port *out = inst->find_port("GLOBAL_BUFFER_OUTPUT");
if (out->connected())
{
int g = chipdb->loc_pin_glb_num.at(chipdb->cell_location[c]);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(out->connection(), 1 << g);
}
}
else if (models.is_pllX(inst))
{
plls.push_back(std::make_pair(inst, c));
Port *a = inst->find_port("PLLOUTGLOBAL");
if (!a)
a = inst->find_port("PLLOUTGLOBALA");
assert(a);
if (a->connected())
{
const auto &p2 = chipdb->cell_mfvs.at(c).at("PLLOUT_A");
Location loc(p2.first, std::stoi(p2.second));
int g = chipdb->loc_pin_glb_num.at(loc);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(a->connection(), 1 << g);
}
Port *b = inst->find_port("PLLOUTGLOBALB");
if (b && b->connected())
{
const auto &p2 = chipdb->cell_mfvs.at(c).at("PLLOUT_B");
Location loc(p2.first, std::stoi(p2.second));
int g = chipdb->loc_pin_glb_num.at(loc);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(b->connection(), 1 << g);
}
}
}
for (const auto &p : plls)
{
Instance *inst = p.first;
int c = p.second;
pll_pass_through(inst, c, "LOCK");
pll_pass_through(inst, c, "SDO");
}
std::set<Net *, IdLess> boundary_nets = top->boundary_nets(d);
std::set<std::pair<int, int>, std::greater<std::pair<int, int>>> promote_q;
std::map<int, uint8_t> net_gc;
std::map<int, Port *> net_driver;
for (int i = 1; i < n_nets; ++i) // skip 0, nullptr
{
Net *n = nets[i];
if (contains(boundary_nets, n)
|| n->is_constant())
continue;
std::map<uint8_t, int> n_gc;
for (uint8_t gc : global_classes)
extend(n_gc, gc, 0);
Port *driver = nullptr;
for (Port *conn : n->connections())
{
assert(!conn->is_bidir());
if (conn->is_output())
{
assert(!driver);
driver = conn;
}
int gc = port_gc(conn, false);
if (gc)
++n_gc[gc];
}
int max_gc = 0;
int max_n = 0;
for (const auto &p : n_gc)
{
if (p.second > max_n)
{
max_gc = p.first;
max_n = p.second;
}
}
if (driver
&& isa<Instance>(driver->node())
&& ((models.is_gbX(cast<Instance>(driver->node()))
&& driver->name() == "GLOBAL_BUFFER_OUTPUT")
|| (models.is_pllX(cast<Instance>(driver->node()))
&& (driver->name() == "PLLOUTGLOBAL"
|| driver->name() == "PLLOUTGLOBALA"
|| driver->name() == "PLLOUTGLOBALB"))))
{
Instance *gb_inst = cast<Instance>(driver->node());
uint8_t gc = max_gc ? max_gc : gc_clk;
++n_global;
++gc_global[gc];
if (models.is_gbX(gb_inst))
{
if (driver->connected())
make_routable(driver->connection(), gc);
extend(gb_inst_gc, gb_inst, gc);
}
for (uint8_t gc2 : global_classes)
{
if ((gc2 & gc) == gc)
++gc_used[gc2];
}
}
else if (do_promote
&& driver
&& max_gc
&& max_n > 4)
{
extend(net_driver, i, driver);
extend(net_gc, i, max_gc);
promote_q.insert(std::make_pair(max_n, i));
}
}
int n_promoted = 0;
std::map<uint8_t, int> gc_promoted;
for (int gc : global_classes)
extend(gc_promoted, gc, 0);
while(!promote_q.empty())
{
std::pair<int, int> p = *promote_q.begin();
promote_q.erase(promote_q.begin());
assert(promote_q.empty()
|| promote_q.begin()->first <= p.first);
Net *n = nets[p.second];
uint8_t gc = net_gc.at(p.second);
for (int gc2 : global_classes)
{
int k2 = 0;
for (int i = 0; i < 8; ++i)
{
if (gc2 & (1 << i))
++k2;
}
if ((gc2 & gc) == gc)
{
if (gc_used.at(gc2) >= k2)
goto L;
}
}
{
++n_promoted;
++gc_promoted[gc];
Instance *gb_inst = top->add_instance(models.gb);
Net *t = top->add_net(n);
int n_conn = 0;
int n_conn_promoted = 0;
for (auto i = n->connections().begin();
i != n->connections().end();)
{
Port *conn = *i;
++i;
if (conn->is_output()
|| conn->is_bidir())
continue;
++n_conn;
int conn_gc = port_gc(conn, true);
if ((conn_gc & gc) == gc)
{
++n_conn_promoted;
conn->connect(t);
}
}
gb_inst->find_port("USER_SIGNAL_TO_GLOBAL_BUFFER")->connect(n);
gb_inst->find_port("GLOBAL_BUFFER_OUTPUT")->connect(t);
++n_global;
++gc_global[gc];
extend(gb_inst_gc, gb_inst, gc);
for (uint8_t gc2 : global_classes)
{
if ((gc2 & gc) == gc)
++gc_used[gc2];
}
*logs << " promoted " << n->name()
<< ", " << n_conn_promoted << " / " << n_conn << "\n";
}
L:;
}
*logs << " promoted " << n_promoted << " nets\n";
for (const auto &p : gc_promoted)
{
if (p.second)
*logs << " " << p.second << " " << global_class_name(p.first) << "\n";
}
*logs << " " << n_global << " globals\n";
for (const auto &p : gc_global)
{
if (p.second)
*logs << " " << p.second << " " << global_class_name(p.first) << "\n";
}
d->prune();
}
void
promote_globals(DesignState &ds, bool do_promote)
{
Promoter promoter(ds);
promoter.promote(do_promote);
}
<commit_msg>Fix incorrect I/O block clock net names This resolves issue #61<commit_after>/* Copyright (C) 2015 Cotton Seed
This file is part of arachne-pnr. Arachne-pnr is free software;
you can redistribute it and/or modify it under the terms of the GNU
General Public License version 2 as published by the Free Software
Foundation.
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/>. */
#include "netlist.hh"
#include "global.hh"
#include "chipdb.hh"
#include "casting.hh"
#include "util.hh"
#include "designstate.hh"
#include <queue>
#include <cassert>
#include <set>
class Promoter
{
std::vector<uint8_t> global_classes;
static const char *global_class_name(uint8_t gc);
DesignState &ds;
const ChipDB *chipdb;
Design *d;
Model *top;
const Models ⊧
std::map<Instance *, uint8_t, IdLess> &gb_inst_gc;
Net *const0;
uint8_t port_gc(Port *conn, bool indirect);
void pll_pass_through(Instance *inst, int cell, const char *p_name);
bool routable(int g, Port *p);
void make_routable(Net *n, int g);
public:
Promoter(DesignState &ds_);
void promote(bool do_promote);
};
const char *
Promoter::global_class_name(uint8_t gc)
{
switch(gc)
{
case gc_clk: return "clk";
case gc_cen: return "cen/wclke";
case gc_sr: return "sr/we";
case gc_rclke: return "rclke";
case gc_re: return "re";
default:
abort();
return nullptr;
}
}
Promoter::Promoter(DesignState &ds_)
: global_classes{
gc_clk, gc_cen, gc_sr, gc_rclke, gc_re,
},
ds(ds_),
chipdb(ds.chipdb),
d(ds.d),
top(ds.top),
models(ds.models),
gb_inst_gc(ds.gb_inst_gc),
const0(nullptr)
{
for (const auto &p : top->nets())
{
if (p.second->is_constant()
&& p.second->constant() == Value::ZERO)
{
const0 = p.second;
break;
}
}
// will prune
if (!const0)
{
const0 = top->add_net("$false");
const0->set_is_constant(true);
const0->set_constant(Value::ZERO);
}
}
uint8_t
Promoter::port_gc(Port *conn, bool indirect)
{
Instance *inst = dyn_cast<Instance>(conn->node());
assert(inst);
if (models.is_lc(inst))
{
if (conn->name() == "CLK")
return gc_clk;
else if (conn->name() == "CEN")
return gc_cen;
else if (conn->name() == "SR")
return gc_sr;
else if (indirect
&& (conn->name() == "I0"
|| conn->name() == "I1"
|| conn->name() == "I2"
|| conn->name() == "I3"))
return gc_clk;
}
else if (models.is_ioX(inst))
{
if (conn->name() == "INPUT_CLK"
|| conn->name() == "OUTPUT_CLK")
return gc_clk;
}
else if (models.is_gb(inst)
|| models.is_warmboot(inst)
|| models.is_pllX(inst))
;
else
{
assert(models.is_ramX(inst));
if (conn->name() == "WCLK"
|| conn->name() == "WCLKN"
|| conn->name() == "RCLK"
|| conn->name() == "RCLKN")
return gc_clk;
else if (conn->name() == "WCLKE")
return gc_wclke;
else if (conn->name() == "WE")
return gc_we;
else if (conn->name() == "RCLKE")
return gc_rclke;
else if (conn->name() == "RE")
return gc_re;
}
return 0;
}
bool
Promoter::routable(int gc, Port *p)
{
return (bool)((port_gc(p, true) & gc) == gc);
}
void
Promoter::pll_pass_through(Instance *inst, int cell, const char *p_name)
{
Port *p = inst->find_port(p_name);
Net *n = p->connection();
if (!n)
return;
Net *t = top->add_net(n);
p->connect(t);
Instance *pass_inst = top->add_instance(models.lc);
pass_inst->find_port("I0")->connect(t);
pass_inst->find_port("I1")->connect(const0);
pass_inst->find_port("I2")->connect(const0);
pass_inst->find_port("I3")->connect(const0);
pass_inst->set_param("LUT_INIT", BitVector(2, 2));
pass_inst->find_port("O")->connect(n);
const auto &p2 = chipdb->cell_mfvs.at(cell).at(p_name);
int pass_cell = chipdb->loc_cell(Location(p2.first, 0));
extend(ds.placement, pass_inst, pass_cell);
}
void
Promoter::make_routable(Net *n, int gc)
{
Net *internal = nullptr;
for (auto i = n->connections().begin();
i != n->connections().end();)
{
Port *p = *i;
++i;
if (!p->is_input())
continue;
if (routable(gc, p))
continue;
if (!internal)
{
internal = top->add_net(n);
Instance *pass_inst = top->add_instance(models.lc);
pass_inst->find_port("I0")->connect(n);
pass_inst->find_port("I1")->connect(const0);
pass_inst->find_port("I2")->connect(const0);
pass_inst->find_port("I3")->connect(const0);
pass_inst->set_param("LUT_INIT", BitVector(2, 2));
pass_inst->find_port("O")->connect(internal);
}
p->connect(internal);
}
}
void
Promoter::promote(bool do_promote)
{
std::vector<Net *> nets;
std::map<Net *, int, IdLess> net_idx;
std::tie(nets, net_idx) = top->index_nets();
int n_nets = nets.size();
int n_global = 0;
std::map<uint8_t, int> gc_global;
std::map<uint8_t, int> gc_used;
for (uint8_t gc : global_classes)
{
extend(gc_global, gc, 0);
extend(gc_used, gc, 0);
}
std::vector<std::pair<Instance *, int>> plls;
for (const auto &p : ds.placement)
{
Instance *inst = p.first;
int c = p.second;
if (models.is_gb_io(inst))
{
Port *out = inst->find_port("GLOBAL_BUFFER_OUTPUT");
if (out->connected())
{
int g = chipdb->loc_pin_glb_num.at(chipdb->cell_location[c]);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(out->connection(), 1 << g);
}
}
else if (models.is_pllX(inst))
{
plls.push_back(std::make_pair(inst, c));
Port *a = inst->find_port("PLLOUTGLOBAL");
if (!a)
a = inst->find_port("PLLOUTGLOBALA");
assert(a);
if (a->connected())
{
const auto &p2 = chipdb->cell_mfvs.at(c).at("PLLOUT_A");
Location loc(p2.first, std::stoi(p2.second));
int g = chipdb->loc_pin_glb_num.at(loc);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(a->connection(), 1 << g);
}
Port *b = inst->find_port("PLLOUTGLOBALB");
if (b && b->connected())
{
const auto &p2 = chipdb->cell_mfvs.at(c).at("PLLOUT_B");
Location loc(p2.first, std::stoi(p2.second));
int g = chipdb->loc_pin_glb_num.at(loc);
for (uint8_t gc : global_classes)
{
if (gc & (1 << g))
++gc_used[gc];
}
make_routable(b->connection(), 1 << g);
}
}
}
for (const auto &p : plls)
{
Instance *inst = p.first;
int c = p.second;
pll_pass_through(inst, c, "LOCK");
pll_pass_through(inst, c, "SDO");
}
std::set<Net *, IdLess> boundary_nets = top->boundary_nets(d);
std::set<std::pair<int, int>, std::greater<std::pair<int, int>>> promote_q;
std::map<int, uint8_t> net_gc;
std::map<int, Port *> net_driver;
for (int i = 1; i < n_nets; ++i) // skip 0, nullptr
{
Net *n = nets[i];
if (contains(boundary_nets, n)
|| n->is_constant())
continue;
std::map<uint8_t, int> n_gc;
for (uint8_t gc : global_classes)
extend(n_gc, gc, 0);
Port *driver = nullptr;
for (Port *conn : n->connections())
{
assert(!conn->is_bidir());
if (conn->is_output())
{
assert(!driver);
driver = conn;
}
int gc = port_gc(conn, false);
if (gc)
++n_gc[gc];
}
int max_gc = 0;
int max_n = 0;
for (const auto &p : n_gc)
{
if (p.second > max_n)
{
max_gc = p.first;
max_n = p.second;
}
}
if (driver
&& isa<Instance>(driver->node())
&& ((models.is_gbX(cast<Instance>(driver->node()))
&& driver->name() == "GLOBAL_BUFFER_OUTPUT")
|| (models.is_pllX(cast<Instance>(driver->node()))
&& (driver->name() == "PLLOUTGLOBAL"
|| driver->name() == "PLLOUTGLOBALA"
|| driver->name() == "PLLOUTGLOBALB"))))
{
Instance *gb_inst = cast<Instance>(driver->node());
uint8_t gc = max_gc ? max_gc : gc_clk;
++n_global;
++gc_global[gc];
if (models.is_gbX(gb_inst))
{
if (driver->connected())
make_routable(driver->connection(), gc);
extend(gb_inst_gc, gb_inst, gc);
}
for (uint8_t gc2 : global_classes)
{
if ((gc2 & gc) == gc)
++gc_used[gc2];
}
}
else if (do_promote
&& driver
&& max_gc
&& max_n > 4)
{
extend(net_driver, i, driver);
extend(net_gc, i, max_gc);
promote_q.insert(std::make_pair(max_n, i));
}
}
int n_promoted = 0;
std::map<uint8_t, int> gc_promoted;
for (int gc : global_classes)
extend(gc_promoted, gc, 0);
while(!promote_q.empty())
{
std::pair<int, int> p = *promote_q.begin();
promote_q.erase(promote_q.begin());
assert(promote_q.empty()
|| promote_q.begin()->first <= p.first);
Net *n = nets[p.second];
uint8_t gc = net_gc.at(p.second);
for (int gc2 : global_classes)
{
int k2 = 0;
for (int i = 0; i < 8; ++i)
{
if (gc2 & (1 << i))
++k2;
}
if ((gc2 & gc) == gc)
{
if (gc_used.at(gc2) >= k2)
goto L;
}
}
{
++n_promoted;
++gc_promoted[gc];
Instance *gb_inst = top->add_instance(models.gb);
Net *t = top->add_net(n);
int n_conn = 0;
int n_conn_promoted = 0;
for (auto i = n->connections().begin();
i != n->connections().end();)
{
Port *conn = *i;
++i;
if (conn->is_output()
|| conn->is_bidir())
continue;
++n_conn;
int conn_gc = port_gc(conn, true);
if ((conn_gc & gc) == gc)
{
++n_conn_promoted;
conn->connect(t);
}
}
gb_inst->find_port("USER_SIGNAL_TO_GLOBAL_BUFFER")->connect(n);
gb_inst->find_port("GLOBAL_BUFFER_OUTPUT")->connect(t);
++n_global;
++gc_global[gc];
extend(gb_inst_gc, gb_inst, gc);
for (uint8_t gc2 : global_classes)
{
if ((gc2 & gc) == gc)
++gc_used[gc2];
}
*logs << " promoted " << n->name()
<< ", " << n_conn_promoted << " / " << n_conn << "\n";
}
L:;
}
*logs << " promoted " << n_promoted << " nets\n";
for (const auto &p : gc_promoted)
{
if (p.second)
*logs << " " << p.second << " " << global_class_name(p.first) << "\n";
}
*logs << " " << n_global << " globals\n";
for (const auto &p : gc_global)
{
if (p.second)
*logs << " " << p.second << " " << global_class_name(p.first) << "\n";
}
d->prune();
}
void
promote_globals(DesignState &ds, bool do_promote)
{
Promoter promoter(ds);
promoter.promote(do_promote);
}
<|endoftext|> |
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "cpu.hh"
#include "gc.hh"
#include "percpu.hh"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "uwq.hh"
#include "vm.hh"
#include "kalloc.hh"
#include "bits.hh"
extern "C" {
#include "kern_c.h"
}
bool
uwq_trywork(void)
{
// Returning true means uwq added a thread to the run queue
u64 i, k;
// A "random" victim CPU
k = rdtsc();
for (i = 0; i < NCPU; i++) {
u64 j = (i+k) % NCPU;
if (j == mycpuid())
continue;
struct cpu *c = &cpus[j];
// The gc_epoch is for p and uwq
scoped_gc_epoch xgc();
barrier();
struct proc *p = c->proc;
if (p == nullptr || p->uwq == nullptr)
continue;
uwq* uwq = p->uwq;
if (uwq->haswork()) {
if (uwq->tryworker())
return true;
break;
}
}
return false;
}
long
sys_wqwait(void)
{
uwq_worker* w = myproc()->worker;
if (w == nullptr)
return -1;
return w->wait();
}
//
// uwq_worker
//
uwq_worker::uwq_worker(uwq* u, proc* p)
: uwq_(u), proc_(p), running_(false)
{
initlock(&lock_, "worker_lock", 0);
initcondvar(&cv_, "worker_cv");
}
void
uwq_worker::exit(void)
{
if (--uwq_->uref_ == 0)
gc_delayed(uwq_);
release(&lock_);
delete this;
::exit();
}
long
uwq_worker::wait(void)
{
acquire(&lock_);
if (!uwq_->valid())
this->exit();
running_ = false;
cv_sleep(&cv_, &lock_);
if (!uwq_->valid())
this->exit();
release(&lock_);
return 0;
}
//
// uwq
//
uwq*
uwq::alloc(vmap* vmap, filetable *ftable)
{
padded_length* len;
uwq* u;
len = (padded_length*) ksalloc(slab_userwq);
if (len == nullptr)
return nullptr;
ftable->incref();
vmap->incref();
u = new uwq(vmap, ftable, len);
if (u == nullptr) {
ftable->decref();
vmap->decref();
ksfree(slab_userwq, len);
return nullptr;
}
if (mapkva(vmap->pml4, (char*)len, USERWQ, USERWQSIZE)) {
ftable->decref();
vmap->decref();
ksfree(slab_userwq, len);
u->dec();
return nullptr;
}
return u;
}
uwq::uwq(vmap* vmap, filetable *ftable, padded_length *len)
: rcu_freed("uwq"),
vmap_(vmap), ftable_(ftable), len_(len),
uentry_(0), ustack_(UWQSTACK), uref_(0)
{
for (int i = 0; i < NCPU; i++)
len_[i].v_ = 0;
initlock(&lock_, "uwq_lock", 0);
memset(worker_, 0, sizeof(worker_));
}
uwq::~uwq(void)
{
if (len_ != nullptr)
ksfree(slab_userwq, len_);
vmap_->decref();
ftable_->decref();
}
bool
uwq::haswork(void) const
{
if (len_ == nullptr)
return false;
for (int i = 0; i < NCPU; i++) {
if (len_[i].v_ > 0) {
return true;
}
}
return false;
}
bool
uwq::tryworker(void)
{
// Try to start a worker thread
scoped_acquire lock0(&lock_);
if (!valid())
return false;
int slot = -1;
for (int i = 0; i < NWORKERS; i++) {
if (worker_[i] == nullptr) {
if (slot == -1)
slot = i;
continue;
}
uwq_worker *w = worker_[i];
if (w->running_)
continue;
else {
scoped_acquire lock1(&w->lock_);
proc* p = w->proc_;
acquire(&p->lock);
p->cpuid = mycpuid();
release(&p->lock);
w->running_ = true;
cv_wakeup(&w->cv_);
return true;
}
}
if (slot != -1) {
proc* p = allocworker();
if (p != nullptr) {
uwq_worker* w = new uwq_worker(this, p);
assert(w != nullptr);
++uref_;
p->worker = w;
w->running_ = true;
acquire(&p->lock);
p->cpuid = mycpuid();
addrun(p);
release(&p->lock);
worker_[slot] = w;
return true;
}
}
return nullptr;
}
void
uwq::finish(void)
{
bool gcnow = true;
scoped_acquire lock0(&lock_);
for (int i = 0; i < NWORKERS; i++) {
if (worker_[i] != nullptr) {
uwq_worker* w = worker_[i];
gcnow = false;
acquire(&w->lock_);
cv_wakeup(&w->cv_);
release(&w->lock_);
}
}
if (gcnow)
gc_delayed(this);
}
void
uwq::onzero() const
{
uwq *u = (uwq*)this;
u->finish();
}
void
uwq::setuentry(uptr uentry)
{
uentry_ = uentry;
}
proc*
uwq::allocworker(void)
{
uptr uentry = uentry_;
if (uentry == 0)
return nullptr;
proc* p = proc::alloc();
if (p == nullptr)
return nullptr;
safestrcpy(p->name, "uwq_worker", sizeof(p->name));
// finishproc will drop these refs
vmap_->incref();
ftable_->incref();
p->vmap = vmap_;
p->ftable = ftable_;
struct vmnode *vmn;
if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {
finishproc(p);
return nullptr;
}
uptr stacktop = ustack_ + (USTACKPAGES*PGSIZE);
if (vmap_->insert(vmn, ustack_, 1) < 0) {
delete vmn;
finishproc(p);
return nullptr;
}
// Include a bumper page
ustack_ += (USTACKPAGES*PGSIZE)+PGSIZE;
p->tf->rsp = stacktop - 8;
p->tf->rip = uentry;
p->tf->cs = UCSEG | 0x3;
p->tf->ds = UDSEG | 0x3;
p->tf->ss = p->tf->ds;
p->tf->rflags = FL_IF;
return p;
}
<commit_msg>uwq_trywork bug fix<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "cpu.hh"
#include "gc.hh"
#include "percpu.hh"
#include "spinlock.h"
#include "condvar.h"
#include "proc.hh"
#include "uwq.hh"
#include "vm.hh"
#include "kalloc.hh"
#include "bits.hh"
extern "C" {
#include "kern_c.h"
}
bool
uwq_trywork(void)
{
// Returning true means uwq added a thread to the run queue
u64 i, k;
// A "random" victim CPU
k = rdtsc();
for (i = 0; i < NCPU; i++) {
u64 j = (i+k) % NCPU;
if (j == mycpuid())
continue;
struct cpu *c = &cpus[j];
// The gc_epoch is for p and uwq
scoped_gc_epoch xgc();
barrier();
struct proc *p = c->proc;
if (p == nullptr)
continue;
uwq* uwq = p->uwq;
if (uwq == nullptr)
continue;
if (uwq->haswork()) {
if (uwq->tryworker())
return true;
break;
}
}
return false;
}
long
sys_wqwait(void)
{
uwq_worker* w = myproc()->worker;
if (w == nullptr)
return -1;
return w->wait();
}
//
// uwq_worker
//
uwq_worker::uwq_worker(uwq* u, proc* p)
: uwq_(u), proc_(p), running_(false)
{
initlock(&lock_, "worker_lock", 0);
initcondvar(&cv_, "worker_cv");
}
void
uwq_worker::exit(void)
{
if (--uwq_->uref_ == 0)
gc_delayed(uwq_);
release(&lock_);
delete this;
::exit();
}
long
uwq_worker::wait(void)
{
acquire(&lock_);
if (!uwq_->valid())
this->exit();
running_ = false;
cv_sleep(&cv_, &lock_);
if (!uwq_->valid())
this->exit();
release(&lock_);
return 0;
}
//
// uwq
//
uwq*
uwq::alloc(vmap* vmap, filetable *ftable)
{
padded_length* len;
uwq* u;
len = (padded_length*) ksalloc(slab_userwq);
if (len == nullptr)
return nullptr;
ftable->incref();
vmap->incref();
u = new uwq(vmap, ftable, len);
if (u == nullptr) {
ftable->decref();
vmap->decref();
ksfree(slab_userwq, len);
return nullptr;
}
if (mapkva(vmap->pml4, (char*)len, USERWQ, USERWQSIZE)) {
ftable->decref();
vmap->decref();
ksfree(slab_userwq, len);
u->dec();
return nullptr;
}
return u;
}
uwq::uwq(vmap* vmap, filetable *ftable, padded_length *len)
: rcu_freed("uwq"),
vmap_(vmap), ftable_(ftable), len_(len),
uentry_(0), ustack_(UWQSTACK), uref_(0)
{
for (int i = 0; i < NCPU; i++)
len_[i].v_ = 0;
initlock(&lock_, "uwq_lock", 0);
memset(worker_, 0, sizeof(worker_));
}
uwq::~uwq(void)
{
if (len_ != nullptr)
ksfree(slab_userwq, len_);
vmap_->decref();
ftable_->decref();
}
bool
uwq::haswork(void) const
{
if (len_ == nullptr)
return false;
for (int i = 0; i < NCPU; i++) {
if (len_[i].v_ > 0) {
return true;
}
}
return false;
}
bool
uwq::tryworker(void)
{
// Try to start a worker thread
scoped_acquire lock0(&lock_);
if (!valid())
return false;
int slot = -1;
for (int i = 0; i < NWORKERS; i++) {
if (worker_[i] == nullptr) {
if (slot == -1)
slot = i;
continue;
}
uwq_worker *w = worker_[i];
if (w->running_)
continue;
else {
scoped_acquire lock1(&w->lock_);
proc* p = w->proc_;
acquire(&p->lock);
p->cpuid = mycpuid();
release(&p->lock);
w->running_ = true;
cv_wakeup(&w->cv_);
return true;
}
}
if (slot != -1) {
proc* p = allocworker();
if (p != nullptr) {
uwq_worker* w = new uwq_worker(this, p);
assert(w != nullptr);
++uref_;
p->worker = w;
w->running_ = true;
acquire(&p->lock);
p->cpuid = mycpuid();
addrun(p);
release(&p->lock);
worker_[slot] = w;
return true;
}
}
return nullptr;
}
void
uwq::finish(void)
{
bool gcnow = true;
scoped_acquire lock0(&lock_);
for (int i = 0; i < NWORKERS; i++) {
if (worker_[i] != nullptr) {
uwq_worker* w = worker_[i];
gcnow = false;
acquire(&w->lock_);
cv_wakeup(&w->cv_);
release(&w->lock_);
}
}
if (gcnow)
gc_delayed(this);
}
void
uwq::onzero() const
{
uwq *u = (uwq*)this;
u->finish();
}
void
uwq::setuentry(uptr uentry)
{
uentry_ = uentry;
}
proc*
uwq::allocworker(void)
{
uptr uentry = uentry_;
if (uentry == 0)
return nullptr;
proc* p = proc::alloc();
if (p == nullptr)
return nullptr;
safestrcpy(p->name, "uwq_worker", sizeof(p->name));
// finishproc will drop these refs
vmap_->incref();
ftable_->incref();
p->vmap = vmap_;
p->ftable = ftable_;
struct vmnode *vmn;
if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {
finishproc(p);
return nullptr;
}
uptr stacktop = ustack_ + (USTACKPAGES*PGSIZE);
if (vmap_->insert(vmn, ustack_, 1) < 0) {
delete vmn;
finishproc(p);
return nullptr;
}
// Include a bumper page
ustack_ += (USTACKPAGES*PGSIZE)+PGSIZE;
p->tf->rsp = stacktop - 8;
p->tf->rip = uentry;
p->tf->cs = UCSEG | 0x3;
p->tf->ds = UDSEG | 0x3;
p->tf->ss = p->tf->ds;
p->tf->rflags = FL_IF;
return p;
}
<|endoftext|> |
<commit_before>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = (char*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g) const;
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
static void cheney_collection(Heap& hp, Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
hp.scan_root_object(gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(gc);
mvpt += obsz;
}
}
void Heap::GC(size_t insurance) {
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance +
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(*this, &*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<commit_msg>src/heaps.cpp: Changed computation of total size in Heap::GC<commit_after>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"
#include<cstdlib>
#include<stdint.h>
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
Semispace::Semispace(size_t nsz)
: max(nsz) {
mem = std::malloc(nsz);
if(!mem) throw std::bad_alloc();
allocpt = mem;
// check alignment
intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
if(tmp & Object::tag_mask) {
char* callocpt = (char*)allocpt;
callocpt += Object::alignment - (tmp & Object::tag_mask);
allocpt = callocpt;
}
allocstart = allocpt;
char* cmem = (char*)mem;
char* clifoallocpt = cmem + nsz;
// adjust for alignment
tmp = reinterpret_cast<intptr_t>(lifoallocpt);
clifoallocpt -= (tmp & Object::tag_mask);
lifoallocpt = clifoallocpt;
}
Semispace::~Semispace() {
Generic* gp;
size_t step;
char* mvpt;
char* endpt;
/*TODO: consider refactoring*/
/*----Delete normally-allocated memory----*/
mvpt = (char*) allocstart;
endpt = (char*) allocpt;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
/*----Delete lifo-allocated memory----*/
mvpt = (char*) lifoallocpt;
endpt = (char*) lifoallocstart;
while(mvpt < endpt) {
gp = (Generic*)(void*) mvpt;
step = gp->real_size();
gp->~Generic();
mvpt += step;
}
}
/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated. This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
prev_alloc = sz;
void* tmp = allocpt;
char* callocpt = (char*) allocpt;
callocpt += sz;
allocpt = callocpt;
return tmp;
}
/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
#ifdef DEBUG
char* callocpt = allocpt;
callocpt -= prev_alloc;
if(callocpt != pt) throw_DeallocError(pt);
#endif
allocpt = pt;
}
void* Semispace::lifo_alloc(size_t sz) {
prev_alloc = sz;
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt -= sz;
lifoallocpt = clifoallocpt;
return lifoallocpt;
}
void Semispace::lifo_dealloc(void* pt) {
/*if we can't deallocate, just ignore*/
if(pt != lifoallocpt) return;
size_t sz = ((Generic*) pt)->real_size();
((Generic*) pt)->~Generic();
char* clifoallocpt = (char*) pt;
clifoallocpt += sz;
lifoallocpt = clifoallocpt;
}
/*This function should be used only when the
constructor for the object fails. It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
#ifdef DEBUG
if(pt != lifoallocpt) throw_DeallocError(pt);
#endif
char* clifoallocpt = (char*) lifoallocpt;
clifoallocpt += prev_alloc;
lifoallocpt = clifoallocpt;
}
/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g) const;
/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/
/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
Semispace* nsp;
public:
explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
void traverse(Object::ref& r) {
if(is_a<Generic*>(r)) {
Generic* gp = as_a<Generic*>(r);
BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
if(bp) { //broken heart
r = Object::to_ref(bp->to);
} else { //unbroken
Generic* ngp = gp->clone(nsp);
gp->break_heart(ngp);
r = Object::to_ref(ngp);
}
} else return;
}
};
static void cheney_collection(Heap& hp, Semispace* nsp) {
GCTraverser gc(nsp);
/*step 1: initial traverse*/
hp.scan_root_object(gc);
/*step 2: non-root traverse*/
/*notice that we traverse the new semispace
this is a two-pointer Cheney collector, with mvpt
being one pointer and nsp->allocpt the other one
*/
char* mvpt = nsp->allocstart;
while(mvpt < ((char*) nsp->allocpt)) {
Generic* gp = (Generic*)(void*) mvpt;
size_t obsz = gp->real_size();
gp->traverse_references(gc);
mvpt += obsz;
}
}
void Heap::GC(size_t insurance) {
/*Determine the sizes of all semispaces*/
size_t total = main->used() + insurance;
total +=
(other_spaces) ? other_spaces->used_total() :
/*otherwise*/ 0 ;
if(tight) total *= 2;
/*get a new Semispace*/
boost::scoped_ptr<Semispace> nsp(new Semispace(total));
/*traverse*/
cheney_collection(*this, &*nsp);
/*replace*/
main.swap(nsp);
nsp.reset();
other_spaces.reset();
/*determine if resizing is appropriate*/
if(main->used() + insurance <= total / 4) {
/*semispace a bit large... make it smaller*/
nsp.reset(new Semispace(total / 2));
cheney_collection(&*nsp);
main.swap(nsp);
nsp.reset();
} else if(main->used() + insurance >= (total / 4) * 3) {
tight = 1;
}
}
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "compiler/pkgmanager.h"
#include "compiler/value.h"
#include "compiler/cstring.h"
#include "modules/std/std_pkg.h"
#include "modules/web/web_pkg.h"
namespace clever {
/**
* Loads native packages
*/
void PackageManager::init() {
addPackage(CSTRING("std"), new packages::Std());
addPackage(CSTRING("web"), new packages::Web());
}
/**
* Load an entire package
*/
void PackageManager::loadPackage(Scope* scope, const CString* const package) {
PackageMap::const_iterator it = m_packages.find(package);
if (it != m_packages.end()) {
/**
* Check if the package already has been loaded
*/
if (it->second->isLoaded()) {
return;
}
/**
* Initializes the package
*/
it->second->init();
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator mit = modules.begin(), end = modules.end();
while (mit != end) {
loadModule(scope, package, mit->second, NULL);
++mit;
}
/**
* Sets the package state to fully loaded
*/
it->second->setFullyLoaded();
} else {
std::cerr << "package '" << *package << "' not found" << std::endl;
}
}
/**
* Loads an specific module
*/
void PackageManager::loadModule(Scope* scope, const CString* const package,
Module* const module, const CString* const alias) {
/**
* Checks if the module already has been loaded
*/
if (module->isLoaded()) {
return;
}
/**
* Initializes the module
*/
module->init();
const std::string prefix_name = alias ?
alias->str() + "::" : package->str() + "." + module->getName() + "::";
FunctionMap& funcs = module->getFunctions();
FunctionMap::const_iterator it = funcs.begin(), end = funcs.end();
/**
* Inserts the function into the symbol table
*/
while (it != end) {
CallableValue* fvalue = new CallableValue(CSTRING(it->first));
fvalue->setHandler(it->second);
scope->pushValue(CSTRING(prefix_name + *fvalue->getName()), fvalue);
scope->pushValue(fvalue->getName(), fvalue);
fvalue->addRef();
++it;
}
ClassMap& classes = module->getClassTable();
ClassMap::iterator itc = classes.begin(), endc = classes.end();
/**
* Inserts all classes into the symbol table
*/
while (itc != endc) {
g_scope.pushType(CSTRING(prefix_name + *itc->first), itc->second);
g_scope.pushType(itc->first, itc->second);
itc->second->addRef();
itc->second->init();
++itc;
}
ConstMap& constants = module->getConstants();
ConstMap::iterator itcs = constants.begin(), endcs = constants.end();
/**
* Inserts all constants into the symbol table
*/
while (itcs != endcs) {
g_scope.pushValue(CSTRING(prefix_name + itcs->first->str()), itcs->second);
++itcs;
}
/**
* Sets the module state to loaded
*/
module->setLoaded();
}
/**
* Loads an specific module package by supplying the package and module names
*/
void PackageManager::loadModule(Scope* scope, const CString* const package,
const CString* const module, const CString* const alias) {
PackageMap::const_iterator it = m_packages.find(package);
if (it == m_packages.end()) {
return;
}
/**
* Checks if the package is unloaded, in this case initialize it
*/
if (it->second->isUnloaded()) {
it->second->init();
}
/**
* Check if the package already has been fully loaded
*/
if (!it->second->isFullyLoaded()) {
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator it_mod = modules.find(module);
/**
* Loads the module if it has been found
*/
if (it_mod != modules.end()) {
loadModule(scope, package, it_mod->second, alias);
}
}
/**
* Change the package state to loaded
*/
it->second->setLoaded();
}
/**
* Copy user-defined function in a scope to another supplied alias
*/
void PackageManager::copyScopeToAlias(Scope* scope, const std::string& alias) {
SymbolMap& symbols = scope->getSymbols();
SymbolMap::const_iterator it2(symbols.begin()), end2(symbols.end());
while (it2 != end2) {
Symbol* sym = it2->second;
if (sym->isValue()) {
Value* val = sym->getValue();
if (val->isCallable()) {
CallableValue* fvalue = static_cast<CallableValue*>(val);
if (fvalue->getFunction()->isUserDefined()) {
scope->pushValue(CSTRING(alias + val->getName()->str()),
fvalue);
fvalue->addRef();
}
}
}
++it2;
}
}
/**
* Removes the packages and its modules
*/
void PackageManager::shutdown() {
PackageMap::const_iterator it = m_packages.begin(), end = m_packages.end();
while (it != end) {
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator it_module = modules.begin(), end_module = modules.end();
/**
* Deletes the module entries
*/
while (it_module != end_module) {
delete it_module->second;
++it_module;
}
/**
* Deletes the package
*/
delete it->second;
++it;
}
}
} // clever
<commit_msg>- Simplified code and added check for non-existent module<commit_after>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "compiler/pkgmanager.h"
#include "compiler/value.h"
#include "compiler/cstring.h"
#include "modules/std/std_pkg.h"
#include "modules/web/web_pkg.h"
namespace clever {
/**
* Loads native packages
*/
void PackageManager::init() {
addPackage(CSTRING("std"), new packages::Std());
addPackage(CSTRING("web"), new packages::Web());
}
/**
* Load an entire package
*/
void PackageManager::loadPackage(Scope* scope, const CString* const package) {
PackageMap::const_iterator it = m_packages.find(package);
if (it == m_packages.end()) {
std::cerr << "package '" << *package << "' not found" << std::endl;
return;
}
/**
* Check if the package already has been loaded
*/
if (it->second->isLoaded()) {
return;
}
/**
* Initializes the package
*/
it->second->init();
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator mit = modules.begin(), end = modules.end();
while (mit != end) {
loadModule(scope, package, mit->second, NULL);
++mit;
}
/**
* Sets the package state to fully loaded
*/
it->second->setFullyLoaded();
}
/**
* Loads an specific module
*/
void PackageManager::loadModule(Scope* scope, const CString* const package,
Module* const module, const CString* const alias) {
/**
* Checks if the module already has been loaded
*/
if (module->isLoaded()) {
return;
}
/**
* Initializes the module
*/
module->init();
const std::string prefix_name = alias ?
alias->str() + "::" : package->str() + "." + module->getName() + "::";
FunctionMap& funcs = module->getFunctions();
FunctionMap::const_iterator it = funcs.begin(), end = funcs.end();
/**
* Inserts the function into the symbol table
*/
while (it != end) {
CallableValue* fvalue = new CallableValue(CSTRING(it->first));
fvalue->setHandler(it->second);
scope->pushValue(CSTRING(prefix_name + *fvalue->getName()), fvalue);
scope->pushValue(fvalue->getName(), fvalue);
fvalue->addRef();
++it;
}
ClassMap& classes = module->getClassTable();
ClassMap::iterator itc = classes.begin(), endc = classes.end();
/**
* Inserts all classes into the symbol table
*/
while (itc != endc) {
g_scope.pushType(CSTRING(prefix_name + *itc->first), itc->second);
g_scope.pushType(itc->first, itc->second);
itc->second->addRef();
itc->second->init();
++itc;
}
ConstMap& constants = module->getConstants();
ConstMap::iterator itcs = constants.begin(), endcs = constants.end();
/**
* Inserts all constants into the symbol table
*/
while (itcs != endcs) {
g_scope.pushValue(CSTRING(prefix_name + itcs->first->str()), itcs->second);
++itcs;
}
/**
* Sets the module state to loaded
*/
module->setLoaded();
}
/**
* Loads an specific module package by supplying the package and module names
*/
void PackageManager::loadModule(Scope* scope, const CString* const package,
const CString* const module, const CString* const alias) {
PackageMap::const_iterator it = m_packages.find(package);
if (it == m_packages.end()) {
return;
}
/**
* Checks if the package is unloaded, in this case initialize it
*/
if (it->second->isUnloaded()) {
it->second->init();
}
/**
* Check if the package already has been fully loaded
*/
if (!it->second->isFullyLoaded()) {
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator it_mod = modules.find(module);
if (it_mod == modules.end()) {
std::cerr << "module '" << *module << "' not found" << std::endl;
return;
}
/**
* Loads the module if it has been found
*/
loadModule(scope, package, it_mod->second, alias);
}
/**
* Change the package state to loaded
*/
it->second->setLoaded();
}
/**
* Copy user-defined function in a scope to another supplied alias
*/
void PackageManager::copyScopeToAlias(Scope* scope, const std::string& alias) {
SymbolMap& symbols = scope->getSymbols();
SymbolMap::const_iterator it2(symbols.begin()), end2(symbols.end());
while (it2 != end2) {
Symbol* sym = it2->second;
if (sym->isValue()) {
Value* val = sym->getValue();
if (val->isCallable()) {
CallableValue* fvalue = static_cast<CallableValue*>(val);
if (fvalue->getFunction()->isUserDefined()) {
scope->pushValue(CSTRING(alias + val->getName()->str()),
fvalue);
fvalue->addRef();
}
}
}
++it2;
}
}
/**
* Removes the packages and its modules
*/
void PackageManager::shutdown() {
PackageMap::const_iterator it = m_packages.begin(), end = m_packages.end();
while (it != end) {
ModuleMap& modules = it->second->getModules();
ModuleMap::const_iterator it_module = modules.begin(), end_module = modules.end();
/**
* Deletes the module entries
*/
while (it_module != end_module) {
delete it_module->second;
++it_module;
}
/**
* Deletes the package
*/
delete it->second;
++it;
}
}
} // clever
<|endoftext|> |
<commit_before>#ifndef __NODE_OSRM_QUERY_H__
#define __NODE_OSRM_QUERY_H__
// v8
#include <v8.h>
// node
#include <node.h>
#include <node_version.h>
#include <node_object_wrap.h>
#include <osrm/OSRM.h>
using namespace v8;
namespace node_osrm {
typedef boost::shared_ptr<RouteParameters> route_parameters_ptr;
class Query: public node::ObjectWrap {
public:
static Persistent<FunctionTemplate> constructor;
static void Initialize(Handle<Object> target);
static Handle<Value> New(Arguments const& args);
Query();
inline route_parameters_ptr get() { return this_; }
void _ref() { Ref(); }
void _unref() { Unref(); }
private:
~Query();
route_parameters_ptr this_;
};
Persistent<FunctionTemplate> Query::constructor;
void Query::Initialize(Handle<Object> target) {
HandleScope scope;
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Query::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("Query"));
target->Set(String::NewSymbol("Query"),constructor->GetFunction());
}
Query::Query()
: ObjectWrap(),
this_(boost::make_shared<RouteParameters>()) { }
Query::~Query() { }
Handle<Value> Query::New(Arguments const& args)
{
HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
}
try {
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
}
if (!args[0]->IsObject()) {
return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
}
Local<Object> obj = args[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined()) {
return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
}
if (!obj->Has(String::NewSymbol("coordinates"))) {
return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
}
Local<Value> coordinates = obj->Get(String::New("coordinates"));
if (!coordinates->IsArray()) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
if (coordinates_array->Length() < 2) {
return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
}
Query* q = new Query();
q->this_->zoomLevel = 18; //no generalization
q->this_->printInstructions = false; //turn by turn instructions
q->this_->alternateRoute = true; //get an alternate route, too
q->this_->geometry = true; //retrieve geometry of route
q->this_->compression = true; //polyline encoding
q->this_->checkSum = UINT_MAX; //see wiki
q->this_->service = "viaroute"; //that's routing
q->this_->outputFormat = "json";
q->this_->jsonpParameter = ""; //set for jsonp wrapping
q->this_->language = ""; //unused atm
if (obj->Has(String::NewSymbol("alternateRoute"))) {
q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
}
if (obj->Has(String::NewSymbol("checksum"))) {
q->this_->checkSum = static_cast<unsigned>(obj->Get(String::New("checksum"))->Uint32Value());
}
if (obj->Has(String::NewSymbol("zoomLevel"))) {
q->this_->zoomLevel = static_cast<short>(obj->Get(String::New("zoomLevel"))->Int32Value());
}
if (obj->Has(String::NewSymbol("printInstructions"))) {
q->this_->printInstructions = obj->Get(String::New("printInstructions"))->BooleanValue();
}
if (obj->Has(String::NewSymbol("jsonpParameter"))) {
q->this_->jsonpParameter = *v8::String::Utf8Value(obj->Get(String::New("jsonpParameter")));
}
if (obj->Has(String::NewSymbol("hints"))) {
Local<Value> hints = obj->Get(String::New("hints"));
if (!hints->IsArray()) {
return ThrowException(Exception::TypeError(String::New("hints must be an array of strings/null")));
}
Local<Array> hints_array = Local<Array>::Cast(hints);
for (uint32_t i = 0; i < hints_array->Length(); ++i) {
Local<Value> hint = hints_array->Get(i);
if (hint->IsString()) {
q->this_->hints.push_back(*v8::String::Utf8Value(hint));
} else if(hint->IsNull()){
q->this_->hints.push_back("");
}else{
return ThrowException(Exception::TypeError(String::New("hint must be null or string")));
}
}
}
for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
Local<Value> coordinate = coordinates_array->Get(i);
if (!coordinate->IsArray()) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
if (coordinate_array->Length() != 2) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
q->this_->coordinates.push_back(
FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
}
q->Wrap(args.This());
return args.This();
} catch (std::exception const& ex) {
return ThrowException(Exception::TypeError(String::New(ex.what())));
}
return Undefined();
}
} // namespace node_osrm
#endif // __NODE_OSRM_QUERY_H__
<commit_msg>use String::New instead of String::NewSymbol<commit_after>#ifndef __NODE_OSRM_QUERY_H__
#define __NODE_OSRM_QUERY_H__
// v8
#include <v8.h>
// node
#include <node.h>
#include <node_version.h>
#include <node_object_wrap.h>
#include <osrm/OSRM.h>
using namespace v8;
namespace node_osrm {
typedef boost::shared_ptr<RouteParameters> route_parameters_ptr;
class Query: public node::ObjectWrap {
public:
static Persistent<FunctionTemplate> constructor;
static void Initialize(Handle<Object> target);
static Handle<Value> New(Arguments const& args);
Query();
inline route_parameters_ptr get() { return this_; }
void _ref() { Ref(); }
void _unref() { Unref(); }
private:
~Query();
route_parameters_ptr this_;
};
Persistent<FunctionTemplate> Query::constructor;
void Query::Initialize(Handle<Object> target) {
HandleScope scope;
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(Query::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::New("Query"));
target->Set(String::New("Query"),constructor->GetFunction());
}
Query::Query()
: ObjectWrap(),
this_(boost::make_shared<RouteParameters>()) { }
Query::~Query() { }
Handle<Value> Query::New(Arguments const& args)
{
HandleScope scope;
if (!args.IsConstructCall()) {
return ThrowException(Exception::Error(String::New("Cannot call constructor as function, you need to use 'new' keyword")));
}
try {
if (args.Length() != 1) {
return ThrowException(Exception::TypeError(String::New("please provide an object of options for the first argument")));
}
if (!args[0]->IsObject()) {
return ThrowException(Exception::TypeError(String::New("first argument must be an object")));
}
Local<Object> obj = args[0]->ToObject();
if (obj->IsNull() || obj->IsUndefined()) {
return ThrowException(Exception::TypeError(String::New("first arg must be an object")));
}
if (!obj->Has(String::New("coordinates"))) {
return ThrowException(Exception::TypeError(String::New("must provide a coordinates property")));
}
Local<Value> coordinates = obj->Get(String::New("coordinates"));
if (!coordinates->IsArray()) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
Local<Array> coordinates_array = Local<Array>::Cast(coordinates);
if (coordinates_array->Length() < 2) {
return ThrowException(Exception::TypeError(String::New("at least two coordinates must be provided")));
}
Query* q = new Query();
q->this_->zoomLevel = 18; //no generalization
q->this_->printInstructions = false; //turn by turn instructions
q->this_->alternateRoute = true; //get an alternate route, too
q->this_->geometry = true; //retrieve geometry of route
q->this_->compression = true; //polyline encoding
q->this_->checkSum = UINT_MAX; //see wiki
q->this_->service = "viaroute"; //that's routing
q->this_->outputFormat = "json";
q->this_->jsonpParameter = ""; //set for jsonp wrapping
q->this_->language = ""; //unused atm
if (obj->Has(String::New("alternateRoute"))) {
q->this_->alternateRoute = obj->Get(String::New("alternateRoute"))->BooleanValue();
}
if (obj->Has(String::New("checksum"))) {
q->this_->checkSum = static_cast<unsigned>(obj->Get(String::New("checksum"))->Uint32Value());
}
if (obj->Has(String::New("zoomLevel"))) {
q->this_->zoomLevel = static_cast<short>(obj->Get(String::New("zoomLevel"))->Int32Value());
}
if (obj->Has(String::New("printInstructions"))) {
q->this_->printInstructions = obj->Get(String::New("printInstructions"))->BooleanValue();
}
if (obj->Has(String::New("jsonpParameter"))) {
q->this_->jsonpParameter = *v8::String::Utf8Value(obj->Get(String::New("jsonpParameter")));
}
if (obj->Has(String::New("hints"))) {
Local<Value> hints = obj->Get(String::New("hints"));
if (!hints->IsArray()) {
return ThrowException(Exception::TypeError(String::New("hints must be an array of strings/null")));
}
Local<Array> hints_array = Local<Array>::Cast(hints);
for (uint32_t i = 0; i < hints_array->Length(); ++i) {
Local<Value> hint = hints_array->Get(i);
if (hint->IsString()) {
q->this_->hints.push_back(*v8::String::Utf8Value(hint));
} else if(hint->IsNull()){
q->this_->hints.push_back("");
}else{
return ThrowException(Exception::TypeError(String::New("hint must be null or string")));
}
}
}
for (uint32_t i = 0; i < coordinates_array->Length(); ++i) {
Local<Value> coordinate = coordinates_array->Get(i);
if (!coordinate->IsArray()) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
Local<Array> coordinate_array = Local<Array>::Cast(coordinate);
if (coordinate_array->Length() != 2) {
return ThrowException(Exception::TypeError(String::New("coordinates must be an array of (lat/long) pairs")));
}
q->this_->coordinates.push_back(
FixedPointCoordinate(coordinate_array->Get(0)->NumberValue()*COORDINATE_PRECISION,
coordinate_array->Get(1)->NumberValue()*COORDINATE_PRECISION));
}
q->Wrap(args.This());
return args.This();
} catch (std::exception const& ex) {
return ThrowException(Exception::TypeError(String::New(ex.what())));
}
return Undefined();
}
} // namespace node_osrm
#endif // __NODE_OSRM_QUERY_H__
<|endoftext|> |
<commit_before>// Copyright (C) 2009, 2010 by Thomas Moulard, CNRS.
//
// This file is part of the hppWalkFootPlanner.
//
// hppWalkFootPlanner 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 3 of the License, or
// (at your option) any later version.
//
// hppWalkFootPlanner 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 hppWalkFootPlanner. If not, see <http://www.gnu.org/licenses/>.
#include <cassert>
#include <iomanip>
#include <ostream>
#include "hpp/util/indent.hh"
namespace hpp
{
inline long int& indent (std::ostream& o)
{
// The slot to store the current indentation level.
static const long int indent_index = std::ios::xalloc ();
return o.iword (indent_index);
}
std::ostream& incindent (std::ostream& o)
{
indent (o) += 2;
return o;
}
std::ostream& decindent (std::ostream& o)
{
assert (indent (o));
indent (o) -= 2;
return o;
}
std::ostream& resetindent (std::ostream& o)
{
indent (o) = 0;
return o;
}
std::ostream& iendl (std::ostream& o)
{
o << std::endl;
// Be sure to be able to restore the stream flags.
char fill = o.fill (' ');
return o << std::setw (indent (o))
<< ""
<< std::setfill (fill);
}
std::ostream& incendl (std::ostream& o)
{
return o << incindent << iendl;
}
std::ostream& decendl (std::ostream& o)
{
return o << decindent << iendl;
}
} // end of namespace hpp.
<commit_msg>Fix indent return type which triggered an error on amd64.<commit_after>// Copyright (C) 2009, 2010 by Thomas Moulard, CNRS.
//
// This file is part of the hppWalkFootPlanner.
//
// hppWalkFootPlanner 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 3 of the License, or
// (at your option) any later version.
//
// hppWalkFootPlanner 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 hppWalkFootPlanner. If not, see <http://www.gnu.org/licenses/>.
#include <cassert>
#include <iomanip>
#include <ostream>
#include "hpp/util/indent.hh"
namespace hpp
{
inline int& indent (std::ostream& o)
{
// The slot to store the current indentation level.
static const int indent_index = std::ios::xalloc ();
return o.iword (indent_index);
}
std::ostream& incindent (std::ostream& o)
{
indent (o) += 2;
return o;
}
std::ostream& decindent (std::ostream& o)
{
assert (indent (o));
indent (o) -= 2;
return o;
}
std::ostream& resetindent (std::ostream& o)
{
indent (o) = 0;
return o;
}
std::ostream& iendl (std::ostream& o)
{
o << std::endl;
// Be sure to be able to restore the stream flags.
char fill = o.fill (' ');
return o << std::setw (indent (o))
<< ""
<< std::setfill (fill);
}
std::ostream& incendl (std::ostream& o)
{
return o << incindent << iendl;
}
std::ostream& decendl (std::ostream& o)
{
return o << decindent << iendl;
}
} // end of namespace hpp.
<|endoftext|> |
<commit_before>#include "space.h"
#include "display.h"
#include "window.h"
#include "tree.h"
#include "border.h"
#include "keys.h"
#include "notifications.h"
#include "helpers.h"
extern kwm_mach KWMMach;
extern kwm_tiling KWMTiling;
extern kwm_screen KWMScreen;
extern kwm_focus KWMFocus;
extern kwm_toggles KWMToggles;
extern kwm_mode KWMMode;
extern kwm_thread KWMThread;
extern kwm_border FocusedBorder;
extern kwm_border MarkedBorder;
void GetTagForMonocleSpace(space_info *Space, std::string &Tag)
{
tree_node *Node = Space->RootNode;
bool FoundFocusedWindow = false;
int FocusedIndex = 0;
int NumberOfWindows = 0;
if(Node && KWMFocus.Window)
{
link_node *Link = Node->List;
while(Link)
{
if(!FoundFocusedWindow)
++FocusedIndex;
if(Link->WindowID == KWMFocus.Window->WID)
FoundFocusedWindow = true;
++NumberOfWindows;
Link = Link->Next;
}
}
if(FoundFocusedWindow)
Tag = "[" + std::to_string(FocusedIndex) + "/" + std::to_string(NumberOfWindows) + "]";
else
Tag = "[" + std::to_string(NumberOfWindows) + "]";
}
void GetTagForCurrentSpace(std::string &Tag)
{
if(IsSpaceInitializedForScreen(KWMScreen.Current))
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == SpaceModeBSP)
Tag = "[bsp]";
else if(Space->Settings.Mode == SpaceModeFloating)
Tag = "[float]";
else if(Space->Settings.Mode == SpaceModeMonocle)
GetTagForMonocleSpace(Space, Tag);
}
else
{
if(KWMMode.Space == SpaceModeBSP)
Tag = "[bsp]";
else if(KWMMode.Space == SpaceModeFloating)
Tag = "[float]";
else if(KWMMode.Space == SpaceModeMonocle)
Tag = "[monocle]";
}
}
void MoveWindowToSpace(std::string SpaceID)
{
if(!KWMFocus.Window)
return;
CGEventTapEnable(KWMMach.EventTap, false);
DestroyApplicationNotifications();
window_info *Window = KWMFocus.Window;
bool WasWindowFloating = IsFocusedWindowFloating();
if(!WasWindowFloating)
{
screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
if(SpaceOfWindow->Settings.Mode == SpaceModeBSP)
RemoveWindowFromBSPTree(ScreenOfWindow, Window->WID, false, false);
else if(SpaceOfWindow->Settings.Mode == SpaceModeMonocle)
RemoveWindowFromMonocleTree(ScreenOfWindow, Window->WID, false);
}
CGPoint CursorPos = GetCursorPos();
CGPoint WindowPos = GetWindowPos(Window);
CGPoint ClickPos = CGPointMake(WindowPos.x + 75, WindowPos.y + 7);
CGEventRef ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
usleep(150000);
KwmEmitKeystroke(KWMHotkeys.SpacesKey, SpaceID);
usleep(300000);
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
UpdateActiveWindowList(KWMScreen.Current);
ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
usleep(150000);
if(!WasWindowFloating)
{
screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
if(SpaceOfWindow->Settings.Mode == SpaceModeBSP)
AddWindowToBSPTree(ScreenOfWindow, Window->WID);
else if(SpaceOfWindow->Settings.Mode == SpaceModeMonocle)
AddWindowToMonocleTree(ScreenOfWindow, Window->WID);
}
CGWarpMouseCursorPosition(CursorPos);
CreateApplicationNotifications();
CGEventTapEnable(KWMMach.EventTap, true);
}
bool IsActiveSpaceFloating()
{
return IsSpaceFloating(KWMScreen.Current->ActiveSpace);
}
bool IsSpaceFloating(int SpaceID)
{
bool Result = false;
if(IsSpaceInitializedForScreen(KWMScreen.Current))
{
std::map<int, space_info>::iterator It = KWMScreen.Current->Space.find(SpaceID);
if(It != KWMScreen.Current->Space.end())
Result = KWMScreen.Current->Space[SpaceID].Settings.Mode == SpaceModeFloating;
}
return Result;
}
space_info *GetActiveSpaceOfScreen(screen_info *Screen)
{
space_info *Space = NULL;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
{
space_info Clear = {{{0}}};
Screen->ActiveSpace = GetActiveSpaceOfDisplay(Screen);
Screen->Space[Screen->ActiveSpace] = Clear;
Space = &Screen->Space[Screen->ActiveSpace];
}
else
{
Space = &Screen->Space[Screen->ActiveSpace];
}
return Space;
}
bool IsSpaceInitializedForScreen(screen_info *Screen)
{
if(!Screen)
return false;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
return false;
else
return It->second.Initialized;
}
bool DoesSpaceExistInMapOfScreen(screen_info *Screen)
{
if(!Screen)
return false;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
return false;
else
return It->second.RootNode != NULL && It->second.Initialized;
}
bool IsSpaceTransitionInProgress()
{
if(KWMScreen.Transitioning)
return true;
bool Result = false;
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(!Screen->Identifier)
Screen->Identifier = GetDisplayIdentifier(Screen);
Result = Result || CGSManagedDisplayIsAnimating(CGSDefaultConnection, Screen->Identifier);
}
if(Result)
{
DEBUG("IsSpaceTransitionInProgress() Space transition detected")
KWMScreen.Transitioning = true;
ClearFocusedWindow();
ClearMarkedWindow();
}
return Result;
}
bool IsActiveSpaceManaged()
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
return Space->Managed;
}
void ShouldActiveSpaceBeManaged()
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
Space->Managed = CGSSpaceGetType(CGSDefaultConnection, KWMScreen.Current->ActiveSpace) == CGSSpaceTypeUser;
}
void FloatFocusedSpace()
{
if(KWMToggles.EnableTilingMode &&
!IsSpaceTransitionInProgress() &&
IsActiveSpaceManaged())
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == SpaceModeFloating)
return;
DestroyNodeTree(Space->RootNode);
Space->RootNode = NULL;
Space->Settings.Mode = SpaceModeFloating;
Space->Initialized = true;
ClearFocusedWindow();
}
}
void TileFocusedSpace(space_tiling_option Mode)
{
if(KWMToggles.EnableTilingMode &&
!IsSpaceTransitionInProgress() &&
IsActiveSpaceManaged() &&
FilterWindowList(KWMScreen.Current))
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == Mode)
return;
DestroyNodeTree(Space->RootNode);
Space->RootNode = NULL;
Space->Settings.Mode = Mode;
std::vector<window_info*> WindowsOnDisplay = GetAllWindowsOnDisplay(KWMScreen.Current->ID);
CreateWindowNodeTree(KWMScreen.Current, &WindowsOnDisplay);
}
}
void UpdateActiveSpace()
{
pthread_mutex_lock(&KWMThread.Lock);
Assert(KWMScreen.Current)
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
space_info *Space = NULL;
if(KWMScreen.PrevSpace != KWMScreen.Current->ActiveSpace)
{
DEBUG("UpdateActiveSpace() Space transition ended " << KWMScreen.PrevSpace << " -> " << KWMScreen.Current->ActiveSpace)
Space = GetActiveSpaceOfScreen(KWMScreen.Current);
UpdateActiveWindowList(KWMScreen.Current);
if(Space->FocusedWindowID != 0)
{
FocusWindowByID(Space->FocusedWindowID);
MoveCursorToCenterOfFocusedWindow();
}
}
else
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == KWMScreen.Current->ID)
continue;
int ScreenCurrentSpace = Screen->ActiveSpace;
int ScreenNewSpace = GetActiveSpaceOfDisplay(Screen);
if(ScreenCurrentSpace != ScreenNewSpace)
{
DEBUG("space changed on monitor: " << Screen->ID)
Screen->ActiveSpace = ScreenNewSpace;
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current = Screen;
ShouldActiveSpaceBeManaged();
Space = GetActiveSpaceOfScreen(Screen);
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
break;
}
}
}
if(!Space || !Space->Managed || Space->Settings.Mode == SpaceModeFloating)
{
ClearFocusedWindow();
ClearMarkedWindow();
}
KWMScreen.Transitioning = false;
pthread_mutex_unlock(&KWMThread.Lock);
}
space_settings *GetSpaceSettingsForDesktopID(int ScreenID, int DesktopID)
{
space_identifier Lookup = { ScreenID, DesktopID };
std::map<space_identifier, space_settings>::iterator It = KWMTiling.SpaceSettings.find(Lookup);
if(It != KWMTiling.SpaceSettings.end())
return &It->second;
else
return NULL;
}
<commit_msg>Destroy notifications for unmanaged spaces<commit_after>#include "space.h"
#include "display.h"
#include "window.h"
#include "tree.h"
#include "border.h"
#include "keys.h"
#include "notifications.h"
#include "helpers.h"
extern kwm_mach KWMMach;
extern kwm_tiling KWMTiling;
extern kwm_screen KWMScreen;
extern kwm_focus KWMFocus;
extern kwm_toggles KWMToggles;
extern kwm_mode KWMMode;
extern kwm_thread KWMThread;
extern kwm_border FocusedBorder;
extern kwm_border MarkedBorder;
void GetTagForMonocleSpace(space_info *Space, std::string &Tag)
{
tree_node *Node = Space->RootNode;
bool FoundFocusedWindow = false;
int FocusedIndex = 0;
int NumberOfWindows = 0;
if(Node && KWMFocus.Window)
{
link_node *Link = Node->List;
while(Link)
{
if(!FoundFocusedWindow)
++FocusedIndex;
if(Link->WindowID == KWMFocus.Window->WID)
FoundFocusedWindow = true;
++NumberOfWindows;
Link = Link->Next;
}
}
if(FoundFocusedWindow)
Tag = "[" + std::to_string(FocusedIndex) + "/" + std::to_string(NumberOfWindows) + "]";
else
Tag = "[" + std::to_string(NumberOfWindows) + "]";
}
void GetTagForCurrentSpace(std::string &Tag)
{
if(IsSpaceInitializedForScreen(KWMScreen.Current))
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == SpaceModeBSP)
Tag = "[bsp]";
else if(Space->Settings.Mode == SpaceModeFloating)
Tag = "[float]";
else if(Space->Settings.Mode == SpaceModeMonocle)
GetTagForMonocleSpace(Space, Tag);
}
else
{
if(KWMMode.Space == SpaceModeBSP)
Tag = "[bsp]";
else if(KWMMode.Space == SpaceModeFloating)
Tag = "[float]";
else if(KWMMode.Space == SpaceModeMonocle)
Tag = "[monocle]";
}
}
void MoveWindowToSpace(std::string SpaceID)
{
if(!KWMFocus.Window)
return;
CGEventTapEnable(KWMMach.EventTap, false);
DestroyApplicationNotifications();
window_info *Window = KWMFocus.Window;
bool WasWindowFloating = IsFocusedWindowFloating();
if(!WasWindowFloating)
{
screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
if(SpaceOfWindow->Settings.Mode == SpaceModeBSP)
RemoveWindowFromBSPTree(ScreenOfWindow, Window->WID, false, false);
else if(SpaceOfWindow->Settings.Mode == SpaceModeMonocle)
RemoveWindowFromMonocleTree(ScreenOfWindow, Window->WID, false);
}
CGPoint CursorPos = GetCursorPos();
CGPoint WindowPos = GetWindowPos(Window);
CGPoint ClickPos = CGPointMake(WindowPos.x + 75, WindowPos.y + 7);
CGEventRef ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
usleep(150000);
KwmEmitKeystroke(KWMHotkeys.SpacesKey, SpaceID);
usleep(300000);
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
UpdateActiveWindowList(KWMScreen.Current);
ClickEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseUp, ClickPos, kCGMouseButtonLeft);
CGEventSetFlags(ClickEvent, 0);
CGEventPost(kCGHIDEventTap, ClickEvent);
CFRelease(ClickEvent);
usleep(150000);
if(!WasWindowFloating)
{
screen_info *ScreenOfWindow = GetDisplayOfWindow(Window);
space_info *SpaceOfWindow = GetActiveSpaceOfScreen(ScreenOfWindow);
if(SpaceOfWindow->Settings.Mode == SpaceModeBSP)
AddWindowToBSPTree(ScreenOfWindow, Window->WID);
else if(SpaceOfWindow->Settings.Mode == SpaceModeMonocle)
AddWindowToMonocleTree(ScreenOfWindow, Window->WID);
}
CGWarpMouseCursorPosition(CursorPos);
CreateApplicationNotifications();
CGEventTapEnable(KWMMach.EventTap, true);
}
bool IsActiveSpaceFloating()
{
return IsSpaceFloating(KWMScreen.Current->ActiveSpace);
}
bool IsSpaceFloating(int SpaceID)
{
bool Result = false;
if(IsSpaceInitializedForScreen(KWMScreen.Current))
{
std::map<int, space_info>::iterator It = KWMScreen.Current->Space.find(SpaceID);
if(It != KWMScreen.Current->Space.end())
Result = KWMScreen.Current->Space[SpaceID].Settings.Mode == SpaceModeFloating;
}
return Result;
}
space_info *GetActiveSpaceOfScreen(screen_info *Screen)
{
space_info *Space = NULL;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
{
space_info Clear = {{{0}}};
Screen->ActiveSpace = GetActiveSpaceOfDisplay(Screen);
Screen->Space[Screen->ActiveSpace] = Clear;
Space = &Screen->Space[Screen->ActiveSpace];
}
else
{
Space = &Screen->Space[Screen->ActiveSpace];
}
return Space;
}
bool IsSpaceInitializedForScreen(screen_info *Screen)
{
if(!Screen)
return false;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
return false;
else
return It->second.Initialized;
}
bool DoesSpaceExistInMapOfScreen(screen_info *Screen)
{
if(!Screen)
return false;
std::map<int, space_info>::iterator It = Screen->Space.find(Screen->ActiveSpace);
if(It == Screen->Space.end())
return false;
else
return It->second.RootNode != NULL && It->second.Initialized;
}
bool IsSpaceTransitionInProgress()
{
if(KWMScreen.Transitioning)
return true;
bool Result = false;
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(!Screen->Identifier)
Screen->Identifier = GetDisplayIdentifier(Screen);
Result = Result || CGSManagedDisplayIsAnimating(CGSDefaultConnection, Screen->Identifier);
}
if(Result)
{
DEBUG("IsSpaceTransitionInProgress() Space transition detected")
KWMScreen.Transitioning = true;
ClearFocusedWindow();
ClearMarkedWindow();
}
return Result;
}
bool IsActiveSpaceManaged()
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
return Space->Managed;
}
void ShouldActiveSpaceBeManaged()
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
Space->Managed = CGSSpaceGetType(CGSDefaultConnection, KWMScreen.Current->ActiveSpace) == CGSSpaceTypeUser;
}
void FloatFocusedSpace()
{
if(KWMToggles.EnableTilingMode &&
!IsSpaceTransitionInProgress() &&
IsActiveSpaceManaged())
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == SpaceModeFloating)
return;
DestroyNodeTree(Space->RootNode);
Space->RootNode = NULL;
Space->Settings.Mode = SpaceModeFloating;
Space->Initialized = true;
ClearFocusedWindow();
}
}
void TileFocusedSpace(space_tiling_option Mode)
{
if(KWMToggles.EnableTilingMode &&
!IsSpaceTransitionInProgress() &&
IsActiveSpaceManaged() &&
FilterWindowList(KWMScreen.Current))
{
space_info *Space = GetActiveSpaceOfScreen(KWMScreen.Current);
if(Space->Settings.Mode == Mode)
return;
DestroyNodeTree(Space->RootNode);
Space->RootNode = NULL;
Space->Settings.Mode = Mode;
std::vector<window_info*> WindowsOnDisplay = GetAllWindowsOnDisplay(KWMScreen.Current->ID);
CreateWindowNodeTree(KWMScreen.Current, &WindowsOnDisplay);
}
}
void UpdateActiveSpace()
{
pthread_mutex_lock(&KWMThread.Lock);
Assert(KWMScreen.Current)
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current->ActiveSpace = GetActiveSpaceOfDisplay(KWMScreen.Current);
ShouldActiveSpaceBeManaged();
space_info *Space = NULL;
if(KWMScreen.PrevSpace != KWMScreen.Current->ActiveSpace)
{
DEBUG("UpdateActiveSpace() Space transition ended " << KWMScreen.PrevSpace << " -> " << KWMScreen.Current->ActiveSpace)
Space = GetActiveSpaceOfScreen(KWMScreen.Current);
UpdateActiveWindowList(KWMScreen.Current);
if(Space->FocusedWindowID != 0)
{
FocusWindowByID(Space->FocusedWindowID);
MoveCursorToCenterOfFocusedWindow();
}
}
else
{
std::map<unsigned int, screen_info>::iterator It;
for(It = KWMTiling.DisplayMap.begin(); It != KWMTiling.DisplayMap.end(); ++It)
{
screen_info *Screen = &It->second;
if(Screen->ID == KWMScreen.Current->ID)
continue;
int ScreenCurrentSpace = Screen->ActiveSpace;
int ScreenNewSpace = GetActiveSpaceOfDisplay(Screen);
if(ScreenCurrentSpace != ScreenNewSpace)
{
DEBUG("space changed on monitor: " << Screen->ID)
Screen->ActiveSpace = ScreenNewSpace;
KWMScreen.PrevSpace = KWMScreen.Current->ActiveSpace;
KWMScreen.Current = Screen;
ShouldActiveSpaceBeManaged();
Space = GetActiveSpaceOfScreen(Screen);
UpdateActiveWindowList(Screen);
FilterWindowList(Screen);
break;
}
}
}
if(!Space || !Space->Managed || Space->Settings.Mode == SpaceModeFloating)
{
ClearFocusedWindow();
ClearMarkedWindow();
DestroyApplicationNotifications();
}
KWMScreen.Transitioning = false;
pthread_mutex_unlock(&KWMThread.Lock);
}
space_settings *GetSpaceSettingsForDesktopID(int ScreenID, int DesktopID)
{
space_identifier Lookup = { ScreenID, DesktopID };
std::map<space_identifier, space_settings>::iterator It = KWMTiling.SpaceSettings.find(Lookup);
if(It != KWMTiling.SpaceSettings.end())
return &It->second;
else
return NULL;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2013, "Kira"
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "precompiled_headers.hpp"
#include "redis.hpp"
#include "logging.hpp"
#include "startup_config.hpp"
#include <time.h>
pthread_mutex_t Redis::requestMutex = PTHREAD_MUTEX_INITIALIZER;
//pthread_mutex_t Redis::replyMutex = PTHREAD_MUTEX_INITIALIZER;
queue<RedisRequest*> Redis::requestQueue;
bool Redis::doRun = true;
struct ev_loop* Redis::redis_loop = 0;
ev_timer* Redis::redis_timer = 0;
redisContext* Redis::context = 0;
const string Redis::onlineUsersKey("users.online");
const string Redis::lastCheckinKey("chat.lastCheckin");
const __useconds_t Redis::REDIS_FAILURE_WAIT = 5000000; //5 seconds;
void Redis::connectToRedis() {
DLOG(INFO) << "Connecting to redis.";
if (context)
redisFree(context);
context = 0;
static struct timeval contimeout;
contimeout.tv_sec = 10;
contimeout.tv_usec = 0;
context = redisConnectWithTimeout(StartupConfig::getString("redishost").c_str(), static_cast<int> (StartupConfig::getDouble("redisport")), contimeout);
if (context->err) {
DLOG(INFO) << "Failed to connect to redis with error: " << context->errstr;
redisFree(context);
context = 0;
return;
}
redisSetTimeout(context, contimeout);
redisReply* reply = (redisReply*) redisCommand(context, "AUTH %s", StartupConfig::getString("redispass").c_str());
if (reply == 0 || (reply->type != REDIS_REPLY_STATUS && reply->len != 2)) {
DLOG(INFO) << "Failed to authenticate with the redis server.";
if (reply)
freeReplyObject(reply);
reply = 0;
redisFree(context);
context = 0;
return;
}
freeReplyObject(reply);
}
void Redis::processRequest(RedisRequest* req) {
while (doRun && !context) {
usleep(REDIS_FAILURE_WAIT);
connectToRedis();
}
if (doRun && context) {
const RedisMethod method = req->method;
switch (method) {
case REDIS_DEL:
{
redisReply* reply = (redisReply*) redisCommand(context, "DEL %s", req->key.c_str());
freeReplyObject(reply);
break;
}
case REDIS_SADD:
case REDIS_SREM:
case REDIS_LPUSH:
case REDIS_LREM:
case REDIS_SET:
{
const char* key = req->key.c_str();
int size = req->values.size();
for (int i = 0; i < size; ++i) {
switch (method) {
case REDIS_SADD:
redisAppendCommand(context, "SADD %s %s", key, req->values.front().c_str());
break;
case REDIS_SREM:
redisAppendCommand(context, "SREM %s %s", key, req->values.front().c_str());
break;
case REDIS_LPUSH:
redisAppendCommand(context, "LPUSH %s %s", key, req->values.front().c_str());
break;
case REDIS_LREM:
redisAppendCommand(context, "LREM %s %s", key, req->values.front().c_str());
break;
case REDIS_SET:
redisAppendCommand(context, "SET %s %s", key, req->values.front().c_str());
break;
default:
delete req;
return;
}
req->values.pop();
}
for (int i = 0; i < size; ++i) {
redisReply* reply = 0;
int ret = redisGetReply(context, (void**) &reply);
if (ret != REDIS_OK) {
DLOG(WARNING) << "A redis command failed. Restarting the redis system.";
if (reply)
freeReplyObject(reply);
redisFree(context);
context = 0;
delete req;
return;
}
if (reply)
freeReplyObject(reply);
}
break;
}
default:
break;
}
}
delete req;
}
void* Redis::runThread(void* param) {
DLOG(INFO) << "Starting Redis thread.";
redis_loop = ev_loop_new(EVFLAG_AUTO);
redis_timer = new ev_timer;
ev_timer_init(redis_timer, Redis::timeoutCallback, 0, 5.);
ev_timer_start(redis_loop, redis_timer);
ev_loop(redis_loop, 0);
//Cleanup
ev_timer_stop(redis_loop, redis_timer);
delete redis_timer;
redis_timer = 0;
ev_loop_destroy(redis_loop);
redis_loop = 0;
DLOG(INFO) << "Redis thread exiting.";
pthread_exit(NULL);
}
void Redis::timeoutCallback(struct ev_loop* loop, ev_timer* w, int revents) {
if (!doRun) {
ev_unloop(redis_loop, EVUNLOOP_ONE);
return;
}
static char timebuf[32];
time_t now = time(NULL);
strftime(&timebuf[0], sizeof (timebuf), "%s", gmtime(&now));
RedisRequest* checkin = new RedisRequest;
checkin->key = lastCheckinKey;
checkin->method = REDIS_SET;
checkin->updateContext = RCONTEXT_ONLINE;
checkin->values.push(&timebuf[0]);
if (!addRequest(checkin))
delete checkin;
RedisRequest* req = getRequest();
while (doRun && req) {
processRequest(req);
req = getRequest();
}
ev_timer_again(redis_loop, w);
}
RedisRequest* Redis::getRequest() {
RedisRequest* ret = 0;
MUT_LOCK(requestMutex);
if (requestQueue.size() > 0) {
ret = requestQueue.front();
requestQueue.pop();
}
MUT_UNLOCK(requestMutex);
return ret;
}
bool Redis::addRequest(RedisRequest* newRequest) {
if (!doRun)
return false;
struct timespec abs_time;
clock_gettime(CLOCK_REALTIME, &abs_time);
abs_time.tv_nsec += REDIS_MUTEX_TIMEOUT;
if (MUT_TIMEDLOCK(requestMutex, abs_time))
return false;
requestQueue.push(newRequest);
MUT_UNLOCK(requestMutex);
return true;
}
<commit_msg>[ISSUE #28] Crash on DEL command in Redis.<commit_after>/*
* Copyright (c) 2011-2013, "Kira"
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "precompiled_headers.hpp"
#include "redis.hpp"
#include "logging.hpp"
#include "startup_config.hpp"
#include <time.h>
pthread_mutex_t Redis::requestMutex = PTHREAD_MUTEX_INITIALIZER;
//pthread_mutex_t Redis::replyMutex = PTHREAD_MUTEX_INITIALIZER;
queue<RedisRequest*> Redis::requestQueue;
bool Redis::doRun = true;
struct ev_loop* Redis::redis_loop = 0;
ev_timer* Redis::redis_timer = 0;
redisContext* Redis::context = 0;
const string Redis::onlineUsersKey("users.online");
const string Redis::lastCheckinKey("chat.lastCheckin");
const __useconds_t Redis::REDIS_FAILURE_WAIT = 5000000; //5 seconds;
void Redis::connectToRedis() {
DLOG(INFO) << "Connecting to redis.";
if (context)
redisFree(context);
context = 0;
static struct timeval contimeout;
contimeout.tv_sec = 10;
contimeout.tv_usec = 0;
context = redisConnectWithTimeout(StartupConfig::getString("redishost").c_str(), static_cast<int> (StartupConfig::getDouble("redisport")), contimeout);
if (context->err) {
DLOG(INFO) << "Failed to connect to redis with error: " << context->errstr;
redisFree(context);
context = 0;
return;
}
redisSetTimeout(context, contimeout);
redisReply* reply = (redisReply*) redisCommand(context, "AUTH %s", StartupConfig::getString("redispass").c_str());
if (reply == 0 || (reply->type != REDIS_REPLY_STATUS && reply->len != 2)) {
DLOG(INFO) << "Failed to authenticate with the redis server.";
if (reply)
freeReplyObject(reply);
reply = 0;
redisFree(context);
context = 0;
return;
}
freeReplyObject(reply);
}
void Redis::processRequest(RedisRequest* req) {
while (doRun && !context) {
usleep(REDIS_FAILURE_WAIT);
connectToRedis();
}
if (doRun && context) {
const RedisMethod method = req->method;
switch (method) {
case REDIS_DEL:
{
redisReply* reply = (redisReply*) redisCommand(context, "DEL %s", req->key.c_str());
if (reply)
freeReplyObject(reply);
else {
DLOG(WARNING) << "A redis command failed. Restarting the redis system.";
redisFree(context);
context = 0;
delete req;
return;
}
break;
}
case REDIS_SADD:
case REDIS_SREM:
case REDIS_LPUSH:
case REDIS_LREM:
case REDIS_SET:
{
const char* key = req->key.c_str();
int size = req->values.size();
for (int i = 0; i < size; ++i) {
switch (method) {
case REDIS_SADD:
redisAppendCommand(context, "SADD %s %s", key, req->values.front().c_str());
break;
case REDIS_SREM:
redisAppendCommand(context, "SREM %s %s", key, req->values.front().c_str());
break;
case REDIS_LPUSH:
redisAppendCommand(context, "LPUSH %s %s", key, req->values.front().c_str());
break;
case REDIS_LREM:
redisAppendCommand(context, "LREM %s %s", key, req->values.front().c_str());
break;
case REDIS_SET:
redisAppendCommand(context, "SET %s %s", key, req->values.front().c_str());
break;
default:
delete req;
return;
}
req->values.pop();
}
for (int i = 0; i < size; ++i) {
redisReply* reply = 0;
int ret = redisGetReply(context, (void**) &reply);
if (ret != REDIS_OK) {
DLOG(WARNING) << "A redis command failed. Restarting the redis system.";
if (reply)
freeReplyObject(reply);
redisFree(context);
context = 0;
delete req;
return;
}
if (reply)
freeReplyObject(reply);
}
break;
}
default:
break;
}
}
delete req;
}
void* Redis::runThread(void* param) {
DLOG(INFO) << "Starting Redis thread.";
redis_loop = ev_loop_new(EVFLAG_AUTO);
redis_timer = new ev_timer;
ev_timer_init(redis_timer, Redis::timeoutCallback, 0, 5.);
ev_timer_start(redis_loop, redis_timer);
ev_loop(redis_loop, 0);
//Cleanup
ev_timer_stop(redis_loop, redis_timer);
delete redis_timer;
redis_timer = 0;
ev_loop_destroy(redis_loop);
redis_loop = 0;
DLOG(INFO) << "Redis thread exiting.";
pthread_exit(NULL);
}
void Redis::timeoutCallback(struct ev_loop* loop, ev_timer* w, int revents) {
if (!doRun) {
ev_unloop(redis_loop, EVUNLOOP_ONE);
return;
}
static char timebuf[32];
time_t now = time(NULL);
strftime(&timebuf[0], sizeof (timebuf), "%s", gmtime(&now));
RedisRequest* checkin = new RedisRequest;
checkin->key = lastCheckinKey;
checkin->method = REDIS_SET;
checkin->updateContext = RCONTEXT_ONLINE;
checkin->values.push(&timebuf[0]);
if (!addRequest(checkin))
delete checkin;
RedisRequest* req = getRequest();
while (doRun && req) {
processRequest(req);
req = getRequest();
}
ev_timer_again(redis_loop, w);
}
RedisRequest* Redis::getRequest() {
RedisRequest* ret = 0;
MUT_LOCK(requestMutex);
if (requestQueue.size() > 0) {
ret = requestQueue.front();
requestQueue.pop();
}
MUT_UNLOCK(requestMutex);
return ret;
}
bool Redis::addRequest(RedisRequest* newRequest) {
if (!doRun)
return false;
struct timespec abs_time;
clock_gettime(CLOCK_REALTIME, &abs_time);
abs_time.tv_nsec += REDIS_MUTEX_TIMEOUT;
if (MUT_TIMEDLOCK(requestMutex, abs_time))
return false;
requestQueue.push(newRequest);
MUT_UNLOCK(requestMutex);
return true;
}
<|endoftext|> |
<commit_before>/* ===========================
*
* Copyright (c) 2013 Philippe Tillet - National Chiao Tung University
*
* curveica - Hybrid ICA using ViennaCL + Eigen
*
* License : MIT X11 - See the LICENSE file in the root folder
* ===========================*/
#include "tests/benchmark-utils.hpp"
#include "curveica.h"
#include "umintl/check_grad.hpp"
#include "umintl/minimize.hpp"
#include "src/whiten.hpp"
#include "src/utils.hpp"
#include "src/backend.hpp"
#include "src/nonlinearities/extended_infomax.h"
namespace curveica{
template<class ScalarType, class NonlinearityType>
struct ica_functor{
public:
ica_functor(ScalarType const * data, std::size_t NF, std::size_t NC) : data_(data), NC_(NC), NF_(NF), nonlinearity_(NC,NF){
is_first_ = true;
ipiv_ = new typename backend<ScalarType>::size_t[NC_+1];
Z = new ScalarType[NC_*NF_];
RZ = new ScalarType[NC_*NF_];
phi = new ScalarType[NC_*NF_];
psi = new ScalarType[NC_*NC_];
dweights = new ScalarType[NC_*NC_];
W = new ScalarType[NC_*NC_];
WLU = new ScalarType[NC_*NC_];
V = new ScalarType[NC_*NC_];
HV = new ScalarType[NC_*NC_];
WinvV = new ScalarType[NC_*NC_];
means_logp = new ScalarType[NC_];
first_signs = new int[NC_];
for(unsigned int c = 0 ; c < NC_ ; ++c){
ScalarType m2 = 0, m4 = 0;
for(unsigned int f = 0; f < NF_ ; f++){
ScalarType X = data_[c*NF_+f];
m2 += std::pow(X,2);
m4 += std::pow(X,4);
}
m2 = std::pow(1/(ScalarType)NF_*m2,2);
m4 = 1/(ScalarType)NF_*m4;
ScalarType k = m4/m2 - 3;
first_signs[c] = (k+0.02>0)?1:-1;
}
}
bool recompute_signs(){
bool sign_change = false;
for(unsigned int c = 0 ; c < NC_ ; ++c){
ScalarType m2 = 0, m4 = 0;
//ScalarType b = b_[c];
for(unsigned int f = 0; f < NF_ ; f++){
ScalarType X = Z[c*NF_+f];
m2 += std::pow(X,2);
m4 += std::pow(X,4);
}
m2 = std::pow(1/(ScalarType)NF_*m2,2);
m4 = 1/(ScalarType)NF_*m4;
ScalarType k = m4/m2 - 3;
int new_sign = (k+0.02>0)?1:-1;
sign_change |= (new_sign!=first_signs[c]);
first_signs[c] = new_sign;
}
return sign_change;
}
~ica_functor(){
delete[] ipiv_;
delete[] Z;
delete[] RZ;
delete[] phi;
delete[] psi;
delete[] dweights;
delete[] W;
delete[] WLU;
delete[] V;
delete[] HV;
delete[] WinvV;
delete[] means_logp;
}
void compute_Hv(ScalarType const * x, ScalarType const * v, ScalarType * Hv) const{
std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(WLU,x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(V, v,sizeof(ScalarType)*NC_*NC_);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,W,NC_,0,Z,NF_);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,V,NC_,0,RZ,NF_);
//Psi = dphi(Z).*RZ
nonlinearity_.compute_dphi(Z,first_signs,psi);
for(unsigned int c = 0 ; c < NC_ ; ++c)
for(unsigned int f = 0; f < NF_ ; ++f)
psi[c*NF_+f] *= RZ[c*NF_+f];
//HV = (inv(W)*V*inv(w))' + 1/n*Psi*X'
backend<ScalarType>::getrf(NC_,NC_,WLU,NC_,ipiv_);
backend<ScalarType>::getri(NC_,WLU,NC_,ipiv_);
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,1,WLU,NC_,V,NC_,0,WinvV,NC_);
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,1,WinvV,NC_,WLU,NC_,0,HV,NC_);
for(std::size_t i = 0 ; i < NC_; ++i)
for(std::size_t j = 0 ; j <= i; ++j)
std::swap(HV[i*NC_+j],HV[i*NC_+j]);
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,1/(ScalarType)NF_,data_,NF_,psi,NF_,1,HV,NC_);
//Copy back
for(std::size_t i = 0 ; i < NC_*NC_; ++i)
Hv[i] = HV[i];
}
void operator()(ScalarType const * x, ScalarType* value, ScalarType ** grad) const {
//Rerolls the variables into the appropriates datastructures
std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(WLU,W,sizeof(ScalarType)*NC_*NC_);
//z1 = W*data_;
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,W,NC_,0,Z,NF_);
//phi = mean(mata.*abs(z2).^(mata-1).*sign(z2),2);
nonlinearity_.compute_means_logp(Z,first_signs,means_logp);
//LU Decomposition
backend<ScalarType>::getrf(NC_,NC_,WLU,NC_,ipiv_);
//det = prod(diag(WLU))
ScalarType absdet = 1;
for(std::size_t i = 0 ; i < NC_ ; ++i){
absdet*=std::abs(WLU[i*NC_+i]);
}
//H = log(abs(det(w))) + sum(means_logp);
ScalarType H = std::log(absdet);
for(std::size_t i = 0; i < NC_ ; ++i){
H+=means_logp[i];
}
if(value)
*value = -H;
if(grad){
nonlinearity_.compute_phi(Z,first_signs,phi);
//dweights = W^-T - 1/n*Phi*X'
backend<ScalarType>::getri(NC_,WLU,NC_,ipiv_);
for(std::size_t i = 0 ; i < NC_; ++i)
for(std::size_t j = 0 ; j < NC_; ++j)
dweights[i*NC_+j] = WLU[j*NC_+i];
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,-1/(ScalarType)NF_,data_,NF_,phi,NF_,1,dweights,NC_);
//Copy back
for(std::size_t i = 0 ; i < NC_*NC_; ++i)
(*grad)[i] = -dweights[i];
}
}
private:
ScalarType const * data_;
int * first_signs;
std::size_t NC_;
std::size_t NF_;
typename backend<ScalarType>::size_t *ipiv_;
//MiniBatch
ScalarType* Z;
ScalarType* RZ;
ScalarType* phi;
//Mixing
ScalarType* psi;
ScalarType* dweights;
ScalarType* V;
ScalarType* HV;
ScalarType* WinvV;
ScalarType* W;
ScalarType* WLU;
ScalarType* means_logp;
NonlinearityType nonlinearity_;
mutable bool is_first_;
};
options make_default_options(){
options opt;
opt.max_iter = 200;
opt.verbosity_level = 2;
opt.optimization_method = LBFGS;
return opt;
}
template<class ScalarType>
void inplace_linear_ica(ScalarType const * data, ScalarType * out, std::size_t NC, std::size_t DataNF, options const & opt, double* W, double* S){
typedef typename umintl_backend<ScalarType>::type BackendType;
typedef ica_functor<ScalarType, extended_infomax_ica<ScalarType> > IcaFunctorType;
std::size_t N = NC*NC;
std::size_t padsize = 4;
std::size_t NF=(DataNF%padsize==0)?DataNF:(DataNF/padsize)*padsize;
ScalarType * Sphere = new ScalarType[NC*NC];
ScalarType * Weights = new ScalarType[NC*NC];
//ScalarType * b = new ScalarType[NC];
ScalarType * X = new ScalarType[N];
std::memset(X,0,N*sizeof(ScalarType));
ScalarType * white_data = new ScalarType[NC*NF];
//Optimization Vector
//Solution vector
//Initial guess W_0 = I
//b_0 = 0
for(unsigned int i = 0 ; i < NC; ++i)
X[i*(NC+1)] = 1;
//Whiten Data
whiten<ScalarType>(NC, DataNF, NF, data,Sphere,white_data);
detail::shuffle(white_data,NC,NF);
IcaFunctorType objective(white_data,NF,NC);
umintl::minimizer<BackendType> minimizer;
if(opt.optimization_method==SD)
minimizer.direction = new umintl::steepest_descent<BackendType>();
else if(opt.optimization_method==LBFGS)
minimizer.direction = new umintl::quasi_newton<BackendType>(new umintl::lbfgs<BackendType>(16));
else if(opt.optimization_method==NCG)
minimizer.direction = new umintl::conjugate_gradient<BackendType>(new umintl::polak_ribiere<BackendType>());
else if(opt.optimization_method==BFGS)
minimizer.direction = new umintl::quasi_newton<BackendType>(new umintl::bfgs<BackendType>());
else if(opt.optimization_method==HESSIAN_FREE){
minimizer.direction = new umintl::truncated_newton<BackendType>(
umintl::hessian_free::options<BackendType>(30
, new umintl::hessian_free::hessian_vector_product_custom<BackendType,IcaFunctorType>(objective)));
}
minimizer.verbosity_level = opt.verbosity_level;
minimizer.max_iter = opt.max_iter;
minimizer.stopping_criterion = new umintl::gradient_treshold<BackendType>(1e-4);
do{
minimizer(X,objective,X,N);
}while(objective.recompute_signs());
//Copies into datastructures
std::memcpy(Weights, X,sizeof(ScalarType)*NC*NC);
//std::memcpy(b, X+NC*NC, sizeof(ScalarType)*NC);
//out = W*Sphere*data;
backend<ScalarType>::gemm(NoTrans,NoTrans,NF,NC,NC,1,data,DataNF,Sphere,NC,0,white_data,NF);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF,NC,NC,1,white_data,NF,Weights,NC,0,out,NF);
for(std::size_t i = 0 ; i < NC ; ++i){
for(std::size_t j = 0 ; j < NC ; ++j){
if(W)
W[i*NC+j] = Weights[j*NC+i];
if(S)
S[i*NC+j] = Sphere[j*NC+i];
}
}
delete[] Weights;
//delete[] b;
delete[] X;
delete[] white_data;
}
template void inplace_linear_ica<float>(float const * data, float * out, std::size_t NC, std::size_t NF, curveica::options const & opt, double* Weights, double* Sphere);
template void inplace_linear_ica<double>(double const * data, double * out, std::size_t NC, std::size_t NF, curveica::options const & opt, double * Weights, double * Sphere);
}
<commit_msg>Algorithm : Bugfix in Hessian-free vector product<commit_after>/* ===========================
*
* Copyright (c) 2013 Philippe Tillet - National Chiao Tung University
*
* curveica - Hybrid ICA using ViennaCL + Eigen
*
* License : MIT X11 - See the LICENSE file in the root folder
* ===========================*/
#include "tests/benchmark-utils.hpp"
#include "curveica.h"
#include "umintl/check_grad.hpp"
#include "umintl/minimize.hpp"
#include "src/whiten.hpp"
#include "src/utils.hpp"
#include "src/backend.hpp"
#include "src/nonlinearities/extended_infomax.h"
namespace curveica{
template<class ScalarType, class NonlinearityType>
struct ica_functor{
public:
ica_functor(ScalarType const * data, std::size_t NF, std::size_t NC) : data_(data), NC_(NC), NF_(NF), nonlinearity_(NC,NF){
is_first_ = true;
ipiv_ = new typename backend<ScalarType>::size_t[NC_+1];
Z = new ScalarType[NC_*NF_];
RZ = new ScalarType[NC_*NF_];
phi = new ScalarType[NC_*NF_];
psi = new ScalarType[NC_*NF_];
dweights = new ScalarType[NC_*NC_];
W = new ScalarType[NC_*NC_];
WLU = new ScalarType[NC_*NC_];
V = new ScalarType[NC_*NC_];
HV = new ScalarType[NC_*NC_];
WinvV = new ScalarType[NC_*NC_];
means_logp = new ScalarType[NC_];
first_signs = new int[NC_];
for(unsigned int c = 0 ; c < NC_ ; ++c){
ScalarType m2 = 0, m4 = 0;
for(unsigned int f = 0; f < NF_ ; f++){
ScalarType X = data_[c*NF_+f];
m2 += std::pow(X,2);
m4 += std::pow(X,4);
}
m2 = std::pow(1/(ScalarType)NF_*m2,2);
m4 = 1/(ScalarType)NF_*m4;
ScalarType k = m4/m2 - 3;
first_signs[c] = (k+0.02>0)?1:-1;
}
}
bool recompute_signs(){
bool sign_change = false;
for(unsigned int c = 0 ; c < NC_ ; ++c){
ScalarType m2 = 0, m4 = 0;
//ScalarType b = b_[c];
for(unsigned int f = 0; f < NF_ ; f++){
ScalarType X = Z[c*NF_+f];
m2 += std::pow(X,2);
m4 += std::pow(X,4);
}
m2 = std::pow(1/(ScalarType)NF_*m2,2);
m4 = 1/(ScalarType)NF_*m4;
ScalarType k = m4/m2 - 3;
int new_sign = (k+0.02>0)?1:-1;
sign_change |= (new_sign!=first_signs[c]);
first_signs[c] = new_sign;
}
return sign_change;
}
~ica_functor(){
delete[] ipiv_;
delete[] Z;
delete[] RZ;
delete[] phi;
delete[] psi;
delete[] dweights;
delete[] W;
delete[] WLU;
delete[] V;
delete[] HV;
delete[] WinvV;
delete[] means_logp;
}
void compute_Hv(ScalarType const * x, ScalarType const * v, ScalarType * Hv) const{
std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(WLU,x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(V, v,sizeof(ScalarType)*NC_*NC_);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,W,NC_,0,Z,NF_);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,V,NC_,0,RZ,NF_);
//Psi = dphi(Z).*RZ
nonlinearity_.compute_dphi(Z,first_signs,psi);
for(unsigned int c = 0 ; c < NC_ ; ++c)
for(unsigned int f = 0; f < NF_ ; ++f)
psi[c*NF_+f] *= RZ[c*NF_+f];
//HV = (inv(W)*V*inv(w))' + 1/n*Psi*X'
backend<ScalarType>::getrf(NC_,NC_,WLU,NC_,ipiv_);
backend<ScalarType>::getri(NC_,WLU,NC_,ipiv_);
backend<ScalarType>::gemm(Trans,Trans,NC_,NC_,NC_ ,1,WLU,NC_,V,NC_,0,WinvV,NC_);
backend<ScalarType>::gemm(NoTrans,Trans,NC_,NC_,NC_ ,1,WinvV,NC_,WLU,NC_,0,HV,NC_);
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,1/(ScalarType)NF_,data_,NF_,psi,NF_,1,HV,NC_);
//Copy back
for(std::size_t i = 0 ; i < NC_*NC_; ++i)
Hv[i] = HV[i];
}
void operator()(ScalarType const * x, ScalarType* value, ScalarType ** grad) const {
//Rerolls the variables into the appropriates datastructures
std::memcpy(W, x,sizeof(ScalarType)*NC_*NC_);
std::memcpy(WLU,W,sizeof(ScalarType)*NC_*NC_);
//z1 = W*data_;
backend<ScalarType>::gemm(NoTrans,NoTrans,NF_,NC_,NC_,1,data_,NF_,W,NC_,0,Z,NF_);
//phi = mean(mata.*abs(z2).^(mata-1).*sign(z2),2);
nonlinearity_.compute_means_logp(Z,first_signs,means_logp);
//LU Decomposition
backend<ScalarType>::getrf(NC_,NC_,WLU,NC_,ipiv_);
//det = prod(diag(WLU))
ScalarType absdet = 1;
for(std::size_t i = 0 ; i < NC_ ; ++i){
absdet*=std::abs(WLU[i*NC_+i]);
}
//H = log(abs(det(w))) + sum(means_logp);
ScalarType H = std::log(absdet);
for(std::size_t i = 0; i < NC_ ; ++i){
H+=means_logp[i];
}
if(value)
*value = -H;
if(grad){
nonlinearity_.compute_phi(Z,first_signs,phi);
//dweights = W^-T - 1/n*Phi*X'
backend<ScalarType>::getri(NC_,WLU,NC_,ipiv_);
for(std::size_t i = 0 ; i < NC_; ++i)
for(std::size_t j = 0 ; j < NC_; ++j)
dweights[i*NC_+j] = WLU[j*NC_+i];
backend<ScalarType>::gemm(Trans,NoTrans,NC_,NC_,NF_ ,-1/(ScalarType)NF_,data_,NF_,phi,NF_,1,dweights,NC_);
//Copy back
for(std::size_t i = 0 ; i < NC_*NC_; ++i)
(*grad)[i] = -dweights[i];
}
}
private:
ScalarType const * data_;
int * first_signs;
std::size_t NC_;
std::size_t NF_;
typename backend<ScalarType>::size_t *ipiv_;
//MiniBatch
ScalarType* Z;
ScalarType* RZ;
ScalarType* phi;
//Mixing
ScalarType* psi;
ScalarType* dweights;
ScalarType* V;
ScalarType* HV;
ScalarType* WinvV;
ScalarType* W;
ScalarType* WLU;
ScalarType* means_logp;
NonlinearityType nonlinearity_;
mutable bool is_first_;
};
options make_default_options(){
options opt;
opt.max_iter = 200;
opt.verbosity_level = 2;
opt.optimization_method = LBFGS;
return opt;
}
template<class ScalarType>
void inplace_linear_ica(ScalarType const * data, ScalarType * out, std::size_t NC, std::size_t DataNF, options const & opt, double* W, double* S){
typedef typename umintl_backend<ScalarType>::type BackendType;
typedef ica_functor<ScalarType, extended_infomax_ica<ScalarType> > IcaFunctorType;
std::size_t N = NC*NC;
std::size_t padsize = 4;
std::size_t NF=(DataNF%padsize==0)?DataNF:(DataNF/padsize)*padsize;
ScalarType * Sphere = new ScalarType[NC*NC];
ScalarType * Weights = new ScalarType[NC*NC];
//ScalarType * b = new ScalarType[NC];
ScalarType * X = new ScalarType[N];
std::memset(X,0,N*sizeof(ScalarType));
ScalarType * white_data = new ScalarType[NC*NF];
//Optimization Vector
//Solution vector
//Initial guess W_0 = I
//b_0 = 0
for(unsigned int i = 0 ; i < NC; ++i)
X[i*(NC+1)] = 1;
//Whiten Data
whiten<ScalarType>(NC, DataNF, NF, data,Sphere,white_data);
detail::shuffle(white_data,NC,NF);
IcaFunctorType objective(white_data,NF,NC);
umintl::minimizer<BackendType> minimizer;
if(opt.optimization_method==SD)
minimizer.direction = new umintl::steepest_descent<BackendType>();
else if(opt.optimization_method==LBFGS)
minimizer.direction = new umintl::quasi_newton<BackendType>(new umintl::lbfgs<BackendType>(16));
else if(opt.optimization_method==NCG)
minimizer.direction = new umintl::conjugate_gradient<BackendType>(new umintl::polak_ribiere<BackendType>());
else if(opt.optimization_method==BFGS)
minimizer.direction = new umintl::quasi_newton<BackendType>(new umintl::bfgs<BackendType>());
else if(opt.optimization_method==HESSIAN_FREE){
minimizer.direction = new umintl::truncated_newton<BackendType>(
umintl::hessian_free::options<BackendType>(30
, new umintl::hessian_free::hessian_vector_product_custom<BackendType,IcaFunctorType>(objective)));
//minimizer.direction = new umintl::truncated_newton<BackendType>();
}
minimizer.verbosity_level = opt.verbosity_level;
minimizer.max_iter = opt.max_iter;
minimizer.stopping_criterion = new umintl::gradient_treshold<BackendType>(1e-4);
do{
minimizer(X,objective,X,N);
}while(objective.recompute_signs());
//Copies into datastructures
std::memcpy(Weights, X,sizeof(ScalarType)*NC*NC);
//std::memcpy(b, X+NC*NC, sizeof(ScalarType)*NC);
//out = W*Sphere*data;
backend<ScalarType>::gemm(NoTrans,NoTrans,NF,NC,NC,1,data,DataNF,Sphere,NC,0,white_data,NF);
backend<ScalarType>::gemm(NoTrans,NoTrans,NF,NC,NC,1,white_data,NF,Weights,NC,0,out,NF);
for(std::size_t i = 0 ; i < NC ; ++i){
for(std::size_t j = 0 ; j < NC ; ++j){
if(W)
W[i*NC+j] = Weights[j*NC+i];
if(S)
S[i*NC+j] = Sphere[j*NC+i];
}
}
delete[] Weights;
//delete[] b;
delete[] X;
delete[] white_data;
}
template void inplace_linear_ica<float>(float const * data, float * out, std::size_t NC, std::size_t NF, curveica::options const & opt, double* Weights, double* Sphere);
template void inplace_linear_ica<double>(double const * data, double * out, std::size_t NC, std::size_t NF, curveica::options const & opt, double * Weights, double * Sphere);
}
<|endoftext|> |
<commit_before>#include <limits>
#include <algorithm>
#include <tr1/array>
#include <cstdlib>
#include "conversions.h"
#include "chars.h"
#include "ustringpiece.h"
#include "jsarray.h"
#include "jsobject.h"
#include "property.h"
#include "jsstring.h"
#include "context.h"
#include "class.h"
namespace iv {
namespace lv5 {
JSArray::JSArray(Context* ctx, std::size_t len)
: JSObject(),
vector_((len < detail::kMaxVectorSize) ? len : 4, JSEmpty),
map_(NULL),
dense_(true),
length_(len) {
JSObject::DefineOwnProperty(ctx, ctx->length_symbol(),
DataDescriptor(len,
PropertyDescriptor::WRITABLE),
false, ctx->error());
}
PropertyDescriptor JSArray::GetOwnProperty(Context* ctx, Symbol name) const {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return GetOwnPropertyWithIndex(ctx, index);
}
return JSObject::GetOwnProperty(ctx, name);
}
PropertyDescriptor JSArray::GetOwnPropertyWithIndex(Context* ctx,
uint32_t index) const {
if (detail::kMaxVectorSize > index) {
// this target included in vector (if dense array)
if (vector_.size() > index) {
const JSVal& val = vector_[index];
if (!val.IsEmpty()) {
// current is target
return DataDescriptor(val,
PropertyDescriptor::ENUMERABLE |
PropertyDescriptor::CONFIGURABLE |
PropertyDescriptor::WRITABLE);
} else if (dense_) {
// if dense array, target is undefined
return JSUndefined;
}
}
} else {
// target is index and included in map
if (map_) {
const Map::const_iterator it = map_->find(index);
if (it != map_->end()) {
// target is found
return DataDescriptor(it->second,
PropertyDescriptor::ENUMERABLE |
PropertyDescriptor::CONFIGURABLE |
PropertyDescriptor::WRITABLE);
} else if (dense_) {
// if target is not found and dense array,
// target is undefined
return JSUndefined;
}
} else if (dense_) {
// if map is none and dense array, target is undefined
return JSUndefined;
}
}
return JSObject::GetOwnProperty(ctx, ctx->InternIndex(index));
}
#define REJECT(str)\
do {\
if (th) {\
res->Report(Error::Type, str);\
}\
return false;\
} while (0)
bool JSArray::DefineOwnProperty(Context* ctx,
Symbol name,
const PropertyDescriptor& desc,
bool th,
Error* res) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return DefineOwnPropertyWithIndex(ctx, index, desc, th, res);
}
const Symbol length_symbol = ctx->length_symbol();
PropertyDescriptor old_len_desc_prop = GetOwnProperty(ctx, length_symbol);
DataDescriptor* const old_len_desc = old_len_desc_prop.AsDataDescriptor();
const JSVal& len_value = old_len_desc->value();
assert(len_value.IsNumber());
if (name == length_symbol) {
if (desc.IsDataDescriptor()) {
const DataDescriptor* const data = desc.AsDataDescriptor();
if (data->IsValueAbsent()) {
// changing attribute [[Writable]] or TypeError.
// [[Value]] not changed.
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
DataDescriptor new_len_desc(*data);
const double new_len_double = new_len_desc.value().ToNumber(ctx, res);
if (*res) {
return false;
}
// length must be uint32_t
const uint32_t new_len = core::DoubleToUInt32(new_len_double);
if (new_len != new_len_double) {
res->Report(Error::Range, "out of range");
return false;
}
new_len_desc.set_value(new_len);
uint32_t old_len = core::DoubleToUInt32(len_value.number());
if (*res) {
return false;
}
if (new_len >= old_len) {
return JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, th, res);
}
if (!old_len_desc->IsWritable()) {
REJECT("\"length\" not writable");
}
const bool new_writable =
new_len_desc.IsWritableAbsent() || new_len_desc.IsWritable();
new_len_desc.set_writable(true);
const bool succeeded = JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, th, res);
if (!succeeded) {
return false;
}
if (new_len < old_len) {
if (dense_) {
// dense array version
CompactionToLength(new_len);
} else if (old_len - new_len < (1 << 24)) {
while (new_len < old_len) {
old_len -= 1;
// see Eratta
const bool delete_succeeded = DeleteWithIndex(ctx, old_len, false, res);
if (*res) {
return false;
}
if (!delete_succeeded) {
new_len_desc.set_value(old_len + 1);
if (!new_writable) {
new_len_desc.set_writable(false);
}
JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, false, res);
if (*res) {
return false;
}
REJECT("shrink array failed");
}
}
} else {
using std::sort;
std::vector<Symbol> keys;
JSObject::GetOwnPropertyNames(ctx, &keys, JSObject::kIncludeNotEnumerable);
std::vector<uint32_t> ix;
for (std::vector<Symbol>::const_iterator it = keys.begin(),
last = keys.end(); it != last; ++it) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(*it), &index)) {
ix.push_back(index);
}
}
sort(ix.begin(), ix.end());
for (std::vector<uint32_t>::const_reverse_iterator it = ix.rbegin(),
last = ix.rend(); it != last; --it) {
if (*it < new_len) {
break;
}
const bool delete_succeeded = DeleteWithIndex(ctx, *it, false, res);
if (!delete_succeeded) {
const uint32_t result_len = *it + 1;
CompactionToLength(result_len);
new_len_desc.set_value(result_len);
if (!new_writable) {
new_len_desc.set_writable(false);
}
JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, false, res);
if (*res) {
return false;
}
REJECT("shrink array failed");
}
}
CompactionToLength(new_len);
}
}
if (!new_writable) {
JSObject::DefineOwnProperty(ctx, length_symbol,
DataDescriptor(
PropertyDescriptor::WRITABLE |
PropertyDescriptor::UNDEF_ENUMERABLE |
PropertyDescriptor::UNDEF_CONFIGURABLE),
false, res);
}
return true;
} else {
// length is not configurable
// so length is not changed
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
} else {
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
}
bool JSArray::DefineOwnPropertyWithIndex(Context* ctx,
uint32_t index,
const PropertyDescriptor& desc,
bool th,
Error* res) {
// array index
PropertyDescriptor old_len_desc_prop = GetOwnProperty(ctx,
ctx->length_symbol());
DataDescriptor* const old_len_desc = old_len_desc_prop.AsDataDescriptor();
const double old_len = old_len_desc->value().ToNumber(ctx, res);
if (*res) {
return false;
}
if (index >= old_len && !old_len_desc->IsWritable()) {
return false;
}
// define step
const bool descriptor_is_default_property = IsDefaultDescriptor(desc);
if (descriptor_is_default_property &&
(dense_ || JSObject::GetOwnProperty(ctx, ctx->InternIndex(index)).IsEmpty())) {
JSVal target;
if (desc.IsDataDescriptor()) {
target = desc.AsDataDescriptor()->value();
} else {
target = JSUndefined;
}
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
vector_[index] = target;
} else {
vector_.resize(index + 1, JSEmpty);
vector_[index] = target;
}
} else {
if (!map_) {
map_ = new (GC) Map();
}
(*map_)[index] = target;
}
} else {
const bool succeeded = JSObject::DefineOwnProperty(
ctx, ctx->InternIndex(index), desc, false, res);
if (*res) {
return false;
}
if (succeeded) {
dense_ = false;
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
vector_[index] = JSEmpty;
}
} else {
if (map_) {
const Map::iterator it = map_->find(index);
if (it != map_->end()) {
map_->erase(it);
}
}
}
} else {
REJECT("define own property failed");
}
}
if (index >= old_len) {
old_len_desc->set_value(index+1);
JSObject::DefineOwnProperty(ctx, ctx->length_symbol(),
*old_len_desc, false, res);
}
return true;
}
#undef REJECT
bool JSArray::Delete(Context* ctx, Symbol name, bool th, Error* res) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return DeleteWithIndex(ctx, index, th, res);
}
return JSObject::Delete(ctx, name, th, res);
}
bool JSArray::DeleteWithIndex(Context* ctx, uint32_t index, bool th, Error* res) {
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
JSVal& val = vector_[index];
if (!val.IsEmpty()) {
val = JSEmpty;
return true;
} else if (dense_) {
return true;
}
}
} else {
if (map_) {
const Map::iterator it = map_->find(index);
if (it != map_->end()) {
map_->erase(it);
return true;
} else if (dense_) {
return true;
}
} else if (dense_) {
return true;
}
}
return JSObject::Delete(ctx, ctx->InternIndex(index), th, res);
}
void JSArray::GetOwnPropertyNames(Context* ctx,
std::vector<Symbol>* vec,
EnumerationMode mode) const {
using std::find;
if (vec->empty()) {
uint32_t index = 0;
for (Vector::const_iterator it = vector_.begin(),
last = vector_.end(); it != last; ++it, ++index) {
if (!it->IsEmpty()) {
vec->push_back(ctx->InternIndex(index));
}
}
if (map_) {
for (Map::const_iterator it = map_->begin(),
last = map_->end(); it != last; ++it) {
if (!it->second.IsEmpty()) {
vec->push_back(ctx->InternIndex(it->first));
}
}
}
} else {
uint32_t index = 0;
for (Vector::const_iterator it = vector_.begin(),
last = vector_.end(); it != last; ++it, ++index) {
if (!it->IsEmpty()) {
const Symbol sym = ctx->InternIndex(index);
if (find(vec->begin(), vec->end(), sym) == vec->end()) {
vec->push_back(sym);
}
}
}
if (map_) {
for (Map::const_iterator it = map_->begin(),
last = map_->end(); it != last; ++it) {
if (!it->second.IsEmpty()) {
const Symbol sym = ctx->InternIndex(it->first);
if (find(vec->begin(), vec->end(), sym) == vec->end()) {
vec->push_back(sym);
}
}
}
}
}
JSObject::GetOwnPropertyNames(ctx, vec, mode);
}
JSArray* JSArray::New(Context* ctx) {
JSArray* const ary = new JSArray(ctx, 0);
const Class& cls = ctx->Cls("Array");
ary->set_class_name(cls.name);
ary->set_prototype(cls.prototype);
return ary;
}
JSArray* JSArray::New(Context* ctx, std::size_t n) {
JSArray* const ary = new JSArray(ctx, n);
const Class& cls = ctx->Cls("Array");
ary->set_class_name(cls.name);
ary->set_prototype(cls.prototype);
return ary;
}
JSArray* JSArray::NewPlain(Context* ctx) {
return new JSArray(ctx, 0);
}
bool JSArray::IsDefaultDescriptor(const PropertyDescriptor& desc) {
if (!(desc.IsEnumerable() || desc.IsEnumerableAbsent())) {
return false;
}
if (!(desc.IsConfigurable() || desc.IsConfigurableAbsent())) {
return false;
}
if (desc.IsAccessorDescriptor()) {
return false;
}
if (desc.IsDataDescriptor()) {
const DataDescriptor* const data = desc.AsDataDescriptor();
return data->IsWritable() || data->IsWritableAbsent();
}
return true;
}
void JSArray::CompactionToLength(uint32_t length) {
if (length > detail::kMaxVectorSize) {
if (map_) {
map_->erase(
map_->upper_bound(length - 1), map_->end());
}
} else {
if (map_) {
map_->clear();
}
if (vector_.size() > length) {
vector_.resize(length, JSEmpty);
}
}
}
} } // namespace iv::lv5
<commit_msg>change vector to set<commit_after>#include <limits>
#include <vector>
#include <set>
#include <algorithm>
#include <tr1/array>
#include <cstdlib>
#include "conversions.h"
#include "chars.h"
#include "ustringpiece.h"
#include "jsarray.h"
#include "jsobject.h"
#include "property.h"
#include "jsstring.h"
#include "context.h"
#include "class.h"
namespace iv {
namespace lv5 {
JSArray::JSArray(Context* ctx, std::size_t len)
: JSObject(),
vector_((len < detail::kMaxVectorSize) ? len : 4, JSEmpty),
map_(NULL),
dense_(true),
length_(len) {
JSObject::DefineOwnProperty(ctx, ctx->length_symbol(),
DataDescriptor(len,
PropertyDescriptor::WRITABLE),
false, ctx->error());
}
PropertyDescriptor JSArray::GetOwnProperty(Context* ctx, Symbol name) const {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return GetOwnPropertyWithIndex(ctx, index);
}
return JSObject::GetOwnProperty(ctx, name);
}
PropertyDescriptor JSArray::GetOwnPropertyWithIndex(Context* ctx,
uint32_t index) const {
if (detail::kMaxVectorSize > index) {
// this target included in vector (if dense array)
if (vector_.size() > index) {
const JSVal& val = vector_[index];
if (!val.IsEmpty()) {
// current is target
return DataDescriptor(val,
PropertyDescriptor::ENUMERABLE |
PropertyDescriptor::CONFIGURABLE |
PropertyDescriptor::WRITABLE);
} else if (dense_) {
// if dense array, target is undefined
return JSUndefined;
}
}
} else {
// target is index and included in map
if (map_) {
const Map::const_iterator it = map_->find(index);
if (it != map_->end()) {
// target is found
return DataDescriptor(it->second,
PropertyDescriptor::ENUMERABLE |
PropertyDescriptor::CONFIGURABLE |
PropertyDescriptor::WRITABLE);
} else if (dense_) {
// if target is not found and dense array,
// target is undefined
return JSUndefined;
}
} else if (dense_) {
// if map is none and dense array, target is undefined
return JSUndefined;
}
}
return JSObject::GetOwnProperty(ctx, ctx->InternIndex(index));
}
#define REJECT(str)\
do {\
if (th) {\
res->Report(Error::Type, str);\
}\
return false;\
} while (0)
bool JSArray::DefineOwnProperty(Context* ctx,
Symbol name,
const PropertyDescriptor& desc,
bool th,
Error* res) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return DefineOwnPropertyWithIndex(ctx, index, desc, th, res);
}
const Symbol length_symbol = ctx->length_symbol();
PropertyDescriptor old_len_desc_prop = GetOwnProperty(ctx, length_symbol);
DataDescriptor* const old_len_desc = old_len_desc_prop.AsDataDescriptor();
const JSVal& len_value = old_len_desc->value();
assert(len_value.IsNumber());
if (name == length_symbol) {
if (desc.IsDataDescriptor()) {
const DataDescriptor* const data = desc.AsDataDescriptor();
if (data->IsValueAbsent()) {
// changing attribute [[Writable]] or TypeError.
// [[Value]] not changed.
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
DataDescriptor new_len_desc(*data);
const double new_len_double = new_len_desc.value().ToNumber(ctx, res);
if (*res) {
return false;
}
// length must be uint32_t
const uint32_t new_len = core::DoubleToUInt32(new_len_double);
if (new_len != new_len_double) {
res->Report(Error::Range, "out of range");
return false;
}
new_len_desc.set_value(new_len);
uint32_t old_len = core::DoubleToUInt32(len_value.number());
if (*res) {
return false;
}
if (new_len >= old_len) {
return JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, th, res);
}
if (!old_len_desc->IsWritable()) {
REJECT("\"length\" not writable");
}
const bool new_writable =
new_len_desc.IsWritableAbsent() || new_len_desc.IsWritable();
new_len_desc.set_writable(true);
const bool succeeded = JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, th, res);
if (!succeeded) {
return false;
}
if (new_len < old_len) {
if (dense_) {
// dense array version
CompactionToLength(new_len);
} else if (old_len - new_len < (1 << 24)) {
while (new_len < old_len) {
old_len -= 1;
// see Eratta
const bool delete_succeeded = DeleteWithIndex(ctx, old_len, false, res);
if (*res) {
return false;
}
if (!delete_succeeded) {
new_len_desc.set_value(old_len + 1);
if (!new_writable) {
new_len_desc.set_writable(false);
}
JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, false, res);
if (*res) {
return false;
}
REJECT("shrink array failed");
}
}
} else {
std::vector<Symbol> keys;
JSObject::GetOwnPropertyNames(ctx, &keys, JSObject::kIncludeNotEnumerable);
std::set<uint32_t> ix;
for (std::vector<Symbol>::const_iterator it = keys.begin(),
last = keys.end(); it != last; ++it) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(*it), &index)) {
ix.insert(index);
}
}
for (std::set<uint32_t>::const_reverse_iterator it = ix.rbegin(),
last = ix.rend(); it != last; --it) {
if (*it < new_len) {
break;
}
const bool delete_succeeded = DeleteWithIndex(ctx, *it, false, res);
if (!delete_succeeded) {
const uint32_t result_len = *it + 1;
CompactionToLength(result_len);
new_len_desc.set_value(result_len);
if (!new_writable) {
new_len_desc.set_writable(false);
}
JSObject::DefineOwnProperty(ctx, length_symbol,
new_len_desc, false, res);
if (*res) {
return false;
}
REJECT("shrink array failed");
}
}
CompactionToLength(new_len);
}
}
if (!new_writable) {
JSObject::DefineOwnProperty(ctx, length_symbol,
DataDescriptor(
PropertyDescriptor::WRITABLE |
PropertyDescriptor::UNDEF_ENUMERABLE |
PropertyDescriptor::UNDEF_CONFIGURABLE),
false, res);
}
return true;
} else {
// length is not configurable
// so length is not changed
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
} else {
return JSObject::DefineOwnProperty(ctx, name, desc, th, res);
}
}
bool JSArray::DefineOwnPropertyWithIndex(Context* ctx,
uint32_t index,
const PropertyDescriptor& desc,
bool th,
Error* res) {
// array index
PropertyDescriptor old_len_desc_prop = GetOwnProperty(ctx,
ctx->length_symbol());
DataDescriptor* const old_len_desc = old_len_desc_prop.AsDataDescriptor();
const double old_len = old_len_desc->value().ToNumber(ctx, res);
if (*res) {
return false;
}
if (index >= old_len && !old_len_desc->IsWritable()) {
return false;
}
// define step
const bool descriptor_is_default_property = IsDefaultDescriptor(desc);
if (descriptor_is_default_property &&
(dense_ || JSObject::GetOwnProperty(ctx, ctx->InternIndex(index)).IsEmpty())) {
JSVal target;
if (desc.IsDataDescriptor()) {
target = desc.AsDataDescriptor()->value();
} else {
target = JSUndefined;
}
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
vector_[index] = target;
} else {
vector_.resize(index + 1, JSEmpty);
vector_[index] = target;
}
} else {
if (!map_) {
map_ = new (GC) Map();
}
(*map_)[index] = target;
}
} else {
const bool succeeded = JSObject::DefineOwnProperty(
ctx, ctx->InternIndex(index), desc, false, res);
if (*res) {
return false;
}
if (succeeded) {
dense_ = false;
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
vector_[index] = JSEmpty;
}
} else {
if (map_) {
const Map::iterator it = map_->find(index);
if (it != map_->end()) {
map_->erase(it);
}
}
}
} else {
REJECT("define own property failed");
}
}
if (index >= old_len) {
old_len_desc->set_value(index+1);
JSObject::DefineOwnProperty(ctx, ctx->length_symbol(),
*old_len_desc, false, res);
}
return true;
}
#undef REJECT
bool JSArray::Delete(Context* ctx, Symbol name, bool th, Error* res) {
uint32_t index;
if (core::ConvertToUInt32(ctx->GetContent(name), &index)) {
return DeleteWithIndex(ctx, index, th, res);
}
return JSObject::Delete(ctx, name, th, res);
}
bool JSArray::DeleteWithIndex(Context* ctx, uint32_t index, bool th, Error* res) {
if (detail::kMaxVectorSize > index) {
if (vector_.size() > index) {
JSVal& val = vector_[index];
if (!val.IsEmpty()) {
val = JSEmpty;
return true;
} else if (dense_) {
return true;
}
}
} else {
if (map_) {
const Map::iterator it = map_->find(index);
if (it != map_->end()) {
map_->erase(it);
return true;
} else if (dense_) {
return true;
}
} else if (dense_) {
return true;
}
}
return JSObject::Delete(ctx, ctx->InternIndex(index), th, res);
}
void JSArray::GetOwnPropertyNames(Context* ctx,
std::vector<Symbol>* vec,
EnumerationMode mode) const {
using std::find;
if (vec->empty()) {
uint32_t index = 0;
for (Vector::const_iterator it = vector_.begin(),
last = vector_.end(); it != last; ++it, ++index) {
if (!it->IsEmpty()) {
vec->push_back(ctx->InternIndex(index));
}
}
if (map_) {
for (Map::const_iterator it = map_->begin(),
last = map_->end(); it != last; ++it) {
if (!it->second.IsEmpty()) {
vec->push_back(ctx->InternIndex(it->first));
}
}
}
} else {
uint32_t index = 0;
for (Vector::const_iterator it = vector_.begin(),
last = vector_.end(); it != last; ++it, ++index) {
if (!it->IsEmpty()) {
const Symbol sym = ctx->InternIndex(index);
if (find(vec->begin(), vec->end(), sym) == vec->end()) {
vec->push_back(sym);
}
}
}
if (map_) {
for (Map::const_iterator it = map_->begin(),
last = map_->end(); it != last; ++it) {
if (!it->second.IsEmpty()) {
const Symbol sym = ctx->InternIndex(it->first);
if (find(vec->begin(), vec->end(), sym) == vec->end()) {
vec->push_back(sym);
}
}
}
}
}
JSObject::GetOwnPropertyNames(ctx, vec, mode);
}
JSArray* JSArray::New(Context* ctx) {
JSArray* const ary = new JSArray(ctx, 0);
const Class& cls = ctx->Cls("Array");
ary->set_class_name(cls.name);
ary->set_prototype(cls.prototype);
return ary;
}
JSArray* JSArray::New(Context* ctx, std::size_t n) {
JSArray* const ary = new JSArray(ctx, n);
const Class& cls = ctx->Cls("Array");
ary->set_class_name(cls.name);
ary->set_prototype(cls.prototype);
return ary;
}
JSArray* JSArray::NewPlain(Context* ctx) {
return new JSArray(ctx, 0);
}
bool JSArray::IsDefaultDescriptor(const PropertyDescriptor& desc) {
if (!(desc.IsEnumerable() || desc.IsEnumerableAbsent())) {
return false;
}
if (!(desc.IsConfigurable() || desc.IsConfigurableAbsent())) {
return false;
}
if (desc.IsAccessorDescriptor()) {
return false;
}
if (desc.IsDataDescriptor()) {
const DataDescriptor* const data = desc.AsDataDescriptor();
return data->IsWritable() || data->IsWritableAbsent();
}
return true;
}
void JSArray::CompactionToLength(uint32_t length) {
if (length > detail::kMaxVectorSize) {
if (map_) {
map_->erase(
map_->upper_bound(length - 1), map_->end());
}
} else {
if (map_) {
map_->clear();
}
if (vector_.size() > length) {
vector_.resize(length, JSEmpty);
}
}
}
} } // namespace iv::lv5
<|endoftext|> |
<commit_before>#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>
class CMailer : public CModule {
protected:
CUser *user;
public:
MODCONSTRUCTOR(CMailer) {
user = GetUser();
}
virtual ~CMailer() {}
virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {
CString user_nick = user->GetNick().AsLower();
if (user->IsUserAttached()){
return CONTINUE;
}
size_t found = sMessage.AsLower().find(user_nick);
if (found!=string::npos){
PutModule("Sending");
FILE *email= popen("mail -s 'IRC Notification' [email protected]", "w");
if (!email){
PutModule("Problems with pipe");
return CONTINUE;
}
CString message = "<" + Nick.GetNick() + "> " + sMessage + "\n\n";
PutModule(message);
fprintf(email, "%s", (char*) message.c_str());
pclose(email);
PutModule("Sent");
}
return CONTINUE;
}
bool send_notification(){
return false;
}
};
MODULEDEFS(CMailer, "To be used to send mentions as an email")
<commit_msg>Refactored the code to make it a bit easier to work with while adding basic rate limiting and the ability to change some of the settings<commit_after>#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>
class CMailerTimer: public CTimer {
public:
CMailerTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CMailerTimer() {}
protected:
virtual void RunJob();
};
class CMailer : public CModule {
protected:
CUser *user;
list<CString> messages_list;
CString notification_subject;
CString notification_email;
unsigned int max_notifications;
public:
MODCONSTRUCTOR(CMailer) {
user = GetUser();
}
virtual ~CMailer() {}
virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {
AddTimer(new CMailerTimer(this, 1200, 0, "Mail", "Send emails every 20 mins."));
this->max_notifications = 50;
PutModule("Please tell me what email address you want notifications to be sent to with 'email <address>'");
return true;
}
virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {
Handle(Nick, Channel.GetName(), sMessage);
return CONTINUE;
}
virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {
Handle(Nick, "PRIVATE", sMessage);
return CONTINUE;
}
virtual void OnIRCConnected() {
PutModule("Connected");
}
void OnModCommand(const CString& command)
{
VCString tokens;
int token_count = command.Split(" ", tokens, false);
if (token_count < 1)
{
return;
}
CString action = tokens[0].AsLower();
if (action == "email"){
if (token_count < 2)
{
PutModule("Usage: email <email address>");
return;
}
this->notification_email = tokens[1].AsLower();
PutModule("email address set");
} else if (action == "subject"){
if (token_count < 2)
{
PutModule("Usage: subject <email subject>");
return;
}
this->notification_subject = tokens[1].AsLower();
PutModule("email subject set.");
} else if (action == "help") {
PutModule("View the documentation at https://github.com/d0ugal/znc_mailer/blob/master/README");
} else {
PutModule("Error: invalid command, try `help`");
}
}
void Handle(CNick& Nick, const CString& location, CString& sMessage){
if (SendNotification(Nick, sMessage) || location == "PRIVATE"){
CString message = "<" + location + ":" + Nick.GetNick() + "> " + sMessage + "\n\n";
messages_list.push_front(message);
if (messages_list.size() > this->max_notifications){
messages_list.pop_back();
}
}
}
bool SendNotification(CNick& Nick, CString& sMessage){
if (user->IsUserAttached()){
return false;
}
CString UserNick = user->GetNick().AsLower();
size_t found = sMessage.AsLower().find(UserNick);
if (found!=string::npos){
return true;
} else {
return false;
}
}
void BatchSend(){
if (user->IsUserAttached()){
return;
}
list<CString>::iterator it;
CString message;
if (messages_list.size() <= 0){
return;
}
for ( it=messages_list.begin() ; it != messages_list.end(); it++ ){
message = message + *it;
}
Send(message);
messages_list.erase(messages_list.begin(),messages_list.end());
}
void Send(CString& sMessage){
PutModule("Sending");
FILE *email= popen(("mail -s '" + this->notification_email + "' " + this->notification_subject).c_str(), "w");
if (!email){
PutModule("Problems with pipe");
return;
}
fprintf(email, "%s", (char*) sMessage.c_str());
pclose(email);
PutModule("Sent");
}
};
void CMailerTimer::RunJob(){
CMailer *p = (CMailer *)m_pModule;
p->BatchSend();
}
MODULEDEFS(CMailer, "To be used to send mentions as an email")
<|endoftext|> |
<commit_before>#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
Search::Search(const Board& board, bool logUci) {
_logUci = logUci;
_board = board;
}
void Search::perform(int depth) {
_rootMax(_board, depth);
MoveBoardList pv = _getPv(_board);
if (_logUci) {
_logUciInfo(pv, depth, _bestMove, _bestScore);
}
}
void Search::_logUciInfo(const MoveBoardList& pv, int depth, CMove bestMove, int bestScore) {
std::string pvString;
for(auto moveBoard : pv) {
pvString += moveBoard.first.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
MoveBoardList Search::_getPv(const Board& board) {
int bestScore = INF;
MoveBoard best;
bool foundBest = false;
for (auto moveBoard : MoveGen(board).getLegalMoves()) {
Board movedBoard = moveBoard.second;
ZKey movedZKey = movedBoard.getZKey();
if (_tt.contains(movedZKey) && _tt.getFlag(movedZKey) == TranspTable::EXACT && _tt.getScore(movedZKey) < bestScore) {
foundBest = true;
bestScore = _tt.getScore(movedZKey);
best = moveBoard;
}
}
if (!foundBest) {
return MoveBoardList();
} else {
MoveBoardList pvList = _getPv(best.second);
pvList.insert(pvList.begin(), best);
return pvList;
}
}
CMove Search::getBestMove() {
return _bestMove;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
int bestScore = -INF;
int currScore;
CMove bestMove;
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
currScore = -_negaMax(movedBoard, depth-1, -INF, -bestScore);
if (currScore > bestScore) {
bestMove = move;
bestScore = currScore;
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & CMove::NULL_MOVE) {
bestMove = legalMoves.at(0).first;
}
_tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = bestScore;
}
void Search::_orderMoves(MoveBoardList& moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
ZKey aKey = a.second.getZKey();
ZKey bKey = b.second.getZKey();
int aScore = _tt.contains(aKey) ? _tt.getScore(aKey) : -INF;
int bScore = _tt.contains(bKey) ? _tt.getScore(bKey) : -INF;
return aScore < bScore;
});
}
void Search::_orderMovesQSearch(MoveBoardList & moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
bool aIsCapture = a.first.getFlags() & CMove::CAPTURE;
bool bIsCapture = b.first.getFlags() & CMove::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
// MVV/LVA
int aPieceValue = _getPieceValue(a.first.getPieceType());
int bPieceValue = _getPieceValue(b.first.getPieceType());
int aCaptureValue = _getPieceValue(a.first.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.first.getCapturedPieceType());
return (aCaptureValue - aPieceValue) > (bCaptureValue - bPieceValue);
}
});
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta) {
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
}
if (alpha > beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
_tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT);
return -INF;
}
// Eval if depth is 0
if (depth == 0) {
int score = _qSearch(board, alpha, beta);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
_orderMoves(legalMoves);
int bestScore = -INF;
for (auto moveBoard : legalMoves) {
Board movedBoard = moveBoard.second;
bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha));
alpha = std::max(alpha, bestScore);
if (alpha > beta) {
break;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (bestScore < alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else if (bestScore >= beta) {
flag = TranspTable::LOWER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, bestScore, depth, flag);
return bestScore;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
return -INF;
}
_orderMovesQSearch(legalMoves);
int standPat = Eval(board, board.getActivePlayer()).getScore();
// If node is quiet, just return eval
if (!(legalMoves.at(0).first.getFlags() & CMove::CAPTURE)) {
return standPat;
}
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
if ((move.getFlags() & CMove::CAPTURE) == 0) {
break;
}
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
<commit_msg>Check for stalemate in _qSearch to avoid out of bounds crash<commit_after>#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
Search::Search(const Board& board, bool logUci) {
_logUci = logUci;
_board = board;
}
void Search::perform(int depth) {
_rootMax(_board, depth);
MoveBoardList pv = _getPv(_board);
if (_logUci) {
_logUciInfo(pv, depth, _bestMove, _bestScore);
}
}
void Search::_logUciInfo(const MoveBoardList& pv, int depth, CMove bestMove, int bestScore) {
std::string pvString;
for(auto moveBoard : pv) {
pvString += moveBoard.first.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
MoveBoardList Search::_getPv(const Board& board) {
int bestScore = INF;
MoveBoard best;
bool foundBest = false;
for (auto moveBoard : MoveGen(board).getLegalMoves()) {
Board movedBoard = moveBoard.second;
ZKey movedZKey = movedBoard.getZKey();
if (_tt.contains(movedZKey) && _tt.getFlag(movedZKey) == TranspTable::EXACT && _tt.getScore(movedZKey) < bestScore) {
foundBest = true;
bestScore = _tt.getScore(movedZKey);
best = moveBoard;
}
}
if (!foundBest) {
return MoveBoardList();
} else {
MoveBoardList pvList = _getPv(best.second);
pvList.insert(pvList.begin(), best);
return pvList;
}
}
CMove Search::getBestMove() {
return _bestMove;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
int bestScore = -INF;
int currScore;
CMove bestMove;
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
currScore = -_negaMax(movedBoard, depth-1, -INF, -bestScore);
if (currScore > bestScore) {
bestMove = move;
bestScore = currScore;
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & CMove::NULL_MOVE) {
bestMove = legalMoves.at(0).first;
}
_tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = bestScore;
}
void Search::_orderMoves(MoveBoardList& moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
ZKey aKey = a.second.getZKey();
ZKey bKey = b.second.getZKey();
int aScore = _tt.contains(aKey) ? _tt.getScore(aKey) : -INF;
int bScore = _tt.contains(bKey) ? _tt.getScore(bKey) : -INF;
return aScore < bScore;
});
}
void Search::_orderMovesQSearch(MoveBoardList & moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
bool aIsCapture = a.first.getFlags() & CMove::CAPTURE;
bool bIsCapture = b.first.getFlags() & CMove::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
// MVV/LVA
int aPieceValue = _getPieceValue(a.first.getPieceType());
int bPieceValue = _getPieceValue(b.first.getPieceType());
int aCaptureValue = _getPieceValue(a.first.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.first.getCapturedPieceType());
return (aCaptureValue - aPieceValue) > (bCaptureValue - bPieceValue);
}
});
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta) {
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
}
if (alpha > beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
_tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT);
return -INF;
}
// Eval if depth is 0
if (depth == 0) {
int score = _qSearch(board, alpha, beta);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
_orderMoves(legalMoves);
int bestScore = -INF;
for (auto moveBoard : legalMoves) {
Board movedBoard = moveBoard.second;
bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha));
alpha = std::max(alpha, bestScore);
if (alpha > beta) {
break;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (bestScore < alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else if (bestScore >= beta) {
flag = TranspTable::LOWER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, bestScore, depth, flag);
return bestScore;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
// Check for checkmate / stalemate
if (legalMoves.size() == 0) {
if (board.colorIsInCheck(board.getActivePlayer())) { // Checkmate
return -INF;
} else { // Stalemate
return 0;
}
}
_orderMovesQSearch(legalMoves);
int standPat = Eval(board, board.getActivePlayer()).getScore();
// If node is quiet, just return eval
if (!(legalMoves.at(0).first.getFlags() & CMove::CAPTURE)) {
return standPat;
}
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
if ((move.getFlags() & CMove::CAPTURE) == 0) {
break;
}
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
<|endoftext|> |
<commit_before>#include "solver.h"
#include <map>
#include <vector>
// -----------------------------------------------------------------------------
cyclus::Solver::Solver() {
index_ = std::map<cyclus::VariablePtr, int>();
}
// -----------------------------------------------------------------------------
void cyclus::Solver::PopulateIndices(
std::vector<cyclus::VariablePtr>& variables) {
for (int i = 0; i < variables.size(); i++) {
index_[variables.at(i)] = i;
}
}
<commit_msg>put solver impl under cyclus namespace<commit_after>#include "solver.h"
#include <map>
#include <vector>
namespace cyclus {
// -----------------------------------------------------------------------------
Solver::Solver() {
index_ = std::map<VariablePtr, int>();
}
// -----------------------------------------------------------------------------
void Solver::PopulateIndices(std::vector<VariablePtr>& variables) {
for (int i = 0; i < variables.size(); i++) {
index_[variables.at(i)] = i;
}
}
} // namespace cyclus
<|endoftext|> |
<commit_before>#include "sound.hpp"
#include "oddlib/audio/SequencePlayer.h"
#include "core/audiobuffer.hpp"
#include "logger.hpp"
#include "resourcemapper.hpp"
#include "audioconverter.hpp"
#include "alive_version.h"
SoundCache::SoundCache(OSBaseFileSystem& fs)
: mFs(fs)
{
}
void SoundCache::Sync()
{
mSoundDataCache.clear();
bool ok = false;
std::string versionFile = "{CacheDir}/CacheVersion.txt";
if (mFs.FileExists(versionFile))
{
if (mFs.Open(versionFile)->LoadAllToString() == ALIVE_VERSION)
{
ok = true;
}
}
if (!ok)
{
DeleteAll();
}
}
void SoundCache::DeleteAll()
{
TRACE_ENTRYEXIT;
// Delete *.wav from {CacheDir}/disk
std::string dirName = mFs.ExpandPath("{CacheDir}");
const auto wavFiles = mFs.EnumerateFiles(dirName, "*.wav");
for (const auto& wavFile : wavFiles)
{
mFs.DeleteFile(dirName + "/" + wavFile);
}
// Remove from memory
mSoundDataCache.clear();
// Update cache version marker to current
const std::string fileName = mFs.ExpandPath("{CacheDir}/CacheVersion.txt");
Oddlib::FileStream versionFile(fileName, Oddlib::IStream::ReadMode::ReadWrite);
versionFile.Write(std::string(ALIVE_VERSION));
}
bool SoundCache::ExistsInMemoryCache(const std::string& name) const
{
return mSoundDataCache.find(name) != std::end(mSoundDataCache);
}
class WavSound : public ISound
{
public:
WavSound(const std::string& name, std::shared_ptr<std::vector<u8>>& data)
: mName(name), mData(data)
{
memcpy(&mHeader.mData, data->data(), sizeof(mHeader.mData));
mOffsetInBytes = sizeof(mHeader.mData);
}
virtual void Load() override { }
virtual void DebugUi() override {}
virtual void Play(f32* stream, u32 len) override
{
u32 kLenInBytes = len * sizeof(f32);
// Handle the case where the audio call back wants N data but we only have N-X left
if (mOffsetInBytes + kLenInBytes > mData->size())
{
kLenInBytes = mData->size() - mOffsetInBytes;
}
const f32* src = reinterpret_cast<const f32*>(mData->data() + mOffsetInBytes);
for (u32 i = 0; i < kLenInBytes/sizeof(f32); i++)
{
stream[i] += src[i];
}
mOffsetInBytes += kLenInBytes;
}
virtual bool AtEnd() const override
{
return mOffsetInBytes >= mData->size();
}
virtual void Restart() override
{
mOffsetInBytes = sizeof(mHeader.mData);
}
virtual void Update() override { }
virtual const std::string& Name() const override { return mName; }
private:
size_t mOffsetInBytes = 0;
std::string mName;
std::shared_ptr<std::vector<u8>> mData;
WavHeader mHeader;
};
std::unique_ptr<ISound> SoundCache::GetCached(const std::string& name)
{
auto it = mSoundDataCache.find(name);
if (it != std::end(mSoundDataCache))
{
return std::make_unique<WavSound>(name, it->second);
}
return nullptr;
}
void SoundCache::AddToMemoryAndDiskCache(ISound& sound)
{
const std::string fileName = mFs.ExpandPath("{CacheDir}/" + sound.Name() + ".wav");
// TODO: mod files that are already wav shouldn't be converted
sound.Load();
AudioConverter::Convert<WavEncoder>(sound, fileName.c_str());
auto stream = mFs.Open(fileName);
mSoundDataCache[sound.Name()] = std::make_shared<std::vector<u8>>(Oddlib::IStream::ReadAll(*stream));
}
bool SoundCache::AddToMemoryCacheFromDiskCache(const std::string& name)
{
std::string fileName = mFs.ExpandPath("{CacheDir}/" + name + ".wav");
if (mFs.FileExists(fileName))
{
auto stream = mFs.Open(fileName);
mSoundDataCache[name] = std::make_shared<std::vector<u8>>(Oddlib::IStream::ReadAll(*stream));
return true;
}
return false;
}
void SoundCache::RemoveFromMemoryCache(const std::string& name)
{
auto it = mSoundDataCache.find(name);
if (it != std::end(mSoundDataCache))
{
mSoundDataCache.erase(it);
}
}
// ====================================================================
void Sound::PlaySoundScript(const char* soundName)
{
auto ret = PlaySound(soundName, nullptr, true, true, true);
if (ret)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(ret));
}
}
std::unique_ptr<ISound> Sound::PlaySound(const char* soundName, const char* explicitSoundBankName, bool useMusicRec, bool useSfxRec, bool useCache)
{
if (useCache)
{
std::unique_ptr<ISound> pSound = mCache.GetCached(soundName);
if (pSound)
{
LOG_INFO("Play sound cached: " << soundName);
}
else
{
LOG_ERROR("Cached sound not found: " << soundName);
}
return pSound;
}
else
{
std::unique_ptr<ISound> pSound = mLocator.LocateSound(soundName, explicitSoundBankName, useMusicRec, useSfxRec);
if (pSound)
{
LOG_INFO("Play sound: " << soundName);
pSound->Load();
}
else
{
LOG_ERROR("Sound: " << soundName << " not found");
}
return pSound;
}
}
void Sound::SetTheme(const char* themeName)
{
mAmbiance = nullptr;
mMusicTrack = nullptr;
const MusicTheme* newTheme = mLocator.LocateSoundTheme(themeName);
// Remove current musics from in memory cache
if (mActiveTheme)
{
CacheActiveTheme(false);
}
mActiveTheme = newTheme;
// Add new musics to in memory cache
if (mActiveTheme)
{
CacheActiveTheme(true);
}
else
{
LOG_ERROR("Music theme " << themeName << " was not found");
}
}
void Sound::CacheMemoryResidentSounds()
{
TRACE_ENTRYEXIT;
// initial one time sync
mCache.Sync();
const std::vector<SoundResource>& resources = mLocator.GetSoundResources();
for (const SoundResource& resource : resources)
{
if (resource.mIsCacheResident)
{
CacheSound(resource.mResourceName);
}
}
}
void Sound::CacheActiveTheme(bool add)
{
for (auto& entry : mActiveTheme->mEntries)
{
for (auto& e : entry.second)
{
if (add)
{
CacheSound(e.mMusicName);
}
else
{
mCache.RemoveFromMemoryCache(e.mMusicName);
}
}
}
}
void Sound::CacheSound(const std::string& name)
{
if (mCache.ExistsInMemoryCache(name))
{
// Already in memory
return;
}
if (mCache.AddToMemoryCacheFromDiskCache(name))
{
// Already on disk and now added to in memory cache
return;
}
std::unique_ptr<ISound> pSound = mLocator.LocateSound(name.c_str(), nullptr, true, true);
if (pSound)
{
// Write into disk cache and then load from disk cache into memory cache
mCache.AddToMemoryAndDiskCache(*pSound);
}
}
void Sound::HandleEvent(const char* eventName)
{
// TODO: Need quarter beat transition in some cases
EnsureAmbiance();
if (strcmp(eventName, "AMBIANCE") == 0)
{
mMusicTrack = nullptr;
return;
}
auto ret = PlayThemeEntry(eventName);
if (ret)
{
mMusicTrack = std::move(ret);
}
}
std::unique_ptr<ISound> Sound::PlayThemeEntry(const char* entryName)
{
if (mActiveTheme)
{
mActiveThemeEntry.SetMusicThemeEntry(mActiveTheme->FindEntry(entryName));
const MusicThemeEntry* entry = mActiveThemeEntry.Entry();
if (entry)
{
return PlaySound(entry->mMusicName.c_str(), nullptr, true, true, true);
}
}
return nullptr;
}
void Sound::EnsureAmbiance()
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (!mAmbiance)
{
mAmbiance = PlayThemeEntry("AMBIANCE");
}
}
// Audio thread context
bool Sound::Play(f32* stream, u32 len)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (mAmbiance)
{
mAmbiance->Play(stream, len);
}
if (mMusicTrack)
{
mMusicTrack->Play(stream, len);
}
for (auto& player : mSoundPlayers)
{
player->Play(stream, len);
}
return false;
}
/*static*/ void Sound::RegisterScriptBindings()
{
Sqrat::Class<Sound, Sqrat::NoConstructor<Sound>> c(Sqrat::DefaultVM::Get(), "Sound");
c.Func("PlaySoundEffect", &Sound::PlaySoundScript);
c.Func("SetTheme", &Sound::SetTheme);
Sqrat::RootTable().Bind("Sound", c);
}
Sound::Sound(IAudioController& audioController, ResourceLocator& locator, OSBaseFileSystem& fs)
: mAudioController(audioController), mLocator(locator), mCache(fs), mScriptInstance("gSound", this)
{
mAudioController.AddPlayer(this);
}
Sound::~Sound()
{
// Ensure the audio call back stops at this point else will be
// calling back into freed objects
SDL_AudioQuit();
mAudioController.RemovePlayer(this);
}
void Sound::Update()
{
if (Debugging().mBrowserUi.soundBrowserOpen)
{
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (!mSoundPlayers.empty())
{
mSoundPlayers[0]->DebugUi();
}
if (ImGui::Begin("Active SEQs"))
{
if (mAmbiance)
{
ImGui::Text("Ambiance: %s", mAmbiance->Name().c_str());
}
if (mMusicTrack)
{
ImGui::Text("Music: %s", mMusicTrack->Name().c_str());
}
int i = 0;
for (auto& player : mSoundPlayers)
{
i++;
if (ImGui::Button((std::to_string(i) + player->Name()).c_str()))
{
// TODO: Kill whatever this SEQ is
}
}
}
ImGui::End();
}
SoundBrowserUi();
}
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
for (auto it = mSoundPlayers.begin(); it != mSoundPlayers.end();)
{
if ((*it)->AtEnd())
{
it = mSoundPlayers.erase(it);
}
else
{
it++;
}
}
if (mAmbiance)
{
mAmbiance->Update();
if (mAmbiance->AtEnd())
{
mAmbiance->Restart();
}
}
if (mMusicTrack)
{
mMusicTrack->Update();
if (mMusicTrack->AtEnd())
{
if (mActiveThemeEntry.ToNextEntry())
{
mMusicTrack = PlaySound(mActiveThemeEntry.Entry()->mMusicName.c_str(), nullptr, true, true, true);
}
else
{
mMusicTrack = nullptr;
}
}
}
for (auto& player : mSoundPlayers)
{
player->Update();
}
}
static const char* kMusicEvents[] =
{
"AMBIANCE",
"BASE_LINE",
"CRITTER_ATTACK",
"CRITTER_PATROL",
"SLIG_ATTACK",
"SLIG_PATROL",
"SLIG_POSSESSED",
};
void Sound::SoundBrowserUi()
{
ImGui::Begin("Sound list");
static const SoundResource* selected = nullptr;
// left
ImGui::BeginChild("left pane", ImVec2(200, 0), true);
{
for (const SoundResource& soundInfo : mLocator.GetSoundResources())
{
if (ImGui::Selectable(soundInfo.mResourceName.c_str()))
{
selected = &soundInfo;
}
}
ImGui::EndChild();
}
ImGui::SameLine();
// right
ImGui::BeginGroup();
{
ImGui::BeginChild("item view");
{
if (selected)
{
ImGui::TextWrapped("Resource name: %s", selected->mResourceName.c_str());
ImGui::Separator();
ImGui::TextWrapped("Comment: %s", selected->mComment.empty() ? "(none)" : selected->mComment.c_str());
ImGui::Separator();
ImGui::TextWrapped("Is memory resident: %s", selected->mIsCacheResident ? "true" : "false");
ImGui::TextWrapped("Is cached: %s", mCache.ExistsInMemoryCache(selected->mResourceName) ? "true" : "false");
static bool bUseCache = false;
ImGui::Checkbox("Use cache", &bUseCache);
const bool bHasMusic = !selected->mMusic.mSoundBanks.empty();
const bool bHasSample = !selected->mSoundEffect.mSoundBanks.empty();
if (bHasMusic)
{
if (ImGui::CollapsingHeader("SEQs"))
{
for (const std::string& sb : selected->mMusic.mSoundBanks)
{
if (ImGui::Selectable(sb.c_str()))
{
auto player = PlaySound(selected->mResourceName.c_str(), sb.c_str(), true, false, bUseCache);
if (player)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(player));
}
}
}
}
}
if (bHasSample)
{
if (ImGui::CollapsingHeader("Samples"))
{
for (const SoundEffectResourceLocation& sbLoc : selected->mSoundEffect.mSoundBanks)
{
for (const std::string& sb : sbLoc.mSoundBanks)
{
if (ImGui::Selectable(sb.c_str()))
{
auto player = PlaySound(selected->mResourceName.c_str(), sb.c_str(), false, true, bUseCache);
if (player)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(player));
}
}
}
}
}
}
if (ImGui::Button("Play (cached/scripted)"))
{
PlaySoundScript(selected->mResourceName.c_str());
}
}
else
{
ImGui::TextWrapped("Click an item to display its info");
}
}
ImGui::EndChild();
}
ImGui::EndGroup();
ImGui::End();
ImGui::Begin("Sound themes");
for (const MusicTheme& theme : mLocator.mResMapper.mSoundResources.mThemes)
{
if (ImGui::RadioButton(theme.mName.c_str(), mActiveTheme && theme.mName == mActiveTheme->mName))
{
SetTheme(theme.mName.c_str());
HandleEvent("BASE_LINE");
}
}
for (const char* eventName : kMusicEvents)
{
if (ImGui::Button(eventName))
{
HandleEvent(eventName);
}
}
ImGui::End();
}
void Sound::Render(int /*w*/, int /*h*/)
{
}
<commit_msg>fix debug build<commit_after>#include "sound.hpp"
#include "oddlib/audio/SequencePlayer.h"
#include "core/audiobuffer.hpp"
#include "logger.hpp"
#include "resourcemapper.hpp"
#include "audioconverter.hpp"
#include "alive_version.h"
SoundCache::SoundCache(OSBaseFileSystem& fs)
: mFs(fs)
{
}
void SoundCache::Sync()
{
mSoundDataCache.clear();
bool ok = false;
std::string versionFile = "{CacheDir}/CacheVersion.txt";
if (mFs.FileExists(versionFile))
{
if (mFs.Open(versionFile)->LoadAllToString() == ALIVE_VERSION)
{
ok = true;
}
}
if (!ok)
{
DeleteAll();
}
}
void SoundCache::DeleteAll()
{
TRACE_ENTRYEXIT;
// Delete *.wav from {CacheDir}/disk
std::string dirName = mFs.ExpandPath("{CacheDir}");
const auto wavFiles = mFs.EnumerateFiles(dirName, "*.wav");
for (const auto& wavFile : wavFiles)
{
mFs.DeleteFile(dirName + "/" + wavFile);
}
// Remove from memory
mSoundDataCache.clear();
// Update cache version marker to current
const std::string fileName = mFs.ExpandPath("{CacheDir}/CacheVersion.txt");
Oddlib::FileStream versionFile(fileName, Oddlib::IStream::ReadMode::ReadWrite);
versionFile.Write(std::string(ALIVE_VERSION));
}
bool SoundCache::ExistsInMemoryCache(const std::string& name) const
{
return mSoundDataCache.find(name) != std::end(mSoundDataCache);
}
class WavSound : public ISound
{
public:
WavSound(const std::string& name, std::shared_ptr<std::vector<u8>>& data)
: mName(name), mData(data)
{
memcpy(&mHeader.mData, data->data(), sizeof(mHeader.mData));
mOffsetInBytes = sizeof(mHeader.mData);
}
virtual void Load() override { }
virtual void DebugUi() override {}
virtual void Play(f32* stream, u32 len) override
{
u32 kLenInBytes = len * sizeof(f32);
// Handle the case where the audio call back wants N data but we only have N-X left
if (mOffsetInBytes + kLenInBytes > mData->size())
{
kLenInBytes = static_cast<u32>(mData->size()) - mOffsetInBytes;
}
const f32* src = reinterpret_cast<const f32*>(mData->data() + mOffsetInBytes);
for (u32 i = 0; i < kLenInBytes/sizeof(f32); i++)
{
stream[i] += src[i];
}
mOffsetInBytes += kLenInBytes;
}
virtual bool AtEnd() const override
{
return mOffsetInBytes >= mData->size();
}
virtual void Restart() override
{
mOffsetInBytes = sizeof(mHeader.mData);
}
virtual void Update() override { }
virtual const std::string& Name() const override { return mName; }
private:
size_t mOffsetInBytes = 0;
std::string mName;
std::shared_ptr<std::vector<u8>> mData;
WavHeader mHeader;
};
std::unique_ptr<ISound> SoundCache::GetCached(const std::string& name)
{
auto it = mSoundDataCache.find(name);
if (it != std::end(mSoundDataCache))
{
return std::make_unique<WavSound>(name, it->second);
}
return nullptr;
}
void SoundCache::AddToMemoryAndDiskCache(ISound& sound)
{
const std::string fileName = mFs.ExpandPath("{CacheDir}/" + sound.Name() + ".wav");
// TODO: mod files that are already wav shouldn't be converted
sound.Load();
AudioConverter::Convert<WavEncoder>(sound, fileName.c_str());
auto stream = mFs.Open(fileName);
mSoundDataCache[sound.Name()] = std::make_shared<std::vector<u8>>(Oddlib::IStream::ReadAll(*stream));
}
bool SoundCache::AddToMemoryCacheFromDiskCache(const std::string& name)
{
std::string fileName = mFs.ExpandPath("{CacheDir}/" + name + ".wav");
if (mFs.FileExists(fileName))
{
auto stream = mFs.Open(fileName);
mSoundDataCache[name] = std::make_shared<std::vector<u8>>(Oddlib::IStream::ReadAll(*stream));
return true;
}
return false;
}
void SoundCache::RemoveFromMemoryCache(const std::string& name)
{
auto it = mSoundDataCache.find(name);
if (it != std::end(mSoundDataCache))
{
mSoundDataCache.erase(it);
}
}
// ====================================================================
void Sound::PlaySoundScript(const char* soundName)
{
auto ret = PlaySound(soundName, nullptr, true, true, true);
if (ret)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(ret));
}
}
std::unique_ptr<ISound> Sound::PlaySound(const char* soundName, const char* explicitSoundBankName, bool useMusicRec, bool useSfxRec, bool useCache)
{
if (useCache)
{
std::unique_ptr<ISound> pSound = mCache.GetCached(soundName);
if (pSound)
{
LOG_INFO("Play sound cached: " << soundName);
}
else
{
LOG_ERROR("Cached sound not found: " << soundName);
}
return pSound;
}
else
{
std::unique_ptr<ISound> pSound = mLocator.LocateSound(soundName, explicitSoundBankName, useMusicRec, useSfxRec);
if (pSound)
{
LOG_INFO("Play sound: " << soundName);
pSound->Load();
}
else
{
LOG_ERROR("Sound: " << soundName << " not found");
}
return pSound;
}
}
void Sound::SetTheme(const char* themeName)
{
mAmbiance = nullptr;
mMusicTrack = nullptr;
const MusicTheme* newTheme = mLocator.LocateSoundTheme(themeName);
// Remove current musics from in memory cache
if (mActiveTheme)
{
CacheActiveTheme(false);
}
mActiveTheme = newTheme;
// Add new musics to in memory cache
if (mActiveTheme)
{
CacheActiveTheme(true);
}
else
{
LOG_ERROR("Music theme " << themeName << " was not found");
}
}
void Sound::CacheMemoryResidentSounds()
{
TRACE_ENTRYEXIT;
// initial one time sync
mCache.Sync();
const std::vector<SoundResource>& resources = mLocator.GetSoundResources();
for (const SoundResource& resource : resources)
{
if (resource.mIsCacheResident)
{
CacheSound(resource.mResourceName);
}
}
}
void Sound::CacheActiveTheme(bool add)
{
for (auto& entry : mActiveTheme->mEntries)
{
for (auto& e : entry.second)
{
if (add)
{
CacheSound(e.mMusicName);
}
else
{
mCache.RemoveFromMemoryCache(e.mMusicName);
}
}
}
}
void Sound::CacheSound(const std::string& name)
{
if (mCache.ExistsInMemoryCache(name))
{
// Already in memory
return;
}
if (mCache.AddToMemoryCacheFromDiskCache(name))
{
// Already on disk and now added to in memory cache
return;
}
std::unique_ptr<ISound> pSound = mLocator.LocateSound(name.c_str(), nullptr, true, true);
if (pSound)
{
// Write into disk cache and then load from disk cache into memory cache
mCache.AddToMemoryAndDiskCache(*pSound);
}
}
void Sound::HandleEvent(const char* eventName)
{
// TODO: Need quarter beat transition in some cases
EnsureAmbiance();
if (strcmp(eventName, "AMBIANCE") == 0)
{
mMusicTrack = nullptr;
return;
}
auto ret = PlayThemeEntry(eventName);
if (ret)
{
mMusicTrack = std::move(ret);
}
}
std::unique_ptr<ISound> Sound::PlayThemeEntry(const char* entryName)
{
if (mActiveTheme)
{
mActiveThemeEntry.SetMusicThemeEntry(mActiveTheme->FindEntry(entryName));
const MusicThemeEntry* entry = mActiveThemeEntry.Entry();
if (entry)
{
return PlaySound(entry->mMusicName.c_str(), nullptr, true, true, true);
}
}
return nullptr;
}
void Sound::EnsureAmbiance()
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (!mAmbiance)
{
mAmbiance = PlayThemeEntry("AMBIANCE");
}
}
// Audio thread context
bool Sound::Play(f32* stream, u32 len)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (mAmbiance)
{
mAmbiance->Play(stream, len);
}
if (mMusicTrack)
{
mMusicTrack->Play(stream, len);
}
for (auto& player : mSoundPlayers)
{
player->Play(stream, len);
}
return false;
}
/*static*/ void Sound::RegisterScriptBindings()
{
Sqrat::Class<Sound, Sqrat::NoConstructor<Sound>> c(Sqrat::DefaultVM::Get(), "Sound");
c.Func("PlaySoundEffect", &Sound::PlaySoundScript);
c.Func("SetTheme", &Sound::SetTheme);
Sqrat::RootTable().Bind("Sound", c);
}
Sound::Sound(IAudioController& audioController, ResourceLocator& locator, OSBaseFileSystem& fs)
: mAudioController(audioController), mLocator(locator), mCache(fs), mScriptInstance("gSound", this)
{
mAudioController.AddPlayer(this);
}
Sound::~Sound()
{
// Ensure the audio call back stops at this point else will be
// calling back into freed objects
SDL_AudioQuit();
mAudioController.RemovePlayer(this);
}
void Sound::Update()
{
if (Debugging().mBrowserUi.soundBrowserOpen)
{
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
if (!mSoundPlayers.empty())
{
mSoundPlayers[0]->DebugUi();
}
if (ImGui::Begin("Active SEQs"))
{
if (mAmbiance)
{
ImGui::Text("Ambiance: %s", mAmbiance->Name().c_str());
}
if (mMusicTrack)
{
ImGui::Text("Music: %s", mMusicTrack->Name().c_str());
}
int i = 0;
for (auto& player : mSoundPlayers)
{
i++;
if (ImGui::Button((std::to_string(i) + player->Name()).c_str()))
{
// TODO: Kill whatever this SEQ is
}
}
}
ImGui::End();
}
SoundBrowserUi();
}
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
for (auto it = mSoundPlayers.begin(); it != mSoundPlayers.end();)
{
if ((*it)->AtEnd())
{
it = mSoundPlayers.erase(it);
}
else
{
it++;
}
}
if (mAmbiance)
{
mAmbiance->Update();
if (mAmbiance->AtEnd())
{
mAmbiance->Restart();
}
}
if (mMusicTrack)
{
mMusicTrack->Update();
if (mMusicTrack->AtEnd())
{
if (mActiveThemeEntry.ToNextEntry())
{
mMusicTrack = PlaySound(mActiveThemeEntry.Entry()->mMusicName.c_str(), nullptr, true, true, true);
}
else
{
mMusicTrack = nullptr;
}
}
}
for (auto& player : mSoundPlayers)
{
player->Update();
}
}
static const char* kMusicEvents[] =
{
"AMBIANCE",
"BASE_LINE",
"CRITTER_ATTACK",
"CRITTER_PATROL",
"SLIG_ATTACK",
"SLIG_PATROL",
"SLIG_POSSESSED",
};
void Sound::SoundBrowserUi()
{
ImGui::Begin("Sound list");
static const SoundResource* selected = nullptr;
// left
ImGui::BeginChild("left pane", ImVec2(200, 0), true);
{
for (const SoundResource& soundInfo : mLocator.GetSoundResources())
{
if (ImGui::Selectable(soundInfo.mResourceName.c_str()))
{
selected = &soundInfo;
}
}
ImGui::EndChild();
}
ImGui::SameLine();
// right
ImGui::BeginGroup();
{
ImGui::BeginChild("item view");
{
if (selected)
{
ImGui::TextWrapped("Resource name: %s", selected->mResourceName.c_str());
ImGui::Separator();
ImGui::TextWrapped("Comment: %s", selected->mComment.empty() ? "(none)" : selected->mComment.c_str());
ImGui::Separator();
ImGui::TextWrapped("Is memory resident: %s", selected->mIsCacheResident ? "true" : "false");
ImGui::TextWrapped("Is cached: %s", mCache.ExistsInMemoryCache(selected->mResourceName) ? "true" : "false");
static bool bUseCache = false;
ImGui::Checkbox("Use cache", &bUseCache);
const bool bHasMusic = !selected->mMusic.mSoundBanks.empty();
const bool bHasSample = !selected->mSoundEffect.mSoundBanks.empty();
if (bHasMusic)
{
if (ImGui::CollapsingHeader("SEQs"))
{
for (const std::string& sb : selected->mMusic.mSoundBanks)
{
if (ImGui::Selectable(sb.c_str()))
{
auto player = PlaySound(selected->mResourceName.c_str(), sb.c_str(), true, false, bUseCache);
if (player)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(player));
}
}
}
}
}
if (bHasSample)
{
if (ImGui::CollapsingHeader("Samples"))
{
for (const SoundEffectResourceLocation& sbLoc : selected->mSoundEffect.mSoundBanks)
{
for (const std::string& sb : sbLoc.mSoundBanks)
{
if (ImGui::Selectable(sb.c_str()))
{
auto player = PlaySound(selected->mResourceName.c_str(), sb.c_str(), false, true, bUseCache);
if (player)
{
std::lock_guard<std::mutex> lock(mSoundPlayersMutex);
mSoundPlayers.push_back(std::move(player));
}
}
}
}
}
}
if (ImGui::Button("Play (cached/scripted)"))
{
PlaySoundScript(selected->mResourceName.c_str());
}
}
else
{
ImGui::TextWrapped("Click an item to display its info");
}
}
ImGui::EndChild();
}
ImGui::EndGroup();
ImGui::End();
ImGui::Begin("Sound themes");
for (const MusicTheme& theme : mLocator.mResMapper.mSoundResources.mThemes)
{
if (ImGui::RadioButton(theme.mName.c_str(), mActiveTheme && theme.mName == mActiveTheme->mName))
{
SetTheme(theme.mName.c_str());
HandleEvent("BASE_LINE");
}
}
for (const char* eventName : kMusicEvents)
{
if (ImGui::Button(eventName))
{
HandleEvent(eventName);
}
}
ImGui::End();
}
void Sound::Render(int /*w*/, int /*h*/)
{
}
<|endoftext|> |
<commit_before>#include "string.hh"
#include "exception.hh"
#include "containers.hh"
#include "utf8_iterator.hh"
#include <cstdio>
namespace Kakoune
{
Vector<String> split(StringView str, char separator, char escape)
{
Vector<String> res;
auto it = str.begin();
while (it != str.end())
{
res.emplace_back();
String& element = res.back();
while (it != str.end())
{
auto c = *it;
if (c == escape and it + 1 != str.end() and *(it+1) == separator)
{
element += separator;
it += 2;
}
else if (c == separator)
{
++it;
break;
}
else
{
element += c;
++it;
}
}
}
return res;
}
Vector<StringView> split(StringView str, char separator)
{
Vector<StringView> res;
auto beg = str.begin();
for (auto it = beg; it != str.end(); ++it)
{
if (*it == separator)
{
res.emplace_back(beg, it);
beg = it + 1;
}
}
res.emplace_back(beg, str.end());
return res;
}
String escape(StringView str, StringView characters, char escape)
{
String res;
for (auto& c : str)
{
if (contains(characters, c))
res += escape;
res += c;
}
return res;
}
String unescape(StringView str, StringView characters, char escape)
{
String res;
for (auto& c : str)
{
if (contains(characters, c) and not res.empty() and res.back() == escape)
res.back() = c;
else
res += c;
}
return res;
}
String indent(StringView str, StringView indent)
{
String res;
bool was_eol = true;
for (ByteCount i = 0; i < str.length(); ++i)
{
if (was_eol)
res += indent;
res += str[i];
was_eol = is_eol(str[i]);
}
return res;
}
int str_to_int(StringView str)
{
int res = 0;
if (sscanf(str.zstr(), "%i", &res) != 1)
throw runtime_error(str + "is not a number");
return res;
}
String to_string(int val)
{
char buf[16];
sprintf(buf, "%i", val);
return buf;
}
String to_string(size_t val)
{
char buf[16];
sprintf(buf, "%zu", val);
return buf;
}
String to_string(float val)
{
char buf[32];
sprintf(buf, "%f", val);
return buf;
}
bool subsequence_match(StringView str, StringView subseq)
{
auto it = str.begin();
for (auto& c : subseq)
{
if (it == str.end())
return false;
while (*it != c)
{
if (++it == str.end())
return false;
}
++it;
}
return true;
}
String expand_tabs(StringView line, CharCount tabstop, CharCount col)
{
String res;
using Utf8It = utf8::iterator<const char*>;
for (Utf8It it = line.begin(); it.base() < line.end(); ++it)
{
if (*it == '\t')
{
CharCount end_col = (col / tabstop + 1) * tabstop;
res += String{' ', end_col - col};
}
else
res += *it;
}
return res;
}
Vector<StringView> wrap_lines(StringView text, CharCount max_width)
{
using Utf8It = utf8::iterator<const char*>;
Utf8It word_begin{text.begin()};
Utf8It word_end{word_begin};
Utf8It end{text.end()};
CharCount col = 0;
Vector<StringView> lines;
Utf8It line_begin = text.begin();
Utf8It line_end = line_begin;
while (word_begin != end)
{
const CharCategories cat = categorize(*word_begin);
do
{
++word_end;
} while (word_end != end and categorize(*word_end) == cat);
col += word_end - word_begin;
if ((word_begin != line_begin and col > max_width) or
cat == CharCategories::EndOfLine)
{
lines.emplace_back(line_begin.base(), line_end.base());
line_begin = (cat == CharCategories::EndOfLine or
cat == CharCategories::Blank) ? word_end : word_begin;
col = word_end - line_begin;
}
if (cat == CharCategories::Word or cat == CharCategories::Punctuation)
line_end = word_end;
word_begin = word_end;
}
if (line_begin != word_begin)
lines.emplace_back(line_begin.base(), word_begin.base());
return lines;
}
}
<commit_msg>Allocate some data in advance in string algorithm<commit_after>#include "string.hh"
#include "exception.hh"
#include "containers.hh"
#include "utf8_iterator.hh"
#include <cstdio>
namespace Kakoune
{
Vector<String> split(StringView str, char separator, char escape)
{
Vector<String> res;
auto it = str.begin();
while (it != str.end())
{
res.emplace_back();
String& element = res.back();
while (it != str.end())
{
auto c = *it;
if (c == escape and it + 1 != str.end() and *(it+1) == separator)
{
element += separator;
it += 2;
}
else if (c == separator)
{
++it;
break;
}
else
{
element += c;
++it;
}
}
}
return res;
}
Vector<StringView> split(StringView str, char separator)
{
Vector<StringView> res;
auto beg = str.begin();
for (auto it = beg; it != str.end(); ++it)
{
if (*it == separator)
{
res.emplace_back(beg, it);
beg = it + 1;
}
}
res.emplace_back(beg, str.end());
return res;
}
String escape(StringView str, StringView characters, char escape)
{
String res;
res.reserve(str.length());
for (auto& c : str)
{
if (contains(characters, c))
res += escape;
res += c;
}
return res;
}
String unescape(StringView str, StringView characters, char escape)
{
String res;
res.reserve(str.length());
for (auto& c : str)
{
if (contains(characters, c) and not res.empty() and res.back() == escape)
res.back() = c;
else
res += c;
}
return res;
}
String indent(StringView str, StringView indent)
{
String res;
res.reserve(str.length());
bool was_eol = true;
for (ByteCount i = 0; i < str.length(); ++i)
{
if (was_eol)
res += indent;
res += str[i];
was_eol = is_eol(str[i]);
}
return res;
}
int str_to_int(StringView str)
{
int res = 0;
if (sscanf(str.zstr(), "%i", &res) != 1)
throw runtime_error(str + "is not a number");
return res;
}
String to_string(int val)
{
char buf[16];
sprintf(buf, "%i", val);
return buf;
}
String to_string(size_t val)
{
char buf[16];
sprintf(buf, "%zu", val);
return buf;
}
String to_string(float val)
{
char buf[32];
sprintf(buf, "%f", val);
return buf;
}
bool subsequence_match(StringView str, StringView subseq)
{
auto it = str.begin();
for (auto& c : subseq)
{
if (it == str.end())
return false;
while (*it != c)
{
if (++it == str.end())
return false;
}
++it;
}
return true;
}
String expand_tabs(StringView line, CharCount tabstop, CharCount col)
{
String res;
res.reserve(line.length());
using Utf8It = utf8::iterator<const char*>;
for (Utf8It it = line.begin(); it.base() < line.end(); ++it)
{
if (*it == '\t')
{
CharCount end_col = (col / tabstop + 1) * tabstop;
res += String{' ', end_col - col};
}
else
res += *it;
}
return res;
}
Vector<StringView> wrap_lines(StringView text, CharCount max_width)
{
using Utf8It = utf8::iterator<const char*>;
Utf8It word_begin{text.begin()};
Utf8It word_end{word_begin};
Utf8It end{text.end()};
CharCount col = 0;
Vector<StringView> lines;
Utf8It line_begin = text.begin();
Utf8It line_end = line_begin;
while (word_begin != end)
{
const CharCategories cat = categorize(*word_begin);
do
{
++word_end;
} while (word_end != end and categorize(*word_end) == cat);
col += word_end - word_begin;
if ((word_begin != line_begin and col > max_width) or
cat == CharCategories::EndOfLine)
{
lines.emplace_back(line_begin.base(), line_end.base());
line_begin = (cat == CharCategories::EndOfLine or
cat == CharCategories::Blank) ? word_end : word_begin;
col = word_end - line_begin;
}
if (cat == CharCategories::Word or cat == CharCategories::Punctuation)
line_end = word_end;
word_begin = word_end;
}
if (line_begin != word_begin)
lines.emplace_back(line_begin.base(), word_begin.base());
return lines;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "tools.h"
#include "division_by_zero_exception.h"
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
VectorXd rmse(4);
rmse << 0, 0, 0, 0;
// check the validity of the following inputs:
// * the estimation vector size should not be zero
// * the estimation vector size should equal ground truth vector size
if(estimations.size() == 0 || estimations.size() != ground_truth.size()) {
std::cout << "calculateRMSE() - Error - Invalid Estimations vector size" << std::endl;
return rmse;
}
//accumulate squared residuals
VectorXd sum(4);
sum << 0, 0, 0, 0;
for(int i = 0; i < estimations.size(); ++i) {
VectorXd estimated = estimations[i];
VectorXd actual = ground_truth[i];
VectorXd diff = (estimated - actual);
//coefficient-wise multiplication
diff = diff.array() * diff.array();
sum = sum + diff;
}
//calculate the mean
Eigen::VectorXd mean = sum / estimations.size();
//calculate the squared root
rmse = mean.array().sqrt();
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
Eigen::MatrixXd Hj = MatrixXd::Zero(3, 4);
//state parameters
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
//divsion by zero check
if(px == 0 || py == 0 ) {
throw DivisionByZeroException();
}
// calculating common values used in Jacobian
float px2 = px * px;
float py2 = py * py;
float px2_py2_sum = px2 + py2;
float px2_py2_sqrt = sqrt(px2_py2_sum);
float px2_py2_sum_3_by_2 = pow((px2_py2_sum), 3/2.0);
if(fabs(px2_py2_sum) < 0.0001) {
throw DivisionByZeroException();
}
// calculating and inserting jacobian values
Hj << (px / px2_py2_sqrt), (py / px2_py2_sqrt), 0, 0,
(-py / px2_py2_sum), (px / px2_py2_sum), 0, 0,
((py * (vx * py - vy * px)) / px2_py2_sum_3_by_2), ((px * (vy * px - vx * py)) / px2_py2_sum_3_by_2), (px / px2_py2_sqrt), (py / px2_py2_sqrt);
return Hj;
}
<commit_msg>feat: Function to normalize angle in [-pi, pi]<commit_after>#include <iostream>
#include "tools.h"
#include "division_by_zero_exception.h"
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
VectorXd rmse(4);
rmse << 0, 0, 0, 0;
// check the validity of the following inputs:
// * the estimation vector size should not be zero
// * the estimation vector size should equal ground truth vector size
if(estimations.size() == 0 || estimations.size() != ground_truth.size()) {
std::cout << "calculateRMSE() - Error - Invalid Estimations vector size" << std::endl;
return rmse;
}
//accumulate squared residuals
VectorXd sum(4);
sum << 0, 0, 0, 0;
for(int i = 0; i < estimations.size(); ++i) {
VectorXd estimated = estimations[i];
VectorXd actual = ground_truth[i];
VectorXd diff = (estimated - actual);
//coefficient-wise multiplication
diff = diff.array() * diff.array();
sum = sum + diff;
}
//calculate the mean
Eigen::VectorXd mean = sum / estimations.size();
//calculate the squared root
rmse = mean.array().sqrt();
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
Eigen::MatrixXd Hj = MatrixXd::Zero(3, 4);
//state parameters
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
//divsion by zero check
if(px == 0 || py == 0 ) {
throw DivisionByZeroException();
}
// calculating common values used in Jacobian
float px2 = px * px;
float py2 = py * py;
float px2_py2_sum = px2 + py2;
float px2_py2_sqrt = sqrt(px2_py2_sum);
float px2_py2_sum_3_by_2 = pow((px2_py2_sum), 3/2.0);
if(fabs(px2_py2_sum) < 0.0001) {
throw DivisionByZeroException();
}
// calculating and inserting jacobian values
Hj << (px / px2_py2_sqrt), (py / px2_py2_sqrt), 0, 0,
(-py / px2_py2_sum), (px / px2_py2_sum), 0, 0,
((py * (vx * py - vy * px)) / px2_py2_sum_3_by_2), ((px * (vy * px - vx * py)) / px2_py2_sum_3_by_2), (px / px2_py2_sqrt), (py / px2_py2_sqrt);
return Hj;
}
float Tools::NormalizeAngle(float angle_rad) {
angle_rad = angle_rad - 2*M_PI*floor( (angle_rad+ M_PI)/(2 * M_PI) );
return angle_rad;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include "types.hpp"
field::field(std::size_t h, std::size_t w){
this->width = w;
this->height = h;
this->f = std::vector< std::vector < bool > >(h);
for (std::size_t i = 0; i < h; ++i)
this->f[i].assign(w, false);
}
std::vector< bool > & field::operator[](std::size_t i){
return this->f[i];
}
vec3d::vec3d( vec3s v ) {
this->x = v.r * sin( v.theta ) * cos ( v.phi );
this->y = v.r * sin( v.theta ) * sin ( v.phi );
this->z = v.r * cos( v.theta );
}
float vec3d::operator*( vec3d rhs ) {
return this->x * rhs.x + this->y * rhs.y + this->z * rhs.z;
}
float vec3s::operator*( vec3s rhs ) {
return vec3d( *this ) * vec3d ( rhs );
}
vec3s & operator += ( vec3s & lhs, const vec3s & rhs ) {
lhs.r += rhs.r;
lhs.theta += rhs.theta;
lhs.phi += rhs.phi;
return lhs;
}
vec3s & operator -= ( vec3s & lhs, const vec3s & rhs ) {
lhs.r -= rhs.r;
lhs.theta -= rhs.theta;
lhs.phi -= rhs.phi;
return lhs;
}
SDL_Point surf_to_screen( vec3s n, vec3s sp, SDL_Point center ) {
// координаты ортов в плоскости экрана в декартовых координатах
vec3s ex = { 1, ( float ) ( M_PI / 2 ), n.phi + ( float ) ( M_PI / 2 ) };
vec3s ey = { 1, n.theta - ( float ) ( M_PI / 2 ), n.phi };
// немного скалярных произведений
return { center.x + ( int ) ( sp * ex ),
center.y - ( int ) ( sp * ey ) };
}
bool visible ( vec3s n, vec3s sp ) {
return ( n * sp >= 0 ); // хак для увеличения области видимости
}
<commit_msg>[upd] minor improvements<commit_after>#include <cmath>
#include <iostream>
#include "types.hpp"
field::field(std::size_t h, std::size_t w) : f(h) {
this->width = w;
this->height = h;
for (std::size_t i = 0; i < h; ++i)
this->f[i].assign(w, false);
}
std::vector< bool > & field::operator[](std::size_t i){
return this->f[i];
}
vec3d::vec3d( vec3s v ) {
float st, ct, sp, cp;
sincosf(v.theta, &st, &ct);
sincosf(v.phi, &sp, &cp);
this->x = v.r * st * cp;
this->y = v.r * st * sp;
this->z = v.r * ct;
}
float vec3d::operator*( vec3d rhs ) {
return this->x * rhs.x + this->y * rhs.y + this->z * rhs.z;
}
float vec3s::operator*( vec3s rhs ) {
return vec3d( *this ) * vec3d ( rhs );
}
vec3s & operator += ( vec3s & lhs, const vec3s & rhs ) {
lhs.r += rhs.r;
lhs.theta += rhs.theta;
lhs.phi += rhs.phi;
return lhs;
}
vec3s & operator -= ( vec3s & lhs, const vec3s & rhs ) {
lhs.r -= rhs.r;
lhs.theta -= rhs.theta;
lhs.phi -= rhs.phi;
return lhs;
}
SDL_Point surf_to_screen( vec3s n, vec3s sp, SDL_Point center ) {
// координаты ортов в плоскости экрана в декартовых координатах
vec3s ex = { 1, ( float ) ( M_PI / 2 ), n.phi + ( float ) ( M_PI / 2 ) };
vec3s ey = { 1, n.theta - ( float ) ( M_PI / 2 ), n.phi };
// немного скалярных произведений
return { center.x + ( int ) ( sp * ex ),
center.y - ( int ) ( sp * ey ) };
}
bool visible ( vec3s n, vec3s sp ) {
return ( n * sp >= 0 ); // хак для увеличения области видимости
}
<|endoftext|> |
<commit_before>/*! \file uqueue.cc
*******************************************************************************
File: uqueue.cc\n
Implementation of the UQueue class.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2005.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.net
**************************************************************************** */
#include <cstdlib>
#include "libport/cstring"
#include "kernel/userver.hh"
#include "uqueue.hh"
//! UQueue constructor.
/*! UQueue implements a dynamic circular FIFO buffer.
You can specify the following parameters:
\param minBufferSize is the initial size of the buffer. If the buffer is
shrinked (adaptive buffer), its size will be at least minBufferSize.
The default value if not specified is 4096 octets.
\param maxBufferSize is the maximal size of the buffer. The buffer size is
increased when one tries to push data that is too big for the current
buffer size. However, this dynamic behavior is limited to
maxBufferSize in any case. If the buffer can still not hold the
pushed data, the push() function returns UFAIL.
If set to zero, the limit is infinite.
The default value is equal to minBufferSize.
\param adaptive the default behavior of the UQueue is to increase the size
of the internal buffer if one tries to hold more data that what the
current size allows (up to maxBufferSize, as we said). However, if
the buffer is adaptive, it will also be able to shrink the buffer.
This is very useful to allow the UQueue to grow momentarily to hold
a large amount of data and then recover memory after the boost, if
this data size is not the usual functioning load.
If adaptive is non null, the behavior is the following: the UQueue
counts the number of calls to the pop() function. Each time this
number goes above 'adaptive', the UQueue will resize to the maximum
data size it has held in the past 'adaptive' calls to pop(), and
minBufferSize at least. So, 'adaptive' is a time windows that is
periodicaly checked to shink the buffer if necessary.
Note that the buffer will shrink only if there is a minimum of 20%
size difference, to avoid time consuming reallocs for nothing.
We recommand a default value of 100 for the adaptive value.
*/
UQueue::UQueue (size_t minBufferSize,
size_t maxBufferSize,
size_t adaptive)
: minBufferSize_ (minBufferSize
? minBufferSize : static_cast<size_t>(INITIAL_BUFFER_SIZE)),
maxBufferSize_ (maxBufferSize == static_cast<size_t>(-1)
? minBufferSize_ : maxBufferSize),
adaptive_(adaptive),
buffer_(minBufferSize_),
outputBuffer_(UQueue::INITIAL_BUFFER_SIZE),
start_(0),
end_(0),
dataSize_(0),
nbPopCall_(0),
topDataSize_(0),
topOutputSize_(0),
mark_(0),
locked_(false)
{
}
//! UQueue destructor.
UQueue::~UQueue()
{
}
//! Clear the queue
void
UQueue::clear()
{
start_ = 0;
end_ = 0;
dataSize_ = 0;
}
//! Set a mark to be able to revert to this position
void
UQueue::mark()
{
mark_ = end_;
locked_ = false;
}
//! Revert the buffer to the marked position.
void
UQueue::revert()
{
end_ = mark_;
locked_ = true;
}
void
UQueue::enlarge (size_t& s) const
{
s *= 2;
if (maxBufferSize_)
s = std::min(s, maxBufferSize_);
}
//! Pushes a buffer into the queue..
/*! This function tries to store the buffer in the queue, and tries to extend
to buffer size when the buffer does not fit and if it is possible.
\param buffer the buffer to push
\param length the length of the buffer
\return
- USUCCESS: successful
- UFAIL : could not push the buffer. The queue is not changed.
*/
UErrorValue
UQueue::push (const ubyte *buffer, size_t length)
{
size_t bfs = bufferFreeSpace();
if (bfs < length) // Is the internal buffer big enough?
{
// No. Check if the internal buffer can be extended.
size_t newSize = buffer_.size() + (length - bfs);
if (newSize > maxBufferSize_ && maxBufferSize_ != 0)
return UFAIL;
else
{
// Calculate the required size + 10%, if it fits.
enlarge(newSize);
// Realloc the internal buffer
size_t old_size = buffer_.size();
buffer_.resize(newSize);
if (end_ < start_ || bfs == 0 )
{
// Translate the rightside of the old internal buffer.
memmove(&buffer_[0] + start_ + newSize - old_size,
&buffer_[0] + start_,
old_size - start_);
start_ += newSize - old_size;
}
}
}
if (buffer_.size() - end_ >= length)
{
// Do we have to split 'buffer'?
// No need to split.
memcpy(&buffer_[0] + end_, buffer, length);
end_ += length;
if (end_ == buffer_.size())
end_ = 0; // loop the circular geometry.
}
else
{
// Split 'buffer' to fit in the internal circular buffer.
memcpy(&buffer_[0] + end_, buffer, buffer_.size() - end_);
memcpy(&buffer_[0],
buffer + (buffer_.size() - end_),
length - (buffer_.size() - end_));
end_ = length - (buffer_.size() - end_);
}
dataSize_ += length;
return USUCCESS;
}
void
UQueue::adapt(size_t toPop)
{
++nbPopCall_;
topDataSize_ = std::max (topDataSize_, dataSize_);
topOutputSize_ = std::max (topOutputSize_, toPop);
if (adaptive_ < nbPopCall_)
{
// time out
if (topOutputSize_ < outputBuffer_.size() * 0.8)
outputBuffer_.resize(topOutputSize_ * 2);
if (topDataSize_ < buffer_.size() * 0.8)
{
// We shrink the buffer to the new size: topDataSize_ + 10% (if it fits)
enlarge(topDataSize_);
if (end_ < start_)
{
// The data is splitted
memmove(&buffer_[0] + start_ - (buffer_.size() - topDataSize_),
&buffer_[0] + start_, buffer_.size() - start_);
start_ = start_ - (buffer_.size() - topDataSize_);
}
else
{
// The data is contiguous
memmove(&buffer_[0], &buffer_[0] + start_, dataSize_);
start_ = 0;
end_ = dataSize_;
// the case end_ == buffer_.size() is handled below.
}
buffer_.resize(topDataSize_);
if (end_ == buffer_.size() )
end_ =0; // loop the circular geometry.
// else... well it should never come to this else anyway.
}
// reset.
nbPopCall_ = 0;
topDataSize_ = 0;
topOutputSize_ = 0;
}
}
//! Pops 'length' bytes out of the Queue
/*! Pops 'length' bytes.
The ubyte* pointer returned is not permanent. You have to make a copy of the
data pointed if you want to keep it. Any call to a member function of UQueue
might alter it later.
\param length the length requested.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::pop (size_t length)
{
// Actual size of the data to pop.
size_t toPop = length;
if (toPop > dataSize_)
return 0; // Not enough data to pop 'length'
if (toPop == 0)
// Pops nothing but gets a pointer to the beginning of the buffer.
return &buffer_[0] + start_;
// Adaptive shrinking behavior
if (adaptive_)
adapt(toPop);
if (buffer_.size() - start_ >= toPop)
{
// Is the packet continuous across the the internal buffer? yes,
// the packet is continuous in the internal buffer
size_t start = start_;
start_ += toPop;
if (start_ == buffer_.size())
start_ = 0; // loop the circular geometry.
dataSize_ -= toPop;
return &buffer_[0] + start;
}
else
{
// no, the packet spans then end and the beginning of the buffer
// and it must be reconstructed.
// Is the temporary internal outputBuffer large enough?
if (outputBuffer_.size() < toPop)
outputBuffer_.resize(toPop * 2);
memcpy(&outputBuffer_[0],
&buffer_[0] + start_,
buffer_.size() - start_);
memcpy(&outputBuffer_[0] + (buffer_.size() - start_ ),
&buffer_[0],
toPop - (buffer_.size() - start_));
start_ = toPop - (buffer_.size() - start_);
dataSize_ -= toPop;
return &outputBuffer_[0];
}
}
//! Pops at most 'length' bytes out of the Queue
/*! Pops at most 'length' bytes. The actual size is returned in 'length'.
The ubyte* pointer returned is not permanent. You have to make a copy of the
data pointed if you want to keep it. Any call to a member function of UQueue
might alter it later.
This method is called "fast" because is will not use the temporary
outputBuffer if the requested data is half at the end and half at the
beginning of the buffer. It will return only the part at the end of the
buffer and return the actual size of data popped. You have to check if this
value is equal to the requested length. If it is not, a second call to
fastPop will give you the rest of the buffer, with a different pointer.
This function is useful if you plan to pop huge amount of data which will
probably span over the end of the buffer and which would, with a simple
call to 'pop', result in a huge memory replication. In other cases, prefer
'pop', which is most of the time as efficient as fastPop and much more
convenient to use.
\param length the length requested. Contains the actual length popped.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::fastPop (size_t &length)
{
return pop((length > buffer_.size() - start_)
? (length = buffer_.size() - start_)
: length);
}
//! Simulates the pop of 'length' bytes out of the Queue
/*! Behave like pop but simulate the effect. This is useful if one wants to try
something with the popped buffer and check the validity before actually
popping the data.
It is also typically used when trying to send bytes in a connection and
it is not known in advance how many bytes will be effectively sent.
\param length the length requested.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::virtualPop (size_t length)
{
// Actual size of the data to pop.
size_t toPop = length;
if (toPop > dataSize_)
return 0; // Not enough data to pop 'length'
if (toPop == 0)
// Pops nothing but gets a pointer to the beginning of the buffer.
return &buffer_[0] + start_;
// Is the packet continuous across the internal buffer?
if (buffer_.size() - start_ >= toPop)
// yes, the packet is continuous in the internal buffer
return &buffer_[0] + start_;
else
{
// no, the packet spans then end and the beginning of the buffer
// and it must be reconstructed.
// Is the temporary internal outputBuffer large enough?
if (outputBuffer_.size() < toPop)
outputBuffer_.resize(toPop * 2);
memcpy(&outputBuffer_[0],
&buffer_[0] + start_,
buffer_.size() - start_);
memcpy(&outputBuffer_[0] + (buffer_.size() - start_),
&buffer_[0],
toPop - (buffer_.size() - start_));
//start_ = toPop - (buffer_.size() - start_);
//dataSize_ -= toPop;
return &outputBuffer_[0];
}
}
<commit_msg>Add missing include of windows.hh<commit_after>/*! \file uqueue.cc
*******************************************************************************
File: uqueue.cc\n
Implementation of the UQueue class.
This file is part of
%URBI Kernel, version __kernelversion__\n
(c) Jean-Christophe Baillie, 2004-2005.
Permission to use, copy, modify, and redistribute this software for
non-commercial use is hereby granted.
This software is provided "as is" without warranty of any kind,
either expressed or implied, including but not limited to the
implied warranties of fitness for a particular purpose.
For more information, comments, bug reports: http://www.urbiforge.net
**************************************************************************** */
#include <cstdlib>
#include <libport/cstring>
#include <libport/windows.hh>
#include "kernel/userver.hh"
#include "uqueue.hh"
//! UQueue constructor.
/*! UQueue implements a dynamic circular FIFO buffer.
You can specify the following parameters:
\param minBufferSize is the initial size of the buffer. If the buffer is
shrinked (adaptive buffer), its size will be at least minBufferSize.
The default value if not specified is 4096 octets.
\param maxBufferSize is the maximal size of the buffer. The buffer size is
increased when one tries to push data that is too big for the current
buffer size. However, this dynamic behavior is limited to
maxBufferSize in any case. If the buffer can still not hold the
pushed data, the push() function returns UFAIL.
If set to zero, the limit is infinite.
The default value is equal to minBufferSize.
\param adaptive the default behavior of the UQueue is to increase the size
of the internal buffer if one tries to hold more data that what the
current size allows (up to maxBufferSize, as we said). However, if
the buffer is adaptive, it will also be able to shrink the buffer.
This is very useful to allow the UQueue to grow momentarily to hold
a large amount of data and then recover memory after the boost, if
this data size is not the usual functioning load.
If adaptive is non null, the behavior is the following: the UQueue
counts the number of calls to the pop() function. Each time this
number goes above 'adaptive', the UQueue will resize to the maximum
data size it has held in the past 'adaptive' calls to pop(), and
minBufferSize at least. So, 'adaptive' is a time windows that is
periodicaly checked to shink the buffer if necessary.
Note that the buffer will shrink only if there is a minimum of 20%
size difference, to avoid time consuming reallocs for nothing.
We recommand a default value of 100 for the adaptive value.
*/
UQueue::UQueue (size_t minBufferSize,
size_t maxBufferSize,
size_t adaptive)
: minBufferSize_ (minBufferSize
? minBufferSize : static_cast<size_t>(INITIAL_BUFFER_SIZE)),
maxBufferSize_ (maxBufferSize == static_cast<size_t>(-1)
? minBufferSize_ : maxBufferSize),
adaptive_(adaptive),
buffer_(minBufferSize_),
outputBuffer_(UQueue::INITIAL_BUFFER_SIZE),
start_(0),
end_(0),
dataSize_(0),
nbPopCall_(0),
topDataSize_(0),
topOutputSize_(0),
mark_(0),
locked_(false)
{
}
//! UQueue destructor.
UQueue::~UQueue()
{
}
//! Clear the queue
void
UQueue::clear()
{
start_ = 0;
end_ = 0;
dataSize_ = 0;
}
//! Set a mark to be able to revert to this position
void
UQueue::mark()
{
mark_ = end_;
locked_ = false;
}
//! Revert the buffer to the marked position.
void
UQueue::revert()
{
end_ = mark_;
locked_ = true;
}
void
UQueue::enlarge (size_t& s) const
{
s *= 2;
if (maxBufferSize_)
s = std::min(s, maxBufferSize_);
}
//! Pushes a buffer into the queue..
/*! This function tries to store the buffer in the queue, and tries to extend
to buffer size when the buffer does not fit and if it is possible.
\param buffer the buffer to push
\param length the length of the buffer
\return
- USUCCESS: successful
- UFAIL : could not push the buffer. The queue is not changed.
*/
UErrorValue
UQueue::push (const ubyte *buffer, size_t length)
{
size_t bfs = bufferFreeSpace();
if (bfs < length) // Is the internal buffer big enough?
{
// No. Check if the internal buffer can be extended.
size_t newSize = buffer_.size() + (length - bfs);
if (newSize > maxBufferSize_ && maxBufferSize_ != 0)
return UFAIL;
else
{
// Calculate the required size + 10%, if it fits.
enlarge(newSize);
// Realloc the internal buffer
size_t old_size = buffer_.size();
buffer_.resize(newSize);
if (end_ < start_ || bfs == 0 )
{
// Translate the rightside of the old internal buffer.
memmove(&buffer_[0] + start_ + newSize - old_size,
&buffer_[0] + start_,
old_size - start_);
start_ += newSize - old_size;
}
}
}
if (buffer_.size() - end_ >= length)
{
// Do we have to split 'buffer'?
// No need to split.
memcpy(&buffer_[0] + end_, buffer, length);
end_ += length;
if (end_ == buffer_.size())
end_ = 0; // loop the circular geometry.
}
else
{
// Split 'buffer' to fit in the internal circular buffer.
memcpy(&buffer_[0] + end_, buffer, buffer_.size() - end_);
memcpy(&buffer_[0],
buffer + (buffer_.size() - end_),
length - (buffer_.size() - end_));
end_ = length - (buffer_.size() - end_);
}
dataSize_ += length;
return USUCCESS;
}
void
UQueue::adapt(size_t toPop)
{
++nbPopCall_;
topDataSize_ = std::max (topDataSize_, dataSize_);
topOutputSize_ = std::max (topOutputSize_, toPop);
if (adaptive_ < nbPopCall_)
{
// time out
if (topOutputSize_ < outputBuffer_.size() * 0.8)
outputBuffer_.resize(topOutputSize_ * 2);
if (topDataSize_ < buffer_.size() * 0.8)
{
// We shrink the buffer to the new size: topDataSize_ + 10% (if it fits)
enlarge(topDataSize_);
if (end_ < start_)
{
// The data is splitted
memmove(&buffer_[0] + start_ - (buffer_.size() - topDataSize_),
&buffer_[0] + start_, buffer_.size() - start_);
start_ = start_ - (buffer_.size() - topDataSize_);
}
else
{
// The data is contiguous
memmove(&buffer_[0], &buffer_[0] + start_, dataSize_);
start_ = 0;
end_ = dataSize_;
// the case end_ == buffer_.size() is handled below.
}
buffer_.resize(topDataSize_);
if (end_ == buffer_.size() )
end_ =0; // loop the circular geometry.
// else... well it should never come to this else anyway.
}
// reset.
nbPopCall_ = 0;
topDataSize_ = 0;
topOutputSize_ = 0;
}
}
//! Pops 'length' bytes out of the Queue
/*! Pops 'length' bytes.
The ubyte* pointer returned is not permanent. You have to make a copy of the
data pointed if you want to keep it. Any call to a member function of UQueue
might alter it later.
\param length the length requested.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::pop (size_t length)
{
// Actual size of the data to pop.
size_t toPop = length;
if (toPop > dataSize_)
return 0; // Not enough data to pop 'length'
if (toPop == 0)
// Pops nothing but gets a pointer to the beginning of the buffer.
return &buffer_[0] + start_;
// Adaptive shrinking behavior
if (adaptive_)
adapt(toPop);
if (buffer_.size() - start_ >= toPop)
{
// Is the packet continuous across the the internal buffer? yes,
// the packet is continuous in the internal buffer
size_t start = start_;
start_ += toPop;
if (start_ == buffer_.size())
start_ = 0; // loop the circular geometry.
dataSize_ -= toPop;
return &buffer_[0] + start;
}
else
{
// no, the packet spans then end and the beginning of the buffer
// and it must be reconstructed.
// Is the temporary internal outputBuffer large enough?
if (outputBuffer_.size() < toPop)
outputBuffer_.resize(toPop * 2);
memcpy(&outputBuffer_[0],
&buffer_[0] + start_,
buffer_.size() - start_);
memcpy(&outputBuffer_[0] + (buffer_.size() - start_ ),
&buffer_[0],
toPop - (buffer_.size() - start_));
start_ = toPop - (buffer_.size() - start_);
dataSize_ -= toPop;
return &outputBuffer_[0];
}
}
//! Pops at most 'length' bytes out of the Queue
/*! Pops at most 'length' bytes. The actual size is returned in 'length'.
The ubyte* pointer returned is not permanent. You have to make a copy of the
data pointed if you want to keep it. Any call to a member function of UQueue
might alter it later.
This method is called "fast" because is will not use the temporary
outputBuffer if the requested data is half at the end and half at the
beginning of the buffer. It will return only the part at the end of the
buffer and return the actual size of data popped. You have to check if this
value is equal to the requested length. If it is not, a second call to
fastPop will give you the rest of the buffer, with a different pointer.
This function is useful if you plan to pop huge amount of data which will
probably span over the end of the buffer and which would, with a simple
call to 'pop', result in a huge memory replication. In other cases, prefer
'pop', which is most of the time as efficient as fastPop and much more
convenient to use.
\param length the length requested. Contains the actual length popped.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::fastPop (size_t &length)
{
return pop((length > buffer_.size() - start_)
? (length = buffer_.size() - start_)
: length);
}
//! Simulates the pop of 'length' bytes out of the Queue
/*! Behave like pop but simulate the effect. This is useful if one wants to try
something with the popped buffer and check the validity before actually
popping the data.
It is also typically used when trying to send bytes in a connection and
it is not known in advance how many bytes will be effectively sent.
\param length the length requested.
\return a pointer to the the data popped or 0 in case of error.
*/
ubyte*
UQueue::virtualPop (size_t length)
{
// Actual size of the data to pop.
size_t toPop = length;
if (toPop > dataSize_)
return 0; // Not enough data to pop 'length'
if (toPop == 0)
// Pops nothing but gets a pointer to the beginning of the buffer.
return &buffer_[0] + start_;
// Is the packet continuous across the internal buffer?
if (buffer_.size() - start_ >= toPop)
// yes, the packet is continuous in the internal buffer
return &buffer_[0] + start_;
else
{
// no, the packet spans then end and the beginning of the buffer
// and it must be reconstructed.
// Is the temporary internal outputBuffer large enough?
if (outputBuffer_.size() < toPop)
outputBuffer_.resize(toPop * 2);
memcpy(&outputBuffer_[0],
&buffer_[0] + start_,
buffer_.size() - start_);
memcpy(&outputBuffer_[0] + (buffer_.size() - start_),
&buffer_[0],
toPop - (buffer_.size() - start_));
//start_ = toPop - (buffer_.size() - start_);
//dataSize_ -= toPop;
return &outputBuffer_[0];
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Daniel Kirchner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#ifndef XXH64_HPP
#define XXH64_HPP
#include <string>
#include <cstdint>
#include "lz4/xxhash.h"
class xxh64 {
static constexpr uint64_t PRIME1 = 11400714785074694791ULL;
static constexpr uint64_t PRIME2 = 14029467366897019727ULL;
static constexpr uint64_t PRIME3 = 1609587929392839161ULL;
static constexpr uint64_t PRIME4 = 9650029242287828579ULL;
static constexpr uint64_t PRIME5 = 2870177450012600261ULL;
static constexpr uint64_t rotl(uint64_t x, int r) {
return ((x << r) | (x >> (64 - r)));
}
static constexpr uint64_t mix1(const uint64_t h, const uint64_t prime, int rshift) {
return (h ^ (h >> rshift)) * prime;
}
static constexpr uint64_t mix2(const uint64_t p, const uint64_t v = 0) {
return rotl (v + p * PRIME2, 31) * PRIME1;
}
static constexpr uint64_t mix3(const uint64_t h, const uint64_t v) {
return (h ^ mix2 (v)) * PRIME1 + PRIME4;
}
#ifdef XXH64_BIG_ENDIAN
static constexpr uint32_t endian32(const char *v) {
return uint32_t(uint8_t(v[3]))|(uint32_t(uint8_t(v[2]))<<8)
|(uint32_t(uint8_t(v[1]))<<16)|(uint32_t(uint8_t(v[0]))<<24);
}
static constexpr uint64_t endian64(const char *v) {
return uint64_t(uint8_t(v[7]))|(uint64_t(uint8_t(v[6]))<<8)
|(uint64_t(uint8_t(v[5]))<<16)|(uint64_t(uint8_t(v[4]))<<24)
|(uint64_t(uint8_t(v[3]))<<32)|(uint64_t(uint8_t(v[2]))<<40)
|(uint64_t(uint8_t(v[1]))<<48)|(uint64_t(uint8_t(v[0]))<<56);
}
#else
static constexpr uint32_t endian32(const char *v) {
return uint32_t(uint8_t(v[0]))|(uint32_t(uint8_t(v[1]))<<8)
|(uint32_t(uint8_t(v[2]))<<16)|(uint32_t(uint8_t(v[3]))<<24);
}
static constexpr uint64_t endian64 (const char *v) {
return uint64_t(uint8_t(v[0]))|(uint64_t(uint8_t(v[1]))<<8)
|(uint64_t(uint8_t(v[2]))<<16)|(uint64_t(uint8_t(v[3]))<<24)
|(uint64_t(uint8_t(v[4]))<<32)|(uint64_t(uint8_t(v[5]))<<40)
|(uint64_t(uint8_t(v[6]))<<48)|(uint64_t(uint8_t(v[7]))<<56);
}
#endif
static constexpr uint64_t fetch64(const char *p, const uint64_t v = 0) {
return mix2 (endian64 (p), v);
}
static constexpr uint64_t fetch32(const char *p) {
return uint64_t (endian32 (p)) * PRIME1;
}
static constexpr uint64_t fetch8(const char *p) {
return uint8_t (*p) * PRIME5;
}
static constexpr uint64_t finalize(const uint64_t h, const char *p, uint64_t len) {
return (len >= 8) ? (finalize (rotl (h ^ fetch64 (p), 27) * PRIME1 + PRIME4, p + 8, len - 8)) :
((len >= 4) ? (finalize (rotl (h ^ fetch32 (p), 23) * PRIME2 + PRIME3, p + 4, len - 4)) :
((len > 0) ? (finalize (rotl (h ^ fetch8 (p), 11) * PRIME1, p + 1, len - 1)) :
(mix1 (mix1 (mix1 (h, PRIME2, 33), PRIME3, 29), 1, 32))));
}
static constexpr uint64_t h32bytes(const char *p, uint64_t len, const uint64_t v1,const uint64_t v2, const uint64_t v3, const uint64_t v4) {
return (len >= 32) ? h32bytes (p + 32, len - 32, fetch64 (p, v1), fetch64 (p + 8, v2), fetch64 (p + 16, v3), fetch64 (p + 24, v4)) :
mix3 (mix3 (mix3 (mix3 (rotl (v1, 1) + rotl (v2, 7) + rotl (v3, 12) + rotl (v4, 18), v1), v2), v3), v4);
}
static constexpr uint64_t h32bytes(const char *p, uint64_t len, const uint64_t seed) {
return h32bytes (p, len, seed + PRIME1 + PRIME2, seed + PRIME2, seed, seed - PRIME1);
}
public:
static constexpr uint64_t hash(const char *p, uint64_t len, uint64_t seed=0) {
return finalize((len >= 32 ? h32bytes(p, len, seed) : seed + PRIME5) + len, p + (len & ~0x1F), len & 0x1F);
}
template <size_t N>
static constexpr uint64_t hash(const char(&s)[N], uint64_t seed=0) {
return hash(s, N - 1, seed);
}
static uint64_t hash(string_view str, uint64_t seed=0) {
return XXH64(str.data(), str.size(), seed);
}
};
constexpr uint32_t operator"" _XXH(const char* s, size_t size) {
return xxh64::hash(s, size, 0);
}
#endif /* !defined XXH64_HPP */
<commit_msg>Added missing string_view include<commit_after>/*
* Copyright (c) 2015 Daniel Kirchner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#ifndef XXH64_HPP
#define XXH64_HPP
#include <string>
#include <cstdint>
#include "string_view.h"
#include "lz4/xxhash.h"
class xxh64 {
static constexpr uint64_t PRIME1 = 11400714785074694791ULL;
static constexpr uint64_t PRIME2 = 14029467366897019727ULL;
static constexpr uint64_t PRIME3 = 1609587929392839161ULL;
static constexpr uint64_t PRIME4 = 9650029242287828579ULL;
static constexpr uint64_t PRIME5 = 2870177450012600261ULL;
static constexpr uint64_t rotl(uint64_t x, int r) {
return ((x << r) | (x >> (64 - r)));
}
static constexpr uint64_t mix1(const uint64_t h, const uint64_t prime, int rshift) {
return (h ^ (h >> rshift)) * prime;
}
static constexpr uint64_t mix2(const uint64_t p, const uint64_t v = 0) {
return rotl (v + p * PRIME2, 31) * PRIME1;
}
static constexpr uint64_t mix3(const uint64_t h, const uint64_t v) {
return (h ^ mix2 (v)) * PRIME1 + PRIME4;
}
#ifdef XXH64_BIG_ENDIAN
static constexpr uint32_t endian32(const char *v) {
return uint32_t(uint8_t(v[3]))|(uint32_t(uint8_t(v[2]))<<8)
|(uint32_t(uint8_t(v[1]))<<16)|(uint32_t(uint8_t(v[0]))<<24);
}
static constexpr uint64_t endian64(const char *v) {
return uint64_t(uint8_t(v[7]))|(uint64_t(uint8_t(v[6]))<<8)
|(uint64_t(uint8_t(v[5]))<<16)|(uint64_t(uint8_t(v[4]))<<24)
|(uint64_t(uint8_t(v[3]))<<32)|(uint64_t(uint8_t(v[2]))<<40)
|(uint64_t(uint8_t(v[1]))<<48)|(uint64_t(uint8_t(v[0]))<<56);
}
#else
static constexpr uint32_t endian32(const char *v) {
return uint32_t(uint8_t(v[0]))|(uint32_t(uint8_t(v[1]))<<8)
|(uint32_t(uint8_t(v[2]))<<16)|(uint32_t(uint8_t(v[3]))<<24);
}
static constexpr uint64_t endian64 (const char *v) {
return uint64_t(uint8_t(v[0]))|(uint64_t(uint8_t(v[1]))<<8)
|(uint64_t(uint8_t(v[2]))<<16)|(uint64_t(uint8_t(v[3]))<<24)
|(uint64_t(uint8_t(v[4]))<<32)|(uint64_t(uint8_t(v[5]))<<40)
|(uint64_t(uint8_t(v[6]))<<48)|(uint64_t(uint8_t(v[7]))<<56);
}
#endif
static constexpr uint64_t fetch64(const char *p, const uint64_t v = 0) {
return mix2 (endian64 (p), v);
}
static constexpr uint64_t fetch32(const char *p) {
return uint64_t (endian32 (p)) * PRIME1;
}
static constexpr uint64_t fetch8(const char *p) {
return uint8_t (*p) * PRIME5;
}
static constexpr uint64_t finalize(const uint64_t h, const char *p, uint64_t len) {
return (len >= 8) ? (finalize (rotl (h ^ fetch64 (p), 27) * PRIME1 + PRIME4, p + 8, len - 8)) :
((len >= 4) ? (finalize (rotl (h ^ fetch32 (p), 23) * PRIME2 + PRIME3, p + 4, len - 4)) :
((len > 0) ? (finalize (rotl (h ^ fetch8 (p), 11) * PRIME1, p + 1, len - 1)) :
(mix1 (mix1 (mix1 (h, PRIME2, 33), PRIME3, 29), 1, 32))));
}
static constexpr uint64_t h32bytes(const char *p, uint64_t len, const uint64_t v1,const uint64_t v2, const uint64_t v3, const uint64_t v4) {
return (len >= 32) ? h32bytes (p + 32, len - 32, fetch64 (p, v1), fetch64 (p + 8, v2), fetch64 (p + 16, v3), fetch64 (p + 24, v4)) :
mix3 (mix3 (mix3 (mix3 (rotl (v1, 1) + rotl (v2, 7) + rotl (v3, 12) + rotl (v4, 18), v1), v2), v3), v4);
}
static constexpr uint64_t h32bytes(const char *p, uint64_t len, const uint64_t seed) {
return h32bytes (p, len, seed + PRIME1 + PRIME2, seed + PRIME2, seed, seed - PRIME1);
}
public:
static constexpr uint64_t hash(const char *p, uint64_t len, uint64_t seed=0) {
return finalize((len >= 32 ? h32bytes(p, len, seed) : seed + PRIME5) + len, p + (len & ~0x1F), len & 0x1F);
}
template <size_t N>
static constexpr uint64_t hash(const char(&s)[N], uint64_t seed=0) {
return hash(s, N - 1, seed);
}
static uint64_t hash(string_view str, uint64_t seed=0) {
return XXH64(str.data(), str.size(), seed);
}
};
constexpr uint32_t operator"" _XXH(const char* s, size_t size) {
return xxh64::hash(s, size, 0);
}
#endif /* !defined XXH64_HPP */
<|endoftext|> |
<commit_before>#include <string>
#include <sstream>
#include <unistd.h> // sysconf()?
#include <sys/sysinfo.h>
#include <linux/kernel.h> // SI_LOAD_SHIFT
#include "../luts.h"
std::string load_string( bool use_colors = false ) {
std::ostringstream oss;
float f = static_cast<float>(1 << SI_LOAD_SHIFT);
struct sysinfo sinfo;
sysinfo(&sinfo);
if( use_colors ) {
// Likely does not work on BSD, but not tested
unsigned number_of_cpus = sysconf( _SC_NPROCESSORS_ONLN );
float recent_load = sinfo.loads[0] / f;
// colors range from zero to twice the number of cpu's
// for the most recent load metric
unsigned load_percent = static_cast< unsigned int >(
recent_load / number_of_cpus * 0.5f * 100.0f );
if( load_percent > 100 )
load_percent = 100;
oss << load_lut[load_percent];
}
// set precision so we get results like "0.22"
oss.setf( std::ios::fixed );
oss.precision(2);
oss << sinfo.loads[0] / f << " " << sinfo.load[1] / f << " "
<< sinfo.load[2] / f;
if( use_colors )
oss << "#[fg=default,bg=default]";
return oss.str();
}
<commit_msg>added missing include "load.h"<commit_after>#include <string>
#include <sstream>
#include <unistd.h> // sysconf()?
#include <sys/sysinfo.h>
#include <linux/kernel.h> // SI_LOAD_SHIFT
#include "load.h"
#include "../luts.h"
std::string load_string( bool use_colors = false ) {
std::ostringstream oss;
float f = static_cast<float>(1 << SI_LOAD_SHIFT);
struct sysinfo sinfo;
sysinfo(&sinfo);
if( use_colors ) {
// Likely does not work on BSD, but not tested
unsigned number_of_cpus = sysconf( _SC_NPROCESSORS_ONLN );
float recent_load = sinfo.loads[0] / f;
// colors range from zero to twice the number of cpu's
// for the most recent load metric
unsigned load_percent = static_cast< unsigned int >(
recent_load / number_of_cpus * 0.5f * 100.0f );
if( load_percent > 100 )
load_percent = 100;
oss << load_lut[load_percent];
}
// set precision so we get results like "0.22"
oss.setf( std::ios::fixed );
oss.precision(2);
oss << sinfo.loads[0] / f << " " << sinfo.load[1] / f << " "
<< sinfo.load[2] / f;
if( use_colors )
oss << "#[fg=default,bg=default]";
return oss.str();
}
<|endoftext|> |
<commit_before>#include <regex>
#include <ctime>
#include "tools.h"
void validarCedula(std::string cedula)
{
std::regex cedulaRegex("\\d{10}");
if (!std::regex_match(cedula, cedulaRegex))
throw "Cédula no válida";
}
void validarTelefono(std::string telefono)
{
std::regex telefonoRegex("\\d{10}");
if (!std::regex_match(telefono, telefonoRegex))
throw "Teléfono no válido";
}
void validarString(std::string str)
{
if (str == "")
throw "Cadena vacía";
}
void validarNumero(double num)
{
if (num < 0)
throw "Número negativo.";
}
std::string estadoToString(Estado estado)
{
if (estado == Estado::libre)
return "libre";
else if (estado == Estado::mantenimiento)
return "mantenimiento";
else if (estado == Estado::ocupado)
return "ocupado";
else if (estado == Estado::reservado)
return "reservado";
else
throw "Tipo de estado no valido.";
}
std::string getFecha(time_t *fecha)
{
char buff[20];
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(fecha));
return buff;
}
time_t getFechaString(std::string fecha)
{
struct tm tm;
strptime(fecha.c_str(), "%Y-%m-%d %H:%M:%S", &tm);
time_t t = mktime(&tm); // t is now your desired time_t
return t;
}
Horario getHorario(std::string horaEntrada, std::string horaSalida)
{
Hora entrada, salida;
std::vector<std::string> elementos = split(horaEntrada,':');
entrada.hora = std::atoi(elementos[0].c_str());
entrada.minuto = std::atoi(elementos[1].c_str());
elementos.clear();
elementos=split(horaSalida,':');
salida.hora = std::atoi(elementos[0].c_str());
salida.minuto = std::atoi(elementos[1].c_str());
Horario horario;
horario.entrada = entrada;
horario.salida = salida;
return horario;
}
std::vector<std::string> split(std::string texto, char delim)
{
std::vector<std::string> elementos;
std::string aux="";
for(char a : texto){
if(a!=delim){
aux+=a;
}else{
elementos.push_back(aux);
aux="";
}
}
elementos.push_back(aux);
return elementos;
}
void validarFechas(time_t fechaReservacion, time_t fechaFinReservacion)
{
if (difftime(fechaReservacion, fechaFinReservacion) > 0)
throw "Fecha final mayor a la inicial";
}
<commit_msg>implementado<commit_after>#include <regex>
#include <ctime>
#include "tools.h"
void validarCedula(std::string cedula)
{
std::regex cedulaRegex("\\d{10}");
if (!std::regex_match(cedula, cedulaRegex))
throw "Cédula no válida";
}
void validarTelefono(std::string telefono)
{
std::regex telefonoRegex("\\d{10}");
if (!std::regex_match(telefono, telefonoRegex))
throw "Teléfono no válido";
}
void validarString(std::string str)
{
if (str == "")
throw "Cadena vacía";
}
void validarNumero(double num)
{
if (num < 0)
throw "Número negativo.";
}
std::string estadoToString(Estado estado)
{
if (estado == Estado::libre)
return "libre";
else if (estado == Estado::mantenimiento)
return "mantenimiento";
else if (estado == Estado::ocupado)
return "ocupado";
else if (estado == Estado::reservado)
return "reservado";
else
throw "Tipo de estado no valido.";
}
std::string getFecha(time_t *fecha)
{
char buff[20];
strftime(buff, 20, "%Y-%m-%d %H:%M:%S", localtime(fecha));
return buff;
}
time_t getFechaString(std::string fecha)
{
struct tm tm;
strptime(fecha.c_str(), "%Y-%m-%d %H:%M:%S", &tm);
time_t t = mktime(&tm); // t is now your desired time_t
return t;
}
Horario getHorario(std::string horaEntrada, std::string horaSalida)
{
Hora entrada, salida;
std::vector<std::string> elementos = split(horaEntrada,':');
entrada.hora = std::atoi(elementos[0].c_str());
entrada.minuto = std::atoi(elementos[1].c_str());
elementos.clear();
elementos=split(horaSalida,':');
salida.hora = std::atoi(elementos[0].c_str());
salida.minuto = std::atoi(elementos[1].c_str());
Horario horario;
horario.entrada = entrada;
horario.salida = salida;
return horario;
}
std::vector<std::string> split(std::string texto, char delim)
{
std::vector<std::string> elementos;
std::string aux="";
for(char a : texto){
if(a!=delim){
aux+=a;
}else{
elementos.push_back(aux);
aux="";
}
}
elementos.push_back(aux);
return elementos;
}
void validarFechas(time_t fechaReservacion, time_t fechaFinReservacion)
{
if (difftime(fechaReservacion, fechaFinReservacion) > 0)
throw "Fecha final mayor a la inicial";
}
Estado getEstado(std::string estadoEspacio)
{
if (estadoEspacio == "libre")
return Estado::libre;
else if (estadoEspacio == "ocupado")
return Estado::ocupado;
else if (estadoEspacio == "reservado")
return Estado::reservado;
else if (estadoEspacio == "mantenimiento")
return Estado::mantenimiento;
else
throw "Estado no válido";
}
<|endoftext|> |
<commit_before>#define __CL_ENABLE_EXCEPTIONS
#define _IN_HOST
#include <CL/cl.hpp>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <bitset>
#include "DeviceInfo.h"
#include "SharedMacros.h"
#include "SharedTypes.h"
#include "Packet.h"
const char *KERNEL_NAME = "vm";
const char *KERNEL_FILE = "kernels/vm.cl";
const char *KERNEL_BUILD_OPTIONS = "-I include";
const int NPACKET_SHIFT = ((NBYTES * 8) - 16);
const int FS_Length = 32;
const long F_Length = 0x0000ffff00000000;
void toggleState(cl::CommandQueue& commandQueue, cl::Buffer& stateBuffer, int *state);
subt *createSubt();
void validateArguments(int argc);
std::deque<bytecode> readBytecode(char *bytecodeFile);
std::deque< std::deque<bytecode> > words2Packets(std::deque<bytecode>& bytecodeWords);
int main(int argc, char **argv) {
validateArguments(argc);
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Device device;
cl::Program program;
DeviceInfo deviceInfo;
try {
/* Create a vector of available platforms. */
cl::Platform::get(&platforms);
/* Create a vector of available devices (GPU Priority). */
try {
/* Use CPU for debugging */
platforms[0].getDevices(CL_DEVICE_TYPE_CPU, &devices);
/* Use GPU in practice. */
// platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
} catch (cl::Error error) {
platforms[0].getDevices(CL_DEVICE_TYPE_CPU, &devices);
}
/* Create a platform context for the available devices. */
cl::Context context(devices);
/* Use the first available device. */
device = devices[0];
/* Get the number of compute units for the device. */
int computeUnits = deviceInfo.max_compute_units(device);
/* Get the global memory size (in bytes) of the device. */
// long globalMemSize = deviceInfo.global_mem_size(device);
/* Create a command queue for the device. */
cl::CommandQueue commandQueue = cl::CommandQueue(context, device);
/* Read the kernel program source. */
std::ifstream kernelSourceFile(KERNEL_FILE);
std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>()));
cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1));
/* Create a program in the context using the kernel source code. */
program = cl::Program(context, source);
/* Build the program for the available devices. */
program.build(devices, KERNEL_BUILD_OPTIONS);
/* Create the kernel. */
cl::Kernel kernel(program, KERNEL_NAME);
/* Calculate the number of queues we need. */
int nQueues = computeUnits * computeUnits;
/* Calculate the memory required to store the queues. The first nQueue packets are used to store
information regarding the queues themselves (head index, tail index and last operation performed). */
int qBufSize = (nQueues * QUEUE_SIZE) + nQueues;
/* Allocate memory for the queues. */
packet *queues = new packet[qBufSize];
packet *readQueues = new packet[qBufSize];
/* Initialise queue elements to zero. */
for (int i = 0; i < qBufSize; i++) {
queues[i].x = 0;
queues[i].y = 0;
readQueues[i].x = 0;
readQueues[i].y = 0;
}
/* Which stage of the READ/WRITE cycle are we in? */
int *state = new int;
*state = WRITE;
/* The code store stores bytecode in QUEUE_SIZE chunks. */
bytecode *codeStore = new bytecode[CODE_STORE_SIZE * QUEUE_SIZE];
/* Read the bytecode from file. */
std::deque<bytecode> bytecodeWords = readBytecode(argv[1]);
std::deque< std::deque<bytecode> > packets = words2Packets(bytecodeWords);
/* Populate the code store. */
codeStore[0] = 0x0000000300000000UL;
codeStore[1] = 0x4000000100000000UL;
codeStore[2] = 0x4000000200000000UL;
codeStore[3] = 0x4000000300000000UL;
codeStore[16] = 0x0000000100000100UL;
codeStore[17] = 0x6040000000000000UL;
codeStore[32] = 0x0000000100000100UL;
codeStore[33] = 0x6040000000000001UL;
codeStore[48] = 0x0000000100000100UL;
codeStore[49] = 0x6040000000000002UL;
/* Create initial packet. */
packet p = pkt_create(REFERENCE, computeUnits + 1, 0, 0, 0);
queues[nQueues] = p; // Initial packet.
queues[0].x = 1 << 16; // Tail index is 1.
queues[0].y = WRITE; // Last operation is write.
/* The subtask table. */
subt *subtaskTable = createSubt();
long avGlobalMemSize = 1024 * 1024 * 1024; // In bytes.
long dataSize = avGlobalMemSize / 4; // How many 32-bit integers?
/* Each computate unit has its own data array for storing temporary results. [input][data] */
cl_uint *data = new cl_uint[avGlobalMemSize];
/* Write input data to data buffer. */
/* :1 :255 :X :Y
nargs narg0..nargN in/out scratch */
data[0] = 3;
data[1] = 256;
data[2] = 256 + 1;
data[3] = 256 + 2;
data[data[0] + 1] = 256 + 3;
data[256] = 2;
data[256 + 1] = 7;
/* Create memory buffers on the device. */
cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(packet));
commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), queues);
cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(packet));
commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), readQueues);
cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int));
commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
cl::Buffer codeStoreBuffer = cl::Buffer(context, CL_MEM_READ_ONLY, CODE_STORE_SIZE * QUEUE_SIZE * sizeof(bytecode));
commandQueue.enqueueWriteBuffer(codeStoreBuffer, CL_TRUE, 0, CODE_STORE_SIZE * QUEUE_SIZE * sizeof(bytecode), codeStore);
cl::Buffer subtaskTableBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(subt));
commandQueue.enqueueWriteBuffer(subtaskTableBuffer, CL_TRUE, 0, sizeof(subt), subtaskTable);
cl::Buffer dataBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, dataSize * sizeof(cl_uint));
commandQueue.enqueueWriteBuffer(dataBuffer, CL_TRUE, 0, dataSize * sizeof(cl_uint), data);
/* Set kernel arguments. */
kernel.setArg(0, qBuffer);
kernel.setArg(1, rqBuffer);
kernel.setArg(2, computeUnits);
kernel.setArg(3, stateBuffer);
kernel.setArg(4, codeStoreBuffer);
kernel.setArg(5, subtaskTableBuffer);
kernel.setArg(6, dataBuffer);
/* Set the NDRange. */
cl::NDRange global(computeUnits), local(computeUnits);
/* Run the kernel on NDRange until completion. */
while (*state != COMPLETE) {
commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local);
commandQueue.finish();
toggleState(commandQueue, stateBuffer, state);
}
/* Read the modified buffers. */
commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), queues);
commandQueue.enqueueReadBuffer(dataBuffer, CL_TRUE, 0, dataSize * sizeof(cl_uint), data);
/* Print the queue details. */
for (int i = 0; i < nQueues; i++) {
int x = ((queues[i].x & 0xFFFF0000) >> 16);
int y = queues[i].x & 0xFFFF;
std::cout << "(" << x << "," << y << " " << queues[i].y << ")" << " ";
}
std::cout << std::endl;
std::cout << std::endl;
/* Print the queues. */
for (int i = nQueues; i < qBufSize; i++) {
if ((i % QUEUE_SIZE) == 0) std::cout << std::endl;
std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
}
std::cout << std::endl;
std::cout << "Result: " << data[258] << std::endl;
/* Cleanup */
delete[] queues;
delete[] readQueues;
delete[] codeStore;
delete[] data;
delete subtaskTable;
delete state;
} catch (cl::Error error) {
std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl;
std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
}
return 0;
}
void toggleState(cl::CommandQueue& commandQueue, cl::Buffer& stateBuffer, int *state) {
commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
if (*state == COMPLETE) return;
*state = (*state == WRITE) ? READ : WRITE;
commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
commandQueue.finish();
}
subt *createSubt() {
subt *table = new subt;
if (table) {
table->av_recs[0] = 1; // The first element is the top of stack index.
/* Populate the stack with the available records in the subtask table. */
for (int i = 1; i < SUBT_SIZE + 1; i++) {
table->av_recs[i] = i - 1;
}
}
return table;
}
void validateArguments(int argc) {
if (argc < 2) {
std::cout << "Usage: ./vm [bytecode-file]" << std::endl;
exit(EXIT_FAILURE);
}
}
std::deque<bytecode> readBytecode(char *bytecodeFile) {
std::ifstream f(bytecodeFile);
std::deque<bytecode> bytecodeWords;
if (f.is_open()) {
while (f.good()) {
bytecode word = 0;
for (int i = 0; i < NBYTES; i++) {
char c = f.get();
word = (word << NBYTES) + c;
}
bytecodeWords.push_back(word);
}
}
return bytecodeWords;
}
std::deque< std::deque<bytecode> > words2Packets(std::deque<bytecode>& bytecodeWords) {
int nPackets = bytecodeWords.front() >> NPACKET_SHIFT;
std::deque< std::deque<bytecode> > packets;
for (int p = 0; p < nPackets; p++) {
std::deque<bytecode> packet;
int length = 0;
for (int i = 0; i < 3; i++) {
bytecode headerWord = bytecodeWords.front();
bytecodeWords.pop_front();
if (i == 1) {
length = (headerWord & F_Length) >> FS_Length;
}
}
for (int i = 0; i < length; i++) {
bytecode payloadWord = bytecodeWords.front();
bytecodeWords.pop_front();
packet.push_back(payloadWord);
}
packets.push_back(packet);
}
return packets;
}
<commit_msg>Corrected bug in words2Packets function.<commit_after>#define __CL_ENABLE_EXCEPTIONS
#define _IN_HOST
#include <CL/cl.hpp>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <bitset>
#include "DeviceInfo.h"
#include "SharedMacros.h"
#include "SharedTypes.h"
#include "Packet.h"
const char *KERNEL_NAME = "vm";
const char *KERNEL_FILE = "kernels/vm.cl";
const char *KERNEL_BUILD_OPTIONS = "-I include";
const int NPACKET_SHIFT = ((NBYTES * 8) - 16);
const int FS_Length = 32;
const long F_Length = 0x0000ffff00000000;
void toggleState(cl::CommandQueue& commandQueue, cl::Buffer& stateBuffer, int *state);
subt *createSubt();
void validateArguments(int argc);
std::deque<bytecode> readBytecode(char *bytecodeFile);
std::deque< std::deque<bytecode> > words2Packets(std::deque<bytecode>& bytecodeWords);
int main(int argc, char **argv) {
validateArguments(argc);
std::vector<cl::Platform> platforms;
std::vector<cl::Device> devices;
cl::Device device;
cl::Program program;
DeviceInfo deviceInfo;
try {
/* Create a vector of available platforms. */
cl::Platform::get(&platforms);
/* Create a vector of available devices (GPU Priority). */
try {
/* Use CPU for debugging */
platforms[0].getDevices(CL_DEVICE_TYPE_CPU, &devices);
/* Use GPU in practice. */
// platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
} catch (cl::Error error) {
platforms[0].getDevices(CL_DEVICE_TYPE_CPU, &devices);
}
/* Create a platform context for the available devices. */
cl::Context context(devices);
/* Use the first available device. */
device = devices[0];
/* Get the number of compute units for the device. */
int computeUnits = deviceInfo.max_compute_units(device);
/* Get the global memory size (in bytes) of the device. */
// long globalMemSize = deviceInfo.global_mem_size(device);
/* Create a command queue for the device. */
cl::CommandQueue commandQueue = cl::CommandQueue(context, device);
/* Read the kernel program source. */
std::ifstream kernelSourceFile(KERNEL_FILE);
std::string kernelSource(std::istreambuf_iterator<char>(kernelSourceFile), (std::istreambuf_iterator<char>()));
cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length() + 1));
/* Create a program in the context using the kernel source code. */
program = cl::Program(context, source);
/* Build the program for the available devices. */
program.build(devices, KERNEL_BUILD_OPTIONS);
/* Create the kernel. */
cl::Kernel kernel(program, KERNEL_NAME);
/* Calculate the number of queues we need. */
int nQueues = computeUnits * computeUnits;
/* Calculate the memory required to store the queues. The first nQueue packets are used to store
information regarding the queues themselves (head index, tail index and last operation performed). */
int qBufSize = (nQueues * QUEUE_SIZE) + nQueues;
/* Allocate memory for the queues. */
packet *queues = new packet[qBufSize];
packet *readQueues = new packet[qBufSize];
/* Initialise queue elements to zero. */
for (int i = 0; i < qBufSize; i++) {
queues[i].x = 0;
queues[i].y = 0;
readQueues[i].x = 0;
readQueues[i].y = 0;
}
/* Which stage of the READ/WRITE cycle are we in? */
int *state = new int;
*state = WRITE;
/* The code store stores bytecode in QUEUE_SIZE chunks. */
bytecode *codeStore = new bytecode[CODE_STORE_SIZE * QUEUE_SIZE];
/* Read the bytecode from file. */
std::deque<bytecode> bytecodeWords = readBytecode(argv[1]);
std::deque< std::deque<bytecode> > packets = words2Packets(bytecodeWords);
/* Populate the code store. */
for (std::deque< std::deque<bytecode> >::iterator iterP = packets.begin(); iterP != packets.end(); iterP++) {
std::deque<bytecode> packet = *iterP;
for (std::deque<bytecode>::iterator iterW = packet.begin(); iterW != packet.end(); iterW++) {
bytecode word = *iterW;
std::bitset<64> x(word);
std::cout << x << std::endl;
int packetN = iterP - packets.begin(); // Which packet?
int wordN = iterW - packet.begin(); // Which word?
codeStore[(packetN * QUEUE_SIZE) + wordN] = word;
}
std::cout << std::endl;
}
/* Create initial packet. */
packet p = pkt_create(REFERENCE, computeUnits + 1, 0, 0, 0);
queues[nQueues] = p; // Initial packet.
queues[0].x = 1 << 16; // Tail index is 1.
queues[0].y = WRITE; // Last operation is write.
/* The subtask table. */
subt *subtaskTable = createSubt();
long avGlobalMemSize = 1024 * 1024 * 1024; // In bytes.
long dataSize = avGlobalMemSize / 4; // How many 32-bit integers?
/* Each computate unit has its own data array for storing temporary results. [input][data] */
cl_uint *data = new cl_uint[avGlobalMemSize];
/* Write input data to data buffer. */
/* :1 :255 :X :Y
nargs narg0..nargN in/out scratch */
data[0] = 3;
data[1] = 256;
data[2] = 256 + 1;
data[3] = 256 + 2;
data[data[0] + 1] = 256 + 3;
data[256] = 2;
data[256 + 1] = 7;
/* Create memory buffers on the device. */
cl::Buffer qBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(packet));
commandQueue.enqueueWriteBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), queues);
cl::Buffer rqBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, qBufSize * sizeof(packet));
commandQueue.enqueueWriteBuffer(rqBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), readQueues);
cl::Buffer stateBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(int));
commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
cl::Buffer codeStoreBuffer = cl::Buffer(context, CL_MEM_READ_ONLY, CODE_STORE_SIZE * QUEUE_SIZE * sizeof(bytecode));
commandQueue.enqueueWriteBuffer(codeStoreBuffer, CL_TRUE, 0, CODE_STORE_SIZE * QUEUE_SIZE * sizeof(bytecode), codeStore);
cl::Buffer subtaskTableBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, sizeof(subt));
commandQueue.enqueueWriteBuffer(subtaskTableBuffer, CL_TRUE, 0, sizeof(subt), subtaskTable);
cl::Buffer dataBuffer = cl::Buffer(context, CL_MEM_READ_WRITE, dataSize * sizeof(cl_uint));
commandQueue.enqueueWriteBuffer(dataBuffer, CL_TRUE, 0, dataSize * sizeof(cl_uint), data);
/* Set kernel arguments. */
kernel.setArg(0, qBuffer);
kernel.setArg(1, rqBuffer);
kernel.setArg(2, computeUnits);
kernel.setArg(3, stateBuffer);
kernel.setArg(4, codeStoreBuffer);
kernel.setArg(5, subtaskTableBuffer);
kernel.setArg(6, dataBuffer);
/* Set the NDRange. */
cl::NDRange global(computeUnits), local(computeUnits);
/* Run the kernel on NDRange until completion. */
while (*state != COMPLETE) {
commandQueue.enqueueNDRangeKernel(kernel, cl::NullRange, global, local);
commandQueue.finish();
toggleState(commandQueue, stateBuffer, state);
}
/* Read the modified buffers. */
commandQueue.enqueueReadBuffer(qBuffer, CL_TRUE, 0, qBufSize * sizeof(packet), queues);
commandQueue.enqueueReadBuffer(dataBuffer, CL_TRUE, 0, dataSize * sizeof(cl_uint), data);
/* Print the queue details. */
for (int i = 0; i < nQueues; i++) {
int x = ((queues[i].x & 0xFFFF0000) >> 16);
int y = queues[i].x & 0xFFFF;
std::cout << "(" << x << "," << y << " " << queues[i].y << ")" << " ";
}
std::cout << std::endl;
std::cout << std::endl;
/* Print the queues. */
for (int i = nQueues; i < qBufSize; i++) {
if ((i % QUEUE_SIZE) == 0) std::cout << std::endl;
std::cout << "(" << queues[i].x << " " << queues[i].y << ")" << " ";
}
std::cout << std::endl;
std::cout << "Result: " << data[258] << std::endl;
/* Cleanup */
delete[] queues;
delete[] readQueues;
delete[] codeStore;
delete[] data;
delete subtaskTable;
delete state;
} catch (cl::Error error) {
std::cout << "EXCEPTION: " << error.what() << " [" << error.err() << "]" << std::endl;
std::cout << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
}
return 0;
}
void toggleState(cl::CommandQueue& commandQueue, cl::Buffer& stateBuffer, int *state) {
commandQueue.enqueueReadBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
if (*state == COMPLETE) return;
*state = (*state == WRITE) ? READ : WRITE;
commandQueue.enqueueWriteBuffer(stateBuffer, CL_TRUE, 0, sizeof(int), state);
commandQueue.finish();
}
subt *createSubt() {
subt *table = new subt;
if (table) {
table->av_recs[0] = 1; // The first element is the top of stack index.
/* Populate the stack with the available records in the subtask table. */
for (int i = 1; i < SUBT_SIZE + 1; i++) {
table->av_recs[i] = i - 1;
}
}
return table;
}
void validateArguments(int argc) {
if (argc < 2) {
std::cout << "Usage: ./vm [bytecode-file]" << std::endl;
exit(EXIT_FAILURE);
}
}
std::deque<bytecode> readBytecode(char *bytecodeFile) {
std::ifstream f(bytecodeFile);
std::deque<bytecode> bytecodeWords;
if (f.is_open()) {
while (f.good()) {
bytecode word = 0;
for (int i = 0; i < NBYTES; i++) {
char c = f.get();
word = (word << NBYTES) + c;
}
bytecodeWords.push_back(word);
}
}
return bytecodeWords;
}
std::deque< std::deque<bytecode> > words2Packets(std::deque<bytecode>& bytecodeWords) {
int nPackets = bytecodeWords.front() >> NPACKET_SHIFT; bytecodeWords.pop_front();
std::deque< std::deque<bytecode> > packets;
for (int p = 0; p < nPackets; p++) {
std::deque<bytecode> packet;
int length = 0;
for (int i = 0; i < 3; i++) {
bytecode headerWord = bytecodeWords.front();
bytecodeWords.pop_front();
if (i == 0) {
length = (headerWord & F_Length) >> FS_Length;
}
}
for (int i = 0; i < length; i++) {
bytecode payloadWord = bytecodeWords.front();
bytecodeWords.pop_front();
packet.push_back(payloadWord);
}
packets.push_back(packet);
}
return packets;
}
<|endoftext|> |
<commit_before>// symbiosis: A hacky and lightweight compiler framework
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
using namespace std;
namespace symbiosis {
bool am_i_pic = false;
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
//printf("\n");
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
int parameter_count = 0;
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
constexpr int parameters_max = 3;
void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
if (out_c + l > out_code_end) throw exception("Code: Out of memory");
for (uchar * b = s; b < e; b++, out_c++) {
*out_c = *b;
}
dump(s, l);
}
bool intel() { return true; }
bool arm() { return false; }
id add_parameter(id p) {
if (parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
//cout << "parameter_count: " << parameter_count << " "; p.describe();
if (p.is_charp()) {
if (!am_i_pic) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
//cout << "is_integer" << endl;
if (intel()) {
//cout << "intel" << endl;
if (p.is_32()) {
//cout << "is_32" << endl;
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
//cout << "is_64" << endl;
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
} else if (arm()) {
emit(register_parameters_intel_32[parameter_count]);
}
}
++parameter_count;
return p;
}
void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit("\xe9"); // JMP
emit(call_offset(out_current_code_pos, f), 4);
}
void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit("\xe8"); // call
emit(call_offset(out_current_code_pos, f), 4);
parameter_count = 0;
}
void __vararg_call(void *f) {
emit("\x30\xc0"); // xor al,al
call(f);
}
size_t __p = 0;
void f(const char *s, int i) {
__p += (size_t)s + i;
}
bool __am_i_pic() {
uchar *p = (uchar *)__am_i_pic;
int i = 0;
uchar c = 0;
do {
c = p[i++];
} while (i < 10 && c != 0x48 && c != 0xbf);
return c == 0x48;
}
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
am_i_pic = __am_i_pic();
printf("am_i_pic: %d\n", am_i_pic);
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
//printf("code: %zu\n", out_code_end - out_code_start);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
//printf("strings: %zu\n", out_strings_end - out_strings_start);
out_s = out_strings_start;
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<commit_msg>Added cpu check.<commit_after>// symbiosis: A hacky and lightweight compiler framework
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
using namespace std;
namespace symbiosis {
bool intel = false;
bool arm = false;
bool am_i_pic = false;
void figure_out_cpu_architecture() {
uchar *p = (uchar *)figure_out_cpu_architecture;
if (p[3] == 0xe9 || p[3] == 0xe5) { cout << "ARM" << endl;
arm = true; return }
cout << "Unknown CPU id: "; dump(p, 4);
}
bool __am_i_pic() {
uchar *p = (uchar *)__am_i_pic;
int i = 0;
uchar c = 0;
do {
c = p[i++];
} while (i < 10 && c != 0x48 && c != 0xbf);
return c == 0x48;
}
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
//printf("\n");
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
int parameter_count = 0;
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
constexpr int parameters_max = 3;
void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
if (out_c + l > out_code_end) throw exception("Code: Out of memory");
for (uchar * b = s; b < e; b++, out_c++) {
*out_c = *b;
}
dump(s, l);
}
bool intel() { return true; }
id add_parameter(id p) {
if (parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
//cout << "parameter_count: " << parameter_count << " "; p.describe();
if (p.is_charp()) {
if (!am_i_pic) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
//cout << "is_integer" << endl;
if (intel) {
//cout << "intel" << endl;
if (p.is_32()) {
//cout << "is_32" << endl;
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
//cout << "is_64" << endl;
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
} else if (arm) {
emit(register_parameters_intel_32[parameter_count]);
}
}
++parameter_count;
return p;
}
void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit("\xe9"); // JMP
emit(call_offset(out_current_code_pos, f), 4);
}
void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit("\xe8"); // call
emit(call_offset(out_current_code_pos, f), 4);
parameter_count = 0;
}
void __vararg_call(void *f) {
emit("\x30\xc0"); // xor al,al
call(f);
}
size_t __p = 0;
void f(const char *s, int i) {
__p += (size_t)s + i;
}
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
figure_out_cpu_architecture();
am_i_pic = __am_i_pic();
printf("am_i_pic: %d\n", am_i_pic);
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
//printf("code: %zu\n", out_code_end - out_code_start);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
//printf("strings: %zu\n", out_strings_end - out_strings_start);
out_s = out_strings_start;
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<|endoftext|> |
<commit_before>// symbiosis: A framework for toy compilers
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
#include <functional>
#include "cpu_defines.hpp"
using namespace std;
namespace symbiosis {
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
}
#ifdef __x86_64__
bool intel = true;
bool arm = false;
#endif
#ifdef __arm__
bool intel = false;
bool arm = true;
#endif
bool pic_mode;
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
constexpr int parameters_max = 3;
class Backend {
vector<function<void()> > callbacks;
public:
int parameter_count = 0;
Backend() { }
virtual ~Backend() { }
void callback(function<void()> f) { callbacks.push_back(f); }
void perform_callbacks() {
for (size_t i = 0; i < callbacks.size(); ++i) { callbacks[i](); }}
virtual void add_parameter(id p) = 0;
virtual void jmp(void *f) = 0;
virtual void __call(void *f) = 0;
virtual void __vararg_call(void *f) = 0;
virtual void emit_byte(uchar uc) = 0;
virtual void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
for (uchar * b = s; b < e; b++) emit_byte(*b);
//dump(out_start, l);
}
};
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
class Intel : public Backend {
public:
Intel() : Backend() { }
void emit_byte(uchar c) {
if (out_c + 1 > out_code_end) throw exception("Code: Out of memory");
*out_c = c;
out_c++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_JMP_e9);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_CALL_e8);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __vararg_call(void *f) {
emit_byte(I_XOR_30); emit_byte(0xc0); // xor al,al
__call(f);
}
};
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
class Arm : public Backend {
int ofs = 1;
public:
Arm() : Backend() { alloc_next_32_bits(); }
void alloc_next_32_bits() {
if (out_c + 4 > out_code_end) throw exception("Code: Out of memory");
out_c += 4;
ofs = 1;
}
void emit_byte(uchar c) {
printf(".%02x", c);
*(out_c - ofs) = c;
ofs++;
if (ofs == 5) {
if (out_c > out_code_start) { printf("<<"); dump(out_c - 4, 4); printf(">>"); }
alloc_next_32_bits();
}
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set string ref for : " <<
parameter_count << endl; });
} else {
throw exception("pic mode not supported yet!");
//uchar *out_current_code_pos = out_c;
//emit(register_rip_relative_parameters_intel_64[parameter_count]);
//emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
callback([=]() {
cout << "Would set imm for : " << parameter_count << endl; });
} else if (p.is_64()) {
throw exception("64bit not supported yet!");
}
} else {
//cout << "No integer not supported yet" << endl;
throw exception("No integer not supported yet");
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_B_08);
emit(call_offset(out_current_code_pos, f), 3);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_BL_eb);
emit(call_offset(out_current_code_pos, f), 3);
perform_callbacks();
}
virtual void __vararg_call(void *f) {
throw exception("No arm support yet!");
}
};
Backend* backend;
id add_parameter(id p) {
if (backend->parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
backend->add_parameter(p);
++backend->parameter_count;
return p;
}
void jmp(void *f) { backend->jmp(f); }
void __call(void *f) { backend->__call(f); backend->parameter_count = 0; }
void __vararg_call(void *f) { backend->__vararg_call(f); }
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
arm = true; intel = false; pic_mode = false;
cout << "intel: " << intel << ", arm: " << arm <<
", pic_mode: " << pic_mode << endl;
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
out_s = out_strings_start;
if (intel) { backend = new Intel(); }
if (arm) { backend = new Arm(); }
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<commit_msg>Fixed callback invocation.<commit_after>// symbiosis: A framework for toy compilers
//
#include "symbiosis.hpp"
#include <sys/stat.h>
#include <iostream>
#include <vector>
#include <functional>
#include "cpu_defines.hpp"
using namespace std;
namespace symbiosis {
void dump(uchar* start, size_t s) {
for (size_t i = 0; i < s; i++) {
printf("%02x ", start[i]);
}
}
#ifdef __x86_64__
bool intel = true;
bool arm = false;
#endif
#ifdef __arm__
bool intel = false;
bool arm = true;
#endif
bool pic_mode;
class exception : public std::exception {
const char *what_;
public:
exception(const char *w) : what_(w) { }
virtual ~exception() throw() { }
virtual const char* what() const throw() { return what_; }
};
char *command_file = 0;;
#define M10(v, b) #v #b
#define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v)
#define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v)
#define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v)
#define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v)
uchar *virtual_code_start = 0;
uchar *virtual_code_end = 0;
uchar *out_code_start = 0;
uchar *out_code_end = 0;
uchar *out_c = 0;
uchar *out_c0 = 0;
uchar *virtual_strings_start = 0;
uchar *virtual_strings_end = 0;
uchar *out_strings_start = 0;
uchar *out_strings_end = 0;
uchar *out_s = 0;
#define STRINGS_START "STRINGS_START"
#define STRINGS_END "STRINGS_END"
unsigned int _i32 = 0;
const char* id::i32() {
if (virtual_adr) { _i32 = (size_t)virtual_adr;
//printf("virtual_adr: %x\n", _i32);
return (const char*)&_i32; }
if (type == T_UINT) return (const char*)&d.ui;
return (const char*)&d.i;
}
const char* id::i64() {
if (type == T_ULONG) return (const char*)&d.ul;
return (const char*)&d.l;
}
vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong",
"charp", "float", "double"};
void id::describe() {
if (type > type_str.size() - 1) {
cout << "<id:" << type << ">";
} else {
cout << type_str[type];
}
cout << endl;
}
id id::operator()(id i) { add_parameter(i); return i; }
id_new::id_new(const char *p) : id(p) {
virtual_adr = virtual_strings_start + (out_s - out_strings_start);
virtual_size = strlen(p);
if (out_s + virtual_size + 1 > out_strings_end)
throw exception("Strings: Out of memory");
memcpy(out_s, p, virtual_size + 1);
out_s += virtual_size + 1;
};
const char *reserved_strings[] = { STRINGS_START,
M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc)
STRINGS_END };
#define FIND(v) { \
pos = 0; \
bool found = false; \
for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \
for (int j = 0; j < v##_s; j++) { \
if (buf[i + j] != v[j]) break; \
if (j == v##_s - 1) { \
pos = i; \
found = true; \
} \
} \
} }
uchar buf[200 * 1024];
FILE* input = 0;
size_t input_size = 0;
void find_space(uchar* start, size_t start_s,
uchar* end, size_t end_s, uchar **out_start, uchar **out_end) {
if (!input) {
input = fopen(command_file, "r");
if (!input) { fprintf(stderr, "Failed\n"); }
input_size = fread(buf, 1, sizeof(buf), input);
}
size_t pos = 0, s = 0, e = 0;
FIND(start); s = pos;
FIND(end); e = pos;
*out_start = &buf[s];
*out_end = &buf[e];
//printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s);
}
void write() {
FILE *out = fopen("a.out", "w");
fwrite(buf, 1, input_size, out);
fclose(out);
printf("Writing a.out\n");
chmod("a.out", 0777);
}
int __offset = 0;
const char* call_offset(uchar *out_current_code_pos, void *__virt_f) {
auto virt_f = (uchar*)__virt_f;
ssize_t out_start_distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = virt_f - virtual_code_start;
__offset = virt_dist_from_code_start - out_start_distance - 5;
cout << "__virt_f: " << __virt_f << endl;
//cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl;
return (const char*)&__offset;
}
const char* rip_relative_offset(uchar *out_current_code_pos,
uchar *virt_adr) {
ssize_t distance = out_current_code_pos - out_code_start;
ssize_t virt_dist_from_code_start = (size_t)virt_adr -
(size_t)virtual_code_start - distance;
__offset = virt_dist_from_code_start - 7;
printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n",
(size_t)virt_adr, __offset,
(size_t)(out_s - out_strings_start));
return (const char*)&__offset;
}
constexpr int parameters_max = 3;
class Backend {
vector<function<void()> > callbacks;
public:
int parameter_count = 0;
Backend() { }
virtual ~Backend() { }
void callback(function<void()> f) { callbacks.push_back(f); }
void perform_callbacks() {
for (size_t i = 0; i < callbacks.size(); ++i) { callbacks[i](); }
callbacks.clear();
}
virtual void add_parameter(id p) = 0;
virtual void jmp(void *f) = 0;
virtual void __call(void *f) = 0;
virtual void __vararg_call(void *f) = 0;
virtual void emit_byte(uchar uc) = 0;
virtual void emit(const char* _s, size_t _l = 0) {
size_t l = _l > 0 ? _l : strlen(_s);
uchar *s = (uchar *)_s; uchar *e = s + l;
for (uchar * b = s; b < e; b++) emit_byte(*b);
//dump(out_start, l);
}
};
const char *register_parameters_intel_32[] = {
"\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ };
const char *register_rip_relative_parameters_intel_64[] = {
"\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */
"\x48\x8d\x15" /* rdx */ };
const char *register_parameters_intel_64[] = {
"\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ };
class Intel : public Backend {
public:
Intel() : Backend() { }
void emit_byte(uchar c) {
if (out_c + 1 > out_code_end) throw exception("Code: Out of memory");
*out_c = c;
out_c++;
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else {
uchar *out_current_code_pos = out_c;
emit(register_rip_relative_parameters_intel_64[parameter_count]);
emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_intel_32[parameter_count]);
emit(p.i32(), 4);
} else if (p.is_64()) {
emit(register_parameters_intel_64[parameter_count]);
emit(p.i64(), 8);
}
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_JMP_e9);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(I_CALL_e8);
emit(call_offset(out_current_code_pos, f), 4);
}
virtual void __vararg_call(void *f) {
emit_byte(I_XOR_30); emit_byte(0xc0); // xor al,al
__call(f);
}
};
const char *register_parameters_arm_32[] = {
"\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ };
class Arm : public Backend {
int ofs = 1;
public:
Arm() : Backend() { alloc_next_32_bits(); }
void alloc_next_32_bits() {
if (out_c + 4 > out_code_end) throw exception("Code: Out of memory");
out_c += 4;
ofs = 1;
}
void emit_byte(uchar c) {
printf(".%02x", c);
*(out_c - ofs) = c;
ofs++;
if (ofs == 5) {
if (out_c > out_code_start) { printf("<<"); dump(out_c - 4, 4); printf(">>"); }
alloc_next_32_bits();
}
}
virtual void add_parameter(id p) {
if (p.is_charp()) {
if (!pic_mode) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
int pc = parameter_count;
callback([pc]() {
cout << "Would set string ref for : " <<
pc << endl; });
} else {
throw exception("pic mode not supported yet!");
//uchar *out_current_code_pos = out_c;
//emit(register_rip_relative_parameters_intel_64[parameter_count]);
//emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4);
}
} else if (p.is_integer()) {
if (p.is_32()) {
emit(register_parameters_arm_32[parameter_count], 3);
uchar *ldr_p = out_c - 1;
emit("\x12");
int pc = parameter_count;
callback([pc]() {
cout << "Would set imm for : " << pc << endl; });
} else if (p.is_64()) {
throw exception("64bit not supported yet!");
}
} else {
//cout << "No integer not supported yet" << endl;
throw exception("No integer not supported yet");
}
}
virtual void jmp(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_B_08);
emit(call_offset(out_current_code_pos, f), 3);
}
virtual void __call(void *f) {
uchar *out_current_code_pos = out_c;
emit_byte(A_BL_eb);
emit(call_offset(out_current_code_pos, f), 3);
perform_callbacks();
}
virtual void __vararg_call(void *f) {
throw exception("No arm support yet!");
}
};
Backend* backend;
id add_parameter(id p) {
if (backend->parameter_count >= parameters_max) {
fprintf(stderr, "Too many parameters!\n");
return p;
}
backend->add_parameter(p);
++backend->parameter_count;
return p;
}
void jmp(void *f) { backend->jmp(f); }
void __call(void *f) { backend->__call(f); backend->parameter_count = 0; }
void __vararg_call(void *f) { backend->__vararg_call(f); }
void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) {
arm = true; intel = false; pic_mode = false;
cout << "intel: " << intel << ", arm: " << arm <<
", pic_mode: " << pic_mode << endl;
command_file = c;
virtual_code_start = start;
virtual_code_end = end;
find_space(start, ss, end, es, &out_code_start,
&out_code_end);
virtual_strings_start = (uchar *)STRINGS_START;
virtual_strings_end = (uchar *)STRINGS_END;
out_c = out_code_start;
find_space(virtual_strings_start, strlen(STRINGS_START),
virtual_strings_end, strlen(STRINGS_END),
&out_strings_start, &out_strings_end);
out_s = out_strings_start;
if (intel) { backend = new Intel(); }
if (arm) { backend = new Arm(); }
}
void finish() {
jmp(virtual_code_end);
write();
}
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <minizinc/model.hh>
#include <minizinc/exception.hh>
namespace MiniZinc {
Model::Model(void) : _parent(NULL) {
GC::add(this);
}
Model::~Model(void) {
for (unsigned int j=0; j<_items.size(); j++) {
Item* i = _items[j];
if (IncludeI* ii = i->dyn_cast<IncludeI>()) {
if (ii->own() && ii->_m) {
delete ii->_m;
ii->_m = NULL;
}
}
}
GC::remove(this);
}
void
Model::registerFn(FunctionI* fi) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::iterator i_id = m->fnmap.find(fi->_id);
if (i_id == m->fnmap.end()) {
// new element
std::vector<FunctionI*> v; v.push_back(fi);
m->fnmap.insert(std::pair<ASTString,std::vector<FunctionI*> >(fi->_id,v));
} else {
// add to list of existing elements
std::vector<FunctionI*>& v = i_id->second;
for (unsigned int i=0; i<v.size(); i++) {
if (v[i]->_params.size() == fi->_params.size()) {
bool alleq=true;
for (unsigned int j=0; j<fi->_params.size(); j++) {
if (v[i]->_params[j]->_type != fi->_params[j]->_type) {
alleq=false; break;
}
}
if (alleq) {
throw TypeError(fi->_loc,
"function with the same type already defined in "
+v[i]->_loc.toString());
}
}
}
v.push_back(fi);
}
}
FunctionI*
Model::matchFn(const ASTString& id,
const std::vector<Type>& t) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::iterator i_id = m->fnmap.find(id);
if (i_id == m->fnmap.end()) {
assert(false);
return NULL; // builtin not defined. TODO: should this be an error?
}
std::vector<FunctionI*>& v = i_id->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == t.size()) {
bool match=true;
for (unsigned int j=0; j<t.size(); j++) {
if (!t[j].isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
assert(false);
return NULL;
}
namespace {
class FunSort {
public:
bool operator()(FunctionI* x, FunctionI* y) const {
if (x->_params.size() < y->_params.size())
return true;
if (x->_params.size() == y->_params.size()) {
for (unsigned int i=0; i<x->_params.size(); i++) {
switch (x->_params[i]->_type.cmp(y->_params[i]->_type)) {
case -1: return true;
case 1: return false;
}
}
}
return false;
}
};
}
void
Model::sortFn(void) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FunSort funsort;
for (FnMap::iterator it=m->fnmap.begin(); it!=m->fnmap.end(); ++it) {
std::sort(it->second.begin(),it->second.end(),funsort);
}
}
FunctionI*
Model::matchFn(const ASTString& id,
const std::vector<Expression*>& args) const {
const Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::const_iterator it = m->fnmap.find(id);
if (it == m->fnmap.end()) {
return NULL;
}
const std::vector<FunctionI*>& v = it->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == args.size()) {
bool match=true;
for (unsigned int j=0; j<args.size(); j++) {
if (!args[j]->_type.isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
return NULL;
}
FunctionI*
Model::matchFn(Call* c) const {
const Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::const_iterator it = m->fnmap.find(c->_id.str());
if (it == m->fnmap.end()) {
return NULL;
}
const std::vector<FunctionI*>& v = it->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == c->_args.size()) {
bool match=true;
for (unsigned int j=0; j<c->_args.size(); j++) {
if (!c->_args[j]->_type.isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
return NULL;
}
Item*&
Model::operator[] (int i) { return _items[i]; }
const Item*
Model::operator[] (int i) const { return _items[i]; }
unsigned int
Model::size(void) const { return _items.size(); }
void
Model::compact(void) {
struct { bool operator() (const Item* i) {
return i->removed();
}} isremoved;
_items.erase(remove_if(_items.begin(),_items.end(),isremoved),
_items.end());
}
}
<commit_msg>Don't allocate new string<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <minizinc/model.hh>
#include <minizinc/exception.hh>
namespace MiniZinc {
Model::Model(void) : _parent(NULL) {
GC::add(this);
}
Model::~Model(void) {
for (unsigned int j=0; j<_items.size(); j++) {
Item* i = _items[j];
if (IncludeI* ii = i->dyn_cast<IncludeI>()) {
if (ii->own() && ii->_m) {
delete ii->_m;
ii->_m = NULL;
}
}
}
GC::remove(this);
}
void
Model::registerFn(FunctionI* fi) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::iterator i_id = m->fnmap.find(fi->_id);
if (i_id == m->fnmap.end()) {
// new element
std::vector<FunctionI*> v; v.push_back(fi);
m->fnmap.insert(std::pair<ASTString,std::vector<FunctionI*> >(fi->_id,v));
} else {
// add to list of existing elements
std::vector<FunctionI*>& v = i_id->second;
for (unsigned int i=0; i<v.size(); i++) {
if (v[i]->_params.size() == fi->_params.size()) {
bool alleq=true;
for (unsigned int j=0; j<fi->_params.size(); j++) {
if (v[i]->_params[j]->_type != fi->_params[j]->_type) {
alleq=false; break;
}
}
if (alleq) {
throw TypeError(fi->_loc,
"function with the same type already defined in "
+v[i]->_loc.toString());
}
}
}
v.push_back(fi);
}
}
FunctionI*
Model::matchFn(const ASTString& id,
const std::vector<Type>& t) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::iterator i_id = m->fnmap.find(id);
if (i_id == m->fnmap.end()) {
assert(false);
return NULL; // builtin not defined. TODO: should this be an error?
}
std::vector<FunctionI*>& v = i_id->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == t.size()) {
bool match=true;
for (unsigned int j=0; j<t.size(); j++) {
if (!t[j].isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
assert(false);
return NULL;
}
namespace {
class FunSort {
public:
bool operator()(FunctionI* x, FunctionI* y) const {
if (x->_params.size() < y->_params.size())
return true;
if (x->_params.size() == y->_params.size()) {
for (unsigned int i=0; i<x->_params.size(); i++) {
switch (x->_params[i]->_type.cmp(y->_params[i]->_type)) {
case -1: return true;
case 1: return false;
}
}
}
return false;
}
};
}
void
Model::sortFn(void) {
Model* m = this;
while (m->_parent)
m = m->_parent;
FunSort funsort;
for (FnMap::iterator it=m->fnmap.begin(); it!=m->fnmap.end(); ++it) {
std::sort(it->second.begin(),it->second.end(),funsort);
}
}
FunctionI*
Model::matchFn(const ASTString& id,
const std::vector<Expression*>& args) const {
const Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::const_iterator it = m->fnmap.find(id);
if (it == m->fnmap.end()) {
return NULL;
}
const std::vector<FunctionI*>& v = it->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == args.size()) {
bool match=true;
for (unsigned int j=0; j<args.size(); j++) {
if (!args[j]->_type.isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
return NULL;
}
FunctionI*
Model::matchFn(Call* c) const {
const Model* m = this;
while (m->_parent)
m = m->_parent;
FnMap::const_iterator it = m->fnmap.find(c->_id);
if (it == m->fnmap.end()) {
return NULL;
}
const std::vector<FunctionI*>& v = it->second;
for (unsigned int i=0; i<v.size(); i++) {
FunctionI* fi = v[i];
if (fi->_params.size() == c->_args.size()) {
bool match=true;
for (unsigned int j=0; j<c->_args.size(); j++) {
if (!c->_args[j]->_type.isSubtypeOf(fi->_params[j]->_type)) {
match=false;
break;
}
}
if (match) {
return fi;
}
}
}
return NULL;
}
Item*&
Model::operator[] (int i) { return _items[i]; }
const Item*
Model::operator[] (int i) const { return _items[i]; }
unsigned int
Model::size(void) const { return _items.size(); }
void
Model::compact(void) {
struct { bool operator() (const Item* i) {
return i->removed();
}} isremoved;
_items.erase(remove_if(_items.begin(),_items.end(),isremoved),
_items.end());
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "fakevimhandler.h"
#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextEdit>
#define EDITOR(editor, call) \
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
(ed->call); \
} else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
(ed->call); \
}
using namespace FakeVim::Internal;
typedef QLatin1String _;
/**
* Simple editor widget.
* @tparam TextEdit QTextEdit or QPlainTextEdit as base class
*/
template <typename TextEdit>
class Editor : public TextEdit
{
public:
Editor(QWidget *parent = 0) : TextEdit(parent)
{
TextEdit::setCursorWidth(0);
}
void paintEvent(QPaintEvent *e)
{
TextEdit::paintEvent(e);
// Draw text cursor.
QRect rect = TextEdit::cursorRect();
if ( e->rect().contains(rect) ) {
QPainter painter(TextEdit::viewport());
if ( TextEdit::overwriteMode() ) {
QFontMetrics fm(TextEdit::font());
rect.setWidth(fm.width(QLatin1Char('m')));
painter.setPen(Qt::NoPen);
painter.setBrush(TextEdit::palette().color(QPalette::Base));
painter.setCompositionMode(QPainter::CompositionMode_Difference);
} else {
rect.setWidth(TextEdit::cursorWidth());
painter.setPen(TextEdit::palette().color(QPalette::Text));
}
painter.drawRect(rect);
}
}
};
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{}
public slots:
void changeSelection(const QList<QTextEdit::ExtraSelection> &s)
{
EDITOR(m_widget, setExtraSelections(s));
}
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void highlightMatches(const QString &pattern)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
// Clear previous highlights.
ed->selectAll();
QTextCursor cur = ed->textCursor();
QTextEdit::ExtraSelection selection;
selection.format.setBackground(Qt::yellow);
// Highlight matches.
QTextDocument *doc = ed->document();
QRegExp re(pattern);
cur = doc->find(re);
QList<QTextEdit::ExtraSelection> selections;
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
selections.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
ed->setExtraSelections(selections);
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, tr("Information"), info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if (cmd.matches(_("q"), _("quit")) || cmd.matches(_("qa"), _("qall"))) {
QApplication::quit();
} else {
*handled = false;
return;
}
*handled = true;
}
private:
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
};
QWidget *createEditorWidget(bool usePlainTextEdit)
{
QWidget *editor = 0;
if (usePlainTextEdit) {
Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
} else {
Editor<QTextEdit> *w = new Editor<QTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
}
editor->setObjectName(_("Editor"));
editor->setFocus();
return editor;
}
void initHandler(FakeVimHandler &handler)
{
// Set some Vim options.
handler.handleCommand(_("set expandtab"));
handler.handleCommand(_("set shiftwidth=8"));
handler.handleCommand(_("set tabstop=16"));
handler.handleCommand(_("set autoindent"));
// Try to source file "fakevimrc" from current directory.
handler.handleCommand(_("source fakevimrc"));
handler.installEventFilter();
handler.setupWidget();
}
void initMainWindow(QMainWindow &mainWindow, QWidget *centralWidget, const QString &title)
{
mainWindow.setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
mainWindow.setCentralWidget(centralWidget);
mainWindow.resize(600, 650);
mainWindow.move(0, 0);
mainWindow.show();
// Set monospace font for editor and status bar.
QFont font = QApplication::font();
font.setFamily(_("Monospace"));
centralWidget->setFont(font);
mainWindow.statusBar()->setFont(font);
}
void readFile(FakeVimHandler &handler, const QString &editFileName)
{
handler.handleCommand(QString(_("r %1")).arg(editFileName));
}
void clearUndoRedo(QWidget *editor)
{
EDITOR(editor, setUndoRedoEnabled(false));
EDITOR(editor, setUndoRedoEnabled(true));
}
void connectSignals(FakeVimHandler &handler, Proxy &proxy)
{
QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)),
&proxy, SLOT(changeStatusMessage(QString,int)));
QObject::connect(&handler,
SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
&proxy, SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
&proxy, SLOT(changeExtraInformation(QString)));
QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
&proxy, SLOT(changeStatusData(QString)));
QObject::connect(&handler, SIGNAL(highlightMatches(QString)),
&proxy, SLOT(highlightMatches(QString)));
QObject::connect(&handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)),
&proxy, SLOT(handleExCommand(bool*,ExCommand)));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = app.arguments();
// If first argument is present use QPlainTextEdit instead on QTextEdit;
bool usePlainTextEdit = args.size() > 1;
// Second argument is path to file to edit.
const QString editFileName = args.value(2, QString(_("/usr/share/vim/vim73/tutor/tutor")));
// Create editor widget.
QWidget *editor = createEditorWidget(usePlainTextEdit);
// Create FakeVimHandler instance which will emulate Vim behavior in editor widget.
FakeVimHandler handler(editor, 0);
// Create main window.
QMainWindow mainWindow;
initMainWindow(mainWindow, editor, usePlainTextEdit ? _("QPlainTextEdit") : _("QTextEdit"));
// Connect slots to FakeVimHandler signals.
Proxy proxy(editor, &mainWindow);
connectSignals(handler, proxy);
// Initialize FakeVimHandler.
initHandler(handler);
// Read file content to editor.
readFile(handler, editFileName);
// Clear undo and redo queues.
clearUndoRedo(editor);
return app.exec();
}
#include "main.moc"
<commit_msg>Redraw cursor correctly with width of current character<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "fakevimhandler.h"
#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextEdit>
#define EDITOR(editor, call) \
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
(ed->call); \
} else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
(ed->call); \
}
using namespace FakeVim::Internal;
typedef QLatin1String _;
/**
* Simple editor widget.
* @tparam TextEdit QTextEdit or QPlainTextEdit as base class
*/
template <typename TextEdit>
class Editor : public TextEdit
{
public:
Editor(QWidget *parent = 0) : TextEdit(parent)
{
TextEdit::setCursorWidth(0);
}
void paintEvent(QPaintEvent *e)
{
TextEdit::paintEvent(e);
if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) {
QRect rect = m_cursorRect;
m_cursorRect = QRect();
TextEdit::update(rect);
}
// Draw text cursor.
QRect rect = TextEdit::cursorRect();
if ( e->rect().intersects(rect) ) {
QPainter painter(TextEdit::viewport());
if ( TextEdit::overwriteMode() ) {
QFontMetrics fm(TextEdit::font());
const int position = TextEdit::textCursor().position();
const QChar c = TextEdit::document()->characterAt(position);
rect.setWidth(fm.width(c));
painter.setPen(Qt::NoPen);
painter.setBrush(TextEdit::palette().color(QPalette::Base));
painter.setCompositionMode(QPainter::CompositionMode_Difference);
} else {
rect.setWidth(TextEdit::cursorWidth());
painter.setPen(TextEdit::palette().color(QPalette::Text));
}
painter.drawRect(rect);
m_cursorRect = rect;
}
}
private:
QRect m_cursorRect;
};
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{}
public slots:
void changeSelection(const QList<QTextEdit::ExtraSelection> &s)
{
EDITOR(m_widget, setExtraSelections(s));
}
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void highlightMatches(const QString &pattern)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
// Clear previous highlights.
ed->selectAll();
QTextCursor cur = ed->textCursor();
QTextEdit::ExtraSelection selection;
selection.format.setBackground(Qt::yellow);
// Highlight matches.
QTextDocument *doc = ed->document();
QRegExp re(pattern);
cur = doc->find(re);
QList<QTextEdit::ExtraSelection> selections;
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
selections.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
ed->setExtraSelections(selections);
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, tr("Information"), info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if (cmd.matches(_("q"), _("quit")) || cmd.matches(_("qa"), _("qall"))) {
QApplication::quit();
} else {
*handled = false;
return;
}
*handled = true;
}
private:
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
};
QWidget *createEditorWidget(bool usePlainTextEdit)
{
QWidget *editor = 0;
if (usePlainTextEdit) {
Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
} else {
Editor<QTextEdit> *w = new Editor<QTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
}
editor->setObjectName(_("Editor"));
editor->setFocus();
return editor;
}
void initHandler(FakeVimHandler &handler)
{
// Set some Vim options.
handler.handleCommand(_("set expandtab"));
handler.handleCommand(_("set shiftwidth=8"));
handler.handleCommand(_("set tabstop=16"));
handler.handleCommand(_("set autoindent"));
// Try to source file "fakevimrc" from current directory.
handler.handleCommand(_("source fakevimrc"));
handler.installEventFilter();
handler.setupWidget();
}
void initMainWindow(QMainWindow &mainWindow, QWidget *centralWidget, const QString &title)
{
mainWindow.setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
mainWindow.setCentralWidget(centralWidget);
mainWindow.resize(600, 650);
mainWindow.move(0, 0);
mainWindow.show();
// Set monospace font for editor and status bar.
QFont font = QApplication::font();
font.setFamily(_("Monospace"));
centralWidget->setFont(font);
mainWindow.statusBar()->setFont(font);
}
void readFile(FakeVimHandler &handler, const QString &editFileName)
{
handler.handleCommand(QString(_("r %1")).arg(editFileName));
}
void clearUndoRedo(QWidget *editor)
{
EDITOR(editor, setUndoRedoEnabled(false));
EDITOR(editor, setUndoRedoEnabled(true));
}
void connectSignals(FakeVimHandler &handler, Proxy &proxy)
{
QObject::connect(&handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)),
&proxy, SLOT(changeStatusMessage(QString,int)));
QObject::connect(&handler,
SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
&proxy, SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
QObject::connect(&handler, SIGNAL(extraInformationChanged(QString)),
&proxy, SLOT(changeExtraInformation(QString)));
QObject::connect(&handler, SIGNAL(statusDataChanged(QString)),
&proxy, SLOT(changeStatusData(QString)));
QObject::connect(&handler, SIGNAL(highlightMatches(QString)),
&proxy, SLOT(highlightMatches(QString)));
QObject::connect(&handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)),
&proxy, SLOT(handleExCommand(bool*,ExCommand)));
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringList args = app.arguments();
// If first argument is present use QPlainTextEdit instead on QTextEdit;
bool usePlainTextEdit = args.size() > 1;
// Second argument is path to file to edit.
const QString editFileName = args.value(2, QString(_("/usr/share/vim/vim74/tutor/tutor")));
// Create editor widget.
QWidget *editor = createEditorWidget(usePlainTextEdit);
// Create FakeVimHandler instance which will emulate Vim behavior in editor widget.
FakeVimHandler handler(editor, 0);
// Create main window.
QMainWindow mainWindow;
initMainWindow(mainWindow, editor, usePlainTextEdit ? _("QPlainTextEdit") : _("QTextEdit"));
// Connect slots to FakeVimHandler signals.
Proxy proxy(editor, &mainWindow);
connectSignals(handler, proxy);
// Initialize FakeVimHandler.
initHandler(handler);
// Read file content to editor.
readFile(handler, editFileName);
// Clear undo and redo queues.
clearUndoRedo(editor);
return app.exec();
}
#include "main.moc"
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 Tobias Koelsch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <catch_with_main.hpp>
<commit_msg>Adapt to new version of Catch<commit_after>/* Copyright (c) 2016 Tobias Koelsch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include "etl/fast_vector.hpp"
#include "etl/fast_matrix.hpp"
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "etl/stop.hpp"
TEST_CASE( "stop/fast_vector_1", "stop<unary<fast_vec>>" ) {
using mat_type = etl::fast_vector<double, 4>;
mat_type test_vector(3.3);
auto r = s(log(test_vector));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 4);
REQUIRE(etl_traits<type>::size(r) == 4);
REQUIRE(size(r) == 4);
REQUIRE(etl_traits<type>::is_vector);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_matrix);
constexpr const auto size_1 = etl_traits<type>::size();
REQUIRE(size_1 == 4);
constexpr const auto size_2 = size(r);
REQUIRE(size_2 == 4);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/fast_matrix_1", "stop<unary<fast_mat>>" ) {
using mat_type = etl::fast_matrix<double, 3, 2>;
mat_type test_matrix(3.3);
auto r = s(log(test_matrix));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
constexpr const auto size_1 = etl_traits<type>::size();
constexpr const auto rows_1 = etl_traits<type>::rows();
constexpr const auto columns_1 = etl_traits<type>::columns();
REQUIRE(size_1 == 6);
REQUIRE(rows_1 == 3);
REQUIRE(columns_1 == 2);
constexpr const auto size_2 = size(r);
constexpr const auto rows_2 = rows(r);
constexpr const auto columns_2 = columns(r);
REQUIRE(size_2 == 6);
REQUIRE(rows_2 == 3);
REQUIRE(columns_2 == 2);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/fast_matrix_2", "stop<binary<fast_mat>>" ) {
using mat_type = etl::fast_matrix<double, 3, 2>;
mat_type test_matrix(3.3);
auto r = s(test_matrix + test_matrix);
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
constexpr const auto size_1 = etl_traits<type>::size();
constexpr const auto rows_1 = etl_traits<type>::rows();
constexpr const auto columns_1 = etl_traits<type>::columns();
REQUIRE(size_1 == 6);
REQUIRE(rows_1 == 3);
REQUIRE(columns_1 == 2);
constexpr const auto size_2 = size(r);
constexpr const auto rows_2 = rows(r);
constexpr const auto columns_2 = columns(r);
REQUIRE(size_2 == 6);
REQUIRE(rows_2 == 3);
REQUIRE(columns_2 == 2);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == 6.6);
}
}<commit_msg>More tests<commit_after>#include "catch.hpp"
#include "etl/fast_vector.hpp"
#include "etl/fast_matrix.hpp"
#include "etl/dyn_vector.hpp"
#include "etl/dyn_matrix.hpp"
#include "etl/stop.hpp"
TEST_CASE( "stop/fast_vector_1", "stop<unary<fast_vec>>" ) {
using mat_type = etl::fast_vector<double, 4>;
mat_type test_vector(3.3);
auto r = s(log(test_vector));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 4);
REQUIRE(etl_traits<type>::size(r) == 4);
REQUIRE(size(r) == 4);
REQUIRE(etl_traits<type>::is_vector);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_matrix);
constexpr const auto size_1 = etl_traits<type>::size();
REQUIRE(size_1 == 4);
constexpr const auto size_2 = size(r);
REQUIRE(size_2 == 4);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/fast_matrix_1", "stop<unary<fast_mat>>" ) {
using mat_type = etl::fast_matrix<double, 3, 2>;
mat_type test_matrix(3.3);
auto r = s(log(test_matrix));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
constexpr const auto size_1 = etl_traits<type>::size();
constexpr const auto rows_1 = etl_traits<type>::rows();
constexpr const auto columns_1 = etl_traits<type>::columns();
REQUIRE(size_1 == 6);
REQUIRE(rows_1 == 3);
REQUIRE(columns_1 == 2);
constexpr const auto size_2 = size(r);
constexpr const auto rows_2 = rows(r);
constexpr const auto columns_2 = columns(r);
REQUIRE(size_2 == 6);
REQUIRE(rows_2 == 3);
REQUIRE(columns_2 == 2);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/fast_matrix_2", "stop<binary<fast_mat>>" ) {
using mat_type = etl::fast_matrix<double, 3, 2>;
mat_type test_matrix(3.3);
auto r = s(test_matrix + test_matrix);
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
constexpr const auto size_1 = etl_traits<type>::size();
constexpr const auto rows_1 = etl_traits<type>::rows();
constexpr const auto columns_1 = etl_traits<type>::columns();
REQUIRE(size_1 == 6);
REQUIRE(rows_1 == 3);
REQUIRE(columns_1 == 2);
constexpr const auto size_2 = size(r);
constexpr const auto rows_2 = rows(r);
constexpr const auto columns_2 = columns(r);
REQUIRE(size_2 == 6);
REQUIRE(rows_2 == 3);
REQUIRE(columns_2 == 2);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == 6.6);
}
}
TEST_CASE( "stop/dyn_vector_1", "stop<unary<dyn_vec>>" ) {
using mat_type = etl::dyn_vector<double>;
mat_type test_vector(4, 3.3);
auto r = s(log(test_vector));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 4);
REQUIRE(etl_traits<type>::size(r) == 4);
REQUIRE(size(r) == 4);
REQUIRE(etl_traits<type>::is_vector);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(!etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_matrix);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/dyn_matrix_1", "stop<unary<dyn_mat>>" ) {
using mat_type = etl::dyn_matrix<double>;
mat_type test_matrix(3, 2, 3.3);
auto r = s(log(test_matrix));
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(!etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == log(3.3));
}
}
TEST_CASE( "stop/dyn_matrix_2", "stop<binary<dyn_mat>>" ) {
using mat_type = etl::dyn_matrix<double>;
mat_type test_matrix(3, 2, 3.3);
auto r = s(test_matrix + test_matrix);
using type = remove_reference_t<remove_cv_t<decltype(r)>>;
REQUIRE(r.size() == 6);
REQUIRE(etl_traits<type>::size(r) == 6);
REQUIRE(size(r) == 6);
REQUIRE(etl_traits<type>::rows(r) == 3);
REQUIRE(rows(r) == 3);
REQUIRE(etl_traits<type>::columns(r) == 2);
REQUIRE(columns(r) == 2);
REQUIRE(etl_traits<type>::is_matrix);
REQUIRE(etl_traits<type>::is_value);
REQUIRE(!etl_traits<type>::is_fast);
REQUIRE(!etl_traits<type>::is_vector);
for(std::size_t i = 0; i < r.size(); ++i){
REQUIRE(r[i] == 6.6);
}
}<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include "encoding/enum.hpp"
#include "encoding/integer.hpp"
#include "encoding/float.hpp"
#include "encoding/input.hpp"
#include "encoding/output.hpp"
using namespace std;
int main(void)
{
encoding::UnsignedIntegerCodec c1(16);
cout << c1.encode(1024) <<endl;
encoding::EnumCodec<string> c2({"hola","adios"}, "hola");
cout << c2.encode("hola") << endl;
cout << c2.decode(encoding::Bitset(1, 1)) << endl;
encoding::FloatCodec c3;
cout << c3.decode(c3.encode(1.5f)) << endl;
encoding::FixedPointFloatCodec<4,28> c4;
cout << "bits: " << c4.sizeInBits << endl;
cout << c4.decode(c4.encode(1.5f)) << endl;
std::istringstream in({0x01,0x25,0x23,0x53});
encoding::InputStream input(in);
cout << "paco: " << input.read(c1) << endl;
cout << "paco: " << input.read(c1) << endl;
encoding::UnsignedIntegerCodec c5(8);
encoding::UnsignedIntegerCodec c6(4);
std::stringstream out;
encoding::OutputStream output(out);
output.write(c5, 97U);
output.write(c5, 98U);
output.write(c5, 99U);
output.write(c6, 6U);
output.write(c6, 4U);
output.close();
cout << "miau: " << out.str() << endl;
return 0;
}
<commit_msg>Add some tests<commit_after>// Copyright (c) 2013, Noe Casas ([email protected]).
// Distributed under New BSD License.
// (see accompanying file COPYING)
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "encoding/enum.hpp"
#include "encoding/integer.hpp"
#include "encoding/float.hpp"
#include "encoding/input.hpp"
#include "encoding/output.hpp"
using namespace std;
using namespace encoding;
/*****************************************************************************/
template<typename Type>
void testEncode(const Codec<Type>& codec,
Type value,
const std::string& bits)
{
encoding::Bitset obtainedBits = codec.encode(value);
if (obtainedBits == Bitset(bits))
{
cout << "[PASS] Encoded " << value
<< " and obtained " << bits
<< endl;
}
else
{
cout << "[FAIL] Encoded " << value
<< " and obtained " << obtainedBits
<< " but expected " << bits
<< endl;
}
}
/*****************************************************************************/
template<typename Type>
void testDecode(const Codec<Type>& codec,
Type value,
const std::string& bits)
{
Type obtainedValue = codec.decode(Bitset(bits));
if (obtainedValue == value)
{
cout << "[PASS] Decoded " << bits
<< " and obtained " << value
<< endl;
}
else
{
cout << "[FAIL] Decoded " << bits
<< " and obtained " << obtainedValue
<< " but expected " << value
<< endl;
}
}
/*****************************************************************************/
template<typename Type>
void testRoundtripValue(const Codec<Type>& codec, Type value)
{
Type roundtripValue = codec.decode(codec.encode(value));
if (roundtripValue == value)
{
cout << "[PASS] Rountrip converted " << value
<< endl;
}
else
{
cout << "[FAIL] Roundtrip converted " << value
<< " and obtained " << roundtripValue
<< endl;
}
}
/*****************************************************************************/
template<typename Type>
void testEncodeAndDecode(const Codec<Type>& codec,
Type value,
const std::string& bits)
{
testEncode (codec, value, bits);
testDecode (codec, value, bits);
}
/*****************************************************************************/
void testUnsignedIntegerRandomRoundtrip()
{
srand (time(0));
for (std::size_t i = 0; i < 5; ++i)
{
std::size_t numBits = rand() % 65;
for (std::size_t k = 0; k < 20; ++k)
{
uint32_t randomNumber = rand() % (1 << numBits);
testRoundtripValue (UnsignedIntegerCodec(numBits), randomNumber);
}
}
}
/*****************************************************************************/
void testUnsignedIntegerEncodePerformance()
{
const std::size_t performanceSamples = 10000000;
UnsignedIntegerCodec codec(32);
clock_t begin = clock();
for (uint32_t x = 0; x < performanceSamples ; ++x)
{
Bitset result = codec.encode(x);
}
clock_t end = clock();
double elapsedmsecs = 1000.0 * double(end - begin) / CLOCKS_PER_SEC;
cout << "Unsigned integer encode time: "
<< (1000 * elapsedmsecs / performanceSamples) << "usecs "
<< "( " << performanceSamples << " samples )"
<< endl;
}
/*****************************************************************************/
void testUnsigned ()
{
testEncodeAndDecode (UnsignedIntegerCodec(1), uint32_t(0), "0");
testEncodeAndDecode (UnsignedIntegerCodec(1), uint32_t(1), "1");
testEncodeAndDecode (UnsignedIntegerCodec(11), uint32_t(1024), "10000000000");
testEncodeAndDecode (UnsignedIntegerCodec(16), uint32_t(1024), "0000010000000000");
testUnsignedIntegerRandomRoundtrip();
testUnsignedIntegerEncodePerformance();
}
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/
int main(void)
{
testUnsigned();
/*
encoding::EnumCodec<string> c2({"hola","adios"}, "hola");
cout << c2.encode("hola") << endl;
cout << c2.decode(encoding::Bitset(1, 1)) << endl;
encoding::FloatCodec c3;
cout << c3.decode(c3.encode(1.5f)) << endl;
encoding::FixedPointFloatCodec<4,28> c4;
cout << "bits: " << c4.sizeInBits << endl;
cout << c4.decode(c4.encode(1.5f)) << endl;
std::istringstream in({0x01,0x25,0x23,0x53});
encoding::InputStream input(in);
cout << "paco: " << input.read(c1) << endl;
cout << "paco: " << input.read(c1) << endl;
encoding::UnsignedIntegerCodec c5(8);
encoding::UnsignedIntegerCodec c6(4);
std::stringstream out;
encoding::OutputStream output(out);
output.write(c5, 97U);
output.write(c5, 98U);
output.write(c5, 99U);
output.write(c6, 6U);
output.write(c6, 4U);
output.close();
cout << "miau: " << out.str() << endl;
*/
return 0;
}
<|endoftext|> |
<commit_before>#include "../src/util.h"
#include "test.h"
using namespace Helium;
void test_factorial()
{
COMPARE(1, factorial(0));
COMPARE(1, factorial(1));
COMPARE(2, factorial(2));
COMPARE(6, factorial(3));
COMPARE(24, factorial(4));
}
void test_num_combinations()
{
COMPARE(8, num_combinations(8, 1));
COMPARE(28, num_combinations(8, 2));
COMPARE(56, num_combinations(8, 3));
}
void test_combinations()
{
std::string s = "ABCDEFGH";
// 1 element
int count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 1, s.end()));
COMPARE(8, count);
// 2 elements
count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 2, s.end()));
COMPARE(28, count);
// 3 elements
count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 3, s.end()));
COMPARE(56, count);
}
int main()
{
test_factorial();
test_num_combinations();
test_combinations();
}
<commit_msg>Fix include path<commit_after>#include <Helium/util.h>
#include "test.h"
using namespace Helium;
void test_factorial()
{
COMPARE(1, factorial(0));
COMPARE(1, factorial(1));
COMPARE(2, factorial(2));
COMPARE(6, factorial(3));
COMPARE(24, factorial(4));
}
void test_num_combinations()
{
COMPARE(8, num_combinations(8, 1));
COMPARE(28, num_combinations(8, 2));
COMPARE(56, num_combinations(8, 3));
}
void test_combinations()
{
std::string s = "ABCDEFGH";
// 1 element
int count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 1, s.end()));
COMPARE(8, count);
// 2 elements
count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 2, s.end()));
COMPARE(28, count);
// 3 elements
count = 0;
do {
++count;
} while (next_combination(s.begin(), s.begin() + 3, s.end()));
COMPARE(56, count);
}
int main()
{
test_factorial();
test_num_combinations();
test_combinations();
}
<|endoftext|> |
<commit_before>#include <bitcoin/network/network.hpp>
#include <bitcoin/util/logger.hpp>
#include <atomic>
#include <functional>
#include <iostream>
using std::placeholders::_1;
using std::placeholders::_2;
using namespace libbitcoin;
void error_exit(const std::string& message, int status=1)
{
log_error() << "net: " << message;
exit(status);
}
std::mutex mutex;
std::condition_variable condition;
size_t inv_count = 0;
void receive_inv(network_ptr net, channel_handle chandle,
const message::inv& packet)
{
log_info() << "Received:";
for (const message::inv_vect& ivv: packet.invs)
{
if (ivv.type != message::inv_type::block)
log_info() << " --";
else
log_info() << " " << pretty_hex(ivv.hash);
}
net->subscribe_inv(chandle, std::bind(&receive_inv, net, chandle, _1));
std::unique_lock<std::mutex> lock(mutex);
inv_count += packet.invs.size();
condition.notify_one();
}
void handle_send_getblock(const std::error_code& ec)
{
if (ec)
error_exit(ec.message());
}
message::getblocks create_getblocks_message()
{
message::getblocks packet;
hash_digest genesis{0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68,
0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93,
0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1,
0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f};
packet.locator_start_hashes.push_back(genesis);
packet.hash_stop = hash_digest{0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
return packet;
}
void handle_handshake(const std::error_code& ec, channel_handle chandle,
network_ptr net)
{
net->subscribe_inv(chandle, std::bind(&receive_inv, net, chandle, _1));
net->send(chandle, create_getblocks_message(),
std::bind(&handle_send_getblock, _1));
}
int main()
{
network_ptr net(new network_impl);
handshake_connect(net, "localhost", 8333,
std::bind(&handle_handshake, _1, _2, net));
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, []{ return inv_count >= 500; });
return 0;
}
<commit_msg>use std::array.fill(0) instead of {0, 0, 0, ...<commit_after>#include <bitcoin/network/network.hpp>
#include <bitcoin/util/logger.hpp>
#include <atomic>
#include <functional>
#include <iostream>
using std::placeholders::_1;
using std::placeholders::_2;
using namespace libbitcoin;
void error_exit(const std::string& message, int status=1)
{
log_error() << "net: " << message;
exit(status);
}
std::mutex mutex;
std::condition_variable condition;
size_t inv_count = 0;
void receive_inv(network_ptr net, channel_handle chandle,
const message::inv& packet)
{
log_info() << "Received:";
for (const message::inv_vect& ivv: packet.invs)
{
if (ivv.type != message::inv_type::block)
log_info() << " --";
else
log_info() << " " << pretty_hex(ivv.hash);
}
net->subscribe_inv(chandle, std::bind(&receive_inv, net, chandle, _1));
std::unique_lock<std::mutex> lock(mutex);
inv_count += packet.invs.size();
condition.notify_one();
}
void handle_send_getblock(const std::error_code& ec)
{
if (ec)
error_exit(ec.message());
}
message::getblocks create_getblocks_message()
{
message::getblocks packet;
hash_digest genesis{0x00, 0x00, 0x00, 0x00, 0x00, 0x19, 0xd6, 0x68,
0x9c, 0x08, 0x5a, 0xe1, 0x65, 0x83, 0x1e, 0x93,
0x4f, 0xf7, 0x63, 0xae, 0x46, 0xa2, 0xa6, 0xc1,
0x72, 0xb3, 0xf1, 0xb6, 0x0a, 0x8c, 0xe2, 0x6f};
packet.locator_start_hashes.push_back(genesis);
packet.hash_stop.fill(0);
return packet;
}
void handle_handshake(const std::error_code& ec, channel_handle chandle,
network_ptr net)
{
net->subscribe_inv(chandle, std::bind(&receive_inv, net, chandle, _1));
net->send(chandle, create_getblocks_message(),
std::bind(&handle_send_getblock, _1));
}
int main()
{
network_ptr net(new network_impl);
handshake_connect(net, "localhost", 8333,
std::bind(&handle_handshake, _1, _2, net));
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, []{ return inv_count >= 500; });
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016, Vlad Meșco
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <string>
#include <sstream>
#include <vector>
#include <functional>
#include <parser.h>
#include <parser_types.h>
#define TEOF (0)
int tokenizer_lineno = 1;
struct Token
{
typedef int Type;
Type type;
std::string value;
Token(Type type_, std::string value_ = "")
: type(type_), value(value_)
{}
};
struct Tokenizer
{
FILE* f;
char c;
Tokenizer(FILE* f_)
: f(f_)
{
if(feof(f)) c = EOF;
else c = fgetc(f);
}
Token operator()()
{
while(isspace(c) || c == 13 || c == 10)
{
c = fgetc(f);
if(feof(f)) return {TEOF};
if(c == 10) tokenizer_lineno++;
}
if(c == '[') { c = fgetc(f); return {LSQUARE}; }
if(c == ']') { c = fgetc(f); return {RSQUARE}; }
if(c == '(') { c = fgetc(f); return {LPAREN}; }
if(c == ')') { c = fgetc(f); return {RPAREN}; }
if(c == '=') { c = fgetc(f); return {EQUALS}; }
std::stringstream ss;
std::function<bool(char)> conditions[] = {
[](char c) -> bool {
return !(isspace(c)
|| c == 13
|| c == 10
|| c == '['
|| c == ']'
|| c == '('
|| c == ')'
|| c == '='
);
},
[](char c) -> bool {
return c != '"';
},
};
bool quoted = (c == '"');
auto condition = conditions[quoted];
if(quoted) c = fgetc(f);
while(condition(c))
{
ss << c;
c = fgetc(f);
if(feof(f)) break;
}
if(quoted) c = fgetc(f);
return {STRING, ss.str()};
}
};
int main(int argc, char* argv[])
{
for(int i = 1; i < argc; ++i) {
if(strcmp(argv[i], "-v") == 0) {
printf("jakbeat v%d\nCopyright Vlad Mesco 2016\n\n", VERSION);
exit(0);
}
}
extern void* ParseAlloc(void* (*)(size_t));
extern void Parse(void*, int, char*, File*);
extern void ParseFree(void*, void (*)(void*));
extern void Render(File, std::string);
File f;
Tokenizer tok(stdin);
auto pParser = ParseAlloc(malloc);
do {
auto t = tok();
printf("%d %s\n", t.type, (t.type == STRING) ? t.value.c_str() : "");
char* s = strdup(t.value.c_str());
Parse(pParser, t.type, s, &f);
if(t.type == TEOF) break;
} while(1);
ParseFree(pParser, free);
Render(f, "test.wav");
return 0;
}
<commit_msg>fix compiler crash (!) on 18.00.21005.1<commit_after>/*
Copyright (c) 2016, Vlad Meșco
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <cstdio>
#include <cctype>
#include <string>
#include <sstream>
#include <vector>
#include <functional>
#include <parser.h>
#include <parser_types.h>
#define TEOF (0)
int tokenizer_lineno = 1;
struct Token
{
typedef int Type;
Type type;
std::string value;
Token(Type type_, std::string value_ = "")
: type(type_), value(value_)
{}
};
struct Tokenizer
{
FILE* f;
char c;
Tokenizer(FILE* f_)
: f(f_)
{
if(feof(f)) c = EOF;
else c = fgetc(f);
}
Token operator()()
{
while(isspace(c) || c == 13 || c == 10)
{
c = fgetc(f);
if(feof(f)) return {TEOF};
if(c == 10) tokenizer_lineno++;
}
if(c == '[') { c = fgetc(f); return {LSQUARE}; }
if(c == ']') { c = fgetc(f); return {RSQUARE}; }
if(c == '(') { c = fgetc(f); return {LPAREN}; }
if(c == ')') { c = fgetc(f); return {RPAREN}; }
if(c == '=') { c = fgetc(f); return {EQUALS}; }
std::stringstream ss;
std::function<bool(char)> conditions[] = {
[](char c) -> bool {
return !(isspace(c)
|| c == 13
|| c == 10
|| c == '['
|| c == ']'
|| c == '('
|| c == ')'
|| c == '='
);
},
[](char c) -> bool {
return c != '"';
},
};
bool quoted = (c == '"');
auto condition = conditions[quoted];
if(quoted) c = fgetc(f);
while(condition(c))
{
ss << c;
c = fgetc(f);
if(feof(f)) break;
}
if(quoted) c = fgetc(f);
//return {STRING, ss.str()}; // curly bracket form crashes msvc 18.00.21005.1
return Token(STRING, ss.str());
}
};
int main(int argc, char* argv[])
{
for(int i = 1; i < argc; ++i) {
if(strcmp(argv[i], "-v") == 0) {
printf("jakbeat v%d\nCopyright Vlad Mesco 2016\n\n", VERSION);
exit(0);
}
}
extern void* ParseAlloc(void* (*)(size_t));
extern void Parse(void*, int, char*, File*);
extern void ParseFree(void*, void (*)(void*));
extern void Render(File, std::string);
File f;
Tokenizer tok(stdin);
auto pParser = ParseAlloc(malloc);
do {
auto t = tok();
printf("%d %s\n", t.type, (t.type == STRING) ? t.value.c_str() : "");
char* s = strdup(t.value.c_str());
Parse(pParser, t.type, s, &f);
if(t.type == TEOF) break;
} while(1);
ParseFree(pParser, free);
Render(f, "test.wav");
return 0;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System
*/
#define __STDC_FORMAT_MACROS
#include "sync_union_tarball.h"
#include <pthread.h>
#include <cassert>
#include <cstdio>
#include <list>
#include <set>
#include <string>
#include <vector>
#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/posix.h"
#include "util_concurrency.h"
namespace publish {
SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
const std::string &rdonly_path,
const std::string &tarball_path,
const std::string &base_directory,
const std::string &to_delete)
: SyncUnion(mediator, rdonly_path, "", ""),
tarball_path_(tarball_path),
base_directory_(base_directory),
to_delete_(to_delete),
read_archive_signal_(new Signal) {
}
SyncUnionTarball::~SyncUnionTarball() { delete read_archive_signal_; }
bool SyncUnionTarball::Initialize() {
bool result;
src = archive_read_new();
assert(ARCHIVE_OK == archive_read_support_format_tar(src));
assert(ARCHIVE_OK == archive_read_support_format_empty(src));
if (tarball_path_ == "-") {
result = archive_read_open_filename(src, NULL, kBlockSize);
} else {
std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
result = archive_read_open_filename(src, tarball_absolute_path.c_str(),
kBlockSize);
}
if (result != ARCHIVE_OK) {
LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
return false;
}
return SyncUnion::Initialize();
}
/*
* Libarchive is not thread aware, so we need to make sure that before
* to read/"open" the next header in the archive the content of the
*
* present header is been consumed completely.
* Different thread read/"open" the header from the one that consumes
* it so we opted for a Signal that is backed by a conditional variable.
* We wait for the signal just before to read the header.
* Then when we have done with the header the Signal is fired.
* The Signal can be fired inside the main loop if we don't need to read
* data, or when the IngestionSource get closed, which means that we are
* not reading data anymore from there.
* This whole process is not necessary for directories since we don't
* actually need to read data from them.
*/
void SyncUnionTarball::Traverse() {
read_archive_signal_->Wakeup();
assert(this->IsInitialized());
/*
* As first step we eliminate the requested directories.
*/
if (to_delete_ != "") {
vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');
for (vector<string>::iterator s = to_eliminate_vec.begin();
s != to_eliminate_vec.end(); ++s) {
std::string parent_path;
std::string filename;
SplitPath(*s, &parent_path, &filename);
if (parent_path == ".") parent_path = "";
SharedPtr<SyncItem> sync_entry =
CreateSyncItem(parent_path, filename, kItemDir);
mediator_->Remove(sync_entry);
}
}
struct archive_entry *entry = archive_entry_new();
while (true) {
// Get the lock, wait if lock is not available yet
read_archive_signal_->Wait();
int result = archive_read_next_header2(src, entry);
switch (result) {
case ARCHIVE_FATAL: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Fatal error in reading the archive.\n%s\n",
archive_error_string(src));
abort();
break; // Only exit point with error
}
case ARCHIVE_RETRY: {
LogCvmfs(kLogUnionFs, kLogStdout,
"Error in reading the header, retrying.\n%s\n",
archive_error_string(src));
continue;
break;
}
case ARCHIVE_EOF: {
for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
dir != to_create_catalog_dirs_.end(); ++dir) {
assert(dirs_.find(*dir) != dirs_.end());
SharedPtr<SyncItem> to_mark = dirs_[*dir];
assert(to_mark->IsDirectory());
to_mark->SetCatalogMarker();
to_mark->IsPlaceholderDirectory();
ProcessDirectory(to_mark);
}
return; // Only successful exit point
break;
}
case ARCHIVE_WARN: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Warning in uncompression reading, going on.\n %s",
archive_error_string(src));
// We actually want this to enter the ARCHIVE_OK case
}
case ARCHIVE_OK: {
ProcessArchiveEntry(entry);
break;
}
default: {
// We should never enter in this branch, but just for safeness we prefer
// to abort in case we hit a case we don't how to manage.
LogCvmfs(kLogUnionFs, kLogStderr,
"Enter in unknow state. Aborting.\nError: %s\n", result,
archive_error_string(src));
abort();
}
}
}
}
void SyncUnionTarball::ProcessArchiveEntry(struct archive_entry *entry) {
std::string archive_file_path(archive_entry_pathname(entry));
std::string complete_path =
MakeCanonicalPath(base_directory_ + "/" + archive_file_path);
std::string parent_path;
std::string filename;
SplitPath(complete_path, &parent_path, &filename);
CreateDirectories(parent_path);
SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
parent_path, filename, src, entry, read_archive_signal_, this));
if (NULL != archive_entry_hardlink(entry)) {
const std::string hardlink =
base_directory_ + "/" + std::string(archive_entry_hardlink(entry));
if (hardlinks_.find(hardlink) != hardlinks_.end()) {
hardlinks_.find(hardlink)->second.push_back(complete_path);
} else {
std::list<std::string> to_hardlink;
to_hardlink.push_back(complete_path);
hardlinks_[hardlink] = to_hardlink;
}
read_archive_signal_->Wakeup();
return;
}
if (sync_entry->IsDirectory()) {
if (know_directories_.find(complete_path) != know_directories_.end()) {
sync_entry->IsPlaceholderDirectory();
}
ProcessUnmaterializedDirectory(sync_entry);
dirs_[complete_path] = sync_entry;
know_directories_.insert(complete_path);
read_archive_signal_->Wakeup(); // We don't need to read data and we
// can read the next header
} else if (sync_entry->IsRegularFile()) {
// inside the process pipeline we will wake up the signal
ProcessFile(sync_entry);
if (filename == ".cvmfscatalog") {
to_create_catalog_dirs_.insert(parent_path);
}
} else if (sync_entry->IsSymlink() || sync_entry->IsFifo() ||
sync_entry->IsSocket()) {
// we avoid to add an entity called as a catalog marker if it is not a
// regular file
if (filename != ".cvmfscatalog") {
ProcessFile(sync_entry);
} else {
LogCvmfs(kLogUnionFs, kLogStderr,
"Found entity called as a catalog marker '%s' that however is "
"not a regular file, abort",
complete_path.c_str());
abort();
}
// here we don't need to read data from the tar file so we can wake up
// immediately the signal
read_archive_signal_->Wakeup();
} else {
LogCvmfs(kLogUnionFs, kLogStderr,
"Fatal error found unexpected file: \n%s\n", filename.c_str());
abort();
}
}
void SyncUnionTarball::PostUpload() {
std::map<const std::string, std::list<std::string> >::iterator hardlink;
for (hardlink = hardlinks_.begin(); hardlink != hardlinks_.end();
++hardlink) {
std::list<std::string>::iterator entry;
for (entry = hardlink->second.begin(); entry != hardlink->second.end();
++entry) {
mediator_->Clone(*entry, hardlink->first);
}
}
}
std::string SyncUnionTarball::UnwindWhiteoutFilename(
SharedPtr<SyncItem> entry) const {
return entry->filename();
}
bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
return false;
}
bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
return false;
}
/* Tar files are not necessarly traversed in order from root to leave.
* So it may happens that we are expanding the file `/a/b/c.txt` without
* having created yet the directory `/a/b/`.
* In order to overcome this limitation the following function create dummy
* directories that can be used as placeholder and that they will be overwritten
* as soon as the real directory is found in the tarball
*/
void SyncUnionTarball::CreateDirectories(const std::string &target) {
if (know_directories_.find(target) != know_directories_.end()) return;
if (target == ".") return;
std::string dirname = "";
std::string filename = "";
SplitPath(target, &dirname, &filename);
CreateDirectories(dirname);
if (dirname == ".") dirname = "";
SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
new SyncItemDummyDir(dirname, filename, this, kItemDir));
ProcessUnmaterializedDirectory(dummy);
know_directories_.insert(target);
}
} // namespace publish
<commit_msg>being more liberal on what we accept inside the tarball<commit_after>/**
* This file is part of the CernVM File System
*/
#define __STDC_FORMAT_MACROS
#include "sync_union_tarball.h"
#include <pthread.h>
#include <cassert>
#include <cstdio>
#include <list>
#include <set>
#include <string>
#include <vector>
#include "duplex_libarchive.h"
#include "fs_traversal.h"
#include "smalloc.h"
#include "sync_item.h"
#include "sync_item_dummy.h"
#include "sync_item_tar.h"
#include "sync_mediator.h"
#include "sync_union.h"
#include "util/posix.h"
#include "util_concurrency.h"
namespace publish {
SyncUnionTarball::SyncUnionTarball(AbstractSyncMediator *mediator,
const std::string &rdonly_path,
const std::string &tarball_path,
const std::string &base_directory,
const std::string &to_delete)
: SyncUnion(mediator, rdonly_path, "", ""),
tarball_path_(tarball_path),
base_directory_(base_directory),
to_delete_(to_delete),
read_archive_signal_(new Signal) {
}
SyncUnionTarball::~SyncUnionTarball() { delete read_archive_signal_; }
bool SyncUnionTarball::Initialize() {
bool result;
src = archive_read_new();
assert(ARCHIVE_OK == archive_read_support_format_tar(src));
assert(ARCHIVE_OK == archive_read_support_format_empty(src));
if (tarball_path_ == "-") {
result = archive_read_open_filename(src, NULL, kBlockSize);
} else {
std::string tarball_absolute_path = GetAbsolutePath(tarball_path_);
result = archive_read_open_filename(src, tarball_absolute_path.c_str(),
kBlockSize);
}
if (result != ARCHIVE_OK) {
LogCvmfs(kLogUnionFs, kLogStderr, "Impossible to open the archive.");
return false;
}
return SyncUnion::Initialize();
}
/*
* Libarchive is not thread aware, so we need to make sure that before
* to read/"open" the next header in the archive the content of the
*
* present header is been consumed completely.
* Different thread read/"open" the header from the one that consumes
* it so we opted for a Signal that is backed by a conditional variable.
* We wait for the signal just before to read the header.
* Then when we have done with the header the Signal is fired.
* The Signal can be fired inside the main loop if we don't need to read
* data, or when the IngestionSource get closed, which means that we are
* not reading data anymore from there.
* This whole process is not necessary for directories since we don't
* actually need to read data from them.
*/
void SyncUnionTarball::Traverse() {
read_archive_signal_->Wakeup();
assert(this->IsInitialized());
/*
* As first step we eliminate the requested directories.
*/
if (to_delete_ != "") {
vector<std::string> to_eliminate_vec = SplitString(to_delete_, ':');
for (vector<string>::iterator s = to_eliminate_vec.begin();
s != to_eliminate_vec.end(); ++s) {
std::string parent_path;
std::string filename;
SplitPath(*s, &parent_path, &filename);
if (parent_path == ".") parent_path = "";
SharedPtr<SyncItem> sync_entry =
CreateSyncItem(parent_path, filename, kItemDir);
mediator_->Remove(sync_entry);
}
}
struct archive_entry *entry = archive_entry_new();
while (true) {
// Get the lock, wait if lock is not available yet
read_archive_signal_->Wait();
int result = archive_read_next_header2(src, entry);
switch (result) {
case ARCHIVE_FATAL: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Fatal error in reading the archive.\n%s\n",
archive_error_string(src));
abort();
break; // Only exit point with error
}
case ARCHIVE_RETRY: {
LogCvmfs(kLogUnionFs, kLogStdout,
"Error in reading the header, retrying.\n%s\n",
archive_error_string(src));
continue;
break;
}
case ARCHIVE_EOF: {
for (set<string>::iterator dir = to_create_catalog_dirs_.begin();
dir != to_create_catalog_dirs_.end(); ++dir) {
assert(dirs_.find(*dir) != dirs_.end());
SharedPtr<SyncItem> to_mark = dirs_[*dir];
assert(to_mark->IsDirectory());
to_mark->SetCatalogMarker();
to_mark->IsPlaceholderDirectory();
ProcessDirectory(to_mark);
}
return; // Only successful exit point
break;
}
case ARCHIVE_WARN: {
LogCvmfs(kLogUnionFs, kLogStderr,
"Warning in uncompression reading, going on.\n %s",
archive_error_string(src));
// We actually want this to enter the ARCHIVE_OK case
}
case ARCHIVE_OK: {
ProcessArchiveEntry(entry);
break;
}
default: {
// We should never enter in this branch, but just for safeness we prefer
// to abort in case we hit a case we don't how to manage.
LogCvmfs(kLogUnionFs, kLogStderr,
"Enter in unknow state. Aborting.\nError: %s\n", result,
archive_error_string(src));
abort();
}
}
}
}
void SyncUnionTarball::ProcessArchiveEntry(struct archive_entry *entry) {
std::string archive_file_path(archive_entry_pathname(entry));
std::string complete_path =
MakeCanonicalPath(base_directory_ + "/" + archive_file_path);
std::string parent_path;
std::string filename;
SplitPath(complete_path, &parent_path, &filename);
CreateDirectories(parent_path);
SharedPtr<SyncItem> sync_entry = SharedPtr<SyncItem>(new SyncItemTar(
parent_path, filename, src, entry, read_archive_signal_, this));
if (NULL != archive_entry_hardlink(entry)) {
const std::string hardlink =
base_directory_ + "/" + std::string(archive_entry_hardlink(entry));
if (hardlinks_.find(hardlink) != hardlinks_.end()) {
hardlinks_.find(hardlink)->second.push_back(complete_path);
} else {
std::list<std::string> to_hardlink;
to_hardlink.push_back(complete_path);
hardlinks_[hardlink] = to_hardlink;
}
read_archive_signal_->Wakeup();
return;
}
if (sync_entry->IsDirectory()) {
if (know_directories_.find(complete_path) != know_directories_.end()) {
sync_entry->IsPlaceholderDirectory();
}
ProcessUnmaterializedDirectory(sync_entry);
dirs_[complete_path] = sync_entry;
know_directories_.insert(complete_path);
read_archive_signal_->Wakeup(); // We don't need to read data and we
// can read the next header
} else if (sync_entry->IsRegularFile()) {
// inside the process pipeline we will wake up the signal
ProcessFile(sync_entry);
if (filename == ".cvmfscatalog") {
to_create_catalog_dirs_.insert(parent_path);
}
} else if (sync_entry->IsSymlink() || sync_entry->IsFifo() ||
sync_entry->IsSocket()) {
// we avoid to add an entity called as a catalog marker if it is not a
// regular file
if (filename != ".cvmfscatalog") {
ProcessFile(sync_entry);
} else {
LogCvmfs(kLogUnionFs, kLogStderr,
"Found entity called as a catalog marker '%s' that however is "
"not a regular file, abort",
complete_path.c_str());
abort();
}
// here we don't need to read data from the tar file so we can wake up
// immediately the signal
read_archive_signal_->Wakeup();
} else {
LogCvmfs(kLogUnionFs, kLogStderr,
"Warning found unexpected file: \n%s\n", filename.c_str());
read_archive_signal_->Wakeup();
}
}
void SyncUnionTarball::PostUpload() {
std::map<const std::string, std::list<std::string> >::iterator hardlink;
for (hardlink = hardlinks_.begin(); hardlink != hardlinks_.end();
++hardlink) {
std::list<std::string>::iterator entry;
for (entry = hardlink->second.begin(); entry != hardlink->second.end();
++entry) {
mediator_->Clone(*entry, hardlink->first);
}
}
}
std::string SyncUnionTarball::UnwindWhiteoutFilename(
SharedPtr<SyncItem> entry) const {
return entry->filename();
}
bool SyncUnionTarball::IsOpaqueDirectory(SharedPtr<SyncItem> directory) const {
return false;
}
bool SyncUnionTarball::IsWhiteoutEntry(SharedPtr<SyncItem> entry) const {
return false;
}
/* Tar files are not necessarly traversed in order from root to leave.
* So it may happens that we are expanding the file `/a/b/c.txt` without
* having created yet the directory `/a/b/`.
* In order to overcome this limitation the following function create dummy
* directories that can be used as placeholder and that they will be overwritten
* as soon as the real directory is found in the tarball
*/
void SyncUnionTarball::CreateDirectories(const std::string &target) {
if (know_directories_.find(target) != know_directories_.end()) return;
if (target == ".") return;
std::string dirname = "";
std::string filename = "";
SplitPath(target, &dirname, &filename);
CreateDirectories(dirname);
if (dirname == ".") dirname = "";
SharedPtr<SyncItem> dummy = SharedPtr<SyncItem>(
new SyncItemDummyDir(dirname, filename, this, kItemDir));
ProcessUnmaterializedDirectory(dummy);
know_directories_.insert(target);
}
} // namespace publish
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperQtWidgetListEditItemModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperStringListInterface.h"
namespace otb
{
namespace Wrapper
{
/*
TRANSLATOR otb::Wapper::ListEditItemModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
const char * const
HEADERS[ ListEditItemModel::COLUMN_COUNT ] =
{
QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Name" ),
};
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
ListEditItemModel
::ListEditItemModel( QObject * p ) :
QAbstractItemModel( p ),
m_StringList( nullptr )
{
}
/*******************************************************************************/
ListEditItemModel
::~ListEditItemModel()
{
}
/*******************************************************************************/
void
ListEditItemModel
::SetStringList( StringListInterface * stringList )
{
m_StringList = stringList;
}
/*****************************************************************************/
/* QAbstractItemModel overloads */
/*****************************************************************************/
int
ListEditItemModel
::columnCount( const QModelIndex & ) const
{
// qDebug() << this << "::columnCount(" << parent << ")";
return COLUMN_COUNT;
}
/*****************************************************************************/
QVariant
ListEditItemModel
::data( const QModelIndex & idx, int role ) const
{
// qDebug() << this << "::data(" << idx << "," << role << ")";
// Get layer.
assert( m_StringList!=NULL );
assert( idx.isValid() );
assert( !idx.parent().isValid() );
assert( idx.internalPointer()!=NULL );
const StringListInterface * stringList =
static_cast< const StringListInterface * >( idx.internalPointer() );
assert( stringList!=nullptr );
// Return data given role.
switch( role )
{
case Qt::CheckStateRole:
if( idx.column()!=COLUMN_NAME )
return QVariant();
else
{
assert( idx.row() >= 0 );
return stringList->IsActive( idx.row() );
}
break;
case Qt::DisplayRole:
switch( idx.column() )
{
case COLUMN_NAME:
{
assert( idx.row() >= 0 );
std::string filename(
stringList->GetNthFileName( idx.row() )
);
// qDebug() << "Filename:" << QString( "%1" ).arg( filename.c_str() );
return
filename.empty()
? "NO FILENAME"
: QFile::decodeName( filename.c_str()
);
}
break;
default:
break;
}
break;
case Qt::FontRole:
break;
case Qt::ToolTipRole:
switch( idx.column() )
{
case COLUMN_NAME:
assert( idx.row() >= 0 );
return QString::fromStdString( stringList->GetToolTip( idx.row() ) );
break;
}
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
Qt::ItemFlags
ListEditItemModel
::flags( const QModelIndex & idx ) const
{
if( !idx.isValid() )
return QAbstractItemModel::flags( idx );
Qt::ItemFlags iflags =
QAbstractItemModel::flags( idx )
// | Qt::ItemIsDragEnabled
// | Qt::ItemIsDropEnabled
;
if( idx.column()==COLUMN_NAME )
iflags |=
Qt::ItemIsUserCheckable
| Qt::ItemIsEditable
// | Qt::ItemIsDragEnabled
;
return iflags;
}
/*****************************************************************************/
bool
ListEditItemModel
::hasChildren( const QModelIndex & idx ) const
{
return !idx.isValid();
}
/*****************************************************************************/
QVariant
ListEditItemModel
::headerData( int section,
Qt::Orientation /**orientation*/,
int role ) const
{
// qDebug()
// << this << "::headerData("
// << section << "," << orientation << "," << role
// << ")";
// assert( orientation==Qt::Horizontal );
switch( role )
{
case Qt::DisplayRole:
assert( section>=0 && section<COLUMN_COUNT );
return tr( HEADERS[ section ] );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::index( int row,
int column,
const QModelIndex & p ) const
{
// qDebug()
// << this << "::index(" << row << "," << column << "," << parent << ")";
if( m_StringList == nullptr )
return QModelIndex();
// qDebug()
// << "index:" << row << "," << column << "," << m_StringList->At( row );
assert( row>=0 && column>=0 );
#if 0
AbstractLayerModel * layer = m_StringList->At( row );
if( layer==NULL || p.isValid() )
return QModelIndex();
#endif
return
createIndex(
row,
column,
p.isValid()
? NULL
: m_StringList
);
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRow( int row, const QModelIndex & parent )
{
return insertRows( row, 1, parent );
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRows( int row, int count, const QModelIndex & parent )
{
// qDebug() << this << "::insertRows(" << row << "," << count << "," << parent << ")";
assert( m_StringList!=nullptr );
beginInsertRows( parent, row, count );
{
for( int r=row; r<row+count; ++r )
m_StringList->Insert( "", r );
}
endInsertRows();
return true;
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::parent( const QModelIndex & ) const
{
// qDebug() << this << "::parent(" << index << ")";
return QModelIndex();
}
/*****************************************************************************/
int
ListEditItemModel
::rowCount( const QModelIndex & p ) const
{
// qDebug() << this << "::rowCount(" << p << ")";
// qDebug() << "row-count:" <<
// ( ( m_StringList==NULL || p.isValid() )
// ? 0
// : m_StringList->GetCount()
// );
return
( m_StringList==nullptr || p.isValid() )
? 0
: m_StringList->Size();
}
/*****************************************************************************/
bool
ListEditItemModel
::setData( const QModelIndex & idx,
const QVariant & value,
int role )
{
// qDebug()
// << this << "::setData(" << idx << "," << value << "," << role
// << ");";
assert( !idx.parent().isValid() );
assert( idx.row()>=0 );
assert( idx.internalPointer()!=nullptr );
StringListInterface * stringList =
static_cast< StringListInterface * >( idx.internalPointer() );
switch( idx.column() )
{
case COLUMN_NAME:
switch( role )
{
case Qt::EditRole:
stringList->SetNthFileName(
idx.row(),
QFile::encodeName( value.toString() ).data()
);
return true;
break;
case Qt::CheckStateRole:
break;
default:
break;
}
break;
default:
break;
}
return false;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
} // end namespace 'Wrapper'.
} // end namespace 'otb'
<commit_msg>ENH: Changed text of empty list-edit item.<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperQtWidgetListEditItemModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperStringListInterface.h"
namespace otb
{
namespace Wrapper
{
/*
TRANSLATOR otb::Wapper::ListEditItemModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
namespace
{
const char * const
HEADERS[ ListEditItemModel::COLUMN_COUNT ] =
{
QT_TRANSLATE_NOOP( "otb::Wrapper::ListEditItemModel", "Name" ),
};
} // end of anonymous namespace.
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
ListEditItemModel
::ListEditItemModel( QObject * p ) :
QAbstractItemModel( p ),
m_StringList( nullptr )
{
}
/*******************************************************************************/
ListEditItemModel
::~ListEditItemModel()
{
}
/*******************************************************************************/
void
ListEditItemModel
::SetStringList( StringListInterface * stringList )
{
m_StringList = stringList;
}
/*****************************************************************************/
/* QAbstractItemModel overloads */
/*****************************************************************************/
int
ListEditItemModel
::columnCount( const QModelIndex & ) const
{
// qDebug() << this << "::columnCount(" << parent << ")";
return COLUMN_COUNT;
}
/*****************************************************************************/
QVariant
ListEditItemModel
::data( const QModelIndex & idx, int role ) const
{
// qDebug() << this << "::data(" << idx << "," << role << ")";
// Get layer.
assert( m_StringList!=NULL );
assert( idx.isValid() );
assert( !idx.parent().isValid() );
assert( idx.internalPointer()!=NULL );
const StringListInterface * stringList =
static_cast< const StringListInterface * >( idx.internalPointer() );
assert( stringList!=nullptr );
// Return data given role.
switch( role )
{
case Qt::CheckStateRole:
if( idx.column()!=COLUMN_NAME )
return QVariant();
else
{
assert( idx.row() >= 0 );
return stringList->IsActive( idx.row() );
}
break;
case Qt::DisplayRole:
switch( idx.column() )
{
case COLUMN_NAME:
{
assert( idx.row() >= 0 );
std::string filename(
stringList->GetNthFileName( idx.row() )
);
// qDebug() << "Filename:" << QString( "%1" ).arg( filename.c_str() );
return
filename.empty()
? "EMPTY"
: QFile::decodeName( filename.c_str()
);
}
break;
default:
break;
}
break;
case Qt::FontRole:
break;
case Qt::ToolTipRole:
switch( idx.column() )
{
case COLUMN_NAME:
assert( idx.row() >= 0 );
return QString::fromStdString( stringList->GetToolTip( idx.row() ) );
break;
}
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
Qt::ItemFlags
ListEditItemModel
::flags( const QModelIndex & idx ) const
{
if( !idx.isValid() )
return QAbstractItemModel::flags( idx );
Qt::ItemFlags iflags =
QAbstractItemModel::flags( idx )
// | Qt::ItemIsDragEnabled
// | Qt::ItemIsDropEnabled
;
if( idx.column()==COLUMN_NAME )
iflags |=
Qt::ItemIsUserCheckable
| Qt::ItemIsEditable
// | Qt::ItemIsDragEnabled
;
return iflags;
}
/*****************************************************************************/
bool
ListEditItemModel
::hasChildren( const QModelIndex & idx ) const
{
return !idx.isValid();
}
/*****************************************************************************/
QVariant
ListEditItemModel
::headerData( int section,
Qt::Orientation /**orientation*/,
int role ) const
{
// qDebug()
// << this << "::headerData("
// << section << "," << orientation << "," << role
// << ")";
// assert( orientation==Qt::Horizontal );
switch( role )
{
case Qt::DisplayRole:
assert( section>=0 && section<COLUMN_COUNT );
return tr( HEADERS[ section ] );
break;
default:
break;
}
return QVariant();
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::index( int row,
int column,
const QModelIndex & p ) const
{
// qDebug()
// << this << "::index(" << row << "," << column << "," << parent << ")";
if( m_StringList == nullptr )
return QModelIndex();
// qDebug()
// << "index:" << row << "," << column << "," << m_StringList->At( row );
assert( row>=0 && column>=0 );
#if 0
AbstractLayerModel * layer = m_StringList->At( row );
if( layer==NULL || p.isValid() )
return QModelIndex();
#endif
return
createIndex(
row,
column,
p.isValid()
? NULL
: m_StringList
);
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRow( int row, const QModelIndex & parent )
{
return insertRows( row, 1, parent );
}
/*****************************************************************************/
bool
ListEditItemModel
::insertRows( int row, int count, const QModelIndex & parent )
{
// qDebug() << this << "::insertRows(" << row << "," << count << "," << parent << ")";
assert( m_StringList!=nullptr );
beginInsertRows( parent, row, count );
{
for( int r=row; r<row+count; ++r )
m_StringList->Insert( "", r );
}
endInsertRows();
return true;
}
/*****************************************************************************/
QModelIndex
ListEditItemModel
::parent( const QModelIndex & ) const
{
// qDebug() << this << "::parent(" << index << ")";
return QModelIndex();
}
/*****************************************************************************/
int
ListEditItemModel
::rowCount( const QModelIndex & p ) const
{
// qDebug() << this << "::rowCount(" << p << ")";
// qDebug() << "row-count:" <<
// ( ( m_StringList==NULL || p.isValid() )
// ? 0
// : m_StringList->GetCount()
// );
return
( m_StringList==nullptr || p.isValid() )
? 0
: m_StringList->Size();
}
/*****************************************************************************/
bool
ListEditItemModel
::setData( const QModelIndex & idx,
const QVariant & value,
int role )
{
// qDebug()
// << this << "::setData(" << idx << "," << value << "," << role
// << ");";
assert( !idx.parent().isValid() );
assert( idx.row()>=0 );
assert( idx.internalPointer()!=nullptr );
StringListInterface * stringList =
static_cast< StringListInterface * >( idx.internalPointer() );
switch( idx.column() )
{
case COLUMN_NAME:
switch( role )
{
case Qt::EditRole:
stringList->SetNthFileName(
idx.row(),
QFile::encodeName( value.toString() ).data()
);
return true;
break;
case Qt::CheckStateRole:
break;
default:
break;
}
break;
default:
break;
}
return false;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
} // end namespace 'Wrapper'.
} // end namespace 'otb'
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/pixel_ref_utils.h"
#include <algorithm>
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/skia/src/core/SkRasterClip.h"
namespace skia {
namespace {
// URI label for a discardable SkPixelRef.
const char kLabelDiscardable[] = "discardable";
class DiscardablePixelRefSet {
public:
DiscardablePixelRefSet(
std::vector<PixelRefUtils::PositionPixelRef>* pixel_refs)
: pixel_refs_(pixel_refs) {}
void Add(SkPixelRef* pixel_ref, const SkRect& rect) {
// Only save discardable pixel refs.
if (pixel_ref->getURI() &&
!strcmp(pixel_ref->getURI(), kLabelDiscardable)) {
PixelRefUtils::PositionPixelRef position_pixel_ref;
position_pixel_ref.pixel_ref = pixel_ref;
position_pixel_ref.pixel_ref_rect = rect;
pixel_refs_->push_back(position_pixel_ref);
}
}
private:
std::vector<PixelRefUtils::PositionPixelRef>* pixel_refs_;
};
class GatherPixelRefDevice : public SkBitmapDevice {
public:
GatherPixelRefDevice(const SkBitmap& bm,
DiscardablePixelRefSet* pixel_ref_set)
: SkBitmapDevice(bm), pixel_ref_set_(pixel_ref_set) {}
virtual void clear(SkColor color) SK_OVERRIDE {}
virtual void writePixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {}
virtual void drawPaint(const SkDraw& draw, const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect clip_rect = SkRect::Make(draw.fRC->getBounds());
AddBitmap(bitmap, clip_rect);
}
}
virtual void drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count,
const SkPoint points[],
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (count == 0)
return;
SkPoint min_point = points[0];
SkPoint max_point = points[0];
for (size_t i = 1; i < count; ++i) {
const SkPoint& point = points[i];
min_point.set(std::min(min_point.x(), point.x()),
std::min(min_point.y(), point.y()));
max_point.set(std::max(max_point.x(), point.x()),
std::max(max_point.y(), point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect mapped_rect;
draw.fMatrix->mapRect(&mapped_rect, rect);
mapped_rect.intersect(SkRect::Make(draw.fRC->getBounds()));
AddBitmap(bitmap, mapped_rect);
}
}
virtual void drawOval(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect, paint);
}
virtual void drawRRect(const SkDraw& draw,
const SkRRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect.rect(), paint);
}
virtual void drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* pre_path_matrix,
bool path_is_mutable) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
SkRect path_bounds = path.getBounds();
SkRect final_rect;
if (pre_path_matrix != NULL)
pre_path_matrix->mapRect(&final_rect, path_bounds);
else
final_rect = path_bounds;
GatherPixelRefDevice::drawRect(draw, final_rect, paint);
}
virtual void drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkMatrix& matrix,
const SkPaint& paint) SK_OVERRIDE {
SkMatrix total_matrix;
total_matrix.setConcat(*draw.fMatrix, matrix);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
total_matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawBitmapRect(const SkDraw& draw,
const SkBitmap& bitmap,
const SkRect* src_or_null,
const SkRect& dst,
const SkPaint& paint,
SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkMatrix matrix;
matrix.setRectToRect(bitmap_rect, dst, SkMatrix::kFill_ScaleToFit);
GatherPixelRefDevice::drawBitmap(draw, bitmap, matrix, paint);
}
virtual void drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x,
int y,
const SkPaint& paint) SK_OVERRIDE {
// Sprites aren't affected by current matrix, so we can't reuse drawRect.
SkMatrix matrix;
matrix.setTranslate(x, y);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawText(const SkDraw& draw,
const void* text,
size_t len,
SkScalar x,
SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds;
paint.measureText(text, len, &bounds);
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
if (paint.isVerticalText()) {
SkScalar h = bounds.fBottom - bounds.fTop;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fTop -= h / 2;
bounds.fBottom -= h / 2;
}
bounds.fBottom += metrics.fBottom;
bounds.fTop += metrics.fTop;
} else {
SkScalar w = bounds.fRight - bounds.fLeft;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fLeft -= w / 2;
bounds.fRight -= w / 2;
} else if (paint.getTextAlign() == SkPaint::kRight_Align) {
bounds.fLeft -= w;
bounds.fRight -= w;
}
bounds.fTop = metrics.fTop;
bounds.fBottom = metrics.fBottom;
}
SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
bounds.fLeft -= pad;
bounds.fRight += pad;
bounds.fLeft += x;
bounds.fRight += x;
bounds.fTop += y;
bounds.fBottom += y;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar const_y,
int scalars_per_pos,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (len == 0)
return;
// Similar to SkDraw asserts.
SkASSERT(scalars_per_pos == 1 || scalars_per_pos == 2);
SkPoint min_point;
SkPoint max_point;
if (scalars_per_pos == 1) {
min_point.set(pos[0], const_y);
max_point.set(pos[0], const_y);
} else if (scalars_per_pos == 2) {
min_point.set(pos[0], const_y + pos[1]);
max_point.set(pos[0], const_y + pos[1]);
}
for (size_t i = 0; i < len; ++i) {
SkScalar x = pos[i * scalars_per_pos];
SkScalar y = const_y;
if (scalars_per_pos == 2)
y += pos[i * scalars_per_pos + 1];
min_point.set(std::min(x, min_point.x()), std::min(y, min_point.y()));
max_point.set(std::max(x, max_point.x()), std::max(y, max_point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
// Math is borrowed from SkBBoxRecord
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
bounds.fTop += metrics.fTop;
bounds.fBottom += metrics.fBottom;
SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
bounds.fLeft += pad;
bounds.fRight -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds = path.getBounds();
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
SkScalar pad = metrics.fTop;
bounds.fLeft += pad;
bounds.fRight -= pad;
bounds.fTop += pad;
bounds.fBottom -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawVertices(const SkDraw& draw,
SkCanvas::VertexMode,
int vertex_count,
const SkPoint verts[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int index_count,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawPoints(
draw, SkCanvas::kPolygon_PointMode, vertex_count, verts, paint);
}
virtual void drawDevice(const SkDraw&,
SkBaseDevice*,
int x,
int y,
const SkPaint&) SK_OVERRIDE {}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
return false;
}
private:
DiscardablePixelRefSet* pixel_ref_set_;
void AddBitmap(const SkBitmap& bm, const SkRect& rect) {
SkRect canvas_rect = SkRect::MakeWH(width(), height());
SkRect paint_rect = SkRect::MakeEmpty();
paint_rect.intersect(rect, canvas_rect);
pixel_ref_set_->Add(bm.pixelRef(), paint_rect);
}
bool GetBitmapFromPaint(const SkPaint& paint, SkBitmap* bm) {
SkShader* shader = paint.getShader();
if (shader) {
// Check whether the shader is a gradient in order to prevent generation
// of bitmaps from gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL))
return shader->asABitmap(bm, NULL, NULL);
}
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkBaseDevice* device) : INHERITED(device) {}
// Turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds,
const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
protected:
// Disable aa for speed.
virtual void onClipRect(const SkRect& rect,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->INHERITED::onClipRect(rect, op, kHard_ClipEdgeStyle);
}
virtual void onClipPath(const SkPath& path,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->updateClipConservativelyUsingBounds(path.getBounds(), op,
path.isInverseFillType());
}
virtual void onClipRRect(const SkRRect& rrect,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->updateClipConservativelyUsingBounds(rrect.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
} // namespace
void PixelRefUtils::GatherDiscardablePixelRefs(
SkPicture* picture,
std::vector<PositionPixelRef>* pixel_refs) {
pixel_refs->clear();
DiscardablePixelRefSet pixel_ref_set(pixel_refs);
SkBitmap empty_bitmap;
empty_bitmap.setConfig(
SkBitmap::kNo_Config, picture->width(), picture->height());
GatherPixelRefDevice device(empty_bitmap, &pixel_ref_set);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(SkRect::MakeWH(picture->width(), picture->height()),
SkRegion::kIntersect_Op,
false);
canvas.drawPicture(*picture);
}
} // namespace skia
<commit_msg>override new virtual onWritePixels instead of deprecated writePixels<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "skia/ext/pixel_ref_utils.h"
#include <algorithm>
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkDraw.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/include/core/SkShader.h"
#include "third_party/skia/src/core/SkRasterClip.h"
namespace skia {
namespace {
// URI label for a discardable SkPixelRef.
const char kLabelDiscardable[] = "discardable";
class DiscardablePixelRefSet {
public:
DiscardablePixelRefSet(
std::vector<PixelRefUtils::PositionPixelRef>* pixel_refs)
: pixel_refs_(pixel_refs) {}
void Add(SkPixelRef* pixel_ref, const SkRect& rect) {
// Only save discardable pixel refs.
if (pixel_ref->getURI() &&
!strcmp(pixel_ref->getURI(), kLabelDiscardable)) {
PixelRefUtils::PositionPixelRef position_pixel_ref;
position_pixel_ref.pixel_ref = pixel_ref;
position_pixel_ref.pixel_ref_rect = rect;
pixel_refs_->push_back(position_pixel_ref);
}
}
private:
std::vector<PixelRefUtils::PositionPixelRef>* pixel_refs_;
};
class GatherPixelRefDevice : public SkBitmapDevice {
public:
GatherPixelRefDevice(const SkBitmap& bm,
DiscardablePixelRefSet* pixel_ref_set)
: SkBitmapDevice(bm), pixel_ref_set_(pixel_ref_set) {}
virtual void clear(SkColor color) SK_OVERRIDE {}
virtual void drawPaint(const SkDraw& draw, const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect clip_rect = SkRect::Make(draw.fRC->getBounds());
AddBitmap(bitmap, clip_rect);
}
}
virtual void drawPoints(const SkDraw& draw,
SkCanvas::PointMode mode,
size_t count,
const SkPoint points[],
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (count == 0)
return;
SkPoint min_point = points[0];
SkPoint max_point = points[0];
for (size_t i = 1; i < count; ++i) {
const SkPoint& point = points[i];
min_point.set(std::min(min_point.x(), point.x()),
std::min(min_point.y(), point.y()));
max_point.set(std::max(max_point.x(), point.x()),
std::max(max_point.y(), point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawRect(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (GetBitmapFromPaint(paint, &bitmap)) {
SkRect mapped_rect;
draw.fMatrix->mapRect(&mapped_rect, rect);
mapped_rect.intersect(SkRect::Make(draw.fRC->getBounds()));
AddBitmap(bitmap, mapped_rect);
}
}
virtual void drawOval(const SkDraw& draw,
const SkRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect, paint);
}
virtual void drawRRect(const SkDraw& draw,
const SkRRect& rect,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawRect(draw, rect.rect(), paint);
}
virtual void drawPath(const SkDraw& draw,
const SkPath& path,
const SkPaint& paint,
const SkMatrix* pre_path_matrix,
bool path_is_mutable) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
SkRect path_bounds = path.getBounds();
SkRect final_rect;
if (pre_path_matrix != NULL)
pre_path_matrix->mapRect(&final_rect, path_bounds);
else
final_rect = path_bounds;
GatherPixelRefDevice::drawRect(draw, final_rect, paint);
}
virtual void drawBitmap(const SkDraw& draw,
const SkBitmap& bitmap,
const SkMatrix& matrix,
const SkPaint& paint) SK_OVERRIDE {
SkMatrix total_matrix;
total_matrix.setConcat(*draw.fMatrix, matrix);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
total_matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawBitmapRect(const SkDraw& draw,
const SkBitmap& bitmap,
const SkRect* src_or_null,
const SkRect& dst,
const SkPaint& paint,
SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkMatrix matrix;
matrix.setRectToRect(bitmap_rect, dst, SkMatrix::kFill_ScaleToFit);
GatherPixelRefDevice::drawBitmap(draw, bitmap, matrix, paint);
}
virtual void drawSprite(const SkDraw& draw,
const SkBitmap& bitmap,
int x,
int y,
const SkPaint& paint) SK_OVERRIDE {
// Sprites aren't affected by current matrix, so we can't reuse drawRect.
SkMatrix matrix;
matrix.setTranslate(x, y);
SkRect bitmap_rect = SkRect::MakeWH(bitmap.width(), bitmap.height());
SkRect mapped_rect;
matrix.mapRect(&mapped_rect, bitmap_rect);
AddBitmap(bitmap, mapped_rect);
SkBitmap paint_bitmap;
if (GetBitmapFromPaint(paint, &paint_bitmap))
AddBitmap(paint_bitmap, mapped_rect);
}
virtual void drawText(const SkDraw& draw,
const void* text,
size_t len,
SkScalar x,
SkScalar y,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds;
paint.measureText(text, len, &bounds);
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
if (paint.isVerticalText()) {
SkScalar h = bounds.fBottom - bounds.fTop;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fTop -= h / 2;
bounds.fBottom -= h / 2;
}
bounds.fBottom += metrics.fBottom;
bounds.fTop += metrics.fTop;
} else {
SkScalar w = bounds.fRight - bounds.fLeft;
if (paint.getTextAlign() == SkPaint::kCenter_Align) {
bounds.fLeft -= w / 2;
bounds.fRight -= w / 2;
} else if (paint.getTextAlign() == SkPaint::kRight_Align) {
bounds.fLeft -= w;
bounds.fRight -= w;
}
bounds.fTop = metrics.fTop;
bounds.fBottom = metrics.fBottom;
}
SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
bounds.fLeft -= pad;
bounds.fRight += pad;
bounds.fLeft += x;
bounds.fRight += x;
bounds.fTop += y;
bounds.fBottom += y;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawPosText(const SkDraw& draw,
const void* text,
size_t len,
const SkScalar pos[],
SkScalar const_y,
int scalars_per_pos,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
if (len == 0)
return;
// Similar to SkDraw asserts.
SkASSERT(scalars_per_pos == 1 || scalars_per_pos == 2);
SkPoint min_point;
SkPoint max_point;
if (scalars_per_pos == 1) {
min_point.set(pos[0], const_y);
max_point.set(pos[0], const_y);
} else if (scalars_per_pos == 2) {
min_point.set(pos[0], const_y + pos[1]);
max_point.set(pos[0], const_y + pos[1]);
}
for (size_t i = 0; i < len; ++i) {
SkScalar x = pos[i * scalars_per_pos];
SkScalar y = const_y;
if (scalars_per_pos == 2)
y += pos[i * scalars_per_pos + 1];
min_point.set(std::min(x, min_point.x()), std::min(y, min_point.y()));
max_point.set(std::max(x, max_point.x()), std::max(y, max_point.y()));
}
SkRect bounds = SkRect::MakeLTRB(
min_point.x(), min_point.y(), max_point.x(), max_point.y());
// Math is borrowed from SkBBoxRecord
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
bounds.fTop += metrics.fTop;
bounds.fBottom += metrics.fBottom;
SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
bounds.fLeft += pad;
bounds.fRight -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawTextOnPath(const SkDraw& draw,
const void* text,
size_t len,
const SkPath& path,
const SkMatrix* matrix,
const SkPaint& paint) SK_OVERRIDE {
SkBitmap bitmap;
if (!GetBitmapFromPaint(paint, &bitmap))
return;
// Math is borrowed from SkBBoxRecord
SkRect bounds = path.getBounds();
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
SkScalar pad = metrics.fTop;
bounds.fLeft += pad;
bounds.fRight -= pad;
bounds.fTop += pad;
bounds.fBottom -= pad;
GatherPixelRefDevice::drawRect(draw, bounds, paint);
}
virtual void drawVertices(const SkDraw& draw,
SkCanvas::VertexMode,
int vertex_count,
const SkPoint verts[],
const SkPoint texs[],
const SkColor colors[],
SkXfermode* xmode,
const uint16_t indices[],
int index_count,
const SkPaint& paint) SK_OVERRIDE {
GatherPixelRefDevice::drawPoints(
draw, SkCanvas::kPolygon_PointMode, vertex_count, verts, paint);
}
virtual void drawDevice(const SkDraw&,
SkBaseDevice*,
int x,
int y,
const SkPaint&) SK_OVERRIDE {}
protected:
virtual bool onReadPixels(const SkBitmap& bitmap,
int x,
int y,
SkCanvas::Config8888 config8888) SK_OVERRIDE {
return false;
}
virtual bool onWritePixels(const SkImageInfo& info,
const void* pixels,
size_t rowBytes,
int x,
int y) SK_OVERRIDE {
return false;
}
private:
DiscardablePixelRefSet* pixel_ref_set_;
void AddBitmap(const SkBitmap& bm, const SkRect& rect) {
SkRect canvas_rect = SkRect::MakeWH(width(), height());
SkRect paint_rect = SkRect::MakeEmpty();
paint_rect.intersect(rect, canvas_rect);
pixel_ref_set_->Add(bm.pixelRef(), paint_rect);
}
bool GetBitmapFromPaint(const SkPaint& paint, SkBitmap* bm) {
SkShader* shader = paint.getShader();
if (shader) {
// Check whether the shader is a gradient in order to prevent generation
// of bitmaps from gradient shaders, which implement asABitmap.
if (SkShader::kNone_GradientType == shader->asAGradient(NULL))
return shader->asABitmap(bm, NULL, NULL);
}
return false;
}
};
class NoSaveLayerCanvas : public SkCanvas {
public:
NoSaveLayerCanvas(SkBaseDevice* device) : INHERITED(device) {}
// Turn saveLayer() into save() for speed, should not affect correctness.
virtual int saveLayer(const SkRect* bounds,
const SkPaint* paint,
SaveFlags flags) SK_OVERRIDE {
// Like SkPictureRecord, we don't want to create layers, but we do need
// to respect the save and (possibly) its rect-clip.
int count = this->INHERITED::save(flags);
if (bounds) {
this->INHERITED::clipRectBounds(bounds, flags, NULL);
}
return count;
}
protected:
// Disable aa for speed.
virtual void onClipRect(const SkRect& rect,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->INHERITED::onClipRect(rect, op, kHard_ClipEdgeStyle);
}
virtual void onClipPath(const SkPath& path,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->updateClipConservativelyUsingBounds(path.getBounds(), op,
path.isInverseFillType());
}
virtual void onClipRRect(const SkRRect& rrect,
SkRegion::Op op,
ClipEdgeStyle edge_style) SK_OVERRIDE {
this->updateClipConservativelyUsingBounds(rrect.getBounds(), op, false);
}
private:
typedef SkCanvas INHERITED;
};
} // namespace
void PixelRefUtils::GatherDiscardablePixelRefs(
SkPicture* picture,
std::vector<PositionPixelRef>* pixel_refs) {
pixel_refs->clear();
DiscardablePixelRefSet pixel_ref_set(pixel_refs);
SkBitmap empty_bitmap;
empty_bitmap.setConfig(
SkBitmap::kNo_Config, picture->width(), picture->height());
GatherPixelRefDevice device(empty_bitmap, &pixel_ref_set);
NoSaveLayerCanvas canvas(&device);
canvas.clipRect(SkRect::MakeWH(picture->width(), picture->height()),
SkRegion::kIntersect_Op,
false);
canvas.drawPicture(*picture);
}
} // namespace skia
<|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 "skia/ext/platform_canvas.h"
#include "skia/ext/bitmap_platform_device.h"
#include "third_party/skia/include/core/SkTypes.h"
namespace skia {
PlatformCanvas::PlatformCanvas()
: SkCanvas(SkNEW(BitmapPlatformDeviceFactory)) {
}
PlatformCanvas::PlatformCanvas(SkDeviceFactory* factory) : SkCanvas(factory) {
}
SkDevice* PlatformCanvas::setBitmapDevice(const SkBitmap&) {
SkASSERT(false); // Should not be called.
return NULL;
}
PlatformDevice& PlatformCanvas::getTopPlatformDevice() const {
// All of our devices should be our special PlatformDevice.
SkCanvas::LayerIter iter(const_cast<PlatformCanvas*>(this), false);
return *static_cast<PlatformDevice*>(iter.device());
}
// static
size_t PlatformCanvas::StrideForWidth(unsigned width) {
return 4 * width;
}
bool PlatformCanvas::initializeWithDevice(SkDevice* device) {
if (!device)
return false;
setDevice(device);
device->unref(); // Was created with refcount 1, and setDevice also refs.
return true;
}
SkCanvas* CreateBitmapCanvas(int width, int height, bool is_opaque) {
return new PlatformCanvas(width, height, is_opaque);
}
bool SupportsPlatformPaint(const SkCanvas* canvas) {
// All of our devices should be our special PlatformDevice.
PlatformDevice* device = static_cast<PlatformDevice*>(canvas->getDevice());
// TODO(alokp): Rename PlatformDevice::IsNativeFontRenderingAllowed after
// removing these calls from WebKit.
return device->IsNativeFontRenderingAllowed();
}
PlatformDevice::PlatformSurface BeginPlatformPaint(SkCanvas* canvas) {
// All of our devices should be our special PlatformDevice.
PlatformDevice* device = static_cast<PlatformDevice*>(canvas->getDevice());
return device->BeginPlatformPaint();
}
void EndPlatformPaint(SkCanvas* canvas) {
// All of our devices should be our special PlatformDevice.
PlatformDevice* device = static_cast<PlatformDevice*>(canvas->getDevice());
device->EndPlatformPaint();
}
} // namespace skia
<commit_msg>Chromium does native painting on a very specific device - a device retrieved through a layer iterator. This device is neither SkCanvas::getDevice() or SkCanvas::getTopDevice(). We changed it to do native painting on SkCanvas::getDevice() in r80955 which resulted in numerous regressions. This patch reverts to using the same device used pre r80955. BUG=78891 Review URL: http://codereview.chromium.org/6826040<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 "skia/ext/platform_canvas.h"
#include "skia/ext/bitmap_platform_device.h"
#include "third_party/skia/include/core/SkTypes.h"
namespace {
skia::PlatformDevice* GetTopPlatformDevice(const SkCanvas* canvas) {
// All of our devices should be our special PlatformDevice.
SkCanvas::LayerIter iter(const_cast<SkCanvas*>(canvas), false);
return static_cast<skia::PlatformDevice*>(iter.device());
}
}
namespace skia {
PlatformCanvas::PlatformCanvas()
: SkCanvas(SkNEW(BitmapPlatformDeviceFactory)) {
}
PlatformCanvas::PlatformCanvas(SkDeviceFactory* factory) : SkCanvas(factory) {
}
SkDevice* PlatformCanvas::setBitmapDevice(const SkBitmap&) {
SkASSERT(false); // Should not be called.
return NULL;
}
PlatformDevice& PlatformCanvas::getTopPlatformDevice() const {
return *GetTopPlatformDevice(this);
}
// static
size_t PlatformCanvas::StrideForWidth(unsigned width) {
return 4 * width;
}
bool PlatformCanvas::initializeWithDevice(SkDevice* device) {
if (!device)
return false;
setDevice(device);
device->unref(); // Was created with refcount 1, and setDevice also refs.
return true;
}
SkCanvas* CreateBitmapCanvas(int width, int height, bool is_opaque) {
return new PlatformCanvas(width, height, is_opaque);
}
bool SupportsPlatformPaint(const SkCanvas* canvas) {
// TODO(alokp): Rename PlatformDevice::IsNativeFontRenderingAllowed after
// removing these calls from WebKit.
return GetTopPlatformDevice(canvas)->IsNativeFontRenderingAllowed();
}
PlatformDevice::PlatformSurface BeginPlatformPaint(SkCanvas* canvas) {
return GetTopPlatformDevice(canvas)->BeginPlatformPaint();
}
void EndPlatformPaint(SkCanvas* canvas) {
GetTopPlatformDevice(canvas)->EndPlatformPaint();
}
} // namespace skia
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: documentdigitalsignatures.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: rt $ $Date: 2004-11-26 14:50:46 $
*
* 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 <documentdigitalsignatures.hxx>
#include <xmlsecurity/digitalsignaturesdialog.hxx>
#include <xmlsecurity/certificateviewer.hxx>
#include <xmlsecurity/macrosecurity.hxx>
#include <xmlsecurity/baseencoding.hxx>
#include <xmlsecurity/biginteger.hxx>
#include <../dialogs/resourcemanager.hxx>
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SECURITYOPTIONS_HXX
#include <svtools/securityoptions.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
DocumentDigitalSignatures::DocumentDigitalSignatures( const Reference< com::sun::star::lang::XMultiServiceFactory> rxMSF )
{
mxMSF = rxMSF;
}
sal_Bool DocumentDigitalSignatures::SignDocumentContent( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModeDocumentContent, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyDocumentContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModeDocumentContent );
}
void DocumentDigitalSignatures::ShowDocumentContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModeDocumentContent, true );
}
sal_Bool DocumentDigitalSignatures::SignScriptingContent( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModeMacros, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyScriptingContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModeMacros );
}
void DocumentDigitalSignatures::ShowScriptingContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModeMacros, true );
}
sal_Bool DocumentDigitalSignatures::SignPackage( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModePackage, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyPackageSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModePackage );
}
void DocumentDigitalSignatures::ShowPackageSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModePackage, true );
}
sal_Bool DocumentDigitalSignatures::ImplViewSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage, DocumentSignatureMode eMode, bool bReadOnly ) throw (RuntimeException)
{
DigitalSignaturesDialog aSignaturesDialog( NULL, mxMSF, eMode, bReadOnly );
bool bInit = aSignaturesDialog.Init( rtl::OUString() );
DBG_ASSERT( bInit, "Error initializing security context!" );
if ( bInit )
{
aSignaturesDialog.SetStorage( rxStorage );
aSignaturesDialog.Execute();
}
return aSignaturesDialog.SignaturesChanged();
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::ImplVerifySignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage, DocumentSignatureMode eMode ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
aSignatureHelper.SetStorage( rxStorage );
aSignatureHelper.StartMission();
SignatureStreamHelper aStreamHelper = DocumentSignatureHelper::OpenSignatureStream( rxStorage, embed::ElementModes::READ, eMode );
if ( aStreamHelper.xSignatureStream.is() )
{
Reference< io::XInputStream > xInputStream( aStreamHelper.xSignatureStream, UNO_QUERY );
aSignatureHelper.ReadAndVerifySignature( xInputStream );
}
aSignatureHelper.EndMission();
aStreamHelper.Clear();
Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > xSecEnv = aSignatureHelper.GetSecurityEnvironment();
SignatureInformations aSignInfos = aSignatureHelper.GetSignatureInformations();
int nInfos = aSignInfos.size();
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > aInfos(nInfos);
if ( nInfos )
{
std::vector< rtl::OUString > aElementsToBeVerified = DocumentSignatureHelper::CreateElementList( rxStorage, ::rtl::OUString(), eMode );
for( int n = 0; n < nInfos; ++n )
{
const SignatureInformation& rInfo = aSignInfos[n];
aInfos[n].Signer = xSecEnv->getCertificate( rInfo.ouX509IssuerName, numericStringToBigInteger( rInfo.ouX509SerialNumber ) );
if ( !aInfos[n].Signer.is() )
aInfos[n].Signer = xSecEnv->createCertificateFromAscii( rInfo.ouX509Certificate ) ;
// MM : the ouDate and ouTime fields have been replaced with stDateTime (com::sun::star::util::DataTime)
/*
aInfos[n].SignatureDate = String( rInfo.ouDate ).ToInt32();
aInfos[n].SignatureTime = String( rInfo.ouTime ).ToInt32();
*/
DBG_ASSERT( rInfo.nStatus != ::com::sun::star::xml::crypto::SecurityOperationStatus_STATUS_UNKNOWN, "Signature not processed!" );
aInfos[n].SignatureIsValid = ( rInfo.nStatus == ::com::sun::star::xml::crypto::SecurityOperationStatus_OPERATION_SUCCEEDED );
if ( aInfos[n].SignatureIsValid )
{
// Can only be valid if ALL streams are signed, which means real stream count == signed stream count
int nRealCount = 0;
for ( int i = rInfo.vSignatureReferenceInfors.size(); i; )
{
const SignatureReferenceInformation& rInf = rInfo.vSignatureReferenceInfors[--i];
// There is also an extra entry of type TYPE_SAMEDOCUMENT_REFERENCE because of signature date.
if ( ( rInf.nType == TYPE_BINARYSTREAM_REFERENCE ) || ( rInf.nType == TYPE_XMLSTREAM_REFERENCE ) )
nRealCount++;
}
aInfos[n].SignatureIsValid = ( aElementsToBeVerified.size() == nRealCount );
}
}
}
return aInfos;
}
void DocumentDigitalSignatures::manageTrustedSources( ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
MacroSecurity aDlg( NULL, aSignatureHelper.GetSecurityEnvironment() );
aDlg.Execute();
}
void DocumentDigitalSignatures::ShowCertificate( const Reference< ::com::sun::star::security::XCertificate >& _Certificate ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
CertificateViewer aViewer( NULL, aSignatureHelper.GetSecurityEnvironment(), _Certificate );
aViewer.Execute();
}
::sal_Bool DocumentDigitalSignatures::isAuthorTrusted( const Reference< ::com::sun::star::security::XCertificate >& Author ) throw (RuntimeException)
{
sal_Bool bFound = sal_False;
::rtl::OUString sSerialNum = bigIntegerToNumericString( Author->getSerialNumber() );
Sequence< SvtSecurityOptions::Certificate > aTrustedAuthors = SvtSecurityOptions().GetTrustedAuthors();
sal_Int32 nCnt = aTrustedAuthors.getLength();
const SvtSecurityOptions::Certificate* pAuthors = aTrustedAuthors.getConstArray();
const SvtSecurityOptions::Certificate* pAuthorsEnd = pAuthors + aTrustedAuthors.getLength();
for ( ; pAuthors != pAuthorsEnd; ++pAuthors )
{
SvtSecurityOptions::Certificate aAuthor = *pAuthors;
if ( ( aAuthor[0] == Author->getIssuerName() ) && ( aAuthor[1] == sSerialNum ) )
{
bFound = sal_True;
break;
}
}
return bFound;
}
::sal_Bool DocumentDigitalSignatures::isLocationTrusted( const ::rtl::OUString& Location ) throw (RuntimeException)
{
sal_Bool bFound = sal_False;
INetURLObject aLocObj( Location );
Sequence< ::rtl::OUString > aSecURLs = SvtSecurityOptions().GetSecureURLs();
sal_Int32 nCnt = aSecURLs.getLength();
const ::rtl::OUString* pSecURLs = aSecURLs.getConstArray();
const ::rtl::OUString* pSecURLsEnd = pSecURLs + aSecURLs.getLength();
for ( ; pSecURLs != pSecURLsEnd; ++pSecURLs )
{
INetURLObject aSecURL( *pSecURLs );
if ( aSecURL == aLocObj )
{
bFound = sal_True;
break;
}
}
return bFound;
}
void DocumentDigitalSignatures::addAuthorToTrustedSources( const Reference< ::com::sun::star::security::XCertificate >& Author ) throw (RuntimeException)
{
SvtSecurityOptions aSecOpts;
SvtSecurityOptions::Certificate aNewCert( 3 );
aNewCert[ 0 ] = Author->getIssuerName();
aNewCert[ 1 ] = bigIntegerToNumericString( Author->getSerialNumber() );
aNewCert[ 2 ] = baseEncode( Author->getEncoded(), BASE64 );
Sequence< SvtSecurityOptions::Certificate > aTrustedAuthors = aSecOpts.GetTrustedAuthors();
sal_Int32 nCnt = aTrustedAuthors.getLength();
aTrustedAuthors.realloc( nCnt + 1 );
aTrustedAuthors[ nCnt ] = aNewCert;
aSecOpts.SetTrustedAuthors( aTrustedAuthors );
}
void DocumentDigitalSignatures::addLocationToTrustedSources( const ::rtl::OUString& Location ) throw (RuntimeException)
{
SvtSecurityOptions aSecOpt;
Sequence< ::rtl::OUString > aSecURLs = aSecOpt.GetSecureURLs();
sal_Int32 nCnt = aSecURLs.getLength();
aSecURLs.realloc( nCnt + 1 );
aSecURLs[ nCnt ] = Location;
aSecOpt.SetSecureURLs( aSecURLs );
}
rtl::OUString DocumentDigitalSignatures::GetImplementationName() throw (RuntimeException)
{
return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) );
}
Sequence< rtl::OUString > DocumentDigitalSignatures::GetSupportedServiceNames() throw (cssu::RuntimeException)
{
Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) );
return aRet;
}
Reference< XInterface > DocumentDigitalSignatures_CreateInstance(
const Reference< com::sun::star::lang::XMultiServiceFactory >& rSMgr) throw ( Exception )
{
return (cppu::OWeakObject*) new DocumentDigitalSignatures( rSMgr );
}
<commit_msg>INTEGRATION: CWS xmlsec07 (1.16.2); FILE MERGED 2004/12/14 11:42:34 pb 1.16.2.1: fix: #i38744# time support again<commit_after>/*************************************************************************
*
* $RCSfile: documentdigitalsignatures.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: kz $ $Date: 2005-01-18 14:33:25 $
*
* 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 <documentdigitalsignatures.hxx>
#include <xmlsecurity/digitalsignaturesdialog.hxx>
#include <xmlsecurity/certificateviewer.hxx>
#include <xmlsecurity/macrosecurity.hxx>
#include <xmlsecurity/baseencoding.hxx>
#include <xmlsecurity/biginteger.hxx>
#include <../dialogs/resourcemanager.hxx>
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_SECURITYOPTIONS_HXX
#include <svtools/securityoptions.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
DocumentDigitalSignatures::DocumentDigitalSignatures( const Reference< com::sun::star::lang::XMultiServiceFactory> rxMSF )
{
mxMSF = rxMSF;
}
sal_Bool DocumentDigitalSignatures::SignDocumentContent( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModeDocumentContent, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyDocumentContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModeDocumentContent );
}
void DocumentDigitalSignatures::ShowDocumentContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModeDocumentContent, true );
}
sal_Bool DocumentDigitalSignatures::SignScriptingContent( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModeMacros, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyScriptingContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModeMacros );
}
void DocumentDigitalSignatures::ShowScriptingContentSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModeMacros, true );
}
sal_Bool DocumentDigitalSignatures::SignPackage( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplViewSignatures( rxStorage, SignatureModePackage, false );
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::VerifyPackageSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
return ImplVerifySignatures( rxStorage, SignatureModePackage );
}
void DocumentDigitalSignatures::ShowPackageSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage ) throw (RuntimeException)
{
ImplViewSignatures( rxStorage, SignatureModePackage, true );
}
sal_Bool DocumentDigitalSignatures::ImplViewSignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage, DocumentSignatureMode eMode, bool bReadOnly ) throw (RuntimeException)
{
DigitalSignaturesDialog aSignaturesDialog( NULL, mxMSF, eMode, bReadOnly );
bool bInit = aSignaturesDialog.Init( rtl::OUString() );
DBG_ASSERT( bInit, "Error initializing security context!" );
if ( bInit )
{
aSignaturesDialog.SetStorage( rxStorage );
aSignaturesDialog.Execute();
}
return aSignaturesDialog.SignaturesChanged();
}
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > DocumentDigitalSignatures::ImplVerifySignatures( const Reference< ::com::sun::star::embed::XStorage >& rxStorage, DocumentSignatureMode eMode ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
aSignatureHelper.SetStorage( rxStorage );
aSignatureHelper.StartMission();
SignatureStreamHelper aStreamHelper = DocumentSignatureHelper::OpenSignatureStream( rxStorage, embed::ElementModes::READ, eMode );
if ( aStreamHelper.xSignatureStream.is() )
{
Reference< io::XInputStream > xInputStream( aStreamHelper.xSignatureStream, UNO_QUERY );
aSignatureHelper.ReadAndVerifySignature( xInputStream );
}
aSignatureHelper.EndMission();
aStreamHelper.Clear();
Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > xSecEnv = aSignatureHelper.GetSecurityEnvironment();
SignatureInformations aSignInfos = aSignatureHelper.GetSignatureInformations();
int nInfos = aSignInfos.size();
Sequence< ::com::sun::star::security::DocumentSignaturesInformation > aInfos(nInfos);
if ( nInfos )
{
std::vector< rtl::OUString > aElementsToBeVerified = DocumentSignatureHelper::CreateElementList( rxStorage, ::rtl::OUString(), eMode );
for( int n = 0; n < nInfos; ++n )
{
const SignatureInformation& rInfo = aSignInfos[n];
aInfos[n].Signer = xSecEnv->getCertificate( rInfo.ouX509IssuerName, numericStringToBigInteger( rInfo.ouX509SerialNumber ) );
if ( !aInfos[n].Signer.is() )
aInfos[n].Signer = xSecEnv->createCertificateFromAscii( rInfo.ouX509Certificate ) ;
// --> PB 2004-12-14 #i38744# time support again
Date aDate( rInfo.stDateTime.Day, rInfo.stDateTime.Month, rInfo.stDateTime.Year );
Time aTime( rInfo.stDateTime.Hours, rInfo.stDateTime.Minutes,
rInfo.stDateTime.Seconds, rInfo.stDateTime.HundredthSeconds );
aInfos[n].SignatureDate = aDate.GetDate();
aInfos[n].SignatureTime = aTime.GetTime();
// <--
DBG_ASSERT( rInfo.nStatus != ::com::sun::star::xml::crypto::SecurityOperationStatus_STATUS_UNKNOWN, "Signature not processed!" );
aInfos[n].SignatureIsValid = ( rInfo.nStatus == ::com::sun::star::xml::crypto::SecurityOperationStatus_OPERATION_SUCCEEDED );
if ( aInfos[n].SignatureIsValid )
{
// Can only be valid if ALL streams are signed, which means real stream count == signed stream count
int nRealCount = 0;
for ( int i = rInfo.vSignatureReferenceInfors.size(); i; )
{
const SignatureReferenceInformation& rInf = rInfo.vSignatureReferenceInfors[--i];
// There is also an extra entry of type TYPE_SAMEDOCUMENT_REFERENCE because of signature date.
if ( ( rInf.nType == TYPE_BINARYSTREAM_REFERENCE ) || ( rInf.nType == TYPE_XMLSTREAM_REFERENCE ) )
nRealCount++;
}
aInfos[n].SignatureIsValid = ( aElementsToBeVerified.size() == nRealCount );
}
}
}
return aInfos;
}
void DocumentDigitalSignatures::manageTrustedSources( ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
MacroSecurity aDlg( NULL, aSignatureHelper.GetSecurityEnvironment() );
aDlg.Execute();
}
void DocumentDigitalSignatures::ShowCertificate( const Reference< ::com::sun::star::security::XCertificate >& _Certificate ) throw (RuntimeException)
{
XMLSignatureHelper aSignatureHelper( mxMSF );
aSignatureHelper.Init( rtl::OUString() );
CertificateViewer aViewer( NULL, aSignatureHelper.GetSecurityEnvironment(), _Certificate );
aViewer.Execute();
}
::sal_Bool DocumentDigitalSignatures::isAuthorTrusted( const Reference< ::com::sun::star::security::XCertificate >& Author ) throw (RuntimeException)
{
sal_Bool bFound = sal_False;
::rtl::OUString sSerialNum = bigIntegerToNumericString( Author->getSerialNumber() );
Sequence< SvtSecurityOptions::Certificate > aTrustedAuthors = SvtSecurityOptions().GetTrustedAuthors();
sal_Int32 nCnt = aTrustedAuthors.getLength();
const SvtSecurityOptions::Certificate* pAuthors = aTrustedAuthors.getConstArray();
const SvtSecurityOptions::Certificate* pAuthorsEnd = pAuthors + aTrustedAuthors.getLength();
for ( ; pAuthors != pAuthorsEnd; ++pAuthors )
{
SvtSecurityOptions::Certificate aAuthor = *pAuthors;
if ( ( aAuthor[0] == Author->getIssuerName() ) && ( aAuthor[1] == sSerialNum ) )
{
bFound = sal_True;
break;
}
}
return bFound;
}
::sal_Bool DocumentDigitalSignatures::isLocationTrusted( const ::rtl::OUString& Location ) throw (RuntimeException)
{
sal_Bool bFound = sal_False;
INetURLObject aLocObj( Location );
Sequence< ::rtl::OUString > aSecURLs = SvtSecurityOptions().GetSecureURLs();
sal_Int32 nCnt = aSecURLs.getLength();
const ::rtl::OUString* pSecURLs = aSecURLs.getConstArray();
const ::rtl::OUString* pSecURLsEnd = pSecURLs + aSecURLs.getLength();
for ( ; pSecURLs != pSecURLsEnd; ++pSecURLs )
{
INetURLObject aSecURL( *pSecURLs );
if ( aSecURL == aLocObj )
{
bFound = sal_True;
break;
}
}
return bFound;
}
void DocumentDigitalSignatures::addAuthorToTrustedSources( const Reference< ::com::sun::star::security::XCertificate >& Author ) throw (RuntimeException)
{
SvtSecurityOptions aSecOpts;
SvtSecurityOptions::Certificate aNewCert( 3 );
aNewCert[ 0 ] = Author->getIssuerName();
aNewCert[ 1 ] = bigIntegerToNumericString( Author->getSerialNumber() );
aNewCert[ 2 ] = baseEncode( Author->getEncoded(), BASE64 );
Sequence< SvtSecurityOptions::Certificate > aTrustedAuthors = aSecOpts.GetTrustedAuthors();
sal_Int32 nCnt = aTrustedAuthors.getLength();
aTrustedAuthors.realloc( nCnt + 1 );
aTrustedAuthors[ nCnt ] = aNewCert;
aSecOpts.SetTrustedAuthors( aTrustedAuthors );
}
void DocumentDigitalSignatures::addLocationToTrustedSources( const ::rtl::OUString& Location ) throw (RuntimeException)
{
SvtSecurityOptions aSecOpt;
Sequence< ::rtl::OUString > aSecURLs = aSecOpt.GetSecureURLs();
sal_Int32 nCnt = aSecURLs.getLength();
aSecURLs.realloc( nCnt + 1 );
aSecURLs[ nCnt ] = Location;
aSecOpt.SetSecureURLs( aSecURLs );
}
rtl::OUString DocumentDigitalSignatures::GetImplementationName() throw (RuntimeException)
{
return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) );
}
Sequence< rtl::OUString > DocumentDigitalSignatures::GetSupportedServiceNames() throw (cssu::RuntimeException)
{
Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.security.DocumentDigitalSignatures" ) );
return aRet;
}
Reference< XInterface > DocumentDigitalSignatures_CreateInstance(
const Reference< com::sun::star::lang::XMultiServiceFactory >& rSMgr) throw ( Exception )
{
return (cppu::OWeakObject*) new DocumentDigitalSignatures( rSMgr );
}
<|endoftext|> |
<commit_before>#include "ReversedCoaxialRZ.h"
#include "iostream"
#include "Units.h"
#include <cmath>
using namespace GeFiCa;
void ReversedCoaxialRZ::SetupBoundary()
{
double x1=HoleOutterR,
y1=Z,
x2=HoleInnerR,
y2=Z-HoleZ,
x3=Radius-ConnorLength,
y3=Z,
x4=Radius,
y4=Z-ConnorZ;
// y = k x + b
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=y3-k2*x3;
for (int i=0;i<n;i++) {
//right side of hole
if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
//left corner
if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
//left side of hole
if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
//right corner
if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
//down right side of hole
if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
//down right of corner
if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
//down left side of hole
if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
//down left of corner
if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
//down center of hole
if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
fdC2p[i]=y2-fC2[i];
}
}
//_____________________________________________________________________________
//
void ReversedCoaxialRZ::Initialize()
{
if (Radius<=HoleOutterR||Radius<=HoleInnerR) {
Warning("Initialize",
"Lower bound (%f) >= upper bound (%f)! No grid is created!",
Radius, HoleOutterR);
return;
}
double steplength1=(Radius*2)/(n1-1);
double steplength2=(Z-Z0)/(n2-1);
SetStepLength(steplength1,steplength2);
double x1=HoleOutterR,
y1=Z,
x2=HoleInnerR,
y2=Z-HoleZ,
x3=Radius-ConnorLength,
y3=Z,
x4=Radius,
y4=Z-ConnorZ;
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=(y3-k2*x3);
for(int i=n;i-->0;)
{
fC1[i]=fC1[i]-Radius;
fV[i]=(V0+V1)/2;
}
// set potential for electrodes
for(int i=n-1;i>=n-n1;i--) {
fIsFixed[i]=true;
fV[i]=V0;
if(fC1[n-1-i]>=-PointContactR-0.001&&fC1[n-1-i]<=PointContactR+0.001) {
fV[n-1-i]=V1;
fIsFixed[n-1-i]=true;
}
}
for(int i=0;i<n-n1;i=i+n1) {
fIsFixed[i]=true;
fIsFixed[i+n1-1]=true;
fV[i]=V0;
fV[i+n1-1]=V0;
}
for (int i=0;i<n;i++)
{
if(((fC2[i]>-k1*(fC1[i])+b1-steplength2/2 && fC2[i]>y2-steplength2/2)||(fC2[i]>-k2*(fC1[i])+b2-steplength2/2))&&fC1[i]<0)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(((fC2[i]>-k1*(fC1[i])+b1+steplength2 && fC2[i]>y2+steplength2)||fC2[i]>-k2*(fC1[i])+b2+steplength2)&&fC1[i]<0)
{
fV[i]=0;
}
if(((fC2[i]>k1*(fC1[i])+b1-steplength2/2 && fC2[i]>y2-steplength2/2)||(fC2[i]>k2*(fC1[i])+b2-steplength2/2))&&fC1[i]>0)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(((fC2[i]>k1*(fC1[i])+b1+steplength2 && fC2[i]>y2+steplength2)||fC2[i]>k2*(fC1[i])+b2+steplength2)&&fC1[i]>0)
{
fV[i]=0;
}
}
SetupBoundary();
}
//_____________________________________________________________________________
//
bool ReversedCoaxialRZ::CalculatePotential(EMethod method)
{
if(!fIsLoaded)Initialize();
return RZ::CalculatePotential(method);
}
<commit_msg>fix hole boundary setup<commit_after>#include "ReversedCoaxialRZ.h"
#include "iostream"
#include "Units.h"
#include <cmath>
using namespace GeFiCa;
void ReversedCoaxialRZ::SetupBoundary()
{
double x1=HoleOutterR,
y1=Z,
x2=HoleInnerR,
y2=Z-HoleZ,
x3=Radius-ConnorLength,
y3=Z,
x4=Radius,
y4=Z-ConnorZ;
// y = k x + b
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=y3-k2*x3;
for (int i=0;i<n;i++) {
//right side of hole
if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
//left corner
if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
//left side of hole
if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
//right corner
if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
//down right side of hole
if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
//down right of corner
if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
//down left side of hole
if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
//down left of corner
if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
//down center of hole
if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
fdC2p[i]=y2-fC2[i];
}
}
//_____________________________________________________________________________
//
void ReversedCoaxialRZ::Initialize()
{
if (Radius<=HoleOutterR||Radius<=HoleInnerR) {
Warning("Initialize",
"Lower bound (%f) >= upper bound (%f)! No grid is created!",
Radius, HoleOutterR);
return;
}
double steplength1=(Radius*2)/(n1-1);
double steplength2=(Z-Z0)/(n2-1);
SetStepLength(steplength1,steplength2);
double x1=HoleOutterR,
y1=Z,
x2=HoleInnerR,
y2=Z-HoleZ,
x3=Radius-ConnorLength,
y3=Z,
x4=Radius,
y4=Z-ConnorZ;
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=(y3-k2*x3);
for(int i=n;i-->0;)
{
fC1[i]=fC1[i]-Radius;
fV[i]=(V0+V1)/2;
}
// set potential for electrodes
for(int i=n-1;i>=n-n1;i--) {
fIsFixed[i]=true;
fV[i]=V0;
if(fC1[n-1-i]>=-PointContactR-0.001&&fC1[n-1-i]<=PointContactR+0.001) {
fV[n-1-i]=V1;
fIsFixed[n-1-i]=true;
}
}
for(int i=0;i<n-n1;i=i+n1) {
fIsFixed[i]=true;
fIsFixed[i+n1-1]=true;
fV[i]=V0;
fV[i+n1-1]=V0;
}
for (int i=0;i<n;i++)
{
if(((fC2[i]>-k1*(fC1[i])+b1 && fC2[i]>y2)||(fC2[i]>-k2*(fC1[i])+b2))&&fC1[i]<0)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(((fC2[i]>k1*(fC1[i])+b1 && fC2[i]>y2)||(fC2[i]>k2*(fC1[i])+b2))&&fC1[i]>0)
{
fIsFixed[i]=true;
fV[i]=V0;
}
}
SetupBoundary();
}
//_____________________________________________________________________________
//
bool ReversedCoaxialRZ::CalculatePotential(EMethod method)
{
if(!fIsLoaded)Initialize();
return RZ::CalculatePotential(method);
}
<|endoftext|> |
<commit_before>#include "SecondaryWindows.h"
FenetreNewGame::FenetreNewGame()
{
setWindowTitle("Nouvelle partie");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFixedSize(300, 240);
QGridLayout *grid1 = new QGridLayout();
QGridLayout *grid2 = new QGridLayout();
group1 = new QGroupBox();
group2 = new QGroupBox();
dialogButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(dialogButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(dialogButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);
// choix de la difficulte
m_facile = new QRadioButton("Facile");
m_moyen = new QRadioButton("Moyen");
m_difficile = new QRadioButton("Difficile");
m_aleatoire = new QRadioButton("Aleatoire");
// choix du nombre de joueurs
m_un = new QRadioButton("Un joueur");
m_deux = new QRadioButton("Deux joueurs");
//Definition des Sections;
grid1->addWidget(m_un);
grid1->addWidget(m_deux);
m_un->setChecked(true);
grid2->addWidget(m_facile, 0, 0, 0, 9, Qt::AlignLeft);
grid2->addWidget(m_moyen, 0, 4, 0, 8);
grid2->addWidget(m_difficile, 0, 6, 0, 9, Qt::AlignCenter);
grid2->addWidget(m_aleatoire, 0, 9, 0, 9, Qt::AlignRight);
m_facile->setChecked(true);
// integration de bouton
QVBoxLayout *vertical = new QVBoxLayout();
QHBoxLayout *horizontal = new QHBoxLayout();
group1->setLayout(grid1);
group1->setTitle("Selectionner le nombre de joueurs");
group2->setLayout(grid2);
group2->setTitle("Selectionner la difficulte");
vertical->addWidget(group1);
horizontal->addWidget(group2);
vertical->addLayout(horizontal);
vertical->addWidget(dialogButtons);
setLayout(vertical);
}
FenetreTutoriel::FenetreTutoriel()
{
setWindowTitle("Tutoriel");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
window = new QVBoxLayout();
title = new QLabel("Dans ce pr" + QString(233) + "sent tutoriel, l'explication du jeu sera fait enti" + QString(232) + "rement.");
content = new QLabel(" Pour ajuster les param" + QString(232) + "tre du canon, dite 'A' ou 'O' et le tenire jusqu'"
+ QString(224) + " ce que vous vouliez arr" + QString(234) +
"ter! \n Pour change le mode, dite 'I' pour changer le mode \n");
window->addWidget(title, 1, Qt::AlignCenter);
window->addWidget(content, 1, Qt::AlignCenter);
QHBoxLayout * firstRow = new QHBoxLayout;
QLabel * firstPicture = new QLabel;
firstPicture->setPixmap(QPixmap(":/resources/tutoriel/tour_joueur.jpg"));
QLabel * firstText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du joueur courant.");
firstRow->addWidget(firstPicture);
firstRow->addWidget(firstText, 0, Qt::AlignRight);
QHBoxLayout * secondRow = new QHBoxLayout;
QLabel * secondPicture = new QLabel;
secondPicture->setPixmap(QPixmap(":/resources/tutoriel/mode_joueur.jpg"));
QLabel * secondText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du mode d'ajustement courant du joueur.");
secondRow->addWidget(secondPicture);
secondRow->addWidget(secondText, 0, Qt::AlignRight);
QHBoxLayout * thirdRow = new QHBoxLayout;
QLabel * thirdPicture = new QLabel;
thirdPicture->setPixmap(QPixmap(":/resources/tutoriel/parametres_mode.jpg"));
QLabel * thirdText = new QLabel("Indicateur des param" + QString(232) + "tres de tir du joueur");
thirdRow->addWidget(thirdPicture);
thirdRow->addWidget(thirdText, 0, Qt::AlignRight);
window->addLayout(firstRow);
window->addLayout(secondRow);
window->addLayout(thirdRow);
setLayout(window);
}
FenetreVersion::FenetreVersion()
{
setWindowTitle("Version");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFixedSize(500, 140);
QVBoxLayout * vertical = new QVBoxLayout();
m_ligne1 = new QLabel("SCORCH VERSION 0.5");
m_ligne2 = new QLabel("Derniere mise a jour : 2016-04-04");
m_ligne3 = new QLabel("Developpe par l'equipe P19 de l'U de S");
m_ligne4 = new QLabel("Les programmeurs ayant particip" + QString(233) + " " + QString(224) + " la cr" + QString(233) + "ation de Scorch");
m_ligne5 = new QLabel("Emile Fugulin, Jean-Philippe Fournier, Julien Larochelle, Philippe Spino");
m_ligne1->setFont(QFont("OCR A extented",10));
m_ligne2->setFont(QFont("fantasque sans mono",10));
m_ligne3->setFont(QFont("fantasque sans mono",10));
m_ligne4->setFont(QFont("fantasque sans mono",10));
m_ligne5->setFont(QFont("fantasque sans mono",10));
vertical->addWidget(m_ligne1, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne2, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne3, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne4, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne5, 1, Qt::AlignCenter);
setLayout(vertical);
}
<commit_msg>Continued tutorial window<commit_after>#include "SecondaryWindows.h"
FenetreNewGame::FenetreNewGame()
{
setWindowTitle("Nouvelle partie");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFixedSize(300, 240);
QGridLayout *grid1 = new QGridLayout();
QGridLayout *grid2 = new QGridLayout();
group1 = new QGroupBox();
group2 = new QGroupBox();
dialogButtons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(dialogButtons, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(dialogButtons, &QDialogButtonBox::rejected, this, &QDialog::reject);
// choix de la difficulte
m_facile = new QRadioButton("Facile");
m_moyen = new QRadioButton("Moyen");
m_difficile = new QRadioButton("Difficile");
m_aleatoire = new QRadioButton("Aleatoire");
// choix du nombre de joueurs
m_un = new QRadioButton("Un joueur");
m_deux = new QRadioButton("Deux joueurs");
//Definition des Sections;
grid1->addWidget(m_un);
grid1->addWidget(m_deux);
m_un->setChecked(true);
grid2->addWidget(m_facile, 0, 0, 0, 9, Qt::AlignLeft);
grid2->addWidget(m_moyen, 0, 4, 0, 8);
grid2->addWidget(m_difficile, 0, 6, 0, 9, Qt::AlignCenter);
grid2->addWidget(m_aleatoire, 0, 9, 0, 9, Qt::AlignRight);
m_facile->setChecked(true);
// integration de bouton
QVBoxLayout *vertical = new QVBoxLayout();
QHBoxLayout *horizontal = new QHBoxLayout();
group1->setLayout(grid1);
group1->setTitle("Selectionner le nombre de joueurs");
group2->setLayout(grid2);
group2->setTitle("Selectionner la difficulte");
vertical->addWidget(group1);
horizontal->addWidget(group2);
vertical->addLayout(horizontal);
vertical->addWidget(dialogButtons);
setLayout(vertical);
}
FenetreTutoriel::FenetreTutoriel()
{
setWindowTitle("Tutoriel");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setMaximumSize(QSize(600, 2000));
setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding);
window = new QVBoxLayout();
//title = new QLabel("Dans ce pr" + QString(233) + "sent tutoriel, l'explication du jeu sera fait enti" + QString(232) + "rement.");
content = new QLabel("Pour ajuster les param" + QString(232) + "tre du canon, dite 'A' ou 'O' et le tenir jusqu'"
+ QString(224) + " ce que vous vouliez arr" + QString(234) + "ter. Pour changer le mode, il faut prononcer la lettre 'I'. Les clavier peut aussi contrler les activits de tir, les flches gauche et droite permettant de modifier le mode d'ajustement et les flches haut et bas permettant d'ajuster le paramtre. La barre espace permet quant elle de provoquer le tir lorsque le mode est \"tir\"");
content->setWordWrap(true);
//window->addWidget(title, 0, Qt::AlignCenter);
window->addWidget(content, 0, Qt::AlignLeft);
QHBoxLayout * firstRow = new QHBoxLayout;
QLabel * firstPicture = new QLabel;
firstPicture->setPixmap(QPixmap(":/resources/tutoriel/tour_joueur.jpg"));
QLabel * firstText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du joueur courant.");
//firstText->setWordWrap(true);
firstRow->addWidget(firstText, 0, Qt::AlignLeft);
firstRow->addWidget(firstPicture, 0, Qt::AlignRight);
QHBoxLayout * secondRow = new QHBoxLayout;
QLabel * secondPicture = new QLabel;
secondPicture->setPixmap(QPixmap(":/resources/tutoriel/mode_joueur.jpg"));
QLabel * secondText = new QLabel("Cette partie de l'interface repr" + QString(233) + "sente l'indication du mode d'ajustement courant du joueur.");
//secondText->setWordWrap(true);
secondRow->addWidget(secondText, 0, Qt::AlignLeft);
secondRow->addWidget(secondPicture, 0, Qt::AlignRight);
QHBoxLayout * thirdRow = new QHBoxLayout;
QLabel * thirdPicture = new QLabel;
thirdPicture->setPixmap(QPixmap(":/resources/tutoriel/parametres_mode.jpg"));
QLabel * thirdText = new QLabel("Indicateur des param" + QString(232) + "tres de tir du joueur");
thirdText->setWordWrap(true);
thirdRow->addWidget(thirdText, 0, Qt::AlignLeft);
thirdRow->addWidget(thirdPicture, 0, Qt::AlignRight);
QHBoxLayout * fourthRow = new QHBoxLayout;
QLabel * fourthText = new QLabel("Dans le menu de nouvelle partie, il est possible de s" + QString(233) + "lectionner un mode de jeu entre \"un joueur\" et \"deux joueurs\". Le mode simple joueur inclut une intelligence pour l'adversaire." + QString("Aussi dans la cr" + QString(233) + "ation d'une nouvelle partie, il est possible de s" + QString(233) + "lectionner le difficult" + QString(233) + ", qui ajuste premi" + QString(232) + "rement le niveau de difficult" + QString(233) + " du terrain."));
fourthText->setWordWrap(true);
fourthRow->addWidget(fourthText, 0, Qt::AlignLeft);
window->addLayout(firstRow);
window->addLayout(secondRow);
window->addLayout(thirdRow);
window->addLayout(fourthRow);
setLayout(window);
}
FenetreVersion::FenetreVersion()
{
setWindowTitle("Version");
setWindowIcon(QIcon(QPixmap(":/resources/icon_big.png")));
setFixedSize(500, 140);
QVBoxLayout * vertical = new QVBoxLayout();
m_ligne1 = new QLabel("SCORCH VERSION 0.5");
m_ligne2 = new QLabel("Derniere mise a jour : 2016-04-04");
m_ligne3 = new QLabel("Developpe par l'equipe P19 de l'U de S");
m_ligne4 = new QLabel("Les programmeurs ayant particip" + QString(233) + " " + QString(224) + " la cr" + QString(233) + "ation de Scorch");
m_ligne5 = new QLabel("Emile Fugulin, Jean-Philippe Fournier, Julien Larochelle, Philippe Spino");
m_ligne1->setFont(QFont("OCR A extented",10));
m_ligne2->setFont(QFont("fantasque sans mono",10));
m_ligne3->setFont(QFont("fantasque sans mono",10));
m_ligne4->setFont(QFont("fantasque sans mono",10));
m_ligne5->setFont(QFont("fantasque sans mono",10));
vertical->addWidget(m_ligne1, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne2, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne3, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne4, 1, Qt::AlignCenter);
vertical->addWidget(m_ligne5, 1, Qt::AlignCenter);
setLayout(vertical);
}
<|endoftext|> |
<commit_before>#include "hyperclient/hyperclient.h"
#include <iostream>
using namespace std;
int main()
{
cout<<"test start "<<endl;
//define hyper attribute
hyperclient_attribute test_attr[3];
test_attr[0].attr = "phone";
test_attr[0].value = "123455";
test_attr[0].value_sz = strlen(test_attr[0].value);
test_attr[0].datatype = HYPERDATATYPE_STRING;
test_attr[1].attr = "last";
test_attr[1].value = "Yang";
test_attr[1].value_sz = strlen(test_attr[1].value);
test_attr[1].datatype = HYPERDATATYPE_STRING;
test_attr[2].attr = "first";
test_attr[2].value = "Fred";
test_attr[2].value_sz = strlen(test_attr[2].value);
test_attr[2].datatype = HYPERDATATYPE_STRING;
hyperclient_returncode retcode;
const char *key = "adamyang";
hyperclient test_client("127.0.0.1", 1234);
const char *trigger = "testtrigger";
int64_t ret = test_client.tri_put("phonebook", key, strlen(key), trigger, strlen(trigger), &retcode, test_attr, 3);
hyperclient_returncode loop_status;
int64_t loop_id = test_client.loop(-1, &loop_status);
if(ret != loop_id)
{
cout <<"exit here 1"<<endl;
exit(1);
}
cout<<"put ret is "<<ret<<" return code is "<<retcode<<endl;
//define the container for the attribute get
const char *key2 = "andywang";
hyperclient_attribute *test_get_attr;
size_t get_size = 0;
ret = test_client.tri_get("phonebook", key2, strlen(key2), trigger, strlen(trigger), &retcode, &test_get_attr, &get_size);
loop_id = test_client.loop(-1, &loop_status);
if(ret != loop_id)
{
cout <<"exit here 2"<<endl;
exit(1);
}
if(get_size!=0)
{
cout<<"we get something "<<endl;
for(int i=0; i<get_size; i++)
{
cout<<"attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
}
}
else
{
cout<<"we get nothing"<<endl;
}
cout<<"get ret is "<<ret<<" return code is "<<retcode<<endl;
return 0;
}
<commit_msg>tested search<commit_after>#include "hyperclient/hyperclient.h"
#include <iostream>
using namespace std;
int main()
{
cout<<"test start "<<endl;
//first we put a entry into the keystore
hyperclient_attribute test_attr[3];
test_attr[0].attr = "phone";
test_attr[0].value = "123455";
test_attr[0].value_sz = strlen(test_attr[0].value);
test_attr[0].datatype = HYPERDATATYPE_STRING;
test_attr[1].attr = "last";
test_attr[1].value = "Yang";
test_attr[1].value_sz = strlen(test_attr[1].value);
test_attr[1].datatype = HYPERDATATYPE_STRING;
test_attr[2].attr = "first";
test_attr[2].value = "Fred";
test_attr[2].value_sz = strlen(test_attr[2].value);
test_attr[2].datatype = HYPERDATATYPE_STRING;
hyperclient_returncode retcode;
const char *key = "adamyang";
hyperclient test_client("127.0.0.1", 1234);
const char *trigger = "testtrigger";
int64_t ret = test_client.tri_put("phonebook", key, strlen(key), trigger, strlen(trigger), &retcode, test_attr, 3);
hyperclient_returncode loop_status;
int64_t loop_id = test_client.loop(-1, &loop_status);
if(ret != loop_id)
{
cout <<"exit here 1"<<endl;
exit(1);
}
cout<<"put ret is "<<ret<<" return code is "<<retcode<<endl;
//define the container for the attribute get
//we then use tri_get to get the data out, which will returned triggered output
const char *key2 = "andywang";
hyperclient_attribute *test_get_attr;
size_t get_size = 0;
ret = test_client.tri_get("phonebook", key2, strlen(key2), trigger, strlen(trigger), &retcode, &test_get_attr, &get_size);
loop_id = test_client.loop(-1, &loop_status);
if(ret != loop_id)
{
cout <<"exit here 2"<<endl;
exit(1);
}
if(get_size!=0)
{
cout<<"we get something "<<endl;
for(int i=0; i<get_size; i++)
{
cout<<"attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
}
}
else
{
cout<<"we get nothing"<<endl;
}
cout<<"get ret is "<<ret<<" return code is "<<retcode<<endl;
//This part will be used to test the search function
hyperclient_attribute search_attr[1];
search_attr[0].attr = "first";
search_attr[0].value = "Fred";
search_attr[0].value_sz = strlen(search_attr[0].value);
search_attr[0].datatype = HYPERDATATYPE_STRING;
ret = test_client.search("phonebook", search_attr, 1, NULL, 0, &retcode, &test_get_attr, &get_size);
while(1)
{
loop_id = test_client.loop(-1, &loop_status);
if(loop_id < 0)
{
cout<<"we break because loop_id < 0"<<endl;
break;
}
if(retcode == HYPERCLIENT_SEARCHDONE)
{
cout<<"we break because we finished search"<<endl;
break;
}
if(loop_id == ret)
{
cout<<"we get something, the retcode is "<<loop_status<<endl;
for(int i=0; i<get_size; i++)
{
cout<<"search out: attr "<<i<<": "<<test_get_attr[i].attr<<", value : "<<string(test_get_attr[i].value, test_get_attr[i].value_sz)<<endl;
}
}
}
if(loop_status != HYPERCLIENT_SEARCHDONE)
cout<<"search error happens loop_status is "<<loop_status<<endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "StageSelectState.h"
#include "MenuState.h"
#include "EditState.h"
#include "CharacterSelectState.h"
#include "Game.h"
#include <string>
#include <cstdlib>
using std::to_string;
StageSelectState::StageSelectState(bool cgo_to_edit) {
planet = Sprite("stage_select/planet.png", 8, FRAME_TIME);
planet.set_scale(1.5);
go_to_edit = cgo_to_edit;
n_stages = 2 + (go_to_edit ? 0 : 1);
blocked = Sound("menu/sound/cancel.ogg");
selected = Sound("menu/sound/select.ogg");
changed = Sound("menu/sound/cursor.ogg");
for(int i=0;i<N_BACKGROUNDS;i++){
background[i] = Sprite("stage_select/background_" + to_string(i) + ".png");
}
for(int i=0;i<n_stages;i++){
stage[i] = Sprite("stage_select/stage_" + to_string(i + 1) + ".png");
}
InputManager::get_instance()->map_keyboard_to_joystick(InputManager::MENU_MODE);
}
void StageSelectState::update(float delta) {
process_input();
InputManager * input_manager = InputManager::get_instance();
if(input_manager->quit_requested()){
m_quit_requested = true;
return;
}
if(pressed[B] || pressed[SELECT]) {
selected.play();
m_quit_requested = true;
Game::get_instance().push(new MenuState(true));
return;
}
if(pressed[LEFT]) {
selected.play();
update_stage_select(-1);
}
if(pressed[RIGHT]) {
selected.play();
update_stage_select(1);
}
if(pressed[A] || pressed[START]) {
selected.play();
m_quit_requested = true;
if(stage_select == 2){
srand(clock());
stage_select = rand() % (n_stages - (go_to_edit ? 0 : 1));
}
if(go_to_edit)
Game::get_instance().push(new EditState(to_string(stage_select + 1)));
else
Game::get_instance().push(new CharacterSelectState(to_string(stage_select + 1)));
}
planet.update(delta);
}
void StageSelectState::render() {
background[0].render();
planet.render(640 - planet.get_width() / 2, 360 - planet.get_height() / 2);
background[1].render();
for(int i=0;i<n_stages;i++){
stage[i].render(i * 780 - stage_select * 780);
}
}
void StageSelectState::update_stage_select(int increment) {
stage_select += increment;
if(stage_select < 0) stage_select = 0;
if(stage_select > n_stages - 1) stage_select = n_stages - 1;
}
void StageSelectState::process_input(){
InputManager * input_manager = InputManager::get_instance();
//MENU BUTTONS HERE
vector< pair<int, int> > joystick_buttons = {
ii(LEFT, InputManager::LEFT),
ii(RIGHT, InputManager::RIGHT),
ii(A, InputManager::A),
ii(B, InputManager::B),
ii(START, InputManager::START),
ii(SELECT, InputManager::SELECT)
};
for(ii button : joystick_buttons){
pressed[button.first] = input_manager->joystick_button_press(button.second, 0);
}
}
void StageSelectState::pause() {
}
void StageSelectState::resume() {
}
<commit_msg>Add cancel sound to stage selection<commit_after>#include "StageSelectState.h"
#include "MenuState.h"
#include "EditState.h"
#include "CharacterSelectState.h"
#include "Game.h"
#include <string>
#include <cstdlib>
using std::to_string;
StageSelectState::StageSelectState(bool cgo_to_edit) {
planet = Sprite("stage_select/planet.png", 8, FRAME_TIME);
planet.set_scale(1.5);
go_to_edit = cgo_to_edit;
n_stages = 2 + (go_to_edit ? 0 : 1);
blocked = Sound("menu/sound/cancel.ogg");
selected = Sound("menu/sound/select.ogg");
changed = Sound("menu/sound/cursor.ogg");
for(int i=0;i<N_BACKGROUNDS;i++){
background[i] = Sprite("stage_select/background_" + to_string(i) + ".png");
}
for(int i=0;i<n_stages;i++){
stage[i] = Sprite("stage_select/stage_" + to_string(i + 1) + ".png");
}
InputManager::get_instance()->map_keyboard_to_joystick(InputManager::MENU_MODE);
}
void StageSelectState::update(float delta) {
process_input();
InputManager * input_manager = InputManager::get_instance();
if(input_manager->quit_requested()){
m_quit_requested = true;
return;
}
if(pressed[B] || pressed[SELECT]) {
selected.play();
m_quit_requested = true;
Game::get_instance().push(new MenuState(true));
return;
}
if(pressed[LEFT]) {
update_stage_select(-1);
}
if(pressed[RIGHT]) {
update_stage_select(1);
}
if(pressed[A] || pressed[START]) {
selected.play();
m_quit_requested = true;
if(stage_select == 2){
srand(clock());
stage_select = rand() % (n_stages - (go_to_edit ? 0 : 1));
}
if(go_to_edit)
Game::get_instance().push(new EditState(to_string(stage_select + 1)));
else
Game::get_instance().push(new CharacterSelectState(to_string(stage_select + 1)));
}
planet.update(delta);
}
void StageSelectState::render() {
background[0].render();
planet.render(640 - planet.get_width() / 2, 360 - planet.get_height() / 2);
background[1].render();
for(int i=0;i<n_stages;i++){
stage[i].render(i * 780 - stage_select * 780);
}
}
void StageSelectState::update_stage_select(int increment) {
stage_select += increment;
if(stage_select < 0){
blocked.play();
stage_select = 0;
}
else if(stage_select > n_stages - 1){
blocked.play();
stage_select = n_stages - 1;
}
else{
selected.play();
}
}
void StageSelectState::process_input(){
InputManager * input_manager = InputManager::get_instance();
//MENU BUTTONS HERE
vector< pair<int, int> > joystick_buttons = {
ii(LEFT, InputManager::LEFT),
ii(RIGHT, InputManager::RIGHT),
ii(A, InputManager::A),
ii(B, InputManager::B),
ii(START, InputManager::START),
ii(SELECT, InputManager::SELECT)
};
for(ii button : joystick_buttons){
pressed[button.first] = input_manager->joystick_button_press(button.second, 0);
}
}
void StageSelectState::pause() {
}
void StageSelectState::resume() {
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QMimeData>
#include <QUrl>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), speedDialMemory(0),
settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()) {
ui->setupUi(this);
ui->PauseResume_Button->setFocus();
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->actionAbout_Qt, SIGNAL(triggered()), QApplication::instance(), SLOT(aboutQt()));
connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll()));
connect(ui->actionDelete, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteSelected()));
connect(ui->actionDelete_Escapees, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteEscapees()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered(bool)), ui->toggleFiringModePushButton, SLOT(setChecked(bool)));
connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation()));
connect(ui->toggleFiringModePushButton, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool)));
connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot()));
connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int)));
connect(ui->actionPrevious_Planet, SIGNAL(triggered()), ui->centralwidget, SLOT(followPrevious()));
connect(ui->actionNext_Planet, SIGNAL(triggered()), ui->centralwidget, SLOT(followNext()));
ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel("0 planets", ui->statusbar));
ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar));
ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar));
fpsLabel->setFixedWidth(120);
planetCountLabel->setFixedWidth(120);
averagefpsLabel->setFixedWidth(160);
connect(&ui->centralwidget->universe, SIGNAL(updatePlanetCountMessage(QString)), planetCountLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString)));
ui->menubar->insertMenu(ui->menuHelp->menuAction(), createPopupMenu())->setText(tr("Tools"));
ui->firingSettings_DockWidget->hide();
ui->randomSettings_DockWidget->hide();
const QStringList &arguments = QApplication::arguments();
foreach (const QString &argument, arguments) {
if(QFileInfo(argument).filePath() != QApplication::applicationFilePath() && ui->centralwidget->universe.load(argument)){
break;
}
}
settings.beginGroup("MainWindow");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("state").toByteArray());
settings.endGroup();
settings.beginGroup("Graphics");
ui->actionGrid->setChecked(settings.value("DrawGrid").toBool());
ui->actionDraw_Paths->setChecked(settings.value("DrawPaths").toBool());
settings.endGroup();
setAcceptDrops(true);
}
MainWindow::~MainWindow(){
settings.beginGroup("MainWindow");
settings.setValue("geometry", saveGeometry());
settings.setValue("state", saveState());
settings.endGroup();
settings.beginGroup("Graphics");
settings.setValue("DrawGrid", ui->actionGrid->isChecked());
settings.setValue("DrawPaths", ui->actionDraw_Paths->isChecked());
settings.endGroup();
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *e){
if(!ui->centralwidget->universe.isEmpty()){
int result = QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
QMessageBox::Yes | QMessageBox::Save | QMessageBox::No, QMessageBox::Yes);
if(result == QMessageBox::No || (result == QMessageBox::Save && !on_actionSave_Simulation_triggered())){
return e->ignore();
}
}
e->accept();
}
void MainWindow::on_createPlanet_PushButton_clicked(){
ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()),
QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac,
ui->newMass_SpinBox->value()));
}
void MainWindow::on_actionClear_Velocity_triggered(){
if(ui->centralwidget->universe.isSelectedValid()){
ui->centralwidget->universe.getSelected().velocity = QVector3D();
}
}
void MainWindow::on_speed_Dial_valueChanged(int value){
ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum();
ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
if(ui->speed_Dial->value() == 0){
ui->PauseResume_Button->setText(tr("Resume"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
}else{
ui->PauseResume_Button->setText(tr("Pause"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
}
}
void MainWindow::on_PauseResume_Button_clicked(){
if(ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(speedDialMemory);
}else{
speedDialMemory = ui->speed_Dial->value();
ui->speed_Dial->setValue(0);
}
}
void MainWindow::on_FastForward_Button_clicked(){
if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(ui->speed_Dial->value() * 2);
}
}
void MainWindow::on_actionNew_Simulation_triggered(){
if(!ui->centralwidget->universe.isEmpty() && QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
ui->centralwidget->universe.deleteAll();
}
}
void MainWindow::on_actionOpen_Simulation_triggered(){
QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
ui->centralwidget->universe.load(filename);
}
}
void MainWindow::on_actionAppend_Simulation_triggered(){
QString filename = QFileDialog::getOpenFileName(this, tr("Append Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
ui->centralwidget->universe.load(filename, false);
}
}
bool MainWindow::on_actionSave_Simulation_triggered(){
if(!ui->centralwidget->universe.isEmpty()){
QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
return ui->centralwidget->universe.save(filename);
}
}else{
QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!"));
}
return false;
}
void MainWindow::on_actionFollow_Selection_triggered(){
ui->centralwidget->following = ui->centralwidget->universe.selected;
ui->centralwidget->followState = PlanetsWidget::Single;
}
void MainWindow::on_actionClear_Follow_triggered(){
ui->centralwidget->following = 0;
ui->centralwidget->followState = PlanetsWidget::FollowNone;
}
void MainWindow::on_actionPlain_Average_triggered(){
ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}
void MainWindow::on_actionWeighted_Average_triggered(){
ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}
void MainWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About Planets3D"),
tr("<html><head/><body>"
"<p>Planets3D is a simple 3D gravitational simulator</p>"
"<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>"
"<p>Build Info:</p><ul>"
"<li>Git sha1: %2</li>"
"<li>Build type: %3</li>"
"<li>Compiler: %4</li>"
"<li>CMake Version: %5</li>"
"</ul></body></html>")
.arg(version::git_revision)
.arg(version::build_type)
.arg(version::compiler)
.arg(version::cmake_version));
}
void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
ui->centralwidget->universe.stepsPerFrame = value;
}
void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
Planet::pathLength = value;
}
void MainWindow::on_planetScaleDoubleSpinBox_valueChanged(double value){
ui->centralwidget->drawScale = value;
}
void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){
Planet::pathRecordDistance = value * value;
}
void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac;
}
void MainWindow::on_firingMassSpinBox_valueChanged(int value){
ui->centralwidget->firingMass = value;
}
void MainWindow::on_actionGrid_toggled(bool value){
ui->centralwidget->drawGrid = value;
}
void MainWindow::on_actionDraw_Paths_toggled(bool value){
ui->centralwidget->drawPlanetTrails = value;
}
void MainWindow::on_actionPlanet_Colors_toggled(bool value){
ui->centralwidget->drawPlanetColors = value;
}
void MainWindow::on_actionHide_Planets_toggled(bool value){
ui->centralwidget->hidePlanets = value;
if(value){
ui->actionDraw_Paths->setChecked(true);
}
}
void MainWindow::on_generateRandomPushButton_clicked(){
ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(),
ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac,
ui->randomMassDoubleSpinBox->value());
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
QFileInfo info(url.toLocalFile());
if(info.exists()){
return event->acceptProposedAction();
}
}
}
}
void MainWindow::dropEvent(QDropEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
if(ui->centralwidget->universe.load(url.toLocalFile())){
return event->acceptProposedAction();
}
}
}
}
bool MainWindow::event(QEvent *event){
switch(event->type()) {
case QEvent::WindowActivate:
if(ui->centralwidget->universe.simspeed <= 0.0f){
on_PauseResume_Button_clicked();
}
break;
case QEvent::WindowDeactivate:
if(ui->centralwidget->universe.simspeed > 0.0f){
on_PauseResume_Button_clicked();
}
break;
default: break;
}
return QMainWindow::event(event);
}
const int MainWindow::speeddialmax = 32;
<commit_msg>added trail settings and steps per frame to settings file. (they have to be manually added for now.)<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QMimeData>
#include <QUrl>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), speedDialMemory(0),
settings(QSettings::IniFormat, QSettings::UserScope, QApplication::organizationName(), QApplication::applicationName()) {
ui->setupUi(this);
ui->PauseResume_Button->setFocus();
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->actionAbout_Qt, SIGNAL(triggered()), QApplication::instance(), SLOT(aboutQt()));
connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll()));
connect(ui->actionDelete, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteSelected()));
connect(ui->actionDelete_Escapees, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteEscapees()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered(bool)), ui->toggleFiringModePushButton, SLOT(setChecked(bool)));
connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation()));
connect(ui->toggleFiringModePushButton, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool)));
connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot()));
connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int)));
connect(ui->actionPrevious_Planet, SIGNAL(triggered()), ui->centralwidget, SLOT(followPrevious()));
connect(ui->actionNext_Planet, SIGNAL(triggered()), ui->centralwidget, SLOT(followNext()));
ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel("0 planets", ui->statusbar));
ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar));
ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar));
fpsLabel->setFixedWidth(120);
planetCountLabel->setFixedWidth(120);
averagefpsLabel->setFixedWidth(160);
connect(&ui->centralwidget->universe, SIGNAL(updatePlanetCountMessage(QString)), planetCountLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString)));
ui->menubar->insertMenu(ui->menuHelp->menuAction(), createPopupMenu())->setText(tr("Tools"));
ui->firingSettings_DockWidget->hide();
ui->randomSettings_DockWidget->hide();
const QStringList &arguments = QApplication::arguments();
foreach (const QString &argument, arguments) {
if(QFileInfo(argument).filePath() != QApplication::applicationFilePath() && ui->centralwidget->universe.load(argument)){
break;
}
}
settings.beginGroup("MainWindow");
restoreGeometry(settings.value("geometry").toByteArray());
restoreState(settings.value("state").toByteArray());
settings.endGroup();
settings.beginGroup("Graphics");
ui->actionGrid->setChecked(settings.value("DrawGrid").toBool());
ui->actionDraw_Paths->setChecked(settings.value("DrawPaths").toBool());
/* These aren't auto-saved, so for the moment they must be manually added to the config file. */
if(settings.contains("TrailLength")){
ui->trailLengthSpinBox->setValue(settings.value("TrailLength").toInt());
}
if(settings.contains("TrailDelta")){
ui->trailRecordDistanceDoubleSpinBox->setValue(settings.value("TrailDelta").toDouble());
}
settings.endGroup();
if(settings.contains("StepsPerFrame")){
ui->stepsPerFrameSpinBox->setValue(settings.value("StepsPerFrame").toInt());
}
setAcceptDrops(true);
}
MainWindow::~MainWindow(){
settings.beginGroup("MainWindow");
settings.setValue("geometry", saveGeometry());
settings.setValue("state", saveState());
settings.endGroup();
settings.beginGroup("Graphics");
settings.setValue("DrawGrid", ui->actionGrid->isChecked());
settings.setValue("DrawPaths", ui->actionDraw_Paths->isChecked());
settings.endGroup();
delete ui;
}
void MainWindow::closeEvent(QCloseEvent *e){
if(!ui->centralwidget->universe.isEmpty()){
int result = QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
QMessageBox::Yes | QMessageBox::Save | QMessageBox::No, QMessageBox::Yes);
if(result == QMessageBox::No || (result == QMessageBox::Save && !on_actionSave_Simulation_triggered())){
return e->ignore();
}
}
e->accept();
}
void MainWindow::on_createPlanet_PushButton_clicked(){
ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()),
QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac,
ui->newMass_SpinBox->value()));
}
void MainWindow::on_actionClear_Velocity_triggered(){
if(ui->centralwidget->universe.isSelectedValid()){
ui->centralwidget->universe.getSelected().velocity = QVector3D();
}
}
void MainWindow::on_speed_Dial_valueChanged(int value){
ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum();
ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
if(ui->speed_Dial->value() == 0){
ui->PauseResume_Button->setText(tr("Resume"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
}else{
ui->PauseResume_Button->setText(tr("Pause"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
}
}
void MainWindow::on_PauseResume_Button_clicked(){
if(ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(speedDialMemory);
}else{
speedDialMemory = ui->speed_Dial->value();
ui->speed_Dial->setValue(0);
}
}
void MainWindow::on_FastForward_Button_clicked(){
if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(ui->speed_Dial->value() * 2);
}
}
void MainWindow::on_actionNew_Simulation_triggered(){
if(!ui->centralwidget->universe.isEmpty() && QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
ui->centralwidget->universe.deleteAll();
}
}
void MainWindow::on_actionOpen_Simulation_triggered(){
QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
ui->centralwidget->universe.load(filename);
}
}
void MainWindow::on_actionAppend_Simulation_triggered(){
QString filename = QFileDialog::getOpenFileName(this, tr("Append Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
ui->centralwidget->universe.load(filename, false);
}
}
bool MainWindow::on_actionSave_Simulation_triggered(){
if(!ui->centralwidget->universe.isEmpty()){
QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));
if(!filename.isEmpty()){
return ui->centralwidget->universe.save(filename);
}
}else{
QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!"));
}
return false;
}
void MainWindow::on_actionFollow_Selection_triggered(){
ui->centralwidget->following = ui->centralwidget->universe.selected;
ui->centralwidget->followState = PlanetsWidget::Single;
}
void MainWindow::on_actionClear_Follow_triggered(){
ui->centralwidget->following = 0;
ui->centralwidget->followState = PlanetsWidget::FollowNone;
}
void MainWindow::on_actionPlain_Average_triggered(){
ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}
void MainWindow::on_actionWeighted_Average_triggered(){
ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}
void MainWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About Planets3D"),
tr("<html><head/><body>"
"<p>Planets3D is a simple 3D gravitational simulator</p>"
"<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>"
"<p>Build Info:</p><ul>"
"<li>Git sha1: %2</li>"
"<li>Build type: %3</li>"
"<li>Compiler: %4</li>"
"<li>CMake Version: %5</li>"
"</ul></body></html>")
.arg(version::git_revision)
.arg(version::build_type)
.arg(version::compiler)
.arg(version::cmake_version));
}
void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
ui->centralwidget->universe.stepsPerFrame = value;
}
void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
Planet::pathLength = value;
}
void MainWindow::on_planetScaleDoubleSpinBox_valueChanged(double value){
ui->centralwidget->drawScale = value;
}
void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){
Planet::pathRecordDistance = value * value;
}
void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac;
}
void MainWindow::on_firingMassSpinBox_valueChanged(int value){
ui->centralwidget->firingMass = value;
}
void MainWindow::on_actionGrid_toggled(bool value){
ui->centralwidget->drawGrid = value;
}
void MainWindow::on_actionDraw_Paths_toggled(bool value){
ui->centralwidget->drawPlanetTrails = value;
}
void MainWindow::on_actionPlanet_Colors_toggled(bool value){
ui->centralwidget->drawPlanetColors = value;
}
void MainWindow::on_actionHide_Planets_toggled(bool value){
ui->centralwidget->hidePlanets = value;
if(value){
ui->actionDraw_Paths->setChecked(true);
}
}
void MainWindow::on_generateRandomPushButton_clicked(){
ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(),
ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac,
ui->randomMassDoubleSpinBox->value());
}
void MainWindow::dragEnterEvent(QDragEnterEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
QFileInfo info(url.toLocalFile());
if(info.exists()){
return event->acceptProposedAction();
}
}
}
}
void MainWindow::dropEvent(QDropEvent *event){
if(event->mimeData()->hasUrls()){
foreach(QUrl url, event->mimeData()->urls()){
if(ui->centralwidget->universe.load(url.toLocalFile())){
return event->acceptProposedAction();
}
}
}
}
bool MainWindow::event(QEvent *event){
switch(event->type()) {
case QEvent::WindowActivate:
if(ui->centralwidget->universe.simspeed <= 0.0f){
on_PauseResume_Button_clicked();
}
break;
case QEvent::WindowDeactivate:
if(ui->centralwidget->universe.simspeed > 0.0f){
on_PauseResume_Button_clicked();
}
break;
default: break;
}
return QMainWindow::event(event);
}
const int MainWindow::speeddialmax = 32;
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util_proxy.h"
#include <map>
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
class FileUtilProxyTest : public testing::Test {
public:
FileUtilProxyTest()
: message_loop_(MessageLoop::TYPE_IO),
file_thread_("FileUtilProxyTestFileThread"),
error_(PLATFORM_FILE_OK),
created_(false),
file_(kInvalidPlatformFileValue),
bytes_written_(-1),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {}
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(dir_.CreateUniqueTempDir());
ASSERT_TRUE(file_thread_.Start());
}
virtual void TearDown() OVERRIDE {
if (file_ != kInvalidPlatformFileValue)
ClosePlatformFile(file_);
}
void DidFinish(PlatformFileError error) {
error_ = error;
MessageLoop::current()->Quit();
}
void DidCreateOrOpen(PlatformFileError error,
PassPlatformFile file,
bool created) {
error_ = error;
file_ = file.ReleaseValue();
created_ = created;
MessageLoop::current()->Quit();
}
void DidCreateTemporary(PlatformFileError error,
PassPlatformFile file,
const FilePath& path) {
error_ = error;
file_ = file.ReleaseValue();
path_ = path;
MessageLoop::current()->Quit();
}
void DidGetFileInfo(PlatformFileError error,
const PlatformFileInfo& file_info) {
error_ = error;
file_info_ = file_info;
MessageLoop::current()->Quit();
}
void DidRead(PlatformFileError error,
const char* data,
int bytes_read) {
error_ = error;
buffer_.resize(bytes_read);
memcpy(&buffer_[0], data, bytes_read);
MessageLoop::current()->Quit();
}
void DidWrite(PlatformFileError error,
int bytes_written) {
error_ = error;
bytes_written_ = bytes_written;
MessageLoop::current()->Quit();
}
protected:
PlatformFile GetTestPlatformFile(int flags) {
if (file_ != kInvalidPlatformFileValue)
return file_;
bool created;
PlatformFileError error;
file_ = CreatePlatformFile(test_path(), flags, &created, &error);
EXPECT_EQ(PLATFORM_FILE_OK, error);
EXPECT_NE(kInvalidPlatformFileValue, file_);
return file_;
}
TaskRunner* file_task_runner() const {
return file_thread_.message_loop_proxy().get();
}
const FilePath& test_dir_path() const { return dir_.path(); }
const FilePath test_path() const { return dir_.path().AppendASCII("test"); }
MessageLoop message_loop_;
Thread file_thread_;
ScopedTempDir dir_;
PlatformFileError error_;
bool created_;
PlatformFile file_;
FilePath path_;
PlatformFileInfo file_info_;
std::vector<char> buffer_;
int bytes_written_;
WeakPtrFactory<FileUtilProxyTest> weak_factory_;
};
TEST_F(FileUtilProxyTest, CreateOrOpen_Create) {
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_CREATE | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_TRUE(created_);
EXPECT_NE(kInvalidPlatformFileValue, file_);
EXPECT_TRUE(file_util::PathExists(test_path()));
}
TEST_F(FileUtilProxyTest, CreateOrOpen_Open) {
// Creates a file.
file_util::WriteFile(test_path(), NULL, 0);
ASSERT_TRUE(file_util::PathExists(test_path()));
// Opens the created file.
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_FALSE(created_);
EXPECT_NE(kInvalidPlatformFileValue, file_);
}
TEST_F(FileUtilProxyTest, CreateOrOpen_OpenNonExistent) {
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_ERROR_NOT_FOUND, error_);
EXPECT_FALSE(created_);
EXPECT_EQ(kInvalidPlatformFileValue, file_);
EXPECT_FALSE(file_util::PathExists(test_path()));
}
TEST_F(FileUtilProxyTest, Close) {
// Creates a file.
PlatformFile file = GetTestPlatformFile(
PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);
#if defined(OS_WIN)
// This fails on Windows if the file is not closed.
EXPECT_FALSE(file_util::Move(test_path(),
test_dir_path().AppendASCII("new")));
#endif
FileUtilProxy::Close(
file_task_runner(),
file,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
// Now it should pass on all platforms.
EXPECT_TRUE(file_util::Move(test_path(), test_dir_path().AppendASCII("new")));
}
TEST_F(FileUtilProxyTest, CreateTemporary) {
FileUtilProxy::CreateTemporary(
file_task_runner(), 0 /* additional_file_flags */,
Bind(&FileUtilProxyTest::DidCreateTemporary, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_TRUE(file_util::PathExists(path_));
EXPECT_NE(kInvalidPlatformFileValue, file_);
// The file should be writable.
#if defined(OS_WIN)
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
OVERLAPPED overlapped = {0};
overlapped.hEvent = hEvent;
DWORD bytes_written;
if (!::WriteFile(file_, "test", 4, &bytes_written, &overlapped)) {
// Temporary file is created with ASYNC flag, so WriteFile may return 0
// with ERROR_IO_PENDING.
EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
GetOverlappedResult(file_, &overlapped, &bytes_written, TRUE);
}
EXPECT_EQ(4, bytes_written);
#else
// On POSIX ASYNC flag does not affect synchronous read/write behavior.
EXPECT_EQ(4, WritePlatformFile(file_, 0, "test", 4));
#endif
EXPECT_TRUE(ClosePlatformFile(file_));
file_ = kInvalidPlatformFileValue;
// Make sure the written data can be read from the returned path.
std::string data;
EXPECT_TRUE(file_util::ReadFileToString(path_, &data));
EXPECT_EQ("test", data);
}
TEST_F(FileUtilProxyTest, GetFileInfo_File) {
// Setup.
ASSERT_EQ(4, file_util::WriteFile(test_path(), "test", 4));
PlatformFileInfo expected_info;
file_util::GetFileInfo(test_path(), &expected_info);
// Run.
FileUtilProxy::GetFileInfo(
file_task_runner(),
test_path(),
Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_info.size, file_info_.size);
EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}
TEST_F(FileUtilProxyTest, GetFileInfo_Directory) {
// Setup.
ASSERT_TRUE(file_util::CreateDirectory(test_path()));
PlatformFileInfo expected_info;
file_util::GetFileInfo(test_path(), &expected_info);
// Run.
FileUtilProxy::GetFileInfo(
file_task_runner(),
test_path(),
Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_info.size, file_info_.size);
EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}
TEST_F(FileUtilProxyTest, Read) {
// Setup.
const char expected_data[] = "bleh";
int expected_bytes = arraysize(expected_data);
ASSERT_EQ(expected_bytes,
file_util::WriteFile(test_path(), expected_data, expected_bytes));
// Run.
FileUtilProxy::Read(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_READ),
0, // offset
128,
Bind(&FileUtilProxyTest::DidRead, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_bytes, static_cast<int>(buffer_.size()));
for (size_t i = 0; i < buffer_.size(); ++i) {
EXPECT_EQ(expected_data[i], buffer_[i]);
}
}
TEST_F(FileUtilProxyTest, WriteAndFlush) {
const char data[] = "foo!";
int data_bytes = ARRAYSIZE_UNSAFE(data);
PlatformFile file = GetTestPlatformFile(
PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);
FileUtilProxy::Write(
file_task_runner(),
file,
0, // offset
data,
data_bytes,
Bind(&FileUtilProxyTest::DidWrite, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(data_bytes, bytes_written_);
// Flush the written data. (So that the following read should always
// succeed. On some platforms it may work with or without this flush.)
FileUtilProxy::Flush(
file_task_runner(),
file,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
// Verify the written data.
char buffer[10];
EXPECT_EQ(data_bytes, file_util::ReadFile(test_path(), buffer, data_bytes));
for (int i = 0; i < data_bytes; ++i) {
EXPECT_EQ(data[i], buffer[i]);
}
}
TEST_F(FileUtilProxyTest, Touch) {
Time last_accessed_time = Time::Now() - TimeDelta::FromDays(12345);
Time last_modified_time = Time::Now() - TimeDelta::FromHours(98765);
FileUtilProxy::Touch(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_CREATE |
PLATFORM_FILE_WRITE |
PLATFORM_FILE_WRITE_ATTRIBUTES),
last_accessed_time,
last_modified_time,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
// The returned values may only have the seconds precision, so we cast
// the double values to int here.
EXPECT_EQ(static_cast<int>(last_modified_time.ToDoubleT()),
static_cast<int>(info.last_modified.ToDoubleT()));
EXPECT_EQ(static_cast<int>(last_accessed_time.ToDoubleT()),
static_cast<int>(info.last_accessed.ToDoubleT()));
}
TEST_F(FileUtilProxyTest, Truncate_Shrink) {
// Setup.
const char kTestData[] = "0123456789";
ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(10, info.size);
// Run.
FileUtilProxy::Truncate(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
7,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(7, info.size);
char buffer[7];
EXPECT_EQ(7, file_util::ReadFile(test_path(), buffer, 7));
int i = 0;
for (; i < 7; ++i)
EXPECT_EQ(kTestData[i], buffer[i]);
}
TEST_F(FileUtilProxyTest, Truncate_Expand) {
// Setup.
const char kTestData[] = "9876543210";
ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(10, info.size);
// Run.
FileUtilProxy::Truncate(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
53,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(53, info.size);
char buffer[53];
EXPECT_EQ(53, file_util::ReadFile(test_path(), buffer, 53));
int i = 0;
for (; i < 10; ++i)
EXPECT_EQ(kTestData[i], buffer[i]);
for (; i < 53; ++i)
EXPECT_EQ(0, buffer[i]);
}
} // namespace base
<commit_msg>Fixed file leak in test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util_proxy.h"
#include <map>
#include "base/bind.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/platform_file.h"
#include "base/scoped_temp_dir.h"
#include "base/threading/thread.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
class FileUtilProxyTest : public testing::Test {
public:
FileUtilProxyTest()
: message_loop_(MessageLoop::TYPE_IO),
file_thread_("FileUtilProxyTestFileThread"),
error_(PLATFORM_FILE_OK),
created_(false),
file_(kInvalidPlatformFileValue),
bytes_written_(-1),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {}
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(dir_.CreateUniqueTempDir());
ASSERT_TRUE(file_thread_.Start());
}
virtual void TearDown() OVERRIDE {
if (file_ != kInvalidPlatformFileValue)
ClosePlatformFile(file_);
}
void DidFinish(PlatformFileError error) {
error_ = error;
MessageLoop::current()->Quit();
}
void DidCreateOrOpen(PlatformFileError error,
PassPlatformFile file,
bool created) {
error_ = error;
file_ = file.ReleaseValue();
created_ = created;
MessageLoop::current()->Quit();
}
void DidCreateTemporary(PlatformFileError error,
PassPlatformFile file,
const FilePath& path) {
error_ = error;
file_ = file.ReleaseValue();
path_ = path;
MessageLoop::current()->Quit();
}
void DidGetFileInfo(PlatformFileError error,
const PlatformFileInfo& file_info) {
error_ = error;
file_info_ = file_info;
MessageLoop::current()->Quit();
}
void DidRead(PlatformFileError error,
const char* data,
int bytes_read) {
error_ = error;
buffer_.resize(bytes_read);
memcpy(&buffer_[0], data, bytes_read);
MessageLoop::current()->Quit();
}
void DidWrite(PlatformFileError error,
int bytes_written) {
error_ = error;
bytes_written_ = bytes_written;
MessageLoop::current()->Quit();
}
protected:
PlatformFile GetTestPlatformFile(int flags) {
if (file_ != kInvalidPlatformFileValue)
return file_;
bool created;
PlatformFileError error;
file_ = CreatePlatformFile(test_path(), flags, &created, &error);
EXPECT_EQ(PLATFORM_FILE_OK, error);
EXPECT_NE(kInvalidPlatformFileValue, file_);
return file_;
}
TaskRunner* file_task_runner() const {
return file_thread_.message_loop_proxy().get();
}
const FilePath& test_dir_path() const { return dir_.path(); }
const FilePath test_path() const { return dir_.path().AppendASCII("test"); }
MessageLoop message_loop_;
Thread file_thread_;
ScopedTempDir dir_;
PlatformFileError error_;
bool created_;
PlatformFile file_;
FilePath path_;
PlatformFileInfo file_info_;
std::vector<char> buffer_;
int bytes_written_;
WeakPtrFactory<FileUtilProxyTest> weak_factory_;
};
TEST_F(FileUtilProxyTest, CreateOrOpen_Create) {
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_CREATE | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_TRUE(created_);
EXPECT_NE(kInvalidPlatformFileValue, file_);
EXPECT_TRUE(file_util::PathExists(test_path()));
}
TEST_F(FileUtilProxyTest, CreateOrOpen_Open) {
// Creates a file.
file_util::WriteFile(test_path(), NULL, 0);
ASSERT_TRUE(file_util::PathExists(test_path()));
// Opens the created file.
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_FALSE(created_);
EXPECT_NE(kInvalidPlatformFileValue, file_);
}
TEST_F(FileUtilProxyTest, CreateOrOpen_OpenNonExistent) {
FileUtilProxy::CreateOrOpen(
file_task_runner(),
test_path(),
PLATFORM_FILE_OPEN | PLATFORM_FILE_READ,
Bind(&FileUtilProxyTest::DidCreateOrOpen, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_ERROR_NOT_FOUND, error_);
EXPECT_FALSE(created_);
EXPECT_EQ(kInvalidPlatformFileValue, file_);
EXPECT_FALSE(file_util::PathExists(test_path()));
}
TEST_F(FileUtilProxyTest, Close) {
// Creates a file.
PlatformFile file = GetTestPlatformFile(
PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);
#if defined(OS_WIN)
// This fails on Windows if the file is not closed.
EXPECT_FALSE(file_util::Move(test_path(),
test_dir_path().AppendASCII("new")));
#endif
FileUtilProxy::Close(
file_task_runner(),
file,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
// Now it should pass on all platforms.
EXPECT_TRUE(file_util::Move(test_path(), test_dir_path().AppendASCII("new")));
}
TEST_F(FileUtilProxyTest, CreateTemporary) {
FileUtilProxy::CreateTemporary(
file_task_runner(), 0 /* additional_file_flags */,
Bind(&FileUtilProxyTest::DidCreateTemporary, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_TRUE(file_util::PathExists(path_));
EXPECT_NE(kInvalidPlatformFileValue, file_);
// The file should be writable.
#if defined(OS_WIN)
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
OVERLAPPED overlapped = {0};
overlapped.hEvent = hEvent;
DWORD bytes_written;
if (!::WriteFile(file_, "test", 4, &bytes_written, &overlapped)) {
// Temporary file is created with ASYNC flag, so WriteFile may return 0
// with ERROR_IO_PENDING.
EXPECT_EQ(ERROR_IO_PENDING, GetLastError());
GetOverlappedResult(file_, &overlapped, &bytes_written, TRUE);
}
EXPECT_EQ(4, bytes_written);
#else
// On POSIX ASYNC flag does not affect synchronous read/write behavior.
EXPECT_EQ(4, WritePlatformFile(file_, 0, "test", 4));
#endif
EXPECT_TRUE(ClosePlatformFile(file_));
file_ = kInvalidPlatformFileValue;
// Make sure the written data can be read from the returned path.
std::string data;
EXPECT_TRUE(file_util::ReadFileToString(path_, &data));
EXPECT_EQ("test", data);
// Make sure we can & do delete the created file to prevent leaks on the bots.
EXPECT_TRUE(file_util::Delete(path_, false));
}
TEST_F(FileUtilProxyTest, GetFileInfo_File) {
// Setup.
ASSERT_EQ(4, file_util::WriteFile(test_path(), "test", 4));
PlatformFileInfo expected_info;
file_util::GetFileInfo(test_path(), &expected_info);
// Run.
FileUtilProxy::GetFileInfo(
file_task_runner(),
test_path(),
Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_info.size, file_info_.size);
EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}
TEST_F(FileUtilProxyTest, GetFileInfo_Directory) {
// Setup.
ASSERT_TRUE(file_util::CreateDirectory(test_path()));
PlatformFileInfo expected_info;
file_util::GetFileInfo(test_path(), &expected_info);
// Run.
FileUtilProxy::GetFileInfo(
file_task_runner(),
test_path(),
Bind(&FileUtilProxyTest::DidGetFileInfo, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_info.size, file_info_.size);
EXPECT_EQ(expected_info.is_directory, file_info_.is_directory);
EXPECT_EQ(expected_info.is_symbolic_link, file_info_.is_symbolic_link);
EXPECT_EQ(expected_info.last_modified, file_info_.last_modified);
EXPECT_EQ(expected_info.last_accessed, file_info_.last_accessed);
EXPECT_EQ(expected_info.creation_time, file_info_.creation_time);
}
TEST_F(FileUtilProxyTest, Read) {
// Setup.
const char expected_data[] = "bleh";
int expected_bytes = arraysize(expected_data);
ASSERT_EQ(expected_bytes,
file_util::WriteFile(test_path(), expected_data, expected_bytes));
// Run.
FileUtilProxy::Read(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_READ),
0, // offset
128,
Bind(&FileUtilProxyTest::DidRead, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(expected_bytes, static_cast<int>(buffer_.size()));
for (size_t i = 0; i < buffer_.size(); ++i) {
EXPECT_EQ(expected_data[i], buffer_[i]);
}
}
TEST_F(FileUtilProxyTest, WriteAndFlush) {
const char data[] = "foo!";
int data_bytes = ARRAYSIZE_UNSAFE(data);
PlatformFile file = GetTestPlatformFile(
PLATFORM_FILE_CREATE | PLATFORM_FILE_WRITE);
FileUtilProxy::Write(
file_task_runner(),
file,
0, // offset
data,
data_bytes,
Bind(&FileUtilProxyTest::DidWrite, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
EXPECT_EQ(data_bytes, bytes_written_);
// Flush the written data. (So that the following read should always
// succeed. On some platforms it may work with or without this flush.)
FileUtilProxy::Flush(
file_task_runner(),
file,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
// Verify the written data.
char buffer[10];
EXPECT_EQ(data_bytes, file_util::ReadFile(test_path(), buffer, data_bytes));
for (int i = 0; i < data_bytes; ++i) {
EXPECT_EQ(data[i], buffer[i]);
}
}
TEST_F(FileUtilProxyTest, Touch) {
Time last_accessed_time = Time::Now() - TimeDelta::FromDays(12345);
Time last_modified_time = Time::Now() - TimeDelta::FromHours(98765);
FileUtilProxy::Touch(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_CREATE |
PLATFORM_FILE_WRITE |
PLATFORM_FILE_WRITE_ATTRIBUTES),
last_accessed_time,
last_modified_time,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
EXPECT_EQ(PLATFORM_FILE_OK, error_);
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
// The returned values may only have the seconds precision, so we cast
// the double values to int here.
EXPECT_EQ(static_cast<int>(last_modified_time.ToDoubleT()),
static_cast<int>(info.last_modified.ToDoubleT()));
EXPECT_EQ(static_cast<int>(last_accessed_time.ToDoubleT()),
static_cast<int>(info.last_accessed.ToDoubleT()));
}
TEST_F(FileUtilProxyTest, Truncate_Shrink) {
// Setup.
const char kTestData[] = "0123456789";
ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(10, info.size);
// Run.
FileUtilProxy::Truncate(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
7,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(7, info.size);
char buffer[7];
EXPECT_EQ(7, file_util::ReadFile(test_path(), buffer, 7));
int i = 0;
for (; i < 7; ++i)
EXPECT_EQ(kTestData[i], buffer[i]);
}
TEST_F(FileUtilProxyTest, Truncate_Expand) {
// Setup.
const char kTestData[] = "9876543210";
ASSERT_EQ(10, file_util::WriteFile(test_path(), kTestData, 10));
PlatformFileInfo info;
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(10, info.size);
// Run.
FileUtilProxy::Truncate(
file_task_runner(),
GetTestPlatformFile(PLATFORM_FILE_OPEN | PLATFORM_FILE_WRITE),
53,
Bind(&FileUtilProxyTest::DidFinish, weak_factory_.GetWeakPtr()));
MessageLoop::current()->Run();
// Verify.
file_util::GetFileInfo(test_path(), &info);
ASSERT_EQ(53, info.size);
char buffer[53];
EXPECT_EQ(53, file_util::ReadFile(test_path(), buffer, 53));
int i = 0;
for (; i < 10; ++i)
EXPECT_EQ(kTestData[i], buffer[i]);
for (; i < 53; ++i)
EXPECT_EQ(0, buffer[i]);
}
} // namespace base
<|endoftext|> |
<commit_before>/*
* Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
*
* Original file:
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SM_ID_HPP
#define SM_ID_HPP
#include <boost/cstdint.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif
#include <boost/serialization/nvp.hpp>
namespace sm {
typedef boost::uint64_t id_type;
///
/// \class Id
/// \brief superclass for stronly-typed uint64 ids
///
/// Usage:
/// \code
/// // MyId is a stronly typed Id for my object.
/// class MyId : public Id
/// {
/// public:
///
/// explicit MyId (id_type id = -1) : Id(id) {}
///
/// template<class Archive>
/// void serialize(Archive & ar, const unsigned int version)
/// {
/// ar & id_;
/// }
/// };
/// \endcode
///
class Id
{
public:
explicit Id (id_type id) : _id(id) {}
/// Only for stl use
Id () : _id(-1) {}
friend std::ostream& operator<< (std::ostream& str, const Id& n)
{
str << n._id;
return str;
}
bool operator== (const Id& other) const
{
return other._id == _id;
}
bool operator!= (const Id& other) const
{
return other._id != _id;
}
bool operator< (const Id& other) const
{
return _id < other._id;
}
bool operator> (const Id& other) const
{
return _id > other._id;
}
bool operator<=(const Id& other) const
{
return _id <= other._id;
}
bool operator>=(const Id& other) const
{
return _id >= other._id;
}
id_type getId () const
{
return _id;
}
// postincrement.
Id operator++ (int unused)
{
Id rval(_id);
++_id;
return rval;
}
// preincrement
Id & operator++ ()
{
++_id;
return (*this);
}
Id& operator= (const Id& other)
{
_id = other._id;
return *this;
}
bool isSet() const
{
return _id != id_type(-1);
}
id_type value() const
{
return _id;
}
void clear()
{
_id = -1;
}
void swap( Id & rhs)
{
std::swap(_id,rhs._id);
}
void setRandom()
{
_id = rand();
}
bool isBinaryEqual(const Id & rhs)
{
return _id == rhs._id;
}
protected:
id_type _id;
};
} // namespace aslam
#define SM_DEFINE_ID(IdTypeName) \
class IdTypeName : public sm::Id \
{ \
public: \
explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {} \
IdTypeName(const sm::Id & id) : sm::Id(id){} \
template<class Archive> \
void serialize(Archive & ar, const unsigned int version) \
{ \
ar & BOOST_SERIALIZATION_NVP(_id); \
} \
};
#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
} \
namespace boost { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) const \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace boost
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { namespace tr1 { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
}} \
namespace boost { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
boost::hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) const \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace boost
#endif
#endif /* SM_ID_HPP */
<commit_msg>added "const" specifier in Id.hpp<commit_after>/*
* Adapted from the Willow Garage pose_graph package by Paul Furgale on October 22, 2010.
*
* Original file:
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SM_ID_HPP
#define SM_ID_HPP
#include <boost/cstdint.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
// The definition of std::tr1::hash
#ifdef _WIN32
#include <functional>
#else
#include <tr1/functional>
#endif
#include <boost/serialization/nvp.hpp>
namespace sm {
typedef boost::uint64_t id_type;
///
/// \class Id
/// \brief superclass for stronly-typed uint64 ids
///
/// Usage:
/// \code
/// // MyId is a stronly typed Id for my object.
/// class MyId : public Id
/// {
/// public:
///
/// explicit MyId (id_type id = -1) : Id(id) {}
///
/// template<class Archive>
/// void serialize(Archive & ar, const unsigned int version)
/// {
/// ar & id_;
/// }
/// };
/// \endcode
///
class Id
{
public:
explicit Id (id_type id) : _id(id) {}
/// Only for stl use
Id () : _id(-1) {}
friend std::ostream& operator<< (std::ostream& str, const Id& n)
{
str << n._id;
return str;
}
bool operator== (const Id& other) const
{
return other._id == _id;
}
bool operator!= (const Id& other) const
{
return other._id != _id;
}
bool operator< (const Id& other) const
{
return _id < other._id;
}
bool operator> (const Id& other) const
{
return _id > other._id;
}
bool operator<=(const Id& other) const
{
return _id <= other._id;
}
bool operator>=(const Id& other) const
{
return _id >= other._id;
}
id_type getId () const
{
return _id;
}
// postincrement.
Id operator++ (int unused)
{
Id rval(_id);
++_id;
return rval;
}
// preincrement
Id & operator++ ()
{
++_id;
return (*this);
}
Id& operator= (const Id& other)
{
_id = other._id;
return *this;
}
bool isSet() const
{
return _id != id_type(-1);
}
id_type value() const
{
return _id;
}
void clear()
{
_id = -1;
}
void swap( Id & rhs)
{
std::swap(_id,rhs._id);
}
void setRandom()
{
_id = rand();
}
bool isBinaryEqual(const Id & rhs)
{
return _id == rhs._id;
}
protected:
id_type _id;
};
} // namespace aslam
#define SM_DEFINE_ID(IdTypeName) \
class IdTypeName : public sm::Id \
{ \
public: \
explicit IdTypeName (sm::id_type id = -1) : sm::Id(id) {} \
IdTypeName(const sm::Id & id) : sm::Id(id){} \
template<class Archive> \
void serialize(Archive & ar, const unsigned int version) \
{ \
ar & BOOST_SERIALIZATION_NVP(_id); \
} \
};
#ifdef _WIN32
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) \
{ \
return _hash(id.getId()); \
} \
}; \
} \
namespace boost { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) const \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace boost
#else
// If you need to use the ID in a tr1 hashing container,
// use this macro outside of any namespace:
// SM_DEFINE_ID_HASH(my_namespace::myIdType);
#define SM_DEFINE_ID_HASH(FullyQualifiedIdTypeName) \
namespace std { namespace tr1 { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) const \
{ \
return _hash(id.getId()); \
} \
}; \
}} \
namespace boost { \
template<> \
struct hash<FullyQualifiedIdTypeName> \
{ \
boost::hash<boost::uint64_t> _hash; \
size_t operator()(const FullyQualifiedIdTypeName & id) const \
{ \
return _hash(id.getId()); \
} \
}; \
} // namespace boost
#endif
#endif /* SM_ID_HPP */
<|endoftext|> |
<commit_before>// Author: Enrico Guiraud, Danilo Piparo CERN 09/2017
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RDATASOURCE
#define ROOT_RDATASOURCE
#include "ROOT/RStringView.hxx"
#include "RtypesCore.h" // ULong64_t
#include <algorithm> // std::transform
#include <vector>
#include <typeinfo>
namespace ROOT {
namespace RDF {
class RDataSource;
}
}
/// Print a RDataSource at the prompt
namespace cling {
std::string printValue(ROOT::RDF::RDataSource *ds);
} // namespace cling
namespace ROOT {
namespace Internal {
namespace TDS {
/// Mother class of TTypedPointerHolder. The instances
/// of this class can be put in a container. Upon destruction,
/// the correct deletion of the pointer is performed in the
/// derived class.
class TPointerHolder {
protected:
void *fPointer{nullptr};
public:
TPointerHolder(void *ptr) : fPointer(ptr) {}
void *GetPointer() { return fPointer; }
void *GetPointerAddr() { return &fPointer; }
virtual TPointerHolder *GetDeepCopy() = 0;
virtual ~TPointerHolder(){};
};
/// Class to wrap a pointer and delete the memory associated to it
/// correctly
template <typename T>
class TTypedPointerHolder final : public TPointerHolder {
public:
TTypedPointerHolder(T *ptr) : TPointerHolder((void *)ptr) {}
virtual TPointerHolder *GetDeepCopy()
{
const auto typedPtr = static_cast<T *>(fPointer);
return new TTypedPointerHolder(new T(*typedPtr));
}
~TTypedPointerHolder() { delete static_cast<T *>(fPointer); }
};
} // ns TDS
} // ns Internal
namespace RDF {
// clang-format off
/**
\class ROOT::RDF::RDataSource
\ingroup dataframe
\brief RDataSource defines an API that RDataFrame can use to read arbitrary data formats.
A concrete RDataSource implementation (i.e. a class that inherits from RDataSource and implements all of its pure
methods) provides an adaptor that RDataFrame can leverage to read any kind of tabular data formats.
RDataFrame calls into RDataSource to retrieve information about the data, retrieve (thread-local) readers or "cursors"
for selected columns and to advance the readers to the desired data entry.
The sequence of calls that RDataFrame (or any other client of a RDataSource) performs is the following:
- SetNSlots() : inform RDataSource of the desired level of parallelism
- GetColumnReaders() : retrieve from RDataSource per-thread readers for the desired columns
- Initialise() : inform RDataSource that an event-loop is about to start
- GetEntryRanges() : retrieve from RDataSource a set of ranges of entries that can be processed concurrently
- InitSlot() : inform RDataSource that a certain thread is about to start working on a certain range of entries
- SetEntry() : inform RDataSource that a certain thread is about to start working on a certain entry
- FinaliseSlot() : inform RDataSource that a certain thread finished working on a certain range of entries
- Finalise() : inform RDataSource that an event-loop finished
RDataSource implementations must support running multiple event-loops consecutively (although sequentially) on the same dataset.
- \b SetNSlots() is called once per RDataSource object, typically when it is associated to a RDataFrame.
- \b GetColumnReaders() can be called several times, potentially with the same arguments, also in-between event-loops, but not during an event-loop.
- \b Initialise() and \b Finalise() are called once per event-loop, right before starting and right after finishing.
- \b InitSlot(), \b SetEntry(), and \b FinaliseSlot() can be called concurrently from multiple threads, multiple times per event-loop.
*/
class RDataSource {
// clang-format on
protected:
using Record_t = std::vector<void *>;
friend std::string cling::printValue(::ROOT::RDF::RDataSource *);
virtual std::string AsString() {return "generic data source";};
public:
virtual ~RDataSource() = default;
// clang-format off
/// \brief Inform RDataSource of the number of processing slots (i.e. worker threads) used by the associated RDataFrame.
/// Slots numbers are used to simplify parallel execution: RDataFrame guarantees that different threads will always
/// pass different slot values when calling methods concurrently.
// clang-format on
virtual void SetNSlots(unsigned int nSlots) = 0;
// clang-format off
/// \brief Returns a reference to the collection of the dataset's column names
// clang-format on
virtual const std::vector<std::string> &GetColumnNames() const = 0;
/// \brief Checks if the dataset has a certain column
/// \param[in] columnName The name of the column
virtual bool HasColumn(std::string_view) const = 0;
// clang-format off
/// \brief Type of a column as a string, e.g. `GetTypeName("x") == "double"`. Required for jitting e.g. `df.Filter("x>0")`.
/// \param[in] columnName The name of the column
// clang-format on
virtual std::string GetTypeName(std::string_view) const = 0;
// clang-format off
/// Called at most once per column by RDF. Return vector of pointers to pointers to column values - one per slot.
/// \tparam T The type of the data stored in the column
/// \param[in] columnName The name of the column
///
/// These pointers are veritable cursors: it's a responsibility of the RDataSource implementation that they point to
/// the "right" memory region.
// clang-format on
template <typename T>
std::vector<T **> GetColumnReaders(std::string_view columnName)
{
auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));
std::vector<T **> typedVec(typeErasedVec.size());
std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),
[](void *p) { return static_cast<T **>(p); });
return typedVec;
}
// clang-format off
/// \brief Return ranges of entries to distribute to tasks.
/// They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the
/// intervals must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.
// clang-format on
virtual std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges() = 0;
// clang-format off
/// \brief Advance the "cursors" returned by GetColumnReaders to the selected entry for a particular slot.
/// \param[in] slot The data processing slot that needs to be considered
/// \param[in] entry The entry which needs to be pointed to by the reader pointers
/// Slots are adopted to accommodate parallel data processing.
/// Different workers will loop over different ranges and
/// will be labelled by different "slot" values.
/// Returns *true* if the entry has to be processed, *false* otherwise.
// clang-format on
virtual bool SetEntry(unsigned int slot, ULong64_t entry) = 0;
// clang-format off
/// \brief Convenience method called before starting an event-loop.
/// This method might be called multiple times over the lifetime of a RDataSource, since
/// users can run multiple event-loops with the same RDataFrame.
/// Ideally, `Initialise` should set the state of the RDataSource so that multiple identical event-loops
/// will produce identical results.
// clang-format on
virtual void Initialise() {}
// clang-format off
/// \brief Convenience method called at the start of the data processing associated to a slot.
/// \param[in] slot The data processing slot wihch needs to be initialised
/// \param[in] firstEntry The first entry of the range that the task will process.
/// This method might be called multiple times per thread per event-loop.
// clang-format on
virtual void InitSlot(unsigned int /*slot*/, ULong64_t /*firstEntry*/) {}
// clang-format off
/// \brief Convenience method called at the end of the data processing associated to a slot.
/// \param[in] slot The data processing slot wihch needs to be finalised
/// This method might be called multiple times per thread per event-loop.
// clang-format on
virtual void FinaliseSlot(unsigned int /*slot*/) {}
// clang-format off
/// \brief Convenience method called after concluding an event-loop.
/// See Initialise for more details.
// clang-format on
virtual void Finalise() {}
protected:
/// type-erased vector of pointers to pointers to column values - one per slot
virtual Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;
};
} // ns RDF
} // ns ROOT
/// Print a RDataSource at the prompt
namespace cling {
inline std::string printValue(ROOT::RDF::RDataSource *ds) {
return ds->AsString();
}
} // namespace cling
#endif // ROOT_TDATASOURCE
<commit_msg>[RDF] Fix build on osx making the string include explicit<commit_after>// Author: Enrico Guiraud, Danilo Piparo CERN 09/2017
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RDATASOURCE
#define ROOT_RDATASOURCE
#include "ROOT/RStringView.hxx"
#include "RtypesCore.h" // ULong64_t
#include <algorithm> // std::transform
#include <string>
#include <vector>
#include <typeinfo>
namespace ROOT {
namespace RDF {
class RDataSource;
}
}
/// Print a RDataSource at the prompt
namespace cling {
std::string printValue(ROOT::RDF::RDataSource *ds);
} // namespace cling
namespace ROOT {
namespace Internal {
namespace TDS {
/// Mother class of TTypedPointerHolder. The instances
/// of this class can be put in a container. Upon destruction,
/// the correct deletion of the pointer is performed in the
/// derived class.
class TPointerHolder {
protected:
void *fPointer{nullptr};
public:
TPointerHolder(void *ptr) : fPointer(ptr) {}
void *GetPointer() { return fPointer; }
void *GetPointerAddr() { return &fPointer; }
virtual TPointerHolder *GetDeepCopy() = 0;
virtual ~TPointerHolder(){};
};
/// Class to wrap a pointer and delete the memory associated to it
/// correctly
template <typename T>
class TTypedPointerHolder final : public TPointerHolder {
public:
TTypedPointerHolder(T *ptr) : TPointerHolder((void *)ptr) {}
virtual TPointerHolder *GetDeepCopy()
{
const auto typedPtr = static_cast<T *>(fPointer);
return new TTypedPointerHolder(new T(*typedPtr));
}
~TTypedPointerHolder() { delete static_cast<T *>(fPointer); }
};
} // ns TDS
} // ns Internal
namespace RDF {
// clang-format off
/**
\class ROOT::RDF::RDataSource
\ingroup dataframe
\brief RDataSource defines an API that RDataFrame can use to read arbitrary data formats.
A concrete RDataSource implementation (i.e. a class that inherits from RDataSource and implements all of its pure
methods) provides an adaptor that RDataFrame can leverage to read any kind of tabular data formats.
RDataFrame calls into RDataSource to retrieve information about the data, retrieve (thread-local) readers or "cursors"
for selected columns and to advance the readers to the desired data entry.
The sequence of calls that RDataFrame (or any other client of a RDataSource) performs is the following:
- SetNSlots() : inform RDataSource of the desired level of parallelism
- GetColumnReaders() : retrieve from RDataSource per-thread readers for the desired columns
- Initialise() : inform RDataSource that an event-loop is about to start
- GetEntryRanges() : retrieve from RDataSource a set of ranges of entries that can be processed concurrently
- InitSlot() : inform RDataSource that a certain thread is about to start working on a certain range of entries
- SetEntry() : inform RDataSource that a certain thread is about to start working on a certain entry
- FinaliseSlot() : inform RDataSource that a certain thread finished working on a certain range of entries
- Finalise() : inform RDataSource that an event-loop finished
RDataSource implementations must support running multiple event-loops consecutively (although sequentially) on the same dataset.
- \b SetNSlots() is called once per RDataSource object, typically when it is associated to a RDataFrame.
- \b GetColumnReaders() can be called several times, potentially with the same arguments, also in-between event-loops, but not during an event-loop.
- \b Initialise() and \b Finalise() are called once per event-loop, right before starting and right after finishing.
- \b InitSlot(), \b SetEntry(), and \b FinaliseSlot() can be called concurrently from multiple threads, multiple times per event-loop.
*/
class RDataSource {
// clang-format on
protected:
using Record_t = std::vector<void *>;
friend std::string cling::printValue(::ROOT::RDF::RDataSource *);
virtual std::string AsString() {return "generic data source";};
public:
virtual ~RDataSource() = default;
// clang-format off
/// \brief Inform RDataSource of the number of processing slots (i.e. worker threads) used by the associated RDataFrame.
/// Slots numbers are used to simplify parallel execution: RDataFrame guarantees that different threads will always
/// pass different slot values when calling methods concurrently.
// clang-format on
virtual void SetNSlots(unsigned int nSlots) = 0;
// clang-format off
/// \brief Returns a reference to the collection of the dataset's column names
// clang-format on
virtual const std::vector<std::string> &GetColumnNames() const = 0;
/// \brief Checks if the dataset has a certain column
/// \param[in] columnName The name of the column
virtual bool HasColumn(std::string_view) const = 0;
// clang-format off
/// \brief Type of a column as a string, e.g. `GetTypeName("x") == "double"`. Required for jitting e.g. `df.Filter("x>0")`.
/// \param[in] columnName The name of the column
// clang-format on
virtual std::string GetTypeName(std::string_view) const = 0;
// clang-format off
/// Called at most once per column by RDF. Return vector of pointers to pointers to column values - one per slot.
/// \tparam T The type of the data stored in the column
/// \param[in] columnName The name of the column
///
/// These pointers are veritable cursors: it's a responsibility of the RDataSource implementation that they point to
/// the "right" memory region.
// clang-format on
template <typename T>
std::vector<T **> GetColumnReaders(std::string_view columnName)
{
auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));
std::vector<T **> typedVec(typeErasedVec.size());
std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),
[](void *p) { return static_cast<T **>(p); });
return typedVec;
}
// clang-format off
/// \brief Return ranges of entries to distribute to tasks.
/// They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the
/// intervals must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.
// clang-format on
virtual std::vector<std::pair<ULong64_t, ULong64_t>> GetEntryRanges() = 0;
// clang-format off
/// \brief Advance the "cursors" returned by GetColumnReaders to the selected entry for a particular slot.
/// \param[in] slot The data processing slot that needs to be considered
/// \param[in] entry The entry which needs to be pointed to by the reader pointers
/// Slots are adopted to accommodate parallel data processing.
/// Different workers will loop over different ranges and
/// will be labelled by different "slot" values.
/// Returns *true* if the entry has to be processed, *false* otherwise.
// clang-format on
virtual bool SetEntry(unsigned int slot, ULong64_t entry) = 0;
// clang-format off
/// \brief Convenience method called before starting an event-loop.
/// This method might be called multiple times over the lifetime of a RDataSource, since
/// users can run multiple event-loops with the same RDataFrame.
/// Ideally, `Initialise` should set the state of the RDataSource so that multiple identical event-loops
/// will produce identical results.
// clang-format on
virtual void Initialise() {}
// clang-format off
/// \brief Convenience method called at the start of the data processing associated to a slot.
/// \param[in] slot The data processing slot wihch needs to be initialised
/// \param[in] firstEntry The first entry of the range that the task will process.
/// This method might be called multiple times per thread per event-loop.
// clang-format on
virtual void InitSlot(unsigned int /*slot*/, ULong64_t /*firstEntry*/) {}
// clang-format off
/// \brief Convenience method called at the end of the data processing associated to a slot.
/// \param[in] slot The data processing slot wihch needs to be finalised
/// This method might be called multiple times per thread per event-loop.
// clang-format on
virtual void FinaliseSlot(unsigned int /*slot*/) {}
// clang-format off
/// \brief Convenience method called after concluding an event-loop.
/// See Initialise for more details.
// clang-format on
virtual void Finalise() {}
protected:
/// type-erased vector of pointers to pointers to column values - one per slot
virtual Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;
};
} // ns RDF
} // ns ROOT
/// Print a RDataSource at the prompt
namespace cling {
inline std::string printValue(ROOT::RDF::RDataSource *ds) {
return ds->AsString();
}
} // namespace cling
#endif // ROOT_TDATASOURCE
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "rdostudioframeview.h"
#include "rdostudioframedoc.h"
#include "rdostudiomodel.h"
#include "rdostudioapp.h"
#include "rdostudiomainfrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ----------------------------------------------------------------------------
// ---------- RDOStudioFrameView
// ----------------------------------------------------------------------------
IMPLEMENT_DYNCREATE(RDOStudioFrameView, CView)
BEGIN_MESSAGE_MAP(RDOStudioFrameView, CView)
//{{AFX_MSG_MAP(RDOStudioFrameView)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_SETFOCUS()
ON_WM_SIZE()
ON_WM_HSCROLL()
ON_WM_VSCROLL()
//}}AFX_MSG_MAP
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
RDOStudioFrameView::RDOStudioFrameView():
CView(),
frameBmpRect( 0, 0, 0, 0 ),
newClientRect( 0, 0, 0, 0 ),
xPos( 0 ),
yPos( 0 ),
bgColor( studioApp.mainFrame->style_frame.theme->backgroundColor ),
mustBeInit( true )
{
dc.CreateCompatibleDC( NULL );
}
RDOStudioFrameView::~RDOStudioFrameView()
{
}
BOOL RDOStudioFrameView::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CView::PreCreateWindow( cs ) ) return FALSE;
cs.style &= ~WS_BORDER;
cs.style |= WS_HSCROLL | WS_VSCROLL;
cs.lpszClass = AfxRegisterWndClass( 0, ::LoadCursor(NULL, IDC_ARROW) );
return TRUE;
}
int RDOStudioFrameView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if ( CView::OnCreate(lpCreateStruct) == -1 ) return -1;
updateScrollBars();
return 0;
}
void RDOStudioFrameView::OnDraw(CDC* pDC)
{
// RDOStudioFrameDoc* pDoc = GetDocument();
// ASSERT_VALID(pDoc);
int index = model->frameManager.findFrameIndex( this );
CSingleLock lock_draw( model->frameManager.getFrameDraw( index ) );
lock_draw.Lock();
GetClientRect( &newClientRect );
CBitmap* pOldBitmap = dc.SelectObject( &frameBmp );
/*
pDC->SetStretchBltMode( HALFTONE );
double k1 = (double)newClientRect.bottom / frameBmpRect.bottom;
double k2 = (double)newClientRect.right / frameBmpRect.right;
double k = min( k1, k2 );
if ( k > 1 ) k = 1;
CRect rect( 0, 0, frameBmpRect.right * k, frameBmpRect.bottom * k );
rect.OffsetRect( (newClientRect.right - rect.right) / 2, (newClientRect.bottom - rect.bottom) / 2 );
pDC->StretchBlt( rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, &dc, 0, 0, frameBmpRect.right, frameBmpRect.bottom, SRCCOPY );
if ( rect.left ) {
pDC->FillSolidRect( 0, 0, rect.left, newClientRect.bottom, bgColor );
pDC->FillSolidRect( rect.right, 0, newClientRect.right, newClientRect.bottom, bgColor );
}
if ( rect.top ) {
pDC->FillSolidRect( 0, 0, newClientRect.right, rect.top, bgColor );
pDC->FillSolidRect( 0, rect.bottom, newClientRect.right, newClientRect.bottom, bgColor );
}
*/
pDC->BitBlt( 0, 0, newClientRect.right, newClientRect.bottom, &dc, xPos, yPos, SRCCOPY );
if ( newClientRect.right - frameBmpRect.right > 0 ) {
pDC->FillSolidRect( frameBmpRect.right, 0, newClientRect.right - frameBmpRect.right, newClientRect.bottom, bgColor );
}
if ( newClientRect.bottom - frameBmpRect.bottom > 0 ) {
pDC->FillSolidRect( 0, frameBmpRect.bottom, newClientRect.right, newClientRect.bottom - frameBmpRect.bottom, bgColor );
}
dc.SelectObject( pOldBitmap );
lock_draw.Unlock();
model->frameManager.getFrameTimer( index )->SetEvent();
}
BOOL RDOStudioFrameView::OnPreparePrinting(CPrintInfo* pInfo)
{
return DoPreparePrinting(pInfo);
}
void RDOStudioFrameView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
void RDOStudioFrameView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
#ifdef _DEBUG
void RDOStudioFrameView::AssertValid() const
{
CView::AssertValid();
}
void RDOStudioFrameView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
RDOStudioFrameDoc* RDOStudioFrameView::GetDocument()
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(RDOStudioFrameDoc)));
return (RDOStudioFrameDoc*)m_pDocument;
}
#endif
void RDOStudioFrameView::OnDestroy()
{
model->frameManager.getFrameClose( model->frameManager.findFrameIndex( this ) )->SetEvent();
model->frameManager.disconnectFrameDoc( GetDocument() );
CView::OnDestroy();
}
void RDOStudioFrameView::OnSetFocus(CWnd* pOldWnd)
{
CView::OnSetFocus( pOldWnd );
model->frameManager.setLastShowedFrame( model->frameManager.findFrameIndex( this ) );
}
void RDOStudioFrameView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
GetClientRect( &newClientRect );
updateScrollBars();
}
void RDOStudioFrameView::updateScrollBars()
{
SCROLLINFO si;
si.cbSize = sizeof( si );
si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
if ( xPos > frameBmpRect.right - newClientRect.right ) xPos = frameBmpRect.right - newClientRect.right;
if ( xPos < 0 ) xPos = 0;
si.nMin = 0;
si.nMax = frameBmpRect.right;
si.nPos = xPos;
si.nPage = newClientRect.right;
SetScrollInfo( SB_HORZ, &si, TRUE );
if ( yPos > frameBmpRect.bottom - newClientRect.bottom ) yPos = frameBmpRect.bottom - newClientRect.bottom;
if ( yPos < 0 ) yPos = 0;
si.nMin = 0;
si.nMax = frameBmpRect.bottom;
si.nPos = yPos;
si.nPage = newClientRect.bottom;
SetScrollInfo( SB_VERT, &si, TRUE );
}
void RDOStudioFrameView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize = sizeof( si );
switch( nSBCode ) {
case SB_PAGEUP:
GetScrollInfo( SB_HORZ, &si, SIF_PAGE );
xPos -= si.nPage;
break;
case SB_PAGEDOWN:
GetScrollInfo( SB_HORZ, &si, SIF_PAGE );
xPos += si.nPage;
break;
case SB_LINEUP:
xPos--;
break;
case SB_LINEDOWN:
xPos++;
break;
case SB_THUMBTRACK: {
GetScrollInfo( SB_HORZ, &si, SIF_TRACKPOS );
xPos += si.nTrackPos - xPos;
break;
}
}
if ( xPos > frameBmpRect.right - newClientRect.right ) xPos = frameBmpRect.right - newClientRect.right;
if ( xPos < 0 ) xPos = 0;
si.fMask = SIF_POS;
si.nPos = xPos;
SetScrollInfo( SB_HORZ, &si, TRUE );
InvalidateRect( NULL );
UpdateWindow();
}
void RDOStudioFrameView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize = sizeof( si );
switch( nSBCode ) {
case SB_PAGEUP:
GetScrollInfo( SB_VERT, &si, SIF_PAGE );
yPos -= si.nPage;
break;
case SB_PAGEDOWN:
GetScrollInfo( SB_VERT, &si, SIF_PAGE );
yPos += si.nPage;
break;
case SB_LINEUP:
yPos--;
break;
case SB_LINEDOWN:
yPos++;
break;
case SB_THUMBTRACK: {
GetScrollInfo( SB_VERT, &si, SIF_TRACKPOS );
yPos += si.nTrackPos - yPos;
break;
}
}
if ( yPos > frameBmpRect.bottom - newClientRect.bottom ) yPos = frameBmpRect.bottom - newClientRect.bottom;
if ( yPos < 0 ) yPos = 0;
si.fMask = SIF_POS;
si.nPos = yPos;
SetScrollInfo( SB_VERT, &si, TRUE );
InvalidateRect( NULL );
UpdateWindow();
}
<commit_msg>don't draw not inited bmp<commit_after>#include "stdafx.h"
#include "rdostudioframeview.h"
#include "rdostudioframedoc.h"
#include "rdostudiomodel.h"
#include "rdostudioapp.h"
#include "rdostudiomainfrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// ----------------------------------------------------------------------------
// ---------- RDOStudioFrameView
// ----------------------------------------------------------------------------
IMPLEMENT_DYNCREATE(RDOStudioFrameView, CView)
BEGIN_MESSAGE_MAP(RDOStudioFrameView, CView)
//{{AFX_MSG_MAP(RDOStudioFrameView)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_WM_SETFOCUS()
ON_WM_SIZE()
ON_WM_HSCROLL()
ON_WM_VSCROLL()
//}}AFX_MSG_MAP
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
RDOStudioFrameView::RDOStudioFrameView():
CView(),
frameBmpRect( 0, 0, 0, 0 ),
newClientRect( 0, 0, 0, 0 ),
xPos( 0 ),
yPos( 0 ),
bgColor( studioApp.mainFrame->style_frame.theme->backgroundColor ),
mustBeInit( true )
{
dc.CreateCompatibleDC( NULL );
}
RDOStudioFrameView::~RDOStudioFrameView()
{
}
BOOL RDOStudioFrameView::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CView::PreCreateWindow( cs ) ) return FALSE;
cs.style &= ~WS_BORDER;
cs.style |= WS_HSCROLL | WS_VSCROLL;
cs.lpszClass = AfxRegisterWndClass( 0, ::LoadCursor(NULL, IDC_ARROW) );
return TRUE;
}
int RDOStudioFrameView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if ( CView::OnCreate(lpCreateStruct) == -1 ) return -1;
updateScrollBars();
return 0;
}
void RDOStudioFrameView::OnDraw(CDC* pDC)
{
// RDOStudioFrameDoc* pDoc = GetDocument();
// ASSERT_VALID(pDoc);
int index = model->frameManager.findFrameIndex( this );
CSingleLock lock_draw( model->frameManager.getFrameDraw( index ) );
lock_draw.Lock();
GetClientRect( &newClientRect );
if ( !mustBeInit ) {
CBitmap* pOldBitmap = dc.SelectObject( &frameBmp );
/*
pDC->SetStretchBltMode( HALFTONE );
double k1 = (double)newClientRect.bottom / frameBmpRect.bottom;
double k2 = (double)newClientRect.right / frameBmpRect.right;
double k = min( k1, k2 );
if ( k > 1 ) k = 1;
CRect rect( 0, 0, frameBmpRect.right * k, frameBmpRect.bottom * k );
rect.OffsetRect( (newClientRect.right - rect.right) / 2, (newClientRect.bottom - rect.bottom) / 2 );
pDC->StretchBlt( rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, &dc, 0, 0, frameBmpRect.right, frameBmpRect.bottom, SRCCOPY );
if ( rect.left ) {
pDC->FillSolidRect( 0, 0, rect.left, newClientRect.bottom, bgColor );
pDC->FillSolidRect( rect.right, 0, newClientRect.right, newClientRect.bottom, bgColor );
}
if ( rect.top ) {
pDC->FillSolidRect( 0, 0, newClientRect.right, rect.top, bgColor );
pDC->FillSolidRect( 0, rect.bottom, newClientRect.right, newClientRect.bottom, bgColor );
}
*/
pDC->BitBlt( 0, 0, newClientRect.right, newClientRect.bottom, &dc, xPos, yPos, SRCCOPY );
dc.SelectObject( pOldBitmap );
}
if ( newClientRect.right - frameBmpRect.right > 0 ) {
pDC->FillSolidRect( frameBmpRect.right, 0, newClientRect.right - frameBmpRect.right, newClientRect.bottom, bgColor );
}
if ( newClientRect.bottom - frameBmpRect.bottom > 0 ) {
pDC->FillSolidRect( 0, frameBmpRect.bottom, newClientRect.right, newClientRect.bottom - frameBmpRect.bottom, bgColor );
}
lock_draw.Unlock();
model->frameManager.getFrameTimer( index )->SetEvent();
}
BOOL RDOStudioFrameView::OnPreparePrinting(CPrintInfo* pInfo)
{
return DoPreparePrinting(pInfo);
}
void RDOStudioFrameView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
void RDOStudioFrameView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
}
#ifdef _DEBUG
void RDOStudioFrameView::AssertValid() const
{
CView::AssertValid();
}
void RDOStudioFrameView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
RDOStudioFrameDoc* RDOStudioFrameView::GetDocument()
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(RDOStudioFrameDoc)));
return (RDOStudioFrameDoc*)m_pDocument;
}
#endif
void RDOStudioFrameView::OnDestroy()
{
model->frameManager.getFrameClose( model->frameManager.findFrameIndex( this ) )->SetEvent();
model->frameManager.disconnectFrameDoc( GetDocument() );
CView::OnDestroy();
}
void RDOStudioFrameView::OnSetFocus(CWnd* pOldWnd)
{
CView::OnSetFocus( pOldWnd );
model->frameManager.setLastShowedFrame( model->frameManager.findFrameIndex( this ) );
}
void RDOStudioFrameView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
GetClientRect( &newClientRect );
updateScrollBars();
}
void RDOStudioFrameView::updateScrollBars()
{
SCROLLINFO si;
si.cbSize = sizeof( si );
si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
if ( xPos > frameBmpRect.right - newClientRect.right ) xPos = frameBmpRect.right - newClientRect.right;
if ( xPos < 0 ) xPos = 0;
si.nMin = 0;
si.nMax = frameBmpRect.right;
si.nPos = xPos;
si.nPage = newClientRect.right;
SetScrollInfo( SB_HORZ, &si, TRUE );
if ( yPos > frameBmpRect.bottom - newClientRect.bottom ) yPos = frameBmpRect.bottom - newClientRect.bottom;
if ( yPos < 0 ) yPos = 0;
si.nMin = 0;
si.nMax = frameBmpRect.bottom;
si.nPos = yPos;
si.nPage = newClientRect.bottom;
SetScrollInfo( SB_VERT, &si, TRUE );
}
void RDOStudioFrameView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize = sizeof( si );
switch( nSBCode ) {
case SB_PAGEUP:
GetScrollInfo( SB_HORZ, &si, SIF_PAGE );
xPos -= si.nPage;
break;
case SB_PAGEDOWN:
GetScrollInfo( SB_HORZ, &si, SIF_PAGE );
xPos += si.nPage;
break;
case SB_LINEUP:
xPos--;
break;
case SB_LINEDOWN:
xPos++;
break;
case SB_THUMBTRACK: {
GetScrollInfo( SB_HORZ, &si, SIF_TRACKPOS );
xPos += si.nTrackPos - xPos;
break;
}
}
if ( xPos > frameBmpRect.right - newClientRect.right ) xPos = frameBmpRect.right - newClientRect.right;
if ( xPos < 0 ) xPos = 0;
si.fMask = SIF_POS;
si.nPos = xPos;
SetScrollInfo( SB_HORZ, &si, TRUE );
InvalidateRect( NULL );
UpdateWindow();
}
void RDOStudioFrameView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
SCROLLINFO si;
si.cbSize = sizeof( si );
switch( nSBCode ) {
case SB_PAGEUP:
GetScrollInfo( SB_VERT, &si, SIF_PAGE );
yPos -= si.nPage;
break;
case SB_PAGEDOWN:
GetScrollInfo( SB_VERT, &si, SIF_PAGE );
yPos += si.nPage;
break;
case SB_LINEUP:
yPos--;
break;
case SB_LINEDOWN:
yPos++;
break;
case SB_THUMBTRACK: {
GetScrollInfo( SB_VERT, &si, SIF_TRACKPOS );
yPos += si.nTrackPos - yPos;
break;
}
}
if ( yPos > frameBmpRect.bottom - newClientRect.bottom ) yPos = frameBmpRect.bottom - newClientRect.bottom;
if ( yPos < 0 ) yPos = 0;
si.fMask = SIF_POS;
si.nPos = yPos;
SetScrollInfo( SB_VERT, &si, TRUE );
InvalidateRect( NULL );
UpdateWindow();
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_CORE_PERFORMANCE_HPP
#define SRS_CORE_PERFORMANCE_HPP
/*
#include <srs_core_performance.hpp>
*/
#include <srs_core.hpp>
/**
* this file defines the perfromance options.
*/
/**
* to improve read performance, merge some packets then read,
* when it on and read small bytes, we sleep to wait more data.,
* that is, we merge some data to read together.
* @see SrsConfig::get_mr_enabled()
* @see SrsConfig::get_mr_sleep_ms()
* @see https://github.com/winlinvip/simple-rtmp-server/issues/241
* @example, for the default settings, this algorithm will use:
* that is, when got nread bytes smaller than 4KB, sleep(780ms).
*/
/**
* https://github.com/winlinvip/simple-rtmp-server/issues/241#issuecomment-65554690
* The merged read algorithm is ok and can be simplified for:
* 1. Suppose the client network is ok. All algorithm go wrong when netowrk is not ok.
* 2. Suppose the client send each packet one by one. Although send some together, it's same.
* 3. SRS MR algorithm will read all data then sleep.
* So, the MR algorithm is:
* while true:
* read all data from socket.
* sleep a while
* For example, sleep 120ms. Then there is, and always 120ms data in buffer.
* That is, the latency is 120ms(the sleep time).
*/
#define SRS_PERF_MERGED_READ
// the default config of mr.
#define SRS_PERF_MR_ENABLED false
#define SRS_PERF_MR_SLEEP 350
/**
* the MW(merged-write) send cache time in ms.
* the default value, user can override it in config.
* to improve send performance, cache msgs and send in a time.
* for example, cache 500ms videos and audios, then convert all these
* msgs to iovecs, finally use writev to send.
* @remark this largely improve performance, from 3.5k+ to 7.5k+.
* the latency+ when cache+.
* @remark the socket send buffer default to 185KB, it large enough.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/194
* @see SrsConfig::get_mw_sleep_ms()
* @remark the mw sleep and msgs to send, maybe:
* mw_sleep msgs iovs
* 350 43 86
* 400 44 88
* 500 46 92
* 600 46 92
* 700 82 164
* 800 81 162
* 900 80 160
* 1000 88 176
* 1100 91 182
* 1200 89 178
* 1300 119 238
* 1400 120 240
* 1500 119 238
* 1600 131 262
* 1700 131 262
* 1800 133 266
* 1900 141 282
* 2000 150 300
*/
// the default config of mw.
#define SRS_PERF_MW_SLEEP 350
/**
* use iovs cache in each msg,
* for the shared ptr message, we calc once and used for every copy.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
* @remark if enable this, donot use protocol iovs cache.
* @remark when reload change the chunk size, previous clients error.
*/
#undef SRS_PERF_MW_MSG_IOVS_CACHE
/**
* how many msgs can be send entirely.
* for play clients to get msgs then totally send out.
* for the mw sleep set to 1800, the msgs is about 133.
* @remark, recomment to 128.
* @remark, when mic enabled, use larger iovs cache, to 512.
*/
#ifndef SRS_PERF_MW_MSG_IOVS_CACHE
#define SRS_PERF_MW_MSGS 128
#else
#define SRS_PERF_MW_MSGS 512
#endif
/**
* whether set the socket send buffer size.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_MW_SO_SNDBUF
/**
* whether set the socket recv buffer size.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_MW_SO_RCVBUF
/**
* whether enable the fast cache.
* @remark this improve performance for large connectios.
* @remark this also introduce complex, default to disable it.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_FAST_CACHE
/**
* whether enable the fast vector for qeueue.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_FAST_VECTOR
/**
* whether use cond wait to send messages.
* @remark this improve performance for large connectios.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_COND_WAIT
/**
* how many chunk stream to cache, [0, N].
* to imporove about 10% performance when chunk size small, and 5% for large chunk.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/249
* @remark 0 to disable the chunk stream cache.
*/
#define SRS_PERF_CHUNK_STREAM_CACHE 16
/**
* the gop cache and play cache queue.
*/
// whether gop cache is on.
#define SRS_PERF_GOP_CACHE true
// in seconds, the live queue length.
#define SRS_PERF_PLAY_QUEUE 30
#endif
<commit_msg>for bug #251, add min msgs for queue cond wait.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_CORE_PERFORMANCE_HPP
#define SRS_CORE_PERFORMANCE_HPP
/*
#include <srs_core_performance.hpp>
*/
#include <srs_core.hpp>
/**
* this file defines the perfromance options.
*/
/**
* to improve read performance, merge some packets then read,
* when it on and read small bytes, we sleep to wait more data.,
* that is, we merge some data to read together.
* @see SrsConfig::get_mr_enabled()
* @see SrsConfig::get_mr_sleep_ms()
* @see https://github.com/winlinvip/simple-rtmp-server/issues/241
* @example, for the default settings, this algorithm will use:
* that is, when got nread bytes smaller than 4KB, sleep(780ms).
*/
/**
* https://github.com/winlinvip/simple-rtmp-server/issues/241#issuecomment-65554690
* The merged read algorithm is ok and can be simplified for:
* 1. Suppose the client network is ok. All algorithm go wrong when netowrk is not ok.
* 2. Suppose the client send each packet one by one. Although send some together, it's same.
* 3. SRS MR algorithm will read all data then sleep.
* So, the MR algorithm is:
* while true:
* read all data from socket.
* sleep a while
* For example, sleep 120ms. Then there is, and always 120ms data in buffer.
* That is, the latency is 120ms(the sleep time).
*/
#define SRS_PERF_MERGED_READ
// the default config of mr.
#define SRS_PERF_MR_ENABLED false
#define SRS_PERF_MR_SLEEP 350
/**
* the MW(merged-write) send cache time in ms.
* the default value, user can override it in config.
* to improve send performance, cache msgs and send in a time.
* for example, cache 500ms videos and audios, then convert all these
* msgs to iovecs, finally use writev to send.
* @remark this largely improve performance, from 3.5k+ to 7.5k+.
* the latency+ when cache+.
* @remark the socket send buffer default to 185KB, it large enough.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/194
* @see SrsConfig::get_mw_sleep_ms()
* @remark the mw sleep and msgs to send, maybe:
* mw_sleep msgs iovs
* 350 43 86
* 400 44 88
* 500 46 92
* 600 46 92
* 700 82 164
* 800 81 162
* 900 80 160
* 1000 88 176
* 1100 91 182
* 1200 89 178
* 1300 119 238
* 1400 120 240
* 1500 119 238
* 1600 131 262
* 1700 131 262
* 1800 133 266
* 1900 141 282
* 2000 150 300
*/
// the default config of mw.
#define SRS_PERF_MW_SLEEP 350
/**
* use iovs cache in each msg,
* for the shared ptr message, we calc once and used for every copy.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
* @remark if enable this, donot use protocol iovs cache.
* @remark when reload change the chunk size, previous clients error.
*/
#undef SRS_PERF_MW_MSG_IOVS_CACHE
/**
* how many msgs can be send entirely.
* for play clients to get msgs then totally send out.
* for the mw sleep set to 1800, the msgs is about 133.
* @remark, recomment to 128.
* @remark, when mic enabled, use larger iovs cache, to 512.
*/
#ifndef SRS_PERF_MW_MSG_IOVS_CACHE
#define SRS_PERF_MW_MSGS 128
#else
#define SRS_PERF_MW_MSGS 512
#endif
/**
* whether set the socket send buffer size.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_MW_SO_SNDBUF
/**
* whether set the socket recv buffer size.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_MW_SO_RCVBUF
/**
* whether enable the fast cache.
* @remark this improve performance for large connectios.
* @remark this also introduce complex, default to disable it.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_FAST_CACHE
/**
* whether enable the fast vector for qeueue.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_FAST_VECTOR
#if defined(SRS_PERF_QUEUE_FAST_CACHE) && defined(SRS_PERF_QUEUE_FAST_VECTOR)
#error "fast cache conflict with fast vector"
#endif
/**
* whether use cond wait to send messages.
* @remark this improve performance for large connectios.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/251
*/
#undef SRS_PERF_QUEUE_COND_WAIT
#ifdef SRS_PERF_QUEUE_COND_WAIT
#define SRS_PERF_MW_MIN_MSGS 8
#endif
/**
* how many chunk stream to cache, [0, N].
* to imporove about 10% performance when chunk size small, and 5% for large chunk.
* @see https://github.com/winlinvip/simple-rtmp-server/issues/249
* @remark 0 to disable the chunk stream cache.
*/
#define SRS_PERF_CHUNK_STREAM_CACHE 16
/**
* the gop cache and play cache queue.
*/
// whether gop cache is on.
#define SRS_PERF_GOP_CACHE true
// in seconds, the live queue length.
#define SRS_PERF_PLAY_QUEUE 30
#endif
<|endoftext|> |
<commit_before>#include <iconv.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <cstring>
#include <cerrno>
#include <cstdio>
using namespace v8;
using namespace node;
namespace {
class Iconv: public ObjectWrap {
public:
static void Initialize(Handle<Object>& target);
static Handle<Value> New(const Arguments& args);
static Handle<Value> Convert(const Arguments& args);
Iconv(iconv_t conv);
~Iconv(); // destructor may not run if program is short-lived or aborted
// the actual conversion happens here
Handle<Value> Convert(char* data, size_t length);
private:
iconv_t conv_;
};
Iconv::Iconv(iconv_t conv): conv_(conv) {
assert(conv_ != (iconv_t) -1);
}
Iconv::~Iconv() {
iconv_close(conv_);
}
// the actual conversion happens here
Handle<Value> Iconv::Convert(char* data, size_t length) {
assert(conv_ != (iconv_t) -1);
assert(data != 0);
char *inbuf;
char *outbuf;
size_t inbytesleft;
size_t outbytesleft;
inbuf = data;
inbytesleft = length;
char tmp[1024];
outbuf = tmp;
outbytesleft = sizeof(tmp);
size_t n = iconv(conv_, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (n == (size_t) -1) {
const char* message = "Unexpected error.";
switch (errno) {
case E2BIG:
message = "Output buffer not large enough. This is a bug.";
break;
case EILSEQ:
message = "Illegal character sequence.";
break;
case EINVAL:
message = "Incomplete character sequence.";
break;
}
return ThrowException(ErrnoException(errno, "iconv", message));
}
n = sizeof(tmp) - outbytesleft;
Buffer& b = *Buffer::New(n);
memcpy(b.data(), tmp, n);
return b.handle_;
}
Handle<Value> Iconv::Convert(const Arguments& args) {
HandleScope scope;
Iconv* self = ObjectWrap::Unwrap<Iconv>(args.This());
Local<Value> arg = args[0];
if (arg->IsString()) {
String::Utf8Value string(arg->ToString());
return self->Convert(*string, string.length());
}
if (arg->IsObject()) {
Handle<Value> object = arg->ToObject();
if (Buffer::HasInstance(object)) {
Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(arg->ToObject());
return self->Convert(buffer.data(), buffer.length());
}
}
return Undefined();
}
Handle<Value> Iconv::New(const Arguments& args) {
HandleScope scope;
String::AsciiValue sourceEncoding(args[0]->ToString());
String::AsciiValue targetEncoding(args[1]->ToString());
iconv_t conv = iconv_open(*targetEncoding, *sourceEncoding);
if (conv == (iconv_t) -1) {
return ThrowException(ErrnoException(errno, "iconv_open", "Conversion not supported."));
}
Iconv* instance = new Iconv(conv);
instance->Wrap(args.Holder());
return args.This();
}
void Iconv::Initialize(Handle<Object>& target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(Iconv::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "convert", Iconv::Convert);
target->Set(String::NewSymbol("Iconv"), t->GetFunction());
}
extern "C" void init(Handle<Object> target) {
Iconv::Initialize(target);
}
} // namespace
<commit_msg>Bump result buffer from 1K to 4K for great recoding justice.<commit_after>#include <iconv.h>
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <cstring>
#include <cerrno>
#include <cstdio>
using namespace v8;
using namespace node;
namespace {
class Iconv: public ObjectWrap {
public:
static void Initialize(Handle<Object>& target);
static Handle<Value> New(const Arguments& args);
static Handle<Value> Convert(const Arguments& args);
Iconv(iconv_t conv);
~Iconv(); // destructor may not run if program is short-lived or aborted
// the actual conversion happens here
Handle<Value> Convert(char* data, size_t length);
private:
iconv_t conv_;
};
Iconv::Iconv(iconv_t conv): conv_(conv) {
assert(conv_ != (iconv_t) -1);
}
Iconv::~Iconv() {
iconv_close(conv_);
}
// the actual conversion happens here
Handle<Value> Iconv::Convert(char* data, size_t length) {
assert(conv_ != (iconv_t) -1);
assert(data != 0);
char *inbuf;
char *outbuf;
size_t inbytesleft;
size_t outbytesleft;
inbuf = data;
inbytesleft = length;
char tmp[4096];
outbuf = tmp;
outbytesleft = sizeof(tmp);
size_t n = iconv(conv_, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
if (n == (size_t) -1) {
const char* message = "Unexpected error.";
switch (errno) {
case E2BIG:
message = "Output buffer not large enough. This is a bug.";
break;
case EILSEQ:
message = "Illegal character sequence.";
break;
case EINVAL:
message = "Incomplete character sequence.";
break;
}
return ThrowException(ErrnoException(errno, "iconv", message));
}
n = sizeof(tmp) - outbytesleft;
Buffer& b = *Buffer::New(n);
memcpy(b.data(), tmp, n);
return b.handle_;
}
Handle<Value> Iconv::Convert(const Arguments& args) {
HandleScope scope;
Iconv* self = ObjectWrap::Unwrap<Iconv>(args.This());
Local<Value> arg = args[0];
if (arg->IsString()) {
String::Utf8Value string(arg->ToString());
return self->Convert(*string, string.length());
}
if (arg->IsObject()) {
Handle<Value> object = arg->ToObject();
if (Buffer::HasInstance(object)) {
Buffer& buffer = *ObjectWrap::Unwrap<Buffer>(arg->ToObject());
return self->Convert(buffer.data(), buffer.length());
}
}
return Undefined();
}
Handle<Value> Iconv::New(const Arguments& args) {
HandleScope scope;
String::AsciiValue sourceEncoding(args[0]->ToString());
String::AsciiValue targetEncoding(args[1]->ToString());
iconv_t conv = iconv_open(*targetEncoding, *sourceEncoding);
if (conv == (iconv_t) -1) {
return ThrowException(ErrnoException(errno, "iconv_open", "Conversion not supported."));
}
Iconv* instance = new Iconv(conv);
instance->Wrap(args.Holder());
return args.This();
}
void Iconv::Initialize(Handle<Object>& target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(Iconv::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "convert", Iconv::Convert);
target->Set(String::NewSymbol("Iconv"), t->GetFunction());
}
extern "C" void init(Handle<Object> target) {
Iconv::Initialize(target);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
const GURL& url,
bool *has_match) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
*has_match = (match.get() != NULL);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new MessageLoop::QuitTask());
}
} // namespace
class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
public:
virtual void SetUp() {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnablePrivacyBlacklists);
ExtensionBrowserTest::SetUp();
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
received_blacklist_notification_ = false;
host_resolver()->AddSimulatedFailure("www.example.com");
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
ExtensionBrowserTest::Observe(type, source, details);
return;
}
received_blacklist_notification_ = true;
MessageLoop::current()->Quit();
}
protected:
BlacklistManager* GetBlacklistManager() {
return browser()->profile()->GetBlacklistManager();
}
bool GetAndResetReceivedBlacklistNotification() {
bool result = received_blacklist_notification_;
received_blacklist_notification_ = false;
return result;
}
bool BlacklistHasMatch(const std::string& url) {
bool has_match = false;
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
GetBlacklistManager(),
GURL(url),
&has_match));
ui_test_utils::RunMessageLoop();
return has_match;
}
private:
bool received_blacklist_notification_;
};
IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, Basic) {
static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";
NotificationRegistrar registrar;
registrar.Add(this,
NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
Source<Profile>(browser()->profile()));
// Test loading an extension with blacklist.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));
// Wait until the blacklist is loaded and ready.
if (!GetAndResetReceivedBlacklistNotification())
ui_test_utils::RunMessageLoop();
// The blacklist should block our test URL.
EXPECT_TRUE(BlacklistHasMatch(kTestUrl));
// TODO(phajdan.jr): Verify that we really blocked the request etc.
ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<commit_msg>Mark BlacklistManagerBrowserTest.Basic as flaky. BUG=29113<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/privacy_blacklist/blacklist_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void GetBlacklistHasMatchOnIOThread(const BlacklistManager* manager,
const GURL& url,
bool *has_match) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
const Blacklist* blacklist = manager->GetCompiledBlacklist();
scoped_ptr<Blacklist::Match> match(blacklist->findMatch(url));
*has_match = (match.get() != NULL);
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
new MessageLoop::QuitTask());
}
} // namespace
class BlacklistManagerBrowserTest : public ExtensionBrowserTest {
public:
virtual void SetUp() {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnablePrivacyBlacklists);
ExtensionBrowserTest::SetUp();
}
virtual void SetUpInProcessBrowserTestFixture() {
ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();
received_blacklist_notification_ = false;
host_resolver()->AddSimulatedFailure("www.example.com");
}
// NotificationObserver
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::BLACKLIST_MANAGER_ERROR &&
type != NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED) {
ExtensionBrowserTest::Observe(type, source, details);
return;
}
received_blacklist_notification_ = true;
MessageLoop::current()->Quit();
}
protected:
BlacklistManager* GetBlacklistManager() {
return browser()->profile()->GetBlacklistManager();
}
bool GetAndResetReceivedBlacklistNotification() {
bool result = received_blacklist_notification_;
received_blacklist_notification_ = false;
return result;
}
bool BlacklistHasMatch(const std::string& url) {
bool has_match = false;
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableFunction(GetBlacklistHasMatchOnIOThread,
GetBlacklistManager(),
GURL(url),
&has_match));
ui_test_utils::RunMessageLoop();
return has_match;
}
private:
bool received_blacklist_notification_;
};
IN_PROC_BROWSER_TEST_F(BlacklistManagerBrowserTest, FLAKY_Basic) {
static const char kTestUrl[] = "http://www.example.com/annoying_ads/ad.jpg";
NotificationRegistrar registrar;
registrar.Add(this,
NotificationType::BLACKLIST_MANAGER_BLACKLIST_READ_FINISHED,
Source<Profile>(browser()->profile()));
// Test loading an extension with blacklist.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("privacy_blacklist")));
// Wait until the blacklist is loaded and ready.
if (!GetAndResetReceivedBlacklistNotification())
ui_test_utils::RunMessageLoop();
// The blacklist should block our test URL.
EXPECT_TRUE(BlacklistHasMatch(kTestUrl));
// TODO(phajdan.jr): Verify that we really blocked the request etc.
ui_test_utils::NavigateToURL(browser(), GURL(kTestUrl));
}
<|endoftext|> |
<commit_before>/*
* Swift Parallel Scripting Language (http://swift-lang.org)
*
* Copyright 2012-2014 University of Chicago
*
* 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 "JobSubmitCommand.h"
#include "CoasterError.h"
#include <cstring>
#include <string>
using namespace Coaster;
using std::cout;
using std::map;
using std::ostream;
using std::string;
using std::stringstream;
using std::vector;
void add(string& ss, const char* key, const string* value);
void add(string& ss, const char* key, const string& value);
void add(string& ss, const char* key, const char* value);
void add(string& ss, const char* key, const char* value, int n);
string JobSubmitCommand::NAME("SUBMITJOB");
JobSubmitCommand::JobSubmitCommand(Job* pjob, const std::string& pconfigId): Command(&NAME) {
job = pjob;
configId = pconfigId;
}
void JobSubmitCommand::send(CoasterChannel* channel, CommandCallback* cb) {
serialize();
Command::send(channel, cb);
}
Job* JobSubmitCommand::getJob() {
return job;
}
string JobSubmitCommand::getRemoteId() {
if (!isReceiveCompleted() || isErrorReceived()) {
throw CoasterError("getRemoteId called before reply was received");
}
string result;
getInData()->at(0)->str(result);
return result;
}
void JobSubmitCommand::serialize() {
stringstream idSS;
idSS << job->getIdentity();
add(ss, "configid", configId);
add(ss, "identity", idSS.str());
add(ss, "executable", job->getExecutable());
add(ss, "directory", job->getDirectory());
add(ss, "stdin", job->getStdinLocation());
add(ss, "stdout", job->getStdoutLocation());
add(ss, "stderr", job->getStderrLocation());
const vector<string*>& arguments = job->getArguments();
for (vector<string*>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) {
add(ss, "arg", *i);
}
map<string, string>* env = job->getEnv();
if (env != NULL) {
for (map<string, string>::iterator i = env->begin(); i != env->end(); ++i) {
add(ss, "env", string(i->first).append("=").append(i->second));
}
}
map<string, string>* attributes = job->getAttributes();
if (attributes != NULL) {
for (map<string, string>::iterator i = attributes->begin(); i != attributes->end(); ++i) {
add(ss, "attr", string(i->first).append("=").append(i->second));
}
}
if (job->getJobManager().empty()) {
cout<< "getJobManager == NULL, setting to : fork "<< endl;
add(ss, "jm", "fork");
}
else {
const char *jm_string = (job->getJobManager()).c_str();
cout<< "getJobManager != !NULL, setting to : "<< job->getJobManager() << endl;
add(ss, "jm", jm_string);
}
addOutData(Buffer::wrap(ss));
}
void add(string& ss, const char* key, const string* value) {
if (value != NULL) {
add(ss, key, value->data(), value->length());
}
}
void add(string& ss, const char* key, const string& value) {
add(ss, key, value.data(), value.length());
}
void add(string& ss, const char* key, const char* value) {
add(ss, key, value, -1);
}
void add(string& ss, const char* key, const char* value, int n) {
if (value != NULL && n != 0) {
ss.append(key);
ss.append(1, '=');
while (*value) {
char c = *value;
switch (c) {
case '\n':
ss.append(1, '\\');
ss.append(1, 'n');
break;
case '\\':
ss.append(1, '\\');
ss.append(1, '\\');
break;
default:
ss.append(1, c);
break;
}
value++;
n--;
}
}
ss.append(1, '\n');
}
<commit_msg>Print debug messages at appropriate log level<commit_after>/*
* Swift Parallel Scripting Language (http://swift-lang.org)
*
* Copyright 2012-2014 University of Chicago
*
* 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 "JobSubmitCommand.h"
#include "CoasterError.h"
#include <cstring>
#include <string>
using namespace Coaster;
using std::map;
using std::ostream;
using std::string;
using std::stringstream;
using std::vector;
void add(string& ss, const char* key, const string* value);
void add(string& ss, const char* key, const string& value);
void add(string& ss, const char* key, const char* value);
void add(string& ss, const char* key, const char* value, int n);
string JobSubmitCommand::NAME("SUBMITJOB");
JobSubmitCommand::JobSubmitCommand(Job* pjob, const std::string& pconfigId): Command(&NAME) {
job = pjob;
configId = pconfigId;
}
void JobSubmitCommand::send(CoasterChannel* channel, CommandCallback* cb) {
serialize();
Command::send(channel, cb);
}
Job* JobSubmitCommand::getJob() {
return job;
}
string JobSubmitCommand::getRemoteId() {
if (!isReceiveCompleted() || isErrorReceived()) {
throw CoasterError("getRemoteId called before reply was received");
}
string result;
getInData()->at(0)->str(result);
return result;
}
void JobSubmitCommand::serialize() {
stringstream idSS;
idSS << job->getIdentity();
add(ss, "configid", configId);
add(ss, "identity", idSS.str());
add(ss, "executable", job->getExecutable());
add(ss, "directory", job->getDirectory());
add(ss, "stdin", job->getStdinLocation());
add(ss, "stdout", job->getStdoutLocation());
add(ss, "stderr", job->getStderrLocation());
const vector<string*>& arguments = job->getArguments();
for (vector<string*>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) {
add(ss, "arg", *i);
}
map<string, string>* env = job->getEnv();
if (env != NULL) {
for (map<string, string>::iterator i = env->begin(); i != env->end(); ++i) {
add(ss, "env", string(i->first).append("=").append(i->second));
}
}
map<string, string>* attributes = job->getAttributes();
if (attributes != NULL) {
for (map<string, string>::iterator i = attributes->begin(); i != attributes->end(); ++i) {
add(ss, "attr", string(i->first).append("=").append(i->second));
}
}
if (job->getJobManager().empty()) {
LogDebug << "getJobManager == NULL, setting to : fork "<< endl;
add(ss, "jm", "fork");
}
else {
const char *jm_string = (job->getJobManager()).c_str();
LogDebug << "getJobManager != !NULL, setting to : "<< job->getJobManager() << endl;
add(ss, "jm", jm_string);
}
addOutData(Buffer::wrap(ss));
}
void add(string& ss, const char* key, const string* value) {
if (value != NULL) {
add(ss, key, value->data(), value->length());
}
}
void add(string& ss, const char* key, const string& value) {
add(ss, key, value.data(), value.length());
}
void add(string& ss, const char* key, const char* value) {
add(ss, key, value, -1);
}
void add(string& ss, const char* key, const char* value, int n) {
if (value != NULL && n != 0) {
ss.append(key);
ss.append(1, '=');
while (*value) {
char c = *value;
switch (c) {
case '\n':
ss.append(1, '\\');
ss.append(1, 'n');
break;
case '\\':
ss.append(1, '\\');
ss.append(1, '\\');
break;
default:
ss.append(1, c);
break;
}
value++;
n--;
}
}
ss.append(1, '\n');
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>
#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/IteratorFromJsonSerializer.h"
using namespace std;
using namespace restc_cpp;
// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
int userId = 0;
int id = 0;
string title;
string body;
};
// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
Post,
(int, userId)
(int, id)
(string, title)
(string, body)
)
// The C++ main function - the place where any adventure starts
void first() {
// Create and instantiate a Post from data received from the server.
Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
// This is a co-routine, running in a worker-thread
// Instantiate a Post structure.
Post post;
// Serialize it asynchronously. The asynchronously part does not really matter
// here, but it may if you receive huge data structures.
SerializeFromJson(post,
// Construct a request to the server
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute());
// Return the post instance trough a C++ future<>
return post;
})
// Get the Post instance from the future<>, or any C++ exception thrown
// within the lambda.
.get();
// Print the result for everyone to see.
cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}
void DoSomethingInteresting(Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
}
void second() {
auto rest_client = RestClient::Create();
// Call DoSomethingInteresting as a co-routine in a worker-thread.
rest_client->Process(DoSomethingInteresting);
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
void third() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://localhost:3001/restricted/posts/1")
// Authenticate as 'alice' with a very popular password
.BasicAuthentication("alice", "12345")
// Send the request.
.Execute();
// Dump the well protected data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void forth() {
// Add the proxy information to the properties used by the client
Request::Properties properties;
properties.proxy.type = Request::Proxy::Type::HTTP;
properties.proxy.address = "http://127.0.0.1:3003";
// Create the client with our configuration
auto rest_client = RestClient::Create(properties);
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://api.example.com/normal/posts/1")
// Send the request.
.Execute();
// Dump the data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void fifth() {
// Fetch a list of records asyncrouesly, one by one.
// This allows us to process single items in a list
// and fetching more data as we move forward.
// This works basically as a database cursor, or
// (literally) as a properly implemented C++ input iterator.
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine
rest_client->Process([&](Context& ctx) {
// This is the co-routine, running in a worker-thread
// Construct a request to the server
auto reply = RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute();
// Instatiate a serializer with begin() and end() methods that
// allows us to work with the reply-data trough a C++
// input iterator.
IteratorFromJsonSerializer<Post> data{*reply};
// Iterate over the data, fetch data asyncrounesly as we go.
for(const auto& post : data) {
cout << "Item #" << post.id << " Title: " << post.title << endl;
}
});
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
void sixth() {
// Create the client without creating a worker thread
auto rest_client = RestClient::CreateUseOwnThread();
// Add a request to the queue of the io-service in the rest client instance
rest_client->Process([&](Context& ctx) {
// Here we are again in a co-routine, now in our own thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Send the request.
.Execute();
// Dump the data
cout << "Got: " << reply->GetBodyAsString();
// Shut down the io-service. This will cause run() (below) to return.
rest_client->CloseWhenReady();
});
// Start the io-service, using this thread.
rest_client->GetIoService().run();
cout << "Done. Exiting normally." << endl;
}
// Use our own RequestBody implementation to supply
// data to a POST request
void seventh() {
// Our own implementation of the raw data provider
class MyBody : public RequestBody
{
public:
MyBody() = default;
Type GetType() const noexcept override {
// This mode causes the request to use chunked data,
// allowing us to send data without knowing the exact
// size of the payload when we start.
return Type::CHUNKED_LAZY_PULL;
}
std::uint64_t GetFixedSize() const override {
throw runtime_error("Not implemented");
}
// This will be called until we return false to indicate
// that we have no further data
bool GetData(write_buffers_t& buffers) override {
if (++count_ > 10) {
// We are done.
return false;
}
ostringstream data;
data << "This is line #" << count_ << " of the payload.\r\n";
// The buffer need to persist until we are called again, or the
// instance is destroyed.
data_buffer_ = data.str();
buffers.emplace_back(data_buffer_.c_str(), data_buffer_.size());
// We added data to buffers, so return true
return true;
}
// Called if we get a HTTP redirect and need to start over again.
void Reset() override {
count_ = 0;
}
private:
int count_ = 0;
string data_buffer_;
};
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine
rest_client->Process([&](Context& ctx) {
// This is the co-routine, running in a worker-thread
// Construct a POST request to the server
RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/")
.Header("Content-Type", "text/text")
.Body(make_unique<MyBody>())
.Execute();
});
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
struct DataItem {
DataItem() = default;
DataItem(string u, string m)
: username{u}, motto{m} {}
int id = 0;
string username;
string motto;
};
BOOST_FUSION_ADAPT_STRUCT(
DataItem,
(int, id)
(string, username)
(string, motto)
)
void eight() {
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine that returns a future
rest_client->ProcessWithPromise([&](Context& ctx) {
// Make a container for data
std::vector<DataItem> data;
// Add some data
data.emplace_back("jgaa", "Carpe Diem!");
data.emplace_back("trump", "Endorse greed!");
data.emplace_back("anonymous", "We are great!");
// Create a request
auto reply = RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/") // URL
// Provide data from a lambda
.DataProvider([&](DataWriter& writer) {
// Here we are called from Execute() below to provide data
// Create a json serializer that can write data asynchronously
RapidJsonInserter<DataItem> inserter(writer, true);
// Serialize the items from our data container
for(const auto& d : data) {
// Serialize one data item.
// If the buffers in the writer fills up, we will
// write data to the net asynchronously.
inserter.Add(d);
}
// Tell the inserter that we have no further data.
inserter.Done();
})
// Execute the request
.Execute();
})
// Wait for the request to finish.
.get();
}
void ninth() {
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine that returns a future
rest_client->ProcessWithPromise([&](Context& ctx) {
// Make a container for data
std::vector<DataItem> data;
// Add some data
data.emplace_back("jgaa", "Carpe Diem!");
data.emplace_back("trump", "Endorse greed!");
data.emplace_back("anonymous", "We are great!");
// Prepare the request
auto request = RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/") // URL
// Make sure we get a DataWriter for chunked data
// This is required when we add data after the request-
// headers are sent.
.Chunked()
// Just create the request. Send nothing to the server.
.Build();
// Send the request to the server. This will send the
// request line and the request headers.
auto& writer = request->SendRequest(ctx);
{
// Create a json list serializer for our data object.
RapidJsonInserter<DataItem> inserter(writer, true);
// Write each item to the server
for(const auto& d : data) {
inserter.Add(d);
}
}
// Finish the request and fetch the reply asynchronously
// This function returns when we have the reply headers.
// If we expect data in the reply, we can read it asynchronously
// as shown in previous examples.
auto reply = request->GetReply(ctx);
cout << "The server replied with code: " << reply->GetResponseCode();
})
// Wait for the request to finish.
.get();
}
void tenth() {
// Construct our own ioservice.
boost::asio::io_service ioservice;
// Give it some work so it don't end prematurely
boost::asio::io_service::work work(ioservice);
// Start it in a worker-thread
thread worker([&ioservice]() {
cout << "ioservice is running" << endl;
ioservice.run();
cout << "ioservice is done" << endl;
});
// Now we have our own io-service running in a worker thread.
// Create a RestClient instance that uses it.
auto rest_client = RestClient::Create(ioservice);
// Make a HTTP request
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are in a co-routine, spawned from our io-service, running
// in our worker thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
})
// Wait for the co-routine to end
.get();
// Stop the io-service
// (We can not just remove 'work', as the rest client may have
// timers pending in the io-service, keeping it running even after
// work is gone).
ioservice.stop();
// Wait for the worker thread to end
worker.join();
cout << "Done." << endl;
}
void eleventh() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
Post data;
data.id = 10;
data.userId = 14;
data.title = "Hi there";
data.body = "This is the body.";
excluded_names_t exclusions{"id", "userId"};
auto reply = RequestBuilder(ctx)
.Post("http://localhost:3000/posts")
// Suppress sending 'id' and 'userId' properties
.Data(data, nullptr, &exclusions)
.Execute();
}).get();
}
void twelfth() {
auto rest_client = RestClient::Create();
RestClient::Create()->ProcessWithPromise([&](Context& ctx) {
Post post;
// Serialize with a limit of 2 kilobytes of memory usage by the post;
SerializeFromJson(post,
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Notice the limit of 2048 bytes
.Execute(), nullptr, 2048);
// Serialize with no limit;
SerializeFromJson(post,
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Notice how we disable the constraint by defining zero
.Execute(), nullptr, 0);
})
.get();
}
int main() {
try {
// cout << "First: " << endl;
// first();
//
// cout << "Second: " << endl;
// second();
//
// cout << "Third: " << endl;
// third();
//
// cout << "Forth: " << endl;
// forth();
//
// cout << "Fifth: " << endl;
// fifth();
//
// cout << "Sixth: " << endl;
// sixth();
//
// cout << "Seventh: " << endl;
// seventh();
//
// cout << "Eight: " << endl;
// eight();
//
// cout << "Ninth: " << endl;
// ninth();
//
// cout << "Tenth: " << endl;
// tenth();
//
// cout << "Eleventh: " << endl;
// eleventh();
cout << "Twelfth: " << endl;
twelfth();
} catch(const exception& ex) {
cerr << "Something threw up: " << ex.what() << endl;
return 1;
}
}
<commit_msg>Re-enabled all readme tests<commit_after>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>
#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
#include "restc-cpp/IteratorFromJsonSerializer.h"
using namespace std;
using namespace restc_cpp;
// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
int userId = 0;
int id = 0;
string title;
string body;
};
// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
Post,
(int, userId)
(int, id)
(string, title)
(string, body)
)
// The C++ main function - the place where any adventure starts
void first() {
// Create and instantiate a Post from data received from the server.
Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
// This is a co-routine, running in a worker-thread
// Instantiate a Post structure.
Post post;
// Serialize it asynchronously. The asynchronously part does not really matter
// here, but it may if you receive huge data structures.
SerializeFromJson(post,
// Construct a request to the server
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute());
// Return the post instance trough a C++ future<>
return post;
})
// Get the Post instance from the future<>, or any C++ exception thrown
// within the lambda.
.get();
// Print the result for everyone to see.
cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}
void DoSomethingInteresting(Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
}
void second() {
auto rest_client = RestClient::Create();
// Call DoSomethingInteresting as a co-routine in a worker-thread.
rest_client->Process(DoSomethingInteresting);
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
void third() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://localhost:3001/restricted/posts/1")
// Authenticate as 'alice' with a very popular password
.BasicAuthentication("alice", "12345")
// Send the request.
.Execute();
// Dump the well protected data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void forth() {
// Add the proxy information to the properties used by the client
Request::Properties properties;
properties.proxy.type = Request::Proxy::Type::HTTP;
properties.proxy.address = "http://127.0.0.1:3003";
// Create the client with our configuration
auto rest_client = RestClient::Create(properties);
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://api.example.com/normal/posts/1")
// Send the request.
.Execute();
// Dump the data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void fifth() {
// Fetch a list of records asyncrouesly, one by one.
// This allows us to process single items in a list
// and fetching more data as we move forward.
// This works basically as a database cursor, or
// (literally) as a properly implemented C++ input iterator.
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine
rest_client->Process([&](Context& ctx) {
// This is the co-routine, running in a worker-thread
// Construct a request to the server
auto reply = RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute();
// Instatiate a serializer with begin() and end() methods that
// allows us to work with the reply-data trough a C++
// input iterator.
IteratorFromJsonSerializer<Post> data{*reply};
// Iterate over the data, fetch data asyncrounesly as we go.
for(const auto& post : data) {
cout << "Item #" << post.id << " Title: " << post.title << endl;
}
});
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
void sixth() {
// Create the client without creating a worker thread
auto rest_client = RestClient::CreateUseOwnThread();
// Add a request to the queue of the io-service in the rest client instance
rest_client->Process([&](Context& ctx) {
// Here we are again in a co-routine, now in our own thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Send the request.
.Execute();
// Dump the data
cout << "Got: " << reply->GetBodyAsString();
// Shut down the io-service. This will cause run() (below) to return.
rest_client->CloseWhenReady();
});
// Start the io-service, using this thread.
rest_client->GetIoService().run();
cout << "Done. Exiting normally." << endl;
}
// Use our own RequestBody implementation to supply
// data to a POST request
void seventh() {
// Our own implementation of the raw data provider
class MyBody : public RequestBody
{
public:
MyBody() = default;
Type GetType() const noexcept override {
// This mode causes the request to use chunked data,
// allowing us to send data without knowing the exact
// size of the payload when we start.
return Type::CHUNKED_LAZY_PULL;
}
std::uint64_t GetFixedSize() const override {
throw runtime_error("Not implemented");
}
// This will be called until we return false to indicate
// that we have no further data
bool GetData(write_buffers_t& buffers) override {
if (++count_ > 10) {
// We are done.
return false;
}
ostringstream data;
data << "This is line #" << count_ << " of the payload.\r\n";
// The buffer need to persist until we are called again, or the
// instance is destroyed.
data_buffer_ = data.str();
buffers.emplace_back(data_buffer_.c_str(), data_buffer_.size());
// We added data to buffers, so return true
return true;
}
// Called if we get a HTTP redirect and need to start over again.
void Reset() override {
count_ = 0;
}
private:
int count_ = 0;
string data_buffer_;
};
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine
rest_client->Process([&](Context& ctx) {
// This is the co-routine, running in a worker-thread
// Construct a POST request to the server
RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/")
.Header("Content-Type", "text/text")
.Body(make_unique<MyBody>())
.Execute();
});
// Wait for the request to finish
rest_client->CloseWhenReady(true);
}
struct DataItem {
DataItem() = default;
DataItem(string u, string m)
: username{u}, motto{m} {}
int id = 0;
string username;
string motto;
};
BOOST_FUSION_ADAPT_STRUCT(
DataItem,
(int, id)
(string, username)
(string, motto)
)
void eight() {
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine that returns a future
rest_client->ProcessWithPromise([&](Context& ctx) {
// Make a container for data
std::vector<DataItem> data;
// Add some data
data.emplace_back("jgaa", "Carpe Diem!");
data.emplace_back("trump", "Endorse greed!");
data.emplace_back("anonymous", "We are great!");
// Create a request
auto reply = RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/") // URL
// Provide data from a lambda
.DataProvider([&](DataWriter& writer) {
// Here we are called from Execute() below to provide data
// Create a json serializer that can write data asynchronously
RapidJsonInserter<DataItem> inserter(writer, true);
// Serialize the items from our data container
for(const auto& d : data) {
// Serialize one data item.
// If the buffers in the writer fills up, we will
// write data to the net asynchronously.
inserter.Add(d);
}
// Tell the inserter that we have no further data.
inserter.Done();
})
// Execute the request
.Execute();
})
// Wait for the request to finish.
.get();
}
void ninth() {
// Create the REST clent
auto rest_client = RestClient::Create();
// Run our example in a lambda co-routine that returns a future
rest_client->ProcessWithPromise([&](Context& ctx) {
// Make a container for data
std::vector<DataItem> data;
// Add some data
data.emplace_back("jgaa", "Carpe Diem!");
data.emplace_back("trump", "Endorse greed!");
data.emplace_back("anonymous", "We are great!");
// Prepare the request
auto request = RequestBuilder(ctx)
.Post("http://localhost:3001/upload_raw/") // URL
// Make sure we get a DataWriter for chunked data
// This is required when we add data after the request-
// headers are sent.
.Chunked()
// Just create the request. Send nothing to the server.
.Build();
// Send the request to the server. This will send the
// request line and the request headers.
auto& writer = request->SendRequest(ctx);
{
// Create a json list serializer for our data object.
RapidJsonInserter<DataItem> inserter(writer, true);
// Write each item to the server
for(const auto& d : data) {
inserter.Add(d);
}
}
// Finish the request and fetch the reply asynchronously
// This function returns when we have the reply headers.
// If we expect data in the reply, we can read it asynchronously
// as shown in previous examples.
auto reply = request->GetReply(ctx);
cout << "The server replied with code: " << reply->GetResponseCode();
})
// Wait for the request to finish.
.get();
}
void tenth() {
// Construct our own ioservice.
boost::asio::io_service ioservice;
// Give it some work so it don't end prematurely
boost::asio::io_service::work work(ioservice);
// Start it in a worker-thread
thread worker([&ioservice]() {
cout << "ioservice is running" << endl;
ioservice.run();
cout << "ioservice is done" << endl;
});
// Now we have our own io-service running in a worker thread.
// Create a RestClient instance that uses it.
auto rest_client = RestClient::Create(ioservice);
// Make a HTTP request
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are in a co-routine, spawned from our io-service, running
// in our worker thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
})
// Wait for the co-routine to end
.get();
// Stop the io-service
// (We can not just remove 'work', as the rest client may have
// timers pending in the io-service, keeping it running even after
// work is gone).
ioservice.stop();
// Wait for the worker thread to end
worker.join();
cout << "Done." << endl;
}
void eleventh() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
Post data;
data.id = 10;
data.userId = 14;
data.title = "Hi there";
data.body = "This is the body.";
excluded_names_t exclusions{"id", "userId"};
auto reply = RequestBuilder(ctx)
.Post("http://localhost:3000/posts")
// Suppress sending 'id' and 'userId' properties
.Data(data, nullptr, &exclusions)
.Execute();
}).get();
}
void twelfth() {
auto rest_client = RestClient::Create();
RestClient::Create()->ProcessWithPromise([&](Context& ctx) {
Post post;
// Serialize with a limit of 2 kilobytes of memory usage by the post;
SerializeFromJson(post,
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Notice the limit of 2048 bytes
.Execute(), nullptr, 2048);
// Serialize with no limit;
SerializeFromJson(post,
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Notice how we disable the constraint by defining zero
.Execute(), nullptr, 0);
})
.get();
}
int main() {
try {
cout << "First: " << endl;
first();
cout << "Second: " << endl;
second();
cout << "Third: " << endl;
third();
cout << "Forth: " << endl;
forth();
cout << "Fifth: " << endl;
fifth();
cout << "Sixth: " << endl;
sixth();
cout << "Seventh: " << endl;
seventh();
cout << "Eight: " << endl;
eight();
cout << "Ninth: " << endl;
ninth();
cout << "Tenth: " << endl;
tenth();
cout << "Eleventh: " << endl;
eleventh();
cout << "Twelfth: " << endl;
twelfth();
} catch(const exception& ex) {
cerr << "Something threw up: " << ex.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_struct.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-09-18 13:59:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <precomp.h>
#include "hfi_struct.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ik_exception.hxx>
#include <ary/idl/ik_struct.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_property.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"
extern const String
C_sCePrefix_Struct("struct");
extern const String
C_sCePrefix_Exception("exception");
namespace
{
const String
C_sBaseStruct("Base Hierarchy");
const String
C_sBaseException("Base Hierarchy");
const String
C_sList_Elements("Elements' Summary");
const String
C_sList_Elements_Label("Elements");
const String
C_sList_ElementDetails("Elements' Details");
const String
C_sList_ElementDetails_Label("ElementDetails");
enum E_SubListIndices
{
sli_ElementsSummary = 0,
sli_ElementsDetails = 1
};
} // anonymous namespace
HF_IdlStruct::HF_IdlStruct( Environment & io_rEnv,
Xml::Element & o_rOut,
bool i_bIsException )
: HtmlFactory_Idl(io_rEnv, &o_rOut),
bIsException(i_bIsException)
{
}
HF_IdlStruct::~HF_IdlStruct()
{
}
void
HF_IdlStruct::Produce_byData( const client & i_ce ) const
{
const ary::idl::Struct *
pStruct =
bIsException
? 0
: static_cast< const ary::idl::Struct* >(&i_ce);
bool bIsTemplate =
pStruct != 0
? pStruct->TemplateParameterType().IsValid()
: false;
Dyn<HF_NaviSubRow>
pNaviSubRow( &make_Navibar(i_ce) );
HF_TitleTable
aTitle(CurOut());
HF_LinkedNameChain
aNameChain(aTitle.Add_Row());
aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);
// Title:
StreamLock
slAnnotations(200);
get_Annotations(slAnnotations(), i_ce);
StreamLock rTitle(200);
if (bIsTemplate)
rTitle() << "template ";
rTitle()
<< (bIsException
? C_sCePrefix_Exception
: C_sCePrefix_Struct)
<< " "
<< i_ce.LocalName();
if (bIsTemplate)
{
csv_assert(pStruct != 0);
rTitle()
<< "<"
<< pStruct->TemplateParameter()
<< ">";
}
aTitle.Produce_Title(slAnnotations().c_str(), rTitle().c_str());
// Bases:
produce_Bases( aTitle.Add_Row(),
i_ce,
bIsException
? C_sBaseException
: C_sBaseStruct );
// Docu:
write_Docu(aTitle.Add_Row(), i_ce);
CurOut() << new Html::HorizontalLine();
// Elements:
dyn_ce_list
dpElements;
if (bIsException)
ary::idl::ifc_exception::attr::Get_Elements(dpElements, i_ce);
else
ary::idl::ifc_struct::attr::Get_Elements(dpElements, i_ce);
if ( (*dpElements).operator bool() )
{
produce_Members( *dpElements,
C_sList_Elements,
C_sList_Elements_Label,
C_sList_ElementDetails,
C_sList_ElementDetails_Label );
pNaviSubRow->SwitchOn(sli_ElementsSummary);
pNaviSubRow->SwitchOn(sli_ElementsDetails);
}
pNaviSubRow->Produce_Row();
}
HtmlFactory_Idl::type_id
HF_IdlStruct::inq_BaseOf( const client & i_ce ) const
{
return bIsException
? ary::idl::ifc_exception::attr::Base(i_ce)
: ary::idl::ifc_struct::attr::Base(i_ce);
}
HF_NaviSubRow &
HF_IdlStruct::make_Navibar( const client & i_ce ) const
{
HF_IdlNavigationBar
aNaviBar(Env(), CurOut());
aNaviBar.Produce_CeMainRow(i_ce);
DYN HF_NaviSubRow &
ret = aNaviBar.Add_SubRow();
ret.AddItem(C_sList_Elements, C_sList_Elements_Label, false);
ret.AddItem(C_sList_ElementDetails, C_sList_ElementDetails_Label, false);
CurOut() << new Html::HorizontalLine();
return ret;
}
void
HF_IdlStruct::produce_MemberDetails( HF_SubTitleTable & o_table,
const client & i_ce) const
{
HF_IdlStructElement
aElement( Env(), o_table );
aElement.Produce_byData(i_ce);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.26); FILE MERGED 2008/03/28 16:02:05 rt 1.8.26.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hfi_struct.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <precomp.h>
#include "hfi_struct.hxx"
// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_ce.hxx>
#include <ary/idl/i_struct.hxx>
#include <ary/idl/ik_exception.hxx>
#include <ary/idl/ik_struct.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_linachain.hxx>
#include <toolkit/hf_navi_sub.hxx>
#include <toolkit/hf_title.hxx>
#include "hfi_navibar.hxx"
#include "hfi_property.hxx"
#include "hfi_typetext.hxx"
#include "hi_linkhelper.hxx"
extern const String
C_sCePrefix_Struct("struct");
extern const String
C_sCePrefix_Exception("exception");
namespace
{
const String
C_sBaseStruct("Base Hierarchy");
const String
C_sBaseException("Base Hierarchy");
const String
C_sList_Elements("Elements' Summary");
const String
C_sList_Elements_Label("Elements");
const String
C_sList_ElementDetails("Elements' Details");
const String
C_sList_ElementDetails_Label("ElementDetails");
enum E_SubListIndices
{
sli_ElementsSummary = 0,
sli_ElementsDetails = 1
};
} // anonymous namespace
HF_IdlStruct::HF_IdlStruct( Environment & io_rEnv,
Xml::Element & o_rOut,
bool i_bIsException )
: HtmlFactory_Idl(io_rEnv, &o_rOut),
bIsException(i_bIsException)
{
}
HF_IdlStruct::~HF_IdlStruct()
{
}
void
HF_IdlStruct::Produce_byData( const client & i_ce ) const
{
const ary::idl::Struct *
pStruct =
bIsException
? 0
: static_cast< const ary::idl::Struct* >(&i_ce);
bool bIsTemplate =
pStruct != 0
? pStruct->TemplateParameterType().IsValid()
: false;
Dyn<HF_NaviSubRow>
pNaviSubRow( &make_Navibar(i_ce) );
HF_TitleTable
aTitle(CurOut());
HF_LinkedNameChain
aNameChain(aTitle.Add_Row());
aNameChain.Produce_CompleteChain(Env().CurPosition(), nameChainLinker);
// Title:
StreamLock
slAnnotations(200);
get_Annotations(slAnnotations(), i_ce);
StreamLock rTitle(200);
if (bIsTemplate)
rTitle() << "template ";
rTitle()
<< (bIsException
? C_sCePrefix_Exception
: C_sCePrefix_Struct)
<< " "
<< i_ce.LocalName();
if (bIsTemplate)
{
csv_assert(pStruct != 0);
rTitle()
<< "<"
<< pStruct->TemplateParameter()
<< ">";
}
aTitle.Produce_Title(slAnnotations().c_str(), rTitle().c_str());
// Bases:
produce_Bases( aTitle.Add_Row(),
i_ce,
bIsException
? C_sBaseException
: C_sBaseStruct );
// Docu:
write_Docu(aTitle.Add_Row(), i_ce);
CurOut() << new Html::HorizontalLine();
// Elements:
dyn_ce_list
dpElements;
if (bIsException)
ary::idl::ifc_exception::attr::Get_Elements(dpElements, i_ce);
else
ary::idl::ifc_struct::attr::Get_Elements(dpElements, i_ce);
if ( (*dpElements).operator bool() )
{
produce_Members( *dpElements,
C_sList_Elements,
C_sList_Elements_Label,
C_sList_ElementDetails,
C_sList_ElementDetails_Label );
pNaviSubRow->SwitchOn(sli_ElementsSummary);
pNaviSubRow->SwitchOn(sli_ElementsDetails);
}
pNaviSubRow->Produce_Row();
}
HtmlFactory_Idl::type_id
HF_IdlStruct::inq_BaseOf( const client & i_ce ) const
{
return bIsException
? ary::idl::ifc_exception::attr::Base(i_ce)
: ary::idl::ifc_struct::attr::Base(i_ce);
}
HF_NaviSubRow &
HF_IdlStruct::make_Navibar( const client & i_ce ) const
{
HF_IdlNavigationBar
aNaviBar(Env(), CurOut());
aNaviBar.Produce_CeMainRow(i_ce);
DYN HF_NaviSubRow &
ret = aNaviBar.Add_SubRow();
ret.AddItem(C_sList_Elements, C_sList_Elements_Label, false);
ret.AddItem(C_sList_ElementDetails, C_sList_ElementDetails_Label, false);
CurOut() << new Html::HorizontalLine();
return ret;
}
void
HF_IdlStruct::produce_MemberDetails( HF_SubTitleTable & o_table,
const client & i_ce) const
{
HF_IdlStructElement
aElement( Env(), o_table );
aElement.Produce_byData(i_ce);
}
<|endoftext|> |
<commit_before>#include <cstdio>
long int f[39];
long int r[39];
long int fib(long int n) {
if (f[n] != -1)
return f[n];
if (n <= 1) {
f[n] = n;
} else {
f[n] = fib(n - 1) + fib(n - 2);
if (n >= 3)
r[n] = r[n - 1] + r[n - 2] + 2;
}
return f[n];
}
int main() {
int i, j;
long int n;
for (j = 0; j <= 39; j++) {
f[j] = -1;
r[j] = -1;
}
r[0] = 0;
r[1] = 0;
r[2] = 2;
scanf("%d", &i);
while (i--) {
scanf("%ld", &n);
printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
}
return 0;
}
<commit_msg>Improves Fibonacci function.<commit_after>#include <cstdio>
long int f[39];
long int r[39];
long int fib(long int n) {
if (f[n] != -1) return f[n];
if (n <= 1) {
f[n] = n;
r[n] = 0;
} else {
f[n] = fib(n - 1) + fib(n - 2);
r[n] = r[n - 1] + r[n - 2] + 2;
}
return f[n];
}
int main() {
int i, j;
long int n;
for (j = 0; j <= 39; j++) {
f[j] = -1;
r[j] = -1;
}
scanf("%d", &i);
while (i--) {
scanf("%ld", &n);
printf("fib(%ld) = %ld calls = %ld\n", n, r[n], fib(n));
}
return 0;
}
<|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 "sot/stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#include <rtl/instance.hxx>
///////////////////////////// class StgIo
// This class holds the storage header and all internal streams.
StgIo::StgIo() : StgCache()
{
pTOC = NULL;
pDataFAT = NULL;
pDataStrm = NULL;
pFAT = NULL;
bCopied = false;
}
StgIo::~StgIo()
{
delete pTOC;
delete pDataFAT;
delete pDataStrm;
delete pFAT;
}
// Load the header. Do not set an error code if the header is invalid.
bool StgIo::Load()
{
if( pStrm )
{
if( aHdr.Load( *this ) )
{
if( aHdr.Check() )
SetupStreams();
else
return false;
}
else
return false;
}
return Good();
}
// Set up an initial, empty storage
bool StgIo::Init()
{
aHdr.Init();
SetupStreams();
return CommitAll();
}
void StgIo::SetupStreams()
{
delete pTOC;
delete pDataFAT;
delete pDataStrm;
delete pFAT;
pTOC = NULL;
pDataFAT = NULL;
pDataStrm = NULL;
pFAT = NULL;
ResetError();
SetPhysPageSize( 1 << aHdr.GetPageSize() );
pFAT = new StgFATStrm( *this );
pTOC = new StgDirStrm( *this );
if( !GetError() )
{
StgDirEntry* pRoot = pTOC->GetRoot();
if( pRoot )
{
pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
pDataStrm = new StgDataStrm( *this, *pRoot );
pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
pDataStrm->SetIncrement( GetDataPageSize() );
pDataStrm->SetEntry( *pRoot );
}
else
SetError( SVSTREAM_FILEFORMAT_ERROR );
}
}
// get the logical data page size
short StgIo::GetDataPageSize()
{
return 1 << aHdr.GetDataPageSize();
}
// Commit everything
bool StgIo::CommitAll()
{
// Store the data (all streams and the TOC)
if( pTOC && pTOC->Store() && pDataFAT )
{
if( Commit() )
{
aHdr.SetDataFATStart( pDataFAT->GetStart() );
aHdr.SetDataFATSize( pDataFAT->GetPages() );
aHdr.SetTOCStart( pTOC->GetStart() );
if( aHdr.Store( *this ) )
{
pStrm->Flush();
sal_uLong n = pStrm->GetError();
SetError( n );
#ifdef DBG_UTIL
if( n==0 ) ValidateFATs();
#endif
return n == 0;
}
}
}
SetError( SVSTREAM_WRITE_ERROR );
return false;
}
class EasyFat
{
sal_Int32 *pFat;
bool *pFree;
sal_Int32 nPages;
sal_Int32 nPageSize;
public:
EasyFat( StgIo & rIo, StgStrm *pFatStream, sal_Int32 nPSize );
~EasyFat() { delete[] pFat; delete[] pFree; }
sal_Int32 GetPageSize() { return nPageSize; }
sal_Int32 Count() { return nPages; }
sal_Int32 operator[]( sal_Int32 nOffset )
{
OSL_ENSURE( nOffset >= 0 && nOffset < nPages, "Unexpected offset!" );
return nOffset >= 0 && nOffset < nPages ? pFat[ nOffset ] : -2;
}
sal_uLong Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect );
bool HasUnrefChains();
};
EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, sal_Int32 nPSize )
{
nPages = pFatStream->GetSize() >> 2;
nPageSize = nPSize;
pFat = new sal_Int32[ nPages ];
pFree = new bool[ nPages ];
rtl::Reference< StgPage > pPage;
sal_Int32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2;
for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
{
if( ! (nPage % nFatPageSize) )
{
pFatStream->Pos2Page( nPage << 2 );
sal_Int32 nPhysPage = pFatStream->GetPage();
pPage = rIo.Get( nPhysPage, true );
}
pFat[ nPage ] = rIo.GetFromPage( pPage, short( nPage % nFatPageSize ) );
pFree[ nPage ] = true;
}
}
bool EasyFat::HasUnrefChains()
{
for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
{
if( pFree[ nPage ] && pFat[ nPage ] != -1 )
return true;
}
return false;
}
sal_uLong EasyFat::Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect )
{
if( nCount > 0 )
--nCount /= GetPageSize(), nCount++;
sal_Int32 nCurPage = nPage;
while( nCount != 0 )
{
if( nCurPage < 0 || nCurPage >= nPages )
return FAT_OUTOFBOUNDS;
pFree[ nCurPage ] = false;
nCurPage = pFat[ nCurPage ];
//Stream zu lang
if( nCurPage != nExpect && nCount == 1 )
return FAT_WRONGLENGTH;
//Stream zu kurz
if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
return FAT_WRONGLENGTH;
// letzter Block bei Stream ohne Laenge
if( nCurPage == nExpect && nCount == -1 )
nCount = 1;
if( nCount != -1 )
nCount--;
}
return FAT_OK;
}
class Validator
{
sal_uLong nError;
EasyFat aSmallFat;
EasyFat aFat;
StgIo &rIo;
sal_uLong ValidateMasterFATs();
sal_uLong ValidateDirectoryEntries();
sal_uLong FindUnrefedChains();
sal_uLong MarkAll( StgDirEntry *pEntry );
public:
Validator( StgIo &rIo );
bool IsError() { return nError != 0; }
};
Validator::Validator( StgIo &rIoP )
: aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
rIo( rIoP )
{
sal_uLong nErr = nError = FAT_OK;
if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
nError = nErr;
else if( ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
nError = nErr;
else if( ( nErr = FindUnrefedChains()) != FAT_OK )
nError = nErr;
}
sal_uLong Validator::ValidateMasterFATs()
{
sal_Int32 nCount = rIo.aHdr.GetFATSize();
sal_uLong nErr;
if ( !rIo.pFAT )
return FAT_INMEMORYERROR;
for( sal_Int32 i = 0; i < nCount; i++ )
{
if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), false ), aFat.GetPageSize(), -3 )) != FAT_OK )
return nErr;
}
if( rIo.aHdr.GetMasters() )
if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
return nErr;
return FAT_OK;
}
sal_uLong Validator::MarkAll( StgDirEntry *pEntry )
{
if ( !pEntry )
return FAT_INMEMORYERROR;
StgIterator aIter( *pEntry );
sal_uLong nErr = FAT_OK;
for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
{
if( p->aEntry.GetType() == STG_STORAGE )
{
nErr = MarkAll( p );
if( nErr != FAT_OK )
return nErr;
}
else
{
sal_Int32 nSize = p->aEntry.GetSize();
if( nSize < rIo.aHdr.GetThreshold() )
nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
else
nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
if( nErr != FAT_OK )
return nErr;
}
}
return FAT_OK;
}
sal_uLong Validator::ValidateDirectoryEntries()
{
if ( !rIo.pTOC )
return FAT_INMEMORYERROR;
// Normale DirEntries
sal_uLong nErr = MarkAll( rIo.pTOC->GetRoot() );
if( nErr != FAT_OK )
return nErr;
// Small Data
nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
if( nErr != FAT_OK )
return nErr;
// Small Data FAT
nErr = aFat.Mark(
rIo.aHdr.GetDataFATStart(),
rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
if( nErr != FAT_OK )
return nErr;
// TOC
nErr = aFat.Mark(
rIo.aHdr.GetTOCStart(), -1, -2 );
return nErr;
}
sal_uLong Validator::FindUnrefedChains()
{
if( aSmallFat.HasUnrefChains() ||
aFat.HasUnrefChains() )
return FAT_UNREFCHAIN;
else
return FAT_OK;
}
namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; }
void StgIo::SetErrorLink( const Link& rLink )
{
ErrorLink::get() = rLink;
}
const Link& StgIo::GetErrorLink()
{
return ErrorLink::get();
}
sal_uLong StgIo::ValidateFATs()
{
if( bFile )
{
Validator *pV = new Validator( *this );
bool bRet1 = !pV->IsError(), bRet2 = true ;
delete pV;
SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
if ( !pFileStrm )
return FAT_INMEMORYERROR;
StgIo aIo;
if( aIo.Open( pFileStrm->GetFileName(),
STREAM_READ | STREAM_SHARE_DENYNONE) &&
aIo.Load() )
{
pV = new Validator( aIo );
bRet2 = !pV->IsError();
delete pV;
}
sal_uLong nErr;
if( bRet1 != bRet2 )
nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
if( nErr != FAT_OK && !bCopied )
{
StgLinkArg aArg;
aArg.aFile = pFileStrm->GetFileName();
aArg.nErr = nErr;
ErrorLink::get().Call( &aArg );
bCopied = true;
}
// DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
return nErr;
}
// OSL_FAIL("Validiere nicht (kein FileStorage)");
return FAT_OK;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused functions<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 "sot/stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#include <rtl/instance.hxx>
///////////////////////////// class StgIo
// This class holds the storage header and all internal streams.
StgIo::StgIo() : StgCache()
{
pTOC = NULL;
pDataFAT = NULL;
pDataStrm = NULL;
pFAT = NULL;
bCopied = false;
}
StgIo::~StgIo()
{
delete pTOC;
delete pDataFAT;
delete pDataStrm;
delete pFAT;
}
// Load the header. Do not set an error code if the header is invalid.
bool StgIo::Load()
{
if( pStrm )
{
if( aHdr.Load( *this ) )
{
if( aHdr.Check() )
SetupStreams();
else
return false;
}
else
return false;
}
return Good();
}
// Set up an initial, empty storage
bool StgIo::Init()
{
aHdr.Init();
SetupStreams();
return CommitAll();
}
void StgIo::SetupStreams()
{
delete pTOC;
delete pDataFAT;
delete pDataStrm;
delete pFAT;
pTOC = NULL;
pDataFAT = NULL;
pDataStrm = NULL;
pFAT = NULL;
ResetError();
SetPhysPageSize( 1 << aHdr.GetPageSize() );
pFAT = new StgFATStrm( *this );
pTOC = new StgDirStrm( *this );
if( !GetError() )
{
StgDirEntry* pRoot = pTOC->GetRoot();
if( pRoot )
{
pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
pDataStrm = new StgDataStrm( *this, *pRoot );
pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
pDataStrm->SetIncrement( GetDataPageSize() );
pDataStrm->SetEntry( *pRoot );
}
else
SetError( SVSTREAM_FILEFORMAT_ERROR );
}
}
// get the logical data page size
short StgIo::GetDataPageSize()
{
return 1 << aHdr.GetDataPageSize();
}
// Commit everything
bool StgIo::CommitAll()
{
// Store the data (all streams and the TOC)
if( pTOC && pTOC->Store() && pDataFAT )
{
if( Commit() )
{
aHdr.SetDataFATStart( pDataFAT->GetStart() );
aHdr.SetDataFATSize( pDataFAT->GetPages() );
aHdr.SetTOCStart( pTOC->GetStart() );
if( aHdr.Store( *this ) )
{
pStrm->Flush();
sal_uLong n = pStrm->GetError();
SetError( n );
#ifdef DBG_UTIL
if( n==0 ) ValidateFATs();
#endif
return n == 0;
}
}
}
SetError( SVSTREAM_WRITE_ERROR );
return false;
}
class EasyFat
{
sal_Int32 *pFat;
bool *pFree;
sal_Int32 nPages;
sal_Int32 nPageSize;
public:
EasyFat( StgIo & rIo, StgStrm *pFatStream, sal_Int32 nPSize );
~EasyFat() { delete[] pFat; delete[] pFree; }
sal_Int32 GetPageSize() { return nPageSize; }
sal_uLong Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect );
bool HasUnrefChains();
};
EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, sal_Int32 nPSize )
{
nPages = pFatStream->GetSize() >> 2;
nPageSize = nPSize;
pFat = new sal_Int32[ nPages ];
pFree = new bool[ nPages ];
rtl::Reference< StgPage > pPage;
sal_Int32 nFatPageSize = (1 << rIo.aHdr.GetPageSize()) - 2;
for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
{
if( ! (nPage % nFatPageSize) )
{
pFatStream->Pos2Page( nPage << 2 );
sal_Int32 nPhysPage = pFatStream->GetPage();
pPage = rIo.Get( nPhysPage, true );
}
pFat[ nPage ] = rIo.GetFromPage( pPage, short( nPage % nFatPageSize ) );
pFree[ nPage ] = true;
}
}
bool EasyFat::HasUnrefChains()
{
for( sal_Int32 nPage = 0; nPage < nPages; nPage++ )
{
if( pFree[ nPage ] && pFat[ nPage ] != -1 )
return true;
}
return false;
}
sal_uLong EasyFat::Mark( sal_Int32 nPage, sal_Int32 nCount, sal_Int32 nExpect )
{
if( nCount > 0 )
--nCount /= GetPageSize(), nCount++;
sal_Int32 nCurPage = nPage;
while( nCount != 0 )
{
if( nCurPage < 0 || nCurPage >= nPages )
return FAT_OUTOFBOUNDS;
pFree[ nCurPage ] = false;
nCurPage = pFat[ nCurPage ];
//Stream zu lang
if( nCurPage != nExpect && nCount == 1 )
return FAT_WRONGLENGTH;
//Stream zu kurz
if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
return FAT_WRONGLENGTH;
// letzter Block bei Stream ohne Laenge
if( nCurPage == nExpect && nCount == -1 )
nCount = 1;
if( nCount != -1 )
nCount--;
}
return FAT_OK;
}
class Validator
{
sal_uLong nError;
EasyFat aSmallFat;
EasyFat aFat;
StgIo &rIo;
sal_uLong ValidateMasterFATs();
sal_uLong ValidateDirectoryEntries();
sal_uLong FindUnrefedChains();
sal_uLong MarkAll( StgDirEntry *pEntry );
public:
Validator( StgIo &rIo );
bool IsError() { return nError != 0; }
};
Validator::Validator( StgIo &rIoP )
: aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
rIo( rIoP )
{
sal_uLong nErr = nError = FAT_OK;
if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
nError = nErr;
else if( ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
nError = nErr;
else if( ( nErr = FindUnrefedChains()) != FAT_OK )
nError = nErr;
}
sal_uLong Validator::ValidateMasterFATs()
{
sal_Int32 nCount = rIo.aHdr.GetFATSize();
sal_uLong nErr;
if ( !rIo.pFAT )
return FAT_INMEMORYERROR;
for( sal_Int32 i = 0; i < nCount; i++ )
{
if( ( nErr = aFat.Mark(rIo.pFAT->GetPage( short(i), false ), aFat.GetPageSize(), -3 )) != FAT_OK )
return nErr;
}
if( rIo.aHdr.GetMasters() )
if( ( nErr = aFat.Mark(rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
return nErr;
return FAT_OK;
}
sal_uLong Validator::MarkAll( StgDirEntry *pEntry )
{
if ( !pEntry )
return FAT_INMEMORYERROR;
StgIterator aIter( *pEntry );
sal_uLong nErr = FAT_OK;
for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
{
if( p->aEntry.GetType() == STG_STORAGE )
{
nErr = MarkAll( p );
if( nErr != FAT_OK )
return nErr;
}
else
{
sal_Int32 nSize = p->aEntry.GetSize();
if( nSize < rIo.aHdr.GetThreshold() )
nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
else
nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
if( nErr != FAT_OK )
return nErr;
}
}
return FAT_OK;
}
sal_uLong Validator::ValidateDirectoryEntries()
{
if ( !rIo.pTOC )
return FAT_INMEMORYERROR;
// Normale DirEntries
sal_uLong nErr = MarkAll( rIo.pTOC->GetRoot() );
if( nErr != FAT_OK )
return nErr;
// Small Data
nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
if( nErr != FAT_OK )
return nErr;
// Small Data FAT
nErr = aFat.Mark(
rIo.aHdr.GetDataFATStart(),
rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
if( nErr != FAT_OK )
return nErr;
// TOC
nErr = aFat.Mark(
rIo.aHdr.GetTOCStart(), -1, -2 );
return nErr;
}
sal_uLong Validator::FindUnrefedChains()
{
if( aSmallFat.HasUnrefChains() ||
aFat.HasUnrefChains() )
return FAT_UNREFCHAIN;
else
return FAT_OK;
}
namespace { struct ErrorLink : public rtl::Static<Link, ErrorLink > {}; }
void StgIo::SetErrorLink( const Link& rLink )
{
ErrorLink::get() = rLink;
}
const Link& StgIo::GetErrorLink()
{
return ErrorLink::get();
}
sal_uLong StgIo::ValidateFATs()
{
if( bFile )
{
Validator *pV = new Validator( *this );
bool bRet1 = !pV->IsError(), bRet2 = true ;
delete pV;
SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
if ( !pFileStrm )
return FAT_INMEMORYERROR;
StgIo aIo;
if( aIo.Open( pFileStrm->GetFileName(),
STREAM_READ | STREAM_SHARE_DENYNONE) &&
aIo.Load() )
{
pV = new Validator( aIo );
bRet2 = !pV->IsError();
delete pV;
}
sal_uLong nErr;
if( bRet1 != bRet2 )
nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
if( nErr != FAT_OK && !bCopied )
{
StgLinkArg aArg;
aArg.aFile = pFileStrm->GetFileName();
aArg.nErr = nErr;
ErrorLink::get().Call( &aArg );
bCopied = true;
}
// DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
return nErr;
}
// OSL_FAIL("Validiere nicht (kein FileStorage)");
return FAT_OK;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 Bolloré telecom
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppConstants.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppUtils.h"
#include <QDomElement>
QList<QXmppElement> QXmppDiscoveryIq::getItems() const
{
return m_items;
}
void QXmppDiscoveryIq::setItems(const QList<QXmppElement> &items)
{
m_items = items;
}
enum QXmppDiscoveryIq::QueryType QXmppDiscoveryIq::getQueryType() const
{
return m_queryType;
}
void QXmppDiscoveryIq::setQueryType(enum QXmppDiscoveryIq::QueryType type)
{
m_queryType = type;
}
bool QXmppDiscoveryIq::isDiscoveryIq( QDomElement &element )
{
QDomElement queryElement = element.firstChildElement("query");
return (queryElement.namespaceURI() == ns_disco_info ||
queryElement.namespaceURI() == ns_disco_items);
}
void QXmppDiscoveryIq::parse( QDomElement &element )
{
setFrom(element.attribute("from"));
setTo(element.attribute("to"));
setTypeFromStr(element.attribute("type"));
QDomElement queryElement = element.firstChildElement("query");
if (queryElement.namespaceURI() == ns_disco_items)
m_queryType = ItemsQuery;
else
m_queryType = InfoQuery;
QDomElement itemElement = queryElement.firstChildElement();
while (!itemElement.isNull())
{
m_items.append(QXmppElement(element));
itemElement = itemElement.nextSiblingElement();
}
}
void QXmppDiscoveryIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("query");
helperToXmlAddAttribute(writer, "xmlns",
m_queryType == InfoQuery ? ns_disco_info : ns_disco_items);
foreach (const QXmppElement &item, m_items)
item.toXml(writer);
writer->writeEndElement();
}
<commit_msg>fix parsing of discovery items<commit_after>/*
* Copyright (C) 2010 Bolloré telecom
*
* Author:
* Jeremy Lainé
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppConstants.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppUtils.h"
#include <QDomElement>
QList<QXmppElement> QXmppDiscoveryIq::getItems() const
{
return m_items;
}
void QXmppDiscoveryIq::setItems(const QList<QXmppElement> &items)
{
m_items = items;
}
enum QXmppDiscoveryIq::QueryType QXmppDiscoveryIq::getQueryType() const
{
return m_queryType;
}
void QXmppDiscoveryIq::setQueryType(enum QXmppDiscoveryIq::QueryType type)
{
m_queryType = type;
}
bool QXmppDiscoveryIq::isDiscoveryIq( QDomElement &element )
{
QDomElement queryElement = element.firstChildElement("query");
return (queryElement.namespaceURI() == ns_disco_info ||
queryElement.namespaceURI() == ns_disco_items);
}
void QXmppDiscoveryIq::parse( QDomElement &element )
{
setFrom(element.attribute("from"));
setTo(element.attribute("to"));
setTypeFromStr(element.attribute("type"));
QDomElement queryElement = element.firstChildElement("query");
if (queryElement.namespaceURI() == ns_disco_items)
m_queryType = ItemsQuery;
else
m_queryType = InfoQuery;
QDomElement itemElement = queryElement.firstChildElement();
while (!itemElement.isNull())
{
m_items.append(QXmppElement(itemElement));
itemElement = itemElement.nextSiblingElement();
}
}
void QXmppDiscoveryIq::toXmlElementFromChild(QXmlStreamWriter *writer) const
{
writer->writeStartElement("query");
helperToXmlAddAttribute(writer, "xmlns",
m_queryType == InfoQuery ? ns_disco_info : ns_disco_items);
foreach (const QXmppElement &item, m_items)
item.toXml(writer);
writer->writeEndElement();
}
<|endoftext|> |
<commit_before>#pragma once
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <vector>
#include "stiffness_matrix.hpp"
//! Sparse Matrix type. Makes using this type easier.
typedef Eigen::SparseMatrix<double> SparseMatrix;
//! Used for filling the sparse matrix.
typedef Eigen::Triplet<double> Triplet;
//----------------AssembleMatrixBegin----------------
//! Assemble the stiffness matrix
//! for the linear system
//!
//! @param[out] A will at the end contain the Galerkin matrix
//! @param[in] vertices a list of triangle vertices
//! @param[in] dofs a list of the dofs' indices in each triangle
template <class Matrix>
void assembleStiffnessMatrix(Matrix &A, const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &dofs, const int &N) {
const int numberOfElements = dofs.rows();
A.resize(N, N);
std::vector<Triplet> triplets;
triplets.reserve(numberOfElements * 6 * 10);
// (write your solution here)
A.setFromTriplets(triplets.begin(), triplets.end());
}
//----------------AssembleMatrixEnd----------------
<commit_msg>Solved series 3 problem 1f<commit_after>#pragma once
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <vector>
#include "stiffness_matrix.hpp"
//! Sparse Matrix type. Makes using this type easier.
typedef Eigen::SparseMatrix<double> SparseMatrix;
//! Used for filling the sparse matrix.
typedef Eigen::Triplet<double> Triplet;
//----------------AssembleMatrixBegin----------------
//! Assemble the stiffness matrix
//! for the linear system
//!
//! @param[out] A will at the end contain the Galerkin matrix
//! @param[in] vertices a list of triangle vertices
//! @param[in] dofs a list of the dofs' indices in each triangle
template <class Matrix>
void assembleStiffnessMatrix(Matrix &A, const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &dofs, const int &N) {
const int numberOfElements = dofs.rows();
A.resize(N, N);
std::vector<Triplet> triplets;
triplets.reserve(numberOfElements * 6 * 10);
// (write your solution here)
for (int i = 0; i < numberOfElements; ++i) {
auto &indexSet = dofs.row(i);
const auto &a = vertices.row(indexSet(0));
const auto &b = vertices.row(indexSet(1));
const auto &c = vertices.row(indexSet(2));
Eigen::MatrixXd stiffnessMatrix;
computeStiffnessMatrix(stiffnessMatrix, a, b, c);
for (int n = 0; n < 6; ++n) {
for (int m = 0; m < 6; ++m) {
auto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));
triplets.push_back(triplet);
}
}
}
A.setFromTriplets(triplets.begin(), triplets.end());
}
//----------------AssembleMatrixEnd----------------
<|endoftext|> |
<commit_before>/** @file gsBoundaryConditions_test.cpp
@brief test gsPde/gsBoundaryConditions
This file is part of the G+Smo library.
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/.
Author(s): A. Mantzaflaris, H. Weiner
**/
#include "gismo_unittest.h"
#include <typeinfo>
#include <memory>
std::string getBoxSideExpectedString(std::string string, int index)
{
std::ostringstream stream;
std::string result;
stream << string << " (" << index << ")";
result = stream.str();
return result;
}
std::string getBoxSideActualString(gismo::boxSide boxSide)
{
std::ostringstream stream;
std::string result;
stream << boxSide;
result = stream.str();
return result;
}
std::string getFunctionExprExpectedString(std::string string)
{
std::ostringstream stream;
std::string result;
stream << "[ " << string << " ]";
result = stream.str();
return result;
}
std::string getFunctionExprActualString(gsFunctionExpr<real_t> func)
{
std::ostringstream stream;
std::string result;
func.print(stream);
result = stream.str();
return result;
}
gsBoundaryConditions<real_t> gsBoundaryConditions_loadFromFile(std::string path)
{
gsBoundaryConditions<real_t> result;
gsReadFile<>(path, result);
return result;
}
void gsBoundaryConditions_saveToFile(std::string path,
gsBoundaryConditions<real_t> &sut)
{
// clean-up before using file
remove(path.c_str());
// now save...
gsFileData<> write;
write << sut;
write.dump(path);
}
// create the same gsBoundary condition as in test-data file "bc.xml"
gsBoundaryConditions<real_t> createBcGsBoundaryConditiions()
{
// set-up
gsBoundaryConditions<real_t> result;
return result;
}
gsBoundaryConditions<real_t> createSimpleGsBoundaryConditiions()
{
gsBoundaryConditions<real_t> result;
return result;
}
gsFunctionExpr<real_t> getFunctionExpr(boundary_condition<real_t> bc)
{
bool funcTypeSame1 = (typeid(*bc.m_function)
== typeid(gsFunctionExpr<real_t> ));
CHECK(funcTypeSame1);
gsFunction<real_t>::Ptr ptr = bc.m_function;
gsFunctionExpr<real_t> * ptr2 =
dynamic_cast<gsFunctionExpr<real_t> *>(ptr.get());
gsFunctionExpr<real_t> result = *ptr2;
return result;
}
void checkBoundaryCondition(boundary_condition<real_t> bc, bool parametric,
std::string label, gismo::condition_type::type conditionType, int patch,
int index, int unknown, int unkcomp, int domainDim,
std::string funcName)
{
// check boundary condition itself
CHECK_EQUAL(parametric, bc.m_parametric);
CHECK_EQUAL(label, bc.m_label);
CHECK_EQUAL(conditionType, bc.m_type);
CHECK_EQUAL(patch, bc.ps.patch);
CHECK_EQUAL(index, bc.ps.m_index);
CHECK_EQUAL(unknown, bc.m_unknown);
CHECK_EQUAL(unkcomp, bc.m_unkcomp);
// check functionExpr
gismo::gsFunctionExpr<real_t> func = getFunctionExpr(bc);
CHECK_EQUAL(domainDim, func.domainDim());
std::string expectedName = getFunctionExprExpectedString(funcName);
std::string actualName = getFunctionExprActualString(func);
CHECK_EQUAL(expectedName, actualName);
}
void checkGsBoundaryCondition(const gsBoundaryConditions<real_t> & sut)
{
// check corner value(s)
gismo::gsBoundaryConditions<real_t>::cornerContainer c1 =
sut.cornerValues();
unsigned elems1 = 1;
CHECK_EQUAL(elems1, c1.size());
gismo::corner_value<real_t> cv1 = c1[0];
CHECK_EQUAL(0, cv1.corner);
CHECK_EQUAL(0, cv1.corner.m_index);
CHECK_EQUAL(0, cv1.patch);
CHECK_EQUAL(0.0, cv1.value);
CHECK_EQUAL(0, cv1.unknown);
// check dirichlet conditions
std::string label1 = "Dirichlet";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc0 = sut.container(
label1);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc1 =
sut.dirichletSides();
unsigned elems2 = 6;
CHECK_EQUAL(elems2, bcc0.size());
CHECK_EQUAL(elems2, bcc1.size());
// check boundary conditions themselves
std::string funcName0 = "0";
int patches[4] =
{ 0, 0, 1, 1 };
int indizes[4] =
{ 1, 3, 1, 2 };
int unknown = 0;
int unkcomp = 0;
int domainDim = 2;
for (int i = 0; i < 4; i++)
{
checkBoundaryCondition(bcc0[i], false, label1,
gismo::condition_type::dirichlet, patches[i], indizes[i],
unknown, unkcomp, domainDim, funcName0);
}
std::string funcName1 = "sin(pi*x)*sin(pi*y)";
int patch4 = 0;
int index4 = 2;
int patch5 = 0;
int index5 = 4;
checkBoundaryCondition(bcc0[4], false, label1,
gismo::condition_type::dirichlet, patch4, index4, unknown, unkcomp,
domainDim, funcName1);
checkBoundaryCondition(bcc0[5], false, label1,
gismo::condition_type::dirichlet, patch5, index5, unknown, unkcomp,
domainDim, funcName1);
// check neumann conditions
std::string label2 = "Neumann";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc2 = sut.container(
label2);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc3 = sut.neumannSides();
unsigned elems3 = 2;
CHECK_EQUAL(elems3, bcc2.size());
CHECK_EQUAL(elems3, bcc3.size());
int patch6 = 1;
int index6 = 3;
int patch7 = 1;
int index7 = 4;
checkBoundaryCondition(bcc2[0], false, label2,
gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc3[0], false, label2,
gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc2[1], false, label2,
gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc3[1], false, label2,
gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
domainDim, funcName0);
// check robin conditions
std::string label3 = "Robin";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc4 = sut.container(
label3);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc5 = sut.robinSides();
unsigned elems4 = 0;
CHECK_EQUAL(elems4, bcc4.size());
CHECK_EQUAL(elems4, bcc5.size());
// check bctype_iterator
typedef typename gismo::gsBoundaryConditions<real_t>::const_bciterator bctype_it;
int c = 0;
for (bctype_it it = sut.beginAll(); it != sut.endAll(); ++it)
{
c++;
}
CHECK_EQUAL(3, c);
}
SUITE(gsBoundaryConditions_test)
{
TEST(gsBoundaryConditions_test_condition_type)
{
gismo::condition_type::type myType = gismo::condition_type::neumann;
CHECK_EQUAL(gismo::condition_type::neumann, myType);
CHECK_EQUAL(1, myType);
}
TEST(gsBoundaryConditions_test_function_expr)
{
int dim1 = 1;
std::string funcName1 = "tan(x)";
gsFunctionExpr<real_t> func1 = gsFunctionExpr<real_t>(funcName1, dim1);
int domainDim1 = func1.domainDim();
CHECK_EQUAL(dim1, domainDim1);
std::string expectedName1 = getFunctionExprExpectedString(funcName1);
std::string actualName1 = getFunctionExprActualString(func1);
CHECK_EQUAL(expectedName1, actualName1);
int dim2 = 2;
std::string funcName2 = "sin(x)*sin(y)";
gsFunctionExpr<real_t> func2 = gsFunctionExpr<real_t>(funcName2, dim2);
int domainDim2 = func2.domainDim();
CHECK_EQUAL(dim2, domainDim2);
std::string expectedName2 = getFunctionExprExpectedString(funcName2);
std::string actualName2 = getFunctionExprActualString(func2);
CHECK_EQUAL(expectedName2, actualName2);
}
TEST(gsBoundaryConditions_test_box_side)
{
int index1 = 1;
gismo::boxSide boxSide1 = gismo::boxSide(index1);
CHECK_EQUAL(index1, boxSide1.m_index);
std::string expect1 = getBoxSideExpectedString("west", index1);
std::string actual1 = getBoxSideActualString(boxSide1);
CHECK_EQUAL(expect1, actual1);
int index2 = 7;
gismo::boxSide boxSide2 = gismo::boxSide(index2);
CHECK_EQUAL(index2, boxSide2.m_index);
std::string expect2 = getBoxSideExpectedString("side", index2);
std::string actual2 = getBoxSideActualString(boxSide2);
CHECK_EQUAL(expect2, actual2);
}
TEST(gsBoundaryConditions_test_boundary_condition)
{
int dim1 = 1;
std::string funcName1 = "tan(x)";
int index1 = 1;
int index2 = 2;
gismo::boxSide boxSide1 = gismo::boxSide(index1);
gismo::boundary_condition<real_t>::function_ptr funcPtr1 =
gismo::memory::make_shared(
new gsFunctionExpr<real_t>(funcName1, dim1));
std::string label1 = "Dirichlet";
bool parametric1 = true;
int unknown1 = 1;
int unkcomp1 = 2;
gismo::boundary_condition<real_t> bound = gismo::boundary_condition<real_t>(
index2, boxSide1, funcPtr1, label1, unknown1, unkcomp1,
parametric1);
CHECK_EQUAL(parametric1, bound.m_parametric);
CHECK_EQUAL(label1, bound.m_label);
CHECK_EQUAL(gismo::condition_type::dirichlet, bound.m_type);
CHECK_EQUAL(index2, bound.ps.patch);
CHECK_EQUAL(index2, bound.patch());
CHECK_EQUAL(index1, bound.ps.m_index);
CHECK_EQUAL(funcPtr1, bound.m_function);
CHECK_EQUAL(unknown1, bound.m_unknown);
CHECK_EQUAL(unkcomp1, bound.m_unkcomp);
}
TEST(gsBoundaryConditions_test_box_corner)
{
int index1 = 3;
gismo::boxCorner c1 = gismo::boxCorner(index1);
CHECK_EQUAL(index1, c1.m_index);
}
TEST(gsBoundaryConditions_test_corner_value)
{
int index1 = 3;
gismo::boxCorner c1 = gismo::boxCorner(index1);
int p1 = 2;
real_t v1 = 3.0;
int u1 = 4;
gismo::corner_value<real_t> cornerVal1 = gismo::corner_value<real_t>(p1, c1,
v1, u1);
CHECK_EQUAL(c1, cornerVal1.corner);
CHECK_EQUAL(index1, cornerVal1.corner.m_index);
CHECK_EQUAL(p1, cornerVal1.patch);
CHECK_EQUAL(v1, cornerVal1.value);
CHECK_EQUAL(u1, cornerVal1.unknown);
}
/***
* test loading from bc.xml
*/
TEST(gsBoundaryConditions_load_from_bc_xml)
{
std::string path = GISMO_DATA_DIR;
path += "gsBoundaryConditions/bc.xml";
gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path);
checkGsBoundaryCondition(sut);
}
/***
* test loading from bc.xml and
* saving to bc2.xml
* and ensure that bc.xml and bc2.xml have
* the same content
*/
TEST(gsBoundaryConditions_save_load_bc_xml)
{
std::string path1 = GISMO_DATA_DIR;
path1 += "/gsBoundaryConditions/bc.xml";
std::string path2 = gismo::util::getTempPath();
path2 += "/bc2.xml";
gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path1);
gsBoundaryConditions_saveToFile(path2, sut);
gsBoundaryConditions<real_t> sut2 = gsBoundaryConditions_loadFromFile(path2);
checkGsBoundaryCondition(sut2);
}
}
<commit_msg>warn fix<commit_after>/** @file gsBoundaryConditions_test.cpp
@brief test gsPde/gsBoundaryConditions
This file is part of the G+Smo library.
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/.
Author(s): A. Mantzaflaris, H. Weiner
**/
#include "gismo_unittest.h"
#include <typeinfo>
#include <memory>
std::string getBoxSideExpectedString(std::string string, int index)
{
std::ostringstream stream;
std::string result;
stream << string << " (" << index << ")";
result = stream.str();
return result;
}
std::string getBoxSideActualString(gismo::boxSide boxSide)
{
std::ostringstream stream;
std::string result;
stream << boxSide;
result = stream.str();
return result;
}
std::string getFunctionExprExpectedString(std::string string)
{
std::ostringstream stream;
std::string result;
stream << "[ " << string << " ]";
result = stream.str();
return result;
}
std::string getFunctionExprActualString(gsFunctionExpr<real_t> func)
{
std::ostringstream stream;
std::string result;
func.print(stream);
result = stream.str();
return result;
}
gsBoundaryConditions<real_t> gsBoundaryConditions_loadFromFile(std::string path)
{
gsBoundaryConditions<real_t> result;
gsReadFile<>(path, result);
return result;
}
void gsBoundaryConditions_saveToFile(std::string path,
gsBoundaryConditions<real_t> &sut)
{
// clean-up before using file
remove(path.c_str());
// now save...
gsFileData<> write;
write << sut;
write.dump(path);
}
// create the same gsBoundary condition as in test-data file "bc.xml"
gsBoundaryConditions<real_t> createBcGsBoundaryConditiions()
{
// set-up
gsBoundaryConditions<real_t> result;
return result;
}
gsBoundaryConditions<real_t> createSimpleGsBoundaryConditiions()
{
gsBoundaryConditions<real_t> result;
return result;
}
gsFunctionExpr<real_t> getFunctionExpr(boundary_condition<real_t> bc)
{
bool funcTypeSame1 =
dynamic_cast<gsFunctionExpr<real_t>*>(bc.m_function.get());
CHECK(funcTypeSame1);
gsFunction<real_t>::Ptr ptr = bc.m_function;
gsFunctionExpr<real_t> * ptr2 =
dynamic_cast<gsFunctionExpr<real_t> *>(ptr.get());
gsFunctionExpr<real_t> result = *ptr2;
return result;
}
void checkBoundaryCondition(boundary_condition<real_t> bc, bool parametric,
std::string label, gismo::condition_type::type conditionType, int patch,
int index, int unknown, int unkcomp, int domainDim,
std::string funcName)
{
// check boundary condition itself
CHECK_EQUAL(parametric, bc.m_parametric);
CHECK_EQUAL(label, bc.m_label);
CHECK_EQUAL(conditionType, bc.m_type);
CHECK_EQUAL(patch, bc.ps.patch);
CHECK_EQUAL(index, bc.ps.m_index);
CHECK_EQUAL(unknown, bc.m_unknown);
CHECK_EQUAL(unkcomp, bc.m_unkcomp);
// check functionExpr
gismo::gsFunctionExpr<real_t> func = getFunctionExpr(bc);
CHECK_EQUAL(domainDim, func.domainDim());
std::string expectedName = getFunctionExprExpectedString(funcName);
std::string actualName = getFunctionExprActualString(func);
CHECK_EQUAL(expectedName, actualName);
}
void checkGsBoundaryCondition(const gsBoundaryConditions<real_t> & sut)
{
// check corner value(s)
gismo::gsBoundaryConditions<real_t>::cornerContainer c1 =
sut.cornerValues();
unsigned elems1 = 1;
CHECK_EQUAL(elems1, c1.size());
gismo::corner_value<real_t> cv1 = c1[0];
CHECK_EQUAL(0, cv1.corner);
CHECK_EQUAL(0, cv1.corner.m_index);
CHECK_EQUAL(0, cv1.patch);
CHECK_EQUAL(0.0, cv1.value);
CHECK_EQUAL(0, cv1.unknown);
// check dirichlet conditions
std::string label1 = "Dirichlet";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc0 = sut.container(
label1);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc1 =
sut.dirichletSides();
unsigned elems2 = 6;
CHECK_EQUAL(elems2, bcc0.size());
CHECK_EQUAL(elems2, bcc1.size());
// check boundary conditions themselves
std::string funcName0 = "0";
int patches[4] =
{ 0, 0, 1, 1 };
int indizes[4] =
{ 1, 3, 1, 2 };
int unknown = 0;
int unkcomp = 0;
int domainDim = 2;
for (int i = 0; i < 4; i++)
{
checkBoundaryCondition(bcc0[i], false, label1,
gismo::condition_type::dirichlet, patches[i], indizes[i],
unknown, unkcomp, domainDim, funcName0);
}
std::string funcName1 = "sin(pi*x)*sin(pi*y)";
int patch4 = 0;
int index4 = 2;
int patch5 = 0;
int index5 = 4;
checkBoundaryCondition(bcc0[4], false, label1,
gismo::condition_type::dirichlet, patch4, index4, unknown, unkcomp,
domainDim, funcName1);
checkBoundaryCondition(bcc0[5], false, label1,
gismo::condition_type::dirichlet, patch5, index5, unknown, unkcomp,
domainDim, funcName1);
// check neumann conditions
std::string label2 = "Neumann";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc2 = sut.container(
label2);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc3 = sut.neumannSides();
unsigned elems3 = 2;
CHECK_EQUAL(elems3, bcc2.size());
CHECK_EQUAL(elems3, bcc3.size());
int patch6 = 1;
int index6 = 3;
int patch7 = 1;
int index7 = 4;
checkBoundaryCondition(bcc2[0], false, label2,
gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc3[0], false, label2,
gismo::condition_type::neumann, patch6, index6, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc2[1], false, label2,
gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
domainDim, funcName0);
checkBoundaryCondition(bcc3[1], false, label2,
gismo::condition_type::neumann, patch7, index7, unknown, unkcomp,
domainDim, funcName0);
// check robin conditions
std::string label3 = "Robin";
gismo::gsBoundaryConditions<real_t>::bcContainer bcc4 = sut.container(
label3);
gismo::gsBoundaryConditions<real_t>::bcContainer bcc5 = sut.robinSides();
unsigned elems4 = 0;
CHECK_EQUAL(elems4, bcc4.size());
CHECK_EQUAL(elems4, bcc5.size());
// check bctype_iterator
typedef typename gismo::gsBoundaryConditions<real_t>::const_bciterator bctype_it;
int c = 0;
for (bctype_it it = sut.beginAll(); it != sut.endAll(); ++it)
{
c++;
}
CHECK_EQUAL(3, c);
}
SUITE(gsBoundaryConditions_test)
{
TEST(gsBoundaryConditions_test_condition_type)
{
gismo::condition_type::type myType = gismo::condition_type::neumann;
CHECK_EQUAL(gismo::condition_type::neumann, myType);
CHECK_EQUAL(1, myType);
}
TEST(gsBoundaryConditions_test_function_expr)
{
int dim1 = 1;
std::string funcName1 = "tan(x)";
gsFunctionExpr<real_t> func1 = gsFunctionExpr<real_t>(funcName1, dim1);
int domainDim1 = func1.domainDim();
CHECK_EQUAL(dim1, domainDim1);
std::string expectedName1 = getFunctionExprExpectedString(funcName1);
std::string actualName1 = getFunctionExprActualString(func1);
CHECK_EQUAL(expectedName1, actualName1);
int dim2 = 2;
std::string funcName2 = "sin(x)*sin(y)";
gsFunctionExpr<real_t> func2 = gsFunctionExpr<real_t>(funcName2, dim2);
int domainDim2 = func2.domainDim();
CHECK_EQUAL(dim2, domainDim2);
std::string expectedName2 = getFunctionExprExpectedString(funcName2);
std::string actualName2 = getFunctionExprActualString(func2);
CHECK_EQUAL(expectedName2, actualName2);
}
TEST(gsBoundaryConditions_test_box_side)
{
int index1 = 1;
gismo::boxSide boxSide1 = gismo::boxSide(index1);
CHECK_EQUAL(index1, boxSide1.m_index);
std::string expect1 = getBoxSideExpectedString("west", index1);
std::string actual1 = getBoxSideActualString(boxSide1);
CHECK_EQUAL(expect1, actual1);
int index2 = 7;
gismo::boxSide boxSide2 = gismo::boxSide(index2);
CHECK_EQUAL(index2, boxSide2.m_index);
std::string expect2 = getBoxSideExpectedString("side", index2);
std::string actual2 = getBoxSideActualString(boxSide2);
CHECK_EQUAL(expect2, actual2);
}
TEST(gsBoundaryConditions_test_boundary_condition)
{
int dim1 = 1;
std::string funcName1 = "tan(x)";
int index1 = 1;
int index2 = 2;
gismo::boxSide boxSide1 = gismo::boxSide(index1);
gismo::boundary_condition<real_t>::function_ptr funcPtr1 =
gismo::memory::make_shared(
new gsFunctionExpr<real_t>(funcName1, dim1));
std::string label1 = "Dirichlet";
bool parametric1 = true;
int unknown1 = 1;
int unkcomp1 = 2;
gismo::boundary_condition<real_t> bound = gismo::boundary_condition<real_t>(
index2, boxSide1, funcPtr1, label1, unknown1, unkcomp1,
parametric1);
CHECK_EQUAL(parametric1, bound.m_parametric);
CHECK_EQUAL(label1, bound.m_label);
CHECK_EQUAL(gismo::condition_type::dirichlet, bound.m_type);
CHECK_EQUAL(index2, bound.ps.patch);
CHECK_EQUAL(index2, bound.patch());
CHECK_EQUAL(index1, bound.ps.m_index);
CHECK_EQUAL(funcPtr1, bound.m_function);
CHECK_EQUAL(unknown1, bound.m_unknown);
CHECK_EQUAL(unkcomp1, bound.m_unkcomp);
}
TEST(gsBoundaryConditions_test_box_corner)
{
int index1 = 3;
gismo::boxCorner c1 = gismo::boxCorner(index1);
CHECK_EQUAL(index1, c1.m_index);
}
TEST(gsBoundaryConditions_test_corner_value)
{
int index1 = 3;
gismo::boxCorner c1 = gismo::boxCorner(index1);
int p1 = 2;
real_t v1 = 3.0;
int u1 = 4;
gismo::corner_value<real_t> cornerVal1 = gismo::corner_value<real_t>(p1, c1,
v1, u1);
CHECK_EQUAL(c1, cornerVal1.corner);
CHECK_EQUAL(index1, cornerVal1.corner.m_index);
CHECK_EQUAL(p1, cornerVal1.patch);
CHECK_EQUAL(v1, cornerVal1.value);
CHECK_EQUAL(u1, cornerVal1.unknown);
}
/***
* test loading from bc.xml
*/
TEST(gsBoundaryConditions_load_from_bc_xml)
{
std::string path = GISMO_DATA_DIR;
path += "gsBoundaryConditions/bc.xml";
gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path);
checkGsBoundaryCondition(sut);
}
/***
* test loading from bc.xml and
* saving to bc2.xml
* and ensure that bc.xml and bc2.xml have
* the same content
*/
TEST(gsBoundaryConditions_save_load_bc_xml)
{
std::string path1 = GISMO_DATA_DIR;
path1 += "/gsBoundaryConditions/bc.xml";
std::string path2 = gismo::util::getTempPath();
path2 += "/bc2.xml";
gsBoundaryConditions<real_t> sut = gsBoundaryConditions_loadFromFile(path1);
gsBoundaryConditions_saveToFile(path2, sut);
gsBoundaryConditions<real_t> sut2 = gsBoundaryConditions_loadFromFile(path2);
checkGsBoundaryCondition(sut2);
}
}
<|endoftext|> |
<commit_before>/**
* PUC-Rio 2015.2
* INF1339 - Computação Gráfica Tridimensional
* Professor: Waldemar Celes
* Gabriel de Quadros Ligneul 1212560
* Trabalho - Projeto de Grafo de Cena
*/
#include <algorithm>
#include <cmath>
#include <GL/gl.h>
#include <GL/glut.h>
#include "Manipulator.h"
#include "invertMatrix.h"
#include "vec3.h"
Manipulator::Manipulator() :
reference_{0, 0, 0},
matrix_{1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1},
inv_{1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1},
operation_{Operation::kNone},
x_{0},
y_{0},
v_{0, 0, 0},
invertX_{false},
invertY_{false} {
}
void Manipulator::Apply() {
glTranslatef(reference_[0], reference_[1], reference_[2]);
glMultMatrixf(matrix_.data());
glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}
void Manipulator::ApplyInv() {
glTranslatef(reference_[0], reference_[1], reference_[2]);
glMultMatrixf(inv_.data());
glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}
void Manipulator::SetReferencePoint(float x, float y, float z) {
reference_ = {x, y, z};
}
void Manipulator::GlutMouse(int button, int state, int x, int y) {
SetOperation<GLUT_LEFT_BUTTON, Operation::kRotation>(button, state, x, y);
SetOperation<GLUT_RIGHT_BUTTON, Operation::kZoom>(button, state, x, y);
}
void Manipulator::SetInvertAxis(bool invertX, bool invertY) {
invertX_ = invertX;
invertY_ = invertY;
}
void Manipulator::GlutMotion(int x, int y) {
if (operation_ == Operation::kNone)
return;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
if (operation_ == Operation::kRotation) {
vec3::Vf v = computeSphereCoordinates(x, y);
vec3::Vf w = vec3::cross(v_, v);
float theta = asin(vec3::norm(w)) * 180 / M_PI;
glRotatef(theta, w[0], w[1], w[2]);
v_ = v;
} else if (operation_ == Operation::kZoom) {
int vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
float dy = y - y_;
float f = dy / vp[3];
float scale = 1 + kZoomScale * f;
glScalef(scale, scale, scale);
}
glMultMatrixf(matrix_.data());
glGetFloatv(GL_MODELVIEW_MATRIX, matrix_.data());
gluInvertMatrix(matrix_.data(), inv_.data());
glPopMatrix();
x_ = x;
y_ = y;
}
template<int k_button, Manipulator::Operation k_operation>
void Manipulator::SetOperation(int button, int state, int x, int y) {
if (button == k_button) {
if (state == GLUT_DOWN && operation_ == Operation::kNone) {
operation_ = k_operation;
x_ = x;
y_ = y;
v_ = computeSphereCoordinates(x, y);
} else if (state == GLUT_UP && operation_ == k_operation) {
operation_ = Operation::kNone;
}
}
}
std::array<float, 3> Manipulator::computeSphereCoordinates(int x, int y) {
int vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
const float w = vp[2];
const float h = vp[3];
if (invertX_) x = w - x;
if (invertY_) y = h - y;
const float radius = std::min(w / 2.0f, h / 2.0f);
std::array<float, 3> v = {
(x - w / 2.0f) / radius,
(h - y - h / 2.0f) / radius,
};
const float dist = hypot(v[0], v[1]);
if (dist > 1.0f) {
v[0] /= dist;
v[1] /= dist;
v[2] = 0;
} else {
v[2] = sqrt(1 - v[0] * v[0] - v[1] * v[1]);
}
return v;
}
<commit_msg>Fixed the accumulation of the manipulator\'s inverse<commit_after>/**
* PUC-Rio 2015.2
* INF1339 - Computação Gráfica Tridimensional
* Professor: Waldemar Celes
* Gabriel de Quadros Ligneul 1212560
* Trabalho - Projeto de Grafo de Cena
*/
#include <algorithm>
#include <cmath>
#include <GL/gl.h>
#include <GL/glut.h>
#include "Manipulator.h"
#include "invertMatrix.h"
#include "vec3.h"
Manipulator::Manipulator() :
reference_{0, 0, 0},
matrix_{1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1},
inv_{1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1},
operation_{Operation::kNone},
x_{0},
y_{0},
v_{0, 0, 0},
invertX_{false},
invertY_{false} {
}
void Manipulator::Apply() {
glTranslatef(reference_[0], reference_[1], reference_[2]);
glMultMatrixf(matrix_.data());
glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
}
void Manipulator::ApplyInv() {
glTranslatef(-reference_[0], -reference_[1], -reference_[2]);
glMultMatrixf(inv_.data());
glTranslatef(reference_[0], reference_[1], reference_[2]);
}
void Manipulator::SetReferencePoint(float x, float y, float z) {
reference_ = {x, y, z};
}
void Manipulator::GlutMouse(int button, int state, int x, int y) {
SetOperation<GLUT_LEFT_BUTTON, Operation::kRotation>(button, state, x, y);
SetOperation<GLUT_RIGHT_BUTTON, Operation::kZoom>(button, state, x, y);
}
void Manipulator::SetInvertAxis(bool invertX, bool invertY) {
invertX_ = invertX;
invertY_ = invertY;
}
void Manipulator::GlutMotion(int x, int y) {
if (operation_ == Operation::kNone)
return;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
if (operation_ == Operation::kRotation) {
vec3::Vf v = computeSphereCoordinates(x, y);
vec3::Vf w = vec3::cross(v_, v);
float theta = asin(vec3::norm(w)) * 180 / M_PI;
glRotatef(theta, w[0], w[1], w[2]);
v_ = v;
} else if (operation_ == Operation::kZoom) {
int vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
float dy = y - y_;
float f = dy / vp[3];
float scale = 1 + kZoomScale * f;
glScalef(scale, scale, scale);
}
glMultMatrixf(matrix_.data());
glGetFloatv(GL_MODELVIEW_MATRIX, matrix_.data());
gluInvertMatrix(matrix_.data(), inv_.data());
glPopMatrix();
x_ = x;
y_ = y;
}
template<int k_button, Manipulator::Operation k_operation>
void Manipulator::SetOperation(int button, int state, int x, int y) {
if (button == k_button) {
if (state == GLUT_DOWN && operation_ == Operation::kNone) {
operation_ = k_operation;
x_ = x;
y_ = y;
v_ = computeSphereCoordinates(x, y);
} else if (state == GLUT_UP && operation_ == k_operation) {
operation_ = Operation::kNone;
}
}
}
std::array<float, 3> Manipulator::computeSphereCoordinates(int x, int y) {
int vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
const float w = vp[2];
const float h = vp[3];
if (invertX_) x = w - x;
if (invertY_) y = h - y;
const float radius = std::min(w / 2.0f, h / 2.0f);
std::array<float, 3> v = {
(x - w / 2.0f) / radius,
(h - y - h / 2.0f) / radius,
};
const float dist = hypot(v[0], v[1]);
if (dist > 1.0f) {
v[0] /= dist;
v[1] /= dist;
v[2] = 0;
} else {
v[2] = sqrt(1 - v[0] * v[0] - v[1] * v[1]);
}
return v;
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdio>
int main() {
float h, s;
scanf("%f", &h);
scanf("%f", &s);
printf("%.3f\n", h * s / 12.0);
}
<commit_msg>Format code<commit_after>#include <cmath>
#include <cstdio>
int main() {
float h, s;
scanf("%f", &h);
scanf("%f", &s);
printf("%.3f\n", h * s / 12.0);
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
int integer, number_of_digits, multiplier, current_digit;
std::map<int, std::string> int_roman_base;
std::string roman;
std::vector<int> splitted_integer;
int_roman_base[0] = "";
int_roman_base[1] = "I";
int_roman_base[2] = "II";
int_roman_base[3] = "III";
int_roman_base[4] = "IV";
int_roman_base[5] = "V";
int_roman_base[6] = "VI";
int_roman_base[7] = "VII";
int_roman_base[8] = "VIII";
int_roman_base[9] = "IX";
int_roman_base[10] = "X";
int_roman_base[20] = "XX";
int_roman_base[30] = "XXX";
int_roman_base[40] = "XL";
int_roman_base[50] = "L";
int_roman_base[60] = "LX";
int_roman_base[70] = "LXX";
int_roman_base[80] = "LXXX";
int_roman_base[90] = "XC";
int_roman_base[100] = "C";
int_roman_base[200] = "CC";
int_roman_base[300] = "CCC";
int_roman_base[400] = "CD";
int_roman_base[500] = "D";
int_roman_base[600] = "DC";
int_roman_base[700] = "DCC";
int_roman_base[800] = "DCCC";
int_roman_base[900] = "CM";
int_roman_base[1000] = "M";
while (std::cin >> integer) {
multiplier = 1;
roman = "";
while (integer > 0) {
current_digit = integer % 10;
integer /= 10;
roman = int_roman_base[current_digit * multiplier] + roman;
multiplier *= 10;
}
std::cout << roman << std::endl;
}
return 0;
}
<commit_msg>Remove unused code<commit_after>#include <cmath>
#include <iostream>
#include <map>
#include <string>
int main() {
int integer, multiplier, current_digit;
std::map<int, std::string> int_roman_base;
std::string roman;
int_roman_base[0] = "";
int_roman_base[1] = "I";
int_roman_base[2] = "II";
int_roman_base[3] = "III";
int_roman_base[4] = "IV";
int_roman_base[5] = "V";
int_roman_base[6] = "VI";
int_roman_base[7] = "VII";
int_roman_base[8] = "VIII";
int_roman_base[9] = "IX";
int_roman_base[10] = "X";
int_roman_base[20] = "XX";
int_roman_base[30] = "XXX";
int_roman_base[40] = "XL";
int_roman_base[50] = "L";
int_roman_base[60] = "LX";
int_roman_base[70] = "LXX";
int_roman_base[80] = "LXXX";
int_roman_base[90] = "XC";
int_roman_base[100] = "C";
int_roman_base[200] = "CC";
int_roman_base[300] = "CCC";
int_roman_base[400] = "CD";
int_roman_base[500] = "D";
int_roman_base[600] = "DC";
int_roman_base[700] = "DCC";
int_roman_base[800] = "DCCC";
int_roman_base[900] = "CM";
int_roman_base[1000] = "M";
while (std::cin >> integer) {
multiplier = 1;
roman = "";
while (integer > 0) {
current_digit = integer % 10;
integer /= 10;
roman = int_roman_base[current_digit * multiplier] + roman;
multiplier *= 10;
}
std::cout << roman << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "bench_framework.hpp"
#include "compare_images.hpp"
class test : public benchmark::test_case
{
std::shared_ptr<image_rgba8> im_;
public:
test(mapnik::parameters const& params)
: test_case(params) {
std::string filename("./benchmark/data/multicolor.png");
std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,"png"));
if (!reader.get())
{
throw mapnik::image_reader_exception("Failed to load: " + filename);
}
im_ = std::make_shared<image_rgba8>(reader->width(),reader->height());
reader->read(0,0,*im_);
}
bool validate() const
{
std::string expected("./benchmark/data/multicolor-hextree-expected.png");
std::string actual("./benchmark/data/multicolor-hextree-actual.png");
mapnik::save_to_file(*im_,actual, "png8:m=h:z=1");
return benchmark::compare_images(actual,expected);
}
bool operator()() const
{
std::string out;
for (std::size_t i=0;i<iterations_;++i) {
out.clear();
out = mapnik::save_to_string(*im_,"png8:m=h:z=1");
}
return true;
}
};
BENCHMARK(test,"encoding multicolor png")
<commit_msg>fix - add missing namespace qualifier.<commit_after>#include "bench_framework.hpp"
#include "compare_images.hpp"
class test : public benchmark::test_case
{
std::shared_ptr<mapnik::image_rgba8> im_;
public:
test(mapnik::parameters const& params)
: test_case(params) {
std::string filename("./benchmark/data/multicolor.png");
std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename,"png"));
if (!reader.get())
{
throw mapnik::image_reader_exception("Failed to load: " + filename);
}
im_ = std::make_shared<mapnik::image_rgba8>(reader->width(),reader->height());
reader->read(0,0,*im_);
}
bool validate() const
{
std::string expected("./benchmark/data/multicolor-hextree-expected.png");
std::string actual("./benchmark/data/multicolor-hextree-actual.png");
mapnik::save_to_file(*im_,actual, "png8:m=h:z=1");
return benchmark::compare_images(actual,expected);
}
bool operator()() const
{
std::string out;
for (std::size_t i=0;i<iterations_;++i) {
out.clear();
out = mapnik::save_to_string(*im_,"png8:m=h:z=1");
}
return true;
}
};
BENCHMARK(test,"encoding multicolor png")
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <compression.h>
#include <compression/delta.h>
#include <compression/xor.h>
#include <compression/flag.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
auto test_buffer_size=1024*1024*100;
uint8_t *buffer=new uint8_t[test_buffer_size];
dariadb::utils::Range rng{buffer,buffer+test_buffer_size};
//delta compression
std::fill(buffer,buffer+test_buffer_size,0);
{
const size_t count=1000000;
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::DeltaCompressor dc(bw);
std::vector<dariadb::Time> deltas{50,255,1024,2050};
dariadb::Time t=0;
auto start=clock();
for(size_t i=0;i<count;i++){
dc.append(t);
t+=deltas[i%deltas.size()];
if (t > std::numeric_limits<dariadb::Time>::max()){
t=0;
}
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"delta compressor : "<<elapsed<<std::endl;
auto w=dc.used_space();
auto sz=sizeof(dariadb::Time)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
}
{
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::DeltaDeCompressor dc(bw,0);
auto start=clock();
for(size_t i=1;i<1000000;i++){
dc.read();
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"delta decompressor : "<<elapsed<<std::endl;
}
//xor compression
std::fill(buffer,buffer+test_buffer_size,0);
{
const size_t count=1000000;
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::XorCompressor dc(bw);
dariadb::Value t=3.14;
auto start=clock();
for(size_t i=0;i<count;i++){
dc.append(t);
t*=1.5;
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"\nxor compressor : "<<elapsed<<std::endl;
auto w=dc.used_space();
auto sz=sizeof(dariadb::Time)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
}
{
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::XorDeCompressor dc(bw,0);
auto start=clock();
for(size_t i=1;i<1000000;i++){
dc.read();
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"xor decompressor : "<<elapsed<<std::endl;
}
{
const size_t count = 1000000;
auto start = clock();
for (size_t i = 0; i<count; i++) {
dariadb::compression::inner::flat_double_to_int(3.14);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "\nflat_double_to_int: " << elapsed << std::endl;
start = clock();
for (size_t i = 0; i<count; i++) {
dariadb::compression::inner::flat_int_to_double(0xfff);
}
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "flat_int_to_double: " << elapsed << std::endl;
}
{
const size_t count=1000000;
uint8_t* buf_begin=new uint8_t[test_buffer_size];
std::fill(buf_begin, buf_begin+test_buffer_size, 0);
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::CopmressedWriter cwr{bw};
auto start = clock();
for (size_t i = 0; i < count; i++) {
auto m = dariadb::Meas::empty();
m.time = static_cast<dariadb::Time>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count());
m.flag = dariadb::Flag(i);
m.value = dariadb::Value(i);
cwr.append(m);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "\ncompress writer : " << elapsed << std::endl;
auto w=cwr.used_space();
auto sz=sizeof(dariadb::Meas)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
auto m = dariadb::Meas::empty();
bw->reset_pos();
dariadb::compression::CopmressedReader crr{bw,m};
start = clock();
for (int i = 1; i < 1000000; i++) {
crr.read();
}
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "compress reader : " << elapsed << std::endl;
delete[] buf_begin;
}
delete[]buffer;
}
<commit_msg>compression bench refact.<commit_after>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <dariadb.h>
#include <compression.h>
#include <compression/delta.h>
#include <compression/xor.h>
#include <compression/flag.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
int main(int argc, char *argv[]) {
(void)argc;
(void)argv;
auto test_buffer_size=1024*1024*100;
uint8_t *buffer=new uint8_t[test_buffer_size];
dariadb::utils::Range rng{buffer,buffer+test_buffer_size};
//delta compression
std::fill(buffer,buffer+test_buffer_size,0);
{
const size_t count=1000000;
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::DeltaCompressor dc(bw);
std::vector<dariadb::Time> deltas{50,255,1024,2050};
dariadb::Time t=0;
auto start=clock();
for(size_t i=0;i<count;i++){
dc.append(t);
t+=deltas[i%deltas.size()];
if (t > std::numeric_limits<dariadb::Time>::max()){
t=0;
}
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"delta compressor : "<<elapsed<<std::endl;
auto w=dc.used_space();
auto sz=sizeof(dariadb::Time)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
}
{
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::DeltaDeCompressor dc(bw,0);
auto start=clock();
for(size_t i=1;i<1000000;i++){
dc.read();
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"delta decompressor : "<<elapsed<<std::endl;
}
//xor compression
std::fill(buffer,buffer+test_buffer_size,0);
{
const size_t count=1000000;
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::XorCompressor dc(bw);
dariadb::Value t=3.14;
auto start=clock();
for(size_t i=0;i<count;i++){
dc.append(t);
t*=1.5;
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"\nxor compressor : "<<elapsed<<std::endl;
auto w=dc.used_space();
auto sz=sizeof(dariadb::Time)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
}
{
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::XorDeCompressor dc(bw,0);
auto start=clock();
for(size_t i=1;i<1000000;i++){
dc.read();
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"xor decompressor : "<<elapsed<<std::endl;
}
{
const size_t count = 1000000;
auto start = clock();
for (size_t i = 0; i<count; i++) {
dariadb::compression::inner::flat_double_to_int(3.14);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "\nflat_double_to_int: " << elapsed << std::endl;
start = clock();
for (size_t i = 0; i<count; i++) {
dariadb::compression::inner::flat_int_to_double(0xfff);
}
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "flat_int_to_double: " << elapsed << std::endl;
}
{
const size_t count=1000000;
uint8_t* buf_begin=new uint8_t[test_buffer_size];
std::fill(buf_begin, buf_begin+test_buffer_size, 0);
auto bw=std::make_shared<dariadb::compression::BinaryBuffer>(rng);
dariadb::compression::CopmressedWriter cwr{bw};
auto start = clock();
for (size_t i = 0; i < count; i++) {
auto m = dariadb::Meas::empty();
m.time = static_cast<dariadb::Time>(dariadb::timeutil::current_time());
m.flag = dariadb::Flag(i);
m.value = dariadb::Value(i);
cwr.append(m);
}
auto elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "\ncompress writer : " << elapsed << std::endl;
auto w=cwr.used_space();
auto sz=sizeof(dariadb::Meas)*count;
std::cout<<"used space: "
<<(w*100.0)/(sz)<<"%"
<<std::endl;
auto m = dariadb::Meas::empty();
bw->reset_pos();
dariadb::compression::CopmressedReader crr{bw,m};
start = clock();
for (int i = 1; i < 1000000; i++) {
crr.read();
}
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "compress reader : " << elapsed << std::endl;
delete[] buf_begin;
}
delete[]buffer;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/text_path.hpp>
// agg
#define AGG_RENDERING_BUFFER row_ptr_cache<int8u>
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_conv_clip_polyline.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_vcgen_markers_term.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_vpgen_clip_polyline.h"
#include "agg_arrowhead.h"
// boost
#include <boost/utility.hpp>
// stl
#ifdef MAPNIK_DEBUG
#include <iostream>
#endif
#include <cmath>
namespace mapnik
{
class pattern_source : private boost::noncopyable
{
public:
pattern_source(image_data_32 const& pattern)
: pattern_(pattern) {}
unsigned int width() const
{
return pattern_.width();
}
unsigned int height() const
{
return pattern_.height();
}
agg::rgba8 pixel(int x, int y) const
{
unsigned c = pattern_(x,y);
return agg::rgba8(c & 0xff,
(c >> 8) & 0xff,
(c >> 16) & 0xff,
(c >> 24) & 0xff);
}
private:
image_data_32 const& pattern_;
};
template <typename T>
agg_renderer<T>::agg_renderer(Map const& m, T & pixmap, double scale_factor, unsigned offset_x, unsigned offset_y)
: feature_style_processor<agg_renderer>(m, scale_factor),
pixmap_(pixmap),
width_(pixmap_.width()),
height_(pixmap_.height()),
scale_factor_(scale_factor),
t_(m.width(),m.height(),m.get_current_extent(),offset_x,offset_y),
font_engine_(),
font_manager_(font_engine_),
detector_(box2d<double>(-m.buffer_size(), -m.buffer_size(), m.width() + m.buffer_size() ,m.height() + m.buffer_size())),
ras_ptr(new rasterizer)
{
boost::optional<color> const& bg = m.background();
if (bg) pixmap_.set_background(*bg);
boost::optional<std::string> const& image_filename = m.background_image();
if (image_filename)
{
boost::optional<mapnik::image_ptr> bg_image = mapnik::image_cache::instance()->find(*image_filename,true);
if (bg_image)
{
int w = (*bg_image)->width();
int h = (*bg_image)->height();
if ( w > 0 && h > 0)
{
// repeat background-image in both x,y
unsigned x_steps = unsigned(std::ceil(width_/double(w)));
unsigned y_steps = unsigned(std::ceil(height_/double(h)));
for (unsigned x=0;x<x_steps;++x)
{
for (unsigned y=0;y<y_steps;++y)
{
pixmap_.set_rectangle_alpha2(*(*bg_image), x*w, y*h, 1.0f);
}
}
}
}
}
#ifdef MAPNIK_DEBUG
std::clog << "scale=" << m.scale() << "\n";
#endif
}
template <typename T>
agg_renderer<T>::~agg_renderer() {}
template <typename T>
void agg_renderer<T>::start_map_processing(Map const& map)
{
#ifdef MAPNIK_DEBUG
std::clog << "start map processing bbox="
<< map.get_current_extent() << "\n";
#endif
ras_ptr->clip_box(0,0,width_,height_);
}
template <typename T>
void agg_renderer<T>::end_map_processing(Map const& )
{
#ifdef MAPNIK_DEBUG
std::clog << "end map processing\n";
#endif
}
template <typename T>
void agg_renderer<T>::start_layer_processing(layer const& lay)
{
#ifdef MAPNIK_DEBUG
std::clog << "start layer processing : " << lay.name() << "\n";
std::clog << "datasource = " << lay.datasource().get() << "\n";
#endif
if (lay.clear_label_cache())
{
detector_.clear();
}
}
template <typename T>
void agg_renderer<T>::end_layer_processing(layer const&)
{
#ifdef MAPNIK_DEBUG
std::clog << "end layer processing\n";
#endif
}
template class agg_renderer<image_32>;
}
<commit_msg>+ fix comment<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
// mapnik
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_cache.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/placement_finder.hpp>
#include <mapnik/config_error.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/text_path.hpp>
// agg
#define AGG_RENDERING_BUFFER row_ptr_cache<int8u>
#include "agg_rendering_buffer.h"
#include "agg_pixfmt_rgba.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_basics.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_conv_clip_polyline.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_vcgen_markers_term.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_vpgen_clip_polyline.h"
#include "agg_arrowhead.h"
// boost
#include <boost/utility.hpp>
// stl
#ifdef MAPNIK_DEBUG
#include <iostream>
#endif
#include <cmath>
namespace mapnik
{
class pattern_source : private boost::noncopyable
{
public:
pattern_source(image_data_32 const& pattern)
: pattern_(pattern) {}
unsigned int width() const
{
return pattern_.width();
}
unsigned int height() const
{
return pattern_.height();
}
agg::rgba8 pixel(int x, int y) const
{
unsigned c = pattern_(x,y);
return agg::rgba8(c & 0xff,
(c >> 8) & 0xff,
(c >> 16) & 0xff,
(c >> 24) & 0xff);
}
private:
image_data_32 const& pattern_;
};
template <typename T>
agg_renderer<T>::agg_renderer(Map const& m, T & pixmap, double scale_factor, unsigned offset_x, unsigned offset_y)
: feature_style_processor<agg_renderer>(m, scale_factor),
pixmap_(pixmap),
width_(pixmap_.width()),
height_(pixmap_.height()),
scale_factor_(scale_factor),
t_(m.width(),m.height(),m.get_current_extent(),offset_x,offset_y),
font_engine_(),
font_manager_(font_engine_),
detector_(box2d<double>(-m.buffer_size(), -m.buffer_size(), m.width() + m.buffer_size() ,m.height() + m.buffer_size())),
ras_ptr(new rasterizer)
{
boost::optional<color> const& bg = m.background();
if (bg) pixmap_.set_background(*bg);
boost::optional<std::string> const& image_filename = m.background_image();
if (image_filename)
{
boost::optional<mapnik::image_ptr> bg_image = mapnik::image_cache::instance()->find(*image_filename,true);
if (bg_image)
{
int w = (*bg_image)->width();
int h = (*bg_image)->height();
if ( w > 0 && h > 0)
{
// repeat background-image both vertically and horizontally
unsigned x_steps = unsigned(std::ceil(width_/double(w)));
unsigned y_steps = unsigned(std::ceil(height_/double(h)));
for (unsigned x=0;x<x_steps;++x)
{
for (unsigned y=0;y<y_steps;++y)
{
pixmap_.set_rectangle_alpha2(*(*bg_image), x*w, y*h, 1.0f);
}
}
}
}
}
#ifdef MAPNIK_DEBUG
std::clog << "scale=" << m.scale() << "\n";
#endif
}
template <typename T>
agg_renderer<T>::~agg_renderer() {}
template <typename T>
void agg_renderer<T>::start_map_processing(Map const& map)
{
#ifdef MAPNIK_DEBUG
std::clog << "start map processing bbox="
<< map.get_current_extent() << "\n";
#endif
ras_ptr->clip_box(0,0,width_,height_);
}
template <typename T>
void agg_renderer<T>::end_map_processing(Map const& )
{
#ifdef MAPNIK_DEBUG
std::clog << "end map processing\n";
#endif
}
template <typename T>
void agg_renderer<T>::start_layer_processing(layer const& lay)
{
#ifdef MAPNIK_DEBUG
std::clog << "start layer processing : " << lay.name() << "\n";
std::clog << "datasource = " << lay.datasource().get() << "\n";
#endif
if (lay.clear_label_cache())
{
detector_.clear();
}
}
template <typename T>
void agg_renderer<T>::end_layer_processing(layer const&)
{
#ifdef MAPNIK_DEBUG
std::clog << "end layer processing\n";
#endif
}
template class agg_renderer<image_32>;
}
<|endoftext|> |
<commit_before>#include "Background.hpp"
Background::Background() {
}
Background::Background(std::string lvlDesc) {
init(lvlDesc);
}
Background::~Background() {
}
void Background::init(std::string lvlDesc) {
readLevel(lvlDesc);
_doors.setPosition(0,0);
_background.setPosition(0,0);
_background.setTexture(_bTexture);
}
bool Background::colision(float x, float y){
return colision(sf::Vector2f(x,y));
}
bool Background::colision(sf::Vector2f pos) {
for(int i = 0; i < _boundaries.size(); ++i){
if(_boundaries[i].contains(pos)) return true;
}
return false;
}
void Background::draw(sf::RenderTarget *target){
target->draw(_background);
if(_doorOpenedL && _doorOpenedR){
_doors.setTexture(Resources::doors_OO);
}
else if( _doorOpenedL && ! _doorOpenedR){
_doors.setTexture(Resources::doors_OX);
}
else if(! _doorOpenedL && ! _doorOpenedR){
_doors.setTexture(Resources::doors_XX);
}
target->draw(_doors);
//DEBUG DRAW RED RECTANGLES
/* for(int i = 0; i < _boundaries.size(); ++i){
sf::RectangleShape RS(sf::Vector2f(_boundaries[i].width,_boundaries[i].height));
RS.setPosition(sf::Vector2f(_boundaries[i].left,_boundaries[i].top));
RS.setFillColor(sf::Color::Red);
target->draw(RS);
}
*/
}
bool Background::circleColision(sf::Vector2f pos, float rad) {
for(int i = 0; i < _boundaries.size(); ++i){
if( _boundaries[i].contains(pos.x+rad, pos.y)
|| _boundaries[i].contains(pos.x-rad, pos.y)
|| _boundaries[i].contains(pos.x, pos.y+rad)
|| _boundaries[i].contains(pos.x, pos.y-rad)
){
return true;
}
else if( getModule(pos, sf::Vector2f(_boundaries[i].left,_boundaries[i].top)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left+_boundaries[i].width,_boundaries[i].top)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left,_boundaries[i].top+_boundaries[i].height)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left+_boundaries[i].width,_boundaries[i].top+_boundaries[i].height)) < rad
){
return true;
}
}
return false;
}
//#include <iostream>
#include <complex>
using namespace std;
typedef complex<double> point;
double error=1e-7;
double prodesc(point p1,point p2)
{
return real(conj(p1)*p2);
}
double prodvec(point p1,point p2)
{
return imag(conj(p1)*p2);
}
point calculainterseccio(point p1,point v1,point p2,point v2)
{
return p1+(prodvec(p2-p1,v2)/prodvec(v1,v2))*v1;
}
pair<bool,point> intersecciosemirectasegment(point p1,point v1,point a,point b)
{
point p2=a;
point v2=b-a;
if (abs(prodvec(v1,v2))<error) return pair<bool,point> (false,0.0);
point interseccio=calculainterseccio(p1,v1,p2,v2);
if (prodesc(interseccio-p1,v1)<-error) return pair<bool,point> (false,0.0);
if (prodesc(interseccio-p2,v2)<-error) return pair<bool,point> (false,0.0);
if (prodesc(interseccio-b,v2)>error) return pair<bool,point> (false,0.0);
return pair<bool,point> (true,interseccio);
}
sf::Vector2i Background::getIntersection(sf::Vector2i position, sf::Vector2i mousePos){
sf::Vector2i ret(0,0);
pair <bool,point> result;
result.second.real(0);
result.second.imag(0);
result.first = false;
point pos(position.x, position.y);
point vec(mousePos.x - position.x, mousePos.y - position.y);
for(int i = 0; i < _boundaries.size(); ++i){
point a, b;
//TOP
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top));
b.real( double( _boundaries[i].left + _boundaries[i].width));
b.imag( double( _boundaries[i].top));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first &&
(abs(pos-result.second) > abs(pos- point(ret.x, ret.y))))
ret = sf::Vector2i(result.second.real(),result.second.imag());
/*
//LEFT
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top));
b.real( double( _boundaries[i].left));
b.imag( double( _boundaries[i].top - _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first) ret = sf::Vector2i(result.second.real(),result.second.imag());
//BOT
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top - _boundaries[i].height));
b.real( double( _boundaries[i].left+ _boundaries[i].width));
b.imag( double( _boundaries[i].top - _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first) ret = sf::Vector2i(result.second.real(),result.second.imag());
//RIGHT
result.first = false;
a.real( double( _boundaries[i].left+ _boundaries[i].width));
a.imag( double( _boundaries[i].top ));
b.real( double( _boundaries[i].left+ _boundaries[i].width));
b.imag( double( _boundaries[i].top - _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first) ret = sf::Vector2i(result.second.real(),result.second.imag());
*/
}
if(ret.x != 0) ret.x = mousePos.x;
if(ret.y != 0) ret.y = mousePos.y;
//retorna minim
return ret;
}
sf::Vector2i Background::getIntersection(sf::Vector2i mousePos){
sf::Vector2i ret(1,1);
for(int i = 0; i < _boundaries.size(); ++i){
if(_boundaries[i].contains(sf::Vector2f(mousePos.x,mousePos.y))){
ret.x = _boundaries[i].left;
ret.y = _boundaries[i].top;
// ret.x = mousePos.x;
// ret.y = mousePos.y;
}
}
return ret;
}
void Background::readLevel(std::string lvlDesc) {
std::string line;
std::ifstream myfile (LVLDESCIPTPATH+lvlDesc+".txt");
if (myfile.is_open()) {
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
if(! _bTexture.loadFromFile(TEXTURETPATH+line) ) std::cout << "error on loading bacground texture" << std::endl;
std::getline (myfile,line);
while (line[0] != '$') {
if(line[0] != '#'){
if(line == "doors"){
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
if(line == "OO"){
_doorOpenedL = _doorOpenedR = true;
}
else if(line == "OX"){
_doorOpenedL = true;
_doorOpenedR = false;
}
else if(line == "XX"){
_doorOpenedL = _doorOpenedR = false;
}
}
if(line == "boundaries"){
//log("boundaries");
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
while(line == "next"){
sf::FloatRect fr;
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.left = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.top = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.width = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.height = myStoi(line);
_boundaries.push_back(fr);
//read next that would be next if ther are more or end (or something else ) if it is done
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
}
}
}
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
}
//std::cout << "bg finishes with line " << line << std::endl;
myfile.close();
} else std::cout << "not oppened backgroound file " << lvlDesc << std::endl;
}
<commit_msg>fixed colisions omg so goood<commit_after>#include "Background.hpp"
Background::Background() {
}
Background::Background(std::string lvlDesc) {
init(lvlDesc);
}
Background::~Background() {
}
void Background::init(std::string lvlDesc) {
readLevel(lvlDesc);
_doors.setPosition(0,0);
_background.setPosition(0,0);
_background.setTexture(_bTexture);
}
bool Background::colision(float x, float y){
return colision(sf::Vector2f(x,y));
}
bool Background::colision(sf::Vector2f pos) {
for(int i = 0; i < _boundaries.size(); ++i){
if(_boundaries[i].contains(pos)) return true;
}
return false;
}
void Background::draw(sf::RenderTarget *target){
target->draw(_background);
if(_doorOpenedL && _doorOpenedR){
_doors.setTexture(Resources::doors_OO);
}
else if( _doorOpenedL && ! _doorOpenedR){
_doors.setTexture(Resources::doors_OX);
}
else if(! _doorOpenedL && ! _doorOpenedR){
_doors.setTexture(Resources::doors_XX);
}
target->draw(_doors);
//DEBUG DRAW RED RECTANGLES
/* for(int i = 0; i < _boundaries.size(); ++i){
sf::RectangleShape RS(sf::Vector2f(_boundaries[i].width,_boundaries[i].height));
RS.setPosition(sf::Vector2f(_boundaries[i].left,_boundaries[i].top));
RS.setFillColor(sf::Color::Red);
target->draw(RS);
}
*/
}
bool Background::circleColision(sf::Vector2f pos, float rad) {
for(int i = 0; i < _boundaries.size(); ++i){
if( _boundaries[i].contains(pos.x+rad, pos.y)
|| _boundaries[i].contains(pos.x-rad, pos.y)
|| _boundaries[i].contains(pos.x, pos.y+rad)
|| _boundaries[i].contains(pos.x, pos.y-rad)
){
return true;
}
else if( getModule(pos, sf::Vector2f(_boundaries[i].left,_boundaries[i].top)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left+_boundaries[i].width,_boundaries[i].top)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left,_boundaries[i].top+_boundaries[i].height)) < rad
|| getModule(pos, sf::Vector2f(_boundaries[i].left+_boundaries[i].width,_boundaries[i].top+_boundaries[i].height)) < rad
){
return true;
}
}
return false;
}
//#include <iostream>
#include <complex>
using namespace std;
typedef complex<double> point;
double error=1e-7;
double prodesc(point p1,point p2)
{
return real(conj(p1)*p2);
}
double prodvec(point p1,point p2)
{
return imag(conj(p1)*p2);
}
point calculainterseccio(point p1,point v1,point p2,point v2)
{
return p1+(prodvec(p2-p1,v2)/prodvec(v1,v2))*v1;
}
pair<bool,point> intersecciosemirectasegment(point p1,point v1,point a,point b)
{
point p2=a;
point v2=b-a;
if (abs(prodvec(v1,v2))<error) return pair<bool,point> (false,0.0);
point interseccio=calculainterseccio(p1,v1,p2,v2);
if (prodesc(interseccio-p1,v1)<-error) return pair<bool,point> (false,0.0);
if (prodesc(interseccio-p2,v2)<-error) return pair<bool,point> (false,0.0);
if (prodesc(interseccio-b,v2)>error) return pair<bool,point> (false,0.0);
return pair<bool,point> (true,interseccio);
}
sf::Vector2i Background::getIntersection(sf::Vector2i position, sf::Vector2i mousePos){
sf::Vector2i ret(-2000,-2000);
pair <bool,point> result;
result.second.real(0);
result.second.imag(0);
result.first = false;
point pos(position.x, position.y);
point vec(mousePos.x - position.x, mousePos.y - position.y);
for(int i = 0; i < _boundaries.size(); ++i){
point a, b;
//TOP
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top));
b.real( double( _boundaries[i].left + _boundaries[i].width));
b.imag( double( _boundaries[i].top));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first &&
(abs(pos-result.second) < abs(pos- point(ret.x, ret.y))))
ret = sf::Vector2i(result.second.real(),result.second.imag());
//LEFT
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top));
b.real( double( _boundaries[i].left));
b.imag( double( _boundaries[i].top + _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first &&
(abs(pos-result.second) < abs(pos- point(ret.x, ret.y))))
ret = sf::Vector2i(result.second.real(),result.second.imag());
//BOT
result.first = false;
a.real( double( _boundaries[i].left));
a.imag( double( _boundaries[i].top + _boundaries[i].height));
b.real( double( _boundaries[i].left+ _boundaries[i].width));
b.imag( double( _boundaries[i].top + _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first &&
(abs(pos-result.second) < abs(pos- point(ret.x, ret.y))))
ret = sf::Vector2i(result.second.real(),result.second.imag());
//RIGHT
result.first = false;
a.real( double( _boundaries[i].left+ _boundaries[i].width));
a.imag( double( _boundaries[i].top ));
b.real( double( _boundaries[i].left+ _boundaries[i].width));
b.imag( double( _boundaries[i].top + _boundaries[i].height));
result = intersecciosemirectasegment(pos, vec, a, b);
if(result.first &&
(abs(pos-result.second) < abs(pos- point(ret.x, ret.y))))
ret = sf::Vector2i(result.second.real(),result.second.imag());
}
// if(ret.x != 0) ret.x = mousePos.x;
// if(ret.y != 0) ret.y = mousePos.y;
//retorna minim
return ret;
}
sf::Vector2i Background::getIntersection(sf::Vector2i mousePos){
sf::Vector2i ret(1,1);
for(int i = 0; i < _boundaries.size(); ++i){
if(_boundaries[i].contains(sf::Vector2f(mousePos.x,mousePos.y))){
ret.x = _boundaries[i].left;
ret.y = _boundaries[i].top;
// ret.x = mousePos.x;
// ret.y = mousePos.y;
}
}
return ret;
}
void Background::readLevel(std::string lvlDesc) {
std::string line;
std::ifstream myfile (LVLDESCIPTPATH+lvlDesc+".txt");
if (myfile.is_open()) {
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
if(! _bTexture.loadFromFile(TEXTURETPATH+line) ) std::cout << "error on loading bacground texture" << std::endl;
std::getline (myfile,line);
while (line[0] != '$') {
if(line[0] != '#'){
if(line == "doors"){
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
if(line == "OO"){
_doorOpenedL = _doorOpenedR = true;
}
else if(line == "OX"){
_doorOpenedL = true;
_doorOpenedR = false;
}
else if(line == "XX"){
_doorOpenedL = _doorOpenedR = false;
}
}
if(line == "boundaries"){
//log("boundaries");
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
while(line == "next"){
sf::FloatRect fr;
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.left = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.top = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.width = myStoi(line);
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
fr.height = myStoi(line);
_boundaries.push_back(fr);
//read next that would be next if ther are more or end (or something else ) if it is done
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
}
}
}
std::getline (myfile,line);
while(line[0] == '#') std::getline (myfile,line);
}
//std::cout << "bg finishes with line " << line << std::endl;
myfile.close();
} else std::cout << "not oppened backgroound file " << lvlDesc << std::endl;
}
<|endoftext|> |
<commit_before>/*
* Based on The New Chronotext Toolkit
* Copyright (C) 2014, Ariel Malka - All rights reserved.
*
* Adaption to Alfons
* Copyright (C) 2015, Hannes Janetzek
*
* The following source-code is distributed under the Simplified BSD License.
*/
#include "textBatch.h"
#include "font.h"
#include "alfons.h"
#include "atlas.h"
#include "utils.h"
#include "logger.h"
#include <glm/vec2.hpp>
namespace alfons {
LineMetrics NO_METRICS;
TextBatch::TextBatch(GlyphAtlas& _atlas, MeshCallback& _mesh)
: m_atlas(_atlas), m_mesh(_mesh) {
m_clip.x1 = 0;
m_clip.y1 = 0;
m_clip.x2 = 0;
m_clip.y2 = 0;
}
void TextBatch::setClip(const Rect& _clipRect) {
m_clip = _clipRect;
m_hasClip = true;
}
void TextBatch::setClip(float x1, float y1, float x2, float y2) {
m_clip.x1 = x1;
m_clip.y1 = y1;
m_clip.x2 = x2;
m_clip.y2 = y2;
m_hasClip = true;
}
bool TextBatch::clip(Rect& _rect) const {
if (_rect.x1 > m_clip.x2 || _rect.x2 < m_clip.x1 ||
_rect.y1 > m_clip.y2 || _rect.y2 < m_clip.y1) {
return true;
}
return false;
}
bool TextBatch::clip(Quad& _quad) const {
return ((_quad.x1 > m_clip.x2 && _quad.x2 > m_clip.x2 &&
_quad.x3 > m_clip.x2 && _quad.x4 > m_clip.x2) ||
(_quad.y1 > m_clip.y2 && _quad.y2 > m_clip.y2 &&
_quad.y3 > m_clip.y2 && _quad.y4 > m_clip.y2) ||
(_quad.x1 < m_clip.x1 && _quad.x2 < m_clip.x1 &&
_quad.x3 < m_clip.x1 && _quad.x4 < m_clip.x1) ||
(_quad.y1 < m_clip.y1 && _quad.y2 < m_clip.y1 &&
_quad.y3 < m_clip.y1 && _quad.y4 < m_clip.y1));
return false;
}
void TextBatch::setupRect(const Shape& _shape, const glm::vec2& _position,
float _sizeRatio, Rect& _rect, AtlasGlyph& _atlasGlyph) {
glm::vec2 ul = _position + (_shape.position + _atlasGlyph.glyph->offset) * _sizeRatio;
_rect.x1 = ul.x;
_rect.y1 = ul.y;
_rect.x2 = ul.x + _atlasGlyph.glyph->size.x * _sizeRatio;
_rect.y2 = ul.y + _atlasGlyph.glyph->size.y * _sizeRatio;
}
void TextBatch::drawShape(const Font& _font, const Shape& _shape,
const glm::vec2& _position, float _scale,
LineMetrics& _metrics) {
AtlasGlyph atlasGlyph;
if (!m_atlas.getGlyph(_font, {_shape.face, _shape.codepoint}, atlasGlyph)) {
return;
}
Rect rect;
setupRect(_shape, _position, _scale, rect, atlasGlyph);
if (m_hasClip && clip(rect)) {
return;
}
m_mesh.drawGlyph(rect, atlasGlyph);
if (&_metrics != &NO_METRICS) {
_metrics.addExtents({rect.x1, rect.y1, rect.x2, rect.y2});
}
}
void TextBatch::drawTransformedShape(const Font& _font, const Shape& _shape,
const glm::vec2& _position, float _scale,
LineMetrics& _metrics) {
AtlasGlyph atlasGlyph;
if (!m_atlas.getGlyph(_font, {_shape.face, _shape.codepoint}, atlasGlyph)) {
return;
}
Rect rect;
setupRect(_shape, _position, _scale, rect, atlasGlyph);
Quad quad;
m_matrix.transformRect(rect, quad);
if (m_hasClip && clip(quad)) {
return;
}
m_mesh.drawGlyph(quad, atlasGlyph);
// FIXME: account for matrix transform
// return glm::vec4(atlasGlyph.glyph->u1,
// atlasGlyph.glyph->u2,
// atlasGlyph.glyph->v1,
// atlasGlyph.glyph->v2);
}
glm::vec2 TextBatch::draw(const LineLayout& _line, glm::vec2 _position, LineMetrics& _metrics) {
return draw(_line, 0, _line.shapes().size(), _position, _metrics);
}
glm::vec2 TextBatch::drawShapeRange(const LineLayout& _line, size_t _start, size_t _end,
glm::vec2 _position, LineMetrics& _metrics) {
for (size_t j = _start; j < _end; j++) {
auto& c = _line.shapes()[j];
if (!c.isSpace) {
drawShape(_line.font(), c, _position, _line.scale(), _metrics);
}
_position.x += _line.advance(c);
}
return _position;
}
glm::vec2 TextBatch::draw(const LineLayout& _line, size_t _start, size_t _end,
glm::vec2 _position, LineMetrics& _metrics) {
float startX = _position.x;
for (size_t j = _start; j < _end; j++) {
auto& c = _line.shapes()[j];
if (!c.isSpace) {
drawShape(_line.font(), c, _position, _line.scale(), _metrics);
}
_position.x += _line.advance(c);
if (c.mustBreak) {
_position.x = startX;
_position.y += _line.height();
}
}
_position.y += _line.height();
return _position;
}
glm::vec2 TextBatch::draw(const LineLayout& _line, glm::vec2 _position, float _width, LineMetrics& _metrics) {
if (_line.shapes().empty()) { return _position; }
float lineWidth = 0;
float startX = _position.x;
float adv = 0;
size_t shapeCount = 0;
float lastWidth = 0;
size_t lastShape = 0;
size_t startShape = 0;
for (auto& shape : _line.shapes()) {
if (!shape.cluster) {
shapeCount++;
lineWidth += _line.advance(shape);
continue;
}
shapeCount++;
lineWidth += _line.advance(shape);
// is break - or must break?
if (shape.canBreak || shape.mustBreak) {
lastShape = shapeCount;
lastWidth = lineWidth;
}
if (lastShape != 0 && (lineWidth > _width || shape.mustBreak)) {
auto& endShape = _line.shapes()[lastShape-1];
if (endShape.isSpace) {
lineWidth -= _line.advance(endShape);
lastWidth -= _line.advance(endShape);
}
adv = std::max(adv, drawShapeRange(_line, startShape, lastShape,
_position, _metrics).x);
lineWidth -= lastWidth;
startShape = lastShape;
lastShape = 0;
_position.y += _line.height();
_position.x = startX;
lineWidth = 0;
}
}
if (startShape < _line.shapes().size()-1) {
adv = std::max(adv, drawShapeRange(_line, startShape,
_line.shapes().size()-1,
_position, _metrics).x);
_position.y += _line.height();
}
_position.x = adv;
return _position;
}
float TextBatch::draw(const LineLayout& _line, const LineSampler& _path,
float _offsetX, float _offsetY) {
bool reverse = false; //(line.direction() == HB_DIRECTION_RTL);
float direction = reverse ? -1 : 1;
// float sampleSize = 0.1 * line.height();
auto& font = _line.font();
float scale = _line.scale();
glm::vec2 position;
float angle;
for (auto& shape : DirectionalRange(_line.shapes(), reverse)) {
//float half = 0.5f * line.advance(shape) * direction;
float half = 0.5f * shape.advance * scale * direction;
_offsetX += half;
if (!shape.isSpace) {
_path.get(_offsetX, position, angle);
m_matrix.setTranslation(position);
//m_matrix.rotateZ(path.offset2SampledAngle(offsetX, sampleSize));
m_matrix.rotateZ(angle);
drawTransformedShape(font, shape, -half, _offsetY, scale);
}
_offsetX += half;
}
return _offsetX;
}
}
<commit_msg>Fix linewrapping bug<commit_after>/*
* Based on The New Chronotext Toolkit
* Copyright (C) 2014, Ariel Malka - All rights reserved.
*
* Adaption to Alfons
* Copyright (C) 2015, Hannes Janetzek
*
* The following source-code is distributed under the Simplified BSD License.
*/
#include "textBatch.h"
#include "font.h"
#include "alfons.h"
#include "atlas.h"
#include "utils.h"
#include "logger.h"
#include <glm/vec2.hpp>
namespace alfons {
LineMetrics NO_METRICS;
TextBatch::TextBatch(GlyphAtlas& _atlas, MeshCallback& _mesh)
: m_atlas(_atlas), m_mesh(_mesh) {
m_clip.x1 = 0;
m_clip.y1 = 0;
m_clip.x2 = 0;
m_clip.y2 = 0;
}
void TextBatch::setClip(const Rect& _clipRect) {
m_clip = _clipRect;
m_hasClip = true;
}
void TextBatch::setClip(float x1, float y1, float x2, float y2) {
m_clip.x1 = x1;
m_clip.y1 = y1;
m_clip.x2 = x2;
m_clip.y2 = y2;
m_hasClip = true;
}
bool TextBatch::clip(Rect& _rect) const {
if (_rect.x1 > m_clip.x2 || _rect.x2 < m_clip.x1 ||
_rect.y1 > m_clip.y2 || _rect.y2 < m_clip.y1) {
return true;
}
return false;
}
bool TextBatch::clip(Quad& _quad) const {
return ((_quad.x1 > m_clip.x2 && _quad.x2 > m_clip.x2 &&
_quad.x3 > m_clip.x2 && _quad.x4 > m_clip.x2) ||
(_quad.y1 > m_clip.y2 && _quad.y2 > m_clip.y2 &&
_quad.y3 > m_clip.y2 && _quad.y4 > m_clip.y2) ||
(_quad.x1 < m_clip.x1 && _quad.x2 < m_clip.x1 &&
_quad.x3 < m_clip.x1 && _quad.x4 < m_clip.x1) ||
(_quad.y1 < m_clip.y1 && _quad.y2 < m_clip.y1 &&
_quad.y3 < m_clip.y1 && _quad.y4 < m_clip.y1));
return false;
}
void TextBatch::setupRect(const Shape& _shape, const glm::vec2& _position,
float _sizeRatio, Rect& _rect, AtlasGlyph& _atlasGlyph) {
glm::vec2 ul = _position + (_shape.position + _atlasGlyph.glyph->offset) * _sizeRatio;
_rect.x1 = ul.x;
_rect.y1 = ul.y;
_rect.x2 = ul.x + _atlasGlyph.glyph->size.x * _sizeRatio;
_rect.y2 = ul.y + _atlasGlyph.glyph->size.y * _sizeRatio;
}
void TextBatch::drawShape(const Font& _font, const Shape& _shape,
const glm::vec2& _position, float _scale,
LineMetrics& _metrics) {
AtlasGlyph atlasGlyph;
if (!m_atlas.getGlyph(_font, {_shape.face, _shape.codepoint}, atlasGlyph)) {
return;
}
Rect rect;
setupRect(_shape, _position, _scale, rect, atlasGlyph);
if (m_hasClip && clip(rect)) {
return;
}
m_mesh.drawGlyph(rect, atlasGlyph);
if (&_metrics != &NO_METRICS) {
_metrics.addExtents({rect.x1, rect.y1, rect.x2, rect.y2});
}
}
void TextBatch::drawTransformedShape(const Font& _font, const Shape& _shape,
const glm::vec2& _position, float _scale,
LineMetrics& _metrics) {
AtlasGlyph atlasGlyph;
if (!m_atlas.getGlyph(_font, {_shape.face, _shape.codepoint}, atlasGlyph)) {
return;
}
Rect rect;
setupRect(_shape, _position, _scale, rect, atlasGlyph);
Quad quad;
m_matrix.transformRect(rect, quad);
if (m_hasClip && clip(quad)) {
return;
}
m_mesh.drawGlyph(quad, atlasGlyph);
// FIXME: account for matrix transform
// return glm::vec4(atlasGlyph.glyph->u1,
// atlasGlyph.glyph->u2,
// atlasGlyph.glyph->v1,
// atlasGlyph.glyph->v2);
}
glm::vec2 TextBatch::draw(const LineLayout& _line, glm::vec2 _position, LineMetrics& _metrics) {
return draw(_line, 0, _line.shapes().size(), _position, _metrics);
}
glm::vec2 TextBatch::drawShapeRange(const LineLayout& _line, size_t _start, size_t _end,
glm::vec2 _position, LineMetrics& _metrics) {
for (size_t j = _start; j < _end; j++) {
auto& c = _line.shapes()[j];
if (!c.isSpace) {
drawShape(_line.font(), c, _position, _line.scale(), _metrics);
}
_position.x += _line.advance(c);
}
return _position;
}
glm::vec2 TextBatch::draw(const LineLayout& _line, size_t _start, size_t _end,
glm::vec2 _position, LineMetrics& _metrics) {
float startX = _position.x;
for (size_t j = _start; j < _end; j++) {
auto& c = _line.shapes()[j];
if (!c.isSpace) {
drawShape(_line.font(), c, _position, _line.scale(), _metrics);
}
_position.x += _line.advance(c);
if (c.mustBreak) {
_position.x = startX;
_position.y += _line.height();
}
}
_position.y += _line.height();
return _position;
}
glm::vec2 TextBatch::draw(const LineLayout& _line, glm::vec2 _position, float _width, LineMetrics& _metrics) {
if (_line.shapes().empty()) { return _position; }
float lineWidth = 0;
float startX = _position.x;
float adv = 0;
size_t shapeCount = 0;
float lastWidth = 0;
size_t lastShape = 0;
size_t startShape = 0;
for (auto& shape : _line.shapes()) {
if (!shape.cluster) {
shapeCount++;
lineWidth += _line.advance(shape);
continue;
}
shapeCount++;
lineWidth += _line.advance(shape);
// is break - or must break?
if (shape.canBreak || shape.mustBreak) {
lastShape = shapeCount;
lastWidth = lineWidth;
}
if (lastShape != 0 && (lineWidth > _width || shape.mustBreak)) {
auto& endShape = _line.shapes()[lastShape-1];
if (endShape.isSpace) {
lineWidth -= _line.advance(endShape);
lastWidth -= _line.advance(endShape);
}
adv = std::max(adv, drawShapeRange(_line, startShape, lastShape,
_position, _metrics).x);
lineWidth -= lastWidth;
startShape = lastShape;
lastShape = 0;
_position.y += _line.height();
_position.x = startX;
}
}
if (startShape < _line.shapes().size()-1) {
adv = std::max(adv, drawShapeRange(_line, startShape,
_line.shapes().size()-1,
_position, _metrics).x);
_position.y += _line.height();
}
_position.x = adv;
return _position;
}
float TextBatch::draw(const LineLayout& _line, const LineSampler& _path,
float _offsetX, float _offsetY) {
bool reverse = false; //(line.direction() == HB_DIRECTION_RTL);
float direction = reverse ? -1 : 1;
// float sampleSize = 0.1 * line.height();
auto& font = _line.font();
float scale = _line.scale();
glm::vec2 position;
float angle;
for (auto& shape : DirectionalRange(_line.shapes(), reverse)) {
//float half = 0.5f * line.advance(shape) * direction;
float half = 0.5f * shape.advance * scale * direction;
_offsetX += half;
if (!shape.isSpace) {
_path.get(_offsetX, position, angle);
m_matrix.setTranslation(position);
//m_matrix.rotateZ(path.offset2SampledAngle(offsetX, sampleSize));
m_matrix.rotateZ(angle);
drawTransformedShape(font, shape, -half, _offsetY, scale);
}
_offsetX += half;
}
return _offsetX;
}
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <qplatformdefs.h>
#include <LunaWebView.h>
#if defined(MEEGO_EDITION_HARMATTAN)
#include <MDeclarativeCache>
#define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
Q_DECL_EXPORT
#else
#define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif
int main(int argc, char** argv)
{
QApplication* app = NEW_QAPPLICATION(argc, argv);
qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");
QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
viewer.showFullScreen();
#else
viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
viewer.show();
#endif
return app->exec();
}
<commit_msg>Delete qApp instance on exit.<commit_after>#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <QScopedPointer>
#include <qplatformdefs.h>
#include <LunaWebView.h>
#if defined(MEEGO_EDITION_HARMATTAN)
#include <MDeclarativeCache>
#define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
Q_DECL_EXPORT
#else
#define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif
int main(int argc, char** argv)
{
QScopedPointer<QApplication> app(NEW_QAPPLICATION(argc, argv));
qmlRegisterType<LunaWebView>("Luna", 1, 0, "LunaWebView");
QDeclarativeView viewer;
#if defined(MEEGO_EDITION_HARMATTAN)
viewer.setSource(QUrl("qrc:/qml/main-harmattan.qml"));
viewer.showFullScreen();
#else
viewer.setSource(QUrl("qrc:/qml/main-desktop.qml"));
viewer.show();
#endif
return app->exec();
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkCudaFFTRampImageFilter.h"
#include "rtkCudaFFTRampImageFilter.hcu"
#include "rtkCudaCropImageFilter.h"
#include "rtkCudaCropImageFilter.hcu"
#include <itkMacro.h>
rtk::CudaFFTRampImageFilter
::CudaFFTRampImageFilter()
{
// We use FFTW for the kernel so we need to do the same thing as in the parent
#if defined(USE_FFTWF)
this->SetGreatestPrimeFactor(13);
#endif
}
void
rtk::CudaFFTRampImageFilter
::GPUGenerateData()
{
// Cuda typedefs
typedef itk::CudaImage<float,
ImageType::ImageDimension > FFTInputImageType;
typedef FFTInputImageType::Pointer FFTInputImagePointer;
typedef itk::CudaImage<std::complex<float>,
ImageType::ImageDimension > FFTOutputImageType;
typedef FFTOutputImageType::Pointer FFTOutputImagePointer;
// Non-cuda typedefs
typedef itk::Image<float,
ImageType::ImageDimension > FFTInputCPUImageType;
typedef FFTInputCPUImageType::Pointer FFTInputCPUImagePointer;
typedef itk::Image<std::complex<float>,
ImageType::ImageDimension > FFTOutputCPUImageType;
typedef FFTOutputCPUImageType::Pointer FFTOutputCPUImagePointer;
//this->AllocateOutputs();
// Pad image region
FFTInputImagePointer paddedImage;
paddedImage = PadInputImageRegion<FFTInputImageType, FFTOutputImageType>(this->GetInput()->GetRequestedRegion());
int3 inputDimension;
inputDimension.x = paddedImage->GetBufferedRegion().GetSize()[0];
inputDimension.y = paddedImage->GetBufferedRegion().GetSize()[1];
inputDimension.z = paddedImage->GetBufferedRegion().GetSize()[2];
if(inputDimension.y==1 && inputDimension.z>1) // Troubles cuda 3.2 and 4.0
std::swap(inputDimension.y, inputDimension.z);
// Get FFT ramp kernel. Must be itk::Image because GetFFTRampKernel is not
// compatible with itk::CudaImage + ITK 3.20.
FFTOutputCPUImagePointer fftK;
FFTOutputImageType::SizeType s = paddedImage->GetLargestPossibleRegion().GetSize();
fftK = this->GetFFTRampKernel<FFTInputCPUImageType, FFTOutputCPUImageType>(s[0], s[1]);
// Create the itk::CudaImage holding the kernel
FFTOutputImagePointer fftKCUDA = FFTOutputImageType::New();
fftKCUDA->SetRegions(fftK->GetLargestPossibleRegion());
fftKCUDA->Allocate();
// CUFFT scales by the number of element, correct for it in kernel.
// Also transfer the kernel from the itk::Image to the itk::CudaImage.
itk::ImageRegionIterator<FFTOutputCPUImageType> itKI(fftK, fftK->GetBufferedRegion() );
itk::ImageRegionIterator<FFTOutputImageType> itKO(fftKCUDA, fftKCUDA->GetBufferedRegion() );
FFTPrecisionType invNPixels = 1 / double(paddedImage->GetBufferedRegion().GetNumberOfPixels() );
while(!itKO.IsAtEnd() )
{
itKO.Set(itKI.Get() * invNPixels );
++itKI;
++itKO;
}
int2 kernelDimension;
kernelDimension.x = fftK->GetBufferedRegion().GetSize()[0];
kernelDimension.y = fftK->GetBufferedRegion().GetSize()[1];
CUDA_fft_convolution(inputDimension,
kernelDimension,
*(float**)(paddedImage->GetCudaDataManager()->GetGPUBufferPointer()),
*(float2**)(fftKCUDA->GetCudaDataManager()->GetGPUBufferPointer()));
// CUDA Cropping and Graft Output
typedef rtk::CudaCropImageFilter CropFilter;
CropFilter::Pointer cf = CropFilter::New();
OutputImageType::SizeType upCropSize, lowCropSize;
for(unsigned int i=0; i<OutputImageType::ImageDimension; i++)
{
lowCropSize[i] = this->GetOutput()->GetRequestedRegion().GetIndex()[i] -
paddedImage->GetLargestPossibleRegion().GetIndex()[i];
upCropSize[i] = paddedImage->GetLargestPossibleRegion().GetSize()[i] -
this->GetOutput()->GetRequestedRegion().GetSize()[i] -
lowCropSize[i];
}
cf->SetUpperBoundaryCropSize(upCropSize);
cf->SetLowerBoundaryCropSize(lowCropSize);
cf->SetInput(paddedImage);
cf->Update();
// We only want to graft the data. To do so, we copy the rest before grafting.
cf->GetOutput()->CopyInformation(this->GetOutput());
cf->GetOutput()->SetBufferedRegion(this->GetOutput()->GetBufferedRegion());
cf->GetOutput()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion());
this->GraftOutput(cf->GetOutput());
}
<commit_msg>ITK3 without FFTW has a kernel size that is too large for cufft, crop it in this case<commit_after>/*=========================================================================
*
* Copyright RTK Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "rtkCudaFFTRampImageFilter.h"
#include "rtkCudaFFTRampImageFilter.hcu"
#include "rtkCudaCropImageFilter.h"
#include "rtkCudaCropImageFilter.hcu"
#include <itkMacro.h>
rtk::CudaFFTRampImageFilter
::CudaFFTRampImageFilter()
{
// We use FFTW for the kernel so we need to do the same thing as in the parent
#if defined(USE_FFTWF)
this->SetGreatestPrimeFactor(13);
#endif
}
void
rtk::CudaFFTRampImageFilter
::GPUGenerateData()
{
// Cuda typedefs
typedef itk::CudaImage<float,
ImageType::ImageDimension > FFTInputImageType;
typedef FFTInputImageType::Pointer FFTInputImagePointer;
typedef itk::CudaImage<std::complex<float>,
ImageType::ImageDimension > FFTOutputImageType;
typedef FFTOutputImageType::Pointer FFTOutputImagePointer;
// Non-cuda typedefs
typedef itk::Image<float,
ImageType::ImageDimension > FFTInputCPUImageType;
typedef FFTInputCPUImageType::Pointer FFTInputCPUImagePointer;
typedef itk::Image<std::complex<float>,
ImageType::ImageDimension > FFTOutputCPUImageType;
typedef FFTOutputCPUImageType::Pointer FFTOutputCPUImagePointer;
//this->AllocateOutputs();
// Pad image region
FFTInputImagePointer paddedImage;
paddedImage = PadInputImageRegion<FFTInputImageType, FFTOutputImageType>(this->GetInput()->GetRequestedRegion());
int3 inputDimension;
inputDimension.x = paddedImage->GetBufferedRegion().GetSize()[0];
inputDimension.y = paddedImage->GetBufferedRegion().GetSize()[1];
inputDimension.z = paddedImage->GetBufferedRegion().GetSize()[2];
if(inputDimension.y==1 && inputDimension.z>1) // Troubles cuda 3.2 and 4.0
std::swap(inputDimension.y, inputDimension.z);
// Get FFT ramp kernel. Must be itk::Image because GetFFTRampKernel is not
// compatible with itk::CudaImage + ITK 3.20.
FFTOutputCPUImagePointer fftK;
FFTOutputImageType::SizeType s = paddedImage->GetLargestPossibleRegion().GetSize();
fftK = this->GetFFTRampKernel<FFTInputCPUImageType, FFTOutputCPUImageType>(s[0], s[1]);
// Create the itk::CudaImage holding the kernel
FFTOutputImageType::RegionType kreg = fftK->GetLargestPossibleRegion();
#if ITK_VERSION_MAJOR <= 3 && !defined(USE_FFTWF)
kreg.SetSize(0, kreg.GetSize(0)/2+1);
#endif
FFTOutputImagePointer fftKCUDA = FFTOutputImageType::New();
fftKCUDA->SetRegions(kreg);
fftKCUDA->Allocate();
// CUFFT scales by the number of element, correct for it in kernel.
// Also transfer the kernel from the itk::Image to the itk::CudaImage.
itk::ImageRegionIterator<FFTOutputCPUImageType> itKI(fftK, kreg);
itk::ImageRegionIterator<FFTOutputImageType> itKO(fftKCUDA, kreg);
FFTPrecisionType invNPixels = 1 / double(paddedImage->GetBufferedRegion().GetNumberOfPixels() );
while(!itKO.IsAtEnd() )
{
itKO.Set(itKI.Get() * invNPixels );
++itKI;
++itKO;
}
int2 kernelDimension;
kernelDimension.x = fftK->GetBufferedRegion().GetSize()[0];
kernelDimension.y = fftK->GetBufferedRegion().GetSize()[1];
CUDA_fft_convolution(inputDimension,
kernelDimension,
*(float**)(paddedImage->GetCudaDataManager()->GetGPUBufferPointer()),
*(float2**)(fftKCUDA->GetCudaDataManager()->GetGPUBufferPointer()));
// CUDA Cropping and Graft Output
typedef rtk::CudaCropImageFilter CropFilter;
CropFilter::Pointer cf = CropFilter::New();
OutputImageType::SizeType upCropSize, lowCropSize;
for(unsigned int i=0; i<OutputImageType::ImageDimension; i++)
{
lowCropSize[i] = this->GetOutput()->GetRequestedRegion().GetIndex()[i] -
paddedImage->GetLargestPossibleRegion().GetIndex()[i];
upCropSize[i] = paddedImage->GetLargestPossibleRegion().GetSize()[i] -
this->GetOutput()->GetRequestedRegion().GetSize()[i] -
lowCropSize[i];
}
cf->SetUpperBoundaryCropSize(upCropSize);
cf->SetLowerBoundaryCropSize(lowCropSize);
cf->SetInput(paddedImage);
cf->Update();
// We only want to graft the data. To do so, we copy the rest before grafting.
cf->GetOutput()->CopyInformation(this->GetOutput());
cf->GetOutput()->SetBufferedRegion(this->GetOutput()->GetBufferedRegion());
cf->GetOutput()->SetRequestedRegion(this->GetOutput()->GetRequestedRegion());
this->GraftOutput(cf->GetOutput());
}
<|endoftext|> |
<commit_before>/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include "MicroBit.h"
extern "C" {
#include "py/obj.h"
STATIC mp_obj_t this__init__(void) {
STATIC const char *this_text =
"The Zen of MicroPython, by Nicholas H.Tollervey\n"
"\n"
"Code,\n"
"Hack it,\n"
"Less is more,\n"
"Keep it simple,\n"
"Small is beautiful,\n"
"\n"
"Be brave! Break things! Learn and have fun!\n"
"Express yourself with MicroPython.\n"
"\n"
"Happy hacking! :-)\n";
mp_printf(&mp_plat_print, "%s", this_text);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(this___init___obj, this__init__);
STATIC mp_obj_t this_authors(void) {
/*
If you contribute code to this project, add your name here.
*/
STATIC const char *authors_text =
"MicroPython on the micro:bit is brought to you by:\n"
"Damien P.George and Nicholas H.Tollervey\n";
mp_printf(&mp_plat_print, "%s", authors_text);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(this_authors_obj, this_authors);
STATIC const mp_map_elem_t this_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_this) },
{ MP_OBJ_NEW_QSTR(MP_QSTR___init__), (mp_obj_t)&this___init___obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_authors), (mp_obj_t)&this_authors_obj },
};
STATIC MP_DEFINE_CONST_DICT(this_module_globals, this_module_globals_table);
const mp_obj_module_t this_module = {
.base = { &mp_type_module },
.name = MP_QSTR_this,
.globals = (mp_obj_dict_t*)&this_module_globals,
};
}
<commit_msg>Add Matthew Else to the author credits.<commit_after>/*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdio.h>
#include "MicroBit.h"
extern "C" {
#include "py/obj.h"
STATIC mp_obj_t this__init__(void) {
STATIC const char *this_text =
"The Zen of MicroPython, by Nicholas H.Tollervey\n"
"\n"
"Code,\n"
"Hack it,\n"
"Less is more,\n"
"Keep it simple,\n"
"Small is beautiful,\n"
"\n"
"Be brave! Break things! Learn and have fun!\n"
"Express yourself with MicroPython.\n"
"\n"
"Happy hacking! :-)\n";
mp_printf(&mp_plat_print, "%s", this_text);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(this___init___obj, this__init__);
STATIC mp_obj_t this_authors(void) {
/*
If you contribute code to this project, add your name here.
*/
STATIC const char *authors_text =
"MicroPython on the micro:bit is brought to you by:\n"
"Damien P.George, Matthew Else and Nicholas H.Tollervey.\n";
mp_printf(&mp_plat_print, "%s", authors_text);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(this_authors_obj, this_authors);
STATIC const mp_map_elem_t this_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_this) },
{ MP_OBJ_NEW_QSTR(MP_QSTR___init__), (mp_obj_t)&this___init___obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_authors), (mp_obj_t)&this_authors_obj },
};
STATIC MP_DEFINE_CONST_DICT(this_module_globals, this_module_globals_table);
const mp_obj_module_t this_module = {
.base = { &mp_type_module },
.name = MP_QSTR_this,
.globals = (mp_obj_dict_t*)&this_module_globals,
};
}
<|endoftext|> |
<commit_before>#include "adapted.h"
#include <boost/date_time/posix_time/posix_time.hpp>
namespace nt = navitia::type;
namespace bg = boost::gregorian;
namespace pt = boost::posix_time;
namespace navimake{
void delete_vj(types::VehicleJourney* vehicle_journey, const nt::Message& message, Data& data){
//TODO on duplique les validitypattern à tort et à travers la, va falloir les mutualiser
types::ValidityPattern* vp = NULL;
// if(vehicle_journey->adapted_validity_pattern == NULL){//on duplique le validity pattern
// vp = new types::ValidityPattern(*vehicle_journey->validity_pattern);
// }else{
vp = new types::ValidityPattern(*vehicle_journey->adapted_validity_pattern);
// }
data.validity_patterns.push_back(vp);
vehicle_journey->adapted_validity_pattern = vp;
for(size_t i=0; i < vp->days.size(); ++i){
bg::date current_date = vp->beginning_date + bg::days(i);
if(!vp->check(i) || current_date < message.application_period.begin().date()
|| current_date > message.application_period.end().date()){
continue;
}
pt::ptime begin(current_date, pt::seconds(vehicle_journey->stop_time_list.front()->departure_time));
//si le départ du vj est dans la plage d'appliation du message, on le supprime
if(message.is_applicable(pt::time_period(begin, pt::seconds(1)))){
vp->remove(current_date);
}
}
}
std::vector<types::StopTime*> get_stop_from_impact(const navitia::type::Message& message, bg::date current_date, std::vector<types::StopTime*> stoplist){
std::vector<types::StopTime*> result;
pt::ptime currenttime;
if(message.object_type == navitia::type::Type_e::StopPoint){
for(auto stop : stoplist){
currenttime = pt::ptime(current_date, pt::seconds(stop->departure_time));
if((stop->tmp_stop_point->uri == message.object_uri) && (message.is_applicable(pt::time_period(currenttime, pt::seconds(1))))){
result.push_back(stop);
}
}
}
if(message.object_type == navitia::type::Type_e::StopArea){
for(auto stop : stoplist){
currenttime = pt::ptime(current_date, pt::seconds(stop->departure_time));
if((stop->tmp_stop_point->stop_area->uri == message.object_uri)&& (message.is_applicable(pt::time_period(currenttime, pt::seconds(1))))){
result.push_back(stop);
}
}
}
return result;
}
void duplicate_vj(types::VehicleJourney* vehicle_journey, const nt::Message& message, Data& data){
types::VehicleJourney* vjadapted = NULL;
//on teste le validitypattern adapté car si le VJ est déjà supprimé le traitement n'est pas nécessaire
//faux car on ne pas appilquer 2 messages différent sur un même jour, mais comment détecter le vj supprimé
for(size_t i=0; i < vehicle_journey->validity_pattern->days.size(); ++i){
bg::date current_date = vehicle_journey->validity_pattern->beginning_date + bg::days(i);
if(!vehicle_journey->validity_pattern->check(i) || current_date < message.application_period.begin().date()
|| current_date > message.application_period.end().date()){
continue;
}
std::vector<types::StopTime*> impacted_stop = get_stop_from_impact(message, current_date, vehicle_journey->stop_time_list);
//ICI il faut récupérer la liste des vjadapted déjà crées actif sur current_date afin de leur appliquer le nouveau message
if((vjadapted == NULL) && (impacted_stop.size()!=0)){
vjadapted = new types::VehicleJourney(*vehicle_journey);
data.vehicle_journeys.push_back(vjadapted);
vjadapted->is_adapted = true;
vjadapted->theoric_vehicle_journey = vehicle_journey;
vehicle_journey->adapted_vehicle_journey_list.push_back(vjadapted);
vjadapted->validity_pattern = new types::ValidityPattern(vehicle_journey->validity_pattern->beginning_date);
data.validity_patterns.push_back(vjadapted->validity_pattern);
vjadapted->adapted_validity_pattern = new types::ValidityPattern(vjadapted->validity_pattern->beginning_date);
data.validity_patterns.push_back(vjadapted->adapted_validity_pattern);
}
for(auto stoptmp : impacted_stop){
std::vector<types::StopTime*>::iterator it = std::find(vjadapted->stop_time_list.begin(), vjadapted->stop_time_list.end(), stoptmp);
if(it != vjadapted->stop_time_list.end()){
vjadapted->stop_time_list.erase(it);
}
}
if(impacted_stop.size()!=0){
vjadapted->adapted_validity_pattern->add(current_date);
vehicle_journey->adapted_validity_pattern->remove(current_date);
}
}
}
void AtAdaptedLoader::init_map(const Data& data){
for(auto* vj : data.vehicle_journeys){
vj_map[vj->uri] = vj;
if(vj->tmp_line != NULL){
line_vj_map[vj->tmp_line->uri].push_back(vj);
if(vj->tmp_line->network != NULL){
network_vj_map[vj->tmp_line->network->uri].push_back(vj);
}
}
}
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::reconcile_impact_with_vj(const navitia::type::Message& message, const Data& data){
std::vector<types::VehicleJourney*> result;
if(message.object_type == navitia::type::Type_e::VehicleJourney){
if(vj_map.find(message.object_uri) != vj_map.end()){
//cas simple; le message pointe sur un seul vj
result.push_back(vj_map[message.object_uri]);
}
}
if(message.object_type == navitia::type::Type_e::Line){
if(line_vj_map.find(message.object_uri) != line_vj_map.end()){
//on à deja le mapping line => vjs
return line_vj_map[message.object_uri];
}
}
if(message.object_type == navitia::type::Type_e::Network){
if(network_vj_map.find(message.object_uri) != network_vj_map.end()){
return network_vj_map[message.object_uri];
}
}
//
return result;
}
void AtAdaptedLoader::apply(const std::map<std::string, std::vector<navitia::type::Message>>& messages, Data& data){
init_map(data);
//on construit la liste des impacts pour chacun des vj impacté
std::map<types::VehicleJourney*, std::vector<navitia::type::Message>> vj_messages_mapping;
for(const std::pair<std::string, std::vector<navitia::type::Message>> & message_list : messages){
for(auto message : message_list.second){
for(auto* vj : reconcile_impact_with_vj(message, data)){
vj_messages_mapping[vj].push_back(message);
}
}
}
std::cout << "nombre de VJ impactés: " << vj_messages_mapping.size() << std::endl;
for(auto pair : vj_messages_mapping){
apply_deletion_on_vj(pair.first, pair.second, data);
}
}
void AtAdaptedLoader::apply_deletion_on_vj(types::VehicleJourney* vehicle_journey, const std::vector<navitia::type::Message>& messages, Data& data){
for(nt::Message m : messages){
if(vehicle_journey->stop_time_list.size() > 0){
delete_vj(vehicle_journey, m, data);
}
}
}
void AtAdaptedLoader::apply_update_on_vj(types::VehicleJourney* vehicle_journey, const std::vector<navitia::type::Message>& messages, Data& data){
for(nt::Message m : messages){
if(vehicle_journey->stop_time_list.size() > 0){
duplicate_vj(vehicle_journey, m, data);
}
}
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::get_vj_from_stoppoint(std::string stoppoint_uri, const Data& data){
std::vector<types::VehicleJourney*> result;
for(navimake::types::JourneyPatternPoint* jpp : data.journey_pattern_points){
if(jpp->stop_point->uri == stoppoint_uri){
//le journeypattern posséde le StopPoint
navimake::types::JourneyPattern* jp = jpp->journey_pattern;
//on récupere tous les vj qui posséde ce journeypattern
for(navimake::types::VehicleJourney* vj : data.vehicle_journeys){
if(vj->journey_pattern == jp){
result.push_back(vj);
}
}
}
}
return result;
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::get_vj_from_impact(const navitia::type::Message& message, const Data& data){
std::vector<types::VehicleJourney*> result;
if(message.object_type == navitia::type::Type_e::StopPoint){
auto tmp = get_vj_from_stoppoint(message.object_uri, data);
std::vector<types::VehicleJourney*>::iterator it;
result.insert(it, tmp.begin(), tmp.end());
}
if(message.object_type == navitia::type::Type_e::StopArea){
for(navimake::types::StopPoint* stp : data.stop_points){
if(message.object_uri == stp->stop_area->uri){
auto tmp = get_vj_from_stoppoint(stp->uri, data);
std::vector<types::VehicleJourney*>::iterator it;
result.insert(it, tmp.begin(), tmp.end());
}
}
}
return result;
}
void AtAdaptedLoader::dispatch_message(const std::map<std::string, std::vector<navitia::type::Message>>& messages, const Data& data){
for(const std::pair<std::string, std::vector<navitia::type::Message>> & message_list : messages){
for(auto m : message_list.second){
//on recupére la liste des VJ associé(s) a l'uri du message
if(m.object_type == nt::Type_e::VehicleJourney || m.object_type == nt::Type_e::Route
|| m.object_type == nt::Type_e::Line || m.object_type == nt::Type_e::Network){
std::vector<navimake::types::VehicleJourney*> vj_list = reconcile_impact_with_vj(m, data);
//on parcourt la liste des VJ associée au message
//et on associe le message au vehiclejourney
for(auto vj : vj_list){
update_vj_map[vj].push_back(m);
}
}else{
if(m.object_type == nt::Type_e::JourneyPatternPoint || m.object_type == nt::Type_e::StopPoint
|| m.object_type == nt::Type_e::StopArea){
std::vector<navimake::types::VehicleJourney*> vj_list = get_vj_from_impact(m, data);
for(auto vj : vj_list){
duplicate_vj_map[vj].push_back(m);
}
}
}
}
}
}
void AtAdaptedLoader::apply_b(const std::map<std::string, std::vector<navitia::type::Message>>& messages, Data& data){
init_map(data);
dispatch_message(messages, data);
std::cout << "nombre de VJ adaptés: " << update_vj_map.size() << std::endl;
for(auto pair : update_vj_map){
apply_deletion_on_vj(pair.first, pair.second, data);
}
for(auto pair : duplicate_vj_map){
apply_update_on_vj(pair.first, pair.second, data);
}
}
}//namespace
<commit_msg>adapted : non application des messages sur vehiclejourney déjà supprimé<commit_after>#include "adapted.h"
#include <boost/date_time/posix_time/posix_time.hpp>
namespace nt = navitia::type;
namespace bg = boost::gregorian;
namespace pt = boost::posix_time;
namespace navimake{
void delete_vj(types::VehicleJourney* vehicle_journey, const nt::Message& message, Data& data){
//TODO on duplique les validitypattern à tort et à travers la, va falloir les mutualiser
types::ValidityPattern* vp = NULL;
// if(vehicle_journey->adapted_validity_pattern == NULL){//on duplique le validity pattern
// vp = new types::ValidityPattern(*vehicle_journey->validity_pattern);
// }else{
vp = new types::ValidityPattern(*vehicle_journey->adapted_validity_pattern);
// }
data.validity_patterns.push_back(vp);
vehicle_journey->adapted_validity_pattern = vp;
for(size_t i=0; i < vp->days.size(); ++i){
bg::date current_date = vp->beginning_date + bg::days(i);
if(!vp->check(i) || current_date < message.application_period.begin().date()
|| current_date > message.application_period.end().date()){
continue;
}
pt::ptime begin(current_date, pt::seconds(vehicle_journey->stop_time_list.front()->departure_time));
//si le départ du vj est dans la plage d'appliation du message, on le supprime
if(message.is_applicable(pt::time_period(begin, pt::seconds(1)))){
vp->remove(current_date);
}
}
}
std::vector<types::StopTime*> get_stop_from_impact(const navitia::type::Message& message, bg::date current_date, std::vector<types::StopTime*> stoplist){
std::vector<types::StopTime*> result;
pt::ptime currenttime;
if(message.object_type == navitia::type::Type_e::StopPoint){
for(auto stop : stoplist){
currenttime = pt::ptime(current_date, pt::seconds(stop->departure_time));
if((stop->tmp_stop_point->uri == message.object_uri) && (message.is_applicable(pt::time_period(currenttime, pt::seconds(1))))){
result.push_back(stop);
}
}
}
if(message.object_type == navitia::type::Type_e::StopArea){
for(auto stop : stoplist){
currenttime = pt::ptime(current_date, pt::seconds(stop->departure_time));
if((stop->tmp_stop_point->stop_area->uri == message.object_uri)&& (message.is_applicable(pt::time_period(currenttime, pt::seconds(1))))){
result.push_back(stop);
}
}
}
return result;
}
void duplicate_vj(types::VehicleJourney* vehicle_journey, const nt::Message& message, Data& data){
types::VehicleJourney* vjadapted = NULL;
//on teste le validitypattern adapté car si le VJ est déjà supprimé le traitement n'est pas nécessaire
//faux car on ne pas appilquer 2 messages différent sur un même jour, mais comment détecter le vj supprimé
for(size_t i=0; i < vehicle_journey->validity_pattern->days.size(); ++i){
bg::date current_date = vehicle_journey->validity_pattern->beginning_date + bg::days(i);
if(!vehicle_journey->validity_pattern->check(i) ||
//le vj a été supprimé par un message de suppression
(!vehicle_journey->adapted_validity_pattern->check((current_date- vehicle_journey->adapted_validity_pattern->beginning_date).days()) && (vehicle_journey->adapted_vehicle_journey_list.size()==0))
|| current_date < message.application_period.begin().date()
|| current_date > message.application_period.end().date()){
continue;
}
std::vector<types::StopTime*> impacted_stop = get_stop_from_impact(message, current_date, vehicle_journey->stop_time_list);
//ICI il faut récupérer la liste des vjadapted déjà crées actif sur current_date afin de leur appliquer le nouveau message
if((vjadapted == NULL) && (impacted_stop.size()!=0)){
vjadapted = new types::VehicleJourney(*vehicle_journey);
data.vehicle_journeys.push_back(vjadapted);
vjadapted->is_adapted = true;
vjadapted->theoric_vehicle_journey = vehicle_journey;
vehicle_journey->adapted_vehicle_journey_list.push_back(vjadapted);
vjadapted->validity_pattern = new types::ValidityPattern(vehicle_journey->validity_pattern->beginning_date);
data.validity_patterns.push_back(vjadapted->validity_pattern);
vjadapted->adapted_validity_pattern = new types::ValidityPattern(vjadapted->validity_pattern->beginning_date);
data.validity_patterns.push_back(vjadapted->adapted_validity_pattern);
}
for(auto stoptmp : impacted_stop){
std::vector<types::StopTime*>::iterator it = std::find(vjadapted->stop_time_list.begin(), vjadapted->stop_time_list.end(), stoptmp);
if(it != vjadapted->stop_time_list.end()){
vjadapted->stop_time_list.erase(it);
}
}
if(impacted_stop.size()!=0){
vjadapted->adapted_validity_pattern->add(current_date);
vehicle_journey->adapted_validity_pattern->remove(current_date);
}
}
}
void AtAdaptedLoader::init_map(const Data& data){
for(auto* vj : data.vehicle_journeys){
vj_map[vj->uri] = vj;
if(vj->tmp_line != NULL){
line_vj_map[vj->tmp_line->uri].push_back(vj);
if(vj->tmp_line->network != NULL){
network_vj_map[vj->tmp_line->network->uri].push_back(vj);
}
}
}
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::reconcile_impact_with_vj(const navitia::type::Message& message, const Data& data){
std::vector<types::VehicleJourney*> result;
if(message.object_type == navitia::type::Type_e::VehicleJourney){
if(vj_map.find(message.object_uri) != vj_map.end()){
//cas simple; le message pointe sur un seul vj
result.push_back(vj_map[message.object_uri]);
}
}
if(message.object_type == navitia::type::Type_e::Line){
if(line_vj_map.find(message.object_uri) != line_vj_map.end()){
//on à deja le mapping line => vjs
return line_vj_map[message.object_uri];
}
}
if(message.object_type == navitia::type::Type_e::Network){
if(network_vj_map.find(message.object_uri) != network_vj_map.end()){
return network_vj_map[message.object_uri];
}
}
//
return result;
}
void AtAdaptedLoader::apply(const std::map<std::string, std::vector<navitia::type::Message>>& messages, Data& data){
init_map(data);
//on construit la liste des impacts pour chacun des vj impacté
std::map<types::VehicleJourney*, std::vector<navitia::type::Message>> vj_messages_mapping;
for(const std::pair<std::string, std::vector<navitia::type::Message>> & message_list : messages){
for(auto message : message_list.second){
for(auto* vj : reconcile_impact_with_vj(message, data)){
vj_messages_mapping[vj].push_back(message);
}
}
}
std::cout << "nombre de VJ impactés: " << vj_messages_mapping.size() << std::endl;
for(auto pair : vj_messages_mapping){
apply_deletion_on_vj(pair.first, pair.second, data);
}
}
void AtAdaptedLoader::apply_deletion_on_vj(types::VehicleJourney* vehicle_journey, const std::vector<navitia::type::Message>& messages, Data& data){
for(nt::Message m : messages){
if(vehicle_journey->stop_time_list.size() > 0){
delete_vj(vehicle_journey, m, data);
}
}
}
void AtAdaptedLoader::apply_update_on_vj(types::VehicleJourney* vehicle_journey, const std::vector<navitia::type::Message>& messages, Data& data){
for(nt::Message m : messages){
if(vehicle_journey->stop_time_list.size() > 0){
duplicate_vj(vehicle_journey, m, data);
}
}
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::get_vj_from_stoppoint(std::string stoppoint_uri, const Data& data){
std::vector<types::VehicleJourney*> result;
for(navimake::types::JourneyPatternPoint* jpp : data.journey_pattern_points){
if(jpp->stop_point->uri == stoppoint_uri){
//le journeypattern posséde le StopPoint
navimake::types::JourneyPattern* jp = jpp->journey_pattern;
//on récupere tous les vj qui posséde ce journeypattern
for(navimake::types::VehicleJourney* vj : data.vehicle_journeys){
if(vj->journey_pattern == jp){
result.push_back(vj);
}
}
}
}
return result;
}
std::vector<types::VehicleJourney*> AtAdaptedLoader::get_vj_from_impact(const navitia::type::Message& message, const Data& data){
std::vector<types::VehicleJourney*> result;
if(message.object_type == navitia::type::Type_e::StopPoint){
auto tmp = get_vj_from_stoppoint(message.object_uri, data);
std::vector<types::VehicleJourney*>::iterator it;
result.insert(it, tmp.begin(), tmp.end());
}
if(message.object_type == navitia::type::Type_e::StopArea){
for(navimake::types::StopPoint* stp : data.stop_points){
if(message.object_uri == stp->stop_area->uri){
auto tmp = get_vj_from_stoppoint(stp->uri, data);
std::vector<types::VehicleJourney*>::iterator it;
result.insert(it, tmp.begin(), tmp.end());
}
}
}
return result;
}
void AtAdaptedLoader::dispatch_message(const std::map<std::string, std::vector<navitia::type::Message>>& messages, const Data& data){
for(const std::pair<std::string, std::vector<navitia::type::Message>> & message_list : messages){
for(auto m : message_list.second){
//on recupére la liste des VJ associé(s) a l'uri du message
if(m.object_type == nt::Type_e::VehicleJourney || m.object_type == nt::Type_e::Route
|| m.object_type == nt::Type_e::Line || m.object_type == nt::Type_e::Network){
std::vector<navimake::types::VehicleJourney*> vj_list = reconcile_impact_with_vj(m, data);
//on parcourt la liste des VJ associée au message
//et on associe le message au vehiclejourney
for(auto vj : vj_list){
update_vj_map[vj].push_back(m);
}
}else{
if(m.object_type == nt::Type_e::JourneyPatternPoint || m.object_type == nt::Type_e::StopPoint
|| m.object_type == nt::Type_e::StopArea){
std::vector<navimake::types::VehicleJourney*> vj_list = get_vj_from_impact(m, data);
for(auto vj : vj_list){
duplicate_vj_map[vj].push_back(m);
}
}
}
}
}
}
void AtAdaptedLoader::apply_b(const std::map<std::string, std::vector<navitia::type::Message>>& messages, Data& data){
init_map(data);
dispatch_message(messages, data);
std::cout << "nombre de VJ adaptés: " << update_vj_map.size() << std::endl;
for(auto pair : update_vj_map){
apply_deletion_on_vj(pair.first, pair.second, data);
}
for(auto pair : duplicate_vj_map){
apply_update_on_vj(pair.first, pair.second, data);
}
}
}//namespace
<|endoftext|> |
<commit_before>#include "BigFont.h"
#include "BigCrystal.h"
BigCrystal::BigCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7) :
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7) :
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3) :
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3) :
LiquidCrystal(rs, enable, d0, d1, d2, d3) {
init();
}
/* Creates custom font shapes for LCD characters 0 through to 7
* used in displaying big fonts
*/
void BigCrystal::init() {
for (uint8_t i = 0; i < 8; i++) {
uint8_t customChar[8];
for (uint8_t j = 0; j < 8; j++) {
customChar[j] = pgm_read_byte(BF_fontShapes + (i * 8) + j);
}
createChar(i, customChar);
}
}
uint8_t BigCrystal::widthBig(char c) {
if (!supported(c)) {
return 0; // we don't support characters outside this range
}
char ch = toUpperCase(c);
uint8_t tableCode;
uint8_t index;
getTableCodeAndIndex(ch, tableCode, index);
uint8_t width = getWidthFromTableCode(tableCode);
if (width == 0) {
return 0;
}
return width + 1; // add one for space after character
}
uint8_t BigCrystal::writeBig(char c, uint8_t col, uint8_t row) {
if (!supported(c)) {
return 0; // we don't support characters outside this range
}
char ch = toUpperCase(c);
uint8_t tableCode;
uint8_t index;
getTableCodeAndIndex(ch, tableCode, index);
uint8_t* table = getTable(tableCode);
uint8_t width = getWidthFromTableCode(tableCode);
int tableOffset = (width * 2) * index;
// Write first row
setCursor(col, row);
for (uint8_t i = 0; i < width; i++) {
write(pgm_read_byte_near(table + tableOffset + i));
}
// Write second row
setCursor(col, row + 1);
for (uint8_t i = 0; i < width; i++) {
write(pgm_read_byte_near(table + tableOffset + width + i));
}
// Clear last column
clearColumn(col + width, row);
return width + 1; // add one for the cleared column
}
uint8_t BigCrystal::printBig(char *str, uint8_t col, uint8_t row) {
uint8_t width = 0;
char *c = str;
while (*c != '\0') {
width += writeBig(*c, col + width, row);
*c++;
}
return width;
}
void BigCrystal::getTableCodeAndIndex(char c, uint8_t& tableCode, uint8_t& index) {
uint8_t tableAndIndex = pgm_read_byte_near(BF_characters + c - ' ');
// Top 3 bits are the table, bottom 5 are index into table
tableCode = (uint8_t) ((tableAndIndex & 0xE0) >> 5);
index = (uint8_t) (tableAndIndex & 0x1F);
}
uint8_t* BigCrystal::getTable(uint8_t tableCode) {
switch (tableCode) {
case BF_WIDTH1_TABLE:
return BF_width1;
case BF_WIDTH2_TABLE:
return BF_width2;
case BF_WIDTH3_TABLE:
return BF_width3;
case BF_WIDTH4_TABLE:
return BF_width4;
case BF_WIDTH5_TABLE:
return BF_width5;
case BF_WIDTH3_SYMBOLS_TABLE:
return BF_width3Symbols;
default:
return NULL;
}
}
uint8_t BigCrystal::getWidthFromTableCode(uint8_t tableCode) {
if (tableCode == BF_WIDTH3_SYMBOLS_TABLE) {
return 3;
}
return tableCode;
}
bool BigCrystal::supported(char c) {
return (c >= ' ' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
char BigCrystal::toUpperCase(char c) {
if (c >= 'a' && c <= 'z') {
return c &0x5f;
}
return c;
}
void BigCrystal::clearColumn(uint8_t col, uint8_t row) {
setCursor(col, row);
write(0x20);
setCursor(col, row + 1);
write(0x20);
}
<commit_msg>Gracefully handle the case if the character table is null.<commit_after>#include "BigFont.h"
#include "BigCrystal.h"
BigCrystal::BigCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7) :
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7) :
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3) :
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3) {
init();
}
BigCrystal::BigCrystal(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3) :
LiquidCrystal(rs, enable, d0, d1, d2, d3) {
init();
}
/* Creates custom font shapes for LCD characters 0 through to 7
* used in displaying big fonts
*/
void BigCrystal::init() {
for (uint8_t i = 0; i < 8; i++) {
uint8_t customChar[8];
for (uint8_t j = 0; j < 8; j++) {
customChar[j] = pgm_read_byte(BF_fontShapes + (i * 8) + j);
}
createChar(i, customChar);
}
}
uint8_t BigCrystal::widthBig(char c) {
if (!supported(c)) {
return 0; // we don't support characters outside this range
}
char ch = toUpperCase(c);
uint8_t tableCode;
uint8_t index;
getTableCodeAndIndex(ch, tableCode, index);
uint8_t width = getWidthFromTableCode(tableCode);
if (width == 0) {
return 0;
}
return width + 1; // add one for space after character
}
uint8_t BigCrystal::writeBig(char c, uint8_t col, uint8_t row) {
if (!supported(c)) {
return 0; // we don't support characters outside this range
}
char ch = toUpperCase(c);
uint8_t tableCode;
uint8_t index;
getTableCodeAndIndex(ch, tableCode, index);
uint8_t* table = getTable(tableCode);
if (table == NULL) {
return 0;
}
uint8_t width = getWidthFromTableCode(tableCode);
int tableOffset = (width * 2) * index;
// Write first row
setCursor(col, row);
for (uint8_t i = 0; i < width; i++) {
write(pgm_read_byte_near(table + tableOffset + i));
}
// Write second row
setCursor(col, row + 1);
for (uint8_t i = 0; i < width; i++) {
write(pgm_read_byte_near(table + tableOffset + width + i));
}
// Clear last column
clearColumn(col + width, row);
return width + 1; // add one for the cleared column
}
uint8_t BigCrystal::printBig(char *str, uint8_t col, uint8_t row) {
uint8_t width = 0;
char *c = str;
while (*c != '\0') {
width += writeBig(*c, col + width, row);
*c++;
}
return width;
}
void BigCrystal::getTableCodeAndIndex(char c, uint8_t& tableCode, uint8_t& index) {
uint8_t tableAndIndex = pgm_read_byte_near(BF_characters + c - ' ');
// Top 3 bits are the table, bottom 5 are index into table
tableCode = (uint8_t) ((tableAndIndex & 0xE0) >> 5);
index = (uint8_t) (tableAndIndex & 0x1F);
}
uint8_t* BigCrystal::getTable(uint8_t tableCode) {
switch (tableCode) {
case BF_WIDTH1_TABLE:
return BF_width1;
case BF_WIDTH2_TABLE:
return BF_width2;
case BF_WIDTH3_TABLE:
return BF_width3;
case BF_WIDTH4_TABLE:
return BF_width4;
case BF_WIDTH5_TABLE:
return BF_width5;
case BF_WIDTH3_SYMBOLS_TABLE:
return BF_width3Symbols;
default:
return NULL;
}
}
uint8_t BigCrystal::getWidthFromTableCode(uint8_t tableCode) {
if (tableCode == BF_WIDTH3_SYMBOLS_TABLE) {
return 3;
}
return tableCode;
}
bool BigCrystal::supported(char c) {
return (c >= ' ' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
char BigCrystal::toUpperCase(char c) {
if (c >= 'a' && c <= 'z') {
return c &0x5f;
}
return c;
}
void BigCrystal::clearColumn(uint8_t col, uint8_t row) {
setCursor(col, row);
write(0x20);
setCursor(col, row + 1);
write(0x20);
}
<|endoftext|> |
<commit_before>#include <UnitTest++.h>
#include "stdio_fixture.h"
#include <string.h>
SUITE(FGets)
{
TEST_FIXTURE(StdIOFixture, FGetsToEofTest)
{
istring.str("Hello");
char text_read[10];
char *str = fslc_fgets(text_read, 10, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("Hello", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsNewLineTest)
{
istring.str("Hello\nWorld");
char text_read[20];
char *str = fslc_fgets(text_read, 20, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[6]);
CHECK_EQUAL(6, strlen(str));
CHECK_EQUAL("Hello\n", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsBufSizeTest)
{
istring.str("Hello World");
char text_read[20];
char *str = fslc_fgets(text_read, 5, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("Hello", std::string(str));
}
}
<commit_msg>Additional fgets() tests CRLF handling and reading second line<commit_after>#include <UnitTest++.h>
#include "stdio_fixture.h"
#include <string.h>
SUITE(FGets)
{
TEST_FIXTURE(StdIOFixture, FGetsToEofTest)
{
istring.str("Hello");
char text_read[10];
char *str = fslc_fgets(text_read, 10, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("Hello", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsNewLineTest)
{
istring.str("Hello\nWorld");
char text_read[20];
char *str = fslc_fgets(text_read, 20, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[6]);
CHECK_EQUAL(6, strlen(str));
CHECK_EQUAL("Hello\n", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsBufSizeTest)
{
istring.str("Hello World");
char text_read[20];
char *str = fslc_fgets(text_read, 5, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("Hello", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsCrLfLineTest)
{
istring.str("Hello\r\nWorld");
char text_read[20];
char *str = fslc_fgets(text_read, 20, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[7]);
CHECK_EQUAL(7, strlen(str));
CHECK_EQUAL("Hello\r\n", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsAfterNewLineTest)
{
istring.str("Hello\nWorld");
char text_read[20];
fslc_fgets(text_read, 20, &stream);
char *str = fslc_fgets(text_read, 20, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("World", std::string(str));
}
TEST_FIXTURE(StdIOFixture, FGetsAfterCrLfLineTest)
{
istring.str("Hello\r\nWorld");
char text_read[20];
fslc_fgets(text_read, 20, &stream);
char *str = fslc_fgets(text_read, 20, &stream);
CHECK_EQUAL(text_read, str);
CHECK_EQUAL(0, str[5]);
CHECK_EQUAL(5, strlen(str));
CHECK_EQUAL("World", std::string(str));
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Bender
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Bender includes
#include "CreateTetrahedralMeshCLP.h"
#include "benderIOUtils.h"
// ITK includes
#include "itkBinaryThresholdImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkConstantPadImageFilter.h"
// Slicer includes
#include "itkPluginUtilities.h"
// VTK includes
#include <vtkCleanPolyData.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkTetra.h>
#include <vtkPolyData.h>
#include <vtkPolyDataWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
// Cleaver includes
#include <Cleaver/Cleaver.h>
#include <Cleaver/InverseField.h>
#include <Cleaver/PaddedVolume.h>
#include <Cleaver/ScalarField.h>
#include <Cleaver/Volume.h>
#include <LabelMapField.h>
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T> int DoIt( int argc, char * argv[] );
std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps(
int argc,
char * argv[]);
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType pixelType;
itk::ImageIOBase::IOComponentType componentType;
try
{
itk::GetImageType(InputVolume, pixelType, componentType);
switch( componentType )
{
case itk::ImageIOBase::UCHAR:
return DoIt<unsigned char>( argc, argv );
break;
case itk::ImageIOBase::CHAR:
return DoIt<char>( argc, argv );
break;
case itk::ImageIOBase::USHORT:
return DoIt<unsigned short>( argc, argv );
break;
case itk::ImageIOBase::SHORT:
return DoIt<short>( argc, argv );
break;
case itk::ImageIOBase::UINT:
return DoIt<unsigned int>( argc, argv );
break;
case itk::ImageIOBase::INT:
return DoIt<int>( argc, argv );
break;
case itk::ImageIOBase::ULONG:
return DoIt<unsigned long>( argc, argv );
break;
case itk::ImageIOBase::LONG:
return DoIt<long>( argc, argv );
break;
case itk::ImageIOBase::FLOAT:
return DoIt<float>( argc, argv );
break;
case itk::ImageIOBase::DOUBLE:
return DoIt<double>( argc, argv );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
std::cerr << "Unknown component type: " << componentType << std::endl;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
std::vector<Cleaver::LabelMapField::ImageType::Pointer >
SplitLabelMaps(Cleaver::LabelMapField::ImageType *image)
{
typedef Cleaver::LabelMapField::ImageType LabelImageType;
typedef itk::RelabelComponentImageFilter<LabelImageType,
LabelImageType> RelabelFilterType;
typedef itk::BinaryThresholdImageFilter<LabelImageType,
LabelImageType> ThresholdFilterType;
typedef itk::ImageFileWriter<LabelImageType> ImageWriterType;
// Assign continuous labels to the connected components, background is
// considered to be 0 and will be ignored in the relabeling process.
RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
relabelFilter->SetInput( image );
relabelFilter->Update();
std::cout << "Total Number of Labels: " <<
relabelFilter->GetNumberOfObjects() << std::endl;
// Extract the labels
typedef RelabelFilterType::LabelType LabelType;
ThresholdFilterType::Pointer skinThresholdFilter =
ThresholdFilterType::New();
// Create a list of images corresponding to labels
std::vector<LabelImageType::Pointer> labels;
// The skin label will become background for internal (smaller) organs
skinThresholdFilter->SetInput(relabelFilter->GetOutput());
skinThresholdFilter->SetLowerThreshold(1);
skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1);
skinThresholdFilter->SetInsideValue(-1);
skinThresholdFilter->SetOutsideValue(0);
skinThresholdFilter->Update();
labels.push_back(skinThresholdFilter->GetOutput());
for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end;
++i)
{
ThresholdFilterType::Pointer organThresholdFilter =
ThresholdFilterType::New();
organThresholdFilter->SetInput(relabelFilter->GetOutput());
organThresholdFilter->SetLowerThreshold(i);
organThresholdFilter->SetUpperThreshold(i);
organThresholdFilter->SetInsideValue(i);
organThresholdFilter->SetOutsideValue(-1);
organThresholdFilter->Update();
labels.push_back(organThresholdFilter->GetOutput());
}
return labels;
}
template <class T>
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
typedef Cleaver::LabelMapField::ImageType LabelImageType;
typedef T InputPixelType;
typedef itk::Image<InputPixelType,3> InputImageType;
typedef itk::CastImageFilter<InputImageType,
LabelImageType> CastFilterType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ConstantPadImageFilter<InputImageType,
InputImageType> ConstantPadType;
typename CastFilterType::Pointer castingFilter = CastFilterType::New();
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( InputVolume );
reader->Update();
// if(padding)
// {
// typename ConstantPadType::Pointer paddingFilter = ConstantPadType::New();
// paddingFilter->SetInput(reader->GetOutput());
// typename InputImageType::SizeType lowerExtendRegion;
// lowerExtendRegion[0] = 1;
// lowerExtendRegion[1] = 1;
//
// typename InputImageType::SizeType upperExtendRegion;
// upperExtendRegion[0] = 1;
// upperExtendRegion[1] = 1;
//
// paddingFilter->SetPadLowerBound(lowerExtendRegion);
// paddingFilter->SetPadUpperBound(upperExtendRegion);
// paddingFilter->SetConstant(0);
// paddingFilter->Update();
// castingFilter->SetInput(paddingFilter->GetOutput());
// }
// else
// {
castingFilter->SetInput(reader->GetOutput());
// }
std::vector<Cleaver::ScalarField*> labelMaps;
std::vector<LabelImageType::Pointer> labels =
SplitLabelMaps(castingFilter->GetOutput());
std::cout << "Total labels found: " << labels.size() << std::endl;
for(size_t i = 0; i < labels.size(); ++i)
{
labelMaps.push_back(new Cleaver::LabelMapField(labels[i]));
static_cast<Cleaver::LabelMapField*>(labelMaps.back())->
SetGenerateDataFromLabels(true);
}
if(labelMaps.empty())
{
std::cerr << "Failed to load image data. Terminating." << std::endl;
return 0;
}
if(labelMaps.size() < 2)
{
labelMaps.push_back(new Cleaver::InverseField(labelMaps[0]));
}
Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps);
if(padding)
volume = new Cleaver::PaddedVolume(volume);
std::cout << "Creating Mesh with Volume Size " << volume->size().toString() <<
std::endl;
//--------------------------------
// Create Mesher & TetMesh
//--------------------------------
Cleaver::TetMesh *cleaverMesh =
Cleaver::createMeshFromVolume(volume, verbose);
//------------------
// Compute Angles
//------------------
if(verbose)
{
cleaverMesh->computeAngles();
std::cout.precision(12);
std::cout << "Worst Angles:" << std::endl;
std::cout << "min: " << cleaverMesh->min_angle << std::endl;
std::cout << "max: " << cleaverMesh->max_angle << std::endl;
}
const int airLabel = 1;
vtkNew<vtkCellArray> meshTetras;
vtkNew<vtkIntArray> cellData;
for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i)
{
int label = cleaverMesh->tets[i]->mat_label+1;
if(label == airLabel)
{
continue;
}
vtkNew<vtkTetra> meshTetra;
meshTetra->GetPointIds()->SetId(0,
cleaverMesh->tets[i]->verts[0]->tm_v_index);
meshTetra->GetPointIds()->SetId(1,
cleaverMesh->tets[i]->verts[1]->tm_v_index);
meshTetra->GetPointIds()->SetId(2,
cleaverMesh->tets[i]->verts[2]->tm_v_index);
meshTetra->GetPointIds()->SetId(3,
cleaverMesh->tets[i]->verts[3]->tm_v_index);
meshTetras->InsertNextCell(meshTetra.GetPointer());
cellData->InsertNextValue(label);
}
vtkNew<vtkPoints> points;
points->SetNumberOfPoints(cleaverMesh->verts.size());
for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i)
{
Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos();
points->SetPoint(i, pos.x,pos.y,pos.z);
}
vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New();
vtkMesh->SetPoints(points.GetPointer());
vtkMesh->SetPolys(meshTetras.GetPointer());
vtkMesh->GetCellData()->SetScalars(cellData.GetPointer());
vtkNew<vtkCleanPolyData> cleanFilter;
cleanFilter->SetInput(vtkMesh);
bender::IOUtils::WritePolyData(cleanFilter->GetOutput(), OutputMesh);
return EXIT_SUCCESS;
}
} // end of anonymous namespace
<commit_msg>Keep the input label value for the mesh material<commit_after>/*=========================================================================
Program: Bender
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Bender includes
#include "CreateTetrahedralMeshCLP.h"
#include "benderIOUtils.h"
// ITK includes
#include "itkBinaryThresholdImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"
#include "itkRelabelComponentImageFilter.h"
#include "itkConstantPadImageFilter.h"
// Slicer includes
#include "itkPluginUtilities.h"
// VTK includes
#include <vtkCleanPolyData.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkTetra.h>
#include <vtkPolyData.h>
#include <vtkPolyDataWriter.h>
#include <vtkNew.h>
#include <vtkSmartPointer.h>
// Cleaver includes
#include <Cleaver/Cleaver.h>
#include <Cleaver/InverseField.h>
#include <Cleaver/PaddedVolume.h>
#include <Cleaver/ScalarField.h>
#include <Cleaver/Volume.h>
#include <LabelMapField.h>
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
template <class T> int DoIt( int argc, char * argv[] );
std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps(
int argc,
char * argv[]);
} // end of anonymous namespace
int main( int argc, char * argv[] )
{
PARSE_ARGS;
itk::ImageIOBase::IOPixelType pixelType;
itk::ImageIOBase::IOComponentType componentType;
try
{
itk::GetImageType(InputVolume, pixelType, componentType);
switch( componentType )
{
case itk::ImageIOBase::UCHAR:
return DoIt<unsigned char>( argc, argv );
break;
case itk::ImageIOBase::CHAR:
return DoIt<char>( argc, argv );
break;
case itk::ImageIOBase::USHORT:
return DoIt<unsigned short>( argc, argv );
break;
case itk::ImageIOBase::SHORT:
return DoIt<short>( argc, argv );
break;
case itk::ImageIOBase::UINT:
return DoIt<unsigned int>( argc, argv );
break;
case itk::ImageIOBase::INT:
return DoIt<int>( argc, argv );
break;
case itk::ImageIOBase::ULONG:
return DoIt<unsigned long>( argc, argv );
break;
case itk::ImageIOBase::LONG:
return DoIt<long>( argc, argv );
break;
case itk::ImageIOBase::FLOAT:
return DoIt<float>( argc, argv );
break;
case itk::ImageIOBase::DOUBLE:
return DoIt<double>( argc, argv );
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
std::cerr << "Unknown component type: " << componentType << std::endl;
break;
}
}
catch( itk::ExceptionObject & excep )
{
std::cerr << argv[0] << ": exception caught !" << std::endl;
std::cerr << excep << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
// Use an anonymous namespace to keep class types and function names
// from colliding when module is used as shared object module. Every
// thing should be in an anonymous namespace except for the module
// entry point, e.g. main()
//
namespace
{
std::vector<Cleaver::LabelMapField::ImageType::Pointer >
SplitLabelMaps(Cleaver::LabelMapField::ImageType *image)
{
typedef Cleaver::LabelMapField::ImageType LabelImageType;
typedef itk::RelabelComponentImageFilter<LabelImageType,
LabelImageType> RelabelFilterType;
typedef itk::BinaryThresholdImageFilter<LabelImageType,
LabelImageType> ThresholdFilterType;
typedef itk::ImageFileWriter<LabelImageType> ImageWriterType;
// Assign continuous labels to the connected components, background is
// considered to be 0 and will be ignored in the relabeling process.
RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New();
relabelFilter->SetInput( image );
relabelFilter->Update();
std::cout << "Total Number of Labels: " <<
relabelFilter->GetNumberOfObjects() << std::endl;
// Extract the labels
typedef RelabelFilterType::LabelType LabelType;
ThresholdFilterType::Pointer skinThresholdFilter =
ThresholdFilterType::New();
// Create a list of images corresponding to labels
std::vector<LabelImageType::Pointer> labels;
// The skin label will become background for internal (smaller) organs
skinThresholdFilter->SetInput(relabelFilter->GetOutput());
skinThresholdFilter->SetLowerThreshold(1);
skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1);
skinThresholdFilter->SetInsideValue(-1);
skinThresholdFilter->SetOutsideValue(0);
skinThresholdFilter->Update();
labels.push_back(skinThresholdFilter->GetOutput());
for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end;
++i)
{
ThresholdFilterType::Pointer organThresholdFilter =
ThresholdFilterType::New();
organThresholdFilter->SetInput(relabelFilter->GetOutput());
organThresholdFilter->SetLowerThreshold(i);
organThresholdFilter->SetUpperThreshold(i);
organThresholdFilter->SetInsideValue(i);
organThresholdFilter->SetOutsideValue(-1);
organThresholdFilter->Update();
labels.push_back(organThresholdFilter->GetOutput());
}
return labels;
}
template <class T>
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
typedef Cleaver::LabelMapField::ImageType LabelImageType;
typedef T InputPixelType;
typedef itk::Image<InputPixelType,3> InputImageType;
typedef itk::CastImageFilter<InputImageType,
LabelImageType> CastFilterType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ConstantPadImageFilter<InputImageType,
InputImageType> ConstantPadType;
typename CastFilterType::Pointer castingFilter = CastFilterType::New();
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( InputVolume );
reader->Update();
// if(padding)
// {
// typename ConstantPadType::Pointer paddingFilter = ConstantPadType::New();
// paddingFilter->SetInput(reader->GetOutput());
// typename InputImageType::SizeType lowerExtendRegion;
// lowerExtendRegion[0] = 1;
// lowerExtendRegion[1] = 1;
//
// typename InputImageType::SizeType upperExtendRegion;
// upperExtendRegion[0] = 1;
// upperExtendRegion[1] = 1;
//
// paddingFilter->SetPadLowerBound(lowerExtendRegion);
// paddingFilter->SetPadUpperBound(upperExtendRegion);
// paddingFilter->SetConstant(0);
// paddingFilter->Update();
// castingFilter->SetInput(paddingFilter->GetOutput());
// }
// else
// {
castingFilter->SetInput(reader->GetOutput());
// }
std::vector<Cleaver::ScalarField*> labelMaps;
std::vector<LabelImageType::Pointer> labels =
SplitLabelMaps(castingFilter->GetOutput());
// Get a map from the original labels to the new labels
std::map<InputPixelType, InputPixelType> originalLabels;
for(size_t i = 0; i < labels.size(); ++i)
{
itk::ImageRegionConstIterator<InputImageType> imageIterator(
reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<LabelImageType> labelsIterator(
labels[i], labels[i]->GetLargestPossibleRegion());
bool foundCorrespondence = false;
while(!imageIterator.IsAtEnd()
&& !labelsIterator.IsAtEnd()
&& !foundCorrespondence)
{
if (labelsIterator.Value() > 0)
{
originalLabels[labelsIterator.Value()] = imageIterator.Value();
}
++imageIterator;
++labelsIterator;
}
}
std::cout << "Total labels found: " << labels.size() << std::endl;
for(size_t i = 0; i < labels.size(); ++i)
{
labelMaps.push_back(new Cleaver::LabelMapField(labels[i]));
static_cast<Cleaver::LabelMapField*>(labelMaps.back())->
SetGenerateDataFromLabels(true);
}
if(labelMaps.empty())
{
std::cerr << "Failed to load image data. Terminating." << std::endl;
return 0;
}
if(labelMaps.size() < 2)
{
labelMaps.push_back(new Cleaver::InverseField(labelMaps[0]));
}
Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps);
if(padding)
volume = new Cleaver::PaddedVolume(volume);
std::cout << "Creating Mesh with Volume Size " << volume->size().toString() <<
std::endl;
//--------------------------------
// Create Mesher & TetMesh
//--------------------------------
Cleaver::TetMesh *cleaverMesh =
Cleaver::createMeshFromVolume(volume, verbose);
//------------------
// Compute Angles
//------------------
if(verbose)
{
cleaverMesh->computeAngles();
std::cout.precision(12);
std::cout << "Worst Angles:" << std::endl;
std::cout << "min: " << cleaverMesh->min_angle << std::endl;
std::cout << "max: " << cleaverMesh->max_angle << std::endl;
}
const int airLabel = 0;
int paddedVolumeLabel = labels.size();
vtkNew<vtkCellArray> meshTetras;
vtkNew<vtkIntArray> cellData;
for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i)
{
int label = cleaverMesh->tets[i]->mat_label;
if(label == airLabel || label == paddedVolumeLabel)
{
continue;
}
vtkNew<vtkTetra> meshTetra;
meshTetra->GetPointIds()->SetId(0,
cleaverMesh->tets[i]->verts[0]->tm_v_index);
meshTetra->GetPointIds()->SetId(1,
cleaverMesh->tets[i]->verts[1]->tm_v_index);
meshTetra->GetPointIds()->SetId(2,
cleaverMesh->tets[i]->verts[2]->tm_v_index);
meshTetra->GetPointIds()->SetId(3,
cleaverMesh->tets[i]->verts[3]->tm_v_index);
meshTetras->InsertNextCell(meshTetra.GetPointer());
cellData->InsertNextValue(originalLabels[label]);
}
vtkNew<vtkPoints> points;
points->SetNumberOfPoints(cleaverMesh->verts.size());
for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i)
{
Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos();
points->SetPoint(i, pos.x,pos.y,pos.z);
}
vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New();
vtkMesh->SetPoints(points.GetPointer());
vtkMesh->SetPolys(meshTetras.GetPointer());
vtkMesh->GetCellData()->SetScalars(cellData.GetPointer());
vtkNew<vtkCleanPolyData> cleanFilter;
cleanFilter->SetInput(vtkMesh);
bender::IOUtils::WritePolyData(cleanFilter->GetOutput(), OutputMesh);
return EXIT_SUCCESS;
}
} // end of anonymous namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cppinterfaceproxy.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 22:09:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#define INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#include "osl/interlck.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.h"
#include "uno/dispatcher.h"
#include "uno/environment.h"
namespace com { namespace sun { namespace star { namespace uno {
class XInterface;
} } } }
namespace bridges { namespace cpp_uno { namespace shared {
class Bridge;
/**
* A cpp proxy wrapping a uno interface.
*/
class CppInterfaceProxy {
public:
// Interface for Bridge:
static com::sun::star::uno::XInterface * create(
Bridge * pBridge, uno_Interface * pUnoI,
typelib_InterfaceTypeDescription * pTypeDescr,
rtl::OUString const & rOId) SAL_THROW(());
static void SAL_CALL free(uno_ExtEnvironment * pEnv, void * pInterface)
SAL_THROW(());
// Interface for individual CPP--UNO bridges:
Bridge * getBridge() { return pBridge; }
uno_Interface * getUnoI() { return pUnoI; }
typelib_InterfaceTypeDescription * getTypeDescr() { return pTypeDescr; }
rtl::OUString getOid() { return oid; }
// non virtual methods called on incoming vtable calls #1, #2
void acquireProxy() SAL_THROW(());
void releaseProxy() SAL_THROW(());
static CppInterfaceProxy * castInterfaceToProxy(void * pInterface);
private:
CppInterfaceProxy(CppInterfaceProxy &); // not implemented
void operator =(CppInterfaceProxy); // not implemented
CppInterfaceProxy(
Bridge * pBridge_, uno_Interface * pUnoI_,
typelib_InterfaceTypeDescription * pTypeDescr_,
rtl::OUString const & rOId_) SAL_THROW(());
~CppInterfaceProxy();
static com::sun::star::uno::XInterface * castProxyToInterface(
CppInterfaceProxy * pProxy);
oslInterlockedCount nRef;
Bridge * pBridge;
// mapping information
uno_Interface * pUnoI; // wrapped interface
typelib_InterfaceTypeDescription * pTypeDescr;
rtl::OUString oid;
void ** vtables[1];
};
} } }
#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.2.100); FILE MERGED 2005/09/22 18:05:06 sb 1.2.100.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/09 12:37:19 sb 1.2.100.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cppinterfaceproxy.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 23:38:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#define INCLUDED_BRIDGES_CPP_UNO_SHARED_CPPINTERFACEPROXY_HXX
#include "osl/interlck.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "typelib/typedescription.h"
#include "uno/dispatcher.h"
#include "uno/environment.h"
namespace com { namespace sun { namespace star { namespace uno {
class XInterface;
} } } }
namespace bridges { namespace cpp_uno { namespace shared {
class Bridge;
extern "C" typedef void SAL_CALL FreeCppInterfaceProxy(
uno_ExtEnvironment * pEnv, void * pInterface);
FreeCppInterfaceProxy freeCppInterfaceProxy;
/**
* A cpp proxy wrapping a uno interface.
*/
class CppInterfaceProxy {
public:
// Interface for Bridge:
static com::sun::star::uno::XInterface * create(
Bridge * pBridge, uno_Interface * pUnoI,
typelib_InterfaceTypeDescription * pTypeDescr,
rtl::OUString const & rOId) SAL_THROW(());
// Interface for individual CPP--UNO bridges:
Bridge * getBridge() { return pBridge; }
uno_Interface * getUnoI() { return pUnoI; }
typelib_InterfaceTypeDescription * getTypeDescr() { return pTypeDescr; }
rtl::OUString getOid() { return oid; }
// non virtual methods called on incoming vtable calls #1, #2
void acquireProxy() SAL_THROW(());
void releaseProxy() SAL_THROW(());
static CppInterfaceProxy * castInterfaceToProxy(void * pInterface);
private:
CppInterfaceProxy(CppInterfaceProxy &); // not implemented
void operator =(CppInterfaceProxy); // not implemented
CppInterfaceProxy(
Bridge * pBridge_, uno_Interface * pUnoI_,
typelib_InterfaceTypeDescription * pTypeDescr_,
rtl::OUString const & rOId_) SAL_THROW(());
~CppInterfaceProxy();
static com::sun::star::uno::XInterface * castProxyToInterface(
CppInterfaceProxy * pProxy);
oslInterlockedCount nRef;
Bridge * pBridge;
// mapping information
uno_Interface * pUnoI; // wrapped interface
typelib_InterfaceTypeDescription * pTypeDescr;
rtl::OUString oid;
void ** vtables[1];
friend void SAL_CALL freeCppInterfaceProxy(
uno_ExtEnvironment * pEnv, void * pInterface);
};
} } }
#endif
<|endoftext|> |
<commit_before>// ParallelExecutionOfCommands.cpp :
// This aplication aims to provide functionality for parallel execution of Behat commands.
//
//#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
//#include <unistd.h>
#include <thread>
using namespace std;
int main()
{
// Declaration of needed variables.
int processes_Count;
char command[128];
string behat_Profile;
string behat_Feature_Folder;
string behat_Bin = "bin/behat -p ";
string result_Command_String;
thread thread_Array[100];
bool parallel_Execution = true;
// Entering values for the variables.
cout << "Enter number of processes you want to execute: ";
cin >> processes_Count;
cout << "Enter Behat profile you want to use: ";
cin >> behat_Profile;
cout << "Enter Behat feature folder or file location you want to execute: ";
cin >> behat_Feature_Folder;
// Creting command for execution.
result_Command_String = behat_Bin + behat_Profile + " features/" + behat_Feature_Folder;
strcpy(command, result_Command_String.c_str());
cout << "You will execute " << processes_Count << " processes with the following command: " << command << ".\n";
// Creating threads to handle the command execution.
for (size_t i = 0; i < processes_Count; i++)
{
thread_Array[i] = thread(system, command);
}
for (size_t i = 0; i < sizeof(thread_Array); i++)
{
thread_Array[i].detach();
}
//// Creating process for execution of the command.
//pid_t pids[processes_Count];
//for (size_t i = 0; i < processes_Count; i++)
//{
// if ((pids[i] = fork()) < 0)
// {
// perror("Process was unable to be created.");
// abort();
// }
// else if (pids[i] == 0)
// {
// system(command);
// exit(0);
// }
//}
return 0;
}
<commit_msg>Using join() for threads.<commit_after>// ParallelExecutionOfCommands.cpp :
// This aplication aims to provide functionality for parallel execution of Behat commands.
//
//#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
//#include <unistd.h>
#include <thread>
using namespace std;
int main()
{
// Declaration of needed variables.
int processes_Count;
char command[128];
string behat_Profile;
string behat_Feature_Folder;
string behat_Bin = "bin/behat -p ";
string result_Command_String;
thread thread_Array[100];
bool parallel_Execution = true;
// Entering values for the variables.
cout << "Enter number of processes you want to execute: ";
cin >> processes_Count;
cout << "Enter Behat profile you want to use: ";
cin >> behat_Profile;
cout << "Enter Behat feature folder or file location you want to execute: ";
cin >> behat_Feature_Folder;
// Creting command for execution.
result_Command_String = behat_Bin + behat_Profile + " features/" + behat_Feature_Folder;
strcpy(command, result_Command_String.c_str());
cout << "You will execute " << processes_Count << " processes with the following command: " << command << ".\n";
// Creating threads to handle the command execution.
for (size_t i = 0; i < processes_Count; i++)
{
thread_Array[i] = thread(system, command);
thread_Array[i].join();
}
for (size_t i = 0; i < sizeof(thread_Array); i++)
{
thread_Array[i].detach();
}
//// Creating process for execution of the command.
//pid_t pids[processes_Count];
//for (size_t i = 0; i < processes_Count; i++)
//{
// if ((pids[i] = fork()) < 0)
// {
// perror("Process was unable to be created.");
// abort();
// }
// else if (pids[i] == 0)
// {
// system(command);
// exit(0);
// }
//}
return 0;
}
<|endoftext|> |
<commit_before>#include "GL_Widget.h"
#include <QtOpenGL/QGLFunctions>
//////////////////////////////////////////////////////////////////////////
GL_Widget::GL_Widget(QWidget* parent)
: QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer), parent)
{
//setAttribute(Qt::WA_PaintOnScreen);
}
//////////////////////////////////////////////////////////////////////////
GL_Widget::~GL_Widget()
{
q::System::destroy();
}
//////////////////////////////////////////////////////////////////////////
void GL_Widget::initializeGL()
{
auto renderer = new q::video::GLES_Renderer();
q::System::create();
q::System::inst().init(q::video::Renderer_ptr(renderer));
renderer->init(math::vec2u32(width() + 1, height()) + 1,
q::video::Render_Target::Color_Format::RGBA_8,
q::video::Render_Target::Depth_Format::FULL,
q::video::Render_Target::Stencil_Format::FULL);
renderer->get_render_target()->set_color_clear_value(math::vec4f(0.6f, 0.6f, 0.6f, 1.f));
q::System::inst().get_file_system().mount("fonts", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/fonts"))));
q::System::inst().get_file_system().mount("techniques", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/techniques"))));
q::System::inst().get_file_system().mount("models", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/models"))));
}
//////////////////////////////////////////////////////////////////////////
void GL_Widget::paintGL()
{
}
<commit_msg>Disabled vsync<commit_after>#include "GL_Widget.h"
#include <QtOpenGL/QGLFunctions>
//////////////////////////////////////////////////////////////////////////
GL_Widget::GL_Widget(QWidget* parent)
: QGLWidget(parent)
{
//setAttribute(Qt::WA_PaintOnScreen);
QGLFormat format(QGL::DepthBuffer | QGL::Rgba | QGL::NoStencilBuffer);
format.setSwapInterval(0);
setFormat(format);
}
//////////////////////////////////////////////////////////////////////////
GL_Widget::~GL_Widget()
{
q::System::destroy();
}
//////////////////////////////////////////////////////////////////////////
void GL_Widget::initializeGL()
{
auto renderer = new q::video::GLES_Renderer();
q::System::create();
q::System::inst().init(q::video::Renderer_ptr(renderer));
renderer->init(math::vec2u32(width() + 1, height()) + 1,
q::video::Render_Target::Color_Format::RGBA_8,
q::video::Render_Target::Depth_Format::FULL,
q::video::Render_Target::Stencil_Format::FULL);
renderer->get_render_target()->set_color_clear_value(math::vec4f(0.6f, 0.6f, 0.6f, 1.f));
q::System::inst().get_file_system().mount("fonts", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/fonts"))));
q::System::inst().get_file_system().mount("techniques", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/techniques"))));
q::System::inst().get_file_system().mount("models", q::data::Data_Pack_uptr(new q::data::Folder_Data_Pack(q::Path("data/models"))));
}
//////////////////////////////////////////////////////////////////////////
void GL_Widget::paintGL()
{
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandintegration.h"
#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"
#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/QWindowSystemInterface>
#include <QtGui/QPlatformCursor>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QGuiGLContext>
#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif
QWaylandIntegration::QWaylandIntegration()
: mFontDb(new QGenericUnixFontDatabase())
, mEventDispatcher(createUnixEventDispatcher())
, mNativeInterface(new QWaylandNativeInterface)
{
QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
mDisplay = new QWaylandDisplay();
foreach (QPlatformScreen *screen, mDisplay->screens())
screenAdded(screen);
}
QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
return mNativeInterface;
}
bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
switch (cap) {
case ThreadedPixmaps: return true;
case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
return true;
#else
return false;
#endif
default: return QPlatformIntegration::hasCapability(cap);
}
}
QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
if (window->surfaceType() == QWindow::OpenGLSurface)
return mDisplay->eglIntegration()->createEglWindow(window);
#endif
return new QWaylandShmWindow(window);
}
QPlatformGLContext *QWaylandIntegration::createPlatformGLContext(QGuiGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
return mDisplay->eglIntegration()->createPlatformGLContext(context->format(), context->shareHandle());
#else
Q_UNUSED(glFormat);
Q_UNUSED(share);
return 0;
#endif
}
QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
return new QWaylandShmBackingStore(window);
}
QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
return mEventDispatcher;
}
QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
return mFontDb;
}
QPlatformClipboard *QWaylandIntegration::clipboard() const
{
return QWaylandClipboard::instance(mDisplay);
}
QPlatformDrag *QWaylandIntegration::drag() const
{
return QWaylandDrag::instance(mDisplay);
}
<commit_msg>Introduce new platform capability ThreadedOpenGL.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the config.tests of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandintegration.h"
#include "qwaylanddisplay.h"
#include "qwaylandshmbackingstore.h"
#include "qwaylandshmwindow.h"
#include "qwaylandnativeinterface.h"
#include "qwaylandclipboard.h"
#include "qwaylanddnd.h"
#include "QtPlatformSupport/private/qgenericunixfontdatabase_p.h"
#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/QWindowSystemInterface>
#include <QtGui/QPlatformCursor>
#include <QtGui/QSurfaceFormat>
#include <QtGui/QGuiGLContext>
#ifdef QT_WAYLAND_GL_SUPPORT
#include "gl_integration/qwaylandglintegration.h"
#endif
QWaylandIntegration::QWaylandIntegration()
: mFontDb(new QGenericUnixFontDatabase())
, mEventDispatcher(createUnixEventDispatcher())
, mNativeInterface(new QWaylandNativeInterface)
{
QGuiApplicationPrivate::instance()->setEventDispatcher(mEventDispatcher);
mDisplay = new QWaylandDisplay();
foreach (QPlatformScreen *screen, mDisplay->screens())
screenAdded(screen);
}
QPlatformNativeInterface * QWaylandIntegration::nativeInterface() const
{
return mNativeInterface;
}
bool QWaylandIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
switch (cap) {
case ThreadedPixmaps: return true;
case OpenGL:
#ifdef QT_WAYLAND_GL_SUPPORT
return true;
#else
return false;
#endif
case ThreadedOpenGL:
return hasCapability(OpenGL);
default: return QPlatformIntegration::hasCapability(cap);
}
}
QPlatformWindow *QWaylandIntegration::createPlatformWindow(QWindow *window) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
if (window->surfaceType() == QWindow::OpenGLSurface)
return mDisplay->eglIntegration()->createEglWindow(window);
#endif
return new QWaylandShmWindow(window);
}
QPlatformGLContext *QWaylandIntegration::createPlatformGLContext(QGuiGLContext *context) const
{
#ifdef QT_WAYLAND_GL_SUPPORT
return mDisplay->eglIntegration()->createPlatformGLContext(context->format(), context->shareHandle());
#else
Q_UNUSED(glFormat);
Q_UNUSED(share);
return 0;
#endif
}
QPlatformBackingStore *QWaylandIntegration::createPlatformBackingStore(QWindow *window) const
{
return new QWaylandShmBackingStore(window);
}
QAbstractEventDispatcher *QWaylandIntegration::guiThreadEventDispatcher() const
{
return mEventDispatcher;
}
QPlatformFontDatabase *QWaylandIntegration::fontDatabase() const
{
return mFontDb;
}
QPlatformClipboard *QWaylandIntegration::clipboard() const
{
return QWaylandClipboard::instance(mDisplay);
}
QPlatformDrag *QWaylandIntegration::drag() const
{
return QWaylandDrag::instance(mDisplay);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DragMethod_Base.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:07:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "DragMethod_Base.hxx"
#include "Strings.hrc"
#include "ResId.hxx"
#include "macros.hxx"
#include "ObjectNameProvider.hxx"
#include "ObjectIdentifier.hxx"
#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
//header for class SdrPageView
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVX_ACTIONDESCRIPTIONPROVIDER_HXX
#include <svx/ActionDescriptionProvider.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::WeakReference;
DragMethod_Base::DragMethod_Base( DrawViewWrapper& rDrawViewWrapper
, const rtl::OUString& rObjectCID
, const Reference< frame::XModel >& xChartModel
, ActionDescriptionProvider::ActionType eActionType )
: SdrDragMethod( rDrawViewWrapper )
, m_rDrawViewWrapper(rDrawViewWrapper)
, m_aObjectCID(rObjectCID)
, m_eActionType( eActionType )
, m_xChartModel( WeakReference< frame::XModel >(xChartModel) )
{
}
DragMethod_Base::~DragMethod_Base()
{
}
Reference< frame::XModel > DragMethod_Base::getChartModel() const
{
return Reference< frame::XModel >( m_xChartModel );;
}
rtl::OUString DragMethod_Base::getUndoDescription() const
{
return ActionDescriptionProvider::createDescription(
m_eActionType,
ObjectNameProvider::getName( ObjectIdentifier::getObjectType( m_aObjectCID )));
}
void DragMethod_Base::TakeComment(String& rStr) const
{
rStr = String( getUndoDescription() );
}
void DragMethod_Base::Brk()
{
Hide();
}
Pointer DragMethod_Base::GetPointer() const
{
if( IsDraggingPoints() || IsDraggingGluePoints() )
return Pointer(POINTER_MOVEPOINT);
else
return Pointer(POINTER_MOVE);
}
FASTBOOL DragMethod_Base::IsMoveOnly() const
{
return TRUE;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 15:04:11 thb 1.2.126.3: #i85898# Stripping all external header guards 2008/04/01 10:50:26 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:43:50 rt 1.2.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DragMethod_Base.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "DragMethod_Base.hxx"
#include "Strings.hrc"
#include "ResId.hxx"
#include "macros.hxx"
#include "ObjectNameProvider.hxx"
#include "ObjectIdentifier.hxx"
#include <rtl/math.hxx>
//header for class SdrPageView
#include <svx/svdpagv.hxx>
#include <svx/ActionDescriptionProvider.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::WeakReference;
DragMethod_Base::DragMethod_Base( DrawViewWrapper& rDrawViewWrapper
, const rtl::OUString& rObjectCID
, const Reference< frame::XModel >& xChartModel
, ActionDescriptionProvider::ActionType eActionType )
: SdrDragMethod( rDrawViewWrapper )
, m_rDrawViewWrapper(rDrawViewWrapper)
, m_aObjectCID(rObjectCID)
, m_eActionType( eActionType )
, m_xChartModel( WeakReference< frame::XModel >(xChartModel) )
{
}
DragMethod_Base::~DragMethod_Base()
{
}
Reference< frame::XModel > DragMethod_Base::getChartModel() const
{
return Reference< frame::XModel >( m_xChartModel );;
}
rtl::OUString DragMethod_Base::getUndoDescription() const
{
return ActionDescriptionProvider::createDescription(
m_eActionType,
ObjectNameProvider::getName( ObjectIdentifier::getObjectType( m_aObjectCID )));
}
void DragMethod_Base::TakeComment(String& rStr) const
{
rStr = String( getUndoDescription() );
}
void DragMethod_Base::Brk()
{
Hide();
}
Pointer DragMethod_Base::GetPointer() const
{
if( IsDraggingPoints() || IsDraggingGluePoints() )
return Pointer(POINTER_MOVEPOINT);
else
return Pointer(POINTER_MOVE);
}
FASTBOOL DragMethod_Base::IsMoveOnly() const
{
return TRUE;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataSeriesProperties.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:57:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CHART_DATASERIESPROPERTIES_HXX
#define CHART_DATASERIESPROPERTIES_HXX
#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"
#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#include <vector>
namespace chart
{
class DataSeriesProperties
{
public:
enum
{
PROP_DATASERIES_DATA_POINT_STYLE = FAST_PROPERTY_ID_START_DATA_SERIES,
PROP_DATASERIES_ATTRIBUTED_DATA_POINTS,
PROP_DATASERIES_IDENTIFIER
};
static void AddPropertiesToVector(
::std::vector< ::com::sun::star::beans::Property > & rOutProperties,
bool bIncludeStyleProperties = false );
static void AddDefaultsToMap( helper::tPropertyValueMap & rOutMap, bool bIncludeStyleProperties = false );
private:
// not implemented
DataSeriesProperties();
};
} // namespace chart
// CHART_DATASERIESPROPERTIES_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.1.1.1.4); FILE MERGED 2007/04/20 08:06:44 iha 1.1.1.1.4.11: #i75393# Connect Bars per diagram not per series 2007/04/19 16:07:00 iha 1.1.1.1.4.10: #i76130# write attribute sort-by-x-values per plot-area not per series 2006/08/21 17:02:45 iha 1.1.1.1.4.9: #i46521# replace modal x value sorting dialog by a checkbox in the chartwizard; perform sorting in view only and not in the cached chart data (as there is no cached data in the model anymore) 2005/12/21 21:29:18 iha 1.1.1.1.4.8: remove identifiers from model objects and create an index based CID protocol instead for selection purposes 2005/11/28 15:35:41 bm 1.1.1.1.4.7: BarConnectors implemented the old way (all series at once) but model offers the property ConnectDataPoints for each series independently 2005/10/24 11:06:45 iha 1.1.1.1.4.6: coordinate system restructure 2005/10/07 11:53:44 bm 1.1.1.1.4.5: RESYNC: (1.1.1.1-1.2); FILE MERGED 2005/07/28 09:34:51 bm 1.1.1.1.4.4: usage of color schemes and the VaryColorsByPoint property to have correct pie colors and legend entries 2005/07/14 13:00:23 iha 1.1.1.1.4.3: remove unused parameter 'bIncludeStyleProperties' from series and point properties 2004/09/15 17:32:02 bm 1.1.1.1.4.2: API simplification 2004/02/13 16:51:29 bm 1.1.1.1.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DataSeriesProperties.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:35:03 $
*
* 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 CHART_DATASERIESPROPERTIES_HXX
#define CHART_DATASERIESPROPERTIES_HXX
#include "PropertyHelper.hxx"
#include "FastPropertyIdRanges.hxx"
#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#include <vector>
namespace chart
{
class DataSeriesProperties
{
public:
enum
{
PROP_DATASERIES_ATTRIBUTED_DATA_POINTS = FAST_PROPERTY_ID_START_DATA_SERIES,
PROP_DATASERIES_STACKING_DIRECTION,
PROP_DATASERIES_VARY_COLORS_BY_POINT,
PROP_DATASERIES_ATTACHED_AXIS_INDEX
};
static void AddPropertiesToVector(
::std::vector< ::com::sun::star::beans::Property > & rOutProperties );
static void AddDefaultsToMap( tPropertyValueMap & rOutMap );
private:
// not implemented
DataSeriesProperties();
};
} // namespace chart
// CHART_DATASERIESPROPERTIES_HXX
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_quota_permission_context.h"
#include <string>
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/pref_names.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/quota/quota_types.h"
namespace {
// If we requested larger quota than this threshold, show a different
// message to the user.
const int64 kRequestLargeQuotaThreshold = 5 * 1024 * 1024;
class RequestQuotaInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
typedef QuotaPermissionContext::PermissionCallback PermissionCallback;
RequestQuotaInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
ChromeQuotaPermissionContext* context,
const GURL& origin_url,
int64 requested_quota,
const std::string& display_languages,
const PermissionCallback& callback)
: ConfirmInfoBarDelegate(infobar_helper),
context_(context),
origin_url_(origin_url),
display_languages_(display_languages),
requested_quota_(requested_quota),
callback_(callback) {}
private:
virtual ~RequestQuotaInfoBarDelegate() {
if (!callback_.is_null())
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
}
virtual bool ShouldExpire(
const content::LoadCommittedDetails& details)
const OVERRIDE {
return false;
}
virtual string16 GetMessageText() const OVERRIDE;
virtual void InfoBarDismissed() OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
scoped_refptr<ChromeQuotaPermissionContext> context_;
GURL origin_url_;
std::string display_languages_;
int64 requested_quota_;
PermissionCallback callback_;
DISALLOW_COPY_AND_ASSIGN(RequestQuotaInfoBarDelegate);
};
void RequestQuotaInfoBarDelegate::InfoBarDismissed() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
}
string16 RequestQuotaInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(
(requested_quota_ > kRequestLargeQuotaThreshold ?
IDS_REQUEST_LARGE_QUOTA_INFOBAR_QUESTION :
IDS_REQUEST_QUOTA_INFOBAR_QUESTION),
net::FormatUrl(origin_url_, display_languages_));
}
bool RequestQuotaInfoBarDelegate::Accept() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseAllow);
return true;
}
bool RequestQuotaInfoBarDelegate::Cancel() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
return true;
}
} // anonymous namespace
ChromeQuotaPermissionContext::ChromeQuotaPermissionContext() {
}
ChromeQuotaPermissionContext::~ChromeQuotaPermissionContext() {
}
void ChromeQuotaPermissionContext::RequestQuotaPermission(
const GURL& origin_url,
quota::StorageType type,
int64 requested_quota,
int render_process_id,
int render_view_id,
const PermissionCallback& callback) {
if (type != quota::kStorageTypePersistent) {
// For now we only support requesting quota with this interface
// for Persistent storage type.
callback.Run(kResponseDisallow);
return;
}
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ChromeQuotaPermissionContext::RequestQuotaPermission, this,
origin_url, type, requested_quota,render_process_id,
render_view_id, callback));
return;
}
TabContents* tab_contents =
tab_util::GetTabContentsByID(render_process_id, render_view_id);
if (!tab_contents) {
// The tab may have gone away or the request may not be from a tab.
LOG(WARNING) << "Attempt to request quota tabless renderer: "
<< render_process_id << "," << render_view_id;
DispatchCallbackOnIOThread(callback, kResponseCancelled);
return;
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
InfoBarTabHelper* infobar_helper = wrapper->infobar_tab_helper();
infobar_helper->AddInfoBar(new RequestQuotaInfoBarDelegate(
infobar_helper, this, origin_url, requested_quota,
wrapper->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages),
callback));
}
void ChromeQuotaPermissionContext::DispatchCallbackOnIOThread(
const PermissionCallback& callback,
Response response) {
DCHECK_EQ(false, callback.is_null());
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&ChromeQuotaPermissionContext::DispatchCallbackOnIOThread,
this, callback, response));
return;
}
callback.Run(response);
}
<commit_msg>Fix build break: use NewRunnableMethod for bind that requires 7-arity.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_quota_permission_context.h"
#include <string>
#include "base/bind.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/infobar_tab_helper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/pref_names.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
#include "webkit/quota/quota_types.h"
namespace {
// If we requested larger quota than this threshold, show a different
// message to the user.
const int64 kRequestLargeQuotaThreshold = 5 * 1024 * 1024;
class RequestQuotaInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
typedef QuotaPermissionContext::PermissionCallback PermissionCallback;
RequestQuotaInfoBarDelegate(
InfoBarTabHelper* infobar_helper,
ChromeQuotaPermissionContext* context,
const GURL& origin_url,
int64 requested_quota,
const std::string& display_languages,
const PermissionCallback& callback)
: ConfirmInfoBarDelegate(infobar_helper),
context_(context),
origin_url_(origin_url),
display_languages_(display_languages),
requested_quota_(requested_quota),
callback_(callback) {}
private:
virtual ~RequestQuotaInfoBarDelegate() {
if (!callback_.is_null())
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
}
virtual bool ShouldExpire(
const content::LoadCommittedDetails& details)
const OVERRIDE {
return false;
}
virtual string16 GetMessageText() const OVERRIDE;
virtual void InfoBarDismissed() OVERRIDE;
virtual bool Accept() OVERRIDE;
virtual bool Cancel() OVERRIDE;
scoped_refptr<ChromeQuotaPermissionContext> context_;
GURL origin_url_;
std::string display_languages_;
int64 requested_quota_;
PermissionCallback callback_;
DISALLOW_COPY_AND_ASSIGN(RequestQuotaInfoBarDelegate);
};
void RequestQuotaInfoBarDelegate::InfoBarDismissed() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
}
string16 RequestQuotaInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(
(requested_quota_ > kRequestLargeQuotaThreshold ?
IDS_REQUEST_LARGE_QUOTA_INFOBAR_QUESTION :
IDS_REQUEST_QUOTA_INFOBAR_QUESTION),
net::FormatUrl(origin_url_, display_languages_));
}
bool RequestQuotaInfoBarDelegate::Accept() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseAllow);
return true;
}
bool RequestQuotaInfoBarDelegate::Cancel() {
context_->DispatchCallbackOnIOThread(
callback_, QuotaPermissionContext::kResponseCancelled);
return true;
}
} // anonymous namespace
ChromeQuotaPermissionContext::ChromeQuotaPermissionContext() {
}
ChromeQuotaPermissionContext::~ChromeQuotaPermissionContext() {
}
void ChromeQuotaPermissionContext::RequestQuotaPermission(
const GURL& origin_url,
quota::StorageType type,
int64 requested_quota,
int render_process_id,
int render_view_id,
const PermissionCallback& callback) {
if (type != quota::kStorageTypePersistent) {
// For now we only support requesting quota with this interface
// for Persistent storage type.
callback.Run(kResponseDisallow);
return;
}
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(
this, &ChromeQuotaPermissionContext::RequestQuotaPermission,
origin_url, type, requested_quota, render_process_id,
render_view_id, callback));
return;
}
TabContents* tab_contents =
tab_util::GetTabContentsByID(render_process_id, render_view_id);
if (!tab_contents) {
// The tab may have gone away or the request may not be from a tab.
LOG(WARNING) << "Attempt to request quota tabless renderer: "
<< render_process_id << "," << render_view_id;
DispatchCallbackOnIOThread(callback, kResponseCancelled);
return;
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
InfoBarTabHelper* infobar_helper = wrapper->infobar_tab_helper();
infobar_helper->AddInfoBar(new RequestQuotaInfoBarDelegate(
infobar_helper, this, origin_url, requested_quota,
wrapper->profile()->GetPrefs()->GetString(prefs::kAcceptLanguages),
callback));
}
void ChromeQuotaPermissionContext::DispatchCallbackOnIOThread(
const PermissionCallback& callback,
Response response) {
DCHECK_EQ(false, callback.is_null());
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&ChromeQuotaPermissionContext::DispatchCallbackOnIOThread,
this, callback, response));
return;
}
callback.Run(response);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ConstantPropagationWholeProgramState.h"
#include "IPConstantPropagationAnalysis.h"
#include "Walkers.h"
using namespace constant_propagation;
namespace {
/*
* Walk all the static or instance fields in :cls, copying their bindings in
* :field_env over to :field_partition.
*/
void set_fields_in_partition(const DexClass* cls,
const FieldEnvironment& field_env,
const FieldType& field_type,
ConstantFieldPartition* field_partition) {
// Note that we *must* iterate over the list of fields in the class and not
// the bindings in field_env here. This ensures that fields whose values are
// unknown (and therefore implicitly represented by Top in the field_env)
// get correctly bound to Top in field_partition (which defaults its
// bindings to Bottom).
const auto& fields =
field_type == FieldType::STATIC ? cls->get_sfields() : cls->get_ifields();
for (auto& field : fields) {
auto value = field_env.get(field);
if (!value.is_top()) {
TRACE(ICONSTP, 2, "%s has value %s after <clinit> or <init>",
SHOW(field), SHOW(value));
always_assert(field->get_class() == cls->get_type());
} else {
TRACE(ICONSTP, 2, "%s has unknown value after <clinit> or <init>",
SHOW(field));
}
field_partition->set(field, value);
}
}
/*
* Record in :field_partition the values of the static fields after the class
* initializers have finished executing.
*
* XXX this assumes that there are no cycles in the class initialization graph!
*/
void analyze_clinits(const Scope& scope,
const interprocedural::FixpointIterator& fp_iter,
ConstantFieldPartition* field_partition) {
for (DexClass* cls : scope) {
auto& dmethods = cls->get_dmethods();
auto clinit = cls->get_clinit();
if (clinit == nullptr) {
// If there is no class initializer, then the initial field values are
// simply the DexEncodedValues.
ConstantEnvironment env;
set_encoded_values(cls, &env);
set_fields_in_partition(cls, env.get_field_environment(),
FieldType::STATIC, field_partition);
continue;
}
IRCode* code = clinit->get_code();
auto& cfg = code->cfg();
auto intra_cp = fp_iter.get_intraprocedural_analysis(clinit);
auto env = intra_cp->get_exit_state_at(cfg.exit_block());
set_fields_in_partition(cls, env.get_field_environment(), FieldType::STATIC,
field_partition);
}
}
bool analyze_gets_helper(const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto field = resolve_field(insn->get_field());
if (field == nullptr) {
return false;
}
auto value = whole_program_state->get_field_value(field);
if (value.is_top()) {
return false;
}
env->set(RESULT_REGISTER, value);
return true;
}
bool not_eligible_ifield(DexField* field) {
return is_static(field) || field->is_external() || !can_delete(field) ||
is_volatile(field);
}
/**
* Initialize non-external, can be deleted instance fields' value to be 0.
*/
void initialize_ifields(const Scope& scope,
ConstantFieldPartition* field_partition) {
walk::fields(scope, [&](DexField* field) {
if (not_eligible_ifield(field)) {
return;
}
field_partition->set(field, SignedConstantDomain(0));
});
}
} // namespace
namespace constant_propagation {
WholeProgramState::WholeProgramState(
const Scope& scope,
const interprocedural::FixpointIterator& fp_iter,
const std::vector<DexMethod*>& non_true_virtuals,
const std::unordered_set<const DexType*>& field_black_list) {
walk::fields(scope, [&](DexField* field) {
// We exclude those marked by keep rules: keep-marked fields may be
// written to by non-Dex bytecode.
// All fields not in m_known_fields will be bound to Top.
if (field_black_list.count(field->get_class())) {
return;
}
if (is_static(field) && !root(field)) {
m_known_fields.emplace(field);
}
if (not_eligible_ifield(field)) {
return;
}
m_known_fields.emplace(field);
});
// Put non-root non true virtual methods in known methods.
for (const auto& non_true_virtual : non_true_virtuals) {
if (!root(non_true_virtual)) {
m_known_methods.emplace(non_true_virtual);
}
}
walk::code(scope, [&](DexMethod* method, const IRCode&) {
if (!method->is_virtual()) {
// Put non virtual methods in known methods.
m_known_methods.emplace(method);
}
});
analyze_clinits(scope, fp_iter, &m_field_partition);
collect(scope, fp_iter);
}
/*
* Walk over the entire program, doing a join over the values written to each
* field, as well as a join over the values returned by each method.
*/
void WholeProgramState::collect(
const Scope& scope, const interprocedural::FixpointIterator& fp_iter) {
initialize_ifields(scope, &m_field_partition);
walk::methods(scope, [&](DexMethod* method) {
IRCode* code = method->get_code();
if (code == nullptr) {
return;
}
auto& cfg = code->cfg();
auto intra_cp = fp_iter.get_intraprocedural_analysis(method);
for (cfg::Block* b : cfg.blocks()) {
auto env = intra_cp->get_entry_state_at(b);
for (auto& mie : InstructionIterable(b)) {
auto* insn = mie.insn;
intra_cp->analyze_instruction(insn, &env);
collect_field_values(insn, env,
is_clinit(method) ? method->get_class() : nullptr);
collect_return_values(insn, env, method);
}
}
});
}
/*
* For each field, do a join over all the values that may have been
* written to it at any point in the program.
*
* If we are encountering a static field write of some value to Foo.someField
* in the body of Foo.<clinit>, don't do anything -- that value will only be
* visible to other methods if it remains unchanged up until the end of the
* <clinit>. In that case, analyze_clinits() will record it.
*/
void WholeProgramState::collect_field_values(const IRInstruction* insn,
const ConstantEnvironment& env,
const DexType* clinit_cls) {
if (!is_sput(insn->opcode()) && !is_iput(insn->opcode())) {
return;
}
auto field = resolve_field(insn->get_field());
if (field != nullptr && m_known_fields.count(field)) {
if (is_sput(insn->opcode()) && field->get_class() == clinit_cls) {
return;
}
auto value = env.get(insn->src(0));
m_field_partition.update(field, [&value](auto* current_value) {
current_value->join_with(value);
});
}
}
/*
* For each method, do a join over all the values that can be returned by it.
*
* If there are no reachable return opcodes in the method, then it never
* returns. Its return value will be represented by Bottom in our analysis.
*/
void WholeProgramState::collect_return_values(const IRInstruction* insn,
const ConstantEnvironment& env,
const DexMethod* method) {
auto op = insn->opcode();
if (!is_return(op)) {
return;
}
if (op == OPCODE_RETURN_VOID) {
// We must set the binding to Top here to record the fact that this method
// does indeed return -- even though `void` is not actually a return value,
// this tells us that the code following any invoke of this method is
// reachable.
m_method_partition.update(
method, [](auto* current_value) { current_value->set_to_top(); });
return;
}
auto value = env.get(insn->src(0));
m_method_partition.update(method, [&value](auto* current_value) {
current_value->join_with(value);
});
}
void WholeProgramState::collect_static_finals(const DexClass* cls,
FieldEnvironment field_env) {
for (auto* field : cls->get_sfields()) {
if (is_static(field) && is_final(field) && !field->is_external()) {
m_known_fields.emplace(field);
} else {
field_env.set(field, ConstantValue::top());
}
}
set_fields_in_partition(cls, field_env, FieldType::STATIC,
&m_field_partition);
}
void WholeProgramState::collect_instance_finals(
const DexClass* cls,
const EligibleIfields& eligible_ifields,
FieldEnvironment field_env) {
always_assert(!cls->is_external());
if (cls->get_ctors().size() > 1) {
// Not dealing with instance field in class not having exact 1 constructor
// now. TODO(suree404): Might be able to improve?
for (auto* field : cls->get_ifields()) {
field_env.set(field, ConstantValue::top());
}
} else {
for (auto* field : cls->get_ifields()) {
if (eligible_ifields.count(field)) {
m_known_fields.emplace(field);
} else {
field_env.set(field, ConstantValue::top());
}
}
}
set_fields_in_partition(cls, field_env, FieldType::INSTANCE,
&m_field_partition);
}
bool WholeProgramAwareAnalyzer::analyze_sget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_iget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_invoke(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto op = insn->opcode();
if (op != OPCODE_INVOKE_DIRECT && op != OPCODE_INVOKE_STATIC &&
op != OPCODE_INVOKE_VIRTUAL) {
return false;
}
auto method = resolve_method(insn->get_method(), opcode_to_search(insn));
if (method == nullptr) {
return false;
}
auto value = whole_program_state->get_return_value(method);
if (value.is_top()) {
return false;
}
env->set(RESULT_REGISTER, value);
return true;
}
} // namespace constant_propagation
<commit_msg>fix possile bug in IPCP<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ConstantPropagationWholeProgramState.h"
#include "IPConstantPropagationAnalysis.h"
#include "Walkers.h"
using namespace constant_propagation;
namespace {
/*
* Walk all the static or instance fields in :cls, copying their bindings in
* :field_env over to :field_partition.
*/
void set_fields_in_partition(const DexClass* cls,
const FieldEnvironment& field_env,
const FieldType& field_type,
ConstantFieldPartition* field_partition) {
// Note that we *must* iterate over the list of fields in the class and not
// the bindings in field_env here. This ensures that fields whose values are
// unknown (and therefore implicitly represented by Top in the field_env)
// get correctly bound to Top in field_partition (which defaults its
// bindings to Bottom).
const auto& fields =
field_type == FieldType::STATIC ? cls->get_sfields() : cls->get_ifields();
for (auto& field : fields) {
auto value = field_env.get(field);
if (!value.is_top()) {
TRACE(ICONSTP, 2, "%s has value %s after <clinit> or <init>",
SHOW(field), SHOW(value));
always_assert(field->get_class() == cls->get_type());
} else {
TRACE(ICONSTP, 2, "%s has unknown value after <clinit> or <init>",
SHOW(field));
}
field_partition->set(field, value);
}
}
/*
* Record in :field_partition the values of the static fields after the class
* initializers have finished executing.
*
* XXX this assumes that there are no cycles in the class initialization graph!
*/
void analyze_clinits(const Scope& scope,
const interprocedural::FixpointIterator& fp_iter,
ConstantFieldPartition* field_partition) {
for (DexClass* cls : scope) {
auto& dmethods = cls->get_dmethods();
auto clinit = cls->get_clinit();
if (clinit == nullptr) {
// If there is no class initializer, then the initial field values are
// simply the DexEncodedValues.
ConstantEnvironment env;
set_encoded_values(cls, &env);
set_fields_in_partition(cls, env.get_field_environment(),
FieldType::STATIC, field_partition);
continue;
}
IRCode* code = clinit->get_code();
auto& cfg = code->cfg();
auto intra_cp = fp_iter.get_intraprocedural_analysis(clinit);
auto env = intra_cp->get_exit_state_at(cfg.exit_block());
set_fields_in_partition(cls, env.get_field_environment(), FieldType::STATIC,
field_partition);
}
}
bool analyze_gets_helper(const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto field = resolve_field(insn->get_field());
if (field == nullptr) {
return false;
}
auto value = whole_program_state->get_field_value(field);
if (value.is_top()) {
return false;
}
env->set(RESULT_REGISTER, value);
return true;
}
bool not_eligible_ifield(DexField* field) {
return is_static(field) || field->is_external() || !can_delete(field) ||
is_volatile(field);
}
/**
* Initialize non-external, can be deleted instance fields' value to be 0.
*/
void initialize_ifields(const Scope& scope,
ConstantFieldPartition* field_partition) {
walk::fields(scope, [&](DexField* field) {
if (not_eligible_ifield(field)) {
return;
}
field_partition->set(field, SignedConstantDomain(0));
});
}
} // namespace
namespace constant_propagation {
WholeProgramState::WholeProgramState(
const Scope& scope,
const interprocedural::FixpointIterator& fp_iter,
const std::vector<DexMethod*>& non_true_virtuals,
const std::unordered_set<const DexType*>& field_black_list) {
walk::fields(scope, [&](DexField* field) {
// We exclude those marked by keep rules: keep-marked fields may be
// written to by non-Dex bytecode.
// All fields not in m_known_fields will be bound to Top.
if (field_black_list.count(field->get_class())) {
return;
}
if (is_static(field) && !root(field)) {
m_known_fields.emplace(field);
}
if (not_eligible_ifield(field)) {
return;
}
m_known_fields.emplace(field);
});
// Put non-root non true virtual methods in known methods.
for (const auto& non_true_virtual : non_true_virtuals) {
if (!root(non_true_virtual) && non_true_virtual->get_code()) {
m_known_methods.emplace(non_true_virtual);
}
}
walk::code(scope, [&](DexMethod* method, const IRCode&) {
if (!method->is_virtual() && method->get_code()) {
// Put non virtual methods in known methods.
m_known_methods.emplace(method);
}
});
analyze_clinits(scope, fp_iter, &m_field_partition);
collect(scope, fp_iter);
}
/*
* Walk over the entire program, doing a join over the values written to each
* field, as well as a join over the values returned by each method.
*/
void WholeProgramState::collect(
const Scope& scope, const interprocedural::FixpointIterator& fp_iter) {
initialize_ifields(scope, &m_field_partition);
walk::methods(scope, [&](DexMethod* method) {
IRCode* code = method->get_code();
if (code == nullptr) {
return;
}
auto& cfg = code->cfg();
auto intra_cp = fp_iter.get_intraprocedural_analysis(method);
for (cfg::Block* b : cfg.blocks()) {
auto env = intra_cp->get_entry_state_at(b);
for (auto& mie : InstructionIterable(b)) {
auto* insn = mie.insn;
intra_cp->analyze_instruction(insn, &env);
collect_field_values(insn, env,
is_clinit(method) ? method->get_class() : nullptr);
collect_return_values(insn, env, method);
}
}
});
}
/*
* For each field, do a join over all the values that may have been
* written to it at any point in the program.
*
* If we are encountering a static field write of some value to Foo.someField
* in the body of Foo.<clinit>, don't do anything -- that value will only be
* visible to other methods if it remains unchanged up until the end of the
* <clinit>. In that case, analyze_clinits() will record it.
*/
void WholeProgramState::collect_field_values(const IRInstruction* insn,
const ConstantEnvironment& env,
const DexType* clinit_cls) {
if (!is_sput(insn->opcode()) && !is_iput(insn->opcode())) {
return;
}
auto field = resolve_field(insn->get_field());
if (field != nullptr && m_known_fields.count(field)) {
if (is_sput(insn->opcode()) && field->get_class() == clinit_cls) {
return;
}
auto value = env.get(insn->src(0));
m_field_partition.update(field, [&value](auto* current_value) {
current_value->join_with(value);
});
}
}
/*
* For each method, do a join over all the values that can be returned by it.
*
* If there are no reachable return opcodes in the method, then it never
* returns. Its return value will be represented by Bottom in our analysis.
*/
void WholeProgramState::collect_return_values(const IRInstruction* insn,
const ConstantEnvironment& env,
const DexMethod* method) {
auto op = insn->opcode();
if (!is_return(op)) {
return;
}
if (op == OPCODE_RETURN_VOID) {
// We must set the binding to Top here to record the fact that this method
// does indeed return -- even though `void` is not actually a return value,
// this tells us that the code following any invoke of this method is
// reachable.
m_method_partition.update(
method, [](auto* current_value) { current_value->set_to_top(); });
return;
}
auto value = env.get(insn->src(0));
m_method_partition.update(method, [&value](auto* current_value) {
current_value->join_with(value);
});
}
void WholeProgramState::collect_static_finals(const DexClass* cls,
FieldEnvironment field_env) {
for (auto* field : cls->get_sfields()) {
if (is_static(field) && is_final(field) && !field->is_external()) {
m_known_fields.emplace(field);
} else {
field_env.set(field, ConstantValue::top());
}
}
set_fields_in_partition(cls, field_env, FieldType::STATIC,
&m_field_partition);
}
void WholeProgramState::collect_instance_finals(
const DexClass* cls,
const EligibleIfields& eligible_ifields,
FieldEnvironment field_env) {
always_assert(!cls->is_external());
if (cls->get_ctors().size() > 1) {
// Not dealing with instance field in class not having exact 1 constructor
// now. TODO(suree404): Might be able to improve?
for (auto* field : cls->get_ifields()) {
field_env.set(field, ConstantValue::top());
}
} else {
for (auto* field : cls->get_ifields()) {
if (eligible_ifields.count(field)) {
m_known_fields.emplace(field);
} else {
field_env.set(field, ConstantValue::top());
}
}
}
set_fields_in_partition(cls, field_env, FieldType::INSTANCE,
&m_field_partition);
}
bool WholeProgramAwareAnalyzer::analyze_sget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_iget(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
return analyze_gets_helper(whole_program_state, insn, env);
}
bool WholeProgramAwareAnalyzer::analyze_invoke(
const WholeProgramState* whole_program_state,
const IRInstruction* insn,
ConstantEnvironment* env) {
if (whole_program_state == nullptr) {
return false;
}
auto op = insn->opcode();
if (op != OPCODE_INVOKE_DIRECT && op != OPCODE_INVOKE_STATIC &&
op != OPCODE_INVOKE_VIRTUAL) {
return false;
}
auto method = resolve_method(insn->get_method(), opcode_to_search(insn));
if (method == nullptr) {
return false;
}
auto value = whole_program_state->get_return_value(method);
if (value.is_top()) {
return false;
}
env->set(RESULT_REGISTER, value);
return true;
}
} // namespace constant_propagation
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<commit_msg>Auto-launch apps after installation.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasEffectiveBrowsingHistoryPermission()) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
previous_use_system_theme_(false),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_system_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#else
DCHECK(!previous_use_system_theme_);
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
return;
}
if (extension->GetFullLaunchURL().is_valid()) {
Browser::OpenApplicationTab(profile_, extension);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,
extension, profile_);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(
const std::string& previous_theme_id, bool previous_use_system_theme,
Extension* new_theme, Profile* profile) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
GetNewThemeInstalledInfoBarDelegate(
tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_), true);
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(
TabContents* tab_contents, Extension* new_theme,
const std::string& previous_theme_id, bool previous_use_system_theme) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id, previous_use_system_theme);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id);
#endif
}
<|endoftext|> |
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_AttributeBlock.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
bool
Attribute::parseInitializer()
{
ASSERT(!m_initializer.isEmpty());
Unit* prevUnit = m_module->m_unitMgr.setCurrentUnit(m_parentUnit);
bool result = m_module->m_operatorMgr.parseConstExpression(m_initializer, &m_value);
if (!result)
return false;
m_module->m_unitMgr.setCurrentUnit(prevUnit);
return true;
}
//..............................................................................
Attribute*
AttributeBlock::createAttribute(
const sl::StringRef& name,
sl::BoxList<Token>* initializer
)
{
sl::StringHashTableIterator<Attribute*> it = m_attributeMap.visit(name);
if (it->m_value)
{
err::setFormatStringError("redefinition of attribute '%s'", name.sz());
return NULL;
}
Attribute* attribute = AXL_MEM_NEW(Attribute);
attribute->m_module = m_module;
attribute->m_name = name;
if (initializer)
sl::takeOver(&attribute->m_initializer, initializer);
m_attributeList.insertTail(attribute);
m_attributeArray.append(attribute);
it->m_value = attribute;
return attribute;
}
bool
AttributeBlock::prepareAttributeValues()
{
ASSERT(!(m_flags & AttributeBlockFlag_ValuesReady));
size_t count = m_attributeArray.getCount();
for (size_t i = 0; i < count; i++)
{
Attribute* attribute = m_attributeArray[i];
if (attribute->hasInitializer())
{
bool result = attribute->parseInitializer();
if (!result)
return false;
}
}
m_flags |= AttributeBlockFlag_ValuesReady;
return true;
}
//..............................................................................
} // namespace ct
} // namespace jnc
<commit_msg>[jnc_ct] ensure layout for function attribute values<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_AttributeBlock.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
bool
Attribute::parseInitializer()
{
ASSERT(!m_initializer.isEmpty());
Unit* prevUnit = m_module->m_unitMgr.setCurrentUnit(m_parentUnit);
bool result = m_module->m_operatorMgr.parseConstExpression(m_initializer, &m_value);
if (!result)
return false;
if (m_value.getValueKind() == ValueKind_Function)
{
result = m_value.getFunction()->getType()->getFunctionPtrType(FunctionPtrTypeKind_Thin)->ensureLayout();
if (!result)
return false;
}
m_module->m_unitMgr.setCurrentUnit(prevUnit);
return true;
}
//..............................................................................
Attribute*
AttributeBlock::createAttribute(
const sl::StringRef& name,
sl::BoxList<Token>* initializer
)
{
sl::StringHashTableIterator<Attribute*> it = m_attributeMap.visit(name);
if (it->m_value)
{
err::setFormatStringError("redefinition of attribute '%s'", name.sz());
return NULL;
}
Attribute* attribute = AXL_MEM_NEW(Attribute);
attribute->m_module = m_module;
attribute->m_name = name;
if (initializer)
sl::takeOver(&attribute->m_initializer, initializer);
m_attributeList.insertTail(attribute);
m_attributeArray.append(attribute);
it->m_value = attribute;
return attribute;
}
bool
AttributeBlock::prepareAttributeValues()
{
ASSERT(!(m_flags & AttributeBlockFlag_ValuesReady));
size_t count = m_attributeArray.getCount();
for (size_t i = 0; i < count; i++)
{
Attribute* attribute = m_attributeArray[i];
if (attribute->hasInitializer())
{
bool result = attribute->parseInitializer();
if (!result)
return false;
}
}
m_flags |= AttributeBlockFlag_ValuesReady;
return true;
}
//..............................................................................
} // namespace ct
} // namespace jnc
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#elif defined(OS_MACOSX)
#include "base/scoped_cftyperef.h"
#include "base/sys_string_conversions.h"
#include <CoreFoundation/CFUserNotification.h>
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
namespace {
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
static std::wstring GetInstallWarning(Extension* extension) {
// If the extension has a plugin, it's easy: the plugin has the most severe
// warning.
if (!extension->plugins().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_FULL_ACCESS);
// Otherwise, we go in descending order of severity: all hosts, several hosts,
// a single host, no hosts. For each of these, we also have a variation of the
// message for when api permissions are also requested.
if (extension->HasAccessToAllHosts()) {
if (extension->api_permissions().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS_AND_BROWSER);
}
const std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() > 1) {
if (extension->api_permissions().empty())
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS_AND_BROWSER);
}
if (hosts.size() == 1) {
if (extension->api_permissions().empty())
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST,
UTF8ToWide(*hosts.begin()));
else
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST_AND_BROWSER,
UTF8ToWide(*hosts.begin()));
}
DCHECK(hosts.size() == 0);
if (extension->api_permissions().empty())
return L"";
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_BROWSER);
}
#endif
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile), ui_loop_(MessageLoop::current())
#if defined(TOOLKIT_GTK)
,previous_use_gtk_theme_(false)
#endif
{
}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension,
SkBitmap* install_icon) {
DCHECK(ui_loop_ == MessageLoop::current());
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_gtk_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#endif
delegate->ContinueInstall();
return;
}
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
if (!install_icon) {
install_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_DEFAULT_EXTENSION_ICON_128);
}
ShowExtensionInstallPrompt(profile_, delegate, extension, install_icon,
GetInstallWarning(extension));
#elif defined(OS_MACOSX)
// TODO(port): Implement nicer UI.
// Using CoreFoundation to do this dialog is unimaginably lame but will do
// until the UI is redone.
scoped_cftyperef<CFStringRef> confirm_title(base::SysWideToCFStringRef(
l10n_util::GetString(IDS_EXTENSION_PROMPT_TITLE)));
// Build the confirmation prompt, including a heading, a random humorous
// warning, and a severe warning.
const string16& confirm_format(ASCIIToUTF16("$1\n\n$2\n\n$3"));
std::vector<string16> subst;
subst.push_back(l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_HEADING,
UTF8ToUTF16(extension->name())));
string16 warnings[] = {
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_1),
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_2),
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_3)
};
subst.push_back(warnings[base::RandInt(0, arraysize(warnings) - 1)]);
subst.push_back(l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT_WARNING_SEVERE));
scoped_cftyperef<CFStringRef> confirm_prompt(base::SysUTF16ToCFStringRef(
ReplaceStringPlaceholders(confirm_format, subst, NULL)));
scoped_cftyperef<CFStringRef> confirm_cancel(base::SysWideToCFStringRef(
l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON)));
CFOptionFlags response;
if (kCFUserNotificationAlternateResponse == CFUserNotificationDisplayAlert(
0, kCFUserNotificationCautionAlertLevel,
NULL, // TODO(port): show the install_icon instead of a default.
NULL, NULL, // Sound URL, localization URL.
confirm_title,
confirm_prompt,
NULL, // Default button.
confirm_cancel,
NULL, // Other button.
&response)) {
delegate->AbortInstall();
} else {
delegate->ContinueInstall();
}
#else
// TODO(port): Implement some UI.
NOTREACHED();
delegate->ContinueInstall();
#endif // OS_*
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
#if defined(OS_WIN)
win_util::MessageBox(NULL, UTF8ToWide(error), L"Extension Install Error",
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_MACOSX)
// There must be a better way to do this, for all platforms.
scoped_cftyperef<CFStringRef> message_cf(
base::SysUTF8ToCFStringRef(error));
CFOptionFlags response;
CFUserNotificationDisplayAlert(
0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL,
CFSTR("Extension Install Error"), message_cf,
NULL, NULL, NULL, &response);
#else
GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", error.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
#endif
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
#if defined(TOOLKIT_GTK)
new GtkThemeInstalledInfoBarDelegate(
tab_contents,
new_theme->name(), previous_theme_id_, previous_use_gtk_theme_);
#else
new ThemeInstalledInfoBarDelegate(tab_contents,
new_theme->name(), previous_theme_id_);
#endif
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
<commit_msg>Fix extension canceling; the CFUserNotification functionality gets a bit weird.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/extensions/extension.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#elif defined(OS_MACOSX)
#include "base/scoped_cftyperef.h"
#include "base/sys_string_conversions.h"
#include <CoreFoundation/CFUserNotification.h>
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
namespace {
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
static std::wstring GetInstallWarning(Extension* extension) {
// If the extension has a plugin, it's easy: the plugin has the most severe
// warning.
if (!extension->plugins().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_FULL_ACCESS);
// Otherwise, we go in descending order of severity: all hosts, several hosts,
// a single host, no hosts. For each of these, we also have a variation of the
// message for when api permissions are also requested.
if (extension->HasAccessToAllHosts()) {
if (extension->api_permissions().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_ALL_HOSTS_AND_BROWSER);
}
const std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() > 1) {
if (extension->api_permissions().empty())
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_NEW_MULTIPLE_HOSTS_AND_BROWSER);
}
if (hosts.size() == 1) {
if (extension->api_permissions().empty())
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST,
UTF8ToWide(*hosts.begin()));
else
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_NEW_SINGLE_HOST_AND_BROWSER,
UTF8ToWide(*hosts.begin()));
}
DCHECK(hosts.size() == 0);
if (extension->api_permissions().empty())
return L"";
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_NEW_BROWSER);
}
#endif
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile), ui_loop_(MessageLoop::current())
#if defined(TOOLKIT_GTK)
,previous_use_gtk_theme_(false)
#endif
{
}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension,
SkBitmap* install_icon) {
DCHECK(ui_loop_ == MessageLoop::current());
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_gtk_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#endif
delegate->ContinueInstall();
return;
}
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
if (!install_icon) {
install_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_DEFAULT_EXTENSION_ICON_128);
}
ShowExtensionInstallPrompt(profile_, delegate, extension, install_icon,
GetInstallWarning(extension));
#elif defined(OS_MACOSX)
// TODO(port): Implement nicer UI.
// Using CoreFoundation to do this dialog is unimaginably lame but will do
// until the UI is redone.
scoped_cftyperef<CFStringRef> confirm_title(base::SysWideToCFStringRef(
l10n_util::GetString(IDS_EXTENSION_PROMPT_TITLE)));
// Build the confirmation prompt, including a heading, a random humorous
// warning, and a severe warning.
const string16& confirm_format(ASCIIToUTF16("$1\n\n$2\n\n$3"));
std::vector<string16> subst;
subst.push_back(l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_HEADING,
UTF8ToUTF16(extension->name())));
string16 warnings[] = {
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_1),
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_2),
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_3)
};
subst.push_back(warnings[base::RandInt(0, arraysize(warnings) - 1)]);
subst.push_back(l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT_WARNING_SEVERE));
scoped_cftyperef<CFStringRef> confirm_prompt(base::SysUTF16ToCFStringRef(
ReplaceStringPlaceholders(confirm_format, subst, NULL)));
scoped_cftyperef<CFStringRef> confirm_cancel(base::SysWideToCFStringRef(
l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON)));
CFOptionFlags response;
CFUserNotificationDisplayAlert(
0, kCFUserNotificationCautionAlertLevel,
NULL, // TODO(port): show the install_icon instead of a default.
NULL, NULL, // Sound URL, localization URL.
confirm_title,
confirm_prompt,
NULL, // Default button.
confirm_cancel,
NULL, // Other button.
&response);
if (response == kCFUserNotificationAlternateResponse) {
delegate->AbortInstall();
} else {
delegate->ContinueInstall();
}
#else
// TODO(port): Implement some UI.
NOTREACHED();
delegate->ContinueInstall();
#endif // OS_*
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
#if defined(OS_WIN)
win_util::MessageBox(NULL, UTF8ToWide(error), L"Extension Install Error",
MB_OK | MB_SETFOREGROUND);
#elif defined(OS_MACOSX)
// There must be a better way to do this, for all platforms.
scoped_cftyperef<CFStringRef> message_cf(
base::SysUTF8ToCFStringRef(error));
CFOptionFlags response;
CFUserNotificationDisplayAlert(
0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL,
CFSTR("Extension Install Error"), message_cf,
NULL, NULL, NULL, &response);
#else
GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", error.c_str());
gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
#endif
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate =
#if defined(TOOLKIT_GTK)
new GtkThemeInstalledInfoBarDelegate(
tab_contents,
new_theme->name(), previous_theme_id_, previous_use_gtk_theme_);
#else
new ThemeInstalledInfoBarDelegate(tab_contents,
new_theme->name(), previous_theme_id_);
#endif
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: iconcache.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2005-04-20 11:42: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): _______________________________________
*
*
************************************************************************/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <stdlib.h>
extern "C" UINT __stdcall RebuildShellIconCache(MSIHANDLE handle)
{
// Rebuild icon cache on windows OS prior XP
OSVERSIONINFO osverinfo;
osverinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (
GetVersionEx( &osverinfo ) &&
VER_PLATFORM_WIN32_NT == osverinfo.dwPlatformId &&
(
5 < osverinfo.dwMajorVersion ||
5 == osverinfo.dwMajorVersion && 0 < osverinfo.dwMinorVersion
)
)
{
return ERROR_SUCCESS;
}
HKEY hKey;
DWORD dwDispostion;
LONG lError = RegCreateKeyEx( HKEY_CURRENT_USER, TEXT("Control Panel\\Desktop\\WindowMetrics"), 0, NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL, &hKey, &dwDispostion );
if ( ERROR_SUCCESS == lError )
{
TCHAR szValue[256];
TCHAR szTempValue[256];
DWORD cbValue = sizeof(szValue);
DWORD dwType;
int iSize = 0;
lError = RegQueryValueEx( hKey, TEXT("Shell Icon Size"), 0, &dwType, (LPBYTE)szValue, &cbValue );
if ( ERROR_SUCCESS == lError )
iSize = atoi( szValue );
if ( !iSize )
{
iSize = GetSystemMetrics( SM_CXICON );
itoa( iSize, szValue, 10 );
cbValue = strlen( szValue ) + 1;
dwType = REG_SZ;
}
itoa( iSize + 1, szTempValue, 10 );
lError = RegSetValueEx( hKey, TEXT("Shell Icon Size"), 0, dwType, (LPBYTE)szTempValue, strlen( szTempValue ) + 1 );
LRESULT lResult = SendMessageTimeout(
HWND_BROADCAST,
WM_SETTINGCHANGE,
SPI_SETNONCLIENTMETRICS,
(LPARAM)TEXT("WindowMetrics"),
SMTO_NORMAL|SMTO_ABORTIFHUNG,
0, NULL);
lError = RegSetValueEx( hKey, TEXT("Shell Icon Size"), 0, dwType, (LPBYTE)szValue, cbValue );
lResult = SendMessageTimeout(
HWND_BROADCAST,
WM_SETTINGCHANGE,
SPI_SETNONCLIENTMETRICS,
(LPARAM)TEXT("WindowMetrics"),
SMTO_NORMAL|SMTO_ABORTIFHUNG,
0, NULL);
lError = RegCloseKey( hKey );
}
return ERROR_SUCCESS;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.44); FILE MERGED 2005/09/05 17:36:45 rt 1.2.44.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: iconcache.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 16:39:53 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#include <stdlib.h>
extern "C" UINT __stdcall RebuildShellIconCache(MSIHANDLE handle)
{
// Rebuild icon cache on windows OS prior XP
OSVERSIONINFO osverinfo;
osverinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (
GetVersionEx( &osverinfo ) &&
VER_PLATFORM_WIN32_NT == osverinfo.dwPlatformId &&
(
5 < osverinfo.dwMajorVersion ||
5 == osverinfo.dwMajorVersion && 0 < osverinfo.dwMinorVersion
)
)
{
return ERROR_SUCCESS;
}
HKEY hKey;
DWORD dwDispostion;
LONG lError = RegCreateKeyEx( HKEY_CURRENT_USER, TEXT("Control Panel\\Desktop\\WindowMetrics"), 0, NULL, REG_OPTION_VOLATILE, KEY_SET_VALUE | KEY_QUERY_VALUE, NULL, &hKey, &dwDispostion );
if ( ERROR_SUCCESS == lError )
{
TCHAR szValue[256];
TCHAR szTempValue[256];
DWORD cbValue = sizeof(szValue);
DWORD dwType;
int iSize = 0;
lError = RegQueryValueEx( hKey, TEXT("Shell Icon Size"), 0, &dwType, (LPBYTE)szValue, &cbValue );
if ( ERROR_SUCCESS == lError )
iSize = atoi( szValue );
if ( !iSize )
{
iSize = GetSystemMetrics( SM_CXICON );
itoa( iSize, szValue, 10 );
cbValue = strlen( szValue ) + 1;
dwType = REG_SZ;
}
itoa( iSize + 1, szTempValue, 10 );
lError = RegSetValueEx( hKey, TEXT("Shell Icon Size"), 0, dwType, (LPBYTE)szTempValue, strlen( szTempValue ) + 1 );
LRESULT lResult = SendMessageTimeout(
HWND_BROADCAST,
WM_SETTINGCHANGE,
SPI_SETNONCLIENTMETRICS,
(LPARAM)TEXT("WindowMetrics"),
SMTO_NORMAL|SMTO_ABORTIFHUNG,
0, NULL);
lError = RegSetValueEx( hKey, TEXT("Shell Icon Size"), 0, dwType, (LPBYTE)szValue, cbValue );
lResult = SendMessageTimeout(
HWND_BROADCAST,
WM_SETTINGCHANGE,
SPI_SETNONCLIENTMETRICS,
(LPARAM)TEXT("WindowMetrics"),
SMTO_NORMAL|SMTO_ABORTIFHUNG,
0, NULL);
lError = RegCloseKey( hKey );
}
return ERROR_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Jae-jun Kang
// See the file COPYING for license details.
#include "xpiler.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include "document.hpp"
#include "boost_formatter.hpp"
#include "xml_handler.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace xpiler
{
options xpiler::opts;
xpiler::handler_map_type xpiler::handlers_;
xpiler::formatter_map_type xpiler::formatters_;
xpiler::static_initializer xpiler::static_init_;
xpiler::xpiler()
{
formatter_ = formatters_[opts.spec];
formatter_->setup();
}
void xpiler::process(const string& path)
{
if (fs::is_directory(path))
{
process_dir(path);
}
else if (fs::exists(path))
{
process_file(path);
}
else
{
cout << path << " doesn't exist." << endl;
error = true;
}
}
void xpiler::process_dir(const fs::path& path)
{
cout << "Directory " << fs::canonical(path).string() << endl;
fs::directory_iterator di(path);
fs::directory_iterator end;
for (; di != end; ++di)
{
fs::directory_entry& entry = *di;
fs::path filename = entry.path().filename();
fs::path pathname = path / filename;
if (fs::is_directory(entry.status()))
{
if (opts.recursive)
{
sub_dirs_.push_back(filename.string());
process_dir(pathname);
sub_dirs_.pop_back();
}
}
else
{
process_file(pathname);
}
}
}
void xpiler::process_file(const fs::path& path)
{
fs::path filename = path.filename();
string extension = path.extension().string();
fs::path out_dir;
if (opts.out_dir.empty())
{
out_dir = path.parent_path();
}
else
{
out_dir = opts.out_dir;
BOOST_FOREACH(string& sub_dir, sub_dirs_)
{
out_dir /= sub_dir;
}
}
boost::algorithm::to_lower(extension);
handler_map_type::iterator it = handlers_.find(extension);
if (it == handlers_.end() ||
(!opts.forced && formatter_->is_up_to_date(path)))
{
return;
}
handler* handler = it->second;
cout << filename.string() << endl;
document* doc;
if (!handler->handle(path.string(), &doc))
{
error = true;
}
if (error == true || doc == NULL)
{
return;
}
doc->basename = filename.stem().string();
if (!out_dir.empty() && !fs::is_directory(out_dir))
{
fs::create_directories(out_dir);
}
if (!formatter_->format(doc, out_dir.string()))
{
error = true;
}
delete doc;
}
xpiler::static_initializer::static_initializer()
{
handlers_[".xml"] = new xml_handler;
formatters_["boost"] = new boost_formatter;
}
xpiler::static_initializer::~static_initializer()
{
BOOST_FOREACH(handler_map_type::value_type& pair, handlers_)
{
delete pair.second;
}
BOOST_FOREACH(formatter_map_type::value_type& pair, formatters_)
{
delete pair.second;
}
}
}
// EOF xpiler.cpp
<commit_msg>touched xpiler<commit_after>// Copyright (c) 2014 Jae-jun Kang
// See the file COPYING for license details.
#include "xpiler.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include "document.hpp"
#include "boost_formatter.hpp"
#include "xml_handler.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace xpiler
{
options xpiler::opts;
xpiler::handler_map_type xpiler::handlers_;
xpiler::formatter_map_type xpiler::formatters_;
xpiler::static_initializer xpiler::static_init_;
xpiler::xpiler()
{
formatter_ = formatters_[opts.spec];
formatter_->setup();
}
void xpiler::process(const string& path)
{
if (fs::is_directory(path))
{
process_dir(path);
}
else if (fs::exists(path))
{
process_file(path);
}
else
{
cout << path << " doesn't exist." << endl;
error = true;
}
}
void xpiler::process_dir(const fs::path& path)
{
cout << "Directory " << fs::canonical(path).string() << endl;
fs::directory_iterator di(path);
fs::directory_iterator end;
for (; di != end; ++di)
{
fs::directory_entry& entry = *di;
fs::path filename = entry.path().filename();
fs::path pathname = path / filename;
if (fs::is_directory(entry.status()))
{
if (opts.recursive)
{
sub_dirs_.push_back(filename.string());
process_dir(pathname);
sub_dirs_.pop_back();
}
}
else
{
process_file(pathname);
}
}
}
void xpiler::process_file(const fs::path& path)
{
fs::path filename = path.filename();
string extension = path.extension().string();
fs::path out_dir;
if (opts.out_dir.empty())
{
out_dir = path.parent_path();
}
else
{
out_dir = opts.out_dir;
BOOST_FOREACH(string& sub_dir, sub_dirs_)
{
out_dir /= sub_dir;
}
}
boost::algorithm::to_lower(extension);
handler_map_type::iterator it = handlers_.find(extension);
if (it == handlers_.end() ||
(!opts.forced && formatter_->is_up_to_date(path)))
{
return;
}
handler* handler = it->second;
document* doc;
if (!handler->handle(path.string(), &doc))
{
error = true;
}
if (error == true || doc == NULL)
{
return;
}
cout << filename.string() << endl;
doc->basename = filename.stem().string();
if (!out_dir.empty() && !fs::is_directory(out_dir))
{
fs::create_directories(out_dir);
}
if (!formatter_->format(doc, out_dir.string()))
{
error = true;
}
delete doc;
}
xpiler::static_initializer::static_initializer()
{
handlers_[".xml"] = new xml_handler;
formatters_["boost"] = new boost_formatter;
}
xpiler::static_initializer::~static_initializer()
{
BOOST_FOREACH(handler_map_type::value_type& pair, handlers_)
{
delete pair.second;
}
BOOST_FOREACH(formatter_map_type::value_type& pair, formatters_)
{
delete pair.second;
}
}
}
// EOF xpiler.cpp
<|endoftext|> |
<commit_before>#include <pistache/http_headers.h>
#include <pistache/date.h>
#include "gtest/gtest.h"
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace Pistache::Http;
TEST(headers_test, accept) {
Header::Accept a1;
a1.parse("audio/*; q=0.2");
{
const auto& media = a1.media();
ASSERT_EQ(media.size(), 1U);
const auto& mime = media[0];
ASSERT_EQ(mime, MIME(Audio, Star));
ASSERT_EQ(mime.q().getOrElse(Mime::Q(0)), Mime::Q(20));
}
Header::Accept a2;
a2.parse("text/*, text/html, text/html;level=1, */*");
{
const auto& media = a2.media();
ASSERT_EQ(media.size(), 4U);
const auto &m1 = media[0];
ASSERT_EQ(m1, MIME(Text, Star));
const auto &m2 = media[1];
ASSERT_EQ(m2, MIME(Text, Html));
const auto& m3 = media[2];
ASSERT_EQ(m3, MIME(Text, Html));
auto level = m3.getParam("level");
ASSERT_EQ(level.getOrElse(""), "1");
const auto& m4 = media[3];
ASSERT_EQ(m4, MIME(Star, Star));
}
Header::Accept a3;
a3.parse("text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
"text/html;level=2;q=0.4, */*;q=0.5");
{
const auto& media = a3.media();
ASSERT_EQ(media.size(), 5U);
ASSERT_EQ(media[0], MIME(Text, Star));
ASSERT_EQ(media[0].q().getOrElse(Mime::Q(0)), Mime::Q(30));
ASSERT_EQ(media[1], MIME(Text, Html));
ASSERT_EQ(media[2], MIME(Text, Html));
ASSERT_EQ(media[3], MIME(Text, Html));
ASSERT_EQ(media[4], MIME(Star, Star));
ASSERT_EQ(media[4].q().getOrElse(Mime::Q(0)), Mime::Q::fromFloat(0.5));
}
Header::Accept a4;
ASSERT_THROW(a4.parse("text/*;q=0.4, text/html;q=0.3,"), std::runtime_error);
Header::Accept a5;
ASSERT_THROW(a5.parse("text/*;q=0.4, text/html;q=0.3, "), std::runtime_error);
}
TEST(headers_test, allow) {
Header::Allow a1(Method::Get);
std::ostringstream os;
a1.write(os);
ASSERT_EQ(os.str(), "GET");
os.str("");
Header::Allow a2({ Method::Post, Method::Put });
a2.write(os);
ASSERT_EQ(os.str(), "POST, PUT");
os.str("");
Header::Allow a3;
a3.addMethod(Method::Get);
a3.write(os);
ASSERT_EQ(os.str(), "GET");
os.str("");
a3.addMethod(Method::Options);
a3.write(os);
ASSERT_EQ(os.str(), "GET, OPTIONS");
os.str("");
Header::Allow a4(Method::Head);
a4.addMethods({ Method::Get, Method::Options });
a4.write(os);
ASSERT_EQ(os.str(), "HEAD, GET, OPTIONS");
}
TEST(headers_test, cache_control) {
auto testTrivial = [](std::string str, CacheDirective::Directive expected) {
Header::CacheControl cc;
cc.parse(str);
auto directives = cc.directives();
ASSERT_EQ(directives.size(), 1U);
ASSERT_EQ(directives[0].directive(), expected);
};
auto testTimed = [](
std::string str, CacheDirective::Directive expected, uint64_t delta) {
Header::CacheControl cc;
cc.parse(str);
auto directives = cc.directives();
ASSERT_EQ(directives.size(), 1U);
ASSERT_EQ(directives[0].directive(), expected);
ASSERT_EQ(directives[0].delta(), std::chrono::seconds(delta));
};
testTrivial("no-cache", CacheDirective::NoCache);
testTrivial("no-store", CacheDirective::NoStore);
testTrivial("no-transform", CacheDirective::NoTransform);
testTrivial("only-if-cached", CacheDirective::OnlyIfCached);
testTimed("max-age=0", CacheDirective::MaxAge, 0);
testTimed("max-age=12", CacheDirective::MaxAge, 12);
testTimed("max-stale=12345", CacheDirective::MaxStale, 12345);
testTimed("min-fresh=48", CacheDirective::MinFresh, 48);
Header::CacheControl cc1;
cc1.parse("private, max-age=600");
auto d1 = cc1.directives();
ASSERT_EQ(d1.size(), 2U);
ASSERT_EQ(d1[0].directive(), CacheDirective::Private);
ASSERT_EQ(d1[1].directive(), CacheDirective::MaxAge);
ASSERT_EQ(d1[1].delta(), std::chrono::seconds(600));
Header::CacheControl cc2;
cc2.parse("public, s-maxage=200, proxy-revalidate");
auto d2 = cc2.directives();
ASSERT_EQ(d2.size(), 3U);
ASSERT_EQ(d2[0].directive(), CacheDirective::Public);
ASSERT_EQ(d2[1].directive(), CacheDirective::SMaxAge);
ASSERT_EQ(d2[1].delta(), std::chrono::seconds(200));
ASSERT_EQ(d2[2].directive(), CacheDirective::ProxyRevalidate);
Header::CacheControl cc3(CacheDirective::NoCache);
std::ostringstream oss;
cc3.write(oss);
ASSERT_EQ(oss.str(), "no-cache");
oss.str("");
cc3.addDirective(CacheDirective::NoStore);
cc3.write(oss);
ASSERT_EQ(oss.str(), "no-cache, no-store");
oss.str("");
Header::CacheControl cc4;
cc4.addDirectives({
CacheDirective::Public,
CacheDirective(CacheDirective::MaxAge, std::chrono::seconds(600))
});
cc4.write(oss);
ASSERT_EQ(oss.str(), "public, max-age=600");
}
TEST(headers_test, content_length) {
Header::ContentLength cl;
cl.parse("3495");
ASSERT_EQ(cl.value(), 3495U);
}
TEST(headers_test, connection) {
Header::Connection connection;
constexpr struct Test {
const char *data;
ConnectionControl expected;
} tests[] = {
{ "close", ConnectionControl::Close },
{ "clOse", ConnectionControl::Close },
{ "Close", ConnectionControl::Close },
{ "CLOSE", ConnectionControl::Close },
{ "keep-alive", ConnectionControl::KeepAlive },
{ "Keep-Alive", ConnectionControl::KeepAlive },
{ "kEEp-alIvE", ConnectionControl::KeepAlive },
{ "KEEP-ALIVE", ConnectionControl::KeepAlive }
};
for (auto test: tests) {
Header::Connection connection;
connection.parse(test.data);
ASSERT_EQ(connection.control(), test.expected);
}
}
TEST(headers_test, date_test_rfc_1123) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* RFC-1123 */
Header::Date d1;
d1.parse("Sun, 06 Nov 1994 08:49:37 GMT");
auto dd1 = d1.fullDate().date();
ASSERT_EQ(expected_time_point, dd1);
}
TEST(headers_test, date_test_rfc_850) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* RFC-850 */
Header::Date d2;
d2.parse("Sunday, 06-Nov-94 08:49:37 GMT");
auto dd2 = d2.fullDate().date();
ASSERT_EQ(dd2, expected_time_point);
}
TEST(headers_test, date_test_asctime) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* ANSI C's asctime format */
Header::Date d3;
d3.parse("Sun Nov 6 08:49:37 1994");
auto dd3 = d3.fullDate().date();
ASSERT_EQ(dd3, expected_time_point);
}
TEST(headers_test, date_test_ostream) {
std::ostringstream os;
Header::Date d4;
d4.parse("Fri, 25 Jan 2019 21:04:45.000000000 UTC");
d4.write(os);
ASSERT_EQ("Fri, 25 Jan 2019 21:04:45.000000000 UTC", os.str());
}
TEST(headers_test, host) {
Header::Host host;
host.parse("www.w3.org");
ASSERT_EQ(host.host(), "www.w3.org");
ASSERT_EQ(host.port(), 80);
host.parse("www.example.com:8080");
ASSERT_EQ(host.host(), "www.example.com");
ASSERT_EQ(host.port(), 8080);
host.parse("localhost:8080");
ASSERT_EQ(host.host(), "localhost");
ASSERT_EQ(host.port(), 8080);
/* Due to an error in GLIBC these tests don't fail as expected, further research needed */
// ASSERT_THROW( host.parse("256.256.256.256:8080");, std::invalid_argument);
// ASSERT_THROW( host.parse("1.0.0.256:8080");, std::invalid_argument);
host.parse("[::1]:8080");
ASSERT_EQ(host.host(), "[::1]");
ASSERT_EQ(host.port(), 8080);
host.parse("[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]:8080");
ASSERT_EQ(host.host(), "[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]");
ASSERT_EQ(host.port(), 8080);
/* Due to an error in GLIBC these tests don't fail as expected, further research needed */
// ASSERT_THROW( host.parse("[GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG]:8080");, std::invalid_argument);
// ASSERT_THROW( host.parse("[::GGGG]:8080");, std::invalid_argument);
}
TEST(headers_test, user_agent) {
Header::UserAgent ua;
ua.parse("CERN-LineMode/2.15 libwww/2.17b3");
ASSERT_EQ(ua.agent(), "CERN-LineMode/2.15 libwww/2.17b3");
}
TEST(headers_test, content_encoding) {
Header::ContentEncoding ce;
ce.parse("gzip");
ASSERT_EQ(ce.encoding(), Header::Encoding::Gzip);
}
TEST(headers_test, content_type) {
Header::ContentType ct;
ct.parse("text/html; charset=ISO-8859-4");
const auto& mime = ct.mime();
ASSERT_EQ(mime, MIME(Text, Html));
ASSERT_EQ(mime.getParam("charset").getOrElse(""), "ISO-8859-4");
}
TEST(headers_test, access_control_allow_origin_test)
{
Header::AccessControlAllowOrigin allowOrigin;
allowOrigin.parse("http://foo.bar");
ASSERT_EQ(allowOrigin.uri(), "http://foo.bar");
}
TEST(headers_test, access_control_allow_headers_test)
{
Header::AccessControlAllowHeaders allowHeaders;
allowHeaders.parse("Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
ASSERT_EQ(allowHeaders.val(), "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
}
TEST(headers_test, access_control_expose_headers_test)
{
Header::AccessControlExposeHeaders exposeHeaders;
exposeHeaders.parse("Accept, Location");
ASSERT_EQ(exposeHeaders.val(), "Accept, Location");
}
TEST(headers_test, access_control_allow_methods_test)
{
Header::AccessControlAllowMethods allowMethods;
allowMethods.parse("GET, POST, DELETE");
ASSERT_EQ(allowMethods.val(), "GET, POST, DELETE");
}
CUSTOM_HEADER(TestHeader)
TEST(header_test, macro_for_custom_headers)
{
TestHeader testHeader;
ASSERT_TRUE( strcmp(TestHeader::Name,"TestHeader") == 0);
testHeader.parse("Header Content Test");
ASSERT_EQ(testHeader.val(), "Header Content Test");
}
TEST(headers_test, add_new_header_test)
{
const std::string headerName = "TestHeader";
ASSERT_FALSE(Header::Registry::instance().isRegistered(headerName));
Header::Registry::instance().registerHeader<TestHeader>();
ASSERT_TRUE(Header::Registry::instance().isRegistered(headerName));
const auto& headersList = Header::Registry::instance().headersList();
const bool isFound = std::find(headersList.begin(), headersList.end(), headerName) != headersList.end();
ASSERT_TRUE(isFound);
}
<commit_msg>Added test cases to exceptions and some uncovered methods in headers<commit_after>#include <pistache/http_headers.h>
#include <pistache/date.h>
#include "gtest/gtest.h"
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace Pistache::Http;
TEST(headers_test, accept) {
Header::Accept a1;
a1.parse("audio/*; q=0.2");
{
const auto& media = a1.media();
ASSERT_EQ(media.size(), 1U);
const auto& mime = media[0];
ASSERT_EQ(mime, MIME(Audio, Star));
ASSERT_EQ(mime.q().getOrElse(Mime::Q(0)), Mime::Q(20));
}
Header::Accept a2;
a2.parse("text/*, text/html, text/html;level=1, */*");
{
const auto& media = a2.media();
ASSERT_EQ(media.size(), 4U);
const auto &m1 = media[0];
ASSERT_EQ(m1, MIME(Text, Star));
const auto &m2 = media[1];
ASSERT_EQ(m2, MIME(Text, Html));
const auto& m3 = media[2];
ASSERT_EQ(m3, MIME(Text, Html));
auto level = m3.getParam("level");
ASSERT_EQ(level.getOrElse(""), "1");
const auto& m4 = media[3];
ASSERT_EQ(m4, MIME(Star, Star));
}
Header::Accept a3;
a3.parse("text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
"text/html;level=2;q=0.4, */*;q=0.5");
{
const auto& media = a3.media();
ASSERT_EQ(media.size(), 5U);
ASSERT_EQ(media[0], MIME(Text, Star));
ASSERT_EQ(media[0].q().getOrElse(Mime::Q(0)), Mime::Q(30));
ASSERT_EQ(media[1], MIME(Text, Html));
ASSERT_EQ(media[2], MIME(Text, Html));
ASSERT_EQ(media[3], MIME(Text, Html));
ASSERT_EQ(media[4], MIME(Star, Star));
ASSERT_EQ(media[4].q().getOrElse(Mime::Q(0)), Mime::Q::fromFloat(0.5));
}
Header::Accept a4;
ASSERT_THROW(a4.parse("text/*;q=0.4, text/html;q=0.3,"), std::runtime_error);
Header::Accept a5;
ASSERT_THROW(a5.parse("text/*;q=0.4, text/html;q=0.3, "), std::runtime_error);
}
TEST(headers_test, allow) {
Header::Allow a1(Method::Get);
std::ostringstream os;
a1.write(os);
ASSERT_EQ(os.str(), "GET");
os.str("");
Header::Allow a2({ Method::Post, Method::Put });
a2.write(os);
ASSERT_EQ(os.str(), "POST, PUT");
os.str("");
Header::Allow a3;
a3.addMethod(Method::Get);
a3.write(os);
ASSERT_EQ(os.str(), "GET");
os.str("");
a3.addMethod(Method::Options);
a3.write(os);
ASSERT_EQ(os.str(), "GET, OPTIONS");
os.str("");
Header::Allow a4(Method::Head);
a4.addMethods({ Method::Get, Method::Options });
a4.write(os);
ASSERT_EQ(os.str(), "HEAD, GET, OPTIONS");
os.str("");
Header::Allow a5(Method::Head);
std::vector<Method> methods;
methods.push_back(Method::Get);
a5.addMethods(methods);
a5.write(os);
ASSERT_EQ(os.str(), "HEAD, GET");
}
TEST(headers_test, cache_control) {
auto testTrivial = [](std::string str, CacheDirective::Directive expected) {
Header::CacheControl cc;
cc.parse(str);
auto directives = cc.directives();
ASSERT_EQ(directives.size(), 1U);
ASSERT_EQ(directives[0].directive(), expected);
};
auto testTimed = [](
std::string str, CacheDirective::Directive expected, uint64_t delta) {
Header::CacheControl cc;
cc.parse(str);
auto directives = cc.directives();
ASSERT_EQ(directives.size(), 1U);
ASSERT_EQ(directives[0].directive(), expected);
ASSERT_EQ(directives[0].delta(), std::chrono::seconds(delta));
};
testTrivial("no-cache", CacheDirective::NoCache);
testTrivial("no-store", CacheDirective::NoStore);
testTrivial("no-transform", CacheDirective::NoTransform);
testTrivial("only-if-cached", CacheDirective::OnlyIfCached);
testTimed("max-age=0", CacheDirective::MaxAge, 0);
testTimed("max-age=12", CacheDirective::MaxAge, 12);
testTimed("max-stale=12345", CacheDirective::MaxStale, 12345);
testTimed("min-fresh=48", CacheDirective::MinFresh, 48);
Header::CacheControl cc1;
cc1.parse("private, max-age=600");
auto d1 = cc1.directives();
ASSERT_EQ(d1.size(), 2U);
ASSERT_EQ(d1[0].directive(), CacheDirective::Private);
ASSERT_EQ(d1[1].directive(), CacheDirective::MaxAge);
ASSERT_EQ(d1[1].delta(), std::chrono::seconds(600));
Header::CacheControl cc2;
cc2.parse("public, s-maxage=200, proxy-revalidate");
auto d2 = cc2.directives();
ASSERT_EQ(d2.size(), 3U);
ASSERT_EQ(d2[0].directive(), CacheDirective::Public);
ASSERT_EQ(d2[1].directive(), CacheDirective::SMaxAge);
ASSERT_EQ(d2[1].delta(), std::chrono::seconds(200));
ASSERT_EQ(d2[2].directive(), CacheDirective::ProxyRevalidate);
Header::CacheControl cc3(CacheDirective::NoCache);
std::ostringstream oss;
cc3.write(oss);
ASSERT_EQ(oss.str(), "no-cache");
oss.str("");
cc3.addDirective(CacheDirective::NoStore);
cc3.write(oss);
ASSERT_EQ(oss.str(), "no-cache, no-store");
oss.str("");
Header::CacheControl cc4;
cc4.addDirectives({
CacheDirective::Public,
CacheDirective(CacheDirective::MaxAge, std::chrono::seconds(600))
});
cc4.write(oss);
ASSERT_EQ(oss.str(), "public, max-age=600");
}
TEST(headers_test, content_length) {
Header::ContentLength cl;
cl.parse("3495");
ASSERT_EQ(cl.value(), 3495U);
}
TEST(headers_test, connection) {
Header::Connection connection;
constexpr struct Test {
const char *data;
ConnectionControl expected;
} tests[] = {
{ "close", ConnectionControl::Close },
{ "clOse", ConnectionControl::Close },
{ "Close", ConnectionControl::Close },
{ "CLOSE", ConnectionControl::Close },
{ "keep-alive", ConnectionControl::KeepAlive },
{ "Keep-Alive", ConnectionControl::KeepAlive },
{ "kEEp-alIvE", ConnectionControl::KeepAlive },
{ "KEEP-ALIVE", ConnectionControl::KeepAlive }
};
for (auto test: tests) {
Header::Connection connection;
connection.parse(test.data);
ASSERT_EQ(connection.control(), test.expected);
}
}
TEST(headers_test, date_test_rfc_1123) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* RFC-1123 */
Header::Date d1;
d1.parse("Sun, 06 Nov 1994 08:49:37 GMT");
auto dd1 = d1.fullDate().date();
ASSERT_EQ(expected_time_point, dd1);
}
TEST(headers_test, date_test_rfc_850) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* RFC-850 */
Header::Date d2;
d2.parse("Sunday, 06-Nov-94 08:49:37 GMT");
auto dd2 = d2.fullDate().date();
ASSERT_EQ(dd2, expected_time_point);
}
TEST(headers_test, date_test_asctime) {
using namespace std::chrono;
FullDate::time_point expected_time_point = date::sys_days(date::year{1994}/11/6)
+ hours(8) + minutes(49) + seconds(37);
/* ANSI C's asctime format */
Header::Date d3;
d3.parse("Sun Nov 6 08:49:37 1994");
auto dd3 = d3.fullDate().date();
ASSERT_EQ(dd3, expected_time_point);
}
TEST(headers_test, date_test_ostream) {
std::ostringstream os;
Header::Date d4;
d4.parse("Fri, 25 Jan 2019 21:04:45.000000000 UTC");
d4.write(os);
ASSERT_EQ("Fri, 25 Jan 2019 21:04:45.000000000 UTC", os.str());
}
TEST(headers_test, host) {
Header::Host host;
host.parse("www.w3.org");
ASSERT_EQ(host.host(), "www.w3.org");
ASSERT_EQ(host.port(), 80);
host.parse("www.example.com:8080");
ASSERT_EQ(host.host(), "www.example.com");
ASSERT_EQ(host.port(), 8080);
host.parse("localhost:8080");
ASSERT_EQ(host.host(), "localhost");
ASSERT_EQ(host.port(), 8080);
/* Due to an error in GLIBC these tests don't fail as expected, further research needed */
// ASSERT_THROW( host.parse("256.256.256.256:8080");, std::invalid_argument);
// ASSERT_THROW( host.parse("1.0.0.256:8080");, std::invalid_argument);
host.parse("[::1]:8080");
ASSERT_EQ(host.host(), "[::1]");
ASSERT_EQ(host.port(), 8080);
host.parse("[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]:8080");
ASSERT_EQ(host.host(), "[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]");
ASSERT_EQ(host.port(), 8080);
/* Due to an error in GLIBC these tests don't fail as expected, further research needed */
// ASSERT_THROW( host.parse("[GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG]:8080");, std::invalid_argument);
// ASSERT_THROW( host.parse("[::GGGG]:8080");, std::invalid_argument);
}
TEST(headers_test, user_agent) {
Header::UserAgent ua;
ua.parse("CERN-LineMode/2.15 libwww/2.17b3");
ASSERT_EQ(ua.agent(), "CERN-LineMode/2.15 libwww/2.17b3");
}
TEST(headers_test, content_encoding) {
Header::ContentEncoding ce;
ce.parse("gzip");
ASSERT_EQ(ce.encoding(), Header::Encoding::Gzip);
}
TEST(headers_test, content_type) {
Header::ContentType ct;
ct.parse("text/html; charset=ISO-8859-4");
const auto& mime = ct.mime();
ASSERT_EQ(mime, MIME(Text, Html));
ASSERT_EQ(mime.getParam("charset").getOrElse(""), "ISO-8859-4");
}
TEST(headers_test, access_control_allow_origin_test)
{
Header::AccessControlAllowOrigin allowOrigin;
allowOrigin.parse("http://foo.bar");
ASSERT_EQ(allowOrigin.uri(), "http://foo.bar");
}
TEST(headers_test, access_control_allow_headers_test)
{
Header::AccessControlAllowHeaders allowHeaders;
allowHeaders.parse("Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
ASSERT_EQ(allowHeaders.val(), "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
}
TEST(headers_test, access_control_expose_headers_test)
{
Header::AccessControlExposeHeaders exposeHeaders;
exposeHeaders.parse("Accept, Location");
ASSERT_EQ(exposeHeaders.val(), "Accept, Location");
}
TEST(headers_test, access_control_allow_methods_test)
{
Header::AccessControlAllowMethods allowMethods;
allowMethods.parse("GET, POST, DELETE");
ASSERT_EQ(allowMethods.val(), "GET, POST, DELETE");
}
CUSTOM_HEADER(TestHeader)
TEST(header_test, macro_for_custom_headers)
{
TestHeader testHeader;
ASSERT_TRUE( strcmp(TestHeader::Name,"TestHeader") == 0);
testHeader.parse("Header Content Test");
ASSERT_EQ(testHeader.val(), "Header Content Test");
}
TEST(headers_test, add_new_header_test)
{
const std::string headerName = "TestHeader";
ASSERT_FALSE(Header::Registry::instance().isRegistered(headerName));
Header::Registry::instance().registerHeader<TestHeader>();
ASSERT_TRUE(Header::Registry::instance().isRegistered(headerName));
const auto& headersList = Header::Registry::instance().headersList();
const bool isFound = std::find(headersList.begin(), headersList.end(), headerName) != headersList.end();
ASSERT_TRUE(isFound);
}
//throw std::runtime_error("Header already registered");
//throw std::runtime_error("Unknown header");
//throw std::runtime_error("Could not find header");
// Collection::get(const std::string& name) const
// Collection::get(const std::string& name)
// Collection::getRaw(const std::string& name) const
using namespace Pistache::Http::Header;
TEST(headers_test, header_already_registered)
{
std::string what;
try {
RegisterHeader(Accept);
} catch (std::exception& e) {
what = e.what();
}
ASSERT_TRUE(strcmp(what.c_str(),"Header already registered") == 0);
}
TEST(headers_test, unknown_header)
{
std::string what;
try {
auto h = Pistache::Http::Header::Registry::instance().makeHeader("UnknownHeader");
} catch (std::exception& e) {
what = e.what();
}
ASSERT_TRUE(std::strcmp(what.c_str(),"Unknown header") == 0);
}<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -std=c++98 -fcxx-exceptions -verify %s
// RUN: %clang_cc1 -std=c++11 -fcxx-exceptions -verify %s
// RUN: %clang_cc1 -std=c++1y -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++14 -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fsized-deallocation -fconcepts-ts -DCONCEPTS_TS=1 -verify %s
// RUN: %clang_cc1 -fno-rtti -verify %s -DNO_EXCEPTIONS -DNO_RTTI
// RUN: %clang_cc1 -fcoroutines-ts -DNO_EXCEPTIONS -DCOROUTINES -verify %s
// expected-no-diagnostics
// FIXME using `defined` in a macro has undefined behavior.
#if __cplusplus < 201103L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx98 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx98
#elif __cplusplus < 201402L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx11 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx11
#elif __cplusplus < 201406L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx14 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx14
#else
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx1z == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx1z
#endif
// --- C++17 features ---
#if check(variadic_using, 0, 0, 0, 201611) // FIXME: provisional name
#error "wrong value for __cpp_variadic_using"
#endif
#if check(hex_float, 0, 0, 0, 201603)
#error "wrong value for __cpp_hex_float"
#endif
#if check(inline_variables, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_inline_variables"
#endif
#if check(aligned_new, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_aligned_new"
#endif
#if check(noexcept_function_type, 0, 0, 0, 201510)
#error "wrong value for __cpp_noexcept_function_type"
#endif
#if check(fold_expressions, 0, 0, 0, 201603)
#error "wrong value for __cpp_fold_expressions"
#endif
#if check(capture_star_this, 0, 0, 0, 201603)
#error "wrong value for __cpp_capture_star_this"
#endif
// constexpr checked below
#if check(if_constexpr, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_if_constexpr"
#endif
// range_based_for checked below
// static_assert checked below
#if check(template_auto, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_template_auto"
#endif
#if check(namespace_attributes, 0, 0, 0, 201411)
// FIXME: allowed without warning in C++14 and C++11
#error "wrong value for __cpp_namespace_attributes"
#endif
#if check(enumerator_attributes, 0, 0, 0, 201411)
// FIXME: allowed without warning in C++14 and C++11
#error "wrong value for __cpp_enumerator_attributes"
#endif
#if check(nested_namespace_definitions, 0, 0, 0, 201411)
#error "wrong value for __cpp_nested_namespace_definitions"
#endif
// inheriting_constructors checked below
#if check(aggregate_bases, 0, 0, 0, 201603)
#error "wrong value for __cpp_aggregate_bases"
#endif
#if check(structured_bindings, 0, 0, 0, 201606)
#error "wrong value for __cpp_structured_bindings"
#endif
#if check(nontype_template_args, 0, 0, 0, 201411)
#error "wrong value for __cpp_nontype_template_args"
#endif
#if check(template_template_args, 0, 0, 0, 0) // FIXME: should be 201611 when feature is enabled
#error "wrong value for __cpp_template_template_args"
#endif
#if check(deduction_guides, 0, 0, 0, 201611) // FIXME: provisional name
#error "wrong value for __cpp_deduction_guides"
#endif
// --- C++14 features ---
#if check(binary_literals, 0, 0, 201304, 201304)
#error "wrong value for __cpp_binary_literals"
#endif
// (Removed from SD-6.)
#if check(digit_separators, 0, 0, 201309, 201309)
#error "wrong value for __cpp_digit_separators"
#endif
#if check(init_captures, 0, 0, 201304, 201304)
#error "wrong value for __cpp_init_captures"
#endif
#if check(generic_lambdas, 0, 0, 201304, 201304)
#error "wrong value for __cpp_generic_lambdas"
#endif
#if check(sized_deallocation, 0, 0, 201309, 201309)
#error "wrong value for __cpp_sized_deallocation"
#endif
// constexpr checked below
#if check(decltype_auto, 0, 0, 201304, 201304)
#error "wrong value for __cpp_decltype_auto"
#endif
#if check(return_type_deduction, 0, 0, 201304, 201304)
#error "wrong value for __cpp_return_type_deduction"
#endif
#if check(runtime_arrays, 0, 0, 0, 0)
#error "wrong value for __cpp_runtime_arrays"
#endif
#if check(aggregate_nsdmi, 0, 0, 201304, 201304)
#error "wrong value for __cpp_aggregate_nsdmi"
#endif
#if check(variable_templates, 0, 0, 201304, 201304)
#error "wrong value for __cpp_variable_templates"
#endif
// --- C++11 features ---
#if check(unicode_characters, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_unicode_characters"
#endif
#if check(raw_strings, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_raw_strings"
#endif
#if check(unicode_literals, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_unicode_literals"
#endif
#if check(user_defined_literals, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_user_defined_literals"
#endif
#if check(lambdas, 0, 200907, 200907, 200907)
#error "wrong value for __cpp_lambdas"
#endif
#if check(constexpr, 0, 200704, 201304, 201603)
#error "wrong value for __cpp_constexpr"
#endif
#if check(range_based_for, 0, 200907, 200907, 201603)
#error "wrong value for __cpp_range_based_for"
#endif
#if check(static_assert, 0, 200410, 200410, 201411)
#error "wrong value for __cpp_static_assert"
#endif
#if check(decltype, 0, 200707, 200707, 200707)
#error "wrong value for __cpp_decltype"
#endif
#if check(attributes, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_attributes"
#endif
#if check(rvalue_references, 0, 200610, 200610, 200610)
#error "wrong value for __cpp_rvalue_references"
#endif
#if check(variadic_templates, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_variadic_templates"
#endif
#if check(initializer_lists, 0, 200806, 200806, 200806)
#error "wrong value for __cpp_initializer_lists"
#endif
#if check(delegating_constructors, 0, 200604, 200604, 200604)
#error "wrong value for __cpp_delegating_constructors"
#endif
#if check(nsdmi, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_nsdmi"
#endif
#if check(inheriting_constructors, 0, 201511, 201511, 201511)
#error "wrong value for __cpp_inheriting_constructors"
#endif
#if check(ref_qualifiers, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_ref_qualifiers"
#endif
#if check(alias_templates, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_alias_templates"
#endif
// --- C++98 features ---
#if defined(NO_RTTI) ? check(rtti, 0, 0, 0, 0) : check(rtti, 199711, 199711, 199711, 199711)
#error "wrong value for __cpp_rtti"
#endif
#if defined(NO_EXCEPTIONS) ? check(exceptions, 0, 0, 0, 0) : check(exceptions, 199711, 199711, 199711, 199711)
#error "wrong value for __cpp_exceptions"
#endif
// --- TS features --
#if check(experimental_concepts, 0, 0, CONCEPTS_TS, CONCEPTS_TS)
#error "wrong value for __cpp_experimental_concepts"
#endif
#if defined(COROUTINES) ? check(coroutines, 201703L, 201703L, 201703L, 201703L) : check(coroutines, 0, 0, 0, 0)
#error "wrong value for __cpp_coroutines"
#endif
<commit_msg>Reorder tests to match latest SD-6 draft.<commit_after>// RUN: %clang_cc1 -std=c++98 -fcxx-exceptions -verify %s
// RUN: %clang_cc1 -std=c++11 -fcxx-exceptions -verify %s
// RUN: %clang_cc1 -std=c++1y -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++14 -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fsized-deallocation -verify %s
// RUN: %clang_cc1 -std=c++1z -fcxx-exceptions -fsized-deallocation -fconcepts-ts -DCONCEPTS_TS=1 -verify %s
// RUN: %clang_cc1 -fno-rtti -verify %s -DNO_EXCEPTIONS -DNO_RTTI
// RUN: %clang_cc1 -fcoroutines-ts -DNO_EXCEPTIONS -DCOROUTINES -verify %s
// expected-no-diagnostics
// FIXME using `defined` in a macro has undefined behavior.
#if __cplusplus < 201103L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx98 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx98
#elif __cplusplus < 201402L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx11 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx11
#elif __cplusplus < 201406L
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx14 == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx14
#else
#define check(macro, cxx98, cxx11, cxx14, cxx1z) cxx1z == 0 ? defined(__cpp_##macro) : __cpp_##macro != cxx1z
#endif
// --- C++17 features ---
#if check(hex_float, 0, 0, 0, 201603)
#error "wrong value for __cpp_hex_float"
#endif
#if check(inline_variables, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_inline_variables"
#endif
#if check(aligned_new, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_aligned_new"
#endif
#if check(noexcept_function_type, 0, 0, 0, 201510)
#error "wrong value for __cpp_noexcept_function_type"
#endif
#if check(fold_expressions, 0, 0, 0, 201603)
#error "wrong value for __cpp_fold_expressions"
#endif
#if check(capture_star_this, 0, 0, 0, 201603)
#error "wrong value for __cpp_capture_star_this"
#endif
// constexpr checked below
#if check(if_constexpr, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_if_constexpr"
#endif
// range_based_for checked below
// static_assert checked below
#if check(deduction_guides, 0, 0, 0, 201611) // FIXME: provisional name
#error "wrong value for __cpp_deduction_guides"
#endif
#if check(template_auto, 0, 0, 0, 201606) // FIXME: provisional name
#error "wrong value for __cpp_template_auto"
#endif
#if check(namespace_attributes, 0, 0, 0, 201411)
// FIXME: allowed without warning in C++14 and C++11
#error "wrong value for __cpp_namespace_attributes"
#endif
#if check(enumerator_attributes, 0, 0, 0, 201411)
// FIXME: allowed without warning in C++14 and C++11
#error "wrong value for __cpp_enumerator_attributes"
#endif
#if check(nested_namespace_definitions, 0, 0, 0, 201411)
#error "wrong value for __cpp_nested_namespace_definitions"
#endif
// inheriting_constructors checked below
#if check(variadic_using, 0, 0, 0, 201611) // FIXME: provisional name
#error "wrong value for __cpp_variadic_using"
#endif
#if check(aggregate_bases, 0, 0, 0, 201603)
#error "wrong value for __cpp_aggregate_bases"
#endif
#if check(structured_bindings, 0, 0, 0, 201606)
#error "wrong value for __cpp_structured_bindings"
#endif
#if check(nontype_template_args, 0, 0, 0, 201411)
#error "wrong value for __cpp_nontype_template_args"
#endif
#if check(template_template_args, 0, 0, 0, 0) // FIXME: should be 201611 when feature is enabled
#error "wrong value for __cpp_template_template_args"
#endif
// --- C++14 features ---
#if check(binary_literals, 0, 0, 201304, 201304)
#error "wrong value for __cpp_binary_literals"
#endif
// (Removed from SD-6.)
#if check(digit_separators, 0, 0, 201309, 201309)
#error "wrong value for __cpp_digit_separators"
#endif
#if check(init_captures, 0, 0, 201304, 201304)
#error "wrong value for __cpp_init_captures"
#endif
#if check(generic_lambdas, 0, 0, 201304, 201304)
#error "wrong value for __cpp_generic_lambdas"
#endif
#if check(sized_deallocation, 0, 0, 201309, 201309)
#error "wrong value for __cpp_sized_deallocation"
#endif
// constexpr checked below
#if check(decltype_auto, 0, 0, 201304, 201304)
#error "wrong value for __cpp_decltype_auto"
#endif
#if check(return_type_deduction, 0, 0, 201304, 201304)
#error "wrong value for __cpp_return_type_deduction"
#endif
#if check(runtime_arrays, 0, 0, 0, 0)
#error "wrong value for __cpp_runtime_arrays"
#endif
#if check(aggregate_nsdmi, 0, 0, 201304, 201304)
#error "wrong value for __cpp_aggregate_nsdmi"
#endif
#if check(variable_templates, 0, 0, 201304, 201304)
#error "wrong value for __cpp_variable_templates"
#endif
// --- C++11 features ---
#if check(unicode_characters, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_unicode_characters"
#endif
#if check(raw_strings, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_raw_strings"
#endif
#if check(unicode_literals, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_unicode_literals"
#endif
#if check(user_defined_literals, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_user_defined_literals"
#endif
#if check(lambdas, 0, 200907, 200907, 200907)
#error "wrong value for __cpp_lambdas"
#endif
#if check(constexpr, 0, 200704, 201304, 201603)
#error "wrong value for __cpp_constexpr"
#endif
#if check(range_based_for, 0, 200907, 200907, 201603)
#error "wrong value for __cpp_range_based_for"
#endif
#if check(static_assert, 0, 200410, 200410, 201411)
#error "wrong value for __cpp_static_assert"
#endif
#if check(decltype, 0, 200707, 200707, 200707)
#error "wrong value for __cpp_decltype"
#endif
#if check(attributes, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_attributes"
#endif
#if check(rvalue_references, 0, 200610, 200610, 200610)
#error "wrong value for __cpp_rvalue_references"
#endif
#if check(variadic_templates, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_variadic_templates"
#endif
#if check(initializer_lists, 0, 200806, 200806, 200806)
#error "wrong value for __cpp_initializer_lists"
#endif
#if check(delegating_constructors, 0, 200604, 200604, 200604)
#error "wrong value for __cpp_delegating_constructors"
#endif
#if check(nsdmi, 0, 200809, 200809, 200809)
#error "wrong value for __cpp_nsdmi"
#endif
#if check(inheriting_constructors, 0, 201511, 201511, 201511)
#error "wrong value for __cpp_inheriting_constructors"
#endif
#if check(ref_qualifiers, 0, 200710, 200710, 200710)
#error "wrong value for __cpp_ref_qualifiers"
#endif
#if check(alias_templates, 0, 200704, 200704, 200704)
#error "wrong value for __cpp_alias_templates"
#endif
// --- C++98 features ---
#if defined(NO_RTTI) ? check(rtti, 0, 0, 0, 0) : check(rtti, 199711, 199711, 199711, 199711)
#error "wrong value for __cpp_rtti"
#endif
#if defined(NO_EXCEPTIONS) ? check(exceptions, 0, 0, 0, 0) : check(exceptions, 199711, 199711, 199711, 199711)
#error "wrong value for __cpp_exceptions"
#endif
// --- TS features --
#if check(experimental_concepts, 0, 0, CONCEPTS_TS, CONCEPTS_TS)
#error "wrong value for __cpp_experimental_concepts"
#endif
#if defined(COROUTINES) ? check(coroutines, 201703L, 201703L, 201703L, 201703L) : check(coroutines, 0, 0, 0, 0)
#error "wrong value for __cpp_coroutines"
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: attriblistmerge.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: fs $ $Date: 2000-12-12 12:02: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 EXPRESS 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 _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#define _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
//.........................................................................
namespace xmloff
{
//.........................................................................
//=====================================================================
//= OAttribListMerger
//=====================================================================
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::xml::sax::XAttributeList
> OAttribListMerger_Base;
/** implements the XAttributeList list by merging different source attribute lists
<p>Currently, the time behavious is O(n), though it would be possible to change it to O(log n).</p>
*/
class OAttribListMerger : public OAttribListMerger_Base
{
protected:
::osl::Mutex m_aMutex;
DECLARE_STL_VECTOR( ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >, AttributeListArray );
AttributeListArray m_aLists;
~OAttribListMerger() { }
public:
OAttribListMerger() { }
// attribute list handling
// (very thinn at the moment ... only adding lists is allowed ... add more if you need it :)
void addList(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rList);
// XAttributeList
virtual sal_Int16 SAL_CALL getLength( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
protected:
sal_Bool seekToIndex(sal_Int16 _nGlobalIndex, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
sal_Bool seekToName(const ::rtl::OUString& _rName, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
};
//.........................................................................
} // namespace xmloff
//.........................................................................
#endif // _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
*
* Revision 1.0 12.12.00 10:25:25 fs
************************************************************************/
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.646); FILE MERGED 2005/09/05 14:38:54 rt 1.1.646.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attriblistmerge.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 14:03:13 $
*
* 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 _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#define _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_
#include <com/sun/star/xml/sax/XAttributeList.hpp>
#endif
//.........................................................................
namespace xmloff
{
//.........................................................................
//=====================================================================
//= OAttribListMerger
//=====================================================================
typedef ::cppu::WeakImplHelper1 < ::com::sun::star::xml::sax::XAttributeList
> OAttribListMerger_Base;
/** implements the XAttributeList list by merging different source attribute lists
<p>Currently, the time behavious is O(n), though it would be possible to change it to O(log n).</p>
*/
class OAttribListMerger : public OAttribListMerger_Base
{
protected:
::osl::Mutex m_aMutex;
DECLARE_STL_VECTOR( ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >, AttributeListArray );
AttributeListArray m_aLists;
~OAttribListMerger() { }
public:
OAttribListMerger() { }
// attribute list handling
// (very thinn at the moment ... only adding lists is allowed ... add more if you need it :)
void addList(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rList);
// XAttributeList
virtual sal_Int16 SAL_CALL getLength( ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getTypeByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 i ) throw(::com::sun::star::uno::RuntimeException);
virtual ::rtl::OUString SAL_CALL getValueByName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);
protected:
sal_Bool seekToIndex(sal_Int16 _nGlobalIndex, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
sal_Bool seekToName(const ::rtl::OUString& _rName, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rSubList, sal_Int16& _rLocalIndex);
};
//.........................................................................
} // namespace xmloff
//.........................................................................
#endif // _XMLOFF_FORMS_ATTRIBLISTMERGE_HXX_
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.1.646.1 2005/09/05 14:38:54 rt
* #i54170# Change license header: remove SISSL
*
* Revision 1.1 2000/12/12 12:02:13 fs
* initial checkin - helper class for mergin XAttributeList instances
*
*
* Revision 1.0 12.12.00 10:25:25 fs
************************************************************************/
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_launcher.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef InProcessBrowserTest FirstRunBrowserTest;
IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShowFirstRunBubblePref) {
EXPECT_TRUE(g_browser_process->local_state()->FindPreference(
prefs::kShowFirstRunBubbleOption));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SHOW));
ASSERT_TRUE(g_browser_process->local_state()->FindPreference(
prefs::kShowFirstRunBubbleOption));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
// Test that toggling the value works in either direction after it's been set.
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_DONT_SHOW));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
// Test that the value can't be set to FIRST_RUN_BUBBLE_SHOW after it has been
// set to FIRST_RUN_BUBBLE_SUPPRESS.
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SUPPRESS));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SHOW));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
}
IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShouldShowWelcomePage) {
EXPECT_FALSE(first_run::ShouldShowWelcomePage());
first_run::SetShouldShowWelcomePage();
EXPECT_TRUE(first_run::ShouldShowWelcomePage());
EXPECT_FALSE(first_run::ShouldShowWelcomePage());
}
#if !defined(OS_CHROMEOS)
namespace {
class FirstRunIntegrationBrowserTest : public InProcessBrowserTest {
public:
FirstRunIntegrationBrowserTest() {}
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kForceFirstRun);
EXPECT_FALSE(first_run::DidPerformProfileImport(NULL));
extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();
// The forked import process should run BrowserMain.
CommandLine import_arguments((CommandLine::NoProgram()));
import_arguments.AppendSwitch(content::kLaunchAsBrowser);
first_run::SetExtraArgumentsForImportProcess(import_arguments);
}
private:
DISALLOW_COPY_AND_ASSIGN(FirstRunIntegrationBrowserTest);
};
class FirstRunMasterPrefsBrowserTest : public FirstRunIntegrationBrowserTest {
public:
FirstRunMasterPrefsBrowserTest() {}
protected:
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(file_util::CreateTemporaryFile(&prefs_file_));
// TODO(tapted): Make this reusable.
const char text[] =
"{\n"
" \"distribution\": {\n"
" \"import_bookmarks\": false,\n"
" \"import_history\": false,\n"
" \"import_home_page\": false,\n"
" \"import_search_engine\": false\n"
" }\n"
"}\n";
EXPECT_TRUE(file_util::WriteFile(prefs_file_, text, strlen(text)));
first_run::SetMasterPrefsPathForTesting(prefs_file_);
// This invokes BrowserMain, and does the import, so must be done last.
FirstRunIntegrationBrowserTest::SetUp();
}
virtual void TearDown() OVERRIDE {
EXPECT_TRUE(file_util::Delete(prefs_file_, false));
FirstRunIntegrationBrowserTest::TearDown();
}
private:
base::FilePath prefs_file_;
DISALLOW_COPY_AND_ASSIGN(FirstRunMasterPrefsBrowserTest);
};
}
// TODO(tapted): Investigate why this fails on Linux bots but does not
// reproduce locally. See http://crbug.com/178062 .
#if defined(OS_LINUX)
#define MAYBE_WaitForImport DISABLED_WaitForImport
#else
#define MAYBE_WaitForImport WaitForImport
#endif
IN_PROC_BROWSER_TEST_F(FirstRunIntegrationBrowserTest, MAYBE_WaitForImport) {
bool success = false;
EXPECT_TRUE(first_run::DidPerformProfileImport(&success));
// Aura builds skip over the import process.
#if defined(USE_AURA)
EXPECT_FALSE(success);
#else
EXPECT_TRUE(success);
#endif
}
// Test an import with all import options disabled. This is a regression test
// for http://crbug.com/169984 where this would cause the import process to
// stay running, and the NTP to be loaded with no apps.
IN_PROC_BROWSER_TEST_F(FirstRunMasterPrefsBrowserTest,
ImportNothingAndShowNewTabPage) {
EXPECT_TRUE(first_run::DidPerformProfileImport(NULL));
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL), CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
content::WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0);
EXPECT_EQ(1, tab->GetMaxPageID());
}
#endif // !defined(OS_CHROMEOS)
<commit_msg>Disable FirstRunIntegrationBrowserTest.WaitForImport on mac_asan.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/test_launcher.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef InProcessBrowserTest FirstRunBrowserTest;
IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShowFirstRunBubblePref) {
EXPECT_TRUE(g_browser_process->local_state()->FindPreference(
prefs::kShowFirstRunBubbleOption));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SHOW));
ASSERT_TRUE(g_browser_process->local_state()->FindPreference(
prefs::kShowFirstRunBubbleOption));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
// Test that toggling the value works in either direction after it's been set.
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_DONT_SHOW));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_DONT_SHOW,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
// Test that the value can't be set to FIRST_RUN_BUBBLE_SHOW after it has been
// set to FIRST_RUN_BUBBLE_SUPPRESS.
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SUPPRESS));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
EXPECT_TRUE(first_run::SetShowFirstRunBubblePref(
first_run::FIRST_RUN_BUBBLE_SHOW));
EXPECT_EQ(first_run::FIRST_RUN_BUBBLE_SUPPRESS,
g_browser_process->local_state()->GetInteger(
prefs::kShowFirstRunBubbleOption));
}
IN_PROC_BROWSER_TEST_F(FirstRunBrowserTest, SetShouldShowWelcomePage) {
EXPECT_FALSE(first_run::ShouldShowWelcomePage());
first_run::SetShouldShowWelcomePage();
EXPECT_TRUE(first_run::ShouldShowWelcomePage());
EXPECT_FALSE(first_run::ShouldShowWelcomePage());
}
#if !defined(OS_CHROMEOS)
namespace {
class FirstRunIntegrationBrowserTest : public InProcessBrowserTest {
public:
FirstRunIntegrationBrowserTest() {}
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kForceFirstRun);
EXPECT_FALSE(first_run::DidPerformProfileImport(NULL));
extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();
// The forked import process should run BrowserMain.
CommandLine import_arguments((CommandLine::NoProgram()));
import_arguments.AppendSwitch(content::kLaunchAsBrowser);
first_run::SetExtraArgumentsForImportProcess(import_arguments);
}
private:
DISALLOW_COPY_AND_ASSIGN(FirstRunIntegrationBrowserTest);
};
class FirstRunMasterPrefsBrowserTest : public FirstRunIntegrationBrowserTest {
public:
FirstRunMasterPrefsBrowserTest() {}
protected:
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(file_util::CreateTemporaryFile(&prefs_file_));
// TODO(tapted): Make this reusable.
const char text[] =
"{\n"
" \"distribution\": {\n"
" \"import_bookmarks\": false,\n"
" \"import_history\": false,\n"
" \"import_home_page\": false,\n"
" \"import_search_engine\": false\n"
" }\n"
"}\n";
EXPECT_TRUE(file_util::WriteFile(prefs_file_, text, strlen(text)));
first_run::SetMasterPrefsPathForTesting(prefs_file_);
// This invokes BrowserMain, and does the import, so must be done last.
FirstRunIntegrationBrowserTest::SetUp();
}
virtual void TearDown() OVERRIDE {
EXPECT_TRUE(file_util::Delete(prefs_file_, false));
FirstRunIntegrationBrowserTest::TearDown();
}
private:
base::FilePath prefs_file_;
DISALLOW_COPY_AND_ASSIGN(FirstRunMasterPrefsBrowserTest);
};
}
// TODO(tapted): Investigate why this fails on Linux bots but does not
// reproduce locally. See http://crbug.com/178062 .
// TODO(tapted): Investigate why this fails on mac_asan flakily
// http://crbug.com/181499 .
#if defined(OS_LINUX) || (defined(OS_MACOSX) && defined(ADDRESS_SANITIZER))
#define MAYBE_WaitForImport DISABLED_WaitForImport
#else
#define MAYBE_WaitForImport WaitForImport
#endif
IN_PROC_BROWSER_TEST_F(FirstRunIntegrationBrowserTest, MAYBE_WaitForImport) {
bool success = false;
EXPECT_TRUE(first_run::DidPerformProfileImport(&success));
// Aura builds skip over the import process.
#if defined(USE_AURA)
EXPECT_FALSE(success);
#else
EXPECT_TRUE(success);
#endif
}
// Test an import with all import options disabled. This is a regression test
// for http://crbug.com/169984 where this would cause the import process to
// stay running, and the NTP to be loaded with no apps.
IN_PROC_BROWSER_TEST_F(FirstRunMasterPrefsBrowserTest,
ImportNothingAndShowNewTabPage) {
EXPECT_TRUE(first_run::DidPerformProfileImport(NULL));
ui_test_utils::NavigateToURLWithDisposition(
browser(), GURL(chrome::kChromeUINewTabURL), CURRENT_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
content::WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(0);
EXPECT_EQ(1, tab->GetMaxPageID());
}
#endif // !defined(OS_CHROMEOS)
<|endoftext|> |
<commit_before>
#include <QVBoxLayout>
#include <quartz_common/widgets/QzScroller.h>
#include "QuartzWindow.h"
namespace Vam { namespace Quartz {
QuartzWindow::QuartzWindow( QWidget *parent )
: QMainWindow( parent )
{
QWidget * widget = new QWidget( this );
QVBoxLayout *layout = new QVBoxLayout();
widget->setContentsMargins( QMargins() );
layout->setContentsMargins( QMargins() );
QzScroller *scroller = new QzScroller( Qt::Vertical, this );
layout->addWidget( scroller );
widget->setLayout( layout );
setCentralWidget( widget );
}
QString QuartzWindow::createStylesheet()
{
return "QWidget{"
"background-color: black; "
"color: #FFA858;"
"border-color: black;"
"}"
"QPushButton{"
"background-color: #202020; "
"color: #FFA858;"
"border-width: 8px;"
"border-color: black;"
"}"
"QPushButton:pressed{"
"background-color: #FFA858; "
"color: white;"
"border-width: 8px;"
"border-color: black;"
"}"
"QLabel{"
"color: #FFA858; "
"border-width: 8px;"
"border-color: black;"
"font: monospace;"
"}"
"QPushButton:checked{"
"background-color: #FFA858; "
"color: black;"
"border-width: 8px;"
"border-color: black;"
"}"
"QToolButton{"
"background-color: #323232; "
"color: #FFA858;"
"border-style: outset;"
"border-color: black;"
"border-radius: 5px;"
"min-width: 40px;"
"min-height: 20px;"
"font-size: 10px;"
"}"
"QToolButton:hover{"
"background-color: #6F5C44;"
"}"
"QToolButton:pressed{"
"background-color: #FFA858; "
"color: #323232;"
"}"
"QToolButton:disabled{"
"background-color: #404040; "
"color: gray;"
"}"
"QToolBar{"
"spacing: 3px;"
"}"
"QTreeView{ "
"background-color: #151515;"
"alternate-background-color: #202020;"
"}"
"QTreeView::item:selected:active, QTreeView::item:selected:!active,"
"QListView::item:selected:active, QListView::item:selected:!active{"
"color: #151515; "
"background-color: rgba( 255, 168, 48, 200 );"
"background-color: #B2936C;"
"}"
"QHeaderView::section {"
"background-color: #202020;"
"color: white;"
"}"
"QTreeView::item:hover, QListView::item:hover { "
"background-color: rgba( 255, 168, 48, 50 );"
"}"
"QProgressBar{ "
"border-radius: 5px;"
"color: white;"
"text-align: center;"
"}"
"QProgressBar::chunk {"
"background-color: #FFA858;"
"}"
"QLineEdit{ background-color: #444444;}"
"QMenu{ background-color: #444444;}"
"QMenu::item:selected{background-color: #696969; }"
"QScrollBar::handle {"
"background: #6F5C44;;"
"min-width: 30px;"
"border-radius: 3px;"
"}"
"QScrollBar{"
"background: #202020;"
"border-radius: 5px;"
"}"
"QScrollBar::add-line, QScrollBar::sub-line{"
"border: 2px solid #202020;"
"background: #202020;"
"}";
}
} }
<commit_msg>1. Updating creation of scroller with size information 2. Testing the vertical orientation for scroller<commit_after>
#include <QVBoxLayout>
#include <quartz_common/widgets/QzScroller.h>
#include "QuartzWindow.h"
namespace Vam { namespace Quartz {
QuartzWindow::QuartzWindow( QWidget *parent )
: QMainWindow( parent )
{
QWidget * widget = new QWidget( this );
QVBoxLayout *layout = new QVBoxLayout();
widget->setContentsMargins( QMargins() );
layout->setContentsMargins( QMargins() );
QzScroller *scroller = new QzScroller( Qt::Horizontal,
30,
30,
this );
layout->addWidget( scroller );
widget->setLayout( layout );
setCentralWidget( widget );
}
QString QuartzWindow::createStylesheet()
{
return "QWidget{"
"background-color: black; "
"color: #FFA858;"
"border-color: black;"
"}"
"QPushButton{"
"background-color: #202020; "
"color: #FFA858;"
"border-width: 8px;"
"border-color: black;"
"}"
"QPushButton:pressed{"
"background-color: #FFA858; "
"color: white;"
"border-width: 8px;"
"border-color: black;"
"}"
"QLabel{"
"color: #FFA858; "
"border-width: 8px;"
"border-color: black;"
"font: monospace;"
"}"
"QPushButton:checked{"
"background-color: #FFA858; "
"color: black;"
"border-width: 8px;"
"border-color: black;"
"}"
"QToolButton{"
"background-color: #323232; "
"color: #FFA858;"
"border-style: outset;"
"border-color: black;"
"border-radius: 5px;"
"min-width: 40px;"
"min-height: 20px;"
"font-size: 10px;"
"}"
"QToolButton:hover{"
"background-color: #6F5C44;"
"}"
"QToolButton:pressed{"
"background-color: #FFA858; "
"color: #323232;"
"}"
"QToolButton:disabled{"
"background-color: #404040; "
"color: gray;"
"}"
"QToolBar{"
"spacing: 3px;"
"}"
"QTreeView{ "
"background-color: #151515;"
"alternate-background-color: #202020;"
"}"
"QTreeView::item:selected:active, QTreeView::item:selected:!active,"
"QListView::item:selected:active, QListView::item:selected:!active{"
"color: #151515; "
"background-color: rgba( 255, 168, 48, 200 );"
"background-color: #B2936C;"
"}"
"QHeaderView::section {"
"background-color: #202020;"
"color: white;"
"}"
"QTreeView::item:hover, QListView::item:hover { "
"background-color: rgba( 255, 168, 48, 50 );"
"}"
"QProgressBar{ "
"border-radius: 5px;"
"color: white;"
"text-align: center;"
"}"
"QProgressBar::chunk {"
"background-color: #FFA858;"
"}"
"QLineEdit{ background-color: #444444;}"
"QMenu{ background-color: #444444;}"
"QMenu::item:selected{background-color: #696969; }"
"QScrollBar::handle {"
"background: #6F5C44;;"
"min-width: 30px;"
"border-radius: 3px;"
"}"
"QScrollBar{"
"background: #202020;"
"border-radius: 5px;"
"}"
"QScrollBar::add-line, QScrollBar::sub-line{"
"border: 2px solid #202020;"
"background: #202020;"
"}";
}
} }
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>
#define private public
#define protected public
#include <cstddef>
#include <iostream>
#include <vector>
#include "../../JPetScopeReader/JPetScopeReader.h"
#include "../../JPetSignal/JPetSignal.h"
#include "../../JPetSigCh/JPetSigCh.h"
BOOST_AUTO_TEST_SUITE (FirstSuite)
BOOST_AUTO_TEST_CASE (default_constructor)
{
JPetScopeReader reader;
BOOST_REQUIRE(reader.fInputFile.is_open() == false);
BOOST_REQUIRE(reader.fIsFileOpen == false);
// BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
}
BOOST_AUTO_TEST_CASE (open_file)
{
JPetScopeReader reader;
reader.openFile("C1_00000.txt");
BOOST_REQUIRE(reader.fInputFile.is_open());
BOOST_REQUIRE(reader.fIsFileOpen);
// BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
reader.readHeader();
// BOOST_CHECK_EQUAL(reader.fSegments, 1);
BOOST_CHECK_EQUAL(reader.fSegmentSize, 502);
JPetSignal* sig = reader.readData();
int points = sig->getNumberOfLeadingEdgePoints();
points += sig->getNumberOfTrailingEdgePoints();
BOOST_CHECK_EQUAL(points, 502);
reader.closeFile();
BOOST_REQUIRE(reader.fInputFile.is_open() == false);
BOOST_REQUIRE(reader.fIsFileOpen == false);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Removed error with JPetScopeReaderTest $584<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include <boost/test/unit_test.hpp>
#define private public
#define protected public
#include <cstddef>
#include <iostream>
#include <vector>
#include "../../JPetScopeReader/JPetScopeReader.h"
#include "../../JPetSignal/JPetSignal.h"
#include "../../JPetSigCh/JPetSigCh.h"
BOOST_AUTO_TEST_SUITE (FirstSuite)
BOOST_AUTO_TEST_CASE (default_constructor)
{
JPetScopeReader reader;
BOOST_REQUIRE(reader.isFileOpen() == false);
// BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
}
BOOST_AUTO_TEST_CASE (open_file)
{
JPetScopeReader reader;
reader.openFile("C1_00000.txt");
BOOST_REQUIRE(reader.isFileOpen());
// BOOST_REQUIRE_EQUAL(reader.fSegments, 0);
BOOST_REQUIRE_EQUAL(reader.fSegmentSize, 0);
reader.readHeader();
// BOOST_CHECK_EQUAL(reader.fSegments, 1);
BOOST_CHECK_EQUAL(reader.fSegmentSize, 502);
JPetSignal* sig = reader.readData();
int points = sig->getNumberOfLeadingEdgePoints();
points += sig->getNumberOfTrailingEdgePoints();
BOOST_CHECK_EQUAL(points, 502);
reader.closeFile();
BOOST_REQUIRE(reader.isFileOpen() == false);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int selectAction(const PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards,0);
initiator_queue.enqueueWithPriority(action_backwards,0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
// set current state angle to angle received from encoder
// and set current state velocity to difference in new and
// old state angles over some time difference
current_state.theta= M_PI * (encoder.GetAngle())/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);
// call updateQ function with state space, old and current states
// and learning rate, discount factor
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
// set old_state to current_state
old_state=current_state;
// determine chosen_action for current state
chosen_action=selectAction(space[current_state]);
// depending upon chosen action, call robot movement tools proxy with either
// swingForwards or swingBackwards commands.
(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution.
*
* @return current system time in milliseconds
*/
double temperature()
{
return static_cast<double>(std::time(NULL));
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectAction(const PriorityQueue<int,double>& a_queue)
{
typedef PriorityQueue<int,double> PQ;
typedef std::vector< std::pair<int, double> > Vec_Pair;
typedef std::pair<int, double> Pair;
double sum= 0;
size_t i = 0;
size_t size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand())/ RAND_MAX;
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return -1; //note that this line should never be reached
}
/**
* @brief Updates the utility (Q-value) of the system
*
* @param space Reference to StateSpace object
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm
* @param gamma Discount factor applied to q-learning equation
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectActionAlt(const PriorityQueue<int, double>& a_queue) {
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature());
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature()) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
<commit_msg>updated select action and commented out the depreeciated version<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int selectAction(const PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards,0);
initiator_queue.enqueueWithPriority(action_backwards,0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
// set current state angle to angle received from encoder
// and set current state velocity to difference in new and
// old state angles over some time difference
current_state.theta= M_PI * (encoder.GetAngle())/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);
// call updateQ function with state space, old and current states
// and learning rate, discount factor
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
// set old_state to current_state
old_state=current_state;
// determine chosen_action for current state
chosen_action=selectAction(space[current_state]);
// depending upon chosen action, call robot movement tools proxy with either
// swingForwards or swingBackwards commands.
(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution.
*
* @return current system time in milliseconds
*/
double temperature()
{
return static_cast<double>(std::time(NULL));
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectAction(const PriorityQueue<int, double>& a_queue) {
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature());
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature()) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
/**
* @brief Updates the utility (Q-value) of the system
*
* @param space Reference to StateSpace object
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm
* @param gamma Discount factor applied to q-learning equation
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/*old select action function in case the new one doesn't work
int selectAction(const PriorityQueue<int,double>& a_queue)
{
typedef PriorityQueue<int,double> PQ;
typedef std::vector< std::pair<int, double> > Vec_Pair;
typedef std::pair<int, double> Pair;
double sum= 0;
size_t i = 0;
size_t size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand())/ RAND_MAX;
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return -1; //note that this line should never be reached
}
*/
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <[email protected]>
// Copyright 2007 Inge Wallin <[email protected]>
// Copyright 2007 Thomas Zander <[email protected]>
// Copyright 2010 Bastian Holst <[email protected]>
//
// Self
#include "CurrentLocationWidget.h"
// Marble
#include "AdjustNavigation.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionProviderPlugin.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "routing/RoutingManager.h"
using namespace Marble;
/* TRANSLATOR Marble::CurrentLocationWidget */
// Ui
#include "ui_CurrentLocationWidget.h"
#include <QtCore/QDateTime>
#include <QtGui/QFileDialog>
namespace Marble
{
class CurrentLocationWidgetPrivate
{
public:
Ui::CurrentLocationWidget m_currentLocationUi;
MarbleWidget *m_widget;
AdjustNavigation *m_adjustNavigation;
QList<PositionProviderPlugin*> m_positionProviderPlugins;
GeoDataCoordinates m_currentPosition;
MarbleLocale* m_locale;
void adjustPositionTrackingStatus( PositionProviderStatus status );
void changePositionProvider( const QString &provider );
void centerOnCurrentLocation();
void updateRecenterComboBox( int centerMode );
void updateAutoZoomCheckBox( bool autoZoom );
void updateActivePositionProvider( PositionProviderPlugin* );
void saveTrack();
void clearTrack();
};
CurrentLocationWidget::CurrentLocationWidget( QWidget *parent, Qt::WindowFlags f )
: QWidget( parent, f ),
d( new CurrentLocationWidgetPrivate() )
{
d->m_currentLocationUi.setupUi( this );
d->m_locale = MarbleGlobal::getInstance()->locale();
connect( d->m_currentLocationUi.recenterComboBox, SIGNAL ( currentIndexChanged( int ) ),
this, SLOT( setRecenterMode( int ) ) );
connect( d->m_currentLocationUi.autoZoomCheckBox, SIGNAL( clicked( bool ) ),
this, SLOT( setAutoZoom( bool ) ) );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
d->m_currentLocationUi.positionTrackingComboBox->setVisible( !smallScreen );
d->m_currentLocationUi.locationLabel->setVisible( !smallScreen );
}
CurrentLocationWidget::~CurrentLocationWidget()
{
delete d;
}
void CurrentLocationWidget::setMarbleWidget( MarbleWidget *widget )
{
d->m_widget = widget;
d->m_adjustNavigation = new AdjustNavigation( d->m_widget, this );
d->m_widget->model()->routingManager()->setAdjustNavigation( d->m_adjustNavigation );
PluginManager* pluginManager = d->m_widget->model()->pluginManager();
d->m_positionProviderPlugins = pluginManager->createPositionProviderPlugins();
foreach( const PositionProviderPlugin *plugin, d->m_positionProviderPlugins ) {
d->m_currentLocationUi.positionTrackingComboBox->addItem( plugin->guiString() );
}
if ( d->m_positionProviderPlugins.isEmpty() ) {
d->m_currentLocationUi.positionTrackingComboBox->setEnabled( false );
QString html = "<p>No Position Tracking Plugin installed.</p>";
d->m_currentLocationUi.locationLabel->setText( html );
d->m_currentLocationUi.locationLabel->setEnabled ( true );
d->m_currentLocationUi.showTrackCheckBox->setEnabled( false );
d->m_currentLocationUi.saveTrackPushButton->setEnabled( false );
d->m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}
//disconnect CurrentLocation Signals
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
disconnect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
this, SLOT( changePositionProvider( QString ) ) );
disconnect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( centerOnCurrentLocation() ) );
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( statusChanged( PositionProviderStatus) ),this,
SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );
disconnect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
this, SLOT( updateRecenterComboBox( int ) ) );
disconnect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
this, SLOT( updateAutoZoomCheckBox( bool ) ) );
//connect CurrentLoctaion signals
connect( d->m_widget->model()->positionTracking(),
SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
connect( d->m_widget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
d->updateActivePositionProvider( d->m_widget->model()->positionTracking()->positionProviderPlugin() );
connect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
this, SLOT( changePositionProvider( QString ) ) );
connect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( centerOnCurrentLocation() ) );
connect( d->m_widget->model()->positionTracking(),
SIGNAL( statusChanged( PositionProviderStatus) ), this,
SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );
connect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
this, SLOT( updateRecenterComboBox( int ) ) );
connect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
this, SLOT( updateAutoZoomCheckBox( bool ) ) );
connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
d->m_widget->model()->positionTracking(), SLOT( setTrackVisible(bool) ));
connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
d->m_widget, SLOT(repaint()));
if ( d->m_widget->model()->positionTracking()->trackVisible() ) {
d->m_currentLocationUi.showTrackCheckBox->setCheckState(Qt::Checked);
}
connect ( d->m_currentLocationUi.saveTrackPushButton, SIGNAL( clicked(bool)),
this, SLOT(saveTrack()));
connect (d->m_currentLocationUi.clearTrackPushButton, SIGNAL( clicked(bool)),
this, SLOT(clearTrack()));
}
void CurrentLocationWidgetPrivate::adjustPositionTrackingStatus( PositionProviderStatus status )
{
if ( status == PositionProviderStatusAvailable ) {
return;
}
QString html = "<html><body><p>";
switch ( status ) {
case PositionProviderStatusUnavailable:
html += QObject::tr( "Waiting for current location information..." );
break;
case PositionProviderStatusAcquiring:
html += QObject::tr( "Initializing current location service..." );
break;
case PositionProviderStatusAvailable:
Q_ASSERT( false );
break;
case PositionProviderStatusError:
html += QObject::tr( "Error when determining current location: " );
html += m_widget->model()->positionTracking()->error();
break;
}
html += "</p></body></html>";
m_currentLocationUi.locationLabel->setEnabled( true );
m_currentLocationUi.locationLabel->setText( html );
}
void CurrentLocationWidgetPrivate::updateActivePositionProvider( PositionProviderPlugin *plugin )
{
m_currentLocationUi.positionTrackingComboBox->blockSignals( true );
if ( !plugin ) {
m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( 0 );
} else {
for( int i=0; i<m_currentLocationUi.positionTrackingComboBox->count(); ++i ) {
if ( m_currentLocationUi.positionTrackingComboBox->itemText( i ) == plugin->guiString() ) {
m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( i );
break;
}
}
}
m_currentLocationUi.positionTrackingComboBox->blockSignals( false );
m_currentLocationUi.recenterLabel->setEnabled( plugin );
m_currentLocationUi.recenterComboBox->setEnabled( plugin );
m_currentLocationUi.autoZoomCheckBox->setEnabled( plugin );
}
void CurrentLocationWidget::receiveGpsCoordinates( const GeoDataCoordinates &position, qreal speed )
{
d->m_currentPosition = position;
QString unitString;
QString speedString;
QString distanceUnitString;
QString distanceString;
qreal unitSpeed = 0.0;
qreal distance = 0.0;
QString html = "<html><body>";
html += "<table cellspacing=\"2\" cellpadding=\"2\">";
html += "<tr><td>Longitude</td><td><a href=\"http://edu.kde.org/marble\">%1</a></td></tr>";
html += "<tr><td>Latitude</td><td><a href=\"http://edu.kde.org/marble\">%2</a></td></tr>";
html += "<tr><td>Altitude</td><td>%3</td></tr>";
html += "<tr><td>Speed</td><td>%4</td></tr>";
html += "</table>";
html += "</body></html>";
switch ( d->m_locale->measureSystem() ) {
case Metric:
//kilometers per hour
unitString = tr("km/h");
unitSpeed = speed * HOUR2SEC * METER2KM;
distanceUnitString = tr("m");
distance = position.altitude();
break;
case Imperial:
//miles per hour
unitString = tr("m/h");
unitSpeed = speed * HOUR2SEC * METER2KM * KM2MI;
distanceUnitString = tr("ft");
distance = position.altitude() * M2FT;
break;
}
// TODO read this value from the incoming signal
speedString = QLocale::system().toString( unitSpeed, 'f', 1);
distanceString = QString( "%1 %2" ).arg( distance, 0, 'f', 1, QChar(' ') ).arg( distanceUnitString );
html = html.arg( position.lonToString() ).arg( position.latToString() );
html = html.arg( distanceString ).arg( speedString + ' ' + unitString );
d->m_currentLocationUi.locationLabel->setText( html );
d->m_currentLocationUi.showTrackCheckBox->setEnabled( true );
d->m_currentLocationUi.saveTrackPushButton->setEnabled( true );
d->m_currentLocationUi.clearTrackPushButton->setEnabled( true );
}
void CurrentLocationWidgetPrivate::changePositionProvider( const QString &provider )
{
bool hasProvider = ( provider != QObject::tr("Disabled") );
if ( hasProvider ) {
foreach( PositionProviderPlugin* plugin, m_positionProviderPlugins ) {
if ( plugin->guiString() == provider ) {
m_currentLocationUi.locationLabel->setEnabled( true );
PositionProviderPlugin* instance = plugin->newInstance();
PositionTracking *tracking = m_widget->model()->positionTracking();
tracking->setPositionProviderPlugin( instance );
m_widget->setShowGps( true );
m_widget->update();
return;
}
}
}
else {
m_currentLocationUi.locationLabel->setEnabled( false );
m_widget->setShowGps( false );
m_widget->model()->positionTracking()->setPositionProviderPlugin( 0 );
m_widget->update();
}
}
void CurrentLocationWidget::setRecenterMode( int centerMode )
{
d->m_adjustNavigation->setRecenter( centerMode );
}
void CurrentLocationWidget::setAutoZoom( bool autoZoom )
{
d->m_adjustNavigation->setAutoZoom( autoZoom );
}
void CurrentLocationWidgetPrivate::updateAutoZoomCheckBox( bool autoZoom )
{
m_currentLocationUi.autoZoomCheckBox->setChecked( autoZoom );
}
void CurrentLocationWidgetPrivate::updateRecenterComboBox( int centerMode )
{
m_currentLocationUi.recenterComboBox->setCurrentIndex( centerMode );
}
void CurrentLocationWidgetPrivate::centerOnCurrentLocation()
{
m_widget->centerOn(m_currentPosition, true);
}
void CurrentLocationWidgetPrivate::saveTrack()
{
static QString s_dirName = QDir::homePath();
QString fileName = QFileDialog::getSaveFileName(m_widget, QObject::tr("Save Track"), // krazy:exclude=qclasses
s_dirName.append('/' + QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss") + ".kml"),
QObject::tr("KML File (*.kml)"));
if ( fileName ) {
QFileInfo file( fileName );
s_dirName = file.absolutePath();
m_widget->model()->positionTracking()->saveTrack( fileName );
}
}
void CurrentLocationWidgetPrivate::clearTrack()
{
m_widget->model()->positionTracking()->clearTrack();
m_widget->repaint();
m_currentLocationUi.saveTrackPushButton->setEnabled( false );
m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}
}
#include "CurrentLocationWidget.moc"
<commit_msg>fix cancel case<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <[email protected]>
// Copyright 2007 Inge Wallin <[email protected]>
// Copyright 2007 Thomas Zander <[email protected]>
// Copyright 2010 Bastian Holst <[email protected]>
//
// Self
#include "CurrentLocationWidget.h"
// Marble
#include "AdjustNavigation.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "MarbleWidget.h"
#include "GeoDataCoordinates.h"
#include "PositionProviderPlugin.h"
#include "PluginManager.h"
#include "PositionTracking.h"
#include "routing/RoutingManager.h"
using namespace Marble;
/* TRANSLATOR Marble::CurrentLocationWidget */
// Ui
#include "ui_CurrentLocationWidget.h"
#include <QtCore/QDateTime>
#include <QtGui/QFileDialog>
namespace Marble
{
class CurrentLocationWidgetPrivate
{
public:
Ui::CurrentLocationWidget m_currentLocationUi;
MarbleWidget *m_widget;
AdjustNavigation *m_adjustNavigation;
QList<PositionProviderPlugin*> m_positionProviderPlugins;
GeoDataCoordinates m_currentPosition;
MarbleLocale* m_locale;
void adjustPositionTrackingStatus( PositionProviderStatus status );
void changePositionProvider( const QString &provider );
void centerOnCurrentLocation();
void updateRecenterComboBox( int centerMode );
void updateAutoZoomCheckBox( bool autoZoom );
void updateActivePositionProvider( PositionProviderPlugin* );
void saveTrack();
void clearTrack();
};
CurrentLocationWidget::CurrentLocationWidget( QWidget *parent, Qt::WindowFlags f )
: QWidget( parent, f ),
d( new CurrentLocationWidgetPrivate() )
{
d->m_currentLocationUi.setupUi( this );
d->m_locale = MarbleGlobal::getInstance()->locale();
connect( d->m_currentLocationUi.recenterComboBox, SIGNAL ( currentIndexChanged( int ) ),
this, SLOT( setRecenterMode( int ) ) );
connect( d->m_currentLocationUi.autoZoomCheckBox, SIGNAL( clicked( bool ) ),
this, SLOT( setAutoZoom( bool ) ) );
bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;
d->m_currentLocationUi.positionTrackingComboBox->setVisible( !smallScreen );
d->m_currentLocationUi.locationLabel->setVisible( !smallScreen );
}
CurrentLocationWidget::~CurrentLocationWidget()
{
delete d;
}
void CurrentLocationWidget::setMarbleWidget( MarbleWidget *widget )
{
d->m_widget = widget;
d->m_adjustNavigation = new AdjustNavigation( d->m_widget, this );
d->m_widget->model()->routingManager()->setAdjustNavigation( d->m_adjustNavigation );
PluginManager* pluginManager = d->m_widget->model()->pluginManager();
d->m_positionProviderPlugins = pluginManager->createPositionProviderPlugins();
foreach( const PositionProviderPlugin *plugin, d->m_positionProviderPlugins ) {
d->m_currentLocationUi.positionTrackingComboBox->addItem( plugin->guiString() );
}
if ( d->m_positionProviderPlugins.isEmpty() ) {
d->m_currentLocationUi.positionTrackingComboBox->setEnabled( false );
QString html = "<p>No Position Tracking Plugin installed.</p>";
d->m_currentLocationUi.locationLabel->setText( html );
d->m_currentLocationUi.locationLabel->setEnabled ( true );
d->m_currentLocationUi.showTrackCheckBox->setEnabled( false );
d->m_currentLocationUi.saveTrackPushButton->setEnabled( false );
d->m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}
//disconnect CurrentLocation Signals
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
disconnect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
this, SLOT( changePositionProvider( QString ) ) );
disconnect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( centerOnCurrentLocation() ) );
disconnect( d->m_widget->model()->positionTracking(),
SIGNAL( statusChanged( PositionProviderStatus) ),this,
SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );
disconnect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
this, SLOT( updateRecenterComboBox( int ) ) );
disconnect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
this, SLOT( updateAutoZoomCheckBox( bool ) ) );
//connect CurrentLoctaion signals
connect( d->m_widget->model()->positionTracking(),
SIGNAL( gpsLocation( GeoDataCoordinates, qreal ) ),
this, SLOT( receiveGpsCoordinates( GeoDataCoordinates, qreal ) ) );
connect( d->m_widget->model()->positionTracking(),
SIGNAL( positionProviderPluginChanged( PositionProviderPlugin* ) ),
this, SLOT( updateActivePositionProvider( PositionProviderPlugin* ) ) );
d->updateActivePositionProvider( d->m_widget->model()->positionTracking()->positionProviderPlugin() );
connect( d->m_currentLocationUi.positionTrackingComboBox, SIGNAL( currentIndexChanged( QString ) ),
this, SLOT( changePositionProvider( QString ) ) );
connect( d->m_currentLocationUi.locationLabel, SIGNAL( linkActivated( QString ) ),
this, SLOT( centerOnCurrentLocation() ) );
connect( d->m_widget->model()->positionTracking(),
SIGNAL( statusChanged( PositionProviderStatus) ), this,
SLOT( adjustPositionTrackingStatus( PositionProviderStatus) ) );
connect( d->m_adjustNavigation, SIGNAL( recenterModeChanged( int ) ),
this, SLOT( updateRecenterComboBox( int ) ) );
connect( d->m_adjustNavigation, SIGNAL( autoZoomToggled( bool ) ),
this, SLOT( updateAutoZoomCheckBox( bool ) ) );
connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
d->m_widget->model()->positionTracking(), SLOT( setTrackVisible(bool) ));
connect (d->m_currentLocationUi.showTrackCheckBox, SIGNAL( clicked(bool) ),
d->m_widget, SLOT(repaint()));
if ( d->m_widget->model()->positionTracking()->trackVisible() ) {
d->m_currentLocationUi.showTrackCheckBox->setCheckState(Qt::Checked);
}
connect ( d->m_currentLocationUi.saveTrackPushButton, SIGNAL( clicked(bool)),
this, SLOT(saveTrack()));
connect (d->m_currentLocationUi.clearTrackPushButton, SIGNAL( clicked(bool)),
this, SLOT(clearTrack()));
}
void CurrentLocationWidgetPrivate::adjustPositionTrackingStatus( PositionProviderStatus status )
{
if ( status == PositionProviderStatusAvailable ) {
return;
}
QString html = "<html><body><p>";
switch ( status ) {
case PositionProviderStatusUnavailable:
html += QObject::tr( "Waiting for current location information..." );
break;
case PositionProviderStatusAcquiring:
html += QObject::tr( "Initializing current location service..." );
break;
case PositionProviderStatusAvailable:
Q_ASSERT( false );
break;
case PositionProviderStatusError:
html += QObject::tr( "Error when determining current location: " );
html += m_widget->model()->positionTracking()->error();
break;
}
html += "</p></body></html>";
m_currentLocationUi.locationLabel->setEnabled( true );
m_currentLocationUi.locationLabel->setText( html );
}
void CurrentLocationWidgetPrivate::updateActivePositionProvider( PositionProviderPlugin *plugin )
{
m_currentLocationUi.positionTrackingComboBox->blockSignals( true );
if ( !plugin ) {
m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( 0 );
} else {
for( int i=0; i<m_currentLocationUi.positionTrackingComboBox->count(); ++i ) {
if ( m_currentLocationUi.positionTrackingComboBox->itemText( i ) == plugin->guiString() ) {
m_currentLocationUi.positionTrackingComboBox->setCurrentIndex( i );
break;
}
}
}
m_currentLocationUi.positionTrackingComboBox->blockSignals( false );
m_currentLocationUi.recenterLabel->setEnabled( plugin );
m_currentLocationUi.recenterComboBox->setEnabled( plugin );
m_currentLocationUi.autoZoomCheckBox->setEnabled( plugin );
}
void CurrentLocationWidget::receiveGpsCoordinates( const GeoDataCoordinates &position, qreal speed )
{
d->m_currentPosition = position;
QString unitString;
QString speedString;
QString distanceUnitString;
QString distanceString;
qreal unitSpeed = 0.0;
qreal distance = 0.0;
QString html = "<html><body>";
html += "<table cellspacing=\"2\" cellpadding=\"2\">";
html += "<tr><td>Longitude</td><td><a href=\"http://edu.kde.org/marble\">%1</a></td></tr>";
html += "<tr><td>Latitude</td><td><a href=\"http://edu.kde.org/marble\">%2</a></td></tr>";
html += "<tr><td>Altitude</td><td>%3</td></tr>";
html += "<tr><td>Speed</td><td>%4</td></tr>";
html += "</table>";
html += "</body></html>";
switch ( d->m_locale->measureSystem() ) {
case Metric:
//kilometers per hour
unitString = tr("km/h");
unitSpeed = speed * HOUR2SEC * METER2KM;
distanceUnitString = tr("m");
distance = position.altitude();
break;
case Imperial:
//miles per hour
unitString = tr("m/h");
unitSpeed = speed * HOUR2SEC * METER2KM * KM2MI;
distanceUnitString = tr("ft");
distance = position.altitude() * M2FT;
break;
}
// TODO read this value from the incoming signal
speedString = QLocale::system().toString( unitSpeed, 'f', 1);
distanceString = QString( "%1 %2" ).arg( distance, 0, 'f', 1, QChar(' ') ).arg( distanceUnitString );
html = html.arg( position.lonToString() ).arg( position.latToString() );
html = html.arg( distanceString ).arg( speedString + ' ' + unitString );
d->m_currentLocationUi.locationLabel->setText( html );
d->m_currentLocationUi.showTrackCheckBox->setEnabled( true );
d->m_currentLocationUi.saveTrackPushButton->setEnabled( true );
d->m_currentLocationUi.clearTrackPushButton->setEnabled( true );
}
void CurrentLocationWidgetPrivate::changePositionProvider( const QString &provider )
{
bool hasProvider = ( provider != QObject::tr("Disabled") );
if ( hasProvider ) {
foreach( PositionProviderPlugin* plugin, m_positionProviderPlugins ) {
if ( plugin->guiString() == provider ) {
m_currentLocationUi.locationLabel->setEnabled( true );
PositionProviderPlugin* instance = plugin->newInstance();
PositionTracking *tracking = m_widget->model()->positionTracking();
tracking->setPositionProviderPlugin( instance );
m_widget->setShowGps( true );
m_widget->update();
return;
}
}
}
else {
m_currentLocationUi.locationLabel->setEnabled( false );
m_widget->setShowGps( false );
m_widget->model()->positionTracking()->setPositionProviderPlugin( 0 );
m_widget->update();
}
}
void CurrentLocationWidget::setRecenterMode( int centerMode )
{
d->m_adjustNavigation->setRecenter( centerMode );
}
void CurrentLocationWidget::setAutoZoom( bool autoZoom )
{
d->m_adjustNavigation->setAutoZoom( autoZoom );
}
void CurrentLocationWidgetPrivate::updateAutoZoomCheckBox( bool autoZoom )
{
m_currentLocationUi.autoZoomCheckBox->setChecked( autoZoom );
}
void CurrentLocationWidgetPrivate::updateRecenterComboBox( int centerMode )
{
m_currentLocationUi.recenterComboBox->setCurrentIndex( centerMode );
}
void CurrentLocationWidgetPrivate::centerOnCurrentLocation()
{
m_widget->centerOn(m_currentPosition, true);
}
void CurrentLocationWidgetPrivate::saveTrack()
{
static QString s_dirName = QDir::homePath();
QString suggested = s_dirName;
QString fileName = QFileDialog::getSaveFileName(m_widget, QObject::tr("Save Track"), // krazy:exclude=qclasses
suggested.append('/' + QDateTime::currentDateTime().toString("yyyy-MM-dd_hhmmss") + ".kml"),
QObject::tr("KML File (*.kml)"));
if ( !fileName.isEmpty() ) {
QFileInfo file( fileName );
s_dirName = file.absolutePath();
m_widget->model()->positionTracking()->saveTrack( fileName );
}
}
void CurrentLocationWidgetPrivate::clearTrack()
{
m_widget->model()->positionTracking()->clearTrack();
m_widget->repaint();
m_currentLocationUi.saveTrackPushButton->setEnabled( false );
m_currentLocationUi.clearTrackPushButton->setEnabled( false );
}
}
#include "CurrentLocationWidget.moc"
<|endoftext|> |
<commit_before>/*
* Telefónica Digital - Product Development and Innovation
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
* All rights reserved.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "parseArgs/paConfig.h"
#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"
#include "au/CommandLine.h" // au::CommandLine
#include "au/statistics/Cronometer.h" // au::Cronometer
#include "au/string/StringUtilities.h" // au::str()
#include "au/CommandLine.h" // au::CommandLine
#define PROGRESSIVE_NUMBER 20000
static const char *manShortDescription =
"word_generator - a simple tool to generate a random sequence of words. Useful in demos on word counting and topic trending.\n";
static const char *manSynopsis =
" [-r] [-t secs] [-l len] num_words\n"
" [-ramdon] flag to generate randomized sequence of words\n"
" [-repeat secs] time_to_repeat in seconds with a new wave of words\n"
" [-l length] Number of letters of generated words ( default 9 ) \n"
" [-alphabet alphabet size] Number of differnt letters used to generate words ( default 10 ) \n"
" [-progresive] flag to generate sequences of numbers in incressing order ( hit demo )\n";
int word_length;
int alphabet_length;
bool rand_flag;
int max_num_lines;
bool progresive;
int max_rate; // Max rate of words per second
PaArgument paArgs[] =
{
{ "-l", &word_length, "", PaInt, PaOpt, 9,
1,
30,
"Number of letters of generated words ( default 9 )" },
{ "-alphabet", &alphabet_length, "", PaInt, PaOpt, 10,
1,
30,
"Number of differnt letters used to generate words ( default 10 )" },
{ "-random", &rand_flag, "", PaBool, PaOpt,
false,
false, true,
"Flag to generate completelly randomized sequence of words" },
{ "-progressive", &progresive, "", PaBool, PaOpt,
false,
false, true,
"Flag to generate sequences of numbers in incressing order" },
{ "-rate", &max_rate, "", PaInt, PaOpt, 0,
0,
10000000000, "Max rate in words / second" },
{ " ", &max_num_lines, "", PaInt, PaOpt, 0,
0,
1000000000,
"Number of words to be generated" },
PA_END_OF_ARGS
};
int logFd = -1;
char word[100]; // Place for this word
int progressive_word_slots[100]; // Indexes to generate progressive words
au::Cronometer cronometer;
// Get a new random word
void getNewWord() {
if (progresive) {
for (int i = 0; i < word_length; i++) {
word[i] = 48 + progressive_word_slots[i];
}
// Increase counter...
progressive_word_slots[word_length - 1]++;
int pos = word_length - 1;
while ((pos >= 0) && (progressive_word_slots[pos] >= alphabet_length)) {
progressive_word_slots[pos] = 0;
if (pos > 0) {
progressive_word_slots[pos - 1]++;
}
pos--;
}
return;
}
for (int i = 0; i < word_length; i++) {
word[i] = 48 + rand() % alphabet_length;
}
}
class BufferToScreen {
char *buffer;
size_t max_size;
size_t size;
public:
BufferToScreen(size_t _max_size) {
max_size = _max_size;
buffer = (char *)malloc(max_size);
size = 0;
}
void append(char *data, int len) {
if ((size + len) > max_size) {
flush();
}
memcpy(buffer + size, data, len);
size += len;
}
void flush() {
size_t w = write(1, buffer, size);
if (w != size) {
LM_X(1, ("Problem writing %lu bytes to the screen", size));
}
size = 0;
}
};
int main(int argC, const char *argV[]) {
paConfig("usage and exit on any warning", (void *)true);
paConfig("log to screen", (void *)true);
paConfig("log to file", (void *)false);
paConfig("screen line format", (void *)"TYPE:EXEC: TEXT");
paConfig("man shortdescription", (void *)manShortDescription);
paConfig("man synopsis", (void *)manSynopsis);
paConfig("log to stderr", (void *)true);
// Parse input arguments
paParse(paArgs, argC, (char **)argV, 1, false);
logFd = lmFirstDiskFileDescriptor();
// Init progressive
if (progresive) {
for (int i = 0; i < word_length; i++) {
progressive_word_slots[i] = 0;
} // End of line for all the words...
}
word[word_length] = '\n';
word[word_length + 1] = '\0';
size_t num_lines = 0;
size_t total_size = 0;
// Init random numbers if random specified
if (rand_flag) {
srand(time(NULL));
} else {
srand(0); // Time to show a message on screen in verbose mode
}
size_t last_message_time = 0;
// Buffer to flsh data to screen in batches
BufferToScreen buffer_to_screen(10000);
double lines_per_second = 0;
// Generate continuously...
while (true) {
// Check the limit of generated words
if (max_num_lines > 0) {
if (num_lines >= (size_t)max_num_lines) {
break; // Get new word
}
}
getNewWord();
// Length of this word
int word_len = strlen(word);
// Append to the screen
buffer_to_screen.append(word, word_len);
// Counter of bytes and words
total_size += word_len;
num_lines++;
// This avoid exesive calls to timeout
if (lines_per_second > 100000) {
size_t num_continue = lines_per_second / 100;
if ((num_lines % num_continue) != 0) {
continue;
}
}
// Flush accumulated buffer so far
buffer_to_screen.flush();
// Get the total number of seconds running...
size_t total_seconds = cronometer.seconds();
// Compute the number of lines per second, so far...
if (total_seconds > 0) {
lines_per_second = (double)num_lines / (double)total_seconds;
}
if ((total_seconds - last_message_time) > 5) {
last_message_time = total_seconds;
LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}
if (total_seconds > 0) {
if (max_num_lines > 100) {
if ((num_lines % (max_num_lines / 100)) == 0) {
LM_V(("Generated %s - %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str_percentage(num_lines, max_num_lines).c_str(),
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str())); // Sleep if necessary
}
}
}
if (max_rate > 0) {
size_t theoretical_seconds = num_lines / max_rate;
if (total_seconds < theoretical_seconds) {
sleep(theoretical_seconds - total_seconds);
}
}
}
buffer_to_screen.flush();
size_t total_seconds = cronometer.seconds();
LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}
<commit_msg>Fix conflicts<commit_after>/*
* Telefónica Digital - Product Development and Innovation
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*
* Copyright (c) Telefónica Investigación y Desarrollo S.A.U.
* All rights reserved.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "parseArgs/paConfig.h"
#include "parseArgs/parseArgs.h"
#include "logMsg/logMsg.h"
#include "au/CommandLine.h" // au::CommandLine
#include "au/statistics/Cronometer.h" // au::Cronometer
#include "au/string/StringUtilities.h" // au::str()
#include "au/CommandLine.h" // au::CommandLine
#define PROGRESSIVE_NUMBER 20000
static const char *manShortDescription =
"word_generator - a simple tool to generate a random sequence of words. Useful in demos on word counting and topic trending.";
static const char *manSynopsis =
" [-r] [-t secs] [-l len] num_words\n"
" [-ramdon] flag to generate randomized sequence of words\n"
" [-repeat secs] time_to_repeat in seconds with a new wave of words\n"
" [-l length] Number of letters of generated words ( default 9 ) \n"
" [-alphabet alphabet size] Number of differnt letters used to generate words ( default 10 ) \n"
" [-progresive] flag to generate sequences of numbers in incressing order ( hit demo )\n";
int word_length;
int alphabet_length;
bool rand_flag;
int max_num_lines;
bool progresive;
int max_rate; // Max rate of words per second
PaArgument paArgs[] =
{
{ "-l", &word_length, "", PaInt, PaOpt, 9,
1,
30,
"Number of letters of generated words ( default 9 )" },
{ "-alphabet", &alphabet_length, "", PaInt, PaOpt, 10,
1,
30,
"Number of differnt letters used to generate words ( default 10 )" },
{ "-random", &rand_flag, "", PaBool, PaOpt,
false,
false, true,
"Flag to generate completelly randomized sequence of words" },
{ "-progressive", &progresive, "", PaBool, PaOpt,
false,
false, true,
"Flag to generate sequences of numbers in incressing order" },
{ "-rate", &max_rate, "", PaInt, PaOpt, 0,
0,
10000000000, "Max rate in words / second" },
{ " ", &max_num_lines, "", PaInt, PaOpt, 0,
0,
1000000000,
"Number of words to be generated" },
PA_END_OF_ARGS
};
int logFd = -1;
char word[100]; // Place for this word
int progressive_word_slots[100]; // Indexes to generate progressive words
au::Cronometer cronometer;
// Get a new random word
void getNewWord() {
if (progresive) {
for (int i = 0; i < word_length; i++) {
word[i] = 48 + progressive_word_slots[i];
}
// Increase counter...
progressive_word_slots[word_length - 1]++;
int pos = word_length - 1;
while ((pos >= 0) && (progressive_word_slots[pos] >= alphabet_length)) {
progressive_word_slots[pos] = 0;
if (pos > 0) {
progressive_word_slots[pos - 1]++;
}
pos--;
}
return;
}
for (int i = 0; i < word_length; i++) {
word[i] = 48 + rand() % alphabet_length;
}
}
class BufferToScreen {
char *buffer;
size_t max_size;
size_t size;
public:
BufferToScreen(size_t _max_size) {
max_size = _max_size;
buffer = (char *)malloc(max_size);
size = 0;
}
void append(char *data, int len) {
if ((size + len) > max_size) {
flush();
}
memcpy(buffer + size, data, len);
size += len;
}
void flush() {
size_t w = write(1, buffer, size);
if (w != size) {
LM_X(1, ("Problem writing %lu bytes to the screen", size));
}
size = 0;
}
};
int main(int argC, const char *argV[]) {
paConfig("usage and exit on any warning", (void *)true);
paConfig("log to screen", (void *)true);
paConfig("log to file", (void *)false);
paConfig("screen line format", (void *)"TYPE:EXEC: TEXT");
paConfig("man shortdescription", (void *)manShortDescription);
paConfig("man synopsis", (void *)manSynopsis);
paConfig("log to stderr", (void *)true);
// Parse input arguments
paParse(paArgs, argC, (char **)argV, 1, false);
logFd = lmFirstDiskFileDescriptor();
// Init progressive
if (progresive) {
for (int i = 0; i < word_length; i++) {
progressive_word_slots[i] = 0;
} // End of line for all the words...
}
word[word_length] = '\n';
word[word_length + 1] = '\0';
size_t num_lines = 0;
size_t total_size = 0;
// Init random numbers if random specified
if (rand_flag) {
srand(time(NULL));
} else {
srand(0); // Time to show a message on screen in verbose mode
}
size_t last_message_time = 0;
// Buffer to flsh data to screen in batches
BufferToScreen buffer_to_screen(10000);
double lines_per_second = 0;
// Generate continuously...
while (true) {
// Check the limit of generated words
if (max_num_lines > 0) {
if (num_lines >= (size_t)max_num_lines) {
break; // Get new word
}
}
getNewWord();
// Length of this word
int word_len = strlen(word);
// Append to the screen
buffer_to_screen.append(word, word_len);
// Counter of bytes and words
total_size += word_len;
num_lines++;
// This avoid exesive calls to timeout
if (lines_per_second > 100000) {
size_t num_continue = lines_per_second / 100;
if ((num_lines % num_continue) != 0) {
continue;
}
}
// Flush accumulated buffer so far
buffer_to_screen.flush();
// Get the total number of seconds running...
size_t total_seconds = cronometer.seconds();
// Compute the number of lines per second, so far...
if (total_seconds > 0) {
lines_per_second = (double)num_lines / (double)total_seconds;
}
if ((total_seconds - last_message_time) > 5) {
last_message_time = total_seconds;
LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}
if (total_seconds > 0) {
if (max_num_lines > 100) {
if ((num_lines % (max_num_lines / 100)) == 0) {
LM_V(("Generated %s - %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str_percentage(num_lines, max_num_lines).c_str(),
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str())); // Sleep if necessary
}
}
}
if (max_rate > 0) {
size_t theoretical_seconds = num_lines / max_rate;
if (total_seconds < theoretical_seconds) {
sleep(theoretical_seconds - total_seconds);
}
}
}
buffer_to_screen.flush();
size_t total_seconds = cronometer.seconds();
LM_V(("Generated %s lines ( %s bytes ) in %s. Rate: %s / %s",
au::str(num_lines).c_str(), au::str(total_size).c_str(), au::str_time(total_seconds).c_str(),
au::str((double)num_lines / (double)total_seconds,
"Lines/s").c_str(), au::str((double)total_size / (double)total_seconds, "Bps").c_str()));
}
<|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 <stdint.h>
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/future.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include "linux/cgroups.hpp"
#include "slave/flags.hpp"
#include "slave/containerizer/mesos/isolator.hpp"
#include "slave/containerizer/mesos/isolators/gpu/nvidia.hpp"
#include "slave/containerizer/mesos/isolators/gpu/nvml.hpp"
using cgroups::devices::Entry;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
using process::Failure;
using process::Future;
using process::PID;
using std::list;
using std::map;
using std::set;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
// TODO(klueska): Expand this when we support other GPU types.
static constexpr unsigned int NVIDIA_MAJOR_DEVICE = 195;
NvidiaGpuIsolatorProcess::NvidiaGpuIsolatorProcess(
const Flags& _flags,
const string& _hierarchy,
const list<Gpu>& gpus,
const cgroups::devices::Entry& uvmDeviceEntry,
const cgroups::devices::Entry& ctlDeviceEntry)
: flags(_flags),
hierarchy(_hierarchy),
available(gpus),
NVIDIA_CTL_DEVICE_ENTRY(ctlDeviceEntry),
NVIDIA_UVM_DEVICE_ENTRY(uvmDeviceEntry) {}
Try<Isolator*> NvidiaGpuIsolatorProcess::create(const Flags& flags)
{
// Make sure the 'cgroups/devices' isolator is present and
// precedes the GPU isolator.
vector<string> tokens = strings::tokenize(flags.isolation, ",");
auto gpuIsolator =
std::find(tokens.begin(), tokens.end(), "gpu/nvidia");
auto devicesIsolator =
std::find(tokens.begin(), tokens.end(), "cgroups/devices");
CHECK(gpuIsolator != tokens.end());
if (devicesIsolator == tokens.end()) {
return Error("The 'cgroups/devices' isolator must be enabled in"
" order to use the gpu/devices isolator");
}
if (devicesIsolator > gpuIsolator) {
return Error("'cgroups/devices' must precede 'gpu/nvidia'"
" in the --isolation flag");
}
// Initialize NVML.
Try<Nothing> initialize = nvml::initialize();
if (initialize.isError()) {
return Error("Failed to initialize nvml: " + initialize.error());
}
// Enumerate all available GPU devices.
list<Gpu> gpus;
if (flags.nvidia_gpu_devices.isSome()) {
foreach (unsigned int index, flags.nvidia_gpu_devices.get()) {
Try<nvmlDevice_t> handle = nvml::deviceGetHandleByIndex(index);
if (handle.isError()) {
return Error("Failed to obtain Nvidia device handle for"
" index " + stringify(index) + ": " + handle.error());
}
Try<unsigned int> minor = nvml::deviceGetMinorNumber(handle.get());
if (minor.isError()) {
return Error("Failed to obtain Nvidia device minor number: " +
minor.error());
}
Gpu gpu;
gpu.handle = handle.get();
gpu.major = NVIDIA_MAJOR_DEVICE;
gpu.minor = minor.get();
gpus.push_back(gpu);
}
}
// Retrieve the cgroups devices hierarchy.
Result<string> hierarchy = cgroups::hierarchy("devices");
if (hierarchy.isError()) {
return Error(
"Error retrieving the 'devices' subsystem hierarchy: " +
hierarchy.error());
}
// Create the device entries for
// `/dev/nvidiactl` and `/dev/nvidia-uvm`.
Try<dev_t> device = os::stat::rdev("/dev/nvidiactl");
if (device.isError()) {
return Error("Failed to obtain device ID for '/dev/nvidiactl': " +
device.error());
}
cgroups::devices::Entry ctlDeviceEntry;
ctlDeviceEntry.selector.type = Entry::Selector::Type::CHARACTER;
ctlDeviceEntry.selector.major = major(device.get());
ctlDeviceEntry.selector.minor = minor(device.get());
ctlDeviceEntry.access.read = true;
ctlDeviceEntry.access.write = true;
ctlDeviceEntry.access.mknod = true;
device = os::stat::rdev("/dev/nvidia-uvm");
if (device.isError()) {
return Error("Failed to obtain device ID for '/dev/nvidia-uvm': " +
device.error());
}
cgroups::devices::Entry uvmDeviceEntry;
uvmDeviceEntry.selector.type = Entry::Selector::Type::CHARACTER;
uvmDeviceEntry.selector.major = major(device.get());
uvmDeviceEntry.selector.minor = minor(device.get());
uvmDeviceEntry.access.read = true;
uvmDeviceEntry.access.write = true;
uvmDeviceEntry.access.mknod = true;
process::Owned<MesosIsolatorProcess> process(
new NvidiaGpuIsolatorProcess(
flags,
hierarchy.get(),
gpus,
ctlDeviceEntry,
uvmDeviceEntry));
return new MesosIsolator(process);
}
Future<Nothing> NvidiaGpuIsolatorProcess::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
foreach (const ContainerState& state, states) {
const ContainerID& containerId = state.container_id();
const string cgroup = path::join(flags.cgroups_root, containerId.value());
Try<bool> exists = cgroups::exists(hierarchy, cgroup);
if (exists.isError()) {
foreachvalue (Info* info, infos) {
delete info;
}
infos.clear();
return Failure("Failed to check cgroup for container '" +
stringify(containerId) + "'");
}
if (!exists.get()) {
VLOG(1) << "Couldn't find cgroup for container " << containerId;
// This may occur if the executor has exited and the isolator
// has destroyed the cgroup but the slave dies before noticing
// this. This will be detected when the containerizer tries to
// monitor the executor's pid.
continue;
}
infos[containerId] = new Info(containerId, cgroup);
// Determine which GPUs are allocated to this container.
Try<vector<cgroups::devices::Entry>> entries =
cgroups::devices::list(hierarchy, cgroup);
if (entries.isError()) {
return Failure("Failed to obtain devices list for cgroup"
" '" + cgroup + "': " + entries.error());
}
foreach (const cgroups::devices::Entry& entry, entries.get()) {
for (auto gpu = available.begin(); gpu != available.end(); ++gpu) {
if (entry.selector.major == gpu->major &&
entry.selector.minor == gpu->minor) {
infos[containerId]->allocated.push_back(*gpu);
available.erase(gpu);
break;
}
}
}
}
return Nothing();
}
Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::prepare(
const ContainerID& containerId,
const mesos::slave::ContainerConfig& containerConfig)
{
if (infos.contains(containerId)) {
return Failure("Container has already been prepared");
}
infos[containerId] = new Info(
containerId, path::join(flags.cgroups_root, containerId.value()));
return update(containerId, containerConfig.executor_info().resources())
.then([]() -> Future<Option<ContainerLaunchInfo>> {
return None();
});
}
Future<Nothing> NvidiaGpuIsolatorProcess::update(
const ContainerID& containerId,
const Resources& resources)
{
if (!infos.contains(containerId)) {
return Failure("Unknown container");
}
Info* info = CHECK_NOTNULL(infos[containerId]);
Option<double> gpus = resources.gpus();
// Make sure that the `gpus` resource is not fractional.
// We rely on scalar resources only having 3 digits of precision.
if (static_cast<long long>(gpus.getOrElse(0.0) * 1000.0) % 1000 != 0) {
return Failure("The 'gpus' resource must be an unsigned integer");
}
size_t requested = static_cast<size_t>(resources.gpus().getOrElse(0.0));
// Update the GPU allocation to reflect the new total.
if (requested > info->allocated.size()) {
size_t additional = requested - info->allocated.size();
if (additional > available.size()) {
return Failure("Not enough GPUs available to reserve"
" " + stringify(additional) + " additional GPUs");
}
// Grant access to /dev/nvidiactl and /dev/nvida-uvm
// if this container is about to get its first GPU.
if (info->allocated.empty()) {
map<string, cgroups::devices::Entry> entries = {
{ "/dev/nvidiactl", NVIDIA_CTL_DEVICE_ENTRY },
{ "/dev/nvidia-uvm", NVIDIA_UVM_DEVICE_ENTRY },
};
foreachkey (const string& device, entries) {
Try<Nothing> allow = cgroups::devices::allow(
hierarchy, info->cgroup, entries[device]);
if (allow.isError()) {
return Failure("Failed to grant cgroups access to"
" '" + device + "': " + allow.error());
}
}
}
for (size_t i = 0; i < additional; i++) {
const Gpu& gpu = available.front();
cgroups::devices::Entry entry;
entry.selector.type = Entry::Selector::Type::CHARACTER;
entry.selector.major = gpu.major;
entry.selector.minor = gpu.minor;
entry.access.read = true;
entry.access.write = true;
entry.access.mknod = true;
Try<Nothing> allow = cgroups::devices::allow(
hierarchy, info->cgroup, entry);
if (allow.isError()) {
return Failure("Failed to grant cgroups access to GPU device"
" '" + stringify(entry) + "': " + allow.error());
}
info->allocated.push_back(gpu);
available.pop_front();
}
} else if (requested < info->allocated.size()) {
size_t fewer = info->allocated.size() - requested;
for (size_t i = 0; i < fewer; i++) {
const Gpu& gpu = info->allocated.front();
cgroups::devices::Entry entry;
entry.selector.type = Entry::Selector::Type::CHARACTER;
entry.selector.major = gpu.major;
entry.selector.minor = gpu.minor;
entry.access.read = true;
entry.access.write = true;
entry.access.mknod = true;
Try<Nothing> deny = cgroups::devices::deny(
hierarchy, info->cgroup, entry);
if (deny.isError()) {
return Failure("Failed to deny cgroups access to GPU device"
" '" + stringify(entry) + "': " + deny.error());
}
info->allocated.pop_front();
available.push_back(gpu);
}
// Revoke access from /dev/nvidiactl and /dev/nvida-uvm
// if this container no longer has access to any GPUs.
if (info->allocated.empty()) {
map<string, cgroups::devices::Entry> entries = {
{ "/dev/nvidiactl", NVIDIA_CTL_DEVICE_ENTRY },
{ "/dev/nvidia-uvm", NVIDIA_UVM_DEVICE_ENTRY },
};
foreachkey (const string& device, entries) {
Try<Nothing> deny = cgroups::devices::deny(
hierarchy, info->cgroup, entries[device]);
if (deny.isError()) {
return Failure("Failed to deny cgroups access to"
" '" + device + "': " + deny.error());
}
}
}
}
return Nothing();
}
Future<ResourceStatistics> NvidiaGpuIsolatorProcess::usage(
const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
return Failure("Unknown container");
}
// TODO(rtodd): Obtain usage information from NVML.
ResourceStatistics result;
return result;
}
Future<Nothing> NvidiaGpuIsolatorProcess::cleanup(
const ContainerID& containerId)
{
// Multiple calls may occur during test clean up.
if (!infos.contains(containerId)) {
VLOG(1) << "Ignoring cleanup request for unknown container " << containerId;
return Nothing();
}
Info* info = CHECK_NOTNULL(infos[containerId]);
// Make any remaining GPUs available.
available.splice(available.end(), info->allocated);
delete info;
infos.erase(containerId);
return Nothing();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Always grant access to NVIDIA control devices.<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 <stdint.h>
#include <algorithm>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/future.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include "linux/cgroups.hpp"
#include "slave/flags.hpp"
#include "slave/containerizer/mesos/isolator.hpp"
#include "slave/containerizer/mesos/isolators/gpu/nvidia.hpp"
#include "slave/containerizer/mesos/isolators/gpu/nvml.hpp"
using cgroups::devices::Entry;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
using process::Failure;
using process::Future;
using process::PID;
using std::list;
using std::map;
using std::set;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace slave {
// TODO(klueska): Expand this when we support other GPU types.
static constexpr unsigned int NVIDIA_MAJOR_DEVICE = 195;
NvidiaGpuIsolatorProcess::NvidiaGpuIsolatorProcess(
const Flags& _flags,
const string& _hierarchy,
const list<Gpu>& gpus,
const cgroups::devices::Entry& uvmDeviceEntry,
const cgroups::devices::Entry& ctlDeviceEntry)
: flags(_flags),
hierarchy(_hierarchy),
available(gpus),
NVIDIA_CTL_DEVICE_ENTRY(ctlDeviceEntry),
NVIDIA_UVM_DEVICE_ENTRY(uvmDeviceEntry) {}
Try<Isolator*> NvidiaGpuIsolatorProcess::create(const Flags& flags)
{
// Make sure the 'cgroups/devices' isolator is present and
// precedes the GPU isolator.
vector<string> tokens = strings::tokenize(flags.isolation, ",");
auto gpuIsolator =
std::find(tokens.begin(), tokens.end(), "gpu/nvidia");
auto devicesIsolator =
std::find(tokens.begin(), tokens.end(), "cgroups/devices");
CHECK(gpuIsolator != tokens.end());
if (devicesIsolator == tokens.end()) {
return Error("The 'cgroups/devices' isolator must be enabled in"
" order to use the gpu/devices isolator");
}
if (devicesIsolator > gpuIsolator) {
return Error("'cgroups/devices' must precede 'gpu/nvidia'"
" in the --isolation flag");
}
// Initialize NVML.
Try<Nothing> initialize = nvml::initialize();
if (initialize.isError()) {
return Error("Failed to initialize nvml: " + initialize.error());
}
// Enumerate all available GPU devices.
list<Gpu> gpus;
if (flags.nvidia_gpu_devices.isSome()) {
foreach (unsigned int index, flags.nvidia_gpu_devices.get()) {
Try<nvmlDevice_t> handle = nvml::deviceGetHandleByIndex(index);
if (handle.isError()) {
return Error("Failed to obtain Nvidia device handle for"
" index " + stringify(index) + ": " + handle.error());
}
Try<unsigned int> minor = nvml::deviceGetMinorNumber(handle.get());
if (minor.isError()) {
return Error("Failed to obtain Nvidia device minor number: " +
minor.error());
}
Gpu gpu;
gpu.handle = handle.get();
gpu.major = NVIDIA_MAJOR_DEVICE;
gpu.minor = minor.get();
gpus.push_back(gpu);
}
}
// Retrieve the cgroups devices hierarchy.
Result<string> hierarchy = cgroups::hierarchy("devices");
if (hierarchy.isError()) {
return Error(
"Error retrieving the 'devices' subsystem hierarchy: " +
hierarchy.error());
}
// Create the device entries for
// `/dev/nvidiactl` and `/dev/nvidia-uvm`.
Try<dev_t> device = os::stat::rdev("/dev/nvidiactl");
if (device.isError()) {
return Error("Failed to obtain device ID for '/dev/nvidiactl': " +
device.error());
}
cgroups::devices::Entry ctlDeviceEntry;
ctlDeviceEntry.selector.type = Entry::Selector::Type::CHARACTER;
ctlDeviceEntry.selector.major = major(device.get());
ctlDeviceEntry.selector.minor = minor(device.get());
ctlDeviceEntry.access.read = true;
ctlDeviceEntry.access.write = true;
ctlDeviceEntry.access.mknod = true;
device = os::stat::rdev("/dev/nvidia-uvm");
if (device.isError()) {
return Error("Failed to obtain device ID for '/dev/nvidia-uvm': " +
device.error());
}
cgroups::devices::Entry uvmDeviceEntry;
uvmDeviceEntry.selector.type = Entry::Selector::Type::CHARACTER;
uvmDeviceEntry.selector.major = major(device.get());
uvmDeviceEntry.selector.minor = minor(device.get());
uvmDeviceEntry.access.read = true;
uvmDeviceEntry.access.write = true;
uvmDeviceEntry.access.mknod = true;
process::Owned<MesosIsolatorProcess> process(
new NvidiaGpuIsolatorProcess(
flags,
hierarchy.get(),
gpus,
ctlDeviceEntry,
uvmDeviceEntry));
return new MesosIsolator(process);
}
Future<Nothing> NvidiaGpuIsolatorProcess::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
foreach (const ContainerState& state, states) {
const ContainerID& containerId = state.container_id();
const string cgroup = path::join(flags.cgroups_root, containerId.value());
Try<bool> exists = cgroups::exists(hierarchy, cgroup);
if (exists.isError()) {
foreachvalue (Info* info, infos) {
delete info;
}
infos.clear();
return Failure("Failed to check cgroup for container '" +
stringify(containerId) + "'");
}
if (!exists.get()) {
VLOG(1) << "Couldn't find cgroup for container " << containerId;
// This may occur if the executor has exited and the isolator
// has destroyed the cgroup but the slave dies before noticing
// this. This will be detected when the containerizer tries to
// monitor the executor's pid.
continue;
}
infos[containerId] = new Info(containerId, cgroup);
// Determine which GPUs are allocated to this container.
Try<vector<cgroups::devices::Entry>> entries =
cgroups::devices::list(hierarchy, cgroup);
if (entries.isError()) {
return Failure("Failed to obtain devices list for cgroup"
" '" + cgroup + "': " + entries.error());
}
foreach (const cgroups::devices::Entry& entry, entries.get()) {
for (auto gpu = available.begin(); gpu != available.end(); ++gpu) {
if (entry.selector.major == gpu->major &&
entry.selector.minor == gpu->minor) {
infos[containerId]->allocated.push_back(*gpu);
available.erase(gpu);
break;
}
}
}
}
return Nothing();
}
Future<Option<ContainerLaunchInfo>> NvidiaGpuIsolatorProcess::prepare(
const ContainerID& containerId,
const mesos::slave::ContainerConfig& containerConfig)
{
if (infos.contains(containerId)) {
return Failure("Container has already been prepared");
}
infos[containerId] = new Info(
containerId, path::join(flags.cgroups_root, containerId.value()));
// Grant access to /dev/nvidiactl and /dev/nvida-uvm
map<string, const cgroups::devices::Entry> entries = {
{ "/dev/nvidiactl", NVIDIA_CTL_DEVICE_ENTRY },
{ "/dev/nvidia-uvm", NVIDIA_UVM_DEVICE_ENTRY },
};
foreachkey (const string& device, entries) {
Try<Nothing> allow = cgroups::devices::allow(
hierarchy, infos[containerId]->cgroup, entries[device]);
if (allow.isError()) {
return Failure("Failed to grant cgroups access to"
" '" + device + "': " + allow.error());
}
}
return update(containerId, containerConfig.executor_info().resources())
.then([]() -> Future<Option<ContainerLaunchInfo>> {
return None();
});
}
Future<Nothing> NvidiaGpuIsolatorProcess::update(
const ContainerID& containerId,
const Resources& resources)
{
if (!infos.contains(containerId)) {
return Failure("Unknown container");
}
Info* info = CHECK_NOTNULL(infos[containerId]);
Option<double> gpus = resources.gpus();
// Make sure that the `gpus` resource is not fractional.
// We rely on scalar resources only having 3 digits of precision.
if (static_cast<long long>(gpus.getOrElse(0.0) * 1000.0) % 1000 != 0) {
return Failure("The 'gpus' resource must be an unsigned integer");
}
size_t requested = static_cast<size_t>(resources.gpus().getOrElse(0.0));
// Update the GPU allocation to reflect the new total.
if (requested > info->allocated.size()) {
size_t additional = requested - info->allocated.size();
if (additional > available.size()) {
return Failure("Not enough GPUs available to reserve"
" " + stringify(additional) + " additional GPUs");
}
for (size_t i = 0; i < additional; i++) {
const Gpu& gpu = available.front();
cgroups::devices::Entry entry;
entry.selector.type = Entry::Selector::Type::CHARACTER;
entry.selector.major = gpu.major;
entry.selector.minor = gpu.minor;
entry.access.read = true;
entry.access.write = true;
entry.access.mknod = true;
Try<Nothing> allow = cgroups::devices::allow(
hierarchy, info->cgroup, entry);
if (allow.isError()) {
return Failure("Failed to grant cgroups access to GPU device"
" '" + stringify(entry) + "': " + allow.error());
}
info->allocated.push_back(gpu);
available.pop_front();
}
} else if (requested < info->allocated.size()) {
size_t fewer = info->allocated.size() - requested;
for (size_t i = 0; i < fewer; i++) {
const Gpu& gpu = info->allocated.front();
cgroups::devices::Entry entry;
entry.selector.type = Entry::Selector::Type::CHARACTER;
entry.selector.major = gpu.major;
entry.selector.minor = gpu.minor;
entry.access.read = true;
entry.access.write = true;
entry.access.mknod = true;
Try<Nothing> deny = cgroups::devices::deny(
hierarchy, info->cgroup, entry);
if (deny.isError()) {
return Failure("Failed to deny cgroups access to GPU device"
" '" + stringify(entry) + "': " + deny.error());
}
info->allocated.pop_front();
available.push_back(gpu);
}
}
return Nothing();
}
Future<ResourceStatistics> NvidiaGpuIsolatorProcess::usage(
const ContainerID& containerId)
{
if (!infos.contains(containerId)) {
return Failure("Unknown container");
}
// TODO(rtodd): Obtain usage information from NVML.
ResourceStatistics result;
return result;
}
Future<Nothing> NvidiaGpuIsolatorProcess::cleanup(
const ContainerID& containerId)
{
// Multiple calls may occur during test clean up.
if (!infos.contains(containerId)) {
VLOG(1) << "Ignoring cleanup request for unknown container " << containerId;
return Nothing();
}
Info* info = CHECK_NOTNULL(infos[containerId]);
// Make any remaining GPUs available.
available.splice(available.end(), info->allocated);
delete info;
infos.erase(containerId);
return Nothing();
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>/*****************************************************************************
* adaptative.cpp: Adaptative streaming module
*****************************************************************************
* Copyright © 2015 - VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdint.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_demux.h>
#include "playlist/BasePeriod.h"
#include "xml/DOMParser.h"
#include "../dash/DASHManager.h"
#include "../dash/DASHStream.hpp"
#include "../dash/mpd/IsoffMainParser.h"
#include "../hls/HLSManager.hpp"
#include "../hls/HLSStreams.hpp"
#include "../hls/playlist/Parser.hpp"
#include "../hls/playlist/M3U8.hpp"
#include "../smooth/SmoothManager.hpp"
#include "../smooth/SmoothStream.hpp"
#include "../smooth/playlist/Parser.hpp"
using namespace adaptative::logic;
using namespace adaptative::playlist;
using namespace adaptative::xml;
using namespace dash::mpd;
using namespace dash;
using namespace hls;
using namespace hls::playlist;
using namespace smooth;
using namespace smooth::playlist;
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open (vlc_object_t *);
static void Close (vlc_object_t *);
#define ADAPT_WIDTH_TEXT N_("Preferred Width")
#define ADAPT_HEIGHT_TEXT N_("Preferred Height")
#define ADAPT_BW_TEXT N_("Fixed Bandwidth in KiB/s")
#define ADAPT_BW_LONGTEXT N_("Preferred bandwidth for non adaptative streams")
#define ADAPT_LOGIC_TEXT N_("Adaptation Logic")
static const int pi_logics[] = {AbstractAdaptationLogic::RateBased,
AbstractAdaptationLogic::FixedRate,
AbstractAdaptationLogic::AlwaysLowest,
AbstractAdaptationLogic::AlwaysBest};
static const char *const ppsz_logics[] = { N_("Bandwidth Adaptive"),
N_("Fixed Bandwidth"),
N_("Lowest Bandwidth/Quality"),
N_("Highest Bandwith/Quality")};
vlc_module_begin ()
set_shortname( N_("Adaptative"))
set_description( N_("Unified adaptative streaming for DASH/HLS") )
set_capability( "demux", 12 )
set_category( CAT_INPUT )
set_subcategory( SUBCAT_INPUT_DEMUX )
add_integer( "adaptative-logic", AbstractAdaptationLogic::Default,
ADAPT_LOGIC_TEXT, NULL, false )
change_integer_list( pi_logics, ppsz_logics )
add_integer( "adaptative-width", 480, ADAPT_WIDTH_TEXT, ADAPT_WIDTH_TEXT, true )
add_integer( "adaptative-height", 360, ADAPT_HEIGHT_TEXT, ADAPT_HEIGHT_TEXT, true )
add_integer( "adaptative-bw", 250, ADAPT_BW_TEXT, ADAPT_BW_LONGTEXT, false )
set_callbacks( Open, Close )
vlc_module_end ()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
static PlaylistManager * HandleDash(demux_t *, DOMParser &,
const std::string &, AbstractAdaptationLogic::LogicType);
static PlaylistManager * HandleSmooth(demux_t *, DOMParser &,
const std::string &, AbstractAdaptationLogic::LogicType);
/*****************************************************************************
* Open:
*****************************************************************************/
static int Open(vlc_object_t *p_obj)
{
demux_t *p_demux = (demux_t*) p_obj;
std::string mimeType;
char *psz_mime = stream_ContentType(p_demux->s);
if(psz_mime)
{
mimeType = std::string(psz_mime);
free(psz_mime);
}
PlaylistManager *p_manager = NULL;
AbstractAdaptationLogic::LogicType logic =
static_cast<AbstractAdaptationLogic::LogicType>(var_InheritInteger(p_obj, "adaptative-logic"));
std::string playlisturl(p_demux->psz_access);
playlisturl.append("://");
playlisturl.append(p_demux->psz_location);
bool dashmime = DASHManager::mimeMatched(mimeType);
bool smoothmime = SmoothManager::mimeMatched(mimeType);
if(!dashmime && !smoothmime && HLSManager::isHTTPLiveStreaming(p_demux->s))
{
M3U8Parser parser;
M3U8 *p_playlist = parser.parse(p_demux->s, playlisturl);
if(!p_playlist)
{
msg_Err( p_demux, "Could not parse playlist" );
return VLC_EGENERIC;
}
p_manager = new (std::nothrow) HLSManager(p_demux, p_playlist,
new (std::nothrow) HLSStreamFactory, logic);
}
else
{
/* Handle XML Based ones */
DOMParser xmlParser; /* Share that xml reader */
if(dashmime)
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(smoothmime)
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
else
{
/* We need to probe content */
const uint8_t *p_peek;
const size_t i_peek = stream_Peek(p_demux->s, &p_peek, 2048);
stream_t *peekstream = stream_MemoryNew(p_demux, const_cast<uint8_t *>(p_peek), i_peek, true);
if(peekstream)
{
if(xmlParser.reset(peekstream) && xmlParser.parse(false))
{
if(DASHManager::isDASH(xmlParser.getRootNode()))
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(SmoothManager::isSmoothStreaming(xmlParser.getRootNode()))
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
}
stream_Delete(peekstream);
}
}
}
if(!p_manager || !p_manager->start())
{
delete p_manager;
return VLC_EGENERIC;
}
p_demux->p_sys = reinterpret_cast<demux_sys_t *>(p_manager);
p_demux->pf_demux = p_manager->demux_callback;
p_demux->pf_control = p_manager->control_callback;
msg_Dbg(p_obj,"opening playlist file (%s)", p_demux->psz_location);
return VLC_SUCCESS;
}
/*****************************************************************************
* Close:
*****************************************************************************/
static void Close(vlc_object_t *p_obj)
{
demux_t *p_demux = (demux_t*) p_obj;
PlaylistManager *p_manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
delete p_manager;
}
/*****************************************************************************
*
*****************************************************************************/
static PlaylistManager * HandleDash(demux_t *p_demux, DOMParser &xmlParser,
const std::string & playlisturl,
AbstractAdaptationLogic::LogicType logic)
{
if(!xmlParser.reset(p_demux->s) || !xmlParser.parse(true))
{
msg_Err(p_demux, "Cannot parse MPD");
return NULL;
}
IsoffMainParser mpdparser(xmlParser.getRootNode(), p_demux->s, playlisturl);
MPD *p_playlist = mpdparser.parse();
if(p_playlist == NULL)
{
msg_Err( p_demux, "Cannot create/unknown MPD for profile");
return NULL;
}
return new (std::nothrow) DASHManager( p_demux, p_playlist,
new (std::nothrow) DASHStreamFactory,
logic );
}
static PlaylistManager * HandleSmooth(demux_t *p_demux, DOMParser &xmlParser,
const std::string & playlisturl,
AbstractAdaptationLogic::LogicType logic)
{
if(!xmlParser.reset(p_demux->s) || !xmlParser.parse(true))
{
msg_Err(p_demux, "Cannot parse Manifest");
return NULL;
}
ManifestParser mparser(xmlParser.getRootNode(), p_demux->s, playlisturl);
Manifest *p_playlist = mparser.parse();
if(p_playlist == NULL)
{
msg_Err( p_demux, "Cannot create Manifest");
return NULL;
}
return new (std::nothrow) SmoothManager( p_demux, p_playlist,
new (std::nothrow) SmoothStreamFactory,
logic );
}
<commit_msg>demux: adaptative: handle peek error code (fix #15819)<commit_after>/*****************************************************************************
* adaptative.cpp: Adaptative streaming module
*****************************************************************************
* Copyright © 2015 - VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <stdint.h>
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_demux.h>
#include "playlist/BasePeriod.h"
#include "xml/DOMParser.h"
#include "../dash/DASHManager.h"
#include "../dash/DASHStream.hpp"
#include "../dash/mpd/IsoffMainParser.h"
#include "../hls/HLSManager.hpp"
#include "../hls/HLSStreams.hpp"
#include "../hls/playlist/Parser.hpp"
#include "../hls/playlist/M3U8.hpp"
#include "../smooth/SmoothManager.hpp"
#include "../smooth/SmoothStream.hpp"
#include "../smooth/playlist/Parser.hpp"
using namespace adaptative::logic;
using namespace adaptative::playlist;
using namespace adaptative::xml;
using namespace dash::mpd;
using namespace dash;
using namespace hls;
using namespace hls::playlist;
using namespace smooth;
using namespace smooth::playlist;
/*****************************************************************************
* Module descriptor
*****************************************************************************/
static int Open (vlc_object_t *);
static void Close (vlc_object_t *);
#define ADAPT_WIDTH_TEXT N_("Preferred Width")
#define ADAPT_HEIGHT_TEXT N_("Preferred Height")
#define ADAPT_BW_TEXT N_("Fixed Bandwidth in KiB/s")
#define ADAPT_BW_LONGTEXT N_("Preferred bandwidth for non adaptative streams")
#define ADAPT_LOGIC_TEXT N_("Adaptation Logic")
static const int pi_logics[] = {AbstractAdaptationLogic::RateBased,
AbstractAdaptationLogic::FixedRate,
AbstractAdaptationLogic::AlwaysLowest,
AbstractAdaptationLogic::AlwaysBest};
static const char *const ppsz_logics[] = { N_("Bandwidth Adaptive"),
N_("Fixed Bandwidth"),
N_("Lowest Bandwidth/Quality"),
N_("Highest Bandwith/Quality")};
vlc_module_begin ()
set_shortname( N_("Adaptative"))
set_description( N_("Unified adaptative streaming for DASH/HLS") )
set_capability( "demux", 12 )
set_category( CAT_INPUT )
set_subcategory( SUBCAT_INPUT_DEMUX )
add_integer( "adaptative-logic", AbstractAdaptationLogic::Default,
ADAPT_LOGIC_TEXT, NULL, false )
change_integer_list( pi_logics, ppsz_logics )
add_integer( "adaptative-width", 480, ADAPT_WIDTH_TEXT, ADAPT_WIDTH_TEXT, true )
add_integer( "adaptative-height", 360, ADAPT_HEIGHT_TEXT, ADAPT_HEIGHT_TEXT, true )
add_integer( "adaptative-bw", 250, ADAPT_BW_TEXT, ADAPT_BW_LONGTEXT, false )
set_callbacks( Open, Close )
vlc_module_end ()
/*****************************************************************************
* Local prototypes
*****************************************************************************/
static PlaylistManager * HandleDash(demux_t *, DOMParser &,
const std::string &, AbstractAdaptationLogic::LogicType);
static PlaylistManager * HandleSmooth(demux_t *, DOMParser &,
const std::string &, AbstractAdaptationLogic::LogicType);
/*****************************************************************************
* Open:
*****************************************************************************/
static int Open(vlc_object_t *p_obj)
{
demux_t *p_demux = (demux_t*) p_obj;
std::string mimeType;
char *psz_mime = stream_ContentType(p_demux->s);
if(psz_mime)
{
mimeType = std::string(psz_mime);
free(psz_mime);
}
PlaylistManager *p_manager = NULL;
AbstractAdaptationLogic::LogicType logic =
static_cast<AbstractAdaptationLogic::LogicType>(var_InheritInteger(p_obj, "adaptative-logic"));
std::string playlisturl(p_demux->psz_access);
playlisturl.append("://");
playlisturl.append(p_demux->psz_location);
bool dashmime = DASHManager::mimeMatched(mimeType);
bool smoothmime = SmoothManager::mimeMatched(mimeType);
if(!dashmime && !smoothmime && HLSManager::isHTTPLiveStreaming(p_demux->s))
{
M3U8Parser parser;
M3U8 *p_playlist = parser.parse(p_demux->s, playlisturl);
if(!p_playlist)
{
msg_Err( p_demux, "Could not parse playlist" );
return VLC_EGENERIC;
}
p_manager = new (std::nothrow) HLSManager(p_demux, p_playlist,
new (std::nothrow) HLSStreamFactory, logic);
}
else
{
/* Handle XML Based ones */
DOMParser xmlParser; /* Share that xml reader */
if(dashmime)
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(smoothmime)
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
else
{
/* We need to probe content */
const uint8_t *p_peek;
const ssize_t i_peek = stream_Peek(p_demux->s, &p_peek, 2048);
if(i_peek > 0)
{
stream_t *peekstream = stream_MemoryNew(p_demux, const_cast<uint8_t *>(p_peek), (size_t)i_peek, true);
if(peekstream)
{
if(xmlParser.reset(peekstream) && xmlParser.parse(false))
{
if(DASHManager::isDASH(xmlParser.getRootNode()))
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(SmoothManager::isSmoothStreaming(xmlParser.getRootNode()))
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
}
stream_Delete(peekstream);
}
}
}
}
if(!p_manager || !p_manager->start())
{
delete p_manager;
return VLC_EGENERIC;
}
p_demux->p_sys = reinterpret_cast<demux_sys_t *>(p_manager);
p_demux->pf_demux = p_manager->demux_callback;
p_demux->pf_control = p_manager->control_callback;
msg_Dbg(p_obj,"opening playlist file (%s)", p_demux->psz_location);
return VLC_SUCCESS;
}
/*****************************************************************************
* Close:
*****************************************************************************/
static void Close(vlc_object_t *p_obj)
{
demux_t *p_demux = (demux_t*) p_obj;
PlaylistManager *p_manager = reinterpret_cast<PlaylistManager *>(p_demux->p_sys);
delete p_manager;
}
/*****************************************************************************
*
*****************************************************************************/
static PlaylistManager * HandleDash(demux_t *p_demux, DOMParser &xmlParser,
const std::string & playlisturl,
AbstractAdaptationLogic::LogicType logic)
{
if(!xmlParser.reset(p_demux->s) || !xmlParser.parse(true))
{
msg_Err(p_demux, "Cannot parse MPD");
return NULL;
}
IsoffMainParser mpdparser(xmlParser.getRootNode(), p_demux->s, playlisturl);
MPD *p_playlist = mpdparser.parse();
if(p_playlist == NULL)
{
msg_Err( p_demux, "Cannot create/unknown MPD for profile");
return NULL;
}
return new (std::nothrow) DASHManager( p_demux, p_playlist,
new (std::nothrow) DASHStreamFactory,
logic );
}
static PlaylistManager * HandleSmooth(demux_t *p_demux, DOMParser &xmlParser,
const std::string & playlisturl,
AbstractAdaptationLogic::LogicType logic)
{
if(!xmlParser.reset(p_demux->s) || !xmlParser.parse(true))
{
msg_Err(p_demux, "Cannot parse Manifest");
return NULL;
}
ManifestParser mparser(xmlParser.getRootNode(), p_demux->s, playlisturl);
Manifest *p_playlist = mparser.parse();
if(p_playlist == NULL)
{
msg_Err( p_demux, "Cannot create Manifest");
return NULL;
}
return new (std::nothrow) SmoothManager( p_demux, p_playlist,
new (std::nothrow) SmoothStreamFactory,
logic );
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "VolumeSceneParser.h"
#include <ospray/ospray_cpp/Data.h>
using namespace ospray;
using namespace ospcommon;
#include "common/importer/Importer.h"
#include "common/tfn_lib/tfn_lib.h"
#include <iostream>
using std::cerr;
using std::endl;
#include <cstdlib>
// SceneParser definitions ////////////////////////////////////////////////////
VolumeSceneParser::VolumeSceneParser(cpp::Renderer renderer) :
renderer(renderer)
{
}
bool VolumeSceneParser::parse(int ac, const char **&av)
{
bool loadedScene = false;
bool loadedTransferFunction = false;
FileName scene;
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "-s" || arg == "--sampling-rate") {
samplingRate = atof(av[++i]);
} else if (arg == "-tfc" || arg == "--tf-color") {
ospcommon::vec4f color;
color.x = atof(av[++i]);
color.y = atof(av[++i]);
color.z = atof(av[++i]);
color.w = atof(av[++i]);
tf_colors.push_back(color);
} else if (arg == "-tfs" || arg == "--tf-scale") {
tf_scale = atof(av[++i]);
} else if (arg == "-tff" || arg == "--tf-file") {
importTransferFunction(std::string(av[++i]));
loadedTransferFunction = true;
} else if (arg == "-is" || arg == "--surface") {
isosurfaces.push_back(atof(av[++i]));
} else {
FileName fn = arg;
if (fn.ext() == "osp") {
scene = arg;
loadedScene = true;
}
}
}
if (loadedScene) {
sceneModel = make_unique<cpp::Model>();
if (!loadedTransferFunction) {
createDefaultTransferFunction();
}
importObjectsFromFile(scene, loadedTransferFunction);
}
return loadedScene;
}
std::deque<cpp::Model> VolumeSceneParser::model() const
{
std::deque<cpp::Model> models;
models.push_back(sceneModel == nullptr ? cpp::Model() : *sceneModel);
return models;
// return sceneModel.get() == nullptr ? cpp::Model() : *sceneModel;
}
std::deque<box3f> VolumeSceneParser::bbox() const
{
std::deque<ospcommon::box3f> boxes;
boxes.push_back(sceneBbox);
return boxes;
}
void VolumeSceneParser::importObjectsFromFile(const std::string &filename,
bool loadedTransferFunction)
{
auto &model = *sceneModel;
// Load OSPRay objects from a file.
ospray::importer::Group *imported = ospray::importer::import(filename);
// Iterate over geometries
for (size_t i = 0; i < imported->geometry.size(); i++) {
auto geometry = ospray::cpp::Geometry(imported->geometry[i]->handle);
geometry.commit();
model.addGeometry(geometry);
}
// Iterate over volumes
for (size_t i = 0 ; i < imported->volume.size(); i++) {
ospray::importer::Volume *vol = imported->volume[i];
auto volume = ospray::cpp::Volume(vol->handle);
// For now we set the same transfer function on all volumes.
volume.set("transferFunction", transferFunction);
volume.set("samplingRate", samplingRate);
volume.commit();
// Add the loaded volume(s) to the model.
model.addVolume(volume);
// Set the minimum and maximum values in the domain for both color and
// opacity components of the transfer function if we didn't load a transfer
// function for a file (in that case this is already set)
if (!loadedTransferFunction) {
transferFunction.set("valueRange", vol->voxelRange.x, vol->voxelRange.y);
transferFunction.commit();
}
//sceneBbox.extend(vol->bounds);
sceneBbox = vol->bounds;
// Create any specified isosurfaces
if (!isosurfaces.empty()) {
auto isoValueData = ospray::cpp::Data(isosurfaces.size(), OSP_FLOAT,
isosurfaces.data());
auto isoGeometry = ospray::cpp::Geometry("isosurfaces");
isoGeometry.set("isovalues", isoValueData);
isoGeometry.set("volume", volume);
isoGeometry.commit();
model.addGeometry(isoGeometry);
}
}
model.commit();
}
void VolumeSceneParser::importTransferFunction(const std::string &filename)
{
tfn::TransferFunction fcn(filename);
auto colorsData = ospray::cpp::Data(fcn.rgbValues.size(), OSP_FLOAT3,
fcn.rgbValues.data());
transferFunction = cpp::TransferFunction("piecewise_linear");
transferFunction.set("colors", colorsData);
tf_scale = fcn.opacityScaling;
// Sample the opacity values, taking 256 samples to match the volume viewer
// the volume viewer does the sampling a bit differently so we match that
// instead of what's done in createDefault
std::vector<float> opacityValues;
const int N_OPACITIES = 256;
size_t lo = 0;
size_t hi = 1;
for (int i = 0; i < N_OPACITIES; ++i) {
const float x = float(i) / float(N_OPACITIES - 1);
float opacity = 0;
if (i == 0) {
opacity = fcn.opacityValues[0].y;
} else if (i == N_OPACITIES - 1) {
opacity = fcn.opacityValues.back().y;
} else {
// If we're over this val, find the next segment
if (x > fcn.opacityValues[lo].x) {
for (size_t j = lo; j < fcn.opacityValues.size() - 1; ++j) {
if (x <= fcn.opacityValues[j + 1].x) {
lo = j;
hi = j + 1;
break;
}
}
}
const float delta = x - fcn.opacityValues[lo].x;
const float interval = fcn.opacityValues[hi].x - fcn.opacityValues[lo].x;
if (delta == 0 || interval == 0) {
opacity = fcn.opacityValues[lo].y;
} else {
opacity = fcn.opacityValues[lo].y + delta / interval
* (fcn.opacityValues[hi].y - fcn.opacityValues[lo].y);
}
}
opacityValues.push_back(tf_scale * opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
transferFunction.set("valueRange", vec2f(fcn.dataValueMin, fcn.dataValueMax));
// Commit transfer function
transferFunction.commit();
}
void VolumeSceneParser::createDefaultTransferFunction()
{
transferFunction = cpp::TransferFunction("piecewise_linear");
// Add colors
std::vector<vec4f> colors;
if (tf_colors.empty()) {
colors.emplace_back(0.f, 0.f, 0.f, 0.f);
colors.emplace_back(0.9f, 0.9f, 0.9f, 1.f);
} else {
colors = tf_colors;
}
std::vector<vec3f> colorsAsVec3;
for (auto &c : colors) colorsAsVec3.emplace_back(c.x, c.y, c.z);
auto colorsData = ospray::cpp::Data(colors.size(), OSP_FLOAT3,
colorsAsVec3.data());
transferFunction.set("colors", colorsData);
// Add opacities
std::vector<float> opacityValues;
const int N_OPACITIES = 64;//NOTE(jda) - This affects image quality and
// performance!
const int N_INTERVALS = colors.size() - 1;
const float OPACITIES_PER_INTERVAL = N_OPACITIES / float(N_INTERVALS);
for (int i = 0; i < N_OPACITIES; ++i) {
int lcolor = static_cast<int>(i/OPACITIES_PER_INTERVAL);
int hcolor = lcolor + 1;
float v0 = colors[lcolor].w;
float v1 = colors[hcolor].w;
float t = (i / OPACITIES_PER_INTERVAL) - lcolor;
float opacity = (1-t)*v0 + t*v1;
if (opacity > 1.f) opacity = 1.f;
opacityValues.push_back(tf_scale*opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
// Commit transfer function
transferFunction.commit();
}
<commit_msg>add ability to override TF type using env var in VolumeSceneParser<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "VolumeSceneParser.h"
#include <ospray/ospray_cpp/Data.h>
using namespace ospray;
using namespace ospcommon;
#include "common/importer/Importer.h"
#include "common/tfn_lib/tfn_lib.h"
#include <iostream>
using std::cerr;
using std::endl;
#include <cstdlib>
// SceneParser definitions ////////////////////////////////////////////////////
VolumeSceneParser::VolumeSceneParser(cpp::Renderer renderer) :
renderer(renderer)
{
}
bool VolumeSceneParser::parse(int ac, const char **&av)
{
bool loadedScene = false;
bool loadedTransferFunction = false;
FileName scene;
for (int i = 1; i < ac; i++) {
const std::string arg = av[i];
if (arg == "-s" || arg == "--sampling-rate") {
samplingRate = atof(av[++i]);
} else if (arg == "-tfc" || arg == "--tf-color") {
ospcommon::vec4f color;
color.x = atof(av[++i]);
color.y = atof(av[++i]);
color.z = atof(av[++i]);
color.w = atof(av[++i]);
tf_colors.push_back(color);
} else if (arg == "-tfs" || arg == "--tf-scale") {
tf_scale = atof(av[++i]);
} else if (arg == "-tff" || arg == "--tf-file") {
importTransferFunction(std::string(av[++i]));
loadedTransferFunction = true;
} else if (arg == "-is" || arg == "--surface") {
isosurfaces.push_back(atof(av[++i]));
} else {
FileName fn = arg;
if (fn.ext() == "osp") {
scene = arg;
loadedScene = true;
}
}
}
if (loadedScene) {
sceneModel = make_unique<cpp::Model>();
if (!loadedTransferFunction) {
createDefaultTransferFunction();
}
importObjectsFromFile(scene, loadedTransferFunction);
}
return loadedScene;
}
std::deque<cpp::Model> VolumeSceneParser::model() const
{
std::deque<cpp::Model> models;
models.push_back(sceneModel == nullptr ? cpp::Model() : *sceneModel);
return models;
// return sceneModel.get() == nullptr ? cpp::Model() : *sceneModel;
}
std::deque<box3f> VolumeSceneParser::bbox() const
{
std::deque<ospcommon::box3f> boxes;
boxes.push_back(sceneBbox);
return boxes;
}
void VolumeSceneParser::importObjectsFromFile(const std::string &filename,
bool loadedTransferFunction)
{
auto &model = *sceneModel;
// Load OSPRay objects from a file.
ospray::importer::Group *imported = ospray::importer::import(filename);
// Iterate over geometries
for (size_t i = 0; i < imported->geometry.size(); i++) {
auto geometry = ospray::cpp::Geometry(imported->geometry[i]->handle);
geometry.commit();
model.addGeometry(geometry);
}
// Iterate over volumes
for (size_t i = 0 ; i < imported->volume.size(); i++) {
ospray::importer::Volume *vol = imported->volume[i];
auto volume = ospray::cpp::Volume(vol->handle);
// For now we set the same transfer function on all volumes.
volume.set("transferFunction", transferFunction);
volume.set("samplingRate", samplingRate);
volume.commit();
// Add the loaded volume(s) to the model.
model.addVolume(volume);
// Set the minimum and maximum values in the domain for both color and
// opacity components of the transfer function if we didn't load a transfer
// function for a file (in that case this is already set)
if (!loadedTransferFunction) {
transferFunction.set("valueRange", vol->voxelRange.x, vol->voxelRange.y);
transferFunction.commit();
}
//sceneBbox.extend(vol->bounds);
sceneBbox = vol->bounds;
// Create any specified isosurfaces
if (!isosurfaces.empty()) {
auto isoValueData = ospray::cpp::Data(isosurfaces.size(), OSP_FLOAT,
isosurfaces.data());
auto isoGeometry = ospray::cpp::Geometry("isosurfaces");
isoGeometry.set("isovalues", isoValueData);
isoGeometry.set("volume", volume);
isoGeometry.commit();
model.addGeometry(isoGeometry);
}
}
model.commit();
}
void VolumeSceneParser::importTransferFunction(const std::string &filename)
{
tfn::TransferFunction fcn(filename);
auto colorsData = ospray::cpp::Data(fcn.rgbValues.size(), OSP_FLOAT3,
fcn.rgbValues.data());
auto tfFromEnv = getEnvVar<std::string>("OSPRAY_USE_TF_TYPE");
if (tfFromEnv.first) {
transferFunction = cpp::TransferFunction(tfFromEnv.second);
} else {
transferFunction = cpp::TransferFunction("piecewise_linear");
}
transferFunction.set("colors", colorsData);
tf_scale = fcn.opacityScaling;
// Sample the opacity values, taking 256 samples to match the volume viewer
// the volume viewer does the sampling a bit differently so we match that
// instead of what's done in createDefault
std::vector<float> opacityValues;
const int N_OPACITIES = 256;
size_t lo = 0;
size_t hi = 1;
for (int i = 0; i < N_OPACITIES; ++i) {
const float x = float(i) / float(N_OPACITIES - 1);
float opacity = 0;
if (i == 0) {
opacity = fcn.opacityValues[0].y;
} else if (i == N_OPACITIES - 1) {
opacity = fcn.opacityValues.back().y;
} else {
// If we're over this val, find the next segment
if (x > fcn.opacityValues[lo].x) {
for (size_t j = lo; j < fcn.opacityValues.size() - 1; ++j) {
if (x <= fcn.opacityValues[j + 1].x) {
lo = j;
hi = j + 1;
break;
}
}
}
const float delta = x - fcn.opacityValues[lo].x;
const float interval = fcn.opacityValues[hi].x - fcn.opacityValues[lo].x;
if (delta == 0 || interval == 0) {
opacity = fcn.opacityValues[lo].y;
} else {
opacity = fcn.opacityValues[lo].y + delta / interval
* (fcn.opacityValues[hi].y - fcn.opacityValues[lo].y);
}
}
opacityValues.push_back(tf_scale * opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
transferFunction.set("valueRange", vec2f(fcn.dataValueMin, fcn.dataValueMax));
// Commit transfer function
transferFunction.commit();
}
void VolumeSceneParser::createDefaultTransferFunction()
{
auto tfFromEnv = getEnvVar<std::string>("OSPRAY_USE_TF_TYPE");
if (tfFromEnv.first) {
transferFunction = cpp::TransferFunction(tfFromEnv.second);
} else {
transferFunction = cpp::TransferFunction("piecewise_linear");
}
// Add colors
std::vector<vec4f> colors;
if (tf_colors.empty()) {
colors.emplace_back(0.f, 0.f, 0.f, 0.f);
colors.emplace_back(0.9f, 0.9f, 0.9f, 1.f);
} else {
colors = tf_colors;
}
std::vector<vec3f> colorsAsVec3;
for (auto &c : colors) colorsAsVec3.emplace_back(c.x, c.y, c.z);
auto colorsData = ospray::cpp::Data(colors.size(), OSP_FLOAT3,
colorsAsVec3.data());
transferFunction.set("colors", colorsData);
// Add opacities
std::vector<float> opacityValues;
const int N_OPACITIES = 64;//NOTE(jda) - This affects image quality and
// performance!
const int N_INTERVALS = colors.size() - 1;
const float OPACITIES_PER_INTERVAL = N_OPACITIES / float(N_INTERVALS);
for (int i = 0; i < N_OPACITIES; ++i) {
int lcolor = static_cast<int>(i/OPACITIES_PER_INTERVAL);
int hcolor = lcolor + 1;
float v0 = colors[lcolor].w;
float v1 = colors[hcolor].w;
float t = (i / OPACITIES_PER_INTERVAL) - lcolor;
float opacity = (1-t)*v0 + t*v1;
if (opacity > 1.f) opacity = 1.f;
opacityValues.push_back(tf_scale*opacity);
}
auto opacityValuesData = ospray::cpp::Data(opacityValues.size(),
OSP_FLOAT,
opacityValues.data());
transferFunction.set("opacities", opacityValuesData);
// Commit transfer function
transferFunction.commit();
}
<|endoftext|> |
<commit_before>#include "audio/audio.hpp"
#include "main/main.hpp"
#include "world/world.hpp"
#include "graphics/graphics.hpp"
namespace Polarity {
using namespace std;
AudioFile *audioTest;
AudioChannelPlayer *audioPlayer;
bool buzzing = false; // TODO: bring this into a game state! you should buzz if you have the appropriate powerup
bool loaded = false;
shared_ptr<Image> test_image;
void loadAssets() {
audioPlayer = new AudioChannelPlayer(32);
if (audioPlayer->addChannel("white", "assets/audio/frozen_star.mp3", 0) != AudioFileError::OK) {
std::cerr << "Couldn't load white track" << std::endl;
}
if (audioPlayer->addChannel("black", "assets/audio/lightless_dawn.mp3", 1) != AudioFileError::OK) {
std::cerr << "Couldn't load black track" << std::endl;
}
if (audioPlayer->addChannel("buzz", "assets/audio/buzz.mp3", 2) != AudioFileError::OK) {
std::cerr << "Couldn't load buzz track" << std::endl;
} else {
audioPlayer->setChannelVolume("buzz", 1.0);
}
test_image = Image::get("assets/helloworld.png");
}
bool loopIter(SDL_Surface *screen) {
test_image->draw(screen, 0, 0);
SDL_Event event;
std::vector<int> keyUps;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
if (event.type == SDL_KEYDOWN) {
world->keyEvent(event.key.keysym.sym, true);
if (event.key.keysym.sym == SDLK_SPACE) {
audioPlayer->playChannel("white");
audioPlayer->playChannel("black");
} else if (event.key.keysym.sym == SDLK_ESCAPE) {
audioPlayer->stopChannel("white");
audioPlayer->stopChannel("black");
} else if (event.key.keysym.sym == SDLK_w) {
// switch to white track
audioPlayer->setChannelVolume("white", 1.0);
audioPlayer->setChannelVolume("black", 0.0);
} else if (event.key.keysym.sym == SDLK_b) {
// switch to black track
audioPlayer->setChannelVolume("white", 0.0);
audioPlayer->setChannelVolume("black", 1.0);
} else if (event.key.keysym.sym == SDLK_1) {
if (!buzzing) {
audioPlayer->playChannel("buzz", -1);
} else {
audioPlayer->stopChannel("buzz");
}
buzzing = !buzzing;
} else if (event.key.keysym.sym == SDLK_2) {
}
} else {
keyUps.push_back(event.key.keysym.sym);
}
}
}
world->tick();
world->draw(screen);
// all key up have to happen after key downs so we get a full tick of downs
for (auto &key : keyUps) {
world->keyEvent(key, false);
}
return true;
}
}
<commit_msg>get rid of the changes in loop<commit_after>#include "audio/audio.hpp"
#include "main/main.hpp"
#include "world/world.hpp"
#include "graphics/graphics.hpp"
namespace Polarity {
using namespace std;
AudioFile *audioTest;
AudioChannelPlayer *audioPlayer;
bool buzzing = false; // TODO: bring this into a game state! you should buzz if you have the appropriate powerup
bool loaded = false;
void loadAssets() {
audioPlayer = new AudioChannelPlayer(32);
if (audioPlayer->addChannel("white", "assets/audio/frozen_star.mp3", 0) != AudioFileError::OK) {
std::cerr << "Couldn't load white track" << std::endl;
}
if (audioPlayer->addChannel("black", "assets/audio/lightless_dawn.mp3", 1) != AudioFileError::OK) {
std::cerr << "Couldn't load black track" << std::endl;
}
if (audioPlayer->addChannel("buzz", "assets/audio/buzz.mp3", 2) != AudioFileError::OK) {
std::cerr << "Couldn't load buzz track" << std::endl;
} else {
audioPlayer->setChannelVolume("buzz", 1.0);
}
}
bool loopIter(SDL_Surface *screen) {
SDL_Event event;
std::vector<int> keyUps;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
if (event.type == SDL_KEYDOWN) {
world->keyEvent(event.key.keysym.sym, true);
if (event.key.keysym.sym == SDLK_SPACE) {
audioPlayer->playChannel("white");
audioPlayer->playChannel("black");
} else if (event.key.keysym.sym == SDLK_ESCAPE) {
audioPlayer->stopChannel("white");
audioPlayer->stopChannel("black");
} else if (event.key.keysym.sym == SDLK_w) {
// switch to white track
audioPlayer->setChannelVolume("white", 1.0);
audioPlayer->setChannelVolume("black", 0.0);
} else if (event.key.keysym.sym == SDLK_b) {
// switch to black track
audioPlayer->setChannelVolume("white", 0.0);
audioPlayer->setChannelVolume("black", 1.0);
} else if (event.key.keysym.sym == SDLK_1) {
if (!buzzing) {
audioPlayer->playChannel("buzz", -1);
} else {
audioPlayer->stopChannel("buzz");
}
buzzing = !buzzing;
} else if (event.key.keysym.sym == SDLK_2) {
}
} else {
keyUps.push_back(event.key.keysym.sym);
}
}
}
world->tick();
world->draw(screen);
// all key up have to happen after key downs so we get a full tick of downs
for (auto &key : keyUps) {
world->keyEvent(key, false);
}
return true;
}
}
<|endoftext|> |
<commit_before>// @(#)root/gl:$Id$
// Author: Timur Pocheptsov 03/08/2004
// NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these
// attic files for previous CVS history
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TGLFaceSet.h"
#include "TGLRnrCtx.h"
#include "TGLIncludes.h"
#include "TBuffer3D.h"
#include "TMath.h"
// For debug tracing
#include "TClass.h"
#include "TError.h"
//______________________________________________________________________________
//
// Implementss a native ROOT-GL representation of an arbitrary set of
// polygons.
ClassImp(TGLFaceSet);
//______________________________________________________________________________
TGLFaceSet::TGLFaceSet(const TBuffer3D & buffer) :
TGLLogicalShape(buffer),
fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()),
fNormals(3 * buffer.NbPols())
{
// constructor
fNbPols = buffer.NbPols();
Int_t *segs = buffer.fSegs;
Int_t *pols = buffer.fPols;
Int_t descSize = 0;
for (UInt_t i = 0, j = 1; i < fNbPols; ++i, ++j)
{
descSize += pols[j] + 1;
j += pols[j] + 1;
}
fPolyDesc.resize(descSize);
{//fix for scope
for (UInt_t numPol = 0, currInd = 0, j = 1; numPol < fNbPols; ++numPol) {
Int_t segmentInd = pols[j] + j;
Int_t segmentCol = pols[j];
Int_t s1 = pols[segmentInd];
segmentInd--;
Int_t s2 = pols[segmentInd];
segmentInd--;
Int_t segEnds[] = {segs[s1 * 3 + 1], segs[s1 * 3 + 2],
segs[s2 * 3 + 1], segs[s2 * 3 + 2]};
Int_t numPnts[3] = {0};
if (segEnds[0] == segEnds[2]) {
numPnts[0] = segEnds[1], numPnts[1] = segEnds[0], numPnts[2] = segEnds[3];
} else if (segEnds[0] == segEnds[3]) {
numPnts[0] = segEnds[1], numPnts[1] = segEnds[0], numPnts[2] = segEnds[2];
} else if (segEnds[1] == segEnds[2]) {
numPnts[0] = segEnds[0], numPnts[1] = segEnds[1], numPnts[2] = segEnds[3];
} else {
numPnts[0] = segEnds[0], numPnts[1] = segEnds[1], numPnts[2] = segEnds[2];
}
fPolyDesc[currInd] = 3;
Int_t sizeInd = currInd++;
fPolyDesc[currInd++] = numPnts[0];
fPolyDesc[currInd++] = numPnts[1];
fPolyDesc[currInd++] = numPnts[2];
Int_t lastAdded = numPnts[2];
Int_t end = j + 1;
for (; segmentInd != end; segmentInd--) {
segEnds[0] = segs[pols[segmentInd] * 3 + 1];
segEnds[1] = segs[pols[segmentInd] * 3 + 2];
if (segEnds[0] == lastAdded) {
fPolyDesc[currInd++] = segEnds[1];
lastAdded = segEnds[1];
} else {
fPolyDesc[currInd++] = segEnds[0];
lastAdded = segEnds[0];
}
++fPolyDesc[sizeInd];
}
j += segmentCol + 2;
}
}
CalculateNormals();
}
//______________________________________________________________________________
void TGLFaceSet::SetFromMesh(const RootCsg::TBaseMesh *mesh)
{
// Should only be done on an empty faceset object
assert(fNbPols == 0);
UInt_t nv = mesh->NumberOfVertices();
fVertices.reserve(3 * nv);
fNormals.resize(mesh->NumberOfPolys() * 3);
UInt_t i;
for (i = 0; i < nv; ++i) {
const Double_t *v = mesh->GetVertex(i);
fVertices.insert(fVertices.end(), v, v + 3);
}
fNbPols = mesh->NumberOfPolys();
UInt_t descSize = 0;
for (i = 0; i < fNbPols; ++i) descSize += mesh->SizeOfPoly(i) + 1;
fPolyDesc.reserve(descSize);
for (UInt_t polyIndex = 0; polyIndex < fNbPols; ++polyIndex) {
UInt_t polySize = mesh->SizeOfPoly(polyIndex);
fPolyDesc.push_back(polySize);
for(i = 0; i < polySize; ++i) fPolyDesc.push_back(mesh->GetVertexIndex(polyIndex, i));
}
CalculateNormals();
}
//______________________________________________________________________________
void TGLFaceSet::DirectDraw(TGLRnrCtx & rnrCtx) const
{
// Debug tracing
if (gDebug > 4) {
Info("TGLFaceSet::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD());
}
GLUtesselator *tessObj = TGLUtil::GetDrawTesselator3dv();
const Double_t *pnts = &fVertices[0];
const Double_t *normals = &fNormals[0];
const Int_t *pols = &fPolyDesc[0];
for (UInt_t i = 0, j = 0; i < fNbPols; ++i) {
Int_t npoints = pols[j++];
if (tessObj && npoints > 4) {
gluBeginPolygon(tessObj);
gluNextContour(tessObj, (GLenum)GLU_UNKNOWN);
glNormal3dv(normals + i * 3);
for (Int_t k = 0; k < npoints; ++k, ++j) {
gluTessVertex(tessObj, (Double_t *)pnts + pols[j] * 3, (Double_t *)pnts + pols[j] * 3);
}
gluEndPolygon(tessObj);
} else {
glBegin(GL_POLYGON);
glNormal3dv(normals + i * 3);
for (Int_t k = 0; k < npoints; ++k, ++j) {
glVertex3dv(pnts + pols[j] * 3);
}
glEnd();
}
}
}
//______________________________________________________________________________
Int_t TGLFaceSet::CheckPoints(const Int_t *source, Int_t *dest) const
{
// CheckPoints
const Double_t * p1 = &fVertices[source[0] * 3];
const Double_t * p2 = &fVertices[source[1] * 3];
const Double_t * p3 = &fVertices[source[2] * 3];
Int_t retVal = 1;
if (Eq(p1, p2)) {
dest[0] = source[0];
if (!Eq(p1, p3) ) {
dest[1] = source[2];
retVal = 2;
}
} else if (Eq(p1, p3)) {
dest[0] = source[0];
dest[1] = source[1];
retVal = 2;
} else {
dest[0] = source[0];
dest[1] = source[1];
retVal = 2;
if (!Eq(p2, p3)) {
dest[2] = source[2];
retVal = 3;
}
}
return retVal;
}
//______________________________________________________________________________
Bool_t TGLFaceSet::Eq(const Double_t *p1, const Double_t *p2)
{
// test equality
Double_t dx = TMath::Abs(p1[0] - p2[0]);
Double_t dy = TMath::Abs(p1[1] - p2[1]);
Double_t dz = TMath::Abs(p1[2] - p2[2]);
return dx < 1e-10 && dy < 1e-10 && dz < 1e-10;
}
//______________________________________________________________________________
void TGLFaceSet::CalculateNormals()
{
// CalculateNormals
Double_t *pnts = &fVertices[0];
for (UInt_t i = 0, j = 0; i < fNbPols; ++i) {
Int_t polEnd = fPolyDesc[j] + j + 1;
Int_t norm[] = {fPolyDesc[j + 1], fPolyDesc[j + 2], fPolyDesc[j + 3]};
j += 4;
Int_t check = CheckPoints(norm, norm), ngood = check;
if (check == 3) {
TMath::Normal2Plane(pnts + norm[0] * 3, pnts + norm[1] * 3,
pnts + norm[2] * 3, &fNormals[i * 3]);
j = polEnd;
continue;
}
while (j < (UInt_t)polEnd) {
norm[ngood++] = fPolyDesc[j++];
if (ngood == 3) {
ngood = CheckPoints(norm, norm);
if (ngood == 3) {
TMath::Normal2Plane(pnts + norm[0] * 3, pnts + norm[1] * 3,
pnts + norm[2] * 3, &fNormals[i * 3]);
j = polEnd;
break;
}
}
}
}
}
<commit_msg>From Bertrand.<commit_after>// @(#)root/gl:$Id$
// Author: Timur Pocheptsov 03/08/2004
// NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these
// attic files for previous CVS history
/*************************************************************************
* Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TGLFaceSet.h"
#include "TGLRnrCtx.h"
#include "TGLIncludes.h"
#include "TBuffer3D.h"
#include "TMath.h"
// For debug tracing
#include "TClass.h"
#include "TError.h"
//______________________________________________________________________________
//
// Implementss a native ROOT-GL representation of an arbitrary set of
// polygons.
ClassImp(TGLFaceSet);
//______________________________________________________________________________
TGLFaceSet::TGLFaceSet(const TBuffer3D & buffer) :
TGLLogicalShape(buffer),
fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()),
fNormals(3 * buffer.NbPols())
{
// constructor
fNbPols = buffer.NbPols();
Int_t *segs = buffer.fSegs;
Int_t *pols = buffer.fPols;
Int_t descSize = 0;
for (UInt_t i = 0, j = 1; i < fNbPols; ++i, ++j)
{
descSize += pols[j] + 1;
j += pols[j] + 1;
}
fPolyDesc.resize(descSize);
{//fix for scope
for (UInt_t numPol = 0, currInd = 0, j = 1; numPol < fNbPols; ++numPol) {
Int_t segmentInd = pols[j] + j;
Int_t segmentCol = pols[j];
Int_t s1 = pols[segmentInd];
segmentInd--;
Int_t s2 = pols[segmentInd];
segmentInd--;
Int_t segEnds[] = {segs[s1 * 3 + 1], segs[s1 * 3 + 2],
segs[s2 * 3 + 1], segs[s2 * 3 + 2]};
Int_t numPnts[3] = {0};
if (segEnds[0] == segEnds[2]) {
numPnts[0] = segEnds[1], numPnts[1] = segEnds[0], numPnts[2] = segEnds[3];
} else if (segEnds[0] == segEnds[3]) {
numPnts[0] = segEnds[1], numPnts[1] = segEnds[0], numPnts[2] = segEnds[2];
} else if (segEnds[1] == segEnds[2]) {
numPnts[0] = segEnds[0], numPnts[1] = segEnds[1], numPnts[2] = segEnds[3];
} else {
numPnts[0] = segEnds[0], numPnts[1] = segEnds[1], numPnts[2] = segEnds[2];
}
fPolyDesc[currInd] = 3;
Int_t sizeInd = currInd++;
fPolyDesc[currInd++] = numPnts[0];
fPolyDesc[currInd++] = numPnts[1];
fPolyDesc[currInd++] = numPnts[2];
Int_t lastAdded = numPnts[2];
Int_t end = j + 1;
for (; segmentInd != end; segmentInd--) {
segEnds[0] = segs[pols[segmentInd] * 3 + 1];
segEnds[1] = segs[pols[segmentInd] * 3 + 2];
if (segEnds[0] == lastAdded) {
fPolyDesc[currInd++] = segEnds[1];
lastAdded = segEnds[1];
} else {
fPolyDesc[currInd++] = segEnds[0];
lastAdded = segEnds[0];
}
++fPolyDesc[sizeInd];
}
j += segmentCol + 2;
}
}
CalculateNormals();
}
//______________________________________________________________________________
void TGLFaceSet::SetFromMesh(const RootCsg::TBaseMesh *mesh)
{
// Should only be done on an empty faceset object
assert(fNbPols == 0);
UInt_t nv = mesh->NumberOfVertices();
fVertices.reserve(3 * nv);
fNormals.resize(mesh->NumberOfPolys() * 3);
UInt_t i;
for (i = 0; i < nv; ++i) {
const Double_t *v = mesh->GetVertex(i);
fVertices.insert(fVertices.end(), v, v + 3);
}
fNbPols = mesh->NumberOfPolys();
UInt_t descSize = 0;
for (i = 0; i < fNbPols; ++i) descSize += mesh->SizeOfPoly(i) + 1;
fPolyDesc.reserve(descSize);
for (UInt_t polyIndex = 0; polyIndex < fNbPols; ++polyIndex) {
UInt_t polySize = mesh->SizeOfPoly(polyIndex);
fPolyDesc.push_back(polySize);
for(i = 0; i < polySize; ++i) fPolyDesc.push_back(mesh->GetVertexIndex(polyIndex, i));
}
CalculateNormals();
}
//______________________________________________________________________________
void TGLFaceSet::DirectDraw(TGLRnrCtx & rnrCtx) const
{
// Debug tracing
if (gDebug > 4) {
Info("TGLFaceSet::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD());
}
if (fNbPols == 0) return;
GLUtesselator *tessObj = TGLUtil::GetDrawTesselator3dv();
const Double_t *pnts = &fVertices[0];
const Double_t *normals = &fNormals[0];
const Int_t *pols = &fPolyDesc[0];
for (UInt_t i = 0, j = 0; i < fNbPols; ++i) {
Int_t npoints = pols[j++];
if (tessObj && npoints > 4) {
gluBeginPolygon(tessObj);
gluNextContour(tessObj, (GLenum)GLU_UNKNOWN);
glNormal3dv(normals + i * 3);
for (Int_t k = 0; k < npoints; ++k, ++j) {
gluTessVertex(tessObj, (Double_t *)pnts + pols[j] * 3, (Double_t *)pnts + pols[j] * 3);
}
gluEndPolygon(tessObj);
} else {
glBegin(GL_POLYGON);
glNormal3dv(normals + i * 3);
for (Int_t k = 0; k < npoints; ++k, ++j) {
glVertex3dv(pnts + pols[j] * 3);
}
glEnd();
}
}
}
//______________________________________________________________________________
Int_t TGLFaceSet::CheckPoints(const Int_t *source, Int_t *dest) const
{
// CheckPoints
const Double_t * p1 = &fVertices[source[0] * 3];
const Double_t * p2 = &fVertices[source[1] * 3];
const Double_t * p3 = &fVertices[source[2] * 3];
Int_t retVal = 1;
if (Eq(p1, p2)) {
dest[0] = source[0];
if (!Eq(p1, p3) ) {
dest[1] = source[2];
retVal = 2;
}
} else if (Eq(p1, p3)) {
dest[0] = source[0];
dest[1] = source[1];
retVal = 2;
} else {
dest[0] = source[0];
dest[1] = source[1];
retVal = 2;
if (!Eq(p2, p3)) {
dest[2] = source[2];
retVal = 3;
}
}
return retVal;
}
//______________________________________________________________________________
Bool_t TGLFaceSet::Eq(const Double_t *p1, const Double_t *p2)
{
// test equality
Double_t dx = TMath::Abs(p1[0] - p2[0]);
Double_t dy = TMath::Abs(p1[1] - p2[1]);
Double_t dz = TMath::Abs(p1[2] - p2[2]);
return dx < 1e-10 && dy < 1e-10 && dz < 1e-10;
}
//______________________________________________________________________________
void TGLFaceSet::CalculateNormals()
{
// CalculateNormals
if (fNbPols == 0) return;
Double_t *pnts = &fVertices[0];
for (UInt_t i = 0, j = 0; i < fNbPols; ++i) {
Int_t polEnd = fPolyDesc[j] + j + 1;
Int_t norm[] = {fPolyDesc[j + 1], fPolyDesc[j + 2], fPolyDesc[j + 3]};
j += 4;
Int_t check = CheckPoints(norm, norm), ngood = check;
if (check == 3) {
TMath::Normal2Plane(pnts + norm[0] * 3, pnts + norm[1] * 3,
pnts + norm[2] * 3, &fNormals[i * 3]);
j = polEnd;
continue;
}
while (j < (UInt_t)polEnd) {
norm[ngood++] = fPolyDesc[j++];
if (ngood == 3) {
ngood = CheckPoints(norm, norm);
if (ngood == 3) {
TMath::Normal2Plane(pnts + norm[0] * 3, pnts + norm[1] * 3,
pnts + norm[2] * 3, &fNormals[i * 3]);
j = polEnd;
break;
}
}
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_JULIA_CONFIG_HPP
#define XTENSOR_JULIA_CONFIG_HPP
#define XTENSOR_JULIA_VERSION_MAJOR 0
#define XTENSOR_JULIA_VERSION_MINOR 0
#define XTENSOR_JULIA_VERSION_PATCH 6
#endif
<commit_msg>Release 0.0.7<commit_after>/***************************************************************************
* Copyright (c) 2016, Johan Mabille and Sylvain Corlay *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XTENSOR_JULIA_CONFIG_HPP
#define XTENSOR_JULIA_CONFIG_HPP
#define XTENSOR_JULIA_VERSION_MAJOR 0
#define XTENSOR_JULIA_VERSION_MINOR 0
#define XTENSOR_JULIA_VERSION_PATCH 7
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.