text stringlengths 54 60.6k |
|---|
<commit_before>#include "libtorrent/udp_socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <stdlib.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/array.hpp>
#include <asio/read.hpp>
using namespace libtorrent;
udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c
, connection_queue& cc)
: m_callback(c)
, m_ipv4_sock(ios)
, m_ipv6_sock(ios)
, m_bind_port(0)
, m_socks5_sock(ios)
, m_connection_ticket(-1)
, m_cc(cc)
, m_resolver(ios)
, m_tunnel_packets(false)
{
}
void udp_socket::send(udp::endpoint const& ep, char const* p, int len)
{
if (m_tunnel_packets)
{
// send udp packets through SOCKS5 server
wrap(ep, p, len);
return;
}
asio::error_code ec;
if (ep.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec);
else
m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec);
}
void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred)
{
if (e) return;
if (!m_callback) return;
if (s == &m_ipv4_sock)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v4_ep == m_proxy_addr)
unwrap(m_v4_buf, bytes_transferred);
else
m_callback(m_v4_ep, m_v4_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
else
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v6_ep == m_proxy_addr)
unwrap(m_v6_buf, bytes_transferred);
else
m_callback(m_v6_ep, m_v6_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
}
void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len)
{
using namespace libtorrent::detail;
char header[20];
char* h = header;
write_uint16(0, h); // reserved
write_uint8(0, h); // fragment
write_uint8(ep.address().is_v4()?1:4, h); // atyp
write_address(ep.address(), h);
write_uint16(ep.port(), h);
boost::array<asio::const_buffer, 2> iovec;
iovec[0] = asio::const_buffer(header, h - header);
iovec[1] = asio::const_buffer(p, len);
asio::error_code ec;
if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec);
else
m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec);
}
// unwrap the UDP packet from the SOCKS5 header
void udp_socket::unwrap(char const* buf, int size)
{
using namespace libtorrent::detail;
// the minimum socks5 header size
if (size <= 10) return;
char const* p = buf;
p += 2; // reserved
int frag = read_uint8(p);
// fragmentation is not supported
if (frag != 0) return;
udp::endpoint sender;
int atyp = read_uint8(p);
if (atyp == 1)
{
// IPv4
sender.address(address_v4(read_uint32(p)));
sender.port(read_uint16(p));
}
else if (atyp == 4)
{
// IPv6
TORRENT_ASSERT(false && "not supported yet");
}
else
{
// domain name not supported
return;
}
m_callback(sender, p, size - (p - buf));
}
void udp_socket::close()
{
m_ipv4_sock.close();
m_ipv6_sock.close();
m_socks5_sock.close();
m_callback.clear();
if (m_connection_ticket >= 0)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
}
}
void udp_socket::bind(int port)
{
asio::error_code ec;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close();
if (m_ipv6_sock.is_open()) m_ipv6_sock.close();
m_ipv4_sock.open(udp::v4(), ec);
if (!ec)
{
m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec);
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2));
}
m_ipv6_sock.open(udp::v6(), ec);
if (!ec)
{
m_ipv6_sock.set_option(v6only(true), ec);
m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec);
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2));
}
m_bind_port = port;
}
void udp_socket::set_proxy_settings(proxy_settings const& ps)
{
m_socks5_sock.close();
m_tunnel_packets = false;
m_proxy_settings = ps;
if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw)
{
// connect to socks5 server and open up the UDP tunnel
tcp::resolver::query q(ps.hostname
, boost::lexical_cast<std::string>(ps.port));
m_resolver.async_resolve(q, boost::bind(
&udp_socket::on_name_lookup, this, _1, _2));
}
}
void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i)
{
if (e) return;
m_proxy_addr.address(i->endpoint().address());
m_proxy_addr.port(i->endpoint().port());
m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1)
, boost::bind(&udp_socket::on_timeout, this), seconds(10));
}
void udp_socket::on_timeout()
{
m_socks5_sock.close();
m_connection_ticket = -1;
}
void udp_socket::on_connect(int ticket)
{
m_connection_ticket = ticket;
asio::error_code ec;
m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec);
m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port())
, boost::bind(&udp_socket::on_connected, this, _1));
}
void udp_socket::on_connected(asio::error_code const& e)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
if (e) return;
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_proxy_settings.username.empty()
|| m_proxy_settings.type == proxy_settings::socks5)
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake1, this, _1));
}
void udp_socket::handshake1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake2, this, _1));
}
void udp_socket::handshake2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5) return;
if (method == 0)
{
socks_forward_udp();
}
else if (method == 2)
{
if (m_proxy_settings.username.empty())
{
m_socks5_sock.close();
return;
}
// start sub-negotiation
char* p = &m_tmp_buf[0];
write_uint8(1, p);
write_uint8(m_proxy_settings.username.size(), p);
write_string(m_proxy_settings.username, p);
write_uint8(m_proxy_settings.password.size(), p);
write_string(m_proxy_settings.password, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake3, this, _1));
}
else
{
m_socks5_sock.close();
return;
}
}
void udp_socket::handshake3(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake4, this, _1));
}
void udp_socket::handshake4(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1) return;
if (status != 0) return;
socks_forward_udp();
}
void udp_socket::socks_forward_udp()
{
using namespace libtorrent::detail;
// send SOCKS5 UDP command
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(3, p); // UDP ASSOCIATE command
write_uint8(0, p); // reserved
write_uint8(0, p); // ATYP IPv4
write_uint32(0, p); // IP any
write_uint16(m_bind_port, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::connect1, this, _1));
}
void udp_socket::connect1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::connect2, this, _1));
}
void udp_socket::connect2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p); // VERSION
int status = read_uint8(p); // STATUS
read_uint8(p); // RESERVED
int atyp = read_uint8(p); // address type
if (version != 5) return;
if (status != 0) return;
if (atyp == 1)
{
m_proxy_addr.address(address_v4(read_uint32(p)));
m_proxy_addr.port(read_uint16(p));
}
else
{
// in this case we need to read more data from the socket
TORRENT_ASSERT(false && "not implemented yet!");
}
m_tunnel_packets = true;
}
<commit_msg>made udp_socket not use exception<commit_after>#include "libtorrent/udp_socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <stdlib.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/array.hpp>
#include <asio/read.hpp>
using namespace libtorrent;
udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c
, connection_queue& cc)
: m_callback(c)
, m_ipv4_sock(ios)
, m_ipv6_sock(ios)
, m_bind_port(0)
, m_socks5_sock(ios)
, m_connection_ticket(-1)
, m_cc(cc)
, m_resolver(ios)
, m_tunnel_packets(false)
{
}
void udp_socket::send(udp::endpoint const& ep, char const* p, int len)
{
if (m_tunnel_packets)
{
// send udp packets through SOCKS5 server
wrap(ep, p, len);
return;
}
asio::error_code ec;
if (ep.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec);
else
m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec);
}
void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred)
{
if (e) return;
if (!m_callback) return;
if (s == &m_ipv4_sock)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v4_ep == m_proxy_addr)
unwrap(m_v4_buf, bytes_transferred);
else
m_callback(m_v4_ep, m_v4_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
else
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v6_ep == m_proxy_addr)
unwrap(m_v6_buf, bytes_transferred);
else
m_callback(m_v6_ep, m_v6_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
}
void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len)
{
using namespace libtorrent::detail;
char header[20];
char* h = header;
write_uint16(0, h); // reserved
write_uint8(0, h); // fragment
write_uint8(ep.address().is_v4()?1:4, h); // atyp
write_address(ep.address(), h);
write_uint16(ep.port(), h);
boost::array<asio::const_buffer, 2> iovec;
iovec[0] = asio::const_buffer(header, h - header);
iovec[1] = asio::const_buffer(p, len);
asio::error_code ec;
if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec);
else
m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec);
}
// unwrap the UDP packet from the SOCKS5 header
void udp_socket::unwrap(char const* buf, int size)
{
using namespace libtorrent::detail;
// the minimum socks5 header size
if (size <= 10) return;
char const* p = buf;
p += 2; // reserved
int frag = read_uint8(p);
// fragmentation is not supported
if (frag != 0) return;
udp::endpoint sender;
int atyp = read_uint8(p);
if (atyp == 1)
{
// IPv4
sender.address(address_v4(read_uint32(p)));
sender.port(read_uint16(p));
}
else if (atyp == 4)
{
// IPv6
TORRENT_ASSERT(false && "not supported yet");
}
else
{
// domain name not supported
return;
}
m_callback(sender, p, size - (p - buf));
}
void udp_socket::close()
{
asio::error_code ec;
m_ipv4_sock.close(ec);
m_ipv6_sock.close(ec);
m_socks5_sock.close(ec);
m_callback.clear();
if (m_connection_ticket >= 0)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
}
}
void udp_socket::bind(int port)
{
asio::error_code ec;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close(ec);
if (m_ipv6_sock.is_open()) m_ipv6_sock.close(ec);
m_ipv4_sock.open(udp::v4(), ec);
if (!ec)
{
m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec);
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2));
}
m_ipv6_sock.open(udp::v6(), ec);
if (!ec)
{
m_ipv6_sock.set_option(v6only(true), ec);
m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec);
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2));
}
m_bind_port = port;
}
void udp_socket::set_proxy_settings(proxy_settings const& ps)
{
asio::error_code ec;
m_socks5_sock.close(ec);
m_tunnel_packets = false;
m_proxy_settings = ps;
if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw)
{
// connect to socks5 server and open up the UDP tunnel
tcp::resolver::query q(ps.hostname
, boost::lexical_cast<std::string>(ps.port));
m_resolver.async_resolve(q, boost::bind(
&udp_socket::on_name_lookup, this, _1, _2));
}
}
void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i)
{
if (e) return;
m_proxy_addr.address(i->endpoint().address());
m_proxy_addr.port(i->endpoint().port());
m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1)
, boost::bind(&udp_socket::on_timeout, this), seconds(10));
}
void udp_socket::on_timeout()
{
asio::error_code ec;
m_socks5_sock.close(ec);
m_connection_ticket = -1;
}
void udp_socket::on_connect(int ticket)
{
m_connection_ticket = ticket;
asio::error_code ec;
m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec);
m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port())
, boost::bind(&udp_socket::on_connected, this, _1));
}
void udp_socket::on_connected(asio::error_code const& e)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
if (e) return;
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_proxy_settings.username.empty()
|| m_proxy_settings.type == proxy_settings::socks5)
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake1, this, _1));
}
void udp_socket::handshake1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake2, this, _1));
}
void udp_socket::handshake2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5) return;
if (method == 0)
{
socks_forward_udp();
}
else if (method == 2)
{
if (m_proxy_settings.username.empty())
{
asio::error_code ec;
m_socks5_sock.close(ec);
return;
}
// start sub-negotiation
char* p = &m_tmp_buf[0];
write_uint8(1, p);
write_uint8(m_proxy_settings.username.size(), p);
write_string(m_proxy_settings.username, p);
write_uint8(m_proxy_settings.password.size(), p);
write_string(m_proxy_settings.password, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake3, this, _1));
}
else
{
asio::error_code ec;
m_socks5_sock.close(ec);
return;
}
}
void udp_socket::handshake3(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake4, this, _1));
}
void udp_socket::handshake4(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1) return;
if (status != 0) return;
socks_forward_udp();
}
void udp_socket::socks_forward_udp()
{
using namespace libtorrent::detail;
// send SOCKS5 UDP command
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(3, p); // UDP ASSOCIATE command
write_uint8(0, p); // reserved
write_uint8(0, p); // ATYP IPv4
write_uint32(0, p); // IP any
write_uint16(m_bind_port, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::connect1, this, _1));
}
void udp_socket::connect1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::connect2, this, _1));
}
void udp_socket::connect2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p); // VERSION
int status = read_uint8(p); // STATUS
read_uint8(p); // RESERVED
int atyp = read_uint8(p); // address type
if (version != 5) return;
if (status != 0) return;
if (atyp == 1)
{
m_proxy_addr.address(address_v4(read_uint32(p)));
m_proxy_addr.port(read_uint16(p));
}
else
{
// in this case we need to read more data from the socket
TORRENT_ASSERT(false && "not implemented yet!");
}
m_tunnel_packets = true;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <functional>
#include <memory>
#include <future>
#include <atomic>
#include "integration_test_helper.h"
#include "dronecore.h"
#include "plugins/telemetry/telemetry.h"
#include "plugins/action/action.h"
#include "plugins/mission/mission.h"
using namespace dronecore;
using namespace std::placeholders; // for `_1`
static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg,
double longitude_deg,
float relative_altitude_m,
float speed_m_s,
bool is_fly_through,
float gimbal_pitch_deg,
float gimbal_yaw_deg,
float camera_action_delay_s,
MissionItem::CameraAction camera_action);
static void compare_mission_items(const std::shared_ptr<MissionItem> original,
const std::shared_ptr<MissionItem> downloaded);
TEST_F(SitlTest, MissionAddWaypointsAndFly)
{
DroneCore dc;
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Waiting to discover device...";
dc.register_on_discover([prom](uint64_t uuid) {
LogInfo() << "Discovered device with UUID: " << uuid;
prom->set_value();
});
DroneCore::ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS);
future_result.get();
}
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(&device);
auto mission = std::make_shared<Mission>(&device);
auto action = std::make_shared<Action>(&device);
while (!telemetry->health_all_ok()) {
LogInfo() << "Waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LogInfo() << "Device ready";
LogInfo() << "Creating and uploading mission";
std::vector<std::shared_ptr<MissionItem>> mission_items;
mission_items.push_back(
add_mission_item(47.398170327054473,
8.5456490218639658,
10.0f, 5.0f, false,
20.0f, 60.0f,
NAN,
MissionItem::CameraAction::NONE));
mission_items.push_back(
add_mission_item(47.398241338125118,
8.5455360114574432,
10.0f, 2.0f, true,
0.0f, -60.0f,
5.0f,
MissionItem::CameraAction::TAKE_PHOTO));
mission_items.push_back(
add_mission_item(47.398139363821485, 8.5453846156597137,
10.0f, 5.0f, true,
-46.0f, 0.0f,
NAN,
MissionItem::CameraAction::START_VIDEO));
mission_items.push_back(
add_mission_item(47.398058617228855,
8.5454618036746979,
10.0f, 2.0f, false,
-90.0f, 30.0f,
NAN,
MissionItem::CameraAction::STOP_VIDEO));
mission_items.push_back(
add_mission_item(47.398100366082858,
8.5456969141960144,
10.0f, 5.0f, false,
-45.0f, -30.0f,
NAN,
MissionItem::CameraAction::START_PHOTO_INTERVAL));
mission_items.push_back(
add_mission_item(47.398001890458097,
8.5455576181411743,
10.0f, 5.0f, false,
0.0f, 0.0f,
NAN,
MissionItem::CameraAction::STOP_PHOTO_INTERVAL));
{
LogInfo() << "Uploading mission...";
// We only have the upload_mission function asynchronous for now, so we wrap it using
// std::future.
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->upload_mission_async(
mission_items, [prom](Mission::Result result) {
ASSERT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Mission uploaded.";
});
future_result.get();
}
{
// Download the mission again and compare it.
LogInfo() << "Downloading mission...";
// We only have the download_mission function asynchronous for now, so we wrap it using
// std::future.
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->download_mission_async(
[prom, mission_items](
Mission::Result result,
std::vector<std::shared_ptr<MissionItem>> mission_items_downloaded) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Mission downloaded (to check it).";
EXPECT_EQ(mission_items.size(), mission_items_downloaded.size());
if (mission_items.size() == mission_items_downloaded.size()) {
for (unsigned i = 0; i < mission_items.size(); ++i) {
compare_mission_items(mission_items.at(i), mission_items_downloaded.at(i));
}
}
});
future_result.get();
}
LogInfo() << "Arming...";
const Action::Result arm_result = action->arm();
EXPECT_EQ(arm_result, Action::Result::SUCCESS);
LogInfo() << "Armed.";
std::atomic<bool> want_to_pause {false};
// Before starting the mission, we want to be sure to subscribe to the mission progress.
mission->subscribe_progress(
[&want_to_pause](int current, int total) {
LogInfo() << "Mission status update: " << current << " / " << total;
if (current >= 2) {
// We can only set a flag here. If we do more request inside the callback,
// we risk blocking the system.
want_to_pause = true;
}
});
{
LogInfo() << "Starting mission.";
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->start_mission_async(
[prom](Mission::Result result) {
ASSERT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Started mission.";
});
future_result.get();
}
while (!want_to_pause) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Pausing mission...";
mission->pause_mission_async(
[prom](Mission::Result result) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
});
future_result.get();
LogInfo() << "Mission paused.";
}
// Pause for 5 seconds.
std::this_thread::sleep_for(std::chrono::seconds(5));
// Then continue.
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Resuming mission...";
mission->start_mission_async(
[prom](Mission::Result result) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
});
future_result.get();
LogInfo() << "Mission resumed.";
}
while (!mission->mission_finished()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{
// We are done, and can do RTL to go home.
LogInfo() << "Commanding RTL...";
const Action::Result result = action->return_to_launch();
EXPECT_EQ(result, Action::Result::SUCCESS);
LogInfo() << "Commanded RTL.";
}
// We need to wait a bit, otherwise the armed state might not be correct yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
while (telemetry->armed()) {
// Wait until we're done.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LogInfo() << "Disarmed, exiting.";
}
std::shared_ptr<MissionItem> add_mission_item(double latitude_deg,
double longitude_deg,
float relative_altitude_m,
float speed_m_s,
bool is_fly_through,
float gimbal_pitch_deg,
float gimbal_yaw_deg,
float camera_action_delay_s,
MissionItem::CameraAction camera_action)
{
auto new_item = std::make_shared<MissionItem>();
new_item->set_position(latitude_deg, longitude_deg);
new_item->set_relative_altitude(relative_altitude_m);
new_item->set_speed(speed_m_s);
new_item->set_fly_through(is_fly_through);
new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg);
new_item->set_camera_action_delay(camera_action_delay_s);
new_item->set_camera_action(camera_action);
// In order to test setting the interval, add it here.
if (camera_action == MissionItem::CameraAction::START_PHOTO_INTERVAL) {
new_item->set_camera_photo_interval(1.5);
}
return new_item;
}
void compare_mission_items(const std::shared_ptr<MissionItem> original,
const std::shared_ptr<MissionItem> downloaded)
{
EXPECT_NEAR(original->get_latitude_deg(), downloaded->get_latitude_deg(), 1e-6);
EXPECT_NEAR(original->get_longitude_deg(), downloaded->get_longitude_deg(), 1e-6);
EXPECT_FLOAT_EQ(original->get_relative_altitude_m(),
downloaded->get_relative_altitude_m());
EXPECT_EQ(original->get_fly_through(), downloaded->get_fly_through());
if (std::isfinite(original->get_speed_m_s())) {
EXPECT_FLOAT_EQ(original->get_speed_m_s(), downloaded->get_speed_m_s());
}
EXPECT_EQ(original->get_camera_action(), downloaded->get_camera_action());
if (original->get_camera_action() == MissionItem::CameraAction::START_PHOTO_INTERVAL &&
std::isfinite(original->get_camera_photo_interval_s())) {
EXPECT_DOUBLE_EQ(original->get_camera_photo_interval_s(),
downloaded->get_camera_photo_interval_s());
}
if (std::isfinite(original->get_camera_action_delay_s())) {
EXPECT_FLOAT_EQ(original->get_camera_action_delay_s(),
downloaded->get_camera_action_delay_s());
}
}
<commit_msg>mission: add define to test huge missions<commit_after>#include <iostream>
#include <functional>
#include <memory>
#include <future>
#include <atomic>
#include "integration_test_helper.h"
#include "dronecore.h"
#include "plugins/telemetry/telemetry.h"
#include "plugins/action/action.h"
#include "plugins/mission/mission.h"
using namespace dronecore;
using namespace std::placeholders; // for `_1`
static std::shared_ptr<MissionItem> add_mission_item(double latitude_deg,
double longitude_deg,
float relative_altitude_m,
float speed_m_s,
bool is_fly_through,
float gimbal_pitch_deg,
float gimbal_yaw_deg,
float camera_action_delay_s,
MissionItem::CameraAction camera_action);
static void compare_mission_items(const std::shared_ptr<MissionItem> original,
const std::shared_ptr<MissionItem> downloaded);
// Set to 1 to test with 1200 mission items.
#define MANY_ITEMS_TEST 0
TEST_F(SitlTest, MissionAddWaypointsAndFly)
{
DroneCore dc;
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Waiting to discover device...";
dc.register_on_discover([prom](uint64_t uuid) {
LogInfo() << "Discovered device with UUID: " << uuid;
prom->set_value();
});
DroneCore::ConnectionResult ret = dc.add_udp_connection();
ASSERT_EQ(ret, DroneCore::ConnectionResult::SUCCESS);
future_result.get();
}
Device &device = dc.device();
auto telemetry = std::make_shared<Telemetry>(&device);
auto mission = std::make_shared<Mission>(&device);
auto action = std::make_shared<Action>(&device);
while (!telemetry->health_all_ok()) {
LogInfo() << "Waiting for device to be ready";
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LogInfo() << "Device ready";
LogInfo() << "Creating and uploading mission";
std::vector<std::shared_ptr<MissionItem>> mission_items;
#if MANY_ITEMS_TEST==1
for (int i = 0; i < 50; ++i) {
#endif
mission_items.push_back(
add_mission_item(47.398170327054473,
8.5456490218639658,
10.0f, 5.0f, false,
20.0f, 60.0f,
NAN,
MissionItem::CameraAction::NONE));
mission_items.push_back(
add_mission_item(47.398241338125118,
8.5455360114574432,
10.0f, 2.0f, true,
0.0f, -60.0f,
5.0f,
MissionItem::CameraAction::TAKE_PHOTO));
mission_items.push_back(
add_mission_item(47.398139363821485, 8.5453846156597137,
10.0f, 5.0f, true,
-46.0f, 0.0f,
NAN,
MissionItem::CameraAction::START_VIDEO));
mission_items.push_back(
add_mission_item(47.398058617228855,
8.5454618036746979,
10.0f, 2.0f, false,
-90.0f, 30.0f,
NAN,
MissionItem::CameraAction::STOP_VIDEO));
mission_items.push_back(
add_mission_item(47.398100366082858,
8.5456969141960144,
10.0f, 5.0f, false,
-45.0f, -30.0f,
NAN,
MissionItem::CameraAction::START_PHOTO_INTERVAL));
mission_items.push_back(
add_mission_item(47.398001890458097,
8.5455576181411743,
10.0f, 5.0f, false,
0.0f, 0.0f,
NAN,
MissionItem::CameraAction::STOP_PHOTO_INTERVAL));
#if MANY_ITEMS_TEST==1
}
#endif
{
LogInfo() << "Uploading mission...";
// We only have the upload_mission function asynchronous for now, so we wrap it using
// std::future.
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->upload_mission_async(
mission_items, [prom](Mission::Result result) {
ASSERT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Mission uploaded.";
});
future_result.get();
}
{
// Download the mission again and compare it.
LogInfo() << "Downloading mission...";
// We only have the download_mission function asynchronous for now, so we wrap it using
// std::future.
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->download_mission_async(
[prom, mission_items](
Mission::Result result,
std::vector<std::shared_ptr<MissionItem>> mission_items_downloaded) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Mission downloaded (to check it).";
EXPECT_EQ(mission_items.size(), mission_items_downloaded.size());
if (mission_items.size() == mission_items_downloaded.size()) {
for (unsigned i = 0; i < mission_items.size(); ++i) {
compare_mission_items(mission_items.at(i), mission_items_downloaded.at(i));
}
}
});
future_result.get();
}
LogInfo() << "Arming...";
const Action::Result arm_result = action->arm();
EXPECT_EQ(arm_result, Action::Result::SUCCESS);
LogInfo() << "Armed.";
std::atomic<bool> want_to_pause {false};
// Before starting the mission, we want to be sure to subscribe to the mission progress.
mission->subscribe_progress(
[&want_to_pause](int current, int total) {
LogInfo() << "Mission status update: " << current << " / " << total;
if (current >= 2) {
// We can only set a flag here. If we do more request inside the callback,
// we risk blocking the system.
want_to_pause = true;
}
});
{
LogInfo() << "Starting mission.";
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
mission->start_mission_async(
[prom](Mission::Result result) {
ASSERT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
LogInfo() << "Started mission.";
});
future_result.get();
}
while (!want_to_pause) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Pausing mission...";
mission->pause_mission_async(
[prom](Mission::Result result) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
});
future_result.get();
LogInfo() << "Mission paused.";
}
// Pause for 5 seconds.
std::this_thread::sleep_for(std::chrono::seconds(5));
// Then continue.
{
auto prom = std::make_shared<std::promise<void>>();
auto future_result = prom->get_future();
LogInfo() << "Resuming mission...";
mission->start_mission_async(
[prom](Mission::Result result) {
EXPECT_EQ(result, Mission::Result::SUCCESS);
prom->set_value();
});
future_result.get();
LogInfo() << "Mission resumed.";
}
while (!mission->mission_finished()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
{
// We are done, and can do RTL to go home.
LogInfo() << "Commanding RTL...";
const Action::Result result = action->return_to_launch();
EXPECT_EQ(result, Action::Result::SUCCESS);
LogInfo() << "Commanded RTL.";
}
// We need to wait a bit, otherwise the armed state might not be correct yet.
std::this_thread::sleep_for(std::chrono::seconds(2));
while (telemetry->armed()) {
// Wait until we're done.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LogInfo() << "Disarmed, exiting.";
}
std::shared_ptr<MissionItem> add_mission_item(double latitude_deg,
double longitude_deg,
float relative_altitude_m,
float speed_m_s,
bool is_fly_through,
float gimbal_pitch_deg,
float gimbal_yaw_deg,
float camera_action_delay_s,
MissionItem::CameraAction camera_action)
{
auto new_item = std::make_shared<MissionItem>();
new_item->set_position(latitude_deg, longitude_deg);
new_item->set_relative_altitude(relative_altitude_m);
new_item->set_speed(speed_m_s);
new_item->set_fly_through(is_fly_through);
new_item->set_gimbal_pitch_and_yaw(gimbal_pitch_deg, gimbal_yaw_deg);
new_item->set_camera_action_delay(camera_action_delay_s);
new_item->set_camera_action(camera_action);
// In order to test setting the interval, add it here.
if (camera_action == MissionItem::CameraAction::START_PHOTO_INTERVAL) {
new_item->set_camera_photo_interval(1.5);
}
return new_item;
}
void compare_mission_items(const std::shared_ptr<MissionItem> original,
const std::shared_ptr<MissionItem> downloaded)
{
EXPECT_NEAR(original->get_latitude_deg(), downloaded->get_latitude_deg(), 1e-6);
EXPECT_NEAR(original->get_longitude_deg(), downloaded->get_longitude_deg(), 1e-6);
EXPECT_FLOAT_EQ(original->get_relative_altitude_m(),
downloaded->get_relative_altitude_m());
EXPECT_EQ(original->get_fly_through(), downloaded->get_fly_through());
if (std::isfinite(original->get_speed_m_s())) {
EXPECT_FLOAT_EQ(original->get_speed_m_s(), downloaded->get_speed_m_s());
}
EXPECT_EQ(original->get_camera_action(), downloaded->get_camera_action());
if (original->get_camera_action() == MissionItem::CameraAction::START_PHOTO_INTERVAL &&
std::isfinite(original->get_camera_photo_interval_s())) {
EXPECT_DOUBLE_EQ(original->get_camera_photo_interval_s(),
downloaded->get_camera_photo_interval_s());
}
if (std::isfinite(original->get_camera_action_delay_s())) {
EXPECT_FLOAT_EQ(original->get_camera_action_delay_s(),
downloaded->get_camera_action_delay_s());
}
}
<|endoftext|> |
<commit_before>#include "Overlay.h"
#include "ui_Overlay.h"
#include "../Hearthstone.h"
#include "../Settings.h"
#ifdef Q_OS_MAC
#include <objc/objc-runtime.h>
#endif
#include <cassert>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QMouseEvent>
#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100
class OverlayHistoryWindow {
private:
QString mTitle;
OverlayHistoryList mHistory;
QFont mRowFont;
QFont mTitleFont;
int mWidth;
int mPadding;
int mRowSpacing;
int TitleHeight() const {
QFontMetrics titleMetrics( mTitleFont );
return titleMetrics.ascent() - titleMetrics.descent();
}
int Padding() const {
return mPadding;
}
int RowSpacing() const {
return mRowSpacing;
}
int RowHeight() const {
QFontMetrics rowMetrics( mRowFont );
return rowMetrics.ascent() - rowMetrics.descent();
}
int RowWidth() const {
return Width() - Padding() * 2;
}
void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {
// Draw mana
QPen origPen = painter.pen();
QPen pen( QColor( 0, 52, 113 ) );
pen.setCosmetic( true );
pen.setWidth( 1 );
painter.setPen( pen );
QBrush brush( QColor( 40, 119, 238 ) );
painter.setBrush( brush );
QTransform transform;
painter.translate( x + width * 0.5, y + height * 0.5 );
painter.scale( width * 0.8, height * 0.8 );
static const QPointF points[5] = {
QPointF( 0.0, -1.0 ),
QPointF( 1.0, -0.2 ),
QPointF( 0.6, 1.0 ),
QPointF( -0.6, 1.0 ),
QPointF( -1.0, -0.2 ),
};
painter.drawConvexPolygon( points, 5 );
painter.resetTransform();
painter.setPen( origPen );
painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );
}
void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {
painter.save();
painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );
if( count > 1 ) {
int nameWidth = QFontMetrics( painter.font() ).width( name + " " );
QString countString = QString( "x%1" ).arg( count );
QFont font = painter.font();
font.setBold( true );
painter.setFont( font );
painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );
}
painter.restore();
}
public:
OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, int titleFontSize, int rowFontSize )
: mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )
{
mRowFont.setPixelSize( titleFontSize );
mTitleFont.setPixelSize( rowFontSize );
mTitleFont.setUnderline( true );
mTitleFont.setBold( true );
}
int Width() const {
return mWidth;
}
int Height() const {
return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items
mHistory.count() * RowHeight() + // Height per item
TitleHeight() + RowSpacing() + // Title
Padding() * 2; // Overall padding
}
void Paint( QPainter& painter, int x, int y ) const {
painter.save();
QRect rect( x, y, Width(), Height() );
painter.setClipRect( rect );
// BG
QPen pen = QPen( QColor( 160, 160, 160 ) );
pen.setWidth( 3 );
painter.setPen( pen );
painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );
painter.drawRoundedRect( rect, 10, 10 );
// Title
y += Padding();
painter.setPen( QPen( Qt::white) );
painter.setFont( mTitleFont );
painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );
y += TitleHeight() + RowSpacing();
// Lines
painter.setPen( QPen( Qt::white) );
painter.setFont( mRowFont );
for( const QVariantMap& it : mHistory ) {
int mx = x + Padding();
DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() );
int cx = mx + RowHeight() + 5;
DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() );
y += RowHeight();
y += RowSpacing();
}
painter.restore();
}
};
Overlay::Overlay( QWidget *parent )
: QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )
{
mUI->setupUi( this );
setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool );
setAttribute( Qt::WA_TranslucentBackground );
connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );
connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );
connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );
connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );
connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );
LoadCards();
hide();
#ifdef Q_OS_MAC
WId windowObject = this->winId();
objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);
objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") );
int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;
objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces );
#endif
}
Overlay::~Overlay() {
delete mUI;
}
void Overlay::CheckForHover() {
QPoint mouseLoc = mapFromGlobal( QCursor::pos() );
Player showPlayerHistory = PLAYER_UNKNOWN;
if( mPlayerDeckRect.contains( mouseLoc ) ) {
showPlayerHistory = PLAYER_SELF;
} else if( mOpponentDeckRect.contains( mouseLoc ) ) {
showPlayerHistory = PLAYER_OPPONENT;
}
if( mShowPlayerHistory != showPlayerHistory ) {
mShowPlayerHistory = showPlayerHistory;
update();
}
}
void Overlay::LoadCards() {
QFile file( ":/data/cards.json" );
bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );
assert( opened );
QByteArray jsonData = file.readAll();
QJsonParseError error;
QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();
assert( error.error == QJsonParseError::NoError );
mCardDB.clear();
for( QJsonValueRef jsonCardRef : jsonCards ) {
QJsonObject jsonCard = jsonCardRef.toObject();
mCardDB[ jsonCard["id"].toString() ] = jsonCard.toVariantMap();
}
}
void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {
int padding = 10;
QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );
rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window
wnd.Paint( painter, rect.x(), rect.y() );
}
void Overlay::paintEvent( QPaintEvent* ) {
QPainter painter( this );
painter.setRenderHint( QPainter::Antialiasing );
int overlayWidth = 200;
if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {
OverlayHistoryWindow wnd( "Cards drawn", mPlayerHistory, overlayWidth, 10, 10, 12, 12 );
PaintHistoryInScreen( painter, wnd, mPlayerDeckRect.topRight() + QPoint( 20, 0 ) );
} else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {
OverlayHistoryWindow wnd( "Cards played by opponent", mOpponentHistory, overlayWidth, 10, 10, 12, 12 );
PaintHistoryInScreen( painter, wnd, mOpponentDeckRect.topRight() + QPoint( 20, 0 ) );
}
}
void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {
move( x, y );
setFixedSize( w, h );
int minWidth = h * 4 / 3;
mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );
mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );
update();
}
void Overlay::Update() {
if( Settings::Instance()->OverlayEnabled() ) {
show();
setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466)
} else {
hide();
}
update();
}
void Overlay::HandleGameStarted() {
mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );
Update();
}
void Overlay::HandleGameStopped() {
mCheckForHoverTimer.stop();
Update();
}
void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {
QMap< QString, QVariantMap > entries;
for( const CardHistoryItem& it : list ) {
const QString& cardId = it.cardId;
if( cardId.isEmpty() ) {
continue;
}
if( !mCardDB.contains( cardId ) ) {
DBG( "Card %s not found", qt2cstr( cardId ) );
continue;
}
if( mCardDB[ cardId ][ "type" ] == "hero" ) {
continue;
}
if( it.player != player ) {
continue;
}
QVariantMap& entry = entries[ cardId ];
entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1;
entry[ "mana" ] = mCardDB[ cardId ][ "mana" ];
entry[ "name" ] = mCardDB[ cardId ][ "name" ];
}
OverlayHistoryList* ref;
if( player == PLAYER_SELF ) {
ref = &mPlayerHistory;
} else {
ref = &mOpponentHistory;
}
*ref = entries.values();
qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {
if( a["mana"].toInt() == b["mana"].toInt() ) {
return a["name"].toString() < b["name"].toString();
} else {
return a["mana"].toInt() < b["mana"].toInt();
}
});
}
void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {
UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );
UpdateHistoryFor( PLAYER_SELF, cardsDrawn );
Update();
}
void Overlay::HandleOverlaySettingChanged( bool enabled ) {
UNUSED_ARG( enabled );
Update();
}
<commit_msg>Change overlay size<commit_after>#include "Overlay.h"
#include "ui_Overlay.h"
#include "../Hearthstone.h"
#include "../Settings.h"
#ifdef Q_OS_MAC
#include <objc/objc-runtime.h>
#endif
#include <cassert>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>
#include <QMouseEvent>
#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100
class OverlayHistoryWindow {
private:
QString mTitle;
OverlayHistoryList mHistory;
QFont mRowFont;
QFont mTitleFont;
int mWidth;
int mPadding;
int mRowSpacing;
int TitleHeight() const {
QFontMetrics titleMetrics( mTitleFont );
return titleMetrics.ascent() - titleMetrics.descent();
}
int Padding() const {
return mPadding;
}
int RowSpacing() const {
return mRowSpacing;
}
int RowHeight() const {
QFontMetrics rowMetrics( mRowFont );
return rowMetrics.ascent() - rowMetrics.descent();
}
int RowWidth() const {
return Width() - Padding() * 2;
}
void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {
// Draw mana
QPen origPen = painter.pen();
QPen pen( QColor( 0, 52, 113 ) );
pen.setCosmetic( true );
pen.setWidth( 1 );
painter.setPen( pen );
QBrush brush( QColor( 40, 119, 238 ) );
painter.setBrush( brush );
QTransform transform;
painter.translate( x + width * 0.5, y + height * 0.5 );
painter.scale( width * 0.8, height * 0.8 );
static const QPointF points[5] = {
QPointF( 0.0, -1.0 ),
QPointF( 1.0, -0.2 ),
QPointF( 0.6, 1.0 ),
QPointF( -0.6, 1.0 ),
QPointF( -1.0, -0.2 ),
};
painter.drawConvexPolygon( points, 5 );
painter.resetTransform();
painter.setPen( origPen );
painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );
}
void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {
painter.save();
painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );
if( count > 1 ) {
int nameWidth = QFontMetrics( painter.font() ).width( name + " " );
QString countString = QString( "x%1" ).arg( count );
QFont font = painter.font();
font.setBold( true );
painter.setFont( font );
painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );
}
painter.restore();
}
public:
OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )
: mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )
{
mRowFont.setPointSize( titleFontSize );
mTitleFont.setPointSize( rowFontSize );
mTitleFont.setUnderline( true );
mTitleFont.setBold( true );
}
int Width() const {
return mWidth;
}
int Height() const {
return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items
mHistory.count() * RowHeight() + // Height per item
TitleHeight() + RowSpacing() + // Title
Padding() * 2; // Overall padding
}
void Paint( QPainter& painter, int x, int y ) const {
painter.save();
QRect rect( x, y, Width(), Height() );
painter.setClipRect( rect );
// BG
QPen pen = QPen( QColor( 160, 160, 160 ) );
pen.setWidth( 3 );
painter.setPen( pen );
painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );
painter.drawRoundedRect( rect, 10, 10 );
// Title
y += Padding();
painter.setPen( QPen( Qt::white) );
painter.setFont( mTitleFont );
painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );
y += TitleHeight() + RowSpacing();
// Lines
painter.setPen( QPen( Qt::white) );
painter.setFont( mRowFont );
for( const QVariantMap& it : mHistory ) {
int mx = x + Padding();
DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() );
int cx = mx + RowHeight() + 5;
DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() );
y += RowHeight();
y += RowSpacing();
}
painter.restore();
}
};
Overlay::Overlay( QWidget *parent )
: QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )
{
mUI->setupUi( this );
setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool );
setAttribute( Qt::WA_TranslucentBackground );
connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );
connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );
connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );
connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );
connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );
LoadCards();
hide();
#ifdef Q_OS_MAC
WId windowObject = this->winId();
objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);
objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") );
int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;
objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces );
#endif
}
Overlay::~Overlay() {
delete mUI;
}
void Overlay::CheckForHover() {
QPoint mouseLoc = mapFromGlobal( QCursor::pos() );
Player showPlayerHistory = PLAYER_UNKNOWN;
if( mPlayerDeckRect.contains( mouseLoc ) ) {
showPlayerHistory = PLAYER_SELF;
} else if( mOpponentDeckRect.contains( mouseLoc ) ) {
showPlayerHistory = PLAYER_OPPONENT;
}
if( mShowPlayerHistory != showPlayerHistory ) {
mShowPlayerHistory = showPlayerHistory;
update();
}
}
void Overlay::LoadCards() {
QFile file( ":/data/cards.json" );
bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );
assert( opened );
QByteArray jsonData = file.readAll();
QJsonParseError error;
QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();
assert( error.error == QJsonParseError::NoError );
mCardDB.clear();
for( QJsonValueRef jsonCardRef : jsonCards ) {
QJsonObject jsonCard = jsonCardRef.toObject();
mCardDB[ jsonCard["id"].toString() ] = jsonCard.toVariantMap();
}
}
void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {
int padding = 10;
QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );
rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window
wnd.Paint( painter, rect.x(), rect.y() );
}
void Overlay::paintEvent( QPaintEvent* ) {
QPainter painter( this );
painter.setRenderHint( QPainter::Antialiasing );
float rowFontSize = 9;
float titleFontSize = 9;
int spacing = 8;
int overlayWidth = 200;
if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > -1 ) {
OverlayHistoryWindow wnd( "Cards drawn", mPlayerHistory, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );
PaintHistoryInScreen( painter, wnd, mPlayerDeckRect.topRight() + QPoint( 20, 0 ) );
} else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > -1 ) {
OverlayHistoryWindow wnd( "Cards played by opponent", mOpponentHistory, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );
PaintHistoryInScreen( painter, wnd, mOpponentDeckRect.topRight() + QPoint( 20, 0 ) );
}
}
void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {
move( x, y );
setFixedSize( w, h );
int minWidth = h * 4 / 3;
mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );
mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );
update();
}
void Overlay::Update() {
if( Settings::Instance()->OverlayEnabled() ) {
show();
setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466)
} else {
hide();
}
update();
}
void Overlay::HandleGameStarted() {
mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );
Update();
}
void Overlay::HandleGameStopped() {
mCheckForHoverTimer.stop();
Update();
}
void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {
QMap< QString, QVariantMap > entries;
for( const CardHistoryItem& it : list ) {
const QString& cardId = it.cardId;
if( cardId.isEmpty() ) {
continue;
}
if( !mCardDB.contains( cardId ) ) {
DBG( "Card %s not found", qt2cstr( cardId ) );
continue;
}
if( mCardDB[ cardId ][ "type" ] == "hero" ) {
continue;
}
if( it.player != player ) {
continue;
}
QVariantMap& entry = entries[ cardId ];
entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1;
entry[ "mana" ] = mCardDB[ cardId ][ "mana" ];
entry[ "name" ] = mCardDB[ cardId ][ "name" ];
}
OverlayHistoryList* ref;
if( player == PLAYER_SELF ) {
ref = &mPlayerHistory;
} else {
ref = &mOpponentHistory;
}
*ref = entries.values();
qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {
if( a["mana"].toInt() == b["mana"].toInt() ) {
return a["name"].toString() < b["name"].toString();
} else {
return a["mana"].toInt() < b["mana"].toInt();
}
});
}
void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {
UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );
UpdateHistoryFor( PLAYER_SELF, cardsDrawn );
Update();
}
void Overlay::HandleOverlaySettingChanged( bool enabled ) {
UNUSED_ARG( enabled );
Update();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Buck Baskin
*
* 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 <quirkd/ui_manager.h>
namespace quirkd
{
UIManager::UIManager(ros::NodeHandle nh) : n_(nh)
{
// low_pub_ = n_.advertise<geometry_msgs::PolygonStamped>("/low_alert", 1);
// warn_pub_ = n_.advertise<geometry_msgs::PolygonStamped>("/warn_alert", 1);
// max_pub_ = n_.advertise<geometry_msgs::PolygonStamped>("/max_alert", 1);
line_pub_ = n_.advertise<visualization_msgs::Marker>("/quirkd/" + ros::this_node::getName() + "/max_line_alert", 1);
alert_sub_ = n_.subscribe("/quirkd/alert/notification", 1, &UIManager::alertCB, this);
alertArray_sub_ = n_.subscribe("/quirkd/alert_array/notification", 1, &UIManager::alertArrayCB, this);
ROS_INFO("Done with UIManager constructor");
}
void UIManager::alertCB(const quirkd::Alert &alert)
{
ROS_DEBUG("Alert CB");
if (alert.level < 10)
{
// publishPolygon(&low_pub_, alert.min_x, alert.max_x, alert.min_y, alert.max_y);
}
else if (alert.level > 100)
{
// publishPolygon(&max_pub_, alert.min_x, alert.max_x, alert.min_y, alert.max_y);
}
else
{
// publishPolygon(&warn_pub_, alert.min_x, alert.max_x, alert.min_y, alert.max_y);
}
}
void UIManager::alertArrayCB(const quirkd::AlertArray &msg)
{
ROS_DEBUG("Alert Array CB");
std::vector<geometry_msgs::Point> points;
for (size_t i = 0; i < msg.alerts.size(); i++)
{
quirkd::Alert alert = msg.alerts[i];
extendLineList(&points, &alert);
}
ROS_INFO("Alert Array publishLineList %d", (int)points.size());
publishLineList(&line_pub_, &points);
}
void UIManager::extendLineList(std::vector<geometry_msgs::Point> *points, quirkd::Alert *msg)
{
if (msg->max_x - msg->min_x < 0.1)
{
msg->max_x += 0.05;
msg->min_x -= 0.05;
}
if (msg->max_y - msg->min_y < 0.1)
{
msg->max_y += 0.05;
msg->min_y -= 0.05;
}
geometry_msgs::Point minmin;
minmin.x = msg->min_x;
minmin.y = msg->min_y;
geometry_msgs::Point minmax;
minmax.x = msg->min_x;
minmax.y = msg->max_y;
geometry_msgs::Point maxmax;
maxmax.x = msg->max_x;
maxmax.y = msg->max_y;
geometry_msgs::Point maxmin;
maxmin.x = msg->max_x;
maxmin.y = msg->min_y;
points->push_back(minmin);
points->push_back(minmax);
points->push_back(minmax);
points->push_back(maxmax);
points->push_back(maxmax);
points->push_back(maxmin);
points->push_back(maxmin);
points->push_back(minmin);
ROS_INFO("Publish lines %.2f %.2f %.2f %.2f", minmin.x, minmin.y, maxmax.x, maxmax.y);
}
void UIManager::publishLineList(ros::Publisher *pub, std::vector<geometry_msgs::Point> *points)
{
visualization_msgs::Marker marker;
marker.header.frame_id = "map";
marker.id = 1;
marker.action = visualization_msgs::Marker::MODIFY;
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.pose.position.x = 0.0;
marker.pose.position.y = 0.0;
marker.pose.position.z = 0.0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
marker.scale.x = 0.05;
// Chance color based on level
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 0.5;
marker.color.b = 0.0;
marker.frame_locked = false;
marker.points = *points;
pub->publish(marker);
}
void UIManager::publishPolygon(ros::Publisher *pub, float min_x, float max_x, float min_y, float max_y)
{
if (max_x - min_x < .1)
{
max_x += .05;
min_x -= .05;
}
if (max_y - min_y < .1)
{
max_y += .05;
min_y -= .05;
}
geometry_msgs::PolygonStamped ps;
ps.header.stamp = ros::Time::now();
ps.header.frame_id = "map";
geometry_msgs::Point32 p1;
p1.x = min_x;
p1.y = min_y;
p1.z = 0;
ps.polygon.points.push_back(p1);
geometry_msgs::Point32 p2;
p2.x = max_x;
p2.y = min_y;
p2.z = 0;
ps.polygon.points.push_back(p2);
geometry_msgs::Point32 p3;
p3.x = max_x;
p3.y = max_y;
p3.z = 0;
ps.polygon.points.push_back(p3);
geometry_msgs::Point32 p4;
p4.x = min_x;
p4.y = max_y;
p4.z = 0;
ps.polygon.points.push_back(p4);
ROS_INFO("Publish polygon %.2f %.2f %.2f %.2f", min_x, max_x, min_y, max_y);
// pub->publish(ps);
}
} // namespace quirkd
int main(int argc, char **argv)
{
ros::init(argc, argv, "UIManager");
ROS_INFO("Init in UIManager");
ros::NodeHandle nh;
quirkd::UIManager ui(nh);
ros::spin();
}
<commit_msg>Remove unused code from ui_manager<commit_after>/*
* Copyright 2017 Buck Baskin
*
* 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 <quirkd/ui_manager.h>
namespace quirkd
{
UIManager::UIManager(ros::NodeHandle nh) : n_(nh)
{
line_pub_ = n_.advertise<visualization_msgs::Marker>("/quirkd/" + ros::this_node::getName() + "/max_line_alert", 1);
alertArray_sub_ = n_.subscribe("/quirkd/alert_array/notification", 1, &UIManager::alertArrayCB, this);
ROS_INFO("Done with UIManager constructor");
}
void UIManager::alertArrayCB(const quirkd::AlertArray &msg)
{
ROS_DEBUG("Alert Array CB");
std::vector<geometry_msgs::Point> points;
for (size_t i = 0; i < msg.alerts.size(); i++)
{
quirkd::Alert alert = msg.alerts[i];
extendLineList(&points, &alert);
}
ROS_INFO("Alert Array publishLineList %d", (int)points.size());
publishLineList(&line_pub_, &points);
}
void UIManager::extendLineList(std::vector<geometry_msgs::Point> *points, quirkd::Alert *msg)
{
if (msg->max_x - msg->min_x < 0.1)
{
msg->max_x += 0.05;
msg->min_x -= 0.05;
}
if (msg->max_y - msg->min_y < 0.1)
{
msg->max_y += 0.05;
msg->min_y -= 0.05;
}
geometry_msgs::Point minmin;
minmin.x = msg->min_x;
minmin.y = msg->min_y;
geometry_msgs::Point minmax;
minmax.x = msg->min_x;
minmax.y = msg->max_y;
geometry_msgs::Point maxmax;
maxmax.x = msg->max_x;
maxmax.y = msg->max_y;
geometry_msgs::Point maxmin;
maxmin.x = msg->max_x;
maxmin.y = msg->min_y;
points->push_back(minmin);
points->push_back(minmax);
points->push_back(minmax);
points->push_back(maxmax);
points->push_back(maxmax);
points->push_back(maxmin);
points->push_back(maxmin);
points->push_back(minmin);
ROS_INFO("Publish lines %.2f %.2f %.2f %.2f", minmin.x, minmin.y, maxmax.x, maxmax.y);
}
void UIManager::publishLineList(ros::Publisher *pub, std::vector<geometry_msgs::Point> *points)
{
visualization_msgs::Marker marker;
marker.header.frame_id = "map";
marker.id = 1;
marker.action = visualization_msgs::Marker::MODIFY;
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.pose.position.x = 0.0;
marker.pose.position.y = 0.0;
marker.pose.position.z = 0.0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
marker.scale.x = 0.05;
// Chance color based on level
marker.color.a = 1.0;
marker.color.r = 1.0;
marker.color.g = 0.5;
marker.color.b = 0.0;
marker.frame_locked = false;
marker.points = *points;
pub->publish(marker);
}
} // namespace quirkd
int main(int argc, char **argv)
{
ros::init(argc, argv, "UIManager");
ROS_INFO("Init in UIManager");
ros::NodeHandle nh;
quirkd::UIManager ui(nh);
ros::spin();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010, Joshua Lackey
* 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 <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <string.h>
#include <pthread.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <complex>
#include "usrp_source.h"
extern int g_verbosity;
#ifdef _WIN32
inline double round(double x) { return floor(x + 0.5); }
#endif
usrp_source::usrp_source(float sample_rate, long int fpga_master_clock_freq) {
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_desired_sample_rate = sample_rate;
m_sample_rate = 0.0;
m_decimation = 0;
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
}
usrp_source::usrp_source(unsigned int decimation, long int fpga_master_clock_freq) {
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_sample_rate = 0.0;
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
m_decimation = decimation & ~1;
if(m_decimation < 4)
m_decimation = 4;
if(m_decimation > 256)
m_decimation = 256;
}
usrp_source::~usrp_source() {
stop();
delete m_cb;
rtlsdr_close(dev);
pthread_mutex_destroy(&m_u_mutex);
}
void usrp_source::stop() {
pthread_mutex_lock(&m_u_mutex);
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::start() {
pthread_mutex_lock(&m_u_mutex);
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::calculate_decimation() {
float decimation_f;
// decimation_f = (float)m_u_rx->fpga_master_clock_freq() / m_desired_sample_rate;
m_decimation = (unsigned int)round(decimation_f) & ~1;
if(m_decimation < 4)
m_decimation = 4;
if(m_decimation > 256)
m_decimation = 256;
}
float usrp_source::sample_rate() {
return m_sample_rate;
}
int usrp_source::tune(double freq) {
int r = 0;
pthread_mutex_lock(&m_u_mutex);
if (freq != m_center_freq) {
r = rtlsdr_set_center_freq(dev, (uint32_t)freq);
// fprintf(stderr, "Tuned to %i Hz.\n", (uint32_t)freq);
if (r < 0)
fprintf(stderr, "Tuning to %lu Hz failed!\n", (uint32_t)freq);
else
m_center_freq = freq;
}
pthread_mutex_unlock(&m_u_mutex);
return 1; //(r < 0) ? 0 : 1;
}
int usrp_source::set_freq_correction(int ppm) {
m_freq_corr = ppm;
return rtlsdr_set_freq_correction(dev, ppm);
}
bool usrp_source::set_antenna(int antenna) {
return 0;
}
bool usrp_source::set_gain(float gain) {
int r, g = gain * 10;
/* Enable manual gain */
r = rtlsdr_set_tuner_gain_mode(dev, 1);
if (r < 0)
fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
fprintf(stderr, "Setting gain: %.1f dB\n", gain/10);
r = rtlsdr_set_tuner_gain(dev, g);
return (r < 0) ? 0 : 1;
}
/*
* open() should be called before multiple threads access usrp_source.
*/
int usrp_source::open(unsigned int subdev) {
int i, r, device_count, count;
uint32_t dev_index = subdev;
uint32_t samp_rate = 270833;
m_sample_rate = 270833.002142;
device_count = rtlsdr_get_device_count();
if (!device_count) {
fprintf(stderr, "No supported devices found.\n");
exit(1);
}
fprintf(stderr, "Found %d device(s):\n", device_count);
for (i = 0; i < device_count; i++)
fprintf(stderr, " %d: %s\n", i, rtlsdr_get_device_name(i));
fprintf(stderr, "\n");
fprintf(stderr, "Using device %d: %s\n",
dev_index,
rtlsdr_get_device_name(dev_index));
r = rtlsdr_open(&dev, dev_index);
if (r < 0) {
fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
exit(1);
}
/* Set the sample rate */
r = rtlsdr_set_sample_rate(dev, samp_rate);
if (r < 0)
fprintf(stderr, "WARNING: Failed to set sample rate.\n");
/* Reset endpoint before we start reading from it (mandatory) */
r = rtlsdr_reset_buffer(dev);
if (r < 0)
fprintf(stderr, "WARNING: Failed to reset buffers.\n");
// r = rtlsdr_set_offset_tuning(dev, 1);
// if (r < 0)
// fprintf(stderr, "WARNING: Failed to enable offset tuning\n");
return 0;
}
#define USB_PACKET_SIZE (2 * 16384)
#define FLUSH_SIZE 512
int usrp_source::fill(unsigned int num_samples, unsigned int *overrun_i) {
unsigned char ubuf[USB_PACKET_SIZE];
unsigned int i, j, space, overruns = 0;
complex *c;
int n_read;
while((m_cb->data_available() < num_samples) && (m_cb->space_available() > 0)) {
// read one usb packet from the usrp
pthread_mutex_lock(&m_u_mutex);
if (rtlsdr_read_sync(dev, ubuf, sizeof(ubuf), &n_read) < 0) {
pthread_mutex_unlock(&m_u_mutex);
fprintf(stderr, "error: usrp_standard_rx::read\n");
return -1;
}
pthread_mutex_unlock(&m_u_mutex);
// write complex<short> input to complex<float> output
c = (complex *)m_cb->poke(&space);
// set space to number of complex items to copy
space = n_read / 2;
// write data
for(i = 0, j = 0; i < space; i += 1, j += 2)
c[i] = complex((ubuf[j] - 127) * 256, (ubuf[j + 1] - 127) * 256);
// update cb
m_cb->wrote(i);
}
// if the cb is full, we left behind data from the usb packet
if(m_cb->space_available() == 0) {
fprintf(stderr, "warning: local overrun\n");
overruns++;
}
if(overrun_i)
*overrun_i = overruns;
return 0;
}
int usrp_source::read(complex *buf, unsigned int num_samples,
unsigned int *samples_read) {
unsigned int n;
if(fill(num_samples, 0))
return -1;
n = m_cb->read(buf, num_samples);
if(samples_read)
*samples_read = n;
return 0;
}
/*
* Don't hold a lock on this and use the usrp at the same time.
*/
circular_buffer *usrp_source::get_buffer() {
return m_cb;
}
int usrp_source::flush(unsigned int flush_count) {
m_cb->flush();
fill(flush_count * FLUSH_SIZE, 0);
m_cb->flush();
return 0;
}
<commit_msg>fix warning due to incorrect format string<commit_after>/*
* Copyright (c) 2010, Joshua Lackey
* 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 <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <string.h>
#include <pthread.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <complex>
#include "usrp_source.h"
extern int g_verbosity;
#ifdef _WIN32
inline double round(double x) { return floor(x + 0.5); }
#endif
usrp_source::usrp_source(float sample_rate, long int fpga_master_clock_freq) {
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_desired_sample_rate = sample_rate;
m_sample_rate = 0.0;
m_decimation = 0;
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
}
usrp_source::usrp_source(unsigned int decimation, long int fpga_master_clock_freq) {
m_fpga_master_clock_freq = fpga_master_clock_freq;
m_sample_rate = 0.0;
m_cb = new circular_buffer(CB_LEN, sizeof(complex), 0);
pthread_mutex_init(&m_u_mutex, 0);
m_decimation = decimation & ~1;
if(m_decimation < 4)
m_decimation = 4;
if(m_decimation > 256)
m_decimation = 256;
}
usrp_source::~usrp_source() {
stop();
delete m_cb;
rtlsdr_close(dev);
pthread_mutex_destroy(&m_u_mutex);
}
void usrp_source::stop() {
pthread_mutex_lock(&m_u_mutex);
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::start() {
pthread_mutex_lock(&m_u_mutex);
pthread_mutex_unlock(&m_u_mutex);
}
void usrp_source::calculate_decimation() {
float decimation_f;
// decimation_f = (float)m_u_rx->fpga_master_clock_freq() / m_desired_sample_rate;
m_decimation = (unsigned int)round(decimation_f) & ~1;
if(m_decimation < 4)
m_decimation = 4;
if(m_decimation > 256)
m_decimation = 256;
}
float usrp_source::sample_rate() {
return m_sample_rate;
}
int usrp_source::tune(double freq) {
int r = 0;
pthread_mutex_lock(&m_u_mutex);
if (freq != m_center_freq) {
r = rtlsdr_set_center_freq(dev, (uint32_t)freq);
if (r < 0)
fprintf(stderr, "Tuning to %u Hz failed!\n", (uint32_t)freq);
else
m_center_freq = freq;
}
pthread_mutex_unlock(&m_u_mutex);
return 1; //(r < 0) ? 0 : 1;
}
int usrp_source::set_freq_correction(int ppm) {
m_freq_corr = ppm;
return rtlsdr_set_freq_correction(dev, ppm);
}
bool usrp_source::set_antenna(int antenna) {
return 0;
}
bool usrp_source::set_gain(float gain) {
int r, g = gain * 10;
/* Enable manual gain */
r = rtlsdr_set_tuner_gain_mode(dev, 1);
if (r < 0)
fprintf(stderr, "WARNING: Failed to enable manual gain.\n");
fprintf(stderr, "Setting gain: %.1f dB\n", gain/10);
r = rtlsdr_set_tuner_gain(dev, g);
return (r < 0) ? 0 : 1;
}
/*
* open() should be called before multiple threads access usrp_source.
*/
int usrp_source::open(unsigned int subdev) {
int i, r, device_count, count;
uint32_t dev_index = subdev;
uint32_t samp_rate = 270833;
m_sample_rate = 270833.002142;
device_count = rtlsdr_get_device_count();
if (!device_count) {
fprintf(stderr, "No supported devices found.\n");
exit(1);
}
fprintf(stderr, "Found %d device(s):\n", device_count);
for (i = 0; i < device_count; i++)
fprintf(stderr, " %d: %s\n", i, rtlsdr_get_device_name(i));
fprintf(stderr, "\n");
fprintf(stderr, "Using device %d: %s\n",
dev_index,
rtlsdr_get_device_name(dev_index));
r = rtlsdr_open(&dev, dev_index);
if (r < 0) {
fprintf(stderr, "Failed to open rtlsdr device #%d.\n", dev_index);
exit(1);
}
/* Set the sample rate */
r = rtlsdr_set_sample_rate(dev, samp_rate);
if (r < 0)
fprintf(stderr, "WARNING: Failed to set sample rate.\n");
/* Reset endpoint before we start reading from it (mandatory) */
r = rtlsdr_reset_buffer(dev);
if (r < 0)
fprintf(stderr, "WARNING: Failed to reset buffers.\n");
// r = rtlsdr_set_offset_tuning(dev, 1);
// if (r < 0)
// fprintf(stderr, "WARNING: Failed to enable offset tuning\n");
return 0;
}
#define USB_PACKET_SIZE (2 * 16384)
#define FLUSH_SIZE 512
int usrp_source::fill(unsigned int num_samples, unsigned int *overrun_i) {
unsigned char ubuf[USB_PACKET_SIZE];
unsigned int i, j, space, overruns = 0;
complex *c;
int n_read;
while((m_cb->data_available() < num_samples) && (m_cb->space_available() > 0)) {
// read one usb packet from the usrp
pthread_mutex_lock(&m_u_mutex);
if (rtlsdr_read_sync(dev, ubuf, sizeof(ubuf), &n_read) < 0) {
pthread_mutex_unlock(&m_u_mutex);
fprintf(stderr, "error: usrp_standard_rx::read\n");
return -1;
}
pthread_mutex_unlock(&m_u_mutex);
// write complex<short> input to complex<float> output
c = (complex *)m_cb->poke(&space);
// set space to number of complex items to copy
space = n_read / 2;
// write data
for(i = 0, j = 0; i < space; i += 1, j += 2)
c[i] = complex((ubuf[j] - 127) * 256, (ubuf[j + 1] - 127) * 256);
// update cb
m_cb->wrote(i);
}
// if the cb is full, we left behind data from the usb packet
if(m_cb->space_available() == 0) {
fprintf(stderr, "warning: local overrun\n");
overruns++;
}
if(overrun_i)
*overrun_i = overruns;
return 0;
}
int usrp_source::read(complex *buf, unsigned int num_samples,
unsigned int *samples_read) {
unsigned int n;
if(fill(num_samples, 0))
return -1;
n = m_cb->read(buf, num_samples);
if(samples_read)
*samples_read = n;
return 0;
}
/*
* Don't hold a lock on this and use the usrp at the same time.
*/
circular_buffer *usrp_source::get_buffer() {
return m_cb;
}
int usrp_source::flush(unsigned int flush_count) {
m_cb->flush();
fill(flush_count * FLUSH_SIZE, 0);
m_cb->flush();
return 0;
}
<|endoftext|> |
<commit_before>/*!
* \brief Contains a bunch of utility functions which may or may not be actually used anywhere
*
* \author David
* \date 18-May-16.
*/
#ifndef RENDERER_UTILS_H
#define RENDERER_UTILS_H
#include <algorithm>
#include <exception>
#include <optional>
#include <string>
#include <vector>
#include <fstream>
#include "filesystem.hpp"
namespace nova {
template <int Num>
struct placeholder;
/*!
* \brief Calls the function once for every element in the provided container
*
* \param container The container to perform an action for each element in
* \param thing_to_do The action to perform for each element in the collection
*/
template <typename Cont, typename Func>
void foreach(Cont container, Func thing_to_do) {
std::for_each(std::cbegin(container), std::cend(container), thing_to_do);
}
std::vector<std::string> split(const std::string &s, char delim);
std::string join(const std::vector<std::string> &strings, const std::string &joiner);
std::string print_color(unsigned int color);
std::string print_array(int *data, int size);
bool ends_with(const std::string &string, const std::string &ending);
void write_to_file(const std::string &data, const fs::path &filepath);
void write_to_file(const std::vector<uint32_t> &data, const fs::path &filepath);
class nova_exception : public std::exception {
private:
std::string msg;
std::string generate_msg(const std::string &msg, const std::optional<std::exception> &exception);
public:
nova_exception();
explicit nova_exception(const std::string &msg);
explicit nova_exception(const std::exception &cause);
nova_exception(const std::string &msg, const std::exception &cause);
[[nodiscard]] const char *what() const noexcept override;
};
#define NOVA_EXCEPTION(name) \
/* NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
class name : public ::nova::nova_exception { \
public: \
name(){}; \
explicit name(std::string msg) : ::nova::nova_exception(std::move(msg)){}; \
\
explicit name(const std::exception &cause) : ::nova::nova_exception(cause){}; \
name(const std::string &msg, const std::exception &cause) : ::nova::nova_exception(msg, cause){}; \
}
NOVA_EXCEPTION(out_of_gpu_memory);
} // namespace nova
#endif // RENDERER_UTILS_H<commit_msg>clang-tidy: performance-unnecessary-value-param again<commit_after>/*!
* \brief Contains a bunch of utility functions which may or may not be actually used anywhere
*
* \author David
* \date 18-May-16.
*/
#ifndef RENDERER_UTILS_H
#define RENDERER_UTILS_H
#include <algorithm>
#include <exception>
#include <optional>
#include <string>
#include <vector>
#include <fstream>
#include "filesystem.hpp"
namespace nova {
template <int Num>
struct placeholder;
/*!
* \brief Calls the function once for every element in the provided container
*
* \param container The container to perform an action for each element in
* \param thing_to_do The action to perform for each element in the collection
*/
template <typename Cont, typename Func>
void foreach(Cont container, Func thing_to_do) {
std::for_each(std::cbegin(container), std::cend(container), thing_to_do);
}
std::vector<std::string> split(const std::string &s, char delim);
std::string join(const std::vector<std::string> &strings, const std::string &joiner);
std::string print_color(unsigned int color);
std::string print_array(int *data, int size);
bool ends_with(const std::string &string, const std::string &ending);
void write_to_file(const std::string &data, const fs::path &filepath);
void write_to_file(const std::vector<uint32_t> &data, const fs::path &filepath);
class nova_exception : public std::exception {
private:
std::string msg;
std::string generate_msg(const std::string &msg, const std::optional<std::exception> &exception);
public:
nova_exception();
explicit nova_exception(const std::string &msg);
explicit nova_exception(const std::exception &cause);
nova_exception(const std::string &msg, const std::exception &cause);
[[nodiscard]] const char *what() const noexcept override;
};
#define NOVA_EXCEPTION(name) \
/* NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
class name : public ::nova::nova_exception { \
public: \
name(){}; \
explicit name(const std::string& msg) : ::nova::nova_exception(msg){}; \
\
explicit name(const std::exception &cause) : ::nova::nova_exception(cause){}; \
name(const std::string &msg, const std::exception &cause) : ::nova::nova_exception(msg, cause){}; \
}
NOVA_EXCEPTION(out_of_gpu_memory);
} // namespace nova
#endif // RENDERER_UTILS_H<|endoftext|> |
<commit_before>/*!
* \brief Contains a bunch of utility functions which may or may not be actually used anywhere
*
* \author David
* \date 18-May-16.
*/
#ifndef RENDERER_UTILS_H
#define RENDERER_UTILS_H
#include <algorithm>
#include <exception>
#include <optional>
#include <string>
#include <vector>
#include <fstream>
#include "filesystem.hpp"
namespace nova {
template <int Num>
struct placeholder;
/*!
* \brief Calls the function once for every element in the provided container
*
* \param container The container to perform an action for each element in
* \param thing_to_do The action to perform for each element in the collection
*/
template <typename Cont, typename Func>
void foreach(Cont container, Func thing_to_do) {
std::for_each(std::cbegin(container), std::cend(container), thing_to_do);
}
std::vector<std::string> split(const std::string &s, char delim);
std::string join(const std::vector<std::string> &strings, const std::string &joiner);
std::string print_color(unsigned int color);
std::string print_array(int *data, int size);
bool ends_with(const std::string &string, const std::string &ending);
void write_to_file(const std::string &data, const fs::path &filepath);
void write_to_file(const std::vector<uint32_t> &data, const fs::path &filepath);
class nova_exception : public std::exception {
private:
std::string msg;
std::string generate_msg(const std::string &msg, const std::optional<std::exception> &exception);
public:
nova_exception();
explicit nova_exception(const std::string &msg);
explicit nova_exception(const std::exception &cause);
nova_exception(const std::string &msg, const std::exception &cause);
[[nodiscard]] const char *what() const noexcept override;
};
#define NOVA_EXCEPTION(name) \
/* NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
class name : public ::nova::nova_exception { \
public: \
name(){}; \
explicit name(std::string msg) : ::nova::nova_exception(std::move(msg)){}; \
\
explicit name(const std::exception &cause) : ::nova::nova_exception(cause){}; \
name(const std::string& msg, const std::exception &cause) : ::nova::nova_exception(msg, cause){}; \
}
NOVA_EXCEPTION(out_of_gpu_memory);
} // namespace nova
#endif // RENDERER_UTILS_H<commit_msg>reformat<commit_after>/*!
* \brief Contains a bunch of utility functions which may or may not be actually used anywhere
*
* \author David
* \date 18-May-16.
*/
#ifndef RENDERER_UTILS_H
#define RENDERER_UTILS_H
#include <algorithm>
#include <exception>
#include <optional>
#include <string>
#include <vector>
#include <fstream>
#include "filesystem.hpp"
namespace nova {
template <int Num>
struct placeholder;
/*!
* \brief Calls the function once for every element in the provided container
*
* \param container The container to perform an action for each element in
* \param thing_to_do The action to perform for each element in the collection
*/
template <typename Cont, typename Func>
void foreach(Cont container, Func thing_to_do) {
std::for_each(std::cbegin(container), std::cend(container), thing_to_do);
}
std::vector<std::string> split(const std::string &s, char delim);
std::string join(const std::vector<std::string> &strings, const std::string &joiner);
std::string print_color(unsigned int color);
std::string print_array(int *data, int size);
bool ends_with(const std::string &string, const std::string &ending);
void write_to_file(const std::string &data, const fs::path &filepath);
void write_to_file(const std::vector<uint32_t> &data, const fs::path &filepath);
class nova_exception : public std::exception {
private:
std::string msg;
std::string generate_msg(const std::string &msg, const std::optional<std::exception> &exception);
public:
nova_exception();
explicit nova_exception(const std::string &msg);
explicit nova_exception(const std::exception &cause);
nova_exception(const std::string &msg, const std::exception &cause);
[[nodiscard]] const char *what() const noexcept override;
};
#define NOVA_EXCEPTION(name) \
/* NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
class name : public ::nova::nova_exception { \
public: \
name(){}; \
explicit name(std::string msg) : ::nova::nova_exception(std::move(msg)){}; \
\
explicit name(const std::exception &cause) : ::nova::nova_exception(cause){}; \
name(const std::string &msg, const std::exception &cause) : ::nova::nova_exception(msg, cause){}; \
}
NOVA_EXCEPTION(out_of_gpu_memory);
} // namespace nova
#endif // RENDERER_UTILS_H<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
//#include "goto-def.h"
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
// Please do not commit with any of these defines on - AB 2015-01-12
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_DATAFLOW
//#define WINO_PARALLEL_TMPS
//#define PFGEMM_WINO_SEQ 32
//#define CLASSIC_SEQ
//#define WINO_SEQ
#define DEBUG 1
#undef NDEBUG
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular-balanced.h>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "tests/test-utils.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
//#ifdef __FFLASFFPACK_USE_DATAFLOW
template<class Element>
void Initialize(Element * C, size_t BS, size_t m, size_t n)
{
//#pragma omp parallel for collapse(2) schedule(runtime)
BS=std::max(BS, (size_t)__FFLASFFPACK_WINOTHRESHOLD_BAL );
PAR_BLOCK{
for(size_t p=0; p<m; p+=BS) ///row
for(size_t pp=0; pp<n; pp+=BS) //column
{
size_t M=BS, MM=BS;
if(!(p+BS<m))
M=m-p;
if(!(pp+BS<n))
MM=n-pp;
//#pragma omp task
TASK(MODE(),
{
for(size_t j=0; j<M; j++)
for(size_t jj=0; jj<MM; jj++)
C[(p+j)*n+pp+jj]=0;
});
}
// #pragma omp taskwait
CHECK_DEPENDENCIES
}
// printf("A = \n");
// for (size_t i=0; i<m; i+=128)
// {
// for (size_t j=0; j<n; j+=128)
// {
// int ld = komp_get_locality_domain_num_for( &C[i*n+j] );
// printf("%i ", ld);
// }
// printf("\n");
// }
}
// #else
// template<class Element>
// void Initialize(Element * C, size_t BS, size_t m, size_t n)
// {}
// #endif
int main(int argc, char** argv) {
size_t iter = 3 ;
long int q = 131071 ;
size_t m = 2000 ;
size_t k = 2000 ;
size_t n = 2000 ;
int nbw = -1 ;
int p=3;
int t=MAX_THREADS;
int NBK = -1;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'k', "-k K", "Set the col dimension of A.", TYPE_INT , &k },
{ 'n', "-n N", "Set the col dimension of B.", TYPE_INT , &n },
{ 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rc in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (NBK==-1) NBK = t;
// typedef Givaro::ModularBalanced<double> Field;
typedef Givaro::ModularBalanced<int64_t> Field;
// typedef Givaro::ModularBalanced<float> Field;
typedef Field::Element Element;
Field F(q);
FFLAS::Timer chrono, freivalds;
double time=0.0, timev=0.0;
Element * A, * B, * C;
Field::RandIter G(F);
A = FFLAS::fflas_new(F,m,k,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(A,m/size_t(NBK),m,k);
FFLAS::ParSeqHelper::Parallel H;
size_t i;
//#pragma omp for
PARFOR1D (i,0, m,H,
for (size_t j=0; j<(size_t)k; ++j)
G.random (*(A+i*k+j));
);
B = FFLAS::fflas_new(F,k,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(B,k/NBK,k,n);
//#pragma omp parallel for
PARFOR1D (i, 0, k,H,
for (size_t j=0; j<(size_t)n; ++j)
G.random(*(B+i*n+j));
);
C = FFLAS::fflas_new(F,m,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(C,m/NBK,m,n);
for (i=0;i<=iter;++i){
// if (argc > 4){
// A = read_field (F, argv[4], &n, &n);
// }
// else{
chrono.clear();
if (p && p!=7){
FFLAS::CuttingStrategy meth;
switch (p){
case 1: meth = FFLAS::BLOCK_THREADS;break;
case 2: meth = FFLAS::TWO_D;break;
case 3: meth = FFLAS::TWO_D_ADAPT;break;
case 4: meth = FFLAS::THREE_D_INPLACE;break;
case 5: meth = FFLAS::THREE_D;break;
case 6: meth = FFLAS::THREE_D_ADAPT;break;
default: meth = FFLAS::BLOCK_THREADS;break;
}
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd,
typename FFLAS::ModeTraits<Field>::value,
FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Parallel(t, meth));
if (i) chrono.start();
PAR_BLOCK{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}else{
if(p==7){
FFLAS::MMHelper<Field, FFLAS::MMHelperAlgo::WinogradPar>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
// cout<<"wino parallel"<<endl;
if (i) chrono.start();
PAR_BLOCK
{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}
else{
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd>//,
//typename FFLAS::FieldTraits<Field>::value,
//FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
if (i) chrono.start();
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
if (i) {chrono.stop(); time+=chrono.realtime();}
}
}
freivalds.clear();
freivalds.start();
bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n);
freivalds.stop();
timev+=freivalds.usertime();
if (!pass)
std::cout<<"FAILED"<<std::endl;
//std::cout << *A << ' ' << *B << ' ' << *C << ' '<< pass << std::endl;
}
FFLAS::fflas_delete( A);
FFLAS::fflas_delete( B);
FFLAS::fflas_delete( C);
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cout << "Time: " << time / double(iter)
<< " Gflops: " << (2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cout, as) << std::endl;
#if DEBUG
std::cout<<"Freivalds vtime: "<<timev/(double)iter<<std::endl;
#endif
return 0;
}
<commit_msg>small fix <commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
//#include "goto-def.h"
/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
// Please do not commit with any of these defines on - AB 2015-01-12
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_DATAFLOW
//#define WINO_PARALLEL_TMPS
//#define PFGEMM_WINO_SEQ 32
//#define CLASSIC_SEQ
//#define WINO_SEQ
#define DEBUG 1
#undef NDEBUG
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular-balanced.h>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "tests/test-utils.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
//#ifdef __FFLASFFPACK_USE_DATAFLOW
template<class Element>
void Initialize(Element * C, size_t BS, size_t m, size_t n)
{
//#pragma omp parallel for collapse(2) schedule(runtime)
BS=std::max(BS, (size_t)__FFLASFFPACK_WINOTHRESHOLD_BAL );
PAR_BLOCK{
for(size_t p=0; p<m; p+=BS) ///row
for(size_t pp=0; pp<n; pp+=BS) //column
{
size_t M=BS, MM=BS;
if(!(p+BS<m))
M=m-p;
if(!(pp+BS<n))
MM=n-pp;
//#pragma omp task
TASK(MODE(),
{
for(size_t j=0; j<M; j++)
for(size_t jj=0; jj<MM; jj++)
C[(p+j)*n+pp+jj]=0;
});
}
// #pragma omp taskwait
CHECK_DEPENDENCIES
}
// printf("A = \n");
// for (size_t i=0; i<m; i+=128)
// {
// for (size_t j=0; j<n; j+=128)
// {
// int ld = komp_get_locality_domain_num_for( &C[i*n+j] );
// printf("%i ", ld);
// }
// printf("\n");
// }
}
// #else
// template<class Element>
// void Initialize(Element * C, size_t BS, size_t m, size_t n)
// {}
// #endif
int main(int argc, char** argv) {
size_t iter = 3 ;
int64_t q = 131071 ;
size_t m = 2000 ;
size_t k = 2000 ;
size_t n = 2000 ;
int nbw = -1 ;
int p=3;
int t=MAX_THREADS;
int NBK = -1;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'k', "-k K", "Set the col dimension of A.", TYPE_INT , &k },
{ 'n', "-n N", "Set the col dimension of B.", TYPE_INT , &n },
{ 'w', "-w N", "Set the number of winograd levels (-1 for random).", TYPE_INT , &nbw },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'p', "-p P", "0 for sequential, 1 for 2D iterative, 2 for 2D rec, 3 for 2D rec adaptive, 4 for 3D rc in-place, 5 for 3D rec, 6 for 3D rec adaptive.", TYPE_INT , &p },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (NBK==-1) NBK = t;
typedef Givaro::ModularBalanced<double> Field;
// typedef Givaro::ModularBalanced<int64_t> Field;
// typedef Givaro::ModularBalanced<float> Field;
typedef Field::Element Element;
Field F(q);
FFLAS::Timer chrono, freivalds;
double time=0.0, timev=0.0;
Element * A, * B, * C;
Field::RandIter G(F);
A = FFLAS::fflas_new(F,m,k,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(A,m/size_t(NBK),m,k);
FFLAS::ParSeqHelper::Parallel H;
size_t i;
//#pragma omp for
PARFOR1D (i,0, m,H,
for (size_t j=0; j<(size_t)k; ++j)
G.random (*(A+i*k+j));
);
B = FFLAS::fflas_new(F,k,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(B,k/NBK,k,n);
//#pragma omp parallel for
PARFOR1D (i, 0, k,H,
for (size_t j=0; j<(size_t)n; ++j)
G.random(*(B+i*n+j));
);
C = FFLAS::fflas_new(F,m,n,Alignment::CACHE_PAGESIZE);
//#pragma omp parallel for collapse(2) schedule(runtime)
Initialize(C,m/NBK,m,n);
for (i=0;i<=iter;++i){
// if (argc > 4){
// A = read_field (F, argv[4], &n, &n);
// }
// else{
chrono.clear();
if (p && p!=7){
FFLAS::CuttingStrategy meth;
switch (p){
case 1: meth = FFLAS::BLOCK_THREADS;break;
case 2: meth = FFLAS::TWO_D;break;
case 3: meth = FFLAS::TWO_D_ADAPT;break;
case 4: meth = FFLAS::THREE_D_INPLACE;break;
case 5: meth = FFLAS::THREE_D;break;
case 6: meth = FFLAS::THREE_D_ADAPT;break;
default: meth = FFLAS::BLOCK_THREADS;break;
}
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd,
typename FFLAS::ModeTraits<Field>::value,
FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Parallel(t, meth));
if (i) chrono.start();
PAR_BLOCK{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}else{
if(p==7){
FFLAS::MMHelper<Field, FFLAS::MMHelperAlgo::WinogradPar>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
// cout<<"wino parallel"<<endl;
if (i) chrono.start();
PAR_BLOCK
{
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
}
if (i) {chrono.stop(); time+=chrono.realtime();}
}
else{
FFLAS::MMHelper<Field,FFLAS::MMHelperAlgo::Winograd>//,
//typename FFLAS::FieldTraits<Field>::value,
//FFLAS::ParSeqHelper::Parallel>
WH (F, nbw, FFLAS::ParSeqHelper::Sequential());
if (i) chrono.start();
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, F.zero, C,n,WH);
if (i) {chrono.stop(); time+=chrono.realtime();}
}
}
freivalds.clear();
freivalds.start();
bool pass = FFLAS::freivalds(F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,k, F.one, A, k, B, n, C,n);
freivalds.stop();
timev+=freivalds.usertime();
if (!pass)
std::cout<<"FAILED"<<std::endl;
}
FFLAS::fflas_delete( A);
FFLAS::fflas_delete( B);
FFLAS::fflas_delete( C);
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cout << "Time: " << time / double(iter)
<< " Gflops: " << (2.*double(m)/1000.*double(n)/1000.*double(k)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cout, as) << std::endl;
#if DEBUG
std::cout<<"Freivalds vtime: "<<timev/(double)iter<<std::endl;
#endif
return 0;
}
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <memseries.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
int main(int argc, char *argv[]) {
auto ms = new memseries::storage::MemoryStorage{ 2000000 };
auto m = memseries::Meas::empty();
std::vector<memseries::Time> deltas{ 50,255,1024,2050 };
auto now=std::chrono::system_clock::now();
memseries::Time t =memseries::timeutil::from_chrono(now);
const size_t ids_count = 2;
auto start = clock();
const size_t K = 2;
for (size_t i = 0; i < K*1000000; i++) {
m.id = i%ids_count;
m.flag = 0xff;
t += deltas[i%deltas.size()];
m.time = t;
m.value = i;
ms->append(m);
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"memorystorage insert : "<<elapsed<<std::endl;
start = clock();
auto reader = ms->readInTimePoint(ms->maxTime());
memseries::Meas::MeasList mlist{};
reader->readAll(&mlist);
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "memorystorage readTimePoint last: " << elapsed / K << std::endl;
std::cout << "raded: " << mlist.size() << std::endl;
start = clock();
auto reader_int = ms->readInterval(memseries::timeutil::from_chrono(now), t);
mlist.clear();
reader_int->readAll(&mlist);
elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"memorystorage readIntarval all: "<<elapsed/K<<std::endl;
std::cout<<"raded: "<<mlist.size()<<std::endl;
delete ms;
}
<commit_msg>elapsed time calc.<commit_after>#include <ctime>
#include <iostream>
#include <cstdlib>
#include <iterator>
#include <memseries.h>
#include <ctime>
#include <limits>
#include <cmath>
#include <chrono>
int main(int argc, char *argv[]) {
auto ms = new memseries::storage::MemoryStorage{ 2000000 };
auto m = memseries::Meas::empty();
std::vector<memseries::Time> deltas{ 50,255,1024,2050 };
auto now=std::chrono::system_clock::now();
memseries::Time t =memseries::timeutil::from_chrono(now);
const size_t ids_count = 2;
auto start = clock();
const size_t K = 2;
for (size_t i = 0; i < K*1000000; i++) {
m.id = i%ids_count;
m.flag = 0xff;
t += deltas[i%deltas.size()];
m.time = t;
m.value = i;
ms->append(m);
}
auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"memorystorage insert : "<<elapsed<<std::endl;
start = clock();
auto reader = ms->readInTimePoint(ms->maxTime());
memseries::Meas::MeasList mlist{};
reader->readAll(&mlist);
elapsed = ((float)clock() - start) / CLOCKS_PER_SEC;
std::cout << "memorystorage readTimePoint last: " << elapsed << std::endl;
std::cout << "raded: " << mlist.size() << std::endl;
start = clock();
auto reader_int = ms->readInterval(memseries::timeutil::from_chrono(now), t);
mlist.clear();
reader_int->readAll(&mlist);
elapsed=((float)clock()-start)/ CLOCKS_PER_SEC;
std::cout<<"memorystorage readIntarval all: "<<elapsed<<std::endl;
std::cout<<"raded: "<<mlist.size()<<std::endl;
delete ms;
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** H26x_V4l2DeviceSource.cpp
**
** H264/H265 V4L2 Live555 source
**
** -------------------------------------------------------------------------*/
#include <sstream>
// live555
#include <Base64.hh>
// project
#include "logger.h"
#include "H26x_V4l2DeviceSource.h"
// extract a frame
unsigned char* H26X_V4L2DeviceSource::extractFrame(unsigned char* frame, size_t& size, size_t& outsize, int& frameType)
{
unsigned char * outFrame = NULL;
outsize = 0;
unsigned int markerlength = 0;
frameType = 0;
unsigned char *startFrame = (unsigned char*)memmem(frame,size,H264marker,sizeof(H264marker));
if (startFrame != NULL) {
markerlength = sizeof(H264marker);
} else {
startFrame = (unsigned char*)memmem(frame,size,H264shortmarker,sizeof(H264shortmarker));
if (startFrame != NULL) {
markerlength = sizeof(H264shortmarker);
}
}
if (startFrame != NULL) {
frameType = startFrame[markerlength];
int remainingSize = size-(startFrame-frame+markerlength);
unsigned char *endFrame = (unsigned char*)memmem(&startFrame[markerlength], remainingSize, H264marker, sizeof(H264marker));
if (endFrame == NULL) {
endFrame = (unsigned char*)memmem(&startFrame[markerlength], remainingSize, H264shortmarker, sizeof(H264shortmarker));
}
if (m_keepMarker)
{
size -= startFrame-frame;
outFrame = startFrame;
}
else
{
size -= startFrame-frame+markerlength;
outFrame = &startFrame[markerlength];
}
if (endFrame != NULL)
{
outsize = endFrame - outFrame;
}
else
{
outsize = size;
}
size -= outsize;
} else if (size>= sizeof(H264shortmarker)) {
LOG(INFO) << "No marker found";
}
return outFrame;
}
std::string H26X_V4L2DeviceSource::getFrameWithMarker(const std::string & frame) {
std::string frameWithMarker(H264marker);
frameWithMarker.append(frame);
return frameWithMarker;
}
<commit_msg>fix init frames<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** H26x_V4l2DeviceSource.cpp
**
** H264/H265 V4L2 Live555 source
**
** -------------------------------------------------------------------------*/
#include <sstream>
// live555
#include <Base64.hh>
// project
#include "logger.h"
#include "H26x_V4l2DeviceSource.h"
// extract a frame
unsigned char* H26X_V4L2DeviceSource::extractFrame(unsigned char* frame, size_t& size, size_t& outsize, int& frameType)
{
unsigned char * outFrame = NULL;
outsize = 0;
unsigned int markerlength = 0;
frameType = 0;
unsigned char *startFrame = (unsigned char*)memmem(frame,size,H264marker,sizeof(H264marker));
if (startFrame != NULL) {
markerlength = sizeof(H264marker);
} else {
startFrame = (unsigned char*)memmem(frame,size,H264shortmarker,sizeof(H264shortmarker));
if (startFrame != NULL) {
markerlength = sizeof(H264shortmarker);
}
}
if (startFrame != NULL) {
frameType = startFrame[markerlength];
int remainingSize = size-(startFrame-frame+markerlength);
unsigned char *endFrame = (unsigned char*)memmem(&startFrame[markerlength], remainingSize, H264marker, sizeof(H264marker));
if (endFrame == NULL) {
endFrame = (unsigned char*)memmem(&startFrame[markerlength], remainingSize, H264shortmarker, sizeof(H264shortmarker));
}
if (m_keepMarker)
{
size -= startFrame-frame;
outFrame = startFrame;
}
else
{
size -= startFrame-frame+markerlength;
outFrame = &startFrame[markerlength];
}
if (endFrame != NULL)
{
outsize = endFrame - outFrame;
}
else
{
outsize = size;
}
size -= outsize;
} else if (size>= sizeof(H264shortmarker)) {
LOG(INFO) << "No marker found";
}
return outFrame;
}
std::string H26X_V4L2DeviceSource::getFrameWithMarker(const std::string & frame) {
std::string frameWithMarker;
frameWithMarker.append(H264marker, sizeof(H264marker));
frameWithMarker.append(frame);
return frameWithMarker;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "tbb/spin_rw_mutex.h"
#include "tbb/concurrent_hash_map.h"
#include "boost/multi_index_container.hpp"
#include "boost/format.hpp"
#include "IECore/HashTable.h"
#include "IECore/InternedString.h"
namespace IECore
{
namespace Detail
{
typedef boost::multi_index::multi_index_container<
std::string,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::identity<std::string>,
Hash<std::string>
>
>
> HashSet;
typedef HashSet::nth_index<0>::type Index;
typedef HashSet::nth_index_const_iterator<0>::type ConstIterator;
typedef tbb::spin_rw_mutex Mutex;
static HashSet *hashSet()
{
static HashSet g_hashSet;
return &g_hashSet;
}
static Mutex *mutex()
{
static Detail::Mutex g_mutex;
return &g_mutex;
}
struct StringCStringEqual
{
bool operator()( const char *c, const std::string &s ) const
{
return strcmp( c, s.c_str() )==0;
}
bool operator()( const std::string &s, const char *c ) const
{
return strcmp( c, s.c_str() )==0;
}
};
} // namespace Detail
const std::string *InternedString::internedString( const char *value )
{
Detail::HashSet *hashSet = Detail::hashSet();
Detail::Index &hashIndex = hashSet->get<0>();
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet::const_iterator it = hashIndex.find( value, Hash<const char *>(), Detail::StringCStringEqual() );
if( it!=hashIndex.end() )
{
return &(*it);
}
else
{
lock.upgrade_to_writer();
return &(*(hashSet->insert( std::string( value ) ).first ) );
}
}
size_t InternedString::numUniqueStrings()
{
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet *hashSet = Detail::hashSet();
return hashSet->size();
}
static InternedString g_emptyString("");
const InternedString &InternedString::emptyString()
{
return g_emptyString;
}
// make sure we create the g_numbers map at load time.
static InternedString g_zero((int64_t)0);
const InternedString &InternedString::numberString( int64_t number )
{
typedef tbb::concurrent_hash_map< int64_t, InternedString > NumbersMap;
static NumbersMap *g_numbers = 0;
if ( !g_numbers )
{
g_numbers = new NumbersMap;
}
NumbersMap::accessor it;
if ( g_numbers->insert( it, number ) )
{
it->second = InternedString( ( boost::format("%d") % number ).str() );
}
return it->second;
}
std::ostream &operator << ( std::ostream &o, const InternedString &str )
{
o << str.c_str();
return o;
}
} // namespace IECore
<commit_msg>Improved speed of InternedString( int64_t ).<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "tbb/spin_rw_mutex.h"
#include "tbb/concurrent_hash_map.h"
#include "boost/multi_index_container.hpp"
#include "boost/lexical_cast.hpp"
#include "IECore/HashTable.h"
#include "IECore/InternedString.h"
namespace IECore
{
namespace Detail
{
typedef boost::multi_index::multi_index_container<
std::string,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::identity<std::string>,
Hash<std::string>
>
>
> HashSet;
typedef HashSet::nth_index<0>::type Index;
typedef HashSet::nth_index_const_iterator<0>::type ConstIterator;
typedef tbb::spin_rw_mutex Mutex;
static HashSet *hashSet()
{
static HashSet g_hashSet;
return &g_hashSet;
}
static Mutex *mutex()
{
static Detail::Mutex g_mutex;
return &g_mutex;
}
struct StringCStringEqual
{
bool operator()( const char *c, const std::string &s ) const
{
return strcmp( c, s.c_str() )==0;
}
bool operator()( const std::string &s, const char *c ) const
{
return strcmp( c, s.c_str() )==0;
}
};
} // namespace Detail
const std::string *InternedString::internedString( const char *value )
{
Detail::HashSet *hashSet = Detail::hashSet();
Detail::Index &hashIndex = hashSet->get<0>();
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet::const_iterator it = hashIndex.find( value, Hash<const char *>(), Detail::StringCStringEqual() );
if( it!=hashIndex.end() )
{
return &(*it);
}
else
{
lock.upgrade_to_writer();
return &(*(hashSet->insert( std::string( value ) ).first ) );
}
}
size_t InternedString::numUniqueStrings()
{
Detail::Mutex::scoped_lock lock( *Detail::mutex(), false ); // read-only lock
Detail::HashSet *hashSet = Detail::hashSet();
return hashSet->size();
}
static InternedString g_emptyString("");
const InternedString &InternedString::emptyString()
{
return g_emptyString;
}
// make sure we create the g_numbers map at load time.
static InternedString g_zero((int64_t)0);
const InternedString &InternedString::numberString( int64_t number )
{
typedef tbb::concurrent_hash_map< int64_t, InternedString > NumbersMap;
static NumbersMap *g_numbers = 0;
if ( !g_numbers )
{
g_numbers = new NumbersMap;
}
NumbersMap::accessor it;
if ( g_numbers->insert( it, number ) )
{
it->second = InternedString( boost::lexical_cast<std::string>( number ) );
}
return it->second;
}
std::ostream &operator << ( std::ostream &o, const InternedString &str )
{
o << str.c_str();
return o;
}
} // namespace IECore
<|endoftext|> |
<commit_before>// Numexpr - Fast numerical array expression evaluator for NumPy.
//
// License: MIT
// Author: See AUTHORS.txt
//
// See LICENSE.txt for details about copyright and rights to use.
//
// module.cpp contains the CPython-specific module exposure.
#define DO_NUMPY_IMPORT_ARRAY
#include "module.hpp"
#include <structmember.h>
#include <vector>
#include "interpreter.hpp"
#include "numexpr_object.hpp"
using namespace std;
// Global state. The file interpreter.hpp also has some global state
// in its 'th_params' variable
global_state gs;
/* Do the worker job for a certain thread */
void *th_worker(void *tidptr)
{
int tid = *(int *)tidptr;
/* Parameters for threads */
npy_intp start;
npy_intp vlen;
npy_intp block_size;
NpyIter *iter;
vm_params params;
int *pc_error;
int ret;
int n_inputs;
int n_constants;
int n_temps;
size_t memsize;
char **mem;
npy_intp *memsteps;
npy_intp istart, iend;
char **errmsg;
// For output buffering if needed
vector<char> out_buffer;
while (1) {
gs.init_sentinels_done = 0; /* sentinels have to be initialised yet */
/* Meeting point for all threads (wait for initialization) */
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads < gs.nthreads) {
gs.count_threads++;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Check if thread has been asked to return */
if (gs.end_threads) {
return(0);
}
/* Get parameters for this thread before entering the main loop */
start = th_params.start;
vlen = th_params.vlen;
block_size = th_params.block_size;
params = th_params.params;
pc_error = th_params.pc_error;
// If output buffering is needed, allocate it
if (th_params.need_output_buffering) {
out_buffer.resize(params.memsizes[0] * BLOCK_SIZE1);
params.out_buffer = &out_buffer[0];
} else {
params.out_buffer = NULL;
}
/* Populate private data for each thread */
n_inputs = params.n_inputs;
n_constants = params.n_constants;
n_temps = params.n_temps;
memsize = (1+n_inputs+n_constants+n_temps) * sizeof(char *);
/* XXX malloc seems thread safe for POSIX, but for Win? */
mem = (char **)malloc(memsize);
memcpy(mem, params.mem, memsize);
errmsg = th_params.errmsg;
params.mem = mem;
/* Loop over blocks */
pthread_mutex_lock(&gs.count_mutex);
if (!gs.init_sentinels_done) {
/* Set sentinels and other global variables */
gs.gindex = start;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
gs.init_sentinels_done = 1; /* sentinels have been initialised */
gs.giveup = 0; /* no giveup initially */
} else {
gs.gindex += block_size;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
}
/* Grab one of the iterators */
iter = th_params.iter[tid];
if (iter == NULL) {
th_params.ret_code = -1;
gs.giveup = 1;
}
memsteps = th_params.memsteps[tid];
/* Get temporary space for each thread */
ret = get_temps_space(params, mem, BLOCK_SIZE1);
if (ret < 0) {
/* Propagate error to main thread */
th_params.ret_code = ret;
gs.giveup = 1;
}
pthread_mutex_unlock(&gs.count_mutex);
while (istart < vlen && !gs.giveup) {
/* Reset the iterator to the range for this task */
ret = NpyIter_ResetToIterIndexRange(iter, istart, iend,
errmsg);
/* Execute the task */
if (ret >= 0) {
ret = vm_engine_iter_task(iter, memsteps, params, pc_error, errmsg);
}
if (ret < 0) {
pthread_mutex_lock(&gs.count_mutex);
gs.giveup = 1;
/* Propagate error to main thread */
th_params.ret_code = ret;
pthread_mutex_unlock(&gs.count_mutex);
break;
}
pthread_mutex_lock(&gs.count_mutex);
gs.gindex += block_size;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
pthread_mutex_unlock(&gs.count_mutex);
}
/* Meeting point for all threads (wait for finalization) */
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads > 0) {
gs.count_threads--;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Release resources */
free_temps_space(params, mem);
free(mem);
} /* closes while(1) */
/* This should never be reached, but anyway */
return(0);
}
/* Initialize threads */
int init_threads(void)
{
int tid, rc;
/* Initialize mutex and condition variable objects */
pthread_mutex_init(&gs.count_mutex, NULL);
/* Barrier initialization */
pthread_mutex_init(&gs.count_threads_mutex, NULL);
pthread_cond_init(&gs.count_threads_cv, NULL);
gs.count_threads = 0; /* Reset threads counter */
/* Finally, create the threads */
for (tid = 0; tid < gs.nthreads; tid++) {
gs.tids[tid] = tid;
rc = pthread_create(&gs.threads[tid], NULL, th_worker,
(void *)&gs.tids[tid]);
if (rc) {
fprintf(stderr,
"ERROR; return code from pthread_create() is %d\n", rc);
fprintf(stderr, "\tError detail: %s\n", strerror(rc));
exit(-1);
}
}
gs.init_threads_done = 1; /* Initialization done! */
gs.pid = (int)getpid(); /* save the PID for this process */
return(0);
}
/* Set the number of threads in numexpr's VM */
int numexpr_set_nthreads(int nthreads_new)
{
int nthreads_old = gs.nthreads;
int t, rc;
void *status;
if (nthreads_new > MAX_THREADS) {
fprintf(stderr,
"Error. nthreads cannot be larger than MAX_THREADS (%d)",
MAX_THREADS);
return -1;
}
else if (nthreads_new <= 0) {
fprintf(stderr, "Error. nthreads must be a positive integer");
return -1;
}
/* Only join threads if they are not initialized or if our PID is
different from that in pid var (probably means that we are a
subprocess, and thus threads are non-existent). */
if (gs.nthreads > 1 && gs.init_threads_done && gs.pid == getpid()) {
/* Tell all existing threads to finish */
gs.end_threads = 1;
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads < gs.nthreads) {
gs.count_threads++;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Join exiting threads */
for (t=0; t<gs.nthreads; t++) {
rc = pthread_join(gs.threads[t], &status);
if (rc) {
fprintf(stderr,
"ERROR; return code from pthread_join() is %d\n",
rc);
fprintf(stderr, "\tError detail: %s\n", strerror(rc));
exit(-1);
}
}
gs.init_threads_done = 0;
gs.end_threads = 0;
}
/* Launch a new pool of threads (if necessary) */
gs.nthreads = nthreads_new;
if (gs.nthreads > 1 && (!gs.init_threads_done || gs.pid != getpid())) {
init_threads();
}
return nthreads_old;
}
#ifdef USE_VML
static PyObject *
_get_vml_version(PyObject *self, PyObject *args)
{
int len=198;
char buf[198];
MKL_Get_Version_String(buf, len);
return Py_BuildValue("s", buf);
}
static PyObject *
_set_vml_accuracy_mode(PyObject *self, PyObject *args)
{
int mode_in, mode_old;
if (!PyArg_ParseTuple(args, "i", &mode_in))
return NULL;
mode_old = vmlGetMode() & VML_ACCURACY_MASK;
vmlSetMode((mode_in & VML_ACCURACY_MASK) | VML_ERRMODE_IGNORE );
return Py_BuildValue("i", mode_old);
}
static PyObject *
_set_vml_num_threads(PyObject *self, PyObject *args)
{
int max_num_threads;
if (!PyArg_ParseTuple(args, "i", &max_num_threads))
return NULL;
mkl_domain_set_num_threads(max_num_threads, MKL_VML);
Py_RETURN_NONE;
}
#endif
static PyObject *
_set_num_threads(PyObject *self, PyObject *args)
{
int num_threads, nthreads_old;
if (!PyArg_ParseTuple(args, "i", &num_threads))
return NULL;
nthreads_old = numexpr_set_nthreads(num_threads);
return Py_BuildValue("i", nthreads_old);
}
static PyMethodDef module_methods[] = {
#ifdef USE_VML
{"_get_vml_version", _get_vml_version, METH_VARARGS,
"Get the VML/MKL library version."},
{"_set_vml_accuracy_mode", _set_vml_accuracy_mode, METH_VARARGS,
"Set accuracy mode for VML functions."},
{"_set_vml_num_threads", _set_vml_num_threads, METH_VARARGS,
"Suggests a maximum number of threads to be used in VML operations."},
#endif
{"_set_num_threads", _set_num_threads, METH_VARARGS,
"Suggests a maximum number of threads to be used in operations."},
{NULL}
};
static int
add_symbol(PyObject *d, const char *sname, int name, const char* routine_name)
{
PyObject *o, *s;
int r;
if (!sname) {
return 0;
}
o = PyLong_FromLong(name);
s = PyBytes_FromString(sname);
if (!s) {
PyErr_SetString(PyExc_RuntimeError, routine_name);
return -1;
}
r = PyDict_SetItem(d, s, o);
Py_XDECREF(o);
return r;
}
#ifdef __cplusplus
extern "C" {
#endif
#if PY_MAJOR_VERSION >= 3
/* XXX: handle the "global_state" state via moduedef */
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"interpreter",
NULL,
-1, /* sizeof(struct global_state), */
module_methods,
NULL,
NULL, /* module_traverse, */
NULL, /* module_clear, */
NULL
};
#define INITERROR return NULL
PyObject *
PyInit_interpreter(void)
#else
#define INITERROR return
PyMODINIT_FUNC
initinterpreter()
#endif
{
PyObject *m, *d;
if (PyType_Ready(&NumExprType) < 0)
INITERROR;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule3("interpreter", module_methods, NULL);
#endif
if (m == NULL)
INITERROR;
Py_INCREF(&NumExprType);
PyModule_AddObject(m, "NumExpr", (PyObject *)&NumExprType);
import_array();
d = PyDict_New();
if (!d) INITERROR;
#define OPCODE(n, name, sname, ...) \
if (add_symbol(d, sname, name, "add_op") < 0) { INITERROR; }
#include "opcodes.hpp"
#undef OPCODE
if (PyModule_AddObject(m, "opcodes", d) < 0) INITERROR;
d = PyDict_New();
if (!d) INITERROR;
#define add_func(name, sname) \
if (add_symbol(d, sname, name, "add_func") < 0) { INITERROR; }
#define FUNC_FF(name, sname, ...) add_func(name, sname);
#define FUNC_FFF(name, sname, ...) add_func(name, sname);
#define FUNC_DD(name, sname, ...) add_func(name, sname);
#define FUNC_DDD(name, sname, ...) add_func(name, sname);
#define FUNC_CC(name, sname, ...) add_func(name, sname);
#define FUNC_CCC(name, sname, ...) add_func(name, sname);
#include "functions.hpp"
#undef FUNC_CCC
#undef FUNC_CC
#undef FUNC_DDD
#undef FUNC_DD
#undef FUNC_DD
#undef FUNC_FFF
#undef FUNC_FF
#undef add_func
if (PyModule_AddObject(m, "funccodes", d) < 0) INITERROR;
if (PyModule_AddObject(m, "allaxes", PyLong_FromLong(255)) < 0) INITERROR;
if (PyModule_AddObject(m, "maxdims", PyLong_FromLong(NPY_MAXDIMS)) < 0) INITERROR;
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
#ifdef __cplusplus
} // extern "C"
#endif
<commit_msg>Using the correct name for mkl_get_version_string() for MKL 11.<commit_after>// Numexpr - Fast numerical array expression evaluator for NumPy.
//
// License: MIT
// Author: See AUTHORS.txt
//
// See LICENSE.txt for details about copyright and rights to use.
//
// module.cpp contains the CPython-specific module exposure.
#define DO_NUMPY_IMPORT_ARRAY
#include "module.hpp"
#include <structmember.h>
#include <vector>
#include "interpreter.hpp"
#include "numexpr_object.hpp"
using namespace std;
// Global state. The file interpreter.hpp also has some global state
// in its 'th_params' variable
global_state gs;
/* Do the worker job for a certain thread */
void *th_worker(void *tidptr)
{
int tid = *(int *)tidptr;
/* Parameters for threads */
npy_intp start;
npy_intp vlen;
npy_intp block_size;
NpyIter *iter;
vm_params params;
int *pc_error;
int ret;
int n_inputs;
int n_constants;
int n_temps;
size_t memsize;
char **mem;
npy_intp *memsteps;
npy_intp istart, iend;
char **errmsg;
// For output buffering if needed
vector<char> out_buffer;
while (1) {
gs.init_sentinels_done = 0; /* sentinels have to be initialised yet */
/* Meeting point for all threads (wait for initialization) */
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads < gs.nthreads) {
gs.count_threads++;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Check if thread has been asked to return */
if (gs.end_threads) {
return(0);
}
/* Get parameters for this thread before entering the main loop */
start = th_params.start;
vlen = th_params.vlen;
block_size = th_params.block_size;
params = th_params.params;
pc_error = th_params.pc_error;
// If output buffering is needed, allocate it
if (th_params.need_output_buffering) {
out_buffer.resize(params.memsizes[0] * BLOCK_SIZE1);
params.out_buffer = &out_buffer[0];
} else {
params.out_buffer = NULL;
}
/* Populate private data for each thread */
n_inputs = params.n_inputs;
n_constants = params.n_constants;
n_temps = params.n_temps;
memsize = (1+n_inputs+n_constants+n_temps) * sizeof(char *);
/* XXX malloc seems thread safe for POSIX, but for Win? */
mem = (char **)malloc(memsize);
memcpy(mem, params.mem, memsize);
errmsg = th_params.errmsg;
params.mem = mem;
/* Loop over blocks */
pthread_mutex_lock(&gs.count_mutex);
if (!gs.init_sentinels_done) {
/* Set sentinels and other global variables */
gs.gindex = start;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
gs.init_sentinels_done = 1; /* sentinels have been initialised */
gs.giveup = 0; /* no giveup initially */
} else {
gs.gindex += block_size;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
}
/* Grab one of the iterators */
iter = th_params.iter[tid];
if (iter == NULL) {
th_params.ret_code = -1;
gs.giveup = 1;
}
memsteps = th_params.memsteps[tid];
/* Get temporary space for each thread */
ret = get_temps_space(params, mem, BLOCK_SIZE1);
if (ret < 0) {
/* Propagate error to main thread */
th_params.ret_code = ret;
gs.giveup = 1;
}
pthread_mutex_unlock(&gs.count_mutex);
while (istart < vlen && !gs.giveup) {
/* Reset the iterator to the range for this task */
ret = NpyIter_ResetToIterIndexRange(iter, istart, iend,
errmsg);
/* Execute the task */
if (ret >= 0) {
ret = vm_engine_iter_task(iter, memsteps, params, pc_error, errmsg);
}
if (ret < 0) {
pthread_mutex_lock(&gs.count_mutex);
gs.giveup = 1;
/* Propagate error to main thread */
th_params.ret_code = ret;
pthread_mutex_unlock(&gs.count_mutex);
break;
}
pthread_mutex_lock(&gs.count_mutex);
gs.gindex += block_size;
istart = gs.gindex;
iend = istart + block_size;
if (iend > vlen) {
iend = vlen;
}
pthread_mutex_unlock(&gs.count_mutex);
}
/* Meeting point for all threads (wait for finalization) */
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads > 0) {
gs.count_threads--;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Release resources */
free_temps_space(params, mem);
free(mem);
} /* closes while(1) */
/* This should never be reached, but anyway */
return(0);
}
/* Initialize threads */
int init_threads(void)
{
int tid, rc;
/* Initialize mutex and condition variable objects */
pthread_mutex_init(&gs.count_mutex, NULL);
/* Barrier initialization */
pthread_mutex_init(&gs.count_threads_mutex, NULL);
pthread_cond_init(&gs.count_threads_cv, NULL);
gs.count_threads = 0; /* Reset threads counter */
/* Finally, create the threads */
for (tid = 0; tid < gs.nthreads; tid++) {
gs.tids[tid] = tid;
rc = pthread_create(&gs.threads[tid], NULL, th_worker,
(void *)&gs.tids[tid]);
if (rc) {
fprintf(stderr,
"ERROR; return code from pthread_create() is %d\n", rc);
fprintf(stderr, "\tError detail: %s\n", strerror(rc));
exit(-1);
}
}
gs.init_threads_done = 1; /* Initialization done! */
gs.pid = (int)getpid(); /* save the PID for this process */
return(0);
}
/* Set the number of threads in numexpr's VM */
int numexpr_set_nthreads(int nthreads_new)
{
int nthreads_old = gs.nthreads;
int t, rc;
void *status;
if (nthreads_new > MAX_THREADS) {
fprintf(stderr,
"Error. nthreads cannot be larger than MAX_THREADS (%d)",
MAX_THREADS);
return -1;
}
else if (nthreads_new <= 0) {
fprintf(stderr, "Error. nthreads must be a positive integer");
return -1;
}
/* Only join threads if they are not initialized or if our PID is
different from that in pid var (probably means that we are a
subprocess, and thus threads are non-existent). */
if (gs.nthreads > 1 && gs.init_threads_done && gs.pid == getpid()) {
/* Tell all existing threads to finish */
gs.end_threads = 1;
pthread_mutex_lock(&gs.count_threads_mutex);
if (gs.count_threads < gs.nthreads) {
gs.count_threads++;
pthread_cond_wait(&gs.count_threads_cv, &gs.count_threads_mutex);
}
else {
pthread_cond_broadcast(&gs.count_threads_cv);
}
pthread_mutex_unlock(&gs.count_threads_mutex);
/* Join exiting threads */
for (t=0; t<gs.nthreads; t++) {
rc = pthread_join(gs.threads[t], &status);
if (rc) {
fprintf(stderr,
"ERROR; return code from pthread_join() is %d\n",
rc);
fprintf(stderr, "\tError detail: %s\n", strerror(rc));
exit(-1);
}
}
gs.init_threads_done = 0;
gs.end_threads = 0;
}
/* Launch a new pool of threads (if necessary) */
gs.nthreads = nthreads_new;
if (gs.nthreads > 1 && (!gs.init_threads_done || gs.pid != getpid())) {
init_threads();
}
return nthreads_old;
}
#ifdef USE_VML
static PyObject *
_get_vml_version(PyObject *self, PyObject *args)
{
int len=198;
char buf[198];
mkl_get_version_string(buf, len);
return Py_BuildValue("s", buf);
}
static PyObject *
_set_vml_accuracy_mode(PyObject *self, PyObject *args)
{
int mode_in, mode_old;
if (!PyArg_ParseTuple(args, "i", &mode_in))
return NULL;
mode_old = vmlGetMode() & VML_ACCURACY_MASK;
vmlSetMode((mode_in & VML_ACCURACY_MASK) | VML_ERRMODE_IGNORE );
return Py_BuildValue("i", mode_old);
}
static PyObject *
_set_vml_num_threads(PyObject *self, PyObject *args)
{
int max_num_threads;
if (!PyArg_ParseTuple(args, "i", &max_num_threads))
return NULL;
mkl_domain_set_num_threads(max_num_threads, MKL_VML);
Py_RETURN_NONE;
}
#endif
static PyObject *
_set_num_threads(PyObject *self, PyObject *args)
{
int num_threads, nthreads_old;
if (!PyArg_ParseTuple(args, "i", &num_threads))
return NULL;
nthreads_old = numexpr_set_nthreads(num_threads);
return Py_BuildValue("i", nthreads_old);
}
static PyMethodDef module_methods[] = {
#ifdef USE_VML
{"_get_vml_version", _get_vml_version, METH_VARARGS,
"Get the VML/MKL library version."},
{"_set_vml_accuracy_mode", _set_vml_accuracy_mode, METH_VARARGS,
"Set accuracy mode for VML functions."},
{"_set_vml_num_threads", _set_vml_num_threads, METH_VARARGS,
"Suggests a maximum number of threads to be used in VML operations."},
#endif
{"_set_num_threads", _set_num_threads, METH_VARARGS,
"Suggests a maximum number of threads to be used in operations."},
{NULL}
};
static int
add_symbol(PyObject *d, const char *sname, int name, const char* routine_name)
{
PyObject *o, *s;
int r;
if (!sname) {
return 0;
}
o = PyLong_FromLong(name);
s = PyBytes_FromString(sname);
if (!s) {
PyErr_SetString(PyExc_RuntimeError, routine_name);
return -1;
}
r = PyDict_SetItem(d, s, o);
Py_XDECREF(o);
return r;
}
#ifdef __cplusplus
extern "C" {
#endif
#if PY_MAJOR_VERSION >= 3
/* XXX: handle the "global_state" state via moduedef */
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"interpreter",
NULL,
-1, /* sizeof(struct global_state), */
module_methods,
NULL,
NULL, /* module_traverse, */
NULL, /* module_clear, */
NULL
};
#define INITERROR return NULL
PyObject *
PyInit_interpreter(void)
#else
#define INITERROR return
PyMODINIT_FUNC
initinterpreter()
#endif
{
PyObject *m, *d;
if (PyType_Ready(&NumExprType) < 0)
INITERROR;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&moduledef);
#else
m = Py_InitModule3("interpreter", module_methods, NULL);
#endif
if (m == NULL)
INITERROR;
Py_INCREF(&NumExprType);
PyModule_AddObject(m, "NumExpr", (PyObject *)&NumExprType);
import_array();
d = PyDict_New();
if (!d) INITERROR;
#define OPCODE(n, name, sname, ...) \
if (add_symbol(d, sname, name, "add_op") < 0) { INITERROR; }
#include "opcodes.hpp"
#undef OPCODE
if (PyModule_AddObject(m, "opcodes", d) < 0) INITERROR;
d = PyDict_New();
if (!d) INITERROR;
#define add_func(name, sname) \
if (add_symbol(d, sname, name, "add_func") < 0) { INITERROR; }
#define FUNC_FF(name, sname, ...) add_func(name, sname);
#define FUNC_FFF(name, sname, ...) add_func(name, sname);
#define FUNC_DD(name, sname, ...) add_func(name, sname);
#define FUNC_DDD(name, sname, ...) add_func(name, sname);
#define FUNC_CC(name, sname, ...) add_func(name, sname);
#define FUNC_CCC(name, sname, ...) add_func(name, sname);
#include "functions.hpp"
#undef FUNC_CCC
#undef FUNC_CC
#undef FUNC_DDD
#undef FUNC_DD
#undef FUNC_DD
#undef FUNC_FFF
#undef FUNC_FF
#undef add_func
if (PyModule_AddObject(m, "funccodes", d) < 0) INITERROR;
if (PyModule_AddObject(m, "allaxes", PyLong_FromLong(255)) < 0) INITERROR;
if (PyModule_AddObject(m, "maxdims", PyLong_FromLong(NPY_MAXDIMS)) < 0) INITERROR;
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}
#ifdef __cplusplus
} // extern "C"
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013, Quarkslab
* 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 Quarkslab nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/random.hpp>
#include <boost/python.hpp>
#include <cstdint>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <leeloo/ip_list_intervals.h>
#include <leeloo/ips_parser.h>
#include <leeloo/list_intervals.h>
#include <leeloo/random.h>
using namespace boost::python;
boost::random::mt19937 g_mt_rand;
void (leeloo::ip_list_intervals::*ip_add1)(leeloo::ip_list_intervals::base_type const, leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::add;
void (leeloo::ip_list_intervals::*ip_add2)(leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::add;
bool (leeloo::ip_list_intervals::*ip_add3)(const char*) = &leeloo::ip_list_intervals::add;
void (leeloo::ip_list_intervals::*ip_remove1)(leeloo::ip_list_intervals::base_type const, leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::remove;
void (leeloo::ip_list_intervals::*ip_remove2)(leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::remove;
bool (leeloo::ip_list_intervals::*ip_remove3)(const char*) = &leeloo::ip_list_intervals::remove;
bool (leeloo::ip_list_intervals::*contains1)(uint32_t const) const = &leeloo::ip_list_intervals::contains;
bool (leeloo::ip_list_intervals::*contains2)(const char*) const = &leeloo::ip_list_intervals::contains;
class set_read_only
{
public:
typedef uint32_t const* iterator;
public:
set_read_only():
_buf(nullptr),
_size(0)
{ }
set_read_only(uint32_t const* buf, size_t const size):
_buf(buf),
_size(size)
{ }
public:
inline uint32_t at(size_t idx) const
{
assert(idx < _size);
return _buf[idx];
}
inline size_t size() const { return _size; }
uint32_t const* begin() const { return _buf; }
uint32_t const* end() const { return _buf+_size; }
private:
uint32_t const* _buf;
size_t _size;
};
static void ip_list_random_sets(leeloo::ip_list_intervals const& l, size_t const size_div, object& f_set)
{
l.random_sets(size_div,
[&f_set](uint32_t const* buf, size_t const size) { f_set(set_read_only(buf, size)); },
leeloo::random_engine<uint32_t>(g_mt_rand));
}
static void init_rand_gen()
{
int fd = open("/dev/urandom", O_RDONLY);
if (fd != -1) {
uint32_t seed;
read(fd, &seed, sizeof(uint32_t));
g_mt_rand.seed(seed);
close(fd);
}
else {
g_mt_rand.seed(time(NULL));
}
}
static uint32_t python_ipv4toi1(const char* ip)
{
bool valid;
return leeloo::ips_parser::ipv4toi(ip, strlen(ip), valid);
}
static uint32_t python_ipv4toi2(const char* ip, bool& valid)
{
return leeloo::ips_parser::ipv4toi(ip, strlen(ip), valid);
}
BOOST_PYTHON_MODULE(pyleeloo)
{
init_rand_gen();
class_<leeloo::ip_interval>("ip_interval")
.def("assign", &leeloo::ip_interval::assign)
.def("lower", &leeloo::ip_interval::lower)
.def("upper", &leeloo::ip_interval::upper)
.def("set_lower", &leeloo::ip_interval::set_lower)
.def("set_upper", &leeloo::ip_interval::set_upper);
class_<leeloo::ip_list_intervals>("ip_list_intervals")
.def("add", ip_add1)
.def("add", ip_add2)
.def("add", ip_add3)
.def("remove", ip_remove1)
.def("remove", ip_remove2)
.def("remove", ip_remove3)
.def("aggregate", &leeloo::ip_list_intervals::aggregate)
.def("create_index_cache", &leeloo::ip_list_intervals::create_index_cache)
.def("size", &leeloo::ip_list_intervals::size)
.def("reserve", &leeloo::ip_list_intervals::reserve)
.def("clear", &leeloo::ip_list_intervals::clear)
.def("at", &leeloo::ip_list_intervals::at)
.def("random_sets", &ip_list_random_sets)
.def("contains", contains1)
.def("contains", contains2)
.def("dump_to_file", &leeloo::ip_list_intervals::dump_to_file)
.def("read_from_file", &leeloo::ip_list_intervals::read_from_file)
.def("__iter__", iterator<leeloo::ip_list_intervals>());
class_<set_read_only>("set_read_only")
.def("at", &set_read_only::at)
.def("size", &set_read_only::size)
.def("__iter__", iterator<set_read_only>());
def("ipv4toi", python_ipv4toi1);
def("ipv4toi", python_ipv4toi2);
}
<commit_msg>Python bindings: add the u64_list_intervals class<commit_after>/*
* Copyright (c) 2013, Quarkslab
* 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 Quarkslab nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <boost/random.hpp>
#include <boost/python.hpp>
#include <cstdint>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <leeloo/ip_list_intervals.h>
#include <leeloo/ips_parser.h>
#include <leeloo/list_intervals.h>
#include <leeloo/random.h>
using namespace boost::python;
boost::random::mt19937 g_mt_rand;
void (leeloo::ip_list_intervals::*ip_add1)(leeloo::ip_list_intervals::base_type const, leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::add;
void (leeloo::ip_list_intervals::*ip_add2)(leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::add;
bool (leeloo::ip_list_intervals::*ip_add3)(const char*) = &leeloo::ip_list_intervals::add;
void (leeloo::ip_list_intervals::*ip_remove1)(leeloo::ip_list_intervals::base_type const, leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::remove;
void (leeloo::ip_list_intervals::*ip_remove2)(leeloo::ip_list_intervals::base_type const) = &leeloo::ip_list_intervals::remove;
bool (leeloo::ip_list_intervals::*ip_remove3)(const char*) = &leeloo::ip_list_intervals::remove;
bool (leeloo::ip_list_intervals::*contains1)(uint32_t const) const = &leeloo::ip_list_intervals::contains;
bool (leeloo::ip_list_intervals::*contains2)(const char*) const = &leeloo::ip_list_intervals::contains;
template <class Integer>
class set_read_only
{
public:
typedef Integer const* iterator;
public:
set_read_only():
_buf(nullptr),
_size(0)
{ }
set_read_only(Integer const* buf, size_t const size):
_buf(buf),
_size(size)
{ }
public:
inline Integer at(size_t idx) const
{
assert(idx < _size);
return _buf[idx];
}
inline size_t size() const { return _size; }
Integer const* begin() const { return _buf; }
Integer const* end() const { return _buf+_size; }
private:
Integer const* _buf;
size_t _size;
};
typedef set_read_only<uint32_t> u32_set_read_only;
typedef set_read_only<uint64_t> u64_set_read_only;
static void ip_list_random_sets(leeloo::ip_list_intervals const& l, size_t const size_div, object& f_set)
{
l.random_sets(size_div,
[&f_set](uint32_t const* buf, size_t const size) { f_set(u32_set_read_only(buf, size)); },
leeloo::random_engine<uint32_t>(g_mt_rand));
}
static void init_rand_gen()
{
int fd = open("/dev/urandom", O_RDONLY);
if (fd != -1) {
uint32_t seed;
read(fd, &seed, sizeof(uint32_t));
g_mt_rand.seed(seed);
close(fd);
}
else {
g_mt_rand.seed(time(NULL));
}
}
static uint32_t python_ipv4toi1(const char* ip)
{
bool valid;
return leeloo::ips_parser::ipv4toi(ip, strlen(ip), valid);
}
static uint32_t python_ipv4toi2(const char* ip, bool& valid)
{
return leeloo::ips_parser::ipv4toi(ip, strlen(ip), valid);
}
// uint64 intervals
//
typedef leeloo::interval<uint64_t> u64_interval;
typedef leeloo::list_intervals<u64_interval> u64_list_intervals;
void (u64_list_intervals::*u64_add1)(u64_list_intervals::base_type const, u64_list_intervals::base_type const) = &u64_list_intervals::add;
static void u64_list_random_sets(u64_list_intervals const& l, size_t const size_div, object& f_set)
{
l.random_sets(size_div,
[&f_set](uint64_t const* buf, size_t const size) { f_set(u64_set_read_only(buf, size)); },
leeloo::random_engine<uint64_t>(g_mt_rand));
}
BOOST_PYTHON_MODULE(pyleeloo)
{
init_rand_gen();
class_<leeloo::ip_interval>("ip_interval")
.def("assign", &leeloo::ip_interval::assign)
.def("lower", &leeloo::ip_interval::lower)
.def("upper", &leeloo::ip_interval::upper)
.def("set_lower", &leeloo::ip_interval::set_lower)
.def("set_upper", &leeloo::ip_interval::set_upper);
class_<u64_interval>("u64_interval")
.def("assign", &u64_interval::assign)
.def("lower", &u64_interval::lower)
.def("upper", &u64_interval::upper)
.def("set_lower", &u64_interval::set_lower)
.def("set_upper", &u64_interval::set_upper);
class_<leeloo::ip_list_intervals>("ip_list_intervals")
.def("add", ip_add1)
.def("add", ip_add2)
.def("add", ip_add3)
.def("remove", ip_remove1)
.def("remove", ip_remove2)
.def("remove", ip_remove3)
.def("aggregate", &leeloo::ip_list_intervals::aggregate)
.def("create_index_cache", &leeloo::ip_list_intervals::create_index_cache)
.def("size", &leeloo::ip_list_intervals::size)
.def("reserve", &leeloo::ip_list_intervals::reserve)
.def("clear", &leeloo::ip_list_intervals::clear)
.def("at", &leeloo::ip_list_intervals::at)
.def("random_sets", &ip_list_random_sets)
.def("contains", contains1)
.def("contains", contains2)
.def("dump_to_file", &leeloo::ip_list_intervals::dump_to_file)
.def("read_from_file", &leeloo::ip_list_intervals::read_from_file)
.def("__iter__", iterator<leeloo::ip_list_intervals>());
class_<u64_list_intervals>("u64_list_intervals")
.def("add", u64_add1)
.def("aggregate", &u64_list_intervals::aggregate)
.def("create_index_cache", &u64_list_intervals::create_index_cache)
.def("size", &u64_list_intervals::size)
.def("reserve", &u64_list_intervals::reserve)
.def("clear", &u64_list_intervals::clear)
.def("at", &u64_list_intervals::at)
.def("random_sets", &u64_list_random_sets)
.def("dump_to_file", &u64_list_intervals::dump_to_file)
.def("read_from_file", &u64_list_intervals::read_from_file)
.def("__iter__", iterator<u64_list_intervals>());
class_<u32_set_read_only>("u32_set_read_only")
.def("at", &u32_set_read_only::at)
.def("size", &u32_set_read_only::size)
.def("__iter__", iterator<u32_set_read_only>());
class_<u64_set_read_only>("u64_set_read_only")
.def("at", &u64_set_read_only::at)
.def("size", &u64_set_read_only::size)
.def("__iter__", iterator<u64_set_read_only>());
def("ipv4toi", python_ipv4toi1);
def("ipv4toi", python_ipv4toi2);
}
<|endoftext|> |
<commit_before>/*
* This file is part ServerManager of package
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
using namespace ServerManager;
using namespace std;
Manager::Manager(){}
void Manager::setConfiguration(Configuration config)
{
this->config = config;
}
string Manager::search(string hostName)
{
string cmd = "cat " + this->config.hosts + " | grep " + hostName;
Console console(cmd);
return console.exec();
}
string Manager::getList()
{
ifstream file(this->config.hosts.c_str());
string line;
string result;
if (file.good()) {
while(getline(file, line)) {
istringstream line_string(line);
string key;
if (line.find(" ") != std::string::npos) {
if (getline(line_string, key, ' ')) {
this->appendLine(&result, key, line);
}
} else {
if (getline(line_string, key, '\t')) {
this->appendLine(&result, key, line);
}
}
}
file.close();
return result;
} else {
file.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
}
string Manager::create(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
if (hostsFile.good()) {
hostsFile << endl << this->getHostConfig(hostName);
result.append("\nAdded virtual host into hosts file");
hostsFile.close();
} else {
hostsFile.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
string path = this->config.nginx + "/" + hostName + ".conf";
ofstream nginxConfig(path.c_str());
if (nginxConfig.good()) {
nginxConfig << this->getServerConfig(hostName);
if(nginxConfig.good()) {
result.append("\nAdded virtual host nginx configuration");
}
Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/log");
Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
result.append("\nCreated base project directories: ");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/log");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
}
nginxConfig.close();
} else {
nginxConfig.close();
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
if (chmodCmd.exec().empty()) {
result.append("\nSet chmod");
}
return result;
}
string Manager::remove(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
if (rmProject.exec().empty()) {
result.append("\nProject directory has been removed");
} else {
throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
}
if (rmNginxConf.exec().empty()) {
result.append("\nNginx configuration has been removed");
} else {
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
ifstream ihostFile(this->config.hosts.c_str());
if (ihostFile.good()) {
string line;
string newContent = "";
while(getline(ihostFile, line)) {
if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty() && line.compare(this->getHostConfig(hostName, " ")) != 0) {
newContent.append(line + "\n");
}
}
ofstream ohostFile(this->config.hosts.c_str());
ohostFile << newContent;
result.append("\nVirtual host has been removed from hosts file");
ihostFile.close();
ohostFile.close();
} else {
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
ihostFile.close();
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
return result;
}
void Manager::appendLine(string* result,string key, string line)
{
if (key.compare("127.0.0.1") == 0) {
(*result).append(line + "\n");
}
}
string Manager::getServerConfig(string hostName)
{
string config = "server {\n" \
"\tlisten 80;\n" \
"\tserver_name " + hostName + this->config.tld + ";\n" \
"\troot " + this->config.htdocs + "/" + hostName + "/" + this->config.root + ";\n" \
"\n" \
"\terror_log " + this->config.htdocs + "/" + hostName + "/log/" + hostName + "_error.log;\n" \
"\taccess_log " + this->config.htdocs + "/" + hostName + "/log/" + hostName + "_accesslog.log;\n" \
"\n" \
"\tinclude common/common.conf;\n" \
"\tinclude common/php.conf;\n" \
"\tinclude common/nette.conf;\n" \
"}\n";
return config;
}
string Manager::getHostConfig(string hostName, string delimiter)
{
string host = "127.0.0.1" + delimiter + hostName + this->config.tld;
return host;
}
<commit_msg>Joined declaration<commit_after>/*
* This file is part ServerManager of package
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
using namespace ServerManager;
using namespace std;
Manager::Manager(){}
void Manager::setConfiguration(Configuration config)
{
this->config = config;
}
string Manager::search(string hostName)
{
string cmd = "cat " + this->config.hosts + " | grep " + hostName;
Console console(cmd);
return console.exec();
}
string Manager::getList()
{
ifstream file(this->config.hosts.c_str());
string line, result;
if (file.good()) {
while(getline(file, line)) {
istringstream line_string(line);
string key;
if (line.find(" ") != std::string::npos) {
if (getline(line_string, key, ' ')) {
this->appendLine(&result, key, line);
}
} else {
if (getline(line_string, key, '\t')) {
this->appendLine(&result, key, line);
}
}
}
file.close();
return result;
} else {
file.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
}
string Manager::create(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
if (hostsFile.good()) {
hostsFile << endl << this->getHostConfig(hostName);
result.append("\nAdded virtual host into hosts file");
hostsFile.close();
} else {
hostsFile.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
string path = this->config.nginx + "/" + hostName + ".conf";
ofstream nginxConfig(path.c_str());
if (nginxConfig.good()) {
nginxConfig << this->getServerConfig(hostName);
if(nginxConfig.good()) {
result.append("\nAdded virtual host nginx configuration");
}
Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/log");
Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
result.append("\nCreated base project directories: ");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/log");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
}
nginxConfig.close();
} else {
nginxConfig.close();
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
if (chmodCmd.exec().empty()) {
result.append("\nSet chmod");
}
return result;
}
string Manager::remove(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
if (rmProject.exec().empty()) {
result.append("\nProject directory has been removed");
} else {
throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
}
if (rmNginxConf.exec().empty()) {
result.append("\nNginx configuration has been removed");
} else {
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
ifstream ihostFile(this->config.hosts.c_str());
if (ihostFile.good()) {
string line;
string newContent = "";
while(getline(ihostFile, line)) {
if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty() && line.compare(this->getHostConfig(hostName, " ")) != 0) {
newContent.append(line + "\n");
}
}
ofstream ohostFile(this->config.hosts.c_str());
ohostFile << newContent;
result.append("\nVirtual host has been removed from hosts file");
ihostFile.close();
ohostFile.close();
} else {
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
ihostFile.close();
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
return result;
}
void Manager::appendLine(string* result,string key, string line)
{
if (key.compare("127.0.0.1") == 0) {
(*result).append(line + "\n");
}
}
string Manager::getServerConfig(string hostName)
{
string config = "server {\n" \
"\tlisten 80;\n" \
"\tserver_name " + hostName + this->config.tld + ";\n" \
"\troot " + this->config.htdocs + "/" + hostName + "/" + this->config.root + ";\n" \
"\n" \
"\terror_log " + this->config.htdocs + "/" + hostName + "/log/" + hostName + "_error.log;\n" \
"\taccess_log " + this->config.htdocs + "/" + hostName + "/log/" + hostName + "_accesslog.log;\n" \
"\n" \
"\tinclude common/common.conf;\n" \
"\tinclude common/php.conf;\n" \
"\tinclude common/nette.conf;\n" \
"}\n";
return config;
}
string Manager::getHostConfig(string hostName, string delimiter)
{
string host = "127.0.0.1" + delimiter + hostName + this->config.tld;
return host;
}
<|endoftext|> |
<commit_before>/*
Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef BITHORDED_THREADPOOL_HPP
#define BITHORDED_THREADPOOL_HPP
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <map>
#include <queue>
class Task {
public:
virtual void operator()() = 0;
};
class ThreadPool
{
public:
ThreadPool(int maxThreads);
void post(Task& task);
void join();
private:
void thread_main();
Task* getTask();
size_t workerCount();
bool _running;
boost::mutex _m;
uint _maxThreads;
std::map<boost::thread::id, boost::thread*> _threads;
std::queue<Task*> _tasks;
};
class TaskQueue : public Task {
public:
TaskQueue(ThreadPool &pool);
void enqueue(Task& task);
void operator()();
private:
Task* getTask();
ThreadPool& _pool;
bool _running;
boost::mutex _m;
std::queue<Task*> _tasks;
};
#endif // BITHORDED_THREADPOOL_HPP
<commit_msg>Add virtual destructor to ThreadPool-Task-base<commit_after>/*
Copyright 2012 Ulrik Mikaelsson <ulrik.mikaelsson@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef BITHORDED_THREADPOOL_HPP
#define BITHORDED_THREADPOOL_HPP
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <map>
#include <queue>
class Task {
public:
virtual ~Task() {};
virtual void operator()() = 0;
};
class ThreadPool
{
public:
ThreadPool(int maxThreads);
void post(Task& task);
void join();
private:
void thread_main();
Task* getTask();
size_t workerCount();
bool _running;
boost::mutex _m;
uint _maxThreads;
std::map<boost::thread::id, boost::thread*> _threads;
std::queue<Task*> _tasks;
};
class TaskQueue : public Task {
public:
TaskQueue(ThreadPool &pool);
void enqueue(Task& task);
void operator()();
private:
Task* getTask();
ThreadPool& _pool;
bool _running;
boost::mutex _m;
std::queue<Task*> _tasks;
};
#endif // BITHORDED_THREADPOOL_HPP
<|endoftext|> |
<commit_before>/*
* MusicBrainz -- The Internet music metadatabase
*
* Copyright (C) 2006 Lukas Lalinsky
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id$
*/
#include <string>
#include <map>
#include <iostream>
#include <string.h>
#include <ne_session.h>
#include <ne_request.h>
#include <ne_utils.h>
#include <ne_auth.h>
#include <ne_uri.h>
#include <musicbrainz3/webservice.h>
#include <musicbrainz3/artist.h>
#include "utilspriv.h"
#include "config.h"
using namespace std;
using namespace MusicBrainz;
void
WebService::init()
{
ne_sock_init();
}
WebService::WebService(const std::string &host,
const int port,
const std::string &pathPrefix,
const std::string &username,
const std::string &password,
const std::string &realm)
: host(host),
port(port),
pathPrefix(pathPrefix),
username(username),
password(password),
realm(realm)
{
}
int
WebService::httpAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
WebService *ws = (WebService *)userdata;
strncpy(username, ws->username.c_str(), NE_ABUFSIZ);
strncpy(password, ws->password.c_str(), NE_ABUFSIZ);
return attempts;
}
int
WebService::httpResponseReader(void *userdata, const char *buf, size_t len)
{
string *str = (string *)userdata;
str->append(buf, len);
return 0;
}
string
WebService::get(const std::string &entity,
const std::string &id,
const IIncludes::IncludeList &include,
const IFilter::ParameterList &filter,
const std::string &version)
{
ne_session *sess;
ne_request *req;
#ifdef DEBUG
cout << endl << "Connecting to http://" << host << ":" << port << endl;
#endif
sess = ne_session_create("http", host.c_str(), port);
if (!sess)
throw WebServiceError("ne_session_create() failed.");
ne_set_server_auth(sess, httpAuth, this);
ne_set_useragent(sess, PACKAGE"/"VERSION);
vector<pair<string, string> > params;
params.push_back(pair<string, string>("type", "xml"));
string inc;
for (IIncludes::IncludeList::const_iterator i = include.begin(); i != include.end(); i++) {
if (!inc.empty())
inc += " ";
inc += *i;
}
if (!inc.empty())
params.push_back(pair<string, string>("inc", inc));
for (IFilter::ParameterList::const_iterator i = filter.begin(); i != filter.end(); i++)
params.push_back(pair<string, string>(i->first, i->second));
string uri = pathPrefix + "/" + version + "/" + entity + "/" + id + "?" + urlEncode(params);
#ifdef DEBUG
cout << "GET " << uri << endl;
#endif
string response;
req = ne_request_create(sess, "GET", uri.c_str());
ne_add_response_body_reader(req, ne_accept_2xx, httpResponseReader, &response);
int result = ne_request_dispatch(req);
int status = ne_get_status(req)->code;
ne_request_destroy(req);
string errorMessage = ne_get_error(sess);
ne_session_destroy(sess);
#ifdef DEBUG
cout << "Result: " << result << " (" << errorMessage << ")"<< endl;
cout << "Status: " << status << endl;
cout << "Response:" << endl << response << endl;
#endif
switch (result) {
case NE_OK:
break;
case NE_CONNECT:
throw ConnectionError(errorMessage);
case NE_TIMEOUT:
throw TimeOutError(errorMessage);
case NE_AUTH:
throw AuthenticationError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
switch (status) {
case 200:
break;
case 400:
throw RequestError(errorMessage);
case 401:
throw AuthenticationError(errorMessage);
case 404:
throw ResourceNotFoundError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
return response;
}
void
WebService::post(const std::string &entity,
const std::string &id,
const std::string &data,
const std::string &version)
{
ne_session *sess;
ne_request *req;
#ifdef DEBUG
cout << endl << "Connecting to http://" << host << ":" << port << endl;
#endif
sess = ne_session_create("http", host.c_str(), port);
if (!sess)
throw WebServiceError("ne_session_create() failed.");
ne_set_server_auth(sess, httpAuth, this);
ne_set_useragent(sess, PACKAGE"/"VERSION);
string uri = pathPrefix + "/" + version + "/" + entity + "/" + id;
#ifdef DEBUG
cout << "POST " << uri << endl;
cout << "POST-BODY: " << data << endl;
#endif
req = ne_request_create(sess, "POST", uri.c_str());
ne_set_request_flag(req, NE_REQFLAG_IDEMPOTENT, 0);
ne_add_request_header(req, "Content-type", "application/x-www-form-urlencoded");
ne_set_request_body_buffer(req, data.c_str(), data.size());
int result = ne_request_dispatch(req);
int status = ne_get_status(req)->code;
ne_request_destroy(req);
string errorMessage = ne_get_error(sess);
ne_session_destroy(sess);
#ifdef DEBUG
cout << "Result: " << result << " (" << errorMessage << ")"<< endl;
cout << "Status: " << status << endl;
#endif
switch (result) {
case NE_OK:
break;
case NE_CONNECT:
throw ConnectionError(errorMessage);
case NE_TIMEOUT:
throw TimeOutError(errorMessage);
case NE_AUTH:
throw AuthenticationError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
switch (status) {
case 200:
break;
case 400:
throw RequestError(errorMessage);
case 401:
throw AuthenticationError(errorMessage);
case 404:
throw ResourceNotFoundError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
}
<commit_msg>Don't set NE_REQFLAG_IDEMPOTENT if we are using neon 0.25.<commit_after>/*
* MusicBrainz -- The Internet music metadatabase
*
* Copyright (C) 2006 Lukas Lalinsky
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id$
*/
#include <string>
#include <map>
#include <iostream>
#include <string.h>
#include <ne_session.h>
#include <ne_request.h>
#include <ne_utils.h>
#include <ne_auth.h>
#include <ne_uri.h>
#include <musicbrainz3/webservice.h>
#include <musicbrainz3/artist.h>
#include "utilspriv.h"
#include "config.h"
using namespace std;
using namespace MusicBrainz;
void
WebService::init()
{
ne_sock_init();
}
WebService::WebService(const std::string &host,
const int port,
const std::string &pathPrefix,
const std::string &username,
const std::string &password,
const std::string &realm)
: host(host),
port(port),
pathPrefix(pathPrefix),
username(username),
password(password),
realm(realm)
{
}
int
WebService::httpAuth(void *userdata, const char *realm, int attempts,
char *username, char *password)
{
WebService *ws = (WebService *)userdata;
strncpy(username, ws->username.c_str(), NE_ABUFSIZ);
strncpy(password, ws->password.c_str(), NE_ABUFSIZ);
return attempts;
}
int
WebService::httpResponseReader(void *userdata, const char *buf, size_t len)
{
string *str = (string *)userdata;
str->append(buf, len);
return 0;
}
string
WebService::get(const std::string &entity,
const std::string &id,
const IIncludes::IncludeList &include,
const IFilter::ParameterList &filter,
const std::string &version)
{
ne_session *sess;
ne_request *req;
#ifdef DEBUG
cout << endl << "Connecting to http://" << host << ":" << port << endl;
#endif
sess = ne_session_create("http", host.c_str(), port);
if (!sess)
throw WebServiceError("ne_session_create() failed.");
ne_set_server_auth(sess, httpAuth, this);
ne_set_useragent(sess, PACKAGE"/"VERSION);
vector<pair<string, string> > params;
params.push_back(pair<string, string>("type", "xml"));
string inc;
for (IIncludes::IncludeList::const_iterator i = include.begin(); i != include.end(); i++) {
if (!inc.empty())
inc += " ";
inc += *i;
}
if (!inc.empty())
params.push_back(pair<string, string>("inc", inc));
for (IFilter::ParameterList::const_iterator i = filter.begin(); i != filter.end(); i++)
params.push_back(pair<string, string>(i->first, i->second));
string uri = pathPrefix + "/" + version + "/" + entity + "/" + id + "?" + urlEncode(params);
#ifdef DEBUG
cout << "GET " << uri << endl;
#endif
string response;
req = ne_request_create(sess, "GET", uri.c_str());
ne_add_response_body_reader(req, ne_accept_2xx, httpResponseReader, &response);
int result = ne_request_dispatch(req);
int status = ne_get_status(req)->code;
ne_request_destroy(req);
string errorMessage = ne_get_error(sess);
ne_session_destroy(sess);
#ifdef DEBUG
cout << "Result: " << result << " (" << errorMessage << ")"<< endl;
cout << "Status: " << status << endl;
cout << "Response:" << endl << response << endl;
#endif
switch (result) {
case NE_OK:
break;
case NE_CONNECT:
throw ConnectionError(errorMessage);
case NE_TIMEOUT:
throw TimeOutError(errorMessage);
case NE_AUTH:
throw AuthenticationError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
switch (status) {
case 200:
break;
case 400:
throw RequestError(errorMessage);
case 401:
throw AuthenticationError(errorMessage);
case 404:
throw ResourceNotFoundError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
return response;
}
void
WebService::post(const std::string &entity,
const std::string &id,
const std::string &data,
const std::string &version)
{
ne_session *sess;
ne_request *req;
#ifdef DEBUG
cout << endl << "Connecting to http://" << host << ":" << port << endl;
#endif
sess = ne_session_create("http", host.c_str(), port);
if (!sess)
throw WebServiceError("ne_session_create() failed.");
ne_set_server_auth(sess, httpAuth, this);
ne_set_useragent(sess, PACKAGE"/"VERSION);
string uri = pathPrefix + "/" + version + "/" + entity + "/" + id;
#ifdef DEBUG
cout << "POST " << uri << endl;
cout << "POST-BODY: " << data << endl;
#endif
req = ne_request_create(sess, "POST", uri.c_str());
// neon 0.26 and higher
#ifdef NE_FEATURE_I18N
ne_set_request_flag(req, NE_REQFLAG_IDEMPOTENT, 0);
#endif
ne_add_request_header(req, "Content-type", "application/x-www-form-urlencoded");
ne_set_request_body_buffer(req, data.c_str(), data.size());
int result = ne_request_dispatch(req);
int status = ne_get_status(req)->code;
ne_request_destroy(req);
string errorMessage = ne_get_error(sess);
ne_session_destroy(sess);
#ifdef DEBUG
cout << "Result: " << result << " (" << errorMessage << ")"<< endl;
cout << "Status: " << status << endl;
#endif
switch (result) {
case NE_OK:
break;
case NE_CONNECT:
throw ConnectionError(errorMessage);
case NE_TIMEOUT:
throw TimeOutError(errorMessage);
case NE_AUTH:
throw AuthenticationError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
switch (status) {
case 200:
break;
case 400:
throw RequestError(errorMessage);
case 401:
throw AuthenticationError(errorMessage);
case 404:
throw ResourceNotFoundError(errorMessage);
default:
throw WebServiceError(errorMessage);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlgedpage.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-01-16 16:37:11 $
*
* 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 _BASCTL_DLGEDPAGE_HXX
#define _BASCTL_DLGEDPAGE_HXX
#ifndef _SVDPAGE_HXX
#include "svx/svdpage.hxx"
#endif
//============================================================================
// DlgEdPage
//============================================================================
class DlgEdModel;
class DlgEdForm;
class DlgEdPage : public SdrPage
{
private:
DlgEdForm* pDlgEdForm;
public:
TYPEINFO();
DlgEdPage( DlgEdModel& rModel, FASTBOOL bMasterPage=FALSE );
DlgEdPage( const DlgEdPage& );
virtual ~DlgEdPage();
using SdrPage::Clone;
virtual SdrPage* Clone() const;
void SetDlgEdForm( DlgEdForm* pForm ) { pDlgEdForm = pForm; }
DlgEdForm* GetDlgEdForm() const { return pDlgEdForm; }
virtual SdrObject* SetObjectOrdNum(ULONG nOldObjNum, ULONG nNewObjNum);
};
#endif //_BASCTL_DLGEDPAGE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.5.92); FILE MERGED 2008/04/01 15:00:41 thb 1.5.92.2: #i85898# Stripping all external header guards 2008/03/28 16:05:04 rt 1.5.92.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: dlgedpage.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _BASCTL_DLGEDPAGE_HXX
#define _BASCTL_DLGEDPAGE_HXX
#include "svx/svdpage.hxx"
//============================================================================
// DlgEdPage
//============================================================================
class DlgEdModel;
class DlgEdForm;
class DlgEdPage : public SdrPage
{
private:
DlgEdForm* pDlgEdForm;
public:
TYPEINFO();
DlgEdPage( DlgEdModel& rModel, FASTBOOL bMasterPage=FALSE );
DlgEdPage( const DlgEdPage& );
virtual ~DlgEdPage();
using SdrPage::Clone;
virtual SdrPage* Clone() const;
void SetDlgEdForm( DlgEdForm* pForm ) { pDlgEdForm = pForm; }
DlgEdForm* GetDlgEdForm() const { return pDlgEdForm; }
virtual SdrObject* SetObjectOrdNum(ULONG nOldObjNum, ULONG nNewObjNum);
};
#endif //_BASCTL_DLGEDPAGE_HXX
<|endoftext|> |
<commit_before>/*
* Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1,
* 0.1% in g2).
*
* Change DEVADDR to a unique address!
* See http://thethingsnetwork.org/wiki/AddressSpace
*
* Do not forget to define the radio type correctly in config.h.
*/
#include <SPI.h>
#include "Lora.h"
#include "Logging.h"
#if defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \
config.h in the lmic library to set it.
#endif
// LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
// 2B7E151628AED2A6ABF7158809CF4F3C
//static const PROGMEM u1_t NWKSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
// LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
//static const u1_t PROGMEM APPSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
//static const u4_t DEVADDR = 0x03FF0001 ; // <-- Change this address for every node!
//static const u4_t DEVADDR = 0x02D1EFEF ; // Manny's
//static const PROGMEM u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
//static const u1_t PROGMEM APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };
// Franks keys:
const u1_t NWKSKEY[16] = { 0x80, 0x42, 0x43, 0x64, 0x2C, 0x1E, 0x3B, 0x04, 0x36, 0x6D, 0x36, 0xC3, 0x90, 0x9F, 0xCA, 0xA2 };
const u1_t APPSKEY[16] = { 0x43, 0x0D, 0x53, 0xB2, 0x72, 0xA6, 0x47, 0xAF, 0x5D, 0xFF, 0x6A, 0x16, 0x7A, 0xB7, 0x9A, 0x20 };
// LoRaWAN end-device address (DevAddr)
// See http://thethingsnetwork.org/wiki/AddressSpace
const u4_t DEVADDR = 0x26011D8B; // <-- Change this address for every node!
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 19,
.rxtx = LMIC_UNUSED_PIN,
.rst = 18,
.dio = {16, 5, 6}, // Moved dio0 from 17 because of overlapping ExtInt4 (pin6)
};
static osjob_t timeoutjob;
static void txtimeout_func(osjob_t *job) {
digitalWrite(LED_BUILTIN, LOW); // off
Log.Debug(F("Transmit Timeout" CR));
//txActive = false;
LMIC_clrTxData ();
}
bool loraSendBytes(uint8_t *data, uint16_t len) {
ostime_t t = os_getTime();
//os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func);
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Log.Debug(F("OP_TXRXPEND, not sending" CR));
return false; // Did not enqueue
} else {
// Prepare upstream data transmission at the next possible time.
Log.Debug(F("Packet queued" CR));
digitalWrite(LED_BUILTIN, HIGH); // off
LMIC_setTxData2(1, data, len, 0);
}
// Timeout TX after 20 seconds
os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func);
return true;
}
void onEvent (ev_t ev) {
Log.Debug("%d: ", os_getTime());
switch(ev) {
case EV_SCAN_TIMEOUT:
Log.Debug(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Log.Debug(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Log.Debug(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Log.Debug(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Log.Debug(F("EV_JOINING"));
break;
case EV_JOINED:
Log.Debug(F("EV_JOINED"));
break;
case EV_RFU1:
Log.Debug(F("EV_RFU1"));
break;
case EV_JOIN_FAILED:
Log.Debug(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Log.Debug(F("EV_REJOIN_FAILED"));
break;
break;
case EV_TXCOMPLETE:
os_clearCallback(&timeoutjob);
Log.Debug(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
digitalWrite(LED_BUILTIN, LOW); // off
if(LMIC.dataLen) {
// data received in rx slot after tx
Log.Debug(F("Data Received: "));
u1_t *p = LMIC.frame+LMIC.dataBeg;
for (int i=0; i<LMIC.dataLen; ++i) {
Log.Debug("%x", *p++);
}
// Log.Debug("%*h", LMIC.dataLen, LMIC.frame+LMIC.dataBeg);
Log.Debug(CR);
}
break;
case EV_LOST_TSYNC:
Log.Debug(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Log.Debug(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Log.Debug(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Log.Debug(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Log.Debug(F("EV_LINK_ALIVE"));
break;
default:
Log.Debug(F("Unknown event"));
break;
}
Log.Debug(CR);
}
void setupLora() {
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Set static session parameters. Instead of dynamically establishing a session
// by joining the network, precomputed session parameters are provided.
#ifdef PROGMEM
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif
#if defined(CFG_eu868)
// Set up the channels used by the Things Network, which corresponds
// to the defaults of most gateways. Without this, only three base
// channels from the LoRaWAN specification are used, which certainly
// works, so it is good for debugging, but can overload those
// frequencies, so be sure to configure the full frequency range of
// your network here (unless your network autoconfigures them).
// Setting up channels should happen after LMIC_setSession, as that
// configures the minimal channel set.
LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band
LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band
// TTN defines an additional channel at 869.525Mhz using SF9 for class B
// devices' ping slots. LMIC does not have an easy way to define set this
// frequency and support for class B is spotty and untested, so this
// frequency is not configured here.
#endif
LMIC_selectSubBand(1);
// Disable link check validation
LMIC_setLinkCheckMode(0);
// Set data rate and transmit power (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF10,20);
}
void loopLora() {
os_runloop_once();
}
void loraSetSF(uint sf) {
dr_t dr;
switch (sf) {
case 7: dr = DR_SF7; break;
case 8: dr = DR_SF8; break;
case 9: dr = DR_SF9; break;
case 10: dr = DR_SF10; break;
default:
dr = DR_SF10;
Log.Debug(F("Invalid SF value: %d" CR), sf);
break;
}
LMIC_setDrTxpow(dr,20);
}
<commit_msg>changed keys<commit_after>/*
* Note: LoRaWAN per sub-band duty-cycle limitation is enforced (1% in g1,
* 0.1% in g2).
*
* Change DEVADDR to a unique address!
* See http://thethingsnetwork.org/wiki/AddressSpace
*
* Do not forget to define the radio type correctly in config.h.
*/
#include <SPI.h>
#include "Lora.h"
#include "Logging.h"
#if defined(DISABLE_INVERT_IQ_ON_RX)
#error This example requires DISABLE_INVERT_IQ_ON_RX to be NOT set. Update \
config.h in the lmic library to set it.
#endif
// LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
// 2B7E151628AED2A6ABF7158809CF4F3C
//static const PROGMEM u1_t NWKSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
// LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the prototype TTN
// network initially.
//static const u1_t PROGMEM APPSKEY[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
//static const u4_t DEVADDR = 0x03FF0001 ; // <-- Change this address for every node!
// Franks keys:
const u1_t NWKSKEY[16] = { 0x48, 0xD6, 0x9F, 0x3D, 0x30, 0x91, 0x41, 0xE2, 0xF7, 0xBA, 0x46, 0xC8, 0xAE, 0x8A, 0x29, 0x19 };
const u1_t APPSKEY[16] = { 0x53, 0x20, 0x83, 0xA2, 0xB5, 0xDB, 0x86, 0xA3, 0x4D, 0xAC, 0xA0, 0xD0, 0x9B, 0xDE, 0x1B, 0x54 };
// AppSKey=532083A2B5DB86A34DACA0D09BDE1B54
// DevAddr=27266BDA Flags=0
// NwkSKey=48D69F3D309141E2F7BA46C8AE8A2919
// MSB Nwks { 0x48, 0xD6, 0x9F, 0x3D, 0x30, 0x91, 0x41, 0xE2, 0xF7, 0xBA, 0x46, 0xC8, 0xAE, 0x8A, 0x29, 0x19 }
// MSB Appskey { 0x53, 0x20, 0x83, 0xA2, 0xB5, 0xDB, 0x86, 0xA3, 0x4D, 0xAC, 0xA0, 0xD0, 0x9B, 0xDE, 0x1B, 0x54 }
// LoRaWAN end-device address (DevAddr)
// See http://thethingsnetwork.org/wiki/AddressSpace
const u4_t DEVADDR = 0x27266BDA; // <-- Change this address for every node!
// These callbacks are only used in over-the-air activation, so they are
// left empty here (we cannot leave them out completely unless
// DISABLE_JOIN is set in config.h, otherwise the linker will complain).
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 19,
.rxtx = LMIC_UNUSED_PIN,
.rst = 18,
.dio = {16, 5, 6}, // Moved dio0 from 17 because of overlapping ExtInt4 (pin6)
};
static osjob_t timeoutjob;
static void txtimeout_func(osjob_t *job) {
digitalWrite(LED_BUILTIN, LOW); // off
Log.Debug(F("Transmit Timeout" CR));
//txActive = false;
LMIC_clrTxData ();
}
bool loraSendBytes(uint8_t *data, uint16_t len) {
ostime_t t = os_getTime();
//os_setTimedCallback(&txjob, t + ms2osticks(100), tx_func);
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Log.Debug(F("OP_TXRXPEND, not sending" CR));
return false; // Did not enqueue
} else {
// Prepare upstream data transmission at the next possible time.
Log.Debug(F("Packet queued" CR));
digitalWrite(LED_BUILTIN, HIGH); // off
LMIC_setTxData2(1, data, len, 0);
}
// Timeout TX after 20 seconds
os_setTimedCallback(&timeoutjob, t + ms2osticks(20000), txtimeout_func);
return true;
}
void onEvent (ev_t ev) {
Log.Debug("%d: ", os_getTime());
switch(ev) {
case EV_SCAN_TIMEOUT:
Log.Debug(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Log.Debug(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Log.Debug(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Log.Debug(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Log.Debug(F("EV_JOINING"));
break;
case EV_JOINED:
Log.Debug(F("EV_JOINED"));
break;
case EV_RFU1:
Log.Debug(F("EV_RFU1"));
break;
case EV_JOIN_FAILED:
Log.Debug(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Log.Debug(F("EV_REJOIN_FAILED"));
break;
break;
case EV_TXCOMPLETE:
os_clearCallback(&timeoutjob);
Log.Debug(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
digitalWrite(LED_BUILTIN, LOW); // off
if(LMIC.dataLen) {
// data received in rx slot after tx
Log.Debug(F("Data Received: "));
u1_t *p = LMIC.frame+LMIC.dataBeg;
for (int i=0; i<LMIC.dataLen; ++i) {
Log.Debug("%x", *p++);
}
// Log.Debug("%*h", LMIC.dataLen, LMIC.frame+LMIC.dataBeg);
Log.Debug(CR);
}
break;
case EV_LOST_TSYNC:
Log.Debug(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Log.Debug(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Log.Debug(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Log.Debug(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Log.Debug(F("EV_LINK_ALIVE"));
break;
default:
Log.Debug(F("Unknown event"));
break;
}
Log.Debug(CR);
}
void setupLora() {
#ifdef VCC_ENABLE
// For Pinoccio Scout boards
pinMode(VCC_ENABLE, OUTPUT);
digitalWrite(VCC_ENABLE, HIGH);
delay(1000);
#endif
// LMIC init
os_init();
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Set static session parameters. Instead of dynamically establishing a session
// by joining the network, precomputed session parameters are provided.
#ifdef PROGMEM
// On AVR, these values are stored in flash and only copied to RAM
// once. Copy them to a temporary buffer here, LMIC_setSession will
// copy them into a buffer of its own again.
uint8_t appskey[sizeof(APPSKEY)];
uint8_t nwkskey[sizeof(NWKSKEY)];
memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
#else
// If not running an AVR with PROGMEM, just use the arrays directly
LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
#endif
#if defined(CFG_eu868)
// Set up the channels used by the Things Network, which corresponds
// to the defaults of most gateways. Without this, only three base
// channels from the LoRaWAN specification are used, which certainly
// works, so it is good for debugging, but can overload those
// frequencies, so be sure to configure the full frequency range of
// your network here (unless your network autoconfigures them).
// Setting up channels should happen after LMIC_setSession, as that
// configures the minimal channel set.
LMIC_setupChannel(0, 868100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(1, 868300000, DR_RANGE_MAP(DR_SF12, DR_SF7B), BAND_CENTI); // g-band
LMIC_setupChannel(2, 868500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(3, 867100000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(4, 867300000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(5, 867500000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(6, 867700000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(7, 867900000, DR_RANGE_MAP(DR_SF12, DR_SF7), BAND_CENTI); // g-band
LMIC_setupChannel(8, 868800000, DR_RANGE_MAP(DR_FSK, DR_FSK), BAND_MILLI); // g2-band
// TTN defines an additional channel at 869.525Mhz using SF9 for class B
// devices' ping slots. LMIC does not have an easy way to define set this
// frequency and support for class B is spotty and untested, so this
// frequency is not configured here.
#endif
LMIC_selectSubBand(1);
// Disable link check validation
LMIC_setLinkCheckMode(0);
// Set data rate and transmit power (note: txpow seems to be ignored by the library)
LMIC_setDrTxpow(DR_SF10,20);
}
void loopLora() {
os_runloop_once();
}
void loraSetSF(uint sf) {
dr_t dr;
switch (sf) {
case 7: dr = DR_SF7; break;
case 8: dr = DR_SF8; break;
case 9: dr = DR_SF9; break;
case 10: dr = DR_SF10; break;
default:
dr = DR_SF10;
Log.Debug(F("Invalid SF value: %d" CR), sf);
break;
}
LMIC_setDrTxpow(dr,20);
}
<|endoftext|> |
<commit_before>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <info@collabora.com>
* Copyright (C) 2011 Dominik Schmidt <kde@dominik-schmidt.de>
* Copyright (C) 2011 Thomas Richard <thomas.richard@proan.be>
*
* 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
*/
#include "add-account-assistant.h"
#include <KTp/wallet-utils.h>
#include "KCMTelepathyAccounts/abstract-account-parameters-widget.h"
#include "KCMTelepathyAccounts/abstract-account-ui.h"
#include "KCMTelepathyAccounts/account-edit-widget.h"
#include "KCMTelepathyAccounts/plugin-manager.h"
#include "KCMTelepathyAccounts/profile-item.h"
#include "KCMTelepathyAccounts/profile-list-model.h"
#include "KCMTelepathyAccounts/profile-select-widget.h"
#include "KCMTelepathyAccounts/simple-profile-select-widget.h"
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KPageWidgetItem>
#include <QtCore/QList>
#include <QtGui/QHBoxLayout>
#include <QtGui/QCheckBox>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/PendingAccount>
#include <TelepathyQt/PendingOperation>
class AddAccountAssistant::Private
{
public:
Private()
: currentProfileItem(0),
profileListModel(0),
profileSelectWidget(0),
simpleProfileSelectWidget(0),
accountEditWidget(0),
pageOne(0),
pageTwo(0),
pageThree(0)
{
}
Tp::AccountManagerPtr accountManager;
Tp::ConnectionManagerPtr connectionManager;
ProfileItem *currentProfileItem;
ProfileListModel *profileListModel;
ProfileSelectWidget *profileSelectWidget;
SimpleProfileSelectWidget *simpleProfileSelectWidget;
AccountEditWidget *accountEditWidget;
QWidget *pageThreeWidget;
KPageWidgetItem *pageOne;
KPageWidgetItem *pageTwo;
KPageWidgetItem *pageThree;
};
AddAccountAssistant::AddAccountAssistant(Tp::AccountManagerPtr accountManager, QWidget *parent)
: KAssistantDialog(parent),
d(new Private)
{
d->accountManager = accountManager;
// Set up the pages of the Assistant.
d->profileListModel = new ProfileListModel(this);
d->profileSelectWidget = new ProfileSelectWidget(d->profileListModel, this, true);
d->simpleProfileSelectWidget = new SimpleProfileSelectWidget(d->profileListModel, this);
d->pageOne = new KPageWidgetItem(d->simpleProfileSelectWidget);
d->pageTwo = new KPageWidgetItem(d->profileSelectWidget);
d->pageOne->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
d->pageTwo->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
setValid(d->pageOne, false);
setValid(d->pageTwo, false);
connect(d->profileSelectWidget,
SIGNAL(profileSelected(bool)),
SLOT(onProfileSelected(bool)));
connect(d->profileSelectWidget,
SIGNAL(profileChosen()),
SLOT(goToPageThree()));
connect(d->simpleProfileSelectWidget,
SIGNAL(profileChosen()),
SLOT(goToPageThree()));
connect(d->simpleProfileSelectWidget,
SIGNAL(othersChosen()),
SLOT(goToPageTwo()));
// we will build the page widget later, but the constructor of
// KPageWidgetItem requires the widget at this point, so...
d->pageThreeWidget = new QWidget(this);
new QHBoxLayout(d->pageThreeWidget);
d->pageThree = new KPageWidgetItem(d->pageThreeWidget);
d->pageThree->setHeader(i18n("Step 2: Fill in the required Parameters."));
addPage(d->pageOne);
addPage(d->pageTwo);
addPage(d->pageThree);
setAppropriate(d->pageTwo, false);
// TODO re-enable the help when we will have one
showButton(KDialog::Help, false);
}
AddAccountAssistant::~AddAccountAssistant()
{
delete d;
}
void AddAccountAssistant::goToPageTwo()
{
KAssistantDialog::setAppropriate(d->pageTwo, true);
KAssistantDialog::next();
}
void AddAccountAssistant::goToPageThree()
{
ProfileItem *selectedItem;
if (currentPage() == d->pageTwo) {
kDebug() << "Current Page seems to be page two";
selectedItem = d->profileSelectWidget->selectedProfile();
}
else {
kDebug() << "Current Page seems to be page one";
selectedItem = d->simpleProfileSelectWidget->selectedProfile();
}
// FIXME: untill packages for missing profiles aren't installed this needs to stay here
if (selectedItem != 0) {
// Set up the next page.
if (d->currentProfileItem != selectedItem) {
d->currentProfileItem = selectedItem;
d->connectionManager = Tp::ConnectionManager::create(selectedItem->cmName());
connect(d->connectionManager->becomeReady(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onConnectionManagerReady(Tp::PendingOperation*)));
}
else {
pageThree();
}
}
else {
KMessageBox::error(this, i18n("To connect to this IM network, you need to install additional plugins. Please install the telepathy-haze and telepathy-gabble packages using your package manager."),i18n("Missing Telepathy Connection Manager"));
}
}
void AddAccountAssistant::next()
{
// the next button is disabled on the first page
// so ::next is called from the second page
// so we go to page three now
goToPageThree();
}
void AddAccountAssistant::back()
{
// Disable pageTwo once we're going back to pageOne
if (currentPage() == d->pageTwo) {
KAssistantDialog::setAppropriate(d->pageTwo, false);
}
KAssistantDialog::back();
}
void AddAccountAssistant::accept()
{
// Check we are being called from page 3.
if (currentPage() != d->pageThree) {
kWarning() << "Called accept() from a non-final page :(.";
return;
}
// Get the parameter values.
QVariantMap values = d->accountEditWidget->parametersSet();
// Check all pages of parameters pass validation.
if (!d->accountEditWidget->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
Q_EMIT feedbackMessage(i18n("Failed to create account"),
d->accountEditWidget->errorMessage(),
KMessageWidget::Error);
return;
}
// FIXME: In some next version of tp-qt4 there should be a convenience class for this
// https://bugs.freedesktop.org/show_bug.cgi?id=33153
QVariantMap properties;
if (d->accountManager->supportedAccountProperties().contains(QLatin1String("org.freedesktop.Telepathy.Account.Service"))) {
properties.insert(QLatin1String("org.freedesktop.Telepathy.Account.Service"), d->currentProfileItem->serviceName());
}
if (d->accountManager->supportedAccountProperties().contains(QLatin1String("org.freedesktop.Telepathy.Account.Enabled"))) {
properties.insert(QLatin1String("org.freedesktop.Telepathy.Account.Enabled"), true);
}
// FIXME: Ask the user to submit a Display Name
QString displayName;
if (values.contains(QLatin1String("account"))) {
displayName = values[QLatin1String("account")].toString();
}
else {
displayName = d->currentProfileItem->protocolName();
}
//remove password values from being sent. These are stored by KWallet instead
//FIXME: This is a hack for jabber registration, we don't remove passwords - see Telepathy ML thread "Storing passwords in MC and regsitering new accounts"
//http://lists.freedesktop.org/archives/telepathy/2011-September/005747.html
if (!values.contains(QLatin1String("register"))) {
values.remove(QLatin1String("password"));
}
Tp::PendingAccount *pa = d->accountManager->createAccount(d->currentProfileItem->cmName(),
d->currentProfileItem->protocolName(),
displayName,
values,
properties);
connect(pa,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onAccountCreated(Tp::PendingOperation*)));
}
void AddAccountAssistant::reject()
{
// Emit a signal to tell the assistant launcher that it was cancelled.
Q_EMIT cancelled();
// Close the assistant
KAssistantDialog::reject();
}
void AddAccountAssistant::onAccountCreated(Tp::PendingOperation *op)
{
if (op->isError()) {
Q_EMIT feedbackMessage(i18n("Failed to create account"),
i18n("Possibly not all required fields are valid"),
KMessageWidget::Error);
kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage();
return;
}
// Get the PendingAccount.
Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op);
if (!pendingAccount) {
Q_EMIT feedbackMessage(i18n("Something went wrong with Telepathy"),
QString(),
KMessageWidget::Error);
kWarning() << "Method called with wrong type.";
return;
}
Tp::AccountPtr account = pendingAccount->account();
//save password to KWallet if needed
QVariantMap values = d->accountEditWidget->parametersSet();
if (values.contains(QLatin1String("password"))) {
KTp::WalletUtils::setAccountPassword(account, values[QLatin1String("password")].toString());
}
if (d->accountEditWidget->connectOnAdd()) {
account->setRequestedPresence(Tp::Presence::available());
}
account->setServiceName(d->currentProfileItem->serviceName());
KAssistantDialog::accept();
}
void AddAccountAssistant::onConnectionManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Creating ConnectionManager failed:" << op->errorName() << op->errorMessage();
}
if (!d->connectionManager->isValid()) {
kWarning() << "Invalid ConnectionManager";
}
pageThree();
}
void AddAccountAssistant::onProfileSelected(bool value)
{
//if a protocol is selected, enable the next button on the first page
setValid(d->pageTwo, value);
}
void AddAccountAssistant::pageThree()
{
// Get the protocol's parameters and values.
Tp::ProtocolInfo protocolInfo = d->connectionManager->protocol(d->currentProfileItem->protocolName());
Tp::ProtocolParameterList parameters = protocolInfo.parameters();
// Add the parameters to the model.
ParameterEditModel *parameterModel = new ParameterEditModel(this);
parameterModel->addItems(parameters, d->currentProfileItem->profile()->parameters());
// Delete account previous widget if it already existed.
if (d->accountEditWidget) {
d->accountEditWidget->deleteLater();
d->accountEditWidget = 0;
}
// Set up the account edit widget.
d->accountEditWidget = new AccountEditWidget(d->currentProfileItem->profile(),
parameterModel,
doConnectOnAdd,
d->pageThreeWidget);
connect(this,
SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)),
d->accountEditWidget,
SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)));
d->pageThreeWidget->layout()->addWidget(d->accountEditWidget);
KAssistantDialog::next();
}
#include "add-account-assistant.moc"
<commit_msg>Use display name in AddAccountAssistant<commit_after>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <info@collabora.com>
* Copyright (C) 2011 Dominik Schmidt <kde@dominik-schmidt.de>
* Copyright (C) 2011 Thomas Richard <thomas.richard@proan.be>
*
* 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
*/
#include "add-account-assistant.h"
#include <KTp/wallet-utils.h>
#include "KCMTelepathyAccounts/abstract-account-parameters-widget.h"
#include "KCMTelepathyAccounts/abstract-account-ui.h"
#include "KCMTelepathyAccounts/account-edit-widget.h"
#include "KCMTelepathyAccounts/plugin-manager.h"
#include "KCMTelepathyAccounts/profile-item.h"
#include "KCMTelepathyAccounts/profile-list-model.h"
#include "KCMTelepathyAccounts/profile-select-widget.h"
#include "KCMTelepathyAccounts/simple-profile-select-widget.h"
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KPageWidgetItem>
#include <QtCore/QList>
#include <QtGui/QHBoxLayout>
#include <QtGui/QCheckBox>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/PendingAccount>
#include <TelepathyQt/PendingOperation>
class AddAccountAssistant::Private
{
public:
Private()
: currentProfileItem(0),
profileListModel(0),
profileSelectWidget(0),
simpleProfileSelectWidget(0),
accountEditWidget(0),
pageOne(0),
pageTwo(0),
pageThree(0)
{
}
Tp::AccountManagerPtr accountManager;
Tp::ConnectionManagerPtr connectionManager;
ProfileItem *currentProfileItem;
ProfileListModel *profileListModel;
ProfileSelectWidget *profileSelectWidget;
SimpleProfileSelectWidget *simpleProfileSelectWidget;
AccountEditWidget *accountEditWidget;
QWidget *pageThreeWidget;
KPageWidgetItem *pageOne;
KPageWidgetItem *pageTwo;
KPageWidgetItem *pageThree;
};
AddAccountAssistant::AddAccountAssistant(Tp::AccountManagerPtr accountManager, QWidget *parent)
: KAssistantDialog(parent),
d(new Private)
{
d->accountManager = accountManager;
// Set up the pages of the Assistant.
d->profileListModel = new ProfileListModel(this);
d->profileSelectWidget = new ProfileSelectWidget(d->profileListModel, this, true);
d->simpleProfileSelectWidget = new SimpleProfileSelectWidget(d->profileListModel, this);
d->pageOne = new KPageWidgetItem(d->simpleProfileSelectWidget);
d->pageTwo = new KPageWidgetItem(d->profileSelectWidget);
d->pageOne->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
d->pageTwo->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
setValid(d->pageOne, false);
setValid(d->pageTwo, false);
connect(d->profileSelectWidget,
SIGNAL(profileSelected(bool)),
SLOT(onProfileSelected(bool)));
connect(d->profileSelectWidget,
SIGNAL(profileChosen()),
SLOT(goToPageThree()));
connect(d->simpleProfileSelectWidget,
SIGNAL(profileChosen()),
SLOT(goToPageThree()));
connect(d->simpleProfileSelectWidget,
SIGNAL(othersChosen()),
SLOT(goToPageTwo()));
// we will build the page widget later, but the constructor of
// KPageWidgetItem requires the widget at this point, so...
d->pageThreeWidget = new QWidget(this);
new QHBoxLayout(d->pageThreeWidget);
d->pageThree = new KPageWidgetItem(d->pageThreeWidget);
d->pageThree->setHeader(i18n("Step 2: Fill in the required Parameters."));
addPage(d->pageOne);
addPage(d->pageTwo);
addPage(d->pageThree);
setAppropriate(d->pageTwo, false);
// TODO re-enable the help when we will have one
showButton(KDialog::Help, false);
}
AddAccountAssistant::~AddAccountAssistant()
{
delete d;
}
void AddAccountAssistant::goToPageTwo()
{
KAssistantDialog::setAppropriate(d->pageTwo, true);
KAssistantDialog::next();
}
void AddAccountAssistant::goToPageThree()
{
ProfileItem *selectedItem;
if (currentPage() == d->pageTwo) {
kDebug() << "Current Page seems to be page two";
selectedItem = d->profileSelectWidget->selectedProfile();
}
else {
kDebug() << "Current Page seems to be page one";
selectedItem = d->simpleProfileSelectWidget->selectedProfile();
}
// FIXME: untill packages for missing profiles aren't installed this needs to stay here
if (selectedItem != 0) {
// Set up the next page.
if (d->currentProfileItem != selectedItem) {
d->currentProfileItem = selectedItem;
d->connectionManager = Tp::ConnectionManager::create(selectedItem->cmName());
connect(d->connectionManager->becomeReady(),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onConnectionManagerReady(Tp::PendingOperation*)));
}
else {
pageThree();
}
}
else {
KMessageBox::error(this, i18n("To connect to this IM network, you need to install additional plugins. Please install the telepathy-haze and telepathy-gabble packages using your package manager."),i18n("Missing Telepathy Connection Manager"));
}
}
void AddAccountAssistant::next()
{
// the next button is disabled on the first page
// so ::next is called from the second page
// so we go to page three now
goToPageThree();
}
void AddAccountAssistant::back()
{
// Disable pageTwo once we're going back to pageOne
if (currentPage() == d->pageTwo) {
KAssistantDialog::setAppropriate(d->pageTwo, false);
}
KAssistantDialog::back();
}
void AddAccountAssistant::accept()
{
// Check we are being called from page 3.
if (currentPage() != d->pageThree) {
kWarning() << "Called accept() from a non-final page :(.";
return;
}
// Get the parameter values.
QVariantMap values = d->accountEditWidget->parametersSet();
// Check all pages of parameters pass validation.
if (!d->accountEditWidget->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
Q_EMIT feedbackMessage(i18n("Failed to create account"),
d->accountEditWidget->errorMessage(),
KMessageWidget::Error);
return;
}
// FIXME: In some next version of tp-qt4 there should be a convenience class for this
// https://bugs.freedesktop.org/show_bug.cgi?id=33153
QVariantMap properties;
if (d->accountManager->supportedAccountProperties().contains(QLatin1String("org.freedesktop.Telepathy.Account.Service"))) {
properties.insert(QLatin1String("org.freedesktop.Telepathy.Account.Service"), d->currentProfileItem->serviceName());
}
if (d->accountManager->supportedAccountProperties().contains(QLatin1String("org.freedesktop.Telepathy.Account.Enabled"))) {
properties.insert(QLatin1String("org.freedesktop.Telepathy.Account.Enabled"), true);
}
//remove password values from being sent. These are stored by KWallet instead
//FIXME: This is a hack for jabber registration, we don't remove passwords - see Telepathy ML thread "Storing passwords in MC and regsitering new accounts"
//http://lists.freedesktop.org/archives/telepathy/2011-September/005747.html
if (!values.contains(QLatin1String("register"))) {
values.remove(QLatin1String("password"));
}
Tp::PendingAccount *pa = d->accountManager->createAccount(d->currentProfileItem->cmName(),
d->currentProfileItem->protocolName(),
d->accountEditWidget->displayName(),
values,
properties);
connect(pa,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onAccountCreated(Tp::PendingOperation*)));
}
void AddAccountAssistant::reject()
{
// Emit a signal to tell the assistant launcher that it was cancelled.
Q_EMIT cancelled();
// Close the assistant
KAssistantDialog::reject();
}
void AddAccountAssistant::onAccountCreated(Tp::PendingOperation *op)
{
if (op->isError()) {
Q_EMIT feedbackMessage(i18n("Failed to create account"),
i18n("Possibly not all required fields are valid"),
KMessageWidget::Error);
kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage();
return;
}
// Get the PendingAccount.
Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op);
if (!pendingAccount) {
Q_EMIT feedbackMessage(i18n("Something went wrong with Telepathy"),
QString(),
KMessageWidget::Error);
kWarning() << "Method called with wrong type.";
return;
}
Tp::AccountPtr account = pendingAccount->account();
//save password to KWallet if needed
QVariantMap values = d->accountEditWidget->parametersSet();
if (values.contains(QLatin1String("password"))) {
KTp::WalletUtils::setAccountPassword(account, values[QLatin1String("password")].toString());
}
if (d->accountEditWidget->connectOnAdd()) {
account->setRequestedPresence(Tp::Presence::available());
}
account->setServiceName(d->currentProfileItem->serviceName());
KAssistantDialog::accept();
}
void AddAccountAssistant::onConnectionManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Creating ConnectionManager failed:" << op->errorName() << op->errorMessage();
}
if (!d->connectionManager->isValid()) {
kWarning() << "Invalid ConnectionManager";
}
pageThree();
}
void AddAccountAssistant::onProfileSelected(bool value)
{
//if a protocol is selected, enable the next button on the first page
setValid(d->pageTwo, value);
}
void AddAccountAssistant::pageThree()
{
// Get the protocol's parameters and values.
Tp::ProtocolInfo protocolInfo = d->connectionManager->protocol(d->currentProfileItem->protocolName());
Tp::ProtocolParameterList parameters = protocolInfo.parameters();
// Add the parameters to the model.
ParameterEditModel *parameterModel = new ParameterEditModel(this);
parameterModel->addItems(parameters, d->currentProfileItem->profile()->parameters());
// Delete account previous widget if it already existed.
if (d->accountEditWidget) {
d->accountEditWidget->deleteLater();
d->accountEditWidget = 0;
}
// Set up the account edit widget.
d->accountEditWidget = new AccountEditWidget(d->currentProfileItem->profile(),
parameterModel,
doConnectOnAdd,
d->pageThreeWidget);
connect(this,
SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)),
d->accountEditWidget,
SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)));
d->pageThreeWidget->layout()->addWidget(d->accountEditWidget);
KAssistantDialog::next();
}
#include "add-account-assistant.moc"
<|endoftext|> |
<commit_before>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
*
* 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
*/
#include "add-account-assistant.h"
#include "KCMTelepathyAccounts/abstract-account-parameters-widget.h"
#include "KCMTelepathyAccounts/abstract-account-ui.h"
#include "KCMTelepathyAccounts/connection-manager-item.h"
#include "KCMTelepathyAccounts/mandatory-parameter-edit-widget.h"
#include "KCMTelepathyAccounts/optional-parameter-edit-widget.h"
#include "KCMTelepathyAccounts/plugin-manager.h"
#include "KCMTelepathyAccounts/protocol-item.h"
#include "KCMTelepathyAccounts/protocol-select-widget.h"
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KPageWidgetItem>
#include <KTabWidget>
#include <QtCore/QList>
#include <TelepathyQt4/PendingAccount>
#include <TelepathyQt4/PendingOperation>
class AddAccountAssistant::Private
{
public:
Private()
: protocolSelectWidget(0),
tabWidget(0),
mandatoryParametersWidget(0),
pageOne(0),
pageTwo(0)
{
kDebug();
}
Tp::AccountManagerPtr accountManager;
Tp::AccountPtr account;
ProtocolSelectWidget *protocolSelectWidget;
KTabWidget *tabWidget;
AbstractAccountParametersWidget *mandatoryParametersWidget;
QList<AbstractAccountParametersWidget*> optionalParametersWidgets;
KPageWidgetItem *pageOne;
KPageWidgetItem *pageTwo;
QString mandatoryPageDesc;
QList<QString> optionalPageDesc;
};
AddAccountAssistant::AddAccountAssistant(Tp::AccountManagerPtr accountManager, QWidget *parent)
: KAssistantDialog(parent),
d(new Private)
{
kDebug();
d->accountManager = accountManager;
// Set up the pages of the Assistant.
d->protocolSelectWidget = new ProtocolSelectWidget(this);
d->pageOne = new KPageWidgetItem(d->protocolSelectWidget);
d->pageOne->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
setValid(d->pageOne, false);
connect(d->protocolSelectWidget,
SIGNAL(protocolGotSelected(bool)),
SLOT(onProtocolSelected(bool)));
connect(d->protocolSelectWidget,
SIGNAL(protocolDoubleClicked()),
SLOT(onProtocolDoubleClicked()),
Qt::DirectConnection);
d->tabWidget = new KTabWidget(this);
d->pageTwo = new KPageWidgetItem(d->tabWidget);
d->pageTwo->setHeader(i18n("Step 2: Fill in the required Parameters."));
addPage(d->pageOne);
addPage(d->pageTwo);
resize(QSize(400, 480));
}
AddAccountAssistant::~AddAccountAssistant()
{
kDebug();
delete d;
}
// FIXME: This method *works*, but is really not very elegant. I don't want to waste time tidying it
// up at the moment, but I'm sure it could have a *lot* less code in it if it were tidied up at some
// point in the future.
void AddAccountAssistant::next()
{
kDebug();
// Check which page we are on.
if (currentPage() == d->pageOne) {
kDebug() << "Current page: Page 1.";
Q_ASSERT(d->protocolSelectWidget->selectedProtocol());
// Set up the next page.
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
ConnectionManagerItem *cmItem = qobject_cast<ConnectionManagerItem*>(item->parent());
if (!cmItem) {
kWarning() << "cmItem is invalid.";
}
QString connectionManager = cmItem->connectionManager()->name();
QString protocol = item->protocol();
// Get the AccountsUi for the plugin, and get the optional parameter widgets for it.
AbstractAccountUi *ui = PluginManager::instance()->accountUiForProtocol(connectionManager,
protocol);
// Delete the widgets for the next page if they already exist
if (d->mandatoryParametersWidget) {
d->mandatoryParametersWidget->deleteLater();
d->mandatoryParametersWidget = 0;
}
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
if (w) {
w->deleteLater();
}
}
d->optionalParametersWidgets.clear();
// Set up the Mandatory Parameters page
Tp::ProtocolParameterList mandatoryParameters = item->mandatoryParameters();
Tp::ProtocolParameterList mandatoryParametersLeft = item->mandatoryParameters();
// Get the list of optional parameters for later
Tp::ProtocolParameterList optionalParameters = item->optionalParameters();
Tp::ProtocolParameterList optionalParametersLeft = item->optionalParameters();
// HACK: Hack round gabble making password optional (FIXME once we sort out the plugin system)
Tp::ProtocolParameter *passwordParameter = 0;
foreach (Tp::ProtocolParameter *oP, optionalParameters) {
if (oP->name() == "password") {
passwordParameter = oP;
}
}
// If the password parameter is optional, add it to the mandatory lot for now instead.
optionalParameters.removeAll(passwordParameter);
optionalParametersLeft.removeAll(passwordParameter);
mandatoryParameters.append(passwordParameter);
mandatoryParametersLeft.append(passwordParameter);
// HACK ends
// Create the custom UI or generic UI depending on available parameters.
if (ui) {
// UI does exist, set it up.
AbstractAccountParametersWidget *widget = ui->mandatoryParametersWidget(mandatoryParameters);
QMap<QString, QVariant::Type> manParams = ui->supportedMandatoryParameters();
QMap<QString, QVariant::Type>::const_iterator manIter = manParams.constBegin();
while(manIter != manParams.constEnd()) {
foreach (Tp::ProtocolParameter *parameter, mandatoryParameters) {
// If the parameter is not
if ((parameter->name() == manIter.key()) &&
(parameter->type() == manIter.value())) {
mandatoryParametersLeft.removeAll(parameter);
}
}
++manIter;
}
if (mandatoryParametersLeft.isEmpty()) {
d->mandatoryParametersWidget = widget;
} else {
// FIXME: At the moment, if the custom widget can't handle all the mandatory
// parameters we fall back to the generic one for all of them. It might be nicer
// to have the custom UI for as many as possible, and stick a small generic one
// underneath for those parameters it doesn't handle.
widget->deleteLater();
widget = 0;
}
}
if (!d->mandatoryParametersWidget) {
d->mandatoryParametersWidget = new MandatoryParameterEditWidget(
item->mandatoryParameters(), QVariantMap(), d->tabWidget);
}
if(d->mandatoryPageDesc.isEmpty())
d->tabWidget->addTab(d->mandatoryParametersWidget, i18n("Mandatory Parameters"));
else
d->tabWidget->addTab(d->mandatoryParametersWidget, d->mandatoryPageDesc);
int pageIndex = 0;
// Check if the AbstractAccountUi exists. If not then we use the autogenerated UI for
// everything.
if (ui) {
// UI Does exist, set it up.
QList<AbstractAccountParametersWidget*> widgets = ui->optionalParametersWidgets(optionalParameters);
// Remove all handled parameters from the optionalParameters list.
QMap<QString, QVariant::Type> opParams = ui->supportedOptionalParameters();
QMap<QString, QVariant::Type>::const_iterator opIter = opParams.constBegin();
while(opIter != opParams.constEnd()) {
foreach (Tp::ProtocolParameter *parameter, optionalParameters) {
// If the parameter is not
if ((parameter->name() == opIter.key()) &&
(parameter->type() == opIter.value())) {
optionalParametersLeft.removeAll(parameter);
}
}
++opIter;
}
foreach (AbstractAccountParametersWidget *widget, widgets) {
d->optionalParametersWidgets.append(widget);
int indexOf = widgets.indexOf(widget);
QString description = i18n("Optional parameter");
if(indexOf < d->optionalPageDesc.size())
description = d->optionalPageDesc.at(indexOf);
d->tabWidget->addTab(widget, description);
pageIndex++;
}
}
// Show the generic UI if optionalParameters is not empty.
if (optionalParametersLeft.size() > 0) {
OptionalParameterEditWidget *opew =
new OptionalParameterEditWidget(optionalParametersLeft,
QVariantMap(),
d->tabWidget);
d->optionalParametersWidgets.append(opew);
if(pageIndex < d->optionalPageDesc.size())
d->tabWidget->addTab(opew, d->optionalPageDesc.at(pageIndex));
else
d->tabWidget->addTab(opew, i18n("Optional Parameters"));
}
KAssistantDialog::next();
}
}
void AddAccountAssistant::accept()
{
kDebug();
// Check we are being called from page 2.
if (currentPage() != d->pageTwo) {
kWarning() << "Called accept() from a non-final page :(.";
return;
}
// Check all pages of parameters pass validation.
if (!d->mandatoryParametersWidget->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
return;
}
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
if (!w->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
return;
}
}
// Get the mandatory parameters.
QMap<Tp::ProtocolParameter*, QVariant> mandatoryParameterValues;
mandatoryParameterValues = d->mandatoryParametersWidget->parameterValues();
// Get the optional properties
QMap<Tp::ProtocolParameter*, QVariant> optionalParameterValues;
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
QMap<Tp::ProtocolParameter*, QVariant> parameters = w->parameterValues();
QMap<Tp::ProtocolParameter*, QVariant>::const_iterator i = parameters.constBegin();
while (i != parameters.constEnd()) {
if (!optionalParameterValues.contains(i.key())) {
optionalParameterValues.insert(i.key(), i.value());
} else {
kWarning() << "Parameter:" << i.key()->name() << "is already in the map.";
}
++i;
}
continue;
}
// Get the ProtocolItem that was selected and the corresponding ConnectionManagerItem.
ProtocolItem *protocolItem = d->protocolSelectWidget->selectedProtocol();
ConnectionManagerItem *connectionManagerItem = qobject_cast<ConnectionManagerItem*>(protocolItem->parent());
if (!connectionManagerItem) {
kWarning() << "Invalid ConnectionManager item.";
return;
}
// Merge the parameters into a QVariantMap for submitting to the Telepathy AM.
QVariantMap parameters;
foreach (Tp::ProtocolParameter *pp, mandatoryParameterValues.keys()) {
QVariant value = mandatoryParameterValues.value(pp);
// Don't try and add empty parameters or ones where the default value is still set.
if ((!value.isNull()) && (value != pp->defaultValue())) {
// Check for params where they are empty and the default is null.
if (pp->type() == QVariant::String) {
if ((pp->defaultValue() == QVariant()) && (value.toString().isEmpty())) {
continue;
}
}
parameters.insert(pp->name(), value);
}
}
foreach (Tp::ProtocolParameter *pp, optionalParameterValues.keys()) {
QVariant value = optionalParameterValues.value(pp);
// Don't try and add empty parameters or ones where the default value is still set.
if ((!value.isNull()) && (value != pp->defaultValue())) {
// Check for params where they are empty and the default is null.
if (pp->type() == QVariant::String) {
if ((pp->defaultValue() == QVariant()) && (value.toString().isEmpty())) {
continue;
}
}
parameters.insert(pp->name(), value);
}
}
// kDebug() << "Parameters to add with:" << parameters;
// FIXME: Ask the user to submit a Display Name
Tp::PendingAccount *pa = d->accountManager->createAccount(connectionManagerItem->connectionManager()->name(),
protocolItem->protocol(),
parameters.value("account").toString(),
parameters);
connect(pa,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onAccountCreated(Tp::PendingOperation*)));
}
void AddAccountAssistant::reject()
{
kDebug();
// Emit a signal to tell the assistant launcher that it was cancelled.
Q_EMIT cancelled();
// Close the assistant
KAssistantDialog::reject();
}
void AddAccountAssistant::onAccountCreated(Tp::PendingOperation *op)
{
kDebug();
if (op->isError()) {
// TODO: User feedback in this case.
kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage();
return;
}
// Get the PendingAccount.
Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op);
if (!pendingAccount) {
// TODO: User visible feedback
kWarning() << "Method called with wrong type.";
return;
}
// Get the account pointer.
d->account = pendingAccount->account();
kDebug() << "Calling set enabled.";
connect(d->account->setEnabled(true),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onSetEnabledFinished(Tp::PendingOperation*)));
}
void AddAccountAssistant::onSetEnabledFinished(Tp::PendingOperation *op)
{
kDebug();
if (op->isError()) {
// TODO: User feedback in this case.
kWarning() << "Enabling Account failed:" << op->errorName() << op->errorMessage();
return;
}
KAssistantDialog::accept();
}
void AddAccountAssistant::onProtocolSelected(bool value)
{
kDebug();
//if a protocol is selected, enable the next button on the first page
setValid(d->pageOne, value);
if(value)
{
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
emit protocolSelected(item->protocol(), item->localizedName());
}
}
void AddAccountAssistant::onProtocolDoubleClicked()
{
kDebug();
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
emit protocolSelected(item->protocol(), item->localizedName());
next();
}
void AddAccountAssistant::onTitleForCustomPages(QString mandatoryPage, QList<QString> optionalPage)
{
kDebug();
d->mandatoryPageDesc.clear();
d->optionalPageDesc.clear();
d->mandatoryPageDesc = mandatoryPage;
d->optionalPageDesc = optionalPage;
}
#include "add-account-assistant.moc"
<commit_msg>Set account icon on account creation.<commit_after>/*
* This file is part of telepathy-accounts-kcm
*
* Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
*
* 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
*/
#include "add-account-assistant.h"
#include "KCMTelepathyAccounts/abstract-account-parameters-widget.h"
#include "KCMTelepathyAccounts/abstract-account-ui.h"
#include "KCMTelepathyAccounts/connection-manager-item.h"
#include "KCMTelepathyAccounts/mandatory-parameter-edit-widget.h"
#include "KCMTelepathyAccounts/optional-parameter-edit-widget.h"
#include "KCMTelepathyAccounts/plugin-manager.h"
#include "KCMTelepathyAccounts/protocol-item.h"
#include "KCMTelepathyAccounts/protocol-select-widget.h"
#include <KDebug>
#include <KLocale>
#include <KMessageBox>
#include <KPageWidgetItem>
#include <KTabWidget>
#include <QtCore/QList>
#include <TelepathyQt4/PendingAccount>
#include <TelepathyQt4/PendingOperation>
class AddAccountAssistant::Private
{
public:
Private()
: protocolSelectWidget(0),
tabWidget(0),
mandatoryParametersWidget(0),
pageOne(0),
pageTwo(0)
{
kDebug();
}
Tp::AccountManagerPtr accountManager;
Tp::AccountPtr account;
ProtocolSelectWidget *protocolSelectWidget;
KTabWidget *tabWidget;
AbstractAccountParametersWidget *mandatoryParametersWidget;
QList<AbstractAccountParametersWidget*> optionalParametersWidgets;
KPageWidgetItem *pageOne;
KPageWidgetItem *pageTwo;
QString mandatoryPageDesc;
QList<QString> optionalPageDesc;
};
AddAccountAssistant::AddAccountAssistant(Tp::AccountManagerPtr accountManager, QWidget *parent)
: KAssistantDialog(parent),
d(new Private)
{
kDebug();
d->accountManager = accountManager;
// Set up the pages of the Assistant.
d->protocolSelectWidget = new ProtocolSelectWidget(this);
d->pageOne = new KPageWidgetItem(d->protocolSelectWidget);
d->pageOne->setHeader(i18n("Step 1: Select an Instant Messaging Network."));
setValid(d->pageOne, false);
connect(d->protocolSelectWidget,
SIGNAL(protocolGotSelected(bool)),
SLOT(onProtocolSelected(bool)));
connect(d->protocolSelectWidget,
SIGNAL(protocolDoubleClicked()),
SLOT(onProtocolDoubleClicked()),
Qt::DirectConnection);
d->tabWidget = new KTabWidget(this);
d->pageTwo = new KPageWidgetItem(d->tabWidget);
d->pageTwo->setHeader(i18n("Step 2: Fill in the required Parameters."));
addPage(d->pageOne);
addPage(d->pageTwo);
resize(QSize(400, 480));
}
AddAccountAssistant::~AddAccountAssistant()
{
kDebug();
delete d;
}
// FIXME: This method *works*, but is really not very elegant. I don't want to waste time tidying it
// up at the moment, but I'm sure it could have a *lot* less code in it if it were tidied up at some
// point in the future.
void AddAccountAssistant::next()
{
kDebug();
// Check which page we are on.
if (currentPage() == d->pageOne) {
kDebug() << "Current page: Page 1.";
Q_ASSERT(d->protocolSelectWidget->selectedProtocol());
// Set up the next page.
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
ConnectionManagerItem *cmItem = qobject_cast<ConnectionManagerItem*>(item->parent());
if (!cmItem) {
kWarning() << "cmItem is invalid.";
}
QString connectionManager = cmItem->connectionManager()->name();
QString protocol = item->protocol();
// Get the AccountsUi for the plugin, and get the optional parameter widgets for it.
AbstractAccountUi *ui = PluginManager::instance()->accountUiForProtocol(connectionManager,
protocol);
// Delete the widgets for the next page if they already exist
if (d->mandatoryParametersWidget) {
d->mandatoryParametersWidget->deleteLater();
d->mandatoryParametersWidget = 0;
}
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
if (w) {
w->deleteLater();
}
}
d->optionalParametersWidgets.clear();
// Set up the Mandatory Parameters page
Tp::ProtocolParameterList mandatoryParameters = item->mandatoryParameters();
Tp::ProtocolParameterList mandatoryParametersLeft = item->mandatoryParameters();
// Get the list of optional parameters for later
Tp::ProtocolParameterList optionalParameters = item->optionalParameters();
Tp::ProtocolParameterList optionalParametersLeft = item->optionalParameters();
// HACK: Hack round gabble making password optional (FIXME once we sort out the plugin system)
Tp::ProtocolParameter *passwordParameter = 0;
foreach (Tp::ProtocolParameter *oP, optionalParameters) {
if (oP->name() == "password") {
passwordParameter = oP;
}
}
// If the password parameter is optional, add it to the mandatory lot for now instead.
optionalParameters.removeAll(passwordParameter);
optionalParametersLeft.removeAll(passwordParameter);
mandatoryParameters.append(passwordParameter);
mandatoryParametersLeft.append(passwordParameter);
// HACK ends
// Create the custom UI or generic UI depending on available parameters.
if (ui) {
// UI does exist, set it up.
AbstractAccountParametersWidget *widget = ui->mandatoryParametersWidget(mandatoryParameters);
QMap<QString, QVariant::Type> manParams = ui->supportedMandatoryParameters();
QMap<QString, QVariant::Type>::const_iterator manIter = manParams.constBegin();
while(manIter != manParams.constEnd()) {
foreach (Tp::ProtocolParameter *parameter, mandatoryParameters) {
// If the parameter is not
if ((parameter->name() == manIter.key()) &&
(parameter->type() == manIter.value())) {
mandatoryParametersLeft.removeAll(parameter);
}
}
++manIter;
}
if (mandatoryParametersLeft.isEmpty()) {
d->mandatoryParametersWidget = widget;
} else {
// FIXME: At the moment, if the custom widget can't handle all the mandatory
// parameters we fall back to the generic one for all of them. It might be nicer
// to have the custom UI for as many as possible, and stick a small generic one
// underneath for those parameters it doesn't handle.
widget->deleteLater();
widget = 0;
}
}
if (!d->mandatoryParametersWidget) {
d->mandatoryParametersWidget = new MandatoryParameterEditWidget(
item->mandatoryParameters(), QVariantMap(), d->tabWidget);
}
if(d->mandatoryPageDesc.isEmpty())
d->tabWidget->addTab(d->mandatoryParametersWidget, i18n("Mandatory Parameters"));
else
d->tabWidget->addTab(d->mandatoryParametersWidget, d->mandatoryPageDesc);
int pageIndex = 0;
// Check if the AbstractAccountUi exists. If not then we use the autogenerated UI for
// everything.
if (ui) {
// UI Does exist, set it up.
QList<AbstractAccountParametersWidget*> widgets = ui->optionalParametersWidgets(optionalParameters);
// Remove all handled parameters from the optionalParameters list.
QMap<QString, QVariant::Type> opParams = ui->supportedOptionalParameters();
QMap<QString, QVariant::Type>::const_iterator opIter = opParams.constBegin();
while(opIter != opParams.constEnd()) {
foreach (Tp::ProtocolParameter *parameter, optionalParameters) {
// If the parameter is not
if ((parameter->name() == opIter.key()) &&
(parameter->type() == opIter.value())) {
optionalParametersLeft.removeAll(parameter);
}
}
++opIter;
}
foreach (AbstractAccountParametersWidget *widget, widgets) {
d->optionalParametersWidgets.append(widget);
int indexOf = widgets.indexOf(widget);
QString description = i18n("Optional parameter");
if(indexOf < d->optionalPageDesc.size())
description = d->optionalPageDesc.at(indexOf);
d->tabWidget->addTab(widget, description);
pageIndex++;
}
}
// Show the generic UI if optionalParameters is not empty.
if (optionalParametersLeft.size() > 0) {
OptionalParameterEditWidget *opew =
new OptionalParameterEditWidget(optionalParametersLeft,
QVariantMap(),
d->tabWidget);
d->optionalParametersWidgets.append(opew);
if(pageIndex < d->optionalPageDesc.size())
d->tabWidget->addTab(opew, d->optionalPageDesc.at(pageIndex));
else
d->tabWidget->addTab(opew, i18n("Optional Parameters"));
}
KAssistantDialog::next();
}
}
void AddAccountAssistant::accept()
{
kDebug();
// Check we are being called from page 2.
if (currentPage() != d->pageTwo) {
kWarning() << "Called accept() from a non-final page :(.";
return;
}
// Check all pages of parameters pass validation.
if (!d->mandatoryParametersWidget->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
return;
}
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
if (!w->validateParameterValues()) {
kDebug() << "A widget failed parameter validation. Not accepting wizard.";
return;
}
}
// Get the mandatory parameters.
QMap<Tp::ProtocolParameter*, QVariant> mandatoryParameterValues;
mandatoryParameterValues = d->mandatoryParametersWidget->parameterValues();
// Get the optional properties
QMap<Tp::ProtocolParameter*, QVariant> optionalParameterValues;
foreach (AbstractAccountParametersWidget *w, d->optionalParametersWidgets) {
QMap<Tp::ProtocolParameter*, QVariant> parameters = w->parameterValues();
QMap<Tp::ProtocolParameter*, QVariant>::const_iterator i = parameters.constBegin();
while (i != parameters.constEnd()) {
if (!optionalParameterValues.contains(i.key())) {
optionalParameterValues.insert(i.key(), i.value());
} else {
kWarning() << "Parameter:" << i.key()->name() << "is already in the map.";
}
++i;
}
continue;
}
// Get the ProtocolItem that was selected and the corresponding ConnectionManagerItem.
ProtocolItem *protocolItem = d->protocolSelectWidget->selectedProtocol();
ConnectionManagerItem *connectionManagerItem = qobject_cast<ConnectionManagerItem*>(protocolItem->parent());
if (!connectionManagerItem) {
kWarning() << "Invalid ConnectionManager item.";
return;
}
// Merge the parameters into a QVariantMap for submitting to the Telepathy AM.
QVariantMap parameters;
foreach (Tp::ProtocolParameter *pp, mandatoryParameterValues.keys()) {
QVariant value = mandatoryParameterValues.value(pp);
// Don't try and add empty parameters or ones where the default value is still set.
if ((!value.isNull()) && (value != pp->defaultValue())) {
// Check for params where they are empty and the default is null.
if (pp->type() == QVariant::String) {
if ((pp->defaultValue() == QVariant()) && (value.toString().isEmpty())) {
continue;
}
}
parameters.insert(pp->name(), value);
}
}
foreach (Tp::ProtocolParameter *pp, optionalParameterValues.keys()) {
QVariant value = optionalParameterValues.value(pp);
// Don't try and add empty parameters or ones where the default value is still set.
if ((!value.isNull()) && (value != pp->defaultValue())) {
// Check for params where they are empty and the default is null.
if (pp->type() == QVariant::String) {
if ((pp->defaultValue() == QVariant()) && (value.toString().isEmpty())) {
continue;
}
}
parameters.insert(pp->name(), value);
}
}
// kDebug() << "Parameters to add with:" << parameters;
// FIXME: Ask the user to submit a Display Name
Tp::PendingAccount *pa = d->accountManager->createAccount(connectionManagerItem->connectionManager()->name(),
protocolItem->protocol(),
parameters.value("account").toString(),
parameters);
connect(pa,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onAccountCreated(Tp::PendingOperation*)));
}
void AddAccountAssistant::reject()
{
kDebug();
// Emit a signal to tell the assistant launcher that it was cancelled.
Q_EMIT cancelled();
// Close the assistant
KAssistantDialog::reject();
}
void AddAccountAssistant::onAccountCreated(Tp::PendingOperation *op)
{
kDebug();
if (op->isError()) {
// TODO: User feedback in this case.
kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage();
return;
}
// Get the PendingAccount.
Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op);
if (!pendingAccount) {
// TODO: User visible feedback
kWarning() << "Method called with wrong type.";
return;
}
// Get the account pointer.
d->account = pendingAccount->account();
// Set the account icon
QString icon = QString("im-%1").arg(d->account->protocolName());
kDebug() << "Set account icon to: " << icon;
d->account->setIcon(icon);
kDebug() << "Calling set enabled.";
connect(d->account->setEnabled(true),
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onSetEnabledFinished(Tp::PendingOperation*)));
}
void AddAccountAssistant::onSetEnabledFinished(Tp::PendingOperation *op)
{
kDebug();
if (op->isError()) {
// TODO: User feedback in this case.
kWarning() << "Enabling Account failed:" << op->errorName() << op->errorMessage();
return;
}
KAssistantDialog::accept();
}
void AddAccountAssistant::onProtocolSelected(bool value)
{
kDebug();
//if a protocol is selected, enable the next button on the first page
setValid(d->pageOne, value);
if(value)
{
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
emit protocolSelected(item->protocol(), item->localizedName());
}
}
void AddAccountAssistant::onProtocolDoubleClicked()
{
kDebug();
ProtocolItem *item = d->protocolSelectWidget->selectedProtocol();
emit protocolSelected(item->protocol(), item->localizedName());
next();
}
void AddAccountAssistant::onTitleForCustomPages(QString mandatoryPage, QList<QString> optionalPage)
{
kDebug();
d->mandatoryPageDesc.clear();
d->optionalPageDesc.clear();
d->mandatoryPageDesc = mandatoryPage;
d->optionalPageDesc = optionalPage;
}
#include "add-account-assistant.moc"
<|endoftext|> |
<commit_before>/* <x0/request.hpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
*/
#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/fileinfo.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>
namespace x0 {
//! \addtogroup core
//@{
/**
* \brief a client HTTP reuqest object, holding the parsed x0 request data.
*
* \see header, response, connection, server
*/
struct request
{
public:
class reader;
public:
explicit request(x0::connection& connection);
/// the TCP/IP connection this request has been sent through
x0::connection& connection;
public: // request properties
/// HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
std::string method;
/// unparsed request uri
std::string uri;
/// decoded path-part
std::string path;
/// the final entity to be served, for example the full path to the file on disk.
fileinfo_ptr fileinfo;
/// decoded query-part
std::string query;
/// HTTP protocol version major part that this request was formed in
int http_version_major;
/// HTTP protocol version minor part that this request was formed in
int http_version_minor;
/// request headers
std::vector<x0::header> headers;
/** retrieve value of a given request header */
std::string header(const std::string& name) const;
/// body
std::string body;
public: // accumulated request data
/// username this client has authenticated with.
std::string username;
/// the document root directory for this request.
std::string document_root;
// std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified.
// std::shared_ptr<range_def> range; //!< parsed "Range" request header
public: // utility methods
bool supports_protocol(int major, int minor) const;
std::string hostid() const;
};
/**
* \brief implements the HTTP request parser.
*
* \see request, connection
*/
class request::reader
{
public:
enum state
{
method_start,
method,
uri_start,
uri,
http_version_h,
http_version_t_1,
http_version_t_2,
http_version_p,
http_version_slash,
http_version_major_start,
http_version_major,
http_version_minor_start,
http_version_minor,
expecting_newline_1,
header_line_start,
header_lws,
header_name,
space_before_header_value,
header_value,
expecting_newline_2,
expecting_newline_3,
reading_body
};
private:
state state_;
std::string buf_;
private:
static inline bool is_char(int ch);
static inline bool is_ctl(int ch);
static inline bool is_tspecial(int ch);
static inline bool is_digit(int ch);
static inline bool url_decode(std::string& url);
public:
reader();
void reset();
/** parses partial HTTP request.
*
* \param req request to fill with parsed data
* \param begin iterator to first byte-wise position of the HTTP request to parse
* \param end iterator marking the end of partial stream. this method will parse up to excluding this end of bytes.
*
* \retval true request has been fully parsed.
* \retval false HTTP request parser error (should result into bad_request if possible.)
* \retval indeterminate parsial request parsed successfully but more input is needed to complete parsing.
*/
inline boost::tribool parse(request& req, const buffer_ref& data);
private:
/**
* \param r reference to the request to fill
* \param input the input character to process as part of the incoming request.
*
* \retval boost::indeterminate parsed successfully but request still incomplete.
* \retval true parsed successfully and request is now complete.
* \retval false parse error
*/
inline boost::tribool consume(request& r, char input);
};
// {{{ request impl
inline request::request(x0::connection& conn) :
connection(conn)
{
}
inline bool request::supports_protocol(int major, int minor) const
{
if (major == http_version_major && minor <= http_version_minor)
return true;
if (major < http_version_major)
return true;
return false;
}
// }}}
// {{{ request::reader impl
inline bool request::reader::is_char(int ch)
{
return ch >= 0 && ch < 127;
}
inline bool request::reader::is_ctl(int ch)
{
return (ch >= 0 && ch <= 31) || ch == 127;
}
inline bool request::reader::is_tspecial(int ch)
{
switch (ch)
{
case '(':
case ')':
case '<':
case '>':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case ' ':
case '\t':
return true;
default:
return false;
}
}
inline bool request::reader::is_digit(int ch)
{
return ch >= '0' && ch <= '9';
}
inline bool request::reader::url_decode(std::string& url)
{
std::string out;
out.reserve(url.size());
for (std::size_t i = 0; i < url.size(); ++i)
{
if (url[i] == '%')
{
if (i + 3 <= url.size())
{
int value;
std::istringstream is(url.substr(i + 1, 2));
if (is >> std::hex >> value)
{
out += static_cast<char>(value);
i += 2;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (url[i] == '+')
{
out += ' ';
}
else
{
out += url[i];
}
}
url = out;
return true;
}
inline request::reader::reader() :
state_(method_start), buf_()
{
}
inline void request::reader::reset()
{
state_ = method_start;
buf_.clear();
}
inline boost::tribool request::reader::parse(request& req, const buffer_ref& data)
{
for (buffer_ref::const_iterator begin = data.begin(), end = data.end(); begin != end; ++begin)
{
boost::tribool result = consume(req, *begin);
if (!indeterminate(result))
return result;
}
return boost::indeterminate;
}
inline boost::tribool request::reader::consume(request& r, char input)
{
switch (state_)
{
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
state_ = method;
buf_.push_back(input);
return boost::indeterminate;
}
case method:
if (input == ' ')
{
r.method = buf_;
buf_.clear();
state_ = uri;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
buf_.push_back(input);
return boost::indeterminate;
}
case uri_start:
if (is_ctl(input))
{
return false;
}
else
{
state_ = uri;
buf_.push_back(input);
return boost::indeterminate;
}
case uri:
if (input == ' ')
{
if (!url_decode(buf_))
return false;
r.uri = buf_;
buf_.clear();
std::size_t n = r.uri.find("?");
if (n != std::string::npos)
{
r.path = r.uri.substr(0, n);
r.query = r.uri.substr(n + 1);
}
else
{
r.path = r.uri;
}
if (r.path.empty() || r.path[0] != '/' || r.path.find("..") != std::string::npos)
return false;
state_ = http_version_h;
return boost::indeterminate;
}
else if (is_ctl(input))
{
return false;
}
else
{
buf_.push_back(input);
return boost::indeterminate;
}
case http_version_h:
if (input == 'H')
{
state_ = http_version_t_1;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_t_1:
if (input == 'T')
{
state_ = http_version_t_2;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_t_2:
if (input == 'T')
{
state_ = http_version_p;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_p:
if (input == 'P')
{
state_ = http_version_slash;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_slash:
if (input == '/')
{
r.http_version_major = 0;
r.http_version_minor = 0;
state_ = http_version_major_start;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_major_start:
if (is_digit(input))
{
r.http_version_major = r.http_version_major * 10 + input - '0';
state_ = http_version_major;
return boost::indeterminate;
}
else
{
return false;
}
case http_version_major:
if (input == '.')
{
state_ = http_version_minor_start;
return boost::indeterminate;
}
else if (is_digit(input))
{
r.http_version_major = r.http_version_major * 10 + input - '0';
return boost::indeterminate;
}
else
{
return false;
}
case http_version_minor_start:
if (input == '\r')
{
state_ = expecting_newline_1;
return boost::indeterminate;
}
else if (is_digit(input))
{
r.http_version_minor = r.http_version_minor * 10 + input - '0';
return boost::indeterminate;
}
else
{
return false;
}
case expecting_newline_1:
if (input == '\n')
{
state_ = header_line_start;
return boost::indeterminate;
}
else
{
return false;
}
case header_line_start:
if (input == '\r')
{
state_ = expecting_newline_3;
return boost::indeterminate;
}
else if (!r.headers.empty() && (input == ' ' || input == '\t'))
{
state_ = header_lws;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
r.headers.push_back(x0::header());
r.headers.back().name.push_back(input);
state_ = header_name;
return boost::indeterminate;
}
case header_lws:
if (input == '\r')
{
state_ = expecting_newline_2;
return boost::indeterminate;
}
else if (input == ' ' || input == '\t')
{
return boost::indeterminate;
}
else
{
state_ = header_value;
r.headers.back().value.push_back(input);
return boost::indeterminate;
}
case header_name:
if (input == ':')
{
state_ = space_before_header_value;
return boost::indeterminate;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
r.headers.back().name.push_back(input);
return boost::indeterminate;
}
case space_before_header_value:
if (input == ' ')
{
state_ = header_value;
return boost::indeterminate;
}
else
{
return false;
}
case header_value:
if (input == '\r')
{
state_ = expecting_newline_2;
return boost::indeterminate;
}
else if (is_ctl(input))
{
return false;
}
else
{
r.headers.back().value.push_back(input);
return boost::indeterminate;
}
case expecting_newline_2:
if (input == '\n')
{
state_ = header_line_start;
return boost::indeterminate;
}
else
{
return false;
}
case expecting_newline_3:
if (input == '\n')
{
std::string s(r.header("Content-Length"));
if (!s.empty())
{
state_ = reading_body;
r.body.reserve(std::atoi(s.c_str()));
return boost::indeterminate;
}
else
{
return true;
}
}
else
{
return false;
}
case reading_body:
r.body.push_back(input);
if (r.body.length() < r.body.capacity())
{
return boost::indeterminate;
}
else
{
return true;
}
default:
return false;
}
}
// }}}
//@}
} // namespace x0
#endif
<commit_msg>step-2: merged parse() and consume()<commit_after>/* <x0/request.hpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
*
* (c) 2009 Chrisitan Parpart <trapni@gentoo.org>
*/
#ifndef x0_http_request_hpp
#define x0_http_request_hpp (1)
#include <x0/buffer.hpp>
#include <x0/header.hpp>
#include <x0/fileinfo.hpp>
#include <x0/types.hpp>
#include <x0/api.hpp>
#include <string>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include <boost/logic/tribool.hpp>
namespace x0 {
//! \addtogroup core
//@{
/**
* \brief a client HTTP reuqest object, holding the parsed x0 request data.
*
* \see header, response, connection, server
*/
struct request
{
public:
class reader;
public:
explicit request(x0::connection& connection);
/// the TCP/IP connection this request has been sent through
x0::connection& connection;
public: // request properties
/// HTTP request method, e.g. HEAD, GET, POST, PUT, etc.
std::string method;
/// unparsed request uri
std::string uri;
/// decoded path-part
std::string path;
/// the final entity to be served, for example the full path to the file on disk.
fileinfo_ptr fileinfo;
/// decoded query-part
std::string query;
/// HTTP protocol version major part that this request was formed in
int http_version_major;
/// HTTP protocol version minor part that this request was formed in
int http_version_minor;
/// request headers
std::vector<x0::header> headers;
/** retrieve value of a given request header */
std::string header(const std::string& name) const;
/// body
std::string body;
public: // accumulated request data
/// username this client has authenticated with.
std::string username;
/// the document root directory for this request.
std::string document_root;
// std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified.
// std::shared_ptr<range_def> range; //!< parsed "Range" request header
public: // utility methods
bool supports_protocol(int major, int minor) const;
std::string hostid() const;
};
/**
* \brief implements the HTTP request parser.
*
* \see request, connection
*/
class request::reader
{
public:
enum state
{
method_start,
method,
uri_start,
uri,
http_version_h,
http_version_t_1,
http_version_t_2,
http_version_p,
http_version_slash,
http_version_major_start,
http_version_major,
http_version_minor_start,
http_version_minor,
expecting_newline_1,
header_line_start,
header_lws,
header_name,
space_before_header_value,
header_value,
expecting_newline_2,
expecting_newline_3,
reading_body
};
private:
state state_;
std::string buf_;
private:
static inline bool is_char(int ch);
static inline bool is_ctl(int ch);
static inline bool is_tspecial(int ch);
static inline bool is_digit(int ch);
static inline bool url_decode(std::string& url);
public:
reader();
void reset();
/** parses partial HTTP request.
*
* \param r request to fill with parsed data
* \param data buffer holding the (possibly partial) data of the request to be parsed.
*
* \retval true request has been fully parsed.
* \retval false HTTP request parser error (should result into bad_request if possible.)
* \retval indeterminate parsial request parsed successfully but more input is needed to complete parsing.
*/
inline boost::tribool parse(request& req, const buffer_ref& data);
};
// {{{ request impl
inline request::request(x0::connection& conn) :
connection(conn)
{
}
inline bool request::supports_protocol(int major, int minor) const
{
if (major == http_version_major && minor <= http_version_minor)
return true;
if (major < http_version_major)
return true;
return false;
}
// }}}
// {{{ request::reader impl
inline bool request::reader::is_char(int ch)
{
return ch >= 0 && ch < 127;
}
inline bool request::reader::is_ctl(int ch)
{
return (ch >= 0 && ch <= 31) || ch == 127;
}
inline bool request::reader::is_tspecial(int ch)
{
switch (ch)
{
case '(':
case ')':
case '<':
case '>':
case '@':
case ',':
case ';':
case ':':
case '\\':
case '"':
case '/':
case '[':
case ']':
case '?':
case '=':
case '{':
case '}':
case ' ':
case '\t':
return true;
default:
return false;
}
}
inline bool request::reader::is_digit(int ch)
{
return ch >= '0' && ch <= '9';
}
inline bool request::reader::url_decode(std::string& url)
{
std::string out;
out.reserve(url.size());
for (std::size_t i = 0; i < url.size(); ++i)
{
if (url[i] == '%')
{
if (i + 3 <= url.size())
{
int value;
std::istringstream is(url.substr(i + 1, 2));
if (is >> std::hex >> value)
{
out += static_cast<char>(value);
i += 2;
}
else
{
return false;
}
}
else
{
return false;
}
}
else if (url[i] == '+')
{
out += ' ';
}
else
{
out += url[i];
}
}
url = out;
return true;
}
inline request::reader::reader() :
state_(method_start), buf_()
{
}
inline void request::reader::reset()
{
state_ = method_start;
buf_.clear();
}
inline boost::tribool request::reader::parse(request& r, const buffer_ref& data)
{
for (buffer_ref::const_iterator i = data.begin(), e = data.end(); i != e; ++i)
{
char input = *i;
switch (state_)
{
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
state_ = method;
buf_.push_back(input);
}
break;
case method:
if (input == ' ')
{
r.method = buf_;
buf_.clear();
state_ = uri;
break;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
buf_.push_back(input);
break;
}
case uri_start:
if (is_ctl(input))
{
return false;
}
else
{
state_ = uri;
buf_.push_back(input);
break;
}
case uri:
if (input == ' ')
{
if (!url_decode(buf_))
return false;
r.uri = buf_;
buf_.clear();
std::size_t n = r.uri.find("?");
if (n != std::string::npos)
{
r.path = r.uri.substr(0, n);
r.query = r.uri.substr(n + 1);
}
else
{
r.path = r.uri;
}
if (r.path.empty() || r.path[0] != '/' || r.path.find("..") != std::string::npos)
return false;
state_ = http_version_h;
break;
}
else if (is_ctl(input))
{
return false;
}
else
{
buf_.push_back(input);
break;
}
case http_version_h:
if (input == 'H')
{
state_ = http_version_t_1;
break;
}
else
{
return false;
}
case http_version_t_1:
if (input == 'T')
{
state_ = http_version_t_2;
break;
}
else
{
return false;
}
case http_version_t_2:
if (input == 'T')
{
state_ = http_version_p;
break;
}
else
{
return false;
}
case http_version_p:
if (input == 'P')
{
state_ = http_version_slash;
break;
}
else
{
return false;
}
case http_version_slash:
if (input == '/')
{
r.http_version_major = 0;
r.http_version_minor = 0;
state_ = http_version_major_start;
break;
}
else
{
return false;
}
case http_version_major_start:
if (is_digit(input))
{
r.http_version_major = r.http_version_major * 10 + input - '0';
state_ = http_version_major;
break;
}
else
{
return false;
}
case http_version_major:
if (input == '.')
{
state_ = http_version_minor_start;
break;
}
else if (is_digit(input))
{
r.http_version_major = r.http_version_major * 10 + input - '0';
break;
}
else
{
return false;
}
case http_version_minor_start:
if (input == '\r')
{
state_ = expecting_newline_1;
break;
}
else if (is_digit(input))
{
r.http_version_minor = r.http_version_minor * 10 + input - '0';
break;
}
else
{
return false;
}
case expecting_newline_1:
if (input == '\n')
{
state_ = header_line_start;
break;
}
else
{
return false;
}
case header_line_start:
if (input == '\r')
{
state_ = expecting_newline_3;
break;
}
else if (!r.headers.empty() && (input == ' ' || input == '\t'))
{
state_ = header_lws;
break;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
r.headers.push_back(x0::header());
r.headers.back().name.push_back(input);
state_ = header_name;
break;
}
case header_lws:
if (input == '\r')
{
state_ = expecting_newline_2;
break;
}
else if (input == ' ' || input == '\t')
{
break;
}
else
{
state_ = header_value;
r.headers.back().value.push_back(input);
break;
}
case header_name:
if (input == ':')
{
state_ = space_before_header_value;
break;
}
else if (!is_char(input) || is_ctl(input) || is_tspecial(input))
{
return false;
}
else
{
r.headers.back().name.push_back(input);
break;
}
case space_before_header_value:
if (input == ' ')
{
state_ = header_value;
break;
}
else
{
return false;
}
case header_value:
if (input == '\r')
{
state_ = expecting_newline_2;
break;
}
else if (is_ctl(input))
{
return false;
}
else
{
r.headers.back().value.push_back(input);
break;
}
case expecting_newline_2:
if (input == '\n')
{
state_ = header_line_start;
break;
}
else
{
return false;
}
case expecting_newline_3:
if (input == '\n')
{
std::string s(r.header("Content-Length"));
if (!s.empty())
{
state_ = reading_body;
r.body.reserve(std::atoi(s.c_str()));
break;
}
else
{
return true;
}
}
else
{
return false;
}
case reading_body:
r.body.push_back(input);
if (r.body.length() < r.body.capacity())
{
break;
}
else
{
return true;
}
default:
return false;
}
}
// request header parsed partially
return boost::indeterminate;
}
// }}}
//@}
} // namespace x0
#endif
<|endoftext|> |
<commit_before>#include "daisysp.h"
#include "../src/kxmx_bluemchen.h"
#include <string.h>
using namespace kxmx;
using namespace daisy;
using namespace daisysp;
Bluemchen bluemchen;
Oscillator osc;
float oofreq = 80.0;
uint numWaves = 2;
std::vector<uint> waves = { 0, 1 } ;
std::string waveStrings[] = { "WAVE_SIN", "WAVE_TRI", "WAVE_SAW", "WAVE_RAMP", "WAVE_SQUARE", "WAVE_POLYBLEP_TRI", "WAVE_POLYBLEP_SAW", "WAVE_POLYBLEP_SQUARE", "WAVE_LAST" };
uint currentWave = 0;
int enc_val = 0;
int midi_note = 0;
Parameter knob1;
Parameter knob2;
Parameter cv1;
Parameter cv2;
void UpdateOled()
{
bluemchen.display.Fill(false);
// Display Encoder test increment value and pressed state
bluemchen.display.SetCursor(0, 0);
std::string str = "Enc: ";
char *cstr = &str[0];
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = std::to_string(enc_val);
bluemchen.display.SetCursor(30, 0);
bluemchen.display.WriteString(cstr, Font_6x8, !bluemchen.encoder.Pressed());
// Display the knob values in millivolts
str = std::to_string(static_cast<int>(knob1.Value()));
bluemchen.display.SetCursor(0, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = ":";
bluemchen.display.SetCursor(30, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = std::to_string(static_cast<int>(knob2.Value()));
bluemchen.display.SetCursor(36, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
// Display Waveform
str = "W:";
bluemchen.display.SetCursor(0, 16);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = waveStrings[currentWave];
bluemchen.display.SetCursor(12, 16);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = ":";
bluemchen.display.SetCursor(30, 16);
bluemchen.display.WriteString(cstr, Font_6x8, true);
// Display MIDI input note number
str = "M:";
bluemchen.display.SetCursor(36, 16);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = std::to_string(static_cast<int>(midi_note));
bluemchen.display.SetCursor(48, 16);
bluemchen.display.WriteString(cstr, Font_6x8, true);
// Display CV input in millivolts
str = std::to_string(static_cast<int>(cv1.Value()));
bluemchen.display.SetCursor(0, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
if (cv2.Value() > -999.0f)
{
str = ":";
bluemchen.display.SetCursor(30, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
}
str = std::to_string(static_cast<int>(cv2.Value()));
bluemchen.display.SetCursor((cv2.Value() > -999.0f) ? 36 : 30, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
bluemchen.display.Update();
}
void HandleMidiMessage(MidiEvent m)
{
if( m.type == NoteOn && m.channel == 1 ){
NoteOnEvent p = m.AsNoteOn();
oofreq = mtof( p.note );
osc.SetFreq( oofreq );
}
}
void UpdateControls()
{
bluemchen.ProcessAllControls();
knob1.Process();
knob2.Process();
cv1.Process();
cv2.Process();
enc_val += bluemchen.encoder.Increment();
}
void AudioCallback(AudioHandle::InputBuffer in, AudioHandle::OutputBuffer out, size_t size)
{
UpdateControls();
for( size_t i = 0; i < size; i++){
float sig;
sig = osc.Process();
out[0][i] = sig;
out[1][i] = sig;
if(osc.IsEOC()){
currentWave++;
if (currentWave > sizeof(waves)/sizeof(waves[0])-1 ){currentWave = 0;};
osc.SetWaveform( currentWave );
}
}
}
int main(void)
{
bluemchen.Init();
bluemchen.StartAdc();
knob1.Init(bluemchen.controls[bluemchen.CTRL_1], 0.0f, 5000.0f, Parameter::LINEAR);
knob2.Init(bluemchen.controls[bluemchen.CTRL_2], 0.0f, 5000.0f, Parameter::LINEAR);
cv1.Init(bluemchen.controls[bluemchen.CTRL_3], -5000.0f, 5000.0f, Parameter::LINEAR);
cv2.Init(bluemchen.controls[bluemchen.CTRL_4], -5000.0f, 5000.0f, Parameter::LINEAR);
osc.Init( bluemchen.AudioSampleRate() );
osc.SetFreq( oofreq );
osc.SetAmp(0.85f);
bluemchen.StartAudio(AudioCallback);
while (1)
{
UpdateControls();
UpdateOled();
bluemchen.midi.Listen();
while (bluemchen.midi.HasEvents())
{
HandleMidiMessage(bluemchen.midi.PopEvent());
}
}
}
<commit_msg>starting presets<commit_after>#include "daisysp.h"
#include "../src/kxmx_bluemchen.h"
#include <string.h>
using namespace kxmx;
using namespace daisy;
using namespace daisysp;
Bluemchen bluemchen;
Oscillator osc;
std::string waveStrings[] = { "WAVE_SIN", "WAVE_TRI", "WAVE_SAW", "WAVE_RAMP", "WAVE_SQUARE", "WAVE_POLYBLEP_TRI", "WAVE_POLYBLEP_SAW", "WAVE_POLYBLEP_SQUARE", "WAVE_LAST" };
uint currentWave = 0;
float oofreq = 500.0;
std::vector<uint> waves = { 0, 2, 1, 5 , 0, 0} ;
bool encoderPrevious = false;
int enc_val = 0;
int midi_note = 0;
Parameter knob1;
Parameter knob2;
Parameter cv1;
Parameter cv2;
void loadPresets(){
//TODO add JSON loading from SD card
}
void changePreset(char preset){
for( int i = 0; i < 6; i++ ){
waves[i] = 0;
}
}
void UpdateOled()
{
bluemchen.display.Fill(false);
// Display Encoder test increment value and pressed state
bluemchen.display.SetCursor(0, 0);
std::string str = "Enc: ";
char *cstr = &str[0];
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = std::to_string(enc_val);
bluemchen.display.SetCursor(30, 0);
bluemchen.display.WriteString(cstr, Font_6x8, !bluemchen.encoder.Pressed());
str = std::to_string(static_cast<int>(knob1.Value()));
bluemchen.display.SetCursor(0, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = ":";
bluemchen.display.SetCursor(30, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
str = std::to_string(static_cast<int>(knob2.Value()));
bluemchen.display.SetCursor(36, 8);
bluemchen.display.WriteString(cstr, Font_6x8, true);
// Display Waveform
bluemchen.display.SetCursor(0, 16);
std::string wvstring = waveStrings[ waves[currentWave]];
wvstring.resize(10);
bluemchen.display.WriteString(wvstring.c_str(), Font_6x8, true);
// // Display MIDI input note number
// str = "M:";
// bluemchen.display.SetCursor(36, 16);
// bluemchen.display.WriteString(cstr, Font_6x8, true);
// str = std::to_string(static_cast<int>(midi_note));
// bluemchen.display.SetCursor(48, 16);
// bluemchen.display.WriteString(cstr, Font_6x8, true);
// Display CV input in millivolts
str = std::to_string(static_cast<int>(cv1.Value()));
bluemchen.display.SetCursor(0, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
if (cv2.Value() > -999.0f)
{
str = ":";
bluemchen.display.SetCursor(30, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
}
str = std::to_string(static_cast<int>(cv2.Value()));
bluemchen.display.SetCursor((cv2.Value() > -999.0f) ? 36 : 30, 24);
bluemchen.display.WriteString(cstr, Font_6x8, true);
bluemchen.display.Update();
}
void HandleMidiMessage(MidiEvent m)
{
if( m.type == NoteOn && m.channel == 1 ){
NoteOnEvent p = m.AsNoteOn();
oofreq = mtof( p.note );
osc.SetFreq( oofreq );
}
}
void UpdateControls()
{
bluemchen.ProcessAllControls();
knob1.Process();
knob2.Process();
cv1.Process();
cv2.Process();
enc_val += bluemchen.encoder.Increment();
osc.SetFreq( oofreq + enc_val );
if(bluemchen.encoder.Pressed() != encoderPrevious ){
changePreset(0);
}
encoderPrevious = bluemchen.encoder.Pressed();
}
void AudioCallback(AudioHandle::InputBuffer in, AudioHandle::OutputBuffer out, size_t size) {
UpdateControls();
for( size_t i = 0; i < size; i++){
float sig;
sig = osc.Process();
out[0][i] = sig;
out[1][i] = sig;
if(osc.IsEOC()){
currentWave++;
if (currentWave == waves.size() ){currentWave = 0;};
osc.SetWaveform( waves[currentWave] );
}
}
}
int main(void)
{
bluemchen.Init();
bluemchen.StartAdc();
knob1.Init(bluemchen.controls[bluemchen.CTRL_1], 0.0f, 5.0f, Parameter::LINEAR);
knob2.Init(bluemchen.controls[bluemchen.CTRL_2], 0.0f, 5.0f, Parameter::LINEAR);
cv1.Init(bluemchen.controls[bluemchen.CTRL_3], 0.0f, 5.99f, Parameter::LINEAR);
cv2.Init(bluemchen.controls[bluemchen.CTRL_4], 0.0f, 5.99f, Parameter::LINEAR);
loadPresets();
osc.Init( bluemchen.AudioSampleRate() );
osc.SetFreq( oofreq );
osc.SetAmp(0.85f);
bluemchen.StartAudio(AudioCallback);
while (1)
{
UpdateControls();
UpdateOled();
bluemchen.midi.Listen();
while (bluemchen.midi.HasEvents())
{
HandleMidiMessage(bluemchen.midi.PopEvent());
}
}
}
<|endoftext|> |
<commit_before>#include <xmppclient.h>
#include <xmppstream.h>
#include <xmppserver.h>
#include <virtualhost.h>
#include <db.h>
#include <tagbuilder.h>
#include <nanosoft/base64.h>
// for debug only
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace nanosoft;
/**
* Конструктор потока
*/
XMPPClient::XMPPClient(XMPPServer *srv, int sock):
XMPPStream(srv, sock), vhost(0),
state(init), initialPresenceSent(false)
{
}
/**
* Деструктор потока
*/
XMPPClient::~XMPPClient()
{
}
/**
* Событие закрытие соединения
*
* Вызывается если peer закрыл соединение
*/
void XMPPClient::onShutdown()
{
cerr << "[XMPPStream]: peer shutdown connection" << endl;
if ( state != terminating ) {
AsyncXMLStream::onShutdown();
//server->onOffline(this);
vhost->onOffline(this);
XMLWriter::flush();
}
server->daemon->removeObject(this);
shutdown(READ | WRITE);
delete this;
cerr << "[XMPPStream]: onShutdown leave" << endl;
}
/**
* Завершить сессию
*
* thread-safe
*/
void XMPPClient::terminate()
{
cerr << "[XMPPStream]: terminating connection..." << endl;
switch ( state )
{
case terminating:
return;
case authorized:
//server->onOffline(this);
break;
}
mutex.lock();
if ( state != terminating ) {
state = terminating;
endElement("stream:stream");
flush();
shutdown(WRITE);
}
mutex.unlock();
}
/**
* Сигнал завершения работы
*
* Объект должен закрыть файловый дескриптор
* и освободить все занимаемые ресурсы
*/
void XMPPClient::onTerminate()
{
terminate();
}
/**
* Обработчик станз
*/
void XMPPClient::onStanza(Stanza stanza)
{
fprintf(stderr, "#%d stanza: %s\n", getWorkerId(), stanza->name().c_str());
if (stanza->name() == "iq") onIqStanza(stanza);
else if (stanza->name() == "auth") onAuthStanza(stanza);
else if (stanza->name() == "response" ) onResponseStanza(stanza);
else if (stanza->name() == "message") onMessageStanza(stanza);
else if (stanza->name() == "presence") onPresenceStanza(stanza);
else ; // ...
}
/**
* Обработчик авторизации
*/
void XMPPClient::onAuthStanza(Stanza stanza)
{
sasl = vhost->start("xmpp", vhost->hostname(), stanza->getAttribute("mechanism"));
onSASLStep(string());
}
/**
* Обработка этапа авторизации SASL
*/
void XMPPClient::onSASLStep(const std::string &input)
{
string output;
switch ( vhost->step(sasl, input, output) )
{
case SASLServer::ok:
client_jid.setUsername(vhost->getUsername(sasl));
vhost->GSASLServer::close(sasl);
startElement("success");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
endElement("success");
flush();
resetWriter();
state = authorized;
depth = 1; // после выхода из onAuthStanza/onStanza() будет стандартный depth--
resetParser();
break;
case SASLServer::next:
startElement("challenge");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
characterData(base64_encode(output));
endElement("challenge");
flush();
break;
case SASLServer::error:
vhost->GSASLServer::close(sasl);
startElement("failure");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
addElement("temporary-auth-failure", "");
endElement("failure");
flush();
break;
}
}
/**
* Обработчик авторизации: ответ клиента
*/
void XMPPClient::onResponseStanza(Stanza stanza)
{
onSASLStep(base64_decode(stanza));
}
/**
* Обработчик iq-станзы
*/
void XMPPClient::onIqStanza(Stanza stanza) {
stanza.setFrom(client_jid);
if(stanza->hasChild("bind") && (stanza.type() == "set" || stanza.type() == "get")) {
client_jid.setResource(stanza.type() == "set" ? string(stanza["bind"]["resource"]) : "foo");
Stanza iq = new ATXmlTag("iq");
iq->setAttribute("type", "result");
iq->setAttribute("id", stanza->getAttribute("id"));
TagHelper bind = iq["bind"];
bind->setDefaultNameSpaceAttribute("urn:ietf:params:xml:ns:xmpp-bind");
bind["jid"] = jid().full();
sendStanza(iq);
delete iq;
vhost->onOnline(this);
return;
}
if(stanza->hasChild("session") && stanza.type() == "set") {
Stanza iq = new ATXmlTag("iq");
if(!stanza.id().empty()) iq->setAttribute("id", stanza.id());
iq->setAttribute("type", "result");
iq["session"]->setDefaultNameSpaceAttribute("urn:ietf:params:xml:ns:xmpp-session");
sendStanza(iq);
return;
}
if(!stanza->hasAttribute("to")) {
vhost->handleIq(stanza);
return;
}
VirtualHost *s = dynamic_cast<VirtualHost*>(server->getHostByName(stanza.to().hostname()));
if(s != 0) { // iq-запрос к виртуальному узлу
s->handleIq(stanza);
} else {
// iq-запрос «наружу»
}
}
ClientPresence XMPPClient::presence() {
return client_presence;
}
void XMPPClient::onMessageStanza(Stanza stanza) {
stanza.setFrom(client_jid);
server->routeStanza(stanza.to().hostname(), stanza);
}
void XMPPClient::onPresenceStanza(Stanza stanza) {
stanza->setAttribute("from", client_jid.full());
if ( stanza->hasAttribute("to") )
{
// доставить личный презенс
server->routeStanza(stanza.to().hostname(), stanza);
}
else
{
client_presence.priority = atoi(stanza->getChildValue("priority", "0").c_str()); // TODO
client_presence.status_text = stanza->getChildValue("status", "");
client_presence.setShow(stanza->getChildValue("show", "Available"));
// Разослать этот presence контактам ростера
if ( initialPresenceSent || stanza->hasAttribute("type") ) {
vhost->broadcastPresence(stanza);
} else {
vhost->initialPresence(stanza);
initialPresenceSent = true;
}
}
}
/**
* Событие: начало потока
*/
void XMPPClient::onStartStream(const std::string &name, const attributes_t &attributes)
{
fprintf(stderr, "#%d new stream to %s\n", getWorkerId(), attributes.find("to")->second.c_str());
initXML();
startElement("stream:stream");
setAttribute("xmlns", "jabber:client");
setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
setAttribute("id", "123456"); // Требования к id — непредсказуемость и уникальность
setAttribute("from", "localhost");
setAttribute("version", "1.0");
setAttribute("xml:lang", "en");
if ( state == init )
{
vhost = dynamic_cast<VirtualHost*>(server->getHostByName(attributes.find("to")->second));
if ( vhost == 0 ) {
Stanza error = Stanza::streamError("host-unknown", "Неизвестный хост", "ru");
sendStanza(error);
delete error;
terminate();
return;
}
}
startElement("stream:features");
if ( state == init )
{
client_jid.setHostname(vhost->hostname());
startElement("mechanisms");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
SASLServer::mechanisms_t list = vhost->getMechanisms();
for(SASLServer::mechanisms_t::const_iterator pos = list.begin(); pos != list.end(); ++pos)
{
addElement("mechanism", *pos);
}
endElement("mechanisms");
startElement("register");
setAttribute("xmlns", "http://jabber.org/features/iq-register");
endElement("register");
}
else
{
startElement("bind");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-bind");
endElement("bind");
/*
startElement("session");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-session");
endElement("session");
*/
}
endElement("stream:features");
flush();
}
/**
* Событие: конец потока
*/
void XMPPClient::onEndStream()
{
cerr << "session closed" << endl;
endElement("stream:stream");
}
/**
* JID потока
*/
JID XMPPClient::jid() const
{
return client_jid;
}
<commit_msg>fix iq-routing :-)<commit_after>#include <xmppclient.h>
#include <xmppstream.h>
#include <xmppserver.h>
#include <virtualhost.h>
#include <db.h>
#include <tagbuilder.h>
#include <nanosoft/base64.h>
// for debug only
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace nanosoft;
/**
* Конструктор потока
*/
XMPPClient::XMPPClient(XMPPServer *srv, int sock):
XMPPStream(srv, sock), vhost(0),
state(init), initialPresenceSent(false)
{
}
/**
* Деструктор потока
*/
XMPPClient::~XMPPClient()
{
}
/**
* Событие закрытие соединения
*
* Вызывается если peer закрыл соединение
*/
void XMPPClient::onShutdown()
{
cerr << "[XMPPStream]: peer shutdown connection" << endl;
if ( state != terminating ) {
AsyncXMLStream::onShutdown();
//server->onOffline(this);
vhost->onOffline(this);
XMLWriter::flush();
}
server->daemon->removeObject(this);
shutdown(READ | WRITE);
delete this;
cerr << "[XMPPStream]: onShutdown leave" << endl;
}
/**
* Завершить сессию
*
* thread-safe
*/
void XMPPClient::terminate()
{
cerr << "[XMPPStream]: terminating connection..." << endl;
switch ( state )
{
case terminating:
return;
case authorized:
//server->onOffline(this);
break;
}
mutex.lock();
if ( state != terminating ) {
state = terminating;
endElement("stream:stream");
flush();
shutdown(WRITE);
}
mutex.unlock();
}
/**
* Сигнал завершения работы
*
* Объект должен закрыть файловый дескриптор
* и освободить все занимаемые ресурсы
*/
void XMPPClient::onTerminate()
{
terminate();
}
/**
* Обработчик станз
*/
void XMPPClient::onStanza(Stanza stanza)
{
fprintf(stderr, "#%d stanza: %s\n", getWorkerId(), stanza->name().c_str());
if (stanza->name() == "iq") onIqStanza(stanza);
else if (stanza->name() == "auth") onAuthStanza(stanza);
else if (stanza->name() == "response" ) onResponseStanza(stanza);
else if (stanza->name() == "message") onMessageStanza(stanza);
else if (stanza->name() == "presence") onPresenceStanza(stanza);
else ; // ...
}
/**
* Обработчик авторизации
*/
void XMPPClient::onAuthStanza(Stanza stanza)
{
sasl = vhost->start("xmpp", vhost->hostname(), stanza->getAttribute("mechanism"));
onSASLStep(string());
}
/**
* Обработка этапа авторизации SASL
*/
void XMPPClient::onSASLStep(const std::string &input)
{
string output;
switch ( vhost->step(sasl, input, output) )
{
case SASLServer::ok:
client_jid.setUsername(vhost->getUsername(sasl));
vhost->GSASLServer::close(sasl);
startElement("success");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
endElement("success");
flush();
resetWriter();
state = authorized;
depth = 1; // после выхода из onAuthStanza/onStanza() будет стандартный depth--
resetParser();
break;
case SASLServer::next:
startElement("challenge");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
characterData(base64_encode(output));
endElement("challenge");
flush();
break;
case SASLServer::error:
vhost->GSASLServer::close(sasl);
startElement("failure");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
addElement("temporary-auth-failure", "");
endElement("failure");
flush();
break;
}
}
/**
* Обработчик авторизации: ответ клиента
*/
void XMPPClient::onResponseStanza(Stanza stanza)
{
onSASLStep(base64_decode(stanza));
}
/**
* Обработчик iq-станзы
*/
void XMPPClient::onIqStanza(Stanza stanza) {
stanza.setFrom(client_jid);
if(stanza->hasChild("bind") && (stanza.type() == "set" || stanza.type() == "get")) {
client_jid.setResource(stanza.type() == "set" ? string(stanza["bind"]["resource"]) : "foo");
Stanza iq = new ATXmlTag("iq");
iq->setAttribute("type", "result");
iq->setAttribute("id", stanza->getAttribute("id"));
TagHelper bind = iq["bind"];
bind->setDefaultNameSpaceAttribute("urn:ietf:params:xml:ns:xmpp-bind");
bind["jid"] = jid().full();
sendStanza(iq);
delete iq;
vhost->onOnline(this);
return;
}
if(stanza->hasChild("session") && stanza.type() == "set") {
Stanza iq = new ATXmlTag("iq");
if(!stanza.id().empty()) iq->setAttribute("id", stanza.id());
iq->setAttribute("type", "result");
iq["session"]->setDefaultNameSpaceAttribute("urn:ietf:params:xml:ns:xmpp-session");
sendStanza(iq);
return;
}
if(!stanza->hasAttribute("to")) {
vhost->handleIq(stanza);
return;
}
server->routeStanza(stanza.to().hostname(), stanza);
}
ClientPresence XMPPClient::presence() {
return client_presence;
}
void XMPPClient::onMessageStanza(Stanza stanza) {
stanza.setFrom(client_jid);
server->routeStanza(stanza.to().hostname(), stanza);
}
void XMPPClient::onPresenceStanza(Stanza stanza) {
stanza->setAttribute("from", client_jid.full());
if ( stanza->hasAttribute("to") )
{
// доставить личный презенс
server->routeStanza(stanza.to().hostname(), stanza);
}
else
{
client_presence.priority = atoi(stanza->getChildValue("priority", "0").c_str()); // TODO
client_presence.status_text = stanza->getChildValue("status", "");
client_presence.setShow(stanza->getChildValue("show", "Available"));
// Разослать этот presence контактам ростера
if ( initialPresenceSent || stanza->hasAttribute("type") ) {
vhost->broadcastPresence(stanza);
} else {
vhost->initialPresence(stanza);
initialPresenceSent = true;
}
}
}
/**
* Событие: начало потока
*/
void XMPPClient::onStartStream(const std::string &name, const attributes_t &attributes)
{
fprintf(stderr, "#%d new stream to %s\n", getWorkerId(), attributes.find("to")->second.c_str());
initXML();
startElement("stream:stream");
setAttribute("xmlns", "jabber:client");
setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
setAttribute("id", "123456"); // Требования к id — непредсказуемость и уникальность
setAttribute("from", "localhost");
setAttribute("version", "1.0");
setAttribute("xml:lang", "en");
if ( state == init )
{
vhost = dynamic_cast<VirtualHost*>(server->getHostByName(attributes.find("to")->second));
if ( vhost == 0 ) {
Stanza error = Stanza::streamError("host-unknown", "Неизвестный хост", "ru");
sendStanza(error);
delete error;
terminate();
return;
}
}
startElement("stream:features");
if ( state == init )
{
client_jid.setHostname(vhost->hostname());
startElement("mechanisms");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
SASLServer::mechanisms_t list = vhost->getMechanisms();
for(SASLServer::mechanisms_t::const_iterator pos = list.begin(); pos != list.end(); ++pos)
{
addElement("mechanism", *pos);
}
endElement("mechanisms");
startElement("register");
setAttribute("xmlns", "http://jabber.org/features/iq-register");
endElement("register");
}
else
{
startElement("bind");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-bind");
endElement("bind");
/*
startElement("session");
setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-session");
endElement("session");
*/
}
endElement("stream:features");
flush();
}
/**
* Событие: конец потока
*/
void XMPPClient::onEndStream()
{
cerr << "session closed" << endl;
endElement("stream:stream");
}
/**
* JID потока
*/
JID XMPPClient::jid() const
{
return client_jid;
}
<|endoftext|> |
<commit_before>#include "ddPropertiesPanel.h"
#include <QtVariantPropertyManager>
#include <QtTreePropertyBrowser>
#include <QtGroupBoxPropertyBrowser>
#include <QtVariantEditorFactory>
#include <QVBoxLayout>
//-----------------------------------------------------------------------------
class ddPropertiesPanel::ddInternal
{
public:
ddInternal()
{
this->Manager = 0;
this->Browser = 0;
}
QtVariantPropertyManager* Manager;
QtAbstractPropertyBrowser* Browser;
QMap<QString, QtVariantProperty*> Properties;
QMap<QtVariantProperty*, QtVariantProperty*> SubPropertyMap;
};
//-----------------------------------------------------------------------------
ddPropertiesPanel::ddPropertiesPanel(QWidget* parent) : QWidget(parent)
{
this->Internal = new ddInternal;
QtVariantPropertyManager *manager = new QtVariantPropertyManager;
this->Internal->Manager = manager;
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
this->setBrowserModeToTree();
this->connect(this->Internal->Manager,
SIGNAL(valueChanged(QtProperty*, const QVariant&)),
SLOT(onPropertyValueChanged(QtProperty*)));
}
//-----------------------------------------------------------------------------
ddPropertiesPanel::~ddPropertiesPanel()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::setBrowserModeToTree()
{
this->clear();
delete this->Internal->Browser;
QtVariantEditorFactory *variantFactory = new QtVariantEditorFactory;
QtTreePropertyBrowser *browser = new QtTreePropertyBrowser;
browser->setFactoryForManager(this->Internal->Manager, variantFactory);
browser->setPropertiesWithoutValueMarked(true);
browser->setRootIsDecorated(true);
this->layout()->addWidget(browser);
this->Internal->Browser = browser;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::setBrowserModeToWidget()
{
this->clear();
delete this->Internal->Browser;
QtVariantEditorFactory *variantFactory = new QtVariantEditorFactory;
QtGroupBoxPropertyBrowser* browser = new QtGroupBoxPropertyBrowser;
browser->setFactoryForManager(this->Internal->Manager, variantFactory);
this->layout()->addWidget(browser);
this->Internal->Browser = browser;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::onPropertyValueChanged(QtProperty* property)
{
emit this->propertyValueChanged(static_cast<QtVariantProperty*>(property));
}
//-----------------------------------------------------------------------------
QtVariantPropertyManager* ddPropertiesPanel::propertyManager() const
{
return this->Internal->Manager;
}
//-----------------------------------------------------------------------------
QtAbstractPropertyBrowser* ddPropertiesPanel::propertyBrowser() const
{
return this->Internal->Browser;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addGroup(const QString& name, const QString& description)
{
QtVariantProperty* property = this->Internal->Manager->addProperty(QtVariantPropertyManager::groupTypeId(), description);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addProperty(const QString& name, const QVariant& value)
{
int propertyType = value.type();
// Python may pass integer properties as QVariant::LongLong
// but this type is not supported by the QtPropertyBrowser
if (propertyType == QVariant::LongLong)
{
propertyType = QVariant::Int;
}
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, name);
property->setValue(value);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
QtBrowserItem * browserItem = this->Internal->Browser->topLevelItem(property);
QtTreePropertyBrowser* treeBrowser = qobject_cast<QtTreePropertyBrowser*>(this->Internal->Browser);
if (browserItem && treeBrowser)
{
treeBrowser->setExpanded(browserItem, false);
}
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addEnumProperty(const QString& name, const QVariant& value)
{
int propertyType = this->Internal->Manager->enumTypeId();
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, name);
property->setValue(value);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
QtBrowserItem * browserItem = this->Internal->Browser->topLevelItem(property);
QtTreePropertyBrowser* treeBrowser = qobject_cast<QtTreePropertyBrowser*>(this->Internal->Browser);
if (browserItem && treeBrowser)
{
treeBrowser->setExpanded(browserItem, false);
}
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addSubProperty(const QString& name, const QVariant& value, QtVariantProperty* parent)
{
if (!parent)
{
return 0;
}
int propertyType = value.type();
int subId = parent->subProperties().length();
QString subName = QString("%1[%2]").arg(name).arg(subId);
// Python may pass integer properties as QVariant::LongLong
// but this type is not supported by the QtPropertyBrowser
if (propertyType == QVariant::LongLong)
{
propertyType = QVariant::Int;
}
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, subName);
property->setValue(value);
parent->addSubProperty(property);
this->Internal->SubPropertyMap[property] = parent;
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getProperty(const QString& name) const
{
return this->Internal->Properties.value(name);
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getSubProperty(QtVariantProperty* parent, const QString& name) const
{
if (!parent)
{
return 0;
}
QList<QtProperty*> subProperties = parent->subProperties();
foreach (QtProperty* subProperty, subProperties)
{
if (subProperty->propertyName() == name)
{
return static_cast<QtVariantProperty*>(subProperty);
}
}
return 0;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getSubProperty(QtVariantProperty* parent, int childIndex) const
{
if (!parent)
{
return 0;
}
QList<QtProperty*> subProperties = parent->subProperties();
if (childIndex >= 0 && childIndex < subProperties.size())
{
return static_cast<QtVariantProperty*>(subProperties[childIndex]);
}
return 0;
}
//-----------------------------------------------------------------------------
int ddPropertiesPanel::getSubPropertyIndex(QtVariantProperty* property) const
{
QtVariantProperty* parent = this->getParentProperty(property);
if (!parent)
{
return 0;
}
return parent->subProperties().indexOf(property);
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getParentProperty(QtVariantProperty* property) const
{
return this->Internal->SubPropertyMap.value(property);
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::clear()
{
this->Internal->Manager->clear();
this->Internal->Properties.clear();
this->Internal->SubPropertyMap.clear();
}
<commit_msg>fix potential crash in ddPropertiesPanel with unknown property variant type<commit_after>#include "ddPropertiesPanel.h"
#include <QtVariantPropertyManager>
#include <QtTreePropertyBrowser>
#include <QtGroupBoxPropertyBrowser>
#include <QtVariantEditorFactory>
#include <QDebug>
#include <QVBoxLayout>
//-----------------------------------------------------------------------------
class ddPropertiesPanel::ddInternal
{
public:
ddInternal()
{
this->Manager = 0;
this->Browser = 0;
}
QtVariantPropertyManager* Manager;
QtAbstractPropertyBrowser* Browser;
QMap<QString, QtVariantProperty*> Properties;
QMap<QtVariantProperty*, QtVariantProperty*> SubPropertyMap;
};
//-----------------------------------------------------------------------------
ddPropertiesPanel::ddPropertiesPanel(QWidget* parent) : QWidget(parent)
{
this->Internal = new ddInternal;
QtVariantPropertyManager *manager = new QtVariantPropertyManager;
this->Internal->Manager = manager;
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
this->setBrowserModeToTree();
this->connect(this->Internal->Manager,
SIGNAL(valueChanged(QtProperty*, const QVariant&)),
SLOT(onPropertyValueChanged(QtProperty*)));
}
//-----------------------------------------------------------------------------
ddPropertiesPanel::~ddPropertiesPanel()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::setBrowserModeToTree()
{
this->clear();
delete this->Internal->Browser;
QtVariantEditorFactory *variantFactory = new QtVariantEditorFactory;
QtTreePropertyBrowser *browser = new QtTreePropertyBrowser;
browser->setFactoryForManager(this->Internal->Manager, variantFactory);
browser->setPropertiesWithoutValueMarked(true);
browser->setRootIsDecorated(true);
this->layout()->addWidget(browser);
this->Internal->Browser = browser;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::setBrowserModeToWidget()
{
this->clear();
delete this->Internal->Browser;
QtVariantEditorFactory *variantFactory = new QtVariantEditorFactory;
QtGroupBoxPropertyBrowser* browser = new QtGroupBoxPropertyBrowser;
browser->setFactoryForManager(this->Internal->Manager, variantFactory);
this->layout()->addWidget(browser);
this->Internal->Browser = browser;
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::onPropertyValueChanged(QtProperty* property)
{
emit this->propertyValueChanged(static_cast<QtVariantProperty*>(property));
}
//-----------------------------------------------------------------------------
QtVariantPropertyManager* ddPropertiesPanel::propertyManager() const
{
return this->Internal->Manager;
}
//-----------------------------------------------------------------------------
QtAbstractPropertyBrowser* ddPropertiesPanel::propertyBrowser() const
{
return this->Internal->Browser;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addGroup(const QString& name, const QString& description)
{
QtVariantProperty* property = this->Internal->Manager->addProperty(QtVariantPropertyManager::groupTypeId(), description);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addProperty(const QString& name, const QVariant& value)
{
int propertyType = value.type();
// Python may pass integer properties as QVariant::LongLong
// but this type is not supported by the QtPropertyBrowser
if (propertyType == QVariant::LongLong)
{
propertyType = QVariant::Int;
}
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, name);
if (!property)
{
qWarning() << "Unsupported property type " << value.typeName() << " given for property " << name;
property = this->Internal->Manager->addProperty(QVariant::String, name);
}
property->setValue(value);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
QtBrowserItem * browserItem = this->Internal->Browser->topLevelItem(property);
QtTreePropertyBrowser* treeBrowser = qobject_cast<QtTreePropertyBrowser*>(this->Internal->Browser);
if (browserItem && treeBrowser)
{
treeBrowser->setExpanded(browserItem, false);
}
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addEnumProperty(const QString& name, const QVariant& value)
{
int propertyType = this->Internal->Manager->enumTypeId();
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, name);
property->setValue(value);
this->Internal->Browser->addProperty(property);
this->Internal->Properties[name] = property;
QtBrowserItem * browserItem = this->Internal->Browser->topLevelItem(property);
QtTreePropertyBrowser* treeBrowser = qobject_cast<QtTreePropertyBrowser*>(this->Internal->Browser);
if (browserItem && treeBrowser)
{
treeBrowser->setExpanded(browserItem, false);
}
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::addSubProperty(const QString& name, const QVariant& value, QtVariantProperty* parent)
{
if (!parent)
{
return 0;
}
int propertyType = value.type();
int subId = parent->subProperties().length();
QString subName = QString("%1[%2]").arg(name).arg(subId);
// Python may pass integer properties as QVariant::LongLong
// but this type is not supported by the QtPropertyBrowser
if (propertyType == QVariant::LongLong)
{
propertyType = QVariant::Int;
}
QtVariantProperty* property = this->Internal->Manager->addProperty(propertyType, subName);
if (!property)
{
qWarning() << "Unsupported property type " << value.typeName() << " given for property " << name;
property = this->Internal->Manager->addProperty(QVariant::String, name);
}
property->setValue(value);
parent->addSubProperty(property);
this->Internal->SubPropertyMap[property] = parent;
return property;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getProperty(const QString& name) const
{
return this->Internal->Properties.value(name);
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getSubProperty(QtVariantProperty* parent, const QString& name) const
{
if (!parent)
{
return 0;
}
QList<QtProperty*> subProperties = parent->subProperties();
foreach (QtProperty* subProperty, subProperties)
{
if (subProperty->propertyName() == name)
{
return static_cast<QtVariantProperty*>(subProperty);
}
}
return 0;
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getSubProperty(QtVariantProperty* parent, int childIndex) const
{
if (!parent)
{
return 0;
}
QList<QtProperty*> subProperties = parent->subProperties();
if (childIndex >= 0 && childIndex < subProperties.size())
{
return static_cast<QtVariantProperty*>(subProperties[childIndex]);
}
return 0;
}
//-----------------------------------------------------------------------------
int ddPropertiesPanel::getSubPropertyIndex(QtVariantProperty* property) const
{
QtVariantProperty* parent = this->getParentProperty(property);
if (!parent)
{
return 0;
}
return parent->subProperties().indexOf(property);
}
//-----------------------------------------------------------------------------
QtVariantProperty* ddPropertiesPanel::getParentProperty(QtVariantProperty* property) const
{
return this->Internal->SubPropertyMap.value(property);
}
//-----------------------------------------------------------------------------
void ddPropertiesPanel::clear()
{
this->Internal->Manager->clear();
this->Internal->Properties.clear();
this->Internal->SubPropertyMap.clear();
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#pragma once
#include <cassert>
#include <memory>
#include <db.h>
namespace ftcxx {
class Slice {
public:
Slice()
: _data(nullptr),
_size(0)
{}
explicit Slice(size_t sz)
: _buf(new char[sz], std::default_delete<char[]>()),
_data(_buf.get()),
_size(sz)
{}
Slice(const char *p, size_t sz)
: _data(p),
_size(sz)
{}
explicit Slice(const std::string &str)
: _data(str.c_str()),
_size(str.size())
{}
Slice(const Slice &other)
: _data(other._data),
_size(other._size)
{}
Slice& operator=(const Slice &other) {
_data = other._data;
_size = other._size;
return *this;
}
Slice(Slice&& other)
: _data(nullptr),
_size(0)
{
std::swap(_data, other._data);
std::swap(_size, other._size);
std::swap(_buf, other._buf);
}
Slice& operator=(Slice&& other) {
std::swap(_data, other._data);
std::swap(_size, other._size);
std::swap(_buf, other._buf);
return *this;
}
template<typename T>
static Slice slice_of(const T &v) {
return Slice(reinterpret_cast<const char *>(&v), sizeof v);
}
template<typename T>
T as() const {
assert(size() == sizeof(T));
const T *p = reinterpret_cast<const T *>(_data);
return *p;
}
const char *data() const { return _data; }
char *mutable_data() const {
assert(_buf);
return _buf.get();
}
size_t size() const { return _size; }
Slice copy() const {
Slice s(_size);
std::copy(_data, _data + _size, s.mutable_data());
return s;
}
Slice owned() const {
if (_buf) {
return *this;
} else {
return copy();
}
}
DBT dbt() const {
DBT d;
d.data = const_cast<void *>(static_cast<const void *>(_data));
d.size = _size;
d.ulen = _size;
d.flags = 0;
return d;
}
private:
std::shared_ptr<char> _buf;
const char *_data;
size_t _size;
};
} // namespace ftcxx
<commit_msg>add more taste to slice<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#pragma once
#include <cassert>
#include <iterator>
#include <memory>
#include <db.h>
namespace ftcxx {
class Slice {
public:
Slice()
: _data(nullptr),
_size(0)
{}
explicit Slice(size_t sz)
: _buf(new char[sz], std::default_delete<char[]>()),
_data(_buf.get()),
_size(sz)
{}
Slice(const char *p, size_t sz)
: _data(p),
_size(sz)
{}
explicit Slice(const std::string &str)
: _data(str.c_str()),
_size(str.size())
{}
Slice(const Slice &other)
: _data(other._data),
_size(other._size)
{}
Slice& operator=(const Slice &other) {
_data = other._data;
_size = other._size;
return *this;
}
Slice(Slice&& other)
: _data(nullptr),
_size(0)
{
std::swap(_data, other._data);
std::swap(_size, other._size);
std::swap(_buf, other._buf);
}
Slice& operator=(Slice&& other) {
std::swap(_data, other._data);
std::swap(_size, other._size);
std::swap(_buf, other._buf);
return *this;
}
template<typename T>
static Slice slice_of(const T &v) {
return Slice(reinterpret_cast<const char *>(&v), sizeof v);
}
template<typename T>
T as() const {
assert(size() == sizeof(T));
const T *p = reinterpret_cast<const T *>(data());
return *p;
}
const char *data() const { return _data; }
char *mutable_data() const {
assert(_buf);
return _buf.get();
}
size_t size() const { return _size; }
bool empty() const { return size() == 0; }
char operator[](size_t n) const {
assert(n < size());
return _data[n];
}
char *begin() { return mutable_data(); }
char *end() { return mutable_data() + size(); }
char *rbegin() { return end(); }
char *rend() { return begin(); }
const char *begin() const { return data(); }
const char *end() const { return data() + size(); }
const char *rbegin() const { return end(); }
const char *rend() const { return begin(); }
const char *cbegin() const { return data(); }
const char *cend() const { return data() + size(); }
const char *crbegin() const { return end(); }
const char *crend() const { return begin(); }
Slice copy() const {
Slice s(size());
std::copy(begin(), end(), s.begin());
return s;
}
Slice owned() const {
if (_buf) {
return *this;
} else {
return copy();
}
}
DBT dbt() const {
DBT d;
d.data = const_cast<void *>(static_cast<const void *>(data()));
d.size = size();
d.ulen = size();
d.flags = 0;
return d;
}
private:
std::shared_ptr<char> _buf;
const char *_data;
size_t _size;
};
} // namespace ftcxx
namespace std {
template<>
class iterator_traits<ftcxx::Slice> {
typedef typename std::iterator_traits<const char *>::difference_type difference_type;
typedef typename std::iterator_traits<const char *>::value_type value_type;
typedef typename std::iterator_traits<const char *>::pointer pointer;
typedef typename std::iterator_traits<const char *>::reference reference;
typedef typename std::iterator_traits<const char *>::iterator_category iterator_category;
};
} // namespace std
<|endoftext|> |
<commit_before>// Copyright (c) 2015 The Brick Authors.
#include "brick/desktop_media.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include "include/internal/cef_linux.h"
#include "include/base/cef_logging.h"
namespace desktop_media {
bool
IsAcceptableState(::Window window) {
::XDisplay *display = cef_get_xdisplay();
Atom wm_state = XInternAtom(display, "WM_STATE", False);
Atom type;
int format;
unsigned long exists, bytes_left;
unsigned char *data;
bool result = false;
long request = XGetWindowProperty(display, window, wm_state, 0L, 2L, False,
wm_state, &type, &format, &exists,
&bytes_left, &data);
if (request != Success || !exists)
return result;
// Todo: also check WithdrawnState?
result = (*(long *) data) == NormalState;
XFree(data);
return result;
}
bool
IsDesktopElement(::Window window) {
::XDisplay *display = cef_get_xdisplay();
Atom wm_state = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
Atom normal_window_type = XInternAtom(display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
Atom type;
int format;
unsigned long exists, bytes_left;
unsigned char *data;
bool result = true;
long request = XGetWindowProperty(display, window, wm_state, 0L, sizeof(Atom), False,
XA_ATOM, &type, &format, &exists,
&bytes_left, &data);
if (request != Success || !exists)
return result;
result = (*(Atom *) data) == normal_window_type;
XFree(data);
return result;
}
bool
GetWindowTitle(::Window window, std::string* title) {
int status;
bool result = false;
XTextProperty window_name;
window_name.value = NULL;
if (!window)
return result;
status = XGetWMName(cef_get_xdisplay(), window, &window_name);
if (status && window_name.value && window_name.nitems) {
int cnt;
char **list = NULL;
status = Xutf8TextPropertyToTextList(cef_get_xdisplay(), &window_name, &list,
&cnt);
if (status >= Success && cnt && *list) {
if (cnt > 1) {
LOG(INFO) << "Window has " << cnt
<< " text properties, only using the first one.";
}
*title = *list;
result = true;
}
if (list)
XFreeStringList(list);
}
if (window_name.value)
XFree(window_name.value);
return result;
}
bool
EnumerateWindows(CefListValue* list) {
int last_index = list->GetSize();
int num_screens = XScreenCount(cef_get_xdisplay());
for (int screen = 0; screen < num_screens; ++screen) {
::Window root_window = XRootWindow(cef_get_xdisplay(), screen);
::Window parent;
::Window *children;
unsigned int num_children;
int status = XQueryTree(cef_get_xdisplay(), root_window, &root_window, &parent,
&children, &num_children);
if (status == 0) {
LOG(ERROR) << "Failed to query for child windows for screen "
<< screen;
continue;
}
for (unsigned int i = 0; i < num_children; ++i) {
// Iterate in reverse order to return windows from front to back.
::Window window = children[num_children - 1 - i];
std::string title;
if (
window
&& IsAcceptableState(window)
&& IsDesktopElement(window)
&& GetWindowTitle(window, &title)
) {
std::string id = "window:" + std::to_string(window);
CefRefPtr<CefListValue> media = CefListValue::Create();
media->SetString(0, id);
media->SetString(1, title);
list->SetList(last_index++, media);
}
}
if (children)
XFree(children);
}
return true;
}
bool
EnumerateScreens(CefListValue* list) {
// ToDo: implement when WebRTC starts support screen enumeration
CefRefPtr<CefListValue> media = CefListValue::Create();
media->SetString(0, "screen:0");
media->SetString(1, "Entire screen");
list->SetList(list->GetSize(), media);
return true;
}
} // namespace desktop_media
<commit_msg>Пробуем поддержкать WithdrawnState в листинге окон для шаринга<commit_after>// Copyright (c) 2015 The Brick Authors.
#include "brick/desktop_media.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include "include/internal/cef_linux.h"
#include "include/base/cef_logging.h"
namespace desktop_media {
::Window
GetApplicationWindow(::Window window) {
::XDisplay *display = cef_get_xdisplay();
Atom wm_state = XInternAtom(display, "WM_STATE", False);
Atom type;
int format;
unsigned long exists, bytes_left;
unsigned char *data;
long state;
long request = XGetWindowProperty(display, window, wm_state, 0L, 2L, False,
wm_state, &type, &format, &exists,
&bytes_left, &data);
if (request != Success || !exists)
return 0;
state = *(long *) data;
if (state == NormalState) {
// Window has WM_STATE == NormalState. It's good window:)
return window;
} else if (state == IconicState) {
// Window was minimized
return 0;
}
// If the window is in WithdrawnState then look at all of its children.
::Window root, parent;
::Window *children;
unsigned int num_children;
if (!XQueryTree(cef_get_xdisplay(), window, &root, &parent, &children,
&num_children)) {
LOG(ERROR) << "Failed to query for child windows although window"
<< "does not have a valid WM_STATE.";
return 0;
}
::Window app_window = 0;
for (unsigned int i = 0; i < num_children; ++i) {
app_window = GetApplicationWindow(children[i]);
if (app_window)
break;
}
if (children)
XFree(children);
return app_window;
}
bool
IsDesktopElement(::Window window) {
::XDisplay *display = cef_get_xdisplay();
Atom wm_state = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
Atom normal_window_type = XInternAtom(display, "_NET_WM_WINDOW_TYPE_NORMAL", False);
Atom type;
int format;
unsigned long exists, bytes_left;
unsigned char *data;
bool result = true;
long request = XGetWindowProperty(display, window, wm_state, 0L, sizeof(Atom), False,
XA_ATOM, &type, &format, &exists,
&bytes_left, &data);
if (request != Success || !exists)
return result;
result = (*(Atom *) data) == normal_window_type;
XFree(data);
return result;
}
bool
GetWindowTitle(::Window window, std::string* title) {
int status;
bool result = false;
XTextProperty window_name;
window_name.value = NULL;
if (!window)
return result;
status = XGetWMName(cef_get_xdisplay(), window, &window_name);
if (status && window_name.value && window_name.nitems) {
int cnt;
char **list = NULL;
status = Xutf8TextPropertyToTextList(cef_get_xdisplay(), &window_name, &list,
&cnt);
if (status >= Success && cnt && *list) {
if (cnt > 1) {
LOG(INFO) << "Window has " << cnt
<< " text properties, only using the first one.";
}
*title = *list;
result = true;
}
if (list)
XFreeStringList(list);
}
if (window_name.value)
XFree(window_name.value);
return result;
}
bool
EnumerateWindows(CefListValue* list) {
int last_index = list->GetSize();
int num_screens = XScreenCount(cef_get_xdisplay());
for (int screen = 0; screen < num_screens; ++screen) {
::Window root_window = XRootWindow(cef_get_xdisplay(), screen);
::Window parent;
::Window *children;
unsigned int num_children;
int status = XQueryTree(cef_get_xdisplay(), root_window, &root_window, &parent,
&children, &num_children);
if (status == 0) {
LOG(ERROR) << "Failed to query for child windows for screen "
<< screen;
continue;
}
for (unsigned int i = 0; i < num_children; ++i) {
// Iterate in reverse order to return windows from front to back.
::Window window = GetApplicationWindow(children[num_children - 1 - i]);
std::string title;
if (
window
&& IsDesktopElement(window)
&& GetWindowTitle(window, &title)
) {
std::string id = "window:" + std::to_string(window);
CefRefPtr<CefListValue> media = CefListValue::Create();
media->SetString(0, id);
media->SetString(1, title);
list->SetList(last_index++, media);
}
}
if (children)
XFree(children);
}
return true;
}
bool
EnumerateScreens(CefListValue* list) {
// ToDo: implement when WebRTC starts support screen enumeration
CefRefPtr<CefListValue> media = CefListValue::Create();
media->SetString(0, "screen:0");
media->SetString(1, "Entire screen");
list->SetList(list->GetSize(), media);
return true;
}
} // namespace desktop_media
<|endoftext|> |
<commit_before>#ifndef GENERICDATA_H
#define GENERICDATA_H
#include "taskdata.hpp"
#include "utils/dbg.hpp"
template <typename T>
class GenericData : public TaskData
{
public:
typedef T container_type;
const T & get_const() const
{
return m_data;
}
T & get_mutable()
{
m_valid = false;
return m_data;
}
virtual std::shared_ptr<TaskData> clone()
{
if (m_valid)
{
D() << "clone shared";
return shared_from_this();
}
else
{
D() << "clone copy";
return clone_copy();
}
}
protected:
GenericData(const std::string & name, std::size_t n)
: TaskData(name, n)
, m_valid(true)
{}
T m_data;
private:
GenericData(const GenericData &) = delete;
GenericData(GenericData &&) = delete;
GenericData operator=(const GenericData&) = delete;
GenericData operator=(GenericData &&) = delete;
bool m_valid;
};
#endif // GENERICDATA_H
<commit_msg>g++4.8 fixes<commit_after>#ifndef GENERICDATA_H
#define GENERICDATA_H
#include "taskdata.hpp"
#include "utils/dbg.hpp"
template <typename T>
class GenericData : public TaskData
{
public:
typedef T container_type;
const T & get_const() const
{
return m_data;
}
T & get_mutable()
{
m_valid = false;
return m_data;
}
virtual std::shared_ptr<TaskData> clone()
{
if (m_valid)
{
D() << "clone shared";
return shared_from_this();
}
else
{
D() << "clone copy";
return clone_copy();
}
}
protected:
GenericData(const std::string & name, std::size_t n)
: TaskData(name, n)
, m_valid(true)
{}
T m_data;
private:
GenericData(const GenericData<T> &) = delete;
GenericData(GenericData<T> &&) = delete;
GenericData<T>& operator=(const GenericData<T>&) = delete;
GenericData<T>& operator=(GenericData<T> &&) = delete;
bool m_valid;
};
#endif // GENERICDATA_H
<|endoftext|> |
<commit_before>
#include <iostream>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
template<typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn{
TMatrixType mA;
void initialize(TMatrixType& TheMatrix){
for(int i = 0 ; i < NumberOfRows ; i++)
for(int j = 0 ; j < NumberOfColumns ; j++)
TheMatrix(i,j) = 0.00;
}
public:
ComparisonColumn(){
initialize(mA);
}
Timer::duration_type MeasureAccessTime() {
int repeat_number = 10000000;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++)
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
mA(i, j) += i - j;
return timer.elapsed().count();
}
};
template <typename TMatrixType>
Timer::duration_type MeasureAssignTime(TMatrixType& A) {
int repeat_number = 10000000;
TMatrixType B = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
B(i, j) += i - j;
A = B;
}
return timer.elapsed().count();
}
template <typename TMatrixType>
Timer::duration_type MeasureSumTime(TMatrixType& A, TMatrixType& B) {
int repeat_number = 10000;
TMatrixType C = A;
TMatrixType D = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
C = A + B;
B = C;
}
return timer.elapsed().count();
}
template <typename TMatrixType1, typename TMatrixType2>
Timer::duration_type MeasureMultTime(TMatrixType1& A, TMatrixType2& B) {
int repeat_number = 1000;
TMatrixType1 C = A;
TMatrixType1 D = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
D = A;
for (int i = 0; i < 1000; i++) {
C = D * B;
D = C;
}
}
return timer.elapsed().count();
}
void CompareAccessTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>,3,3> a_matrix_column;
ComparisonColumn<Eigen::Matrix<double, 3, 3>,3,3> eigen_column;
std::cout << "A[i,j] += i -j\t\t" << a_matrix_column.MeasureAccessTime();
std::cout << "\t\t" << eigen_column.MeasureAccessTime() << std::endl;
}
void CompareAssignTime() {
AMatrix::Matrix<double, 3, 3> m_33(0.00);
std::cout << "A = B\t\t\t" << MeasureAssignTime(m_33) << std::endl;
}
int main() {
std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
CompareAccessTime();
CompareAssignTime();
return 0;
}
<commit_msg>Apply styling<commit_after>
#include <iostream>
#include "timer.h"
#include "matrix.h"
#if defined(AMATRIX_COMPARE_WITH_EIGEN)
#include "Eigen/Dense"
#endif
template <typename TMatrixType, int NumberOfRows, int NumberOfColumns>
class ComparisonColumn {
TMatrixType mA;
void initialize(TMatrixType& TheMatrix) {
for (int i = 0; i < NumberOfRows; i++)
for (int j = 0; j < NumberOfColumns; j++)
TheMatrix(i, j) = 0.00;
}
public:
ComparisonColumn() { initialize(mA); }
Timer::duration_type MeasureAccessTime() {
int repeat_number = 10000000;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++)
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
mA(i, j) += i - j;
return timer.elapsed().count();
}
};
template <typename TMatrixType>
Timer::duration_type MeasureAssignTime(TMatrixType& A) {
int repeat_number = 10000000;
TMatrixType B = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
B(i, j) += i - j;
A = B;
}
return timer.elapsed().count();
}
template <typename TMatrixType>
Timer::duration_type MeasureSumTime(TMatrixType& A, TMatrixType& B) {
int repeat_number = 10000;
TMatrixType C = A;
TMatrixType D = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
C = A + B;
B = C;
}
return timer.elapsed().count();
}
template <typename TMatrixType1, typename TMatrixType2>
Timer::duration_type MeasureMultTime(TMatrixType1& A, TMatrixType2& B) {
int repeat_number = 1000;
TMatrixType1 C = A;
TMatrixType1 D = A;
Timer timer;
for (int i_repeat = 0; i_repeat < repeat_number; i_repeat++) {
D = A;
for (int i = 0; i < 1000; i++) {
C = D * B;
D = C;
}
}
return timer.elapsed().count();
}
void CompareAccessTime() {
ComparisonColumn<AMatrix::Matrix<double, 3, 3>, 3, 3> a_matrix_column;
ComparisonColumn<Eigen::Matrix<double, 3, 3>, 3, 3> eigen_column;
std::cout << "A[i,j] += i -j\t\t" << a_matrix_column.MeasureAccessTime();
std::cout << "\t\t" << eigen_column.MeasureAccessTime() << std::endl;
}
void CompareAssignTime() {
AMatrix::Matrix<double, 3, 3> m_33(0.00);
std::cout << "A = B\t\t\t" << MeasureAssignTime(m_33) << std::endl;
}
int main() {
std::cout << "operation\t\tAMatrix\t\tEigen\t\tUblas\t\tAtlas" << std::endl;
CompareAccessTime();
CompareAssignTime();
return 0;
}
<|endoftext|> |
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided 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 <stdio.h>
#include "allocator.h"
int
main(int argc, char* argv[])
{
return 0;
}
<commit_msg>add test for single memory allocator<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided 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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "allocator.h"
struct test_data_t {
int id_;
char name_[32];
};
int
main(int argc, char* argv[])
{
const int ALLOC_TIMES = 10000, LOOP_TIMES = 500;
clock_t beg, end;
int counter;
size_t size = sizeof(test_data_t);
test_data_t* arr[ALLOC_TIMES];
counter = 0;
beg = clock();
while (counter++ < LOOP_TIMES) {
for (int i = 0; i < ALLOC_TIMES; ++i) {
arr[i] = (test_data_t*)malloc(size);
free(arr[i]);
}
}
end = clock();
fprintf(stdout, "default use %lu\n", end - beg);
counter = 0;
beg = clock();
while (counter++ < LOOP_TIMES) {
for (int i = 0; i < ALLOC_TIMES; ++i) {
arr[i] = (test_data_t*)allocator_t::singleton().alloc(size);
allocator_t::singleton().dealloc(arr[i], size);
}
}
end = clock();
fprintf(stdout, "default use %lu\n", end - beg);
return 0;
}
<|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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // namespace
<commit_msg>DevTools: temporarily disable breakpoint tests<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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // 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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
// Flaky: http://code.google.com/p/chromium/issues/detail?id=23768
// TODO(mnaganov): fix the problem in V8 and roll it out.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // namespace
<commit_msg>DevTools: temporarily disable failing test<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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
// Flaky: http://code.google.com/p/chromium/issues/detail?id=23768
// TODO(mnaganov): fix the problem in V8 and roll it out.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // 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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<commit_msg>Disable DevToolsExtensionDebugTest.TestContentScriptIsPresent because it started failing after the webkit merge.<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 "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kPauseOnExceptionTestPage[] =
L"files/devtools/pause_on_exception.html";
const wchar_t kPauseWhenLoadingDevTools[] =
L"files/devtools/pause_when_loading_devtools.html";
const wchar_t kResourceContentLengthTestPage[] = L"files/devtools/image.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
const wchar_t kDebuggerIntrinsicPropertiesPage[] =
L"files/devtools/debugger_intrinsic_properties.html";
const wchar_t kCompletionOnPause[] =
L"files/devtools/completion_on_pause.html";
const wchar_t kPageWithContentScript[] =
L"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Reset inspector settings to defaults to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->UpdateInspectorSettings(
WebPreferences().inspector_settings);
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
DISABLED_TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that intrinsic properties(__proto__, prototype, constructor) are
// present.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestDebugIntrinsicProperties) {
RunTest("testDebugIntrinsicProperties", kDebuggerIntrinsicPropertiesPage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
} // namespace
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseOnExceptionTestPage[] =
"files/devtools/pause_on_exception.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kSyntaxErrorTestPage[] =
"files/devtools/script_syntax_error.html";
const char kDebuggerClosurePage[] =
"files/devtools/debugger_closure.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
// The test fails on linux and should be related to Webkit patch
// http://trac.webkit.org/changeset/64124/trunk.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests that scope can be expanded and contains expected variables.
// TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, FAILS_TestMessageLoopReentrant) {
RunTest("testMessageLoopReentrant", kDebuggerTestPage);
}
} // namespace
<commit_msg>Second try for DevTools sanity tests start failing after rolling WebKit from 65992 to 66033<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
explicit BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseOnExceptionTestPage[] =
"files/devtools/pause_on_exception.html";
const char kPauseWhenLoadingDevTools[] =
"files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
"files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kSyntaxErrorTestPage[] =
"files/devtools/script_syntax_error.html";
const char kDebuggerClosurePage[] =
"files/devtools/debugger_closure.html";
const char kCompletionOnPause[] =
"files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
"files/devtools/page_with_content_script.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::string& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::string& test_page) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL(test_page);
ui_test_utils::NavigateToURL(browser(), url);
inspected_rvh_ = GetInspectedTab()->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
TabContents* GetInspectedTab() {
return browser()->GetTabContentsAt(0);
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
// Wait only when DevToolsWindow has a browser. For docked DevTools, this
// is NULL and we skip the wait.
if (browser)
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
class CancelableQuitTask : public Task {
public:
explicit CancelableQuitTask(const std::string& timeout_message)
: timeout_message_(timeout_message),
cancelled_(false) {
}
void cancel() {
cancelled_ = true;
}
virtual void Run() {
if (cancelled_) {
return;
}
FAIL() << timeout_message_;
MessageLoop::current()->Quit();
}
private:
std::string timeout_message_;
bool cancelled_;
};
// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
public NotificationObserver {
public:
DevToolsExtensionDebugTest() : DevToolsSanityTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
}
protected:
// Load an extention from test\data\devtools\extensions\<extension_name>
void LoadExtension(const char* extension_name) {
FilePath path = test_extensions_dir_.AppendASCII(extension_name);
ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
}
private:
bool LoadExtensionFromPath(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
{
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_LOADED,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
service->LoadExtension(path);
ui_test_utils::RunMessageLoop();
delayed_quit->cancel();
}
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
NotificationService::AllSources());
CancelableQuitTask* delayed_quit =
new CancelableQuitTask("Extension host load timed out.");
MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
4*1000);
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end();) {
if ((*iter)->did_stop_loading())
++iter;
else
ui_test_utils::RunMessageLoop();
}
delayed_quit->cancel();
return true;
}
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_LOADED:
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
FilePath test_extensions_dir_;
};
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif // defined(OS_LINUX)
// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
RunTest("testCachedResourceMimeType", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
RunTest("testHeapProfiler", kHeapProfilerPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
// Clear inspector settings to ensure that Elements will be
// current panel when DevTools window is open.
GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
kDebuggerTestPage);
}
// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
TestContentScriptIsPresent) {
LoadExtension("simple_content_script");
RunTest("testContentScriptIsPresent", kPageWithContentScript);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests pause on exception.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) {
RunTest("testPauseOnException", kPauseOnExceptionTestPage);
}
// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestPauseWhenLoadingDevTools) {
RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}
// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
// The test fails on linux and should be related to Webkit patch
// http://trac.webkit.org/changeset/64124/trunk.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) {
RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}
// Tests that scope can be expanded and contains expected variables.
// TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) {
RunTest("testCompletionOnPause", kCompletionOnPause);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
RunTest("testShowStoragePanel", kDebuggerTestPage);
}
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMessageLoopReentrant) {
RunTest("testMessageLoopReentrant", kDebuggerTestPage);
}
} // 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/extensions/extension_apitest.h"
// Flaky, http://crbug.com/20828. Please consult phajdan.jr before re-enabling.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) {
ASSERT_TRUE(RunExtensionTest("tabs")) << message_;
}
<commit_msg>Re-disable ExtensionApiTest.Tabs (flakey)<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_apitest.h"
// Flaky, http://crbug.com/20828. Please consult phajdan.jr before re-enabling.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Tabs) {
ASSERT_TRUE(RunExtensionTest("tabs")) << message_;
}
<|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_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_MACOSX)
// Tabs appears to timeout, or maybe crash on mac.
// http://crbug.com/53779
#define MAYBE_Tabs FAILS_Tabs
#elif defined(OS_WIN)
// It's flaky on win.
// http://crbug.com/58269
#define MAYBE_Tabs FLAKY_Tabs
#else
#define MAYBE_Tabs Tabs
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<commit_msg>Enable ExtensionApiTest.Tabs on Mac and remove FLAKY prefix from Win.<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_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) {
ASSERT_TRUE(test_server()->Start());
// The test creates a tab and checks that the URL of the new tab
// is that of the new tab page. Make sure the pref that controls
// this is set.
browser()->profile()->GetPrefs()->SetBoolean(
prefs::kHomePageIsNewTabPage, true);
ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_jpeg.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabPng) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab",
"test_png.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
ASSERT_TRUE(test_server()->Start());
ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<|endoftext|> |
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if(eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";")
for(int i = 0; i < xDataList.GetCount(); ++i)
{
if(nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if(nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for(bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",")
if(xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if(strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if(nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<commit_msg>fixed for compile<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCProperty.cpp
// @Author : LvSheng.Huang
// @Date : 2012-03-01
// @Module : NFCProperty
//
// -------------------------------------------------------------------------
#include "NFCProperty.h"
#include <complex>
NFCProperty::NFCProperty()
{
mbPublic = false;
mbPrivate = false;
mbSave = false;
mSelf = NFGUID();
eType = TDATA_UNKNOWN;
msPropertyName = "";
}
NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, const std::string& strRelationValue)
{
mbPublic = bPublic;
mbPrivate = bPrivate;
mbSave = bSave;
mSelf = self;
msPropertyName = strPropertyName;
mstrRelationValue = strRelationValue;
eType = varType;
}
NFCProperty::~NFCProperty()
{
for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
{
iter->reset();
}
mtPropertyCallback.clear();
mxData.reset();
}
void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
if (eType != TData.GetType())
{
return;
}
if (!mxData.get())
{
if (!TData.IsNullValue())
{
return;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->variantData = TData.variantData;
NFCDataList::TData newValue;
newValue = *mxData;
OnEventHandler(oldValue , newValue);
}
void NFCProperty::SetValue(const NFIProperty* pProperty)
{
SetValue(pProperty->GetValue());
}
const NFIDataList::TData& NFCProperty::GetValue() const
{
if (mxData.get())
{
return *mxData;
}
return NULL_TDATA;
}
const std::string& NFCProperty::GetKey() const
{
return msPropertyName;
}
const bool NFCProperty::GetSave() const
{
return mbSave;
}
const bool NFCProperty::GetPublic() const
{
return mbPublic;
}
const bool NFCProperty::GetPrivate() const
{
return mbPrivate;
}
const std::string& NFCProperty::GetRelationValue() const
{
return mstrRelationValue;
}
void NFCProperty::SetSave(bool bSave)
{
mbSave = bSave;
}
void NFCProperty::SetPublic(bool bPublic)
{
mbPublic = bPublic;
}
void NFCProperty::SetPrivate(bool bPrivate)
{
mbPrivate = bPrivate;
}
void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
mstrRelationValue = strRelationValue;
}
NFINT64 NFCProperty::GetInt() const
{
if (!mxData.get())
{
return 0;
}
return mxData->GetInt();
}
double NFCProperty::GetFloat() const
{
if (!mxData.get())
{
return 0.0;
}
return mxData->GetFloat();
}
const std::string& NFCProperty::GetString() const
{
if (!mxData.get())
{
return NULL_STR;
}
return mxData->GetString();
}
const NFGUID& NFCProperty::GetObject() const
{
if (!mxData.get())
{
return NULL_OBJECT;
}
return mxData->GetObject();
}
void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
mtPropertyCallback.push_back(cb);
}
int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
if (mtPropertyCallback.size() <= 0)
{
return 0;
}
TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
for (it; it != end; ++it)
{
//NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
}
return 0;
}
bool NFCProperty::SetInt(const NFINT64 value)
{
if (eType != TDATA_INT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (0 == value)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
mxData->SetInt(0);
}
if (value == mxData->GetInt())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetInt(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetFloat(const double value)
{
if (eType != TDATA_FLOAT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (std::abs(value) < 0.001)
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
mxData->SetFloat(0.0);
}
if (value - mxData->GetFloat() < 0.001)
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetFloat(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetString(const std::string& value)
{
if (eType != TDATA_STRING)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.empty())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
mxData->SetString(NULL_STR);
}
if (value == mxData->GetString())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetString(value);
OnEventHandler(oldValue, *mxData);
return true;
}
bool NFCProperty::SetObject(const NFGUID& value)
{
if (eType != TDATA_OBJECT)
{
return false;
}
if (!mxData.get())
{
//ǿվΪûݣûݵľͲ
if (value.IsNull())
{
return false;
}
mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
mxData->SetObject(NFGUID());
}
if (value == mxData->GetObject())
{
return false;
}
NFCDataList::TData oldValue;
oldValue = *mxData;
mxData->SetObject(value);
OnEventHandler(oldValue , *mxData);
return true;
}
bool NFCProperty::Changed() const
{
return GetValue().IsNullValue();
}
const TDATA_TYPE NFCProperty::GetType() const
{
return eType;
}
const bool NFCProperty::GeUsed() const
{
if (mxData.get())
{
return true;
}
return false;
}
std::string NFCProperty::ToString()
{
std::string strData;
const TDATA_TYPE eType = GetType();
switch (eType)
{
case TDATA_INT:
strData = lexical_cast<std::string> (GetInt());
break;
case TDATA_FLOAT:
strData = lexical_cast<std::string> (GetFloat());
break;
case TDATA_STRING:
strData = GetString();
break;
case TDATA_OBJECT:
strData = GetObject().ToString();
break;
default:
strData = NULL_STR;
break;
}
return strData;
}
bool NFCProperty::FromString(const std::string& strData)
{
const TDATA_TYPE eType = GetType();
bool bRet = false;
switch (eType)
{
case TDATA_INT:
{
NFINT64 nValue = 0;
bRet = NF_StrTo(strData, nValue);
SetInt(nValue);
}
break;
case TDATA_FLOAT:
{
double dValue = 0;
bRet = NF_StrTo(strData, dValue);
SetFloat(dValue);
}
break;
case TDATA_STRING:
{
SetString(strData);
bRet = true;
}
break;
case TDATA_OBJECT:
{
NFGUID xID;
bRet = xID.FromString(strData);
SetObject(xID);
}
break;
default:
break;
}
return bRet;
}
bool NFCProperty::DeSerialization()
{
bool bRet = false;
const TDATA_TYPE eType = GetType();
if (eType == TDATA_STRING)
{
NFCDataList xDataList;
const std::string& strData = mxData->GetString();
xDataList.Split(strData.c_str(), ";");
for (int i = 0; i < xDataList.GetCount(); ++i)
{
if (nullptr == mxEmbeddedList)
{
mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
}
else
{
mxEmbeddedList->ClearAll();
}
if(xDataList.String(i).empty())
{
NFASSERT(0, strData, __FILE__, __FUNCTION__);
}
mxEmbeddedList->Add(xDataList.String(i));
}
if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
{
std::string strTemData;
for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
{
NFCDataList xTemDataList;
xTemDataList.Split(strTemData.c_str(), ",");
if (xTemDataList.GetCount() > 0)
{
if (xTemDataList.GetCount() != 2)
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
const std::string& strKey = xTemDataList.String(0);
const std::string& strValue = xTemDataList.String(0);
if (strKey.empty() || strValue.empty())
{
NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
}
if (nullptr == mxEmbeddedMap)
{
mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
}
else
{
mxEmbeddedMap->ClearAll();
}
mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
}
}
bRet = true;
}
}
return bRet;
}
const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
return this->mxEmbeddedList;
}
const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
return this->mxEmbeddedMap;
}
<|endoftext|> |
<commit_before>/*
* PhraseTableMemory.cpp
*
* Created on: 28 Oct 2015
* Author: hieu
*/
#include <cassert>
#include <boost/foreach.hpp>
#include "PhraseTableMemory.h"
#include "../../PhraseBased/PhraseImpl.h"
#include "../../Phrase.h"
#include "../../System.h"
#include "../../Scores.h"
#include "../../InputPathsBase.h"
#include "../../legacy/InputFileStream.h"
#include "util/exception.hh"
#include "../../PhraseBased/InputPath.h"
#include "../../PhraseBased/TargetPhraseImpl.h"
#include "../../PhraseBased/TargetPhrases.h"
#include "../../SCFG/PhraseImpl.h"
#include "../../SCFG/TargetPhraseImpl.h"
#include "../../SCFG/InputPath.h"
#include "../../SCFG/Stack.h"
#include "../../SCFG/Stacks.h"
#include "../../SCFG/Manager.h"
using namespace std;
namespace Moses2
{
////////////////////////////////////////////////////////////////////////
PhraseTableMemory::PhraseTableMemory(size_t startInd, const std::string &line) :
PhraseTable(startInd, line)
{
ReadParameters();
}
PhraseTableMemory::~PhraseTableMemory()
{
// TODO Auto-generated destructor stub
}
void PhraseTableMemory::Load(System &system)
{
FactorCollection &vocab = system.GetVocab();
MemPool &systemPool = system.GetSystemPool();
MemPool tmpSourcePool;
vector<string> toks;
size_t lineNum = 0;
InputFileStream strme(m_path);
string line;
while (getline(strme, line)) {
if (++lineNum % 1000000 == 0) {
cerr << lineNum << " ";
}
toks.clear();
TokenizeMultiCharSeparator(toks, line, "|||");
UTIL_THROW_IF2(toks.size() < 3, "Wrong format");
//cerr << "line=" << line << endl;
Phrase<Moses2::Word> *source;
TargetPhrase<Moses2::Word> *target;
if (system.isPb) {
source = PhraseImpl::CreateFromString(tmpSourcePool, vocab, system,
toks[0]);
//cerr << "created soure" << endl;
target = TargetPhraseImpl::CreateFromString(systemPool, *this, system,
toks[1]);
//cerr << "created target" << endl;
target->GetScores().CreateFromString(toks[2], *this, system, true);
//cerr << "created scores:" << *target << endl;
// properties
if (toks.size() == 7) {
//target->properties = (char*) system.systemPool.Allocate(toks[6].size() + 1);
//strcpy(target->properties, toks[6].c_str());
}
system.featureFunctions.EvaluateInIsolation(systemPool, system, *source,
*target);
//cerr << "EvaluateInIsolation:" << *target << endl;
m_rootPb.AddRule(*source, target);
}
else {
//source = SCFG::PhraseImpl::CreateFromString(tmpSourcePool, vocab, system,
// toks[0]);
//cerr << "created soure" << endl;
SCFG::TargetPhraseImpl *targetSCFG;
targetSCFG = SCFG::TargetPhraseImpl::CreateFromString(systemPool, *this,
system, toks[1]);
targetSCFG->SetAlignmentInfo(toks[3]);
//target = targetSCFG;
cerr << "created target " << *targetSCFG << endl;
target->GetScores().CreateFromString(toks[2], *this, system, true);
//cerr << "created scores:" << *target << endl;
// properties
if (toks.size() == 7) {
//target->properties = (char*) system.systemPool.Allocate(toks[6].size() + 1);
//strcpy(target->properties, toks[6].c_str());
}
system.featureFunctions.EvaluateInIsolation(systemPool, system, *source,
*target);
//cerr << "EvaluateInIsolation:" << *target << endl;
//m_rootSCFG.AddRule(*source, target);
}
}
m_rootPb.SortAndPrune(m_tableLimit, systemPool, system);
cerr << "root=" << &m_rootPb << endl;
BOOST_FOREACH(const PtMem::Node<Word>::Children::value_type &valPair, m_rootPb.GetChildren()) {
const Word &word = valPair.first;
cerr << word << " ";
}
cerr << endl;
}
TargetPhrases* PhraseTableMemory::Lookup(const Manager &mgr, MemPool &pool,
InputPath &inputPath) const
{
const SubPhrase<Moses2::Word> &phrase = inputPath.subPhrase;
TargetPhrases *tps = m_rootPb.Find(phrase);
return tps;
}
void PhraseTableMemory::InitActiveChart(SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
ActiveChartEntryMem *chartEntry = new ActiveChartEntryMem(NULL, false, &m_rootPb);
path.AddActiveChartEntry(ptInd, chartEntry);
}
void PhraseTableMemory::Lookup(MemPool &pool,
const SCFG::Manager &mgr,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
size_t endPos = path.range.GetEndPos();
// TERMINAL
const Word &lastWord = path.subPhrase.Back();
//cerr << "PhraseTableMemory lastWord=" << lastWord << endl;
//cerr << "path=" << path << endl;
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(endPos, 1);
const SCFG::InputPath *prefixPath = static_cast<const SCFG::InputPath*>(path.prefixPath);
UTIL_THROW_IF2(prefixPath == NULL, "prefixPath == NULL");
LookupGivenPrefixPath(*prefixPath, lastWord, subPhrasePath, false, path);
// NON-TERMINAL
//const SCFG::InputPath *prefixPath = static_cast<const SCFG::InputPath*>(path.prefixPath);
while (prefixPath) {
const Range &prefixRange = prefixPath->range;
//cerr << "prefixRange=" << prefixRange << endl;
size_t startPos = prefixRange.GetEndPos() + 1;
size_t ntSize = endPos - startPos + 1;
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(startPos, ntSize);
const SCFG::Stack &ntStack = stacks.GetStack(startPos, ntSize);
const SCFG::Stack::Coll &coll = ntStack.GetColl();
BOOST_FOREACH (const SCFG::Stack::Coll::value_type &valPair, coll) {
const SCFG::Word &ntSought = valPair.first;
//cerr << "ntSought=" << ntSought << ntSought.isNonTerminal << endl;
LookupGivenPrefixPath(*prefixPath, ntSought, subPhrasePath, true, path);
}
prefixPath = static_cast<const SCFG::InputPath*>(prefixPath->prefixPath);
}
}
void PhraseTableMemory::LookupGivenPrefixPath(const SCFG::InputPath &prefixPath,
const Word &wordSought,
const SCFG::InputPath &subPhrasePath,
bool isNT,
SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
cerr << "prefixPath=" << prefixPath.range << " " << prefixPath.GetActiveChart(ptInd).entries.size() << endl;
BOOST_FOREACH(const SCFG::ActiveChartEntry *entry, prefixPath.GetActiveChart(ptInd).entries) {
const ActiveChartEntryMem *entryCast = static_cast<const ActiveChartEntryMem*>(entry);
const PtMem::Node<Word> *node = entryCast->node;
UTIL_THROW_IF2(node == NULL, "node == NULL");
cerr << "node=" << node << endl;
LookupGivenNode(*node, wordSought, subPhrasePath, isNT, path);
}
}
void PhraseTableMemory::LookupGivenNode(const PtMem::Node<Word> &node,
const Word &wordSought,
const SCFG::InputPath &subPhrasePath,
bool isNT,
SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
const PtMem::Node<Word> *nextNode = node.Find(wordSought);
cerr << "wordSought=" << wordSought << " " << nextNode << endl;
if (nextNode) {
// new entries
ActiveChartEntryMem *chartEntry = new ActiveChartEntryMem(&subPhrasePath, isNT, nextNode);
path.AddActiveChartEntry(ptInd, chartEntry);
const SCFG::SymbolBind &symbolBind = chartEntry->symbolBinds;
// there are some rules
AddTargetPhrasesToPath(*nextNode, symbolBind, path);
}
}
void PhraseTableMemory::AddTargetPhrasesToPath(const PtMem::Node<Word> &node,
const SCFG::SymbolBind &symbolBind,
SCFG::InputPath &path) const
{
/*
const TargetPhrases *tps = node.GetTargetPhrases();
if (tps) {
TargetPhrases::const_iterator iter;
for (iter = tps->begin(); iter != tps->end(); ++iter) {
const TargetPhrase<Moses2::Word> *tp = *iter;
const SCFG::TargetPhraseImpl *tpCast = static_cast<const SCFG::TargetPhraseImpl*>(tp);
cerr << "tpCast=" << *tpCast << endl;
path.AddTargetPhrase(*this, symbolBind, tpCast);
}
}
*/
}
}
<commit_msg>pt mem<commit_after>/*
* PhraseTableMemory.cpp
*
* Created on: 28 Oct 2015
* Author: hieu
*/
#include <cassert>
#include <boost/foreach.hpp>
#include "PhraseTableMemory.h"
#include "../../PhraseBased/PhraseImpl.h"
#include "../../Phrase.h"
#include "../../System.h"
#include "../../Scores.h"
#include "../../InputPathsBase.h"
#include "../../legacy/InputFileStream.h"
#include "util/exception.hh"
#include "../../PhraseBased/InputPath.h"
#include "../../PhraseBased/TargetPhraseImpl.h"
#include "../../PhraseBased/TargetPhrases.h"
#include "../../SCFG/PhraseImpl.h"
#include "../../SCFG/TargetPhraseImpl.h"
#include "../../SCFG/InputPath.h"
#include "../../SCFG/Stack.h"
#include "../../SCFG/Stacks.h"
#include "../../SCFG/Manager.h"
using namespace std;
namespace Moses2
{
////////////////////////////////////////////////////////////////////////
PhraseTableMemory::PhraseTableMemory(size_t startInd, const std::string &line) :
PhraseTable(startInd, line)
{
ReadParameters();
}
PhraseTableMemory::~PhraseTableMemory()
{
// TODO Auto-generated destructor stub
}
void PhraseTableMemory::Load(System &system)
{
FactorCollection &vocab = system.GetVocab();
MemPool &systemPool = system.GetSystemPool();
MemPool tmpSourcePool;
vector<string> toks;
size_t lineNum = 0;
InputFileStream strme(m_path);
string line;
while (getline(strme, line)) {
if (++lineNum % 1000000 == 0) {
cerr << lineNum << " ";
}
toks.clear();
TokenizeMultiCharSeparator(toks, line, "|||");
UTIL_THROW_IF2(toks.size() < 3, "Wrong format");
//cerr << "line=" << line << endl;
if (system.isPb) {
PhraseImpl *source = PhraseImpl::CreateFromString(tmpSourcePool, vocab, system,
toks[0]);
//cerr << "created soure" << endl;
TargetPhraseImpl *target = TargetPhraseImpl::CreateFromString(systemPool, *this, system,
toks[1]);
//cerr << "created target" << endl;
target->GetScores().CreateFromString(toks[2], *this, system, true);
//cerr << "created scores:" << *target << endl;
// properties
if (toks.size() == 7) {
//target->properties = (char*) system.systemPool.Allocate(toks[6].size() + 1);
//strcpy(target->properties, toks[6].c_str());
}
system.featureFunctions.EvaluateInIsolation(systemPool, system, *source,
*target);
//cerr << "EvaluateInIsolation:" << *target << endl;
m_rootPb.AddRule(*source, target);
}
else {
SCFG::PhraseImpl *source = SCFG::PhraseImpl::CreateFromString(tmpSourcePool, vocab, system,
toks[0]);
//cerr << "created soure" << endl;
SCFG::TargetPhraseImpl *target = SCFG::TargetPhraseImpl::CreateFromString(systemPool, *this,
system, toks[1]);
target->SetAlignmentInfo(toks[3]);
cerr << "created target " << *target << endl;
target->GetScores().CreateFromString(toks[2], *this, system, true);
//cerr << "created scores:" << *target << endl;
// properties
if (toks.size() == 7) {
//target->properties = (char*) system.systemPool.Allocate(toks[6].size() + 1);
//strcpy(target->properties, toks[6].c_str());
}
//system.featureFunctions.EvaluateInIsolation(systemPool, system, *source,
// *target);
//cerr << "EvaluateInIsolation:" << *target << endl;
//m_rootSCFG.AddRule(*source, target);
}
}
m_rootPb.SortAndPrune(m_tableLimit, systemPool, system);
cerr << "root=" << &m_rootPb << endl;
BOOST_FOREACH(const PtMem::Node<Word>::Children::value_type &valPair, m_rootPb.GetChildren()) {
const Word &word = valPair.first;
cerr << word << " ";
}
cerr << endl;
}
TargetPhrases* PhraseTableMemory::Lookup(const Manager &mgr, MemPool &pool,
InputPath &inputPath) const
{
const SubPhrase<Moses2::Word> &phrase = inputPath.subPhrase;
TargetPhrases *tps = m_rootPb.Find(phrase);
return tps;
}
void PhraseTableMemory::InitActiveChart(SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
ActiveChartEntryMem *chartEntry = new ActiveChartEntryMem(NULL, false, &m_rootPb);
path.AddActiveChartEntry(ptInd, chartEntry);
}
void PhraseTableMemory::Lookup(MemPool &pool,
const SCFG::Manager &mgr,
const SCFG::Stacks &stacks,
SCFG::InputPath &path) const
{
size_t endPos = path.range.GetEndPos();
// TERMINAL
const Word &lastWord = path.subPhrase.Back();
//cerr << "PhraseTableMemory lastWord=" << lastWord << endl;
//cerr << "path=" << path << endl;
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(endPos, 1);
const SCFG::InputPath *prefixPath = static_cast<const SCFG::InputPath*>(path.prefixPath);
UTIL_THROW_IF2(prefixPath == NULL, "prefixPath == NULL");
LookupGivenPrefixPath(*prefixPath, lastWord, subPhrasePath, false, path);
// NON-TERMINAL
//const SCFG::InputPath *prefixPath = static_cast<const SCFG::InputPath*>(path.prefixPath);
while (prefixPath) {
const Range &prefixRange = prefixPath->range;
//cerr << "prefixRange=" << prefixRange << endl;
size_t startPos = prefixRange.GetEndPos() + 1;
size_t ntSize = endPos - startPos + 1;
const SCFG::InputPath &subPhrasePath = *mgr.GetInputPaths().GetMatrix().GetValue(startPos, ntSize);
const SCFG::Stack &ntStack = stacks.GetStack(startPos, ntSize);
const SCFG::Stack::Coll &coll = ntStack.GetColl();
BOOST_FOREACH (const SCFG::Stack::Coll::value_type &valPair, coll) {
const SCFG::Word &ntSought = valPair.first;
//cerr << "ntSought=" << ntSought << ntSought.isNonTerminal << endl;
LookupGivenPrefixPath(*prefixPath, ntSought, subPhrasePath, true, path);
}
prefixPath = static_cast<const SCFG::InputPath*>(prefixPath->prefixPath);
}
}
void PhraseTableMemory::LookupGivenPrefixPath(const SCFG::InputPath &prefixPath,
const Word &wordSought,
const SCFG::InputPath &subPhrasePath,
bool isNT,
SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
cerr << "prefixPath=" << prefixPath.range << " " << prefixPath.GetActiveChart(ptInd).entries.size() << endl;
BOOST_FOREACH(const SCFG::ActiveChartEntry *entry, prefixPath.GetActiveChart(ptInd).entries) {
const ActiveChartEntryMem *entryCast = static_cast<const ActiveChartEntryMem*>(entry);
const PtMem::Node<Word> *node = entryCast->node;
UTIL_THROW_IF2(node == NULL, "node == NULL");
cerr << "node=" << node << endl;
LookupGivenNode(*node, wordSought, subPhrasePath, isNT, path);
}
}
void PhraseTableMemory::LookupGivenNode(const PtMem::Node<Word> &node,
const Word &wordSought,
const SCFG::InputPath &subPhrasePath,
bool isNT,
SCFG::InputPath &path) const
{
size_t ptInd = GetPtInd();
const PtMem::Node<Word> *nextNode = node.Find(wordSought);
cerr << "wordSought=" << wordSought << " " << nextNode << endl;
if (nextNode) {
// new entries
ActiveChartEntryMem *chartEntry = new ActiveChartEntryMem(&subPhrasePath, isNT, nextNode);
path.AddActiveChartEntry(ptInd, chartEntry);
const SCFG::SymbolBind &symbolBind = chartEntry->symbolBinds;
// there are some rules
AddTargetPhrasesToPath(*nextNode, symbolBind, path);
}
}
void PhraseTableMemory::AddTargetPhrasesToPath(const PtMem::Node<Word> &node,
const SCFG::SymbolBind &symbolBind,
SCFG::InputPath &path) const
{
/*
const TargetPhrases *tps = node.GetTargetPhrases();
if (tps) {
TargetPhrases::const_iterator iter;
for (iter = tps->begin(); iter != tps->end(); ++iter) {
const TargetPhrase<Moses2::Word> *tp = *iter;
const SCFG::TargetPhraseImpl *tpCast = static_cast<const SCFG::TargetPhraseImpl*>(tp);
cerr << "tpCast=" << *tpCast << endl;
path.AddTargetPhrase(*this, symbolBind, tpCast);
}
}
*/
}
}
<|endoftext|> |
<commit_before>#include "xchainer/memory.h"
#include <cassert>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/backend.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
namespace internal {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.isManaged) {
return true;
} else {
throw XchainerError("Non-managed GPU memory is not supported");
}
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
(void)ptr; // unused
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(Device& device, size_t bytesize) {
// TODO(sonots): Use device.backend().Allocate()
if (device.backend().GetName() == "native") {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device.backend().GetName() == "cuda") {
void* raw_ptr = nullptr;
// Be careful to be exception-safe, i.e., do not throw before creating shared_ptr
cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);
if (status == cudaSuccess) {
return std::shared_ptr<void>{raw_ptr, cudaFree};
} else {
cuda::Throw(status);
}
assert(false); // should never be reached
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
// Copy from device to device is faster even in unified memory
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
// TODO(sonots): Use device.backend().FromBuffer()
#ifdef XCHAINER_ENABLE_CUDA
if (device.backend().GetName() == "native") {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device.backend().GetName() == "cuda") {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
(void)bytesize; // unused
if (device.backend().GetName() == "native") {
return src_ptr;
} else {
throw DeviceError("invalid device");
}
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace internal
} // namespace xchainer
<commit_msg>Add missing include<commit_after>#include "xchainer/memory.h"
#include <cassert>
#include <cstring>
#ifdef XCHAINER_ENABLE_CUDA
#include <cuda.h>
#include <cuda_runtime.h>
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/backend.h"
#ifdef XCHAINER_ENABLE_CUDA
#include "xchainer/cuda/cuda_runtime.h"
#endif // XCHAINER_ENABLE_CUDA
#include "xchainer/device.h"
#include "xchainer/error.h"
namespace xchainer {
namespace internal {
bool IsPointerCudaMemory(const void* ptr) {
#ifdef XCHAINER_ENABLE_CUDA
cudaPointerAttributes attr = {};
cudaError_t status = cudaPointerGetAttributes(&attr, ptr);
switch (status) {
case cudaSuccess:
if (attr.isManaged) {
return true;
} else {
throw XchainerError("Non-managed GPU memory is not supported");
}
case cudaErrorInvalidValue:
return false;
default:
cuda::CheckError(status);
break;
}
assert(false); // should never be reached
#else
(void)ptr; // unused
return false;
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> Allocate(Device& device, size_t bytesize) {
// TODO(sonots): Use device.backend().Allocate()
if (device.backend().GetName() == "native") {
return std::make_unique<uint8_t[]>(bytesize);
#ifdef XCHAINER_ENABLE_CUDA
} else if (device.backend().GetName() == "cuda") {
void* raw_ptr = nullptr;
// Be careful to be exception-safe, i.e., do not throw before creating shared_ptr
cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);
if (status == cudaSuccess) {
return std::shared_ptr<void>{raw_ptr, cudaFree};
} else {
cuda::Throw(status);
}
assert(false); // should never be reached
#endif // XCHAINER_ENABLE_CUDA
} else {
throw DeviceError("invalid device");
}
}
void MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {
#ifdef XCHAINER_ENABLE_CUDA
bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);
bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);
if (is_dst_cuda_memory) {
if (is_src_cuda_memory) {
// Copy from device to device is faster even in unified memory
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));
} else {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));
}
} else {
if (is_src_cuda_memory) {
// For pre-6.x GPU architecture, we encountered SEGV with std::memcpy
// ref. https://github.com/pfnet/xchainer/pull/74
cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));
} else {
std::memcpy(dst_ptr, src_ptr, bytesize);
}
}
#else
std::memcpy(dst_ptr, src_ptr, bytesize);
#endif // XCHAINER_ENABLE_CUDA
}
std::shared_ptr<void> MemoryFromBuffer(Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {
// TODO(sonots): Use device.backend().FromBuffer()
#ifdef XCHAINER_ENABLE_CUDA
if (device.backend().GetName() == "native") {
if (IsPointerCudaMemory(src_ptr.get())) {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));
return dst_ptr;
} else {
return src_ptr;
}
} else if (device.backend().GetName() == "cuda") {
if (IsPointerCudaMemory(src_ptr.get())) {
return src_ptr;
} else {
std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);
cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));
return dst_ptr;
}
} else {
throw DeviceError("invalid device");
}
#else
(void)bytesize; // unused
if (device.backend().GetName() == "native") {
return src_ptr;
} else {
throw DeviceError("invalid device");
}
#endif // XCHAINER_ENABLE_CUDA
}
} // namespace internal
} // namespace xchainer
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessibleeventbuffer.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:25:04 $
*
* 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
*
************************************************************************/
#if !defined INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
#define INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include <vector>
namespace com { namespace sun { namespace star { namespace uno {
class XInterface;
} } } }
namespace com { namespace sun { namespace star {
namespace accessibility { struct AccessibleEventObject; }
} } }
namespace comphelper {
/**
A buffer for AccessibleEventObjects about to be sent to
XAccessibleEventListeners.
This buffer records pairs of AccessibleEventObjects and sequences of
XAccessibleEventListeners. At a time when it is safe to do so (e.g., when
no critical mutexes are held), all events can be notified at once.
This class is not thread-safe in itself, but it is thread-compatible (i.e.,
all multi-threaded uses of instances of this class have to ensure proper
mutual exclusion).
*/
class AccessibleEventBuffer
{
public:
/**
Create an initially empty buffer.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer();
/**
Create a buffer with a copy of another buffer.
The events from the other buffer are copied, not shared.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer(AccessibleEventBuffer const & rOther);
/**
Destroy the buffer.
If the buffer contains any events that have not yet been sent, those
events are lost.
Does not throw any exceptions.
*/
~AccessibleEventBuffer();
/**
Copy another buffer into this buffer.
If this buffer contained any events that had not yet been sent, those
events are lost. The events from the other buffer are copied, not
shared.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer operator =(AccessibleEventBuffer const & rOther);
/**
Add an event to the buffer.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
void addEvent(
::com::sun::star::accessibility::AccessibleEventObject const &
rEvent,
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > > const & rListeners);
/**
Sends all the events accumulated in the buffer.
If sending any of the events to a specific XAccessibleListener fails with
a RuntimeException, that exception is ignored and the method carries on
with the rest of the notifications.
After sending all events, the buffer is cleared.
*/
void sendEvents() const;
private:
struct Entry;
typedef ::std::vector< Entry > Entries;
Entries m_aEntries;
};
}
#endif // INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.246); FILE MERGED 2008/03/31 12:19:26 rt 1.3.246.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: accessibleeventbuffer.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#if !defined INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
#define INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include <vector>
namespace com { namespace sun { namespace star { namespace uno {
class XInterface;
} } } }
namespace com { namespace sun { namespace star {
namespace accessibility { struct AccessibleEventObject; }
} } }
namespace comphelper {
/**
A buffer for AccessibleEventObjects about to be sent to
XAccessibleEventListeners.
This buffer records pairs of AccessibleEventObjects and sequences of
XAccessibleEventListeners. At a time when it is safe to do so (e.g., when
no critical mutexes are held), all events can be notified at once.
This class is not thread-safe in itself, but it is thread-compatible (i.e.,
all multi-threaded uses of instances of this class have to ensure proper
mutual exclusion).
*/
class AccessibleEventBuffer
{
public:
/**
Create an initially empty buffer.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer();
/**
Create a buffer with a copy of another buffer.
The events from the other buffer are copied, not shared.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer(AccessibleEventBuffer const & rOther);
/**
Destroy the buffer.
If the buffer contains any events that have not yet been sent, those
events are lost.
Does not throw any exceptions.
*/
~AccessibleEventBuffer();
/**
Copy another buffer into this buffer.
If this buffer contained any events that had not yet been sent, those
events are lost. The events from the other buffer are copied, not
shared.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
AccessibleEventBuffer operator =(AccessibleEventBuffer const & rOther);
/**
Add an event to the buffer.
Internally uses ::std::vector and thus may throw exceptions thrown by
operations on ::std::vector, especially ::std::bad_alloc.
*/
void addEvent(
::com::sun::star::accessibility::AccessibleEventObject const &
rEvent,
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<
::com::sun::star::uno::XInterface > > const & rListeners);
/**
Sends all the events accumulated in the buffer.
If sending any of the events to a specific XAccessibleListener fails with
a RuntimeException, that exception is ignored and the method carries on
with the rest of the notifications.
After sending all events, the buffer is cleared.
*/
void sendEvents() const;
private:
struct Entry;
typedef ::std::vector< Entry > Entries;
Entries m_aEntries;
};
}
#endif // INCLUDED_COMPHELPER_ACCESSIBLEEVENTBUFFER_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: numrule.hxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: obo $ $Date: 2005-07-18 13:33:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _NUMRULE_HXX
#define _NUMRULE_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SV_GEN_HXX //autogen wg. Size
#include <tools/gen.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX //autogen
#include <svx/svxenum.hxx>
#endif
#ifndef _SVX_NUMITEM_HXX
#include <svx/numitem.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _CALBCK_HXX
#include <calbck.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx> // Fuer die inline-ASSERTs
#endif
#ifndef _SWERROR_H
#include <error.h> // Fuer die inline-ASSERTs
#endif
#ifndef _SW_BIT_ARRAY_HXX
#include <SwBitArray.hxx> // #i27615#
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
#include <hash_map>
#include <stringhash.hxx>
class Font;
class SvxBrushItem;
class SvxNumRule;
class SwCharFmt;
class SwDoc;
class SwFmtVertOrient;
class SwNodeNum;
class SwTxtNode;
extern char __FAR_DATA sOutlineStr[]; // SWG-Filter
BYTE SW_DLLPUBLIC GetRealLevel( const BYTE nLvl );
BOOL SW_DLLPUBLIC IsNum( BYTE nLvl );
BOOL SW_DLLPUBLIC IsShowNum( BYTE nLvl );
void SW_DLLPUBLIC SetNoNum( BYTE * nLvl, BOOL nVal = TRUE );
void SW_DLLPUBLIC SetLevel( BYTE * nLvl, BYTE nNewLvl);
const sal_Unicode cBulletChar = 0x2022; // Charakter fuer Aufzaehlungen
class SW_DLLPUBLIC SwNumFmt : public SvxNumberFormat, public SwClient
{
SwFmtVertOrient* pVertOrient;
SW_DLLPRIVATE void UpdateNumNodes( SwDoc* pDoc );
SW_DLLPRIVATE virtual void NotifyGraphicArrived();
public:
SwNumFmt();
SwNumFmt( const SwNumFmt& );
SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc);
virtual ~SwNumFmt();
SwNumFmt& operator=( const SwNumFmt& );
BOOL operator==( const SwNumFmt& ) const;
BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); }
const Graphic* GetGraphic() const;
SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; }
void SetCharFmt( SwCharFmt* );
virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );
virtual void SetCharFmtName(const String& rSet);
virtual const String& GetCharFmtName()const;
virtual void SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0);
virtual void SetVertOrient(SvxFrameVertOrient eSet);
virtual SvxFrameVertOrient GetVertOrient() const;
const SwFmtVertOrient* GetGraphicOrientation() const;
BOOL IsEnumeration() const; // #i22362#
BOOL IsItemize() const; // #i29560#
};
enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 };
class SW_DLLPUBLIC SwNumRule
{
friend void _FinitCore();
#ifndef PRODUCT
long int nSerial;
static long int nInstances;
#endif
static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ];
static USHORT aDefNumIndents[ MAXLEVEL ];
static USHORT nRefCount;
static Font* pDefBulletFont;
static char* pDefOutlineName;
SwNumFmt* aFmts[ MAXLEVEL ];
/**
cache for associated text nodes
*/
SwTxtNodeTable * pList;
/**
marked levels
*/
SwBitArray aMarkedLevels;
// #i36749#
/**
hash_map containing "name->rule" relation
*/
std::hash_map<String, SwNumRule *, StringHash> * pNumRuleMap;
String sName;
SwNumRuleType eRuleType;
USHORT nPoolFmtId; // Id-fuer "automatich" erzeugte NumRules
USHORT nPoolHelpId; // HelpId fuer diese Pool-Vorlage
BYTE nPoolHlpFileId; // FilePos ans Doc auf die Vorlagen-Hilfen
BOOL bAutoRuleFlag : 1;
BOOL bInvalidRuleFlag : 1;
BOOL bContinusNum : 1; // Fortlaufende Numerierung - ohne Ebenen
BOOL bAbsSpaces : 1; // die Ebenen repraesentieren absol. Einzuege
SW_DLLPRIVATE static void _MakeDefBulletFont();
// forbidden and not implemented.
SwNumRule();
public:
// single argument constructors shall be explicit.
explicit SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE,
BOOL bAutoFlg = TRUE );
SwNumRule( const SwNumRule& );
~SwNumRule();
SwNumRule& operator=( const SwNumRule& );
BOOL operator==( const SwNumRule& ) const;
BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); }
const SwNumFmt* GetNumFmt( USHORT i ) const;
const SwNumFmt& Get( USHORT i ) const;
void Set( USHORT i, const SwNumFmt* );
void Set( USHORT i, const SwNumFmt& );
String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE,
BOOL bOnlyArabic = FALSE ) const;
/**
Returns list of associated text nodes.
@return list of associated text nodes, or NULL if none present
*/
const SwTxtNodeTable * GetList() const { return pList; }
/**
Set list of associated text nodes.
@param _pList the list of associated text nodes
*/
void SetList(SwTxtNodeTable * _pList);
// #i36749#
/**
Register this rule in a "name->numrule" map.
@param pNumRuleMap map to register in
*/
void SetNumRuleMap(std::hash_map<String, SwNumRule *, StringHash> *
pNumRuleMap);
static const Font& GetDefBulletFont();
static char* GetOutlineRuleName() { return pDefOutlineName; }
static USHORT GetNumIndent( BYTE nLvl );
static USHORT GetBullIndent( BYTE nLvl );
SwNumRuleType GetRuleType() const { return eRuleType; }
void SetRuleType( SwNumRuleType eNew ) { eRuleType = eNew;
bInvalidRuleFlag = TRUE; }
// eine Art Copy-Constructor, damit die Num-Formate auch an den
// richtigen CharFormaten eines Dokumentes haengen !!
// (Kopiert die NumFormate und returnt sich selbst)
SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& );
// testet ob die CharFormate aus dem angegeben Doc sind und kopiert
// die gegebenfalls
void CheckCharFmts( SwDoc* pDoc );
#ifndef NUM_RELSPACE
// test ob der Einzug von dieser Numerierung kommt.
BOOL IsRuleLSpace( SwTxtNode& rNd ) const;
#endif
const String& GetName() const { return sName; }
void SetName( const String& rNm ); // #i36749#
BOOL IsAutoRule() const { return bAutoRuleFlag; }
void SetAutoRule( BOOL bFlag ) { bAutoRuleFlag = bFlag; }
BOOL IsInvalidRule() const { return bInvalidRuleFlag; }
void SetInvalidRule( BOOL bFlag );
BOOL IsContinusNum() const { return bContinusNum; }
void SetContinusNum( BOOL bFlag ) { bContinusNum = bFlag; }
BOOL IsAbsSpaces() const { return bAbsSpaces; }
void SetAbsSpaces( BOOL bFlag ) { bAbsSpaces = bFlag; }
// #115901#
BOOL IsOutlineRule() const { return eRuleType == OUTLINE_RULE; }
// erfragen und setzen der Poolvorlagen-Id's
USHORT GetPoolFmtId() const { return nPoolFmtId; }
void SetPoolFmtId( USHORT nId ) { nPoolFmtId = nId; }
// erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen
USHORT GetPoolHelpId() const { return nPoolHelpId; }
void SetPoolHelpId( USHORT nId ) { nPoolHelpId = nId; }
BYTE GetPoolHlpFileId() const { return nPoolHlpFileId; }
void SetPoolHlpFileId( BYTE nId ) { nPoolHlpFileId = nId; }
/**
#109308# Sets adjustment in all formats of the numbering rule.
@param eNum adjustment to be set
*/
void SetNumAdjust(SvxAdjust eNum);
void SetSvxRule(const SvxNumRule&, SwDoc* pDoc);
SvxNumRule MakeSvxNumRule() const;
// -> #i27615#
/**
Returns if a level is marked.
@param nLvl level to check
@retval TRUE level is marked
@retval FALSE level is not marked
*/
BOOL IsLevelMarked(BYTE nLvl) const { return aMarkedLevels.Get(nLvl); }
/**
Mark/unmark a level.
@param nLvl level to mark/unmark
@param bVal - TRUE mark
- FALSE unmark
@return bit array in which the altered levels are marked.
*/
SwBitArray SetLevelMarked(BYTE nLvl, BOOL bVal);
/**
Unmarks all levels.
*/
void ResetMarkedLevels() { aMarkedLevels.Reset(); }
// <- #i27615#
// #i23726#, #i23725#
void Indent(short aAmount, int nLevel = -1,
int nReferenceLevel = -1, BOOL bRelative = TRUE,
BOOL bFirstLine = TRUE, BOOL bCheckGtZero = TRUE);
};
class SW_DLLPUBLIC SwNodeNum
{
#ifndef PRODUCT
static long nSerial;
long nMySerial;
#endif
USHORT nLevelVal[ MAXLEVEL ]; // Nummern aller Levels
USHORT nSetValue; // vorgegeben Nummer
BYTE nMyLevel; // akt. Level
BOOL bStartNum; // Numerierung neu starten
BOOL bContNum; // #111955#
// TRUE -> in continuous numbering
public:
SwNodeNum( BYTE nLevel = NO_NUMBERING, USHORT nSetVal = USHRT_MAX );
SwNodeNum& operator=( const SwNodeNum& rCpy );
BOOL operator==( const SwNodeNum& ) const;
BYTE GetLevel() const { return nMyLevel; }
void SetLevel( BYTE nVal ) { ::SetLevel(&nMyLevel, nVal); }
BOOL IsStart() const { return bStartNum; }
void SetStart( BOOL bFlag = TRUE ) { bStartNum = bFlag; }
// -> #111955#
BOOL IsContinuousNum() const { return bContNum; }
void SetContinuousNum( BOOL bFlag = TRUE ) { bContNum = bFlag; }
// <- #111955#
BOOL HasSetValue() const { return USHRT_MAX != nSetValue; }
USHORT GetSetValue() const { return nSetValue; }
void SetSetValue( USHORT nVal ) { nSetValue = nVal; }
const USHORT* GetLevelVal() const { return nLevelVal; }
USHORT* GetLevelVal() { return nLevelVal; }
BYTE GetRealLevel() const { return ::GetRealLevel(nMyLevel); }
BOOL IsNum() const { return ::IsNum(nMyLevel); }
BOOL IsShowNum() const { return ::IsShowNum(nMyLevel); }
void SetNoNum(BOOL nVal = TRUE)
{
nMyLevel = nVal ? nMyLevel | NO_NUMLEVEL : nMyLevel & ~NO_NUMLEVEL;
}
};
sal_Unicode GetBulletChar(BYTE nLevel);
#endif // _NUMRULE_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.24.80); FILE MERGED 2005/09/05 13:36:21 rt 1.24.80.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: numrule.hxx,v $
*
* $Revision: 1.25 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:03:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _NUMRULE_HXX
#define _NUMRULE_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SV_GEN_HXX //autogen wg. Size
#include <tools/gen.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX //autogen
#include <svx/svxenum.hxx>
#endif
#ifndef _SVX_NUMITEM_HXX
#include <svx/numitem.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _CALBCK_HXX
#include <calbck.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx> // Fuer die inline-ASSERTs
#endif
#ifndef _SWERROR_H
#include <error.h> // Fuer die inline-ASSERTs
#endif
#ifndef _SW_BIT_ARRAY_HXX
#include <SwBitArray.hxx> // #i27615#
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>
#endif
#include <hash_map>
#include <stringhash.hxx>
class Font;
class SvxBrushItem;
class SvxNumRule;
class SwCharFmt;
class SwDoc;
class SwFmtVertOrient;
class SwNodeNum;
class SwTxtNode;
extern char __FAR_DATA sOutlineStr[]; // SWG-Filter
BYTE SW_DLLPUBLIC GetRealLevel( const BYTE nLvl );
BOOL SW_DLLPUBLIC IsNum( BYTE nLvl );
BOOL SW_DLLPUBLIC IsShowNum( BYTE nLvl );
void SW_DLLPUBLIC SetNoNum( BYTE * nLvl, BOOL nVal = TRUE );
void SW_DLLPUBLIC SetLevel( BYTE * nLvl, BYTE nNewLvl);
const sal_Unicode cBulletChar = 0x2022; // Charakter fuer Aufzaehlungen
class SW_DLLPUBLIC SwNumFmt : public SvxNumberFormat, public SwClient
{
SwFmtVertOrient* pVertOrient;
SW_DLLPRIVATE void UpdateNumNodes( SwDoc* pDoc );
SW_DLLPRIVATE virtual void NotifyGraphicArrived();
public:
SwNumFmt();
SwNumFmt( const SwNumFmt& );
SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc);
virtual ~SwNumFmt();
SwNumFmt& operator=( const SwNumFmt& );
BOOL operator==( const SwNumFmt& ) const;
BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); }
const Graphic* GetGraphic() const;
SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; }
void SetCharFmt( SwCharFmt* );
virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );
virtual void SetCharFmtName(const String& rSet);
virtual const String& GetCharFmtName()const;
virtual void SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0);
virtual void SetVertOrient(SvxFrameVertOrient eSet);
virtual SvxFrameVertOrient GetVertOrient() const;
const SwFmtVertOrient* GetGraphicOrientation() const;
BOOL IsEnumeration() const; // #i22362#
BOOL IsItemize() const; // #i29560#
};
enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 };
class SW_DLLPUBLIC SwNumRule
{
friend void _FinitCore();
#ifndef PRODUCT
long int nSerial;
static long int nInstances;
#endif
static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ];
static USHORT aDefNumIndents[ MAXLEVEL ];
static USHORT nRefCount;
static Font* pDefBulletFont;
static char* pDefOutlineName;
SwNumFmt* aFmts[ MAXLEVEL ];
/**
cache for associated text nodes
*/
SwTxtNodeTable * pList;
/**
marked levels
*/
SwBitArray aMarkedLevels;
// #i36749#
/**
hash_map containing "name->rule" relation
*/
std::hash_map<String, SwNumRule *, StringHash> * pNumRuleMap;
String sName;
SwNumRuleType eRuleType;
USHORT nPoolFmtId; // Id-fuer "automatich" erzeugte NumRules
USHORT nPoolHelpId; // HelpId fuer diese Pool-Vorlage
BYTE nPoolHlpFileId; // FilePos ans Doc auf die Vorlagen-Hilfen
BOOL bAutoRuleFlag : 1;
BOOL bInvalidRuleFlag : 1;
BOOL bContinusNum : 1; // Fortlaufende Numerierung - ohne Ebenen
BOOL bAbsSpaces : 1; // die Ebenen repraesentieren absol. Einzuege
SW_DLLPRIVATE static void _MakeDefBulletFont();
// forbidden and not implemented.
SwNumRule();
public:
// single argument constructors shall be explicit.
explicit SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE,
BOOL bAutoFlg = TRUE );
SwNumRule( const SwNumRule& );
~SwNumRule();
SwNumRule& operator=( const SwNumRule& );
BOOL operator==( const SwNumRule& ) const;
BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); }
const SwNumFmt* GetNumFmt( USHORT i ) const;
const SwNumFmt& Get( USHORT i ) const;
void Set( USHORT i, const SwNumFmt* );
void Set( USHORT i, const SwNumFmt& );
String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE,
BOOL bOnlyArabic = FALSE ) const;
/**
Returns list of associated text nodes.
@return list of associated text nodes, or NULL if none present
*/
const SwTxtNodeTable * GetList() const { return pList; }
/**
Set list of associated text nodes.
@param _pList the list of associated text nodes
*/
void SetList(SwTxtNodeTable * _pList);
// #i36749#
/**
Register this rule in a "name->numrule" map.
@param pNumRuleMap map to register in
*/
void SetNumRuleMap(std::hash_map<String, SwNumRule *, StringHash> *
pNumRuleMap);
static const Font& GetDefBulletFont();
static char* GetOutlineRuleName() { return pDefOutlineName; }
static USHORT GetNumIndent( BYTE nLvl );
static USHORT GetBullIndent( BYTE nLvl );
SwNumRuleType GetRuleType() const { return eRuleType; }
void SetRuleType( SwNumRuleType eNew ) { eRuleType = eNew;
bInvalidRuleFlag = TRUE; }
// eine Art Copy-Constructor, damit die Num-Formate auch an den
// richtigen CharFormaten eines Dokumentes haengen !!
// (Kopiert die NumFormate und returnt sich selbst)
SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& );
// testet ob die CharFormate aus dem angegeben Doc sind und kopiert
// die gegebenfalls
void CheckCharFmts( SwDoc* pDoc );
#ifndef NUM_RELSPACE
// test ob der Einzug von dieser Numerierung kommt.
BOOL IsRuleLSpace( SwTxtNode& rNd ) const;
#endif
const String& GetName() const { return sName; }
void SetName( const String& rNm ); // #i36749#
BOOL IsAutoRule() const { return bAutoRuleFlag; }
void SetAutoRule( BOOL bFlag ) { bAutoRuleFlag = bFlag; }
BOOL IsInvalidRule() const { return bInvalidRuleFlag; }
void SetInvalidRule( BOOL bFlag );
BOOL IsContinusNum() const { return bContinusNum; }
void SetContinusNum( BOOL bFlag ) { bContinusNum = bFlag; }
BOOL IsAbsSpaces() const { return bAbsSpaces; }
void SetAbsSpaces( BOOL bFlag ) { bAbsSpaces = bFlag; }
// #115901#
BOOL IsOutlineRule() const { return eRuleType == OUTLINE_RULE; }
// erfragen und setzen der Poolvorlagen-Id's
USHORT GetPoolFmtId() const { return nPoolFmtId; }
void SetPoolFmtId( USHORT nId ) { nPoolFmtId = nId; }
// erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen
USHORT GetPoolHelpId() const { return nPoolHelpId; }
void SetPoolHelpId( USHORT nId ) { nPoolHelpId = nId; }
BYTE GetPoolHlpFileId() const { return nPoolHlpFileId; }
void SetPoolHlpFileId( BYTE nId ) { nPoolHlpFileId = nId; }
/**
#109308# Sets adjustment in all formats of the numbering rule.
@param eNum adjustment to be set
*/
void SetNumAdjust(SvxAdjust eNum);
void SetSvxRule(const SvxNumRule&, SwDoc* pDoc);
SvxNumRule MakeSvxNumRule() const;
// -> #i27615#
/**
Returns if a level is marked.
@param nLvl level to check
@retval TRUE level is marked
@retval FALSE level is not marked
*/
BOOL IsLevelMarked(BYTE nLvl) const { return aMarkedLevels.Get(nLvl); }
/**
Mark/unmark a level.
@param nLvl level to mark/unmark
@param bVal - TRUE mark
- FALSE unmark
@return bit array in which the altered levels are marked.
*/
SwBitArray SetLevelMarked(BYTE nLvl, BOOL bVal);
/**
Unmarks all levels.
*/
void ResetMarkedLevels() { aMarkedLevels.Reset(); }
// <- #i27615#
// #i23726#, #i23725#
void Indent(short aAmount, int nLevel = -1,
int nReferenceLevel = -1, BOOL bRelative = TRUE,
BOOL bFirstLine = TRUE, BOOL bCheckGtZero = TRUE);
};
class SW_DLLPUBLIC SwNodeNum
{
#ifndef PRODUCT
static long nSerial;
long nMySerial;
#endif
USHORT nLevelVal[ MAXLEVEL ]; // Nummern aller Levels
USHORT nSetValue; // vorgegeben Nummer
BYTE nMyLevel; // akt. Level
BOOL bStartNum; // Numerierung neu starten
BOOL bContNum; // #111955#
// TRUE -> in continuous numbering
public:
SwNodeNum( BYTE nLevel = NO_NUMBERING, USHORT nSetVal = USHRT_MAX );
SwNodeNum& operator=( const SwNodeNum& rCpy );
BOOL operator==( const SwNodeNum& ) const;
BYTE GetLevel() const { return nMyLevel; }
void SetLevel( BYTE nVal ) { ::SetLevel(&nMyLevel, nVal); }
BOOL IsStart() const { return bStartNum; }
void SetStart( BOOL bFlag = TRUE ) { bStartNum = bFlag; }
// -> #111955#
BOOL IsContinuousNum() const { return bContNum; }
void SetContinuousNum( BOOL bFlag = TRUE ) { bContNum = bFlag; }
// <- #111955#
BOOL HasSetValue() const { return USHRT_MAX != nSetValue; }
USHORT GetSetValue() const { return nSetValue; }
void SetSetValue( USHORT nVal ) { nSetValue = nVal; }
const USHORT* GetLevelVal() const { return nLevelVal; }
USHORT* GetLevelVal() { return nLevelVal; }
BYTE GetRealLevel() const { return ::GetRealLevel(nMyLevel); }
BOOL IsNum() const { return ::IsNum(nMyLevel); }
BOOL IsShowNum() const { return ::IsShowNum(nMyLevel); }
void SetNoNum(BOOL nVal = TRUE)
{
nMyLevel = nVal ? nMyLevel | NO_NUMLEVEL : nMyLevel & ~NO_NUMLEVEL;
}
};
sal_Unicode GetBulletChar(BYTE nLevel);
#endif // _NUMRULE_HXX
<|endoftext|> |
<commit_before>#include <set>
#include <sstream>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace placeholders = asio::placeholders;
namespace sys = boost::system;
namespace algorithm = boost::algorithm;
template< typename TConnection >
class Task
{
public:
Task( TConnection * connection )
: m_connection( connection )
{
}
static typename TConnection::Action start()
{
return TConnection::Action::Read;
}
typename TConnection::Action parse(
char const * const buffer,
std::size_t const bytesTransferred
)
{
std::istringstream iss( std::string( buffer, bytesTransferred ) );
char command, space, cr, lf;
iss >> command;
if( command == 'g' )
{
std::string id;
iss >> id;
m_connection->setId( id );
char const * const line = "Hello.";
m_connection->response( line, strlen( line ) );
m_connection->read();
}
else if( command == 'b' )
{
std::string message;
iss >> message;
m_connection->broadcast( message.c_str(), message.size() );
m_connection->read();
}
else if( command == 'u' )
{
std::string id;
std::string message;
iss >> id >> message;
m_connection->unicast( id, message.c_str(), message.size() );
m_connection->read();
}
else if( command == 'd' )
{
m_connection->disconnect();
}
else if( command == 'r' )
{
std::string message;
iss >> message;
m_connection->response( message.c_str(), message.size() );
m_connection->read();
}
else
{
char const * const message = "unknown";
m_connection->response( message, strlen( message ) );
m_connection->read();
}
return TConnection::Action::Process;
}
void parseError()
{
std::cerr
<< "Parse error"
<< std::endl;
}
void process()
{
}
private:
TConnection * m_connection;
};
class ConnectionManager;
class Connection
: public boost::enable_shared_from_this< Connection >
{
public:
typedef boost::shared_ptr< Connection > ConnectionPtr;
public:
enum class Action
{
Read,
ReadError,
Process
};
Connection(
asio::io_service & ioService,
ConnectionManager & connectionManager
);
ip::tcp::socket & socket();
void disconnect();
void start(
Action const action = Task< Connection >::start()
);
public: // api
void setId(
std::string const & id
);
std::string const & getId() const ;
void read();
void parseError();
void process();
void response(
char const * const message,
std::size_t const size
);
void unicast(
std::string const & receiverId,
char const * const message,
std::size_t const size
);
void broadcast(
char const * const message,
std::size_t const size
);
void doNothing(
sys::error_code const & errorCode
)
{
if( errorCode )
{
std::cerr << "Do Nothing Error: " << errorCode.message() << std::endl;
disconnect();
}
}
private:
void parse(
sys::error_code const & errorCode,
std::size_t const bytesTransferred
);
void startAgain(
sys::error_code const & errorCode
);
void stop(
sys::error_code const & errorCode
);
private:
ip::tcp::socket m_socket;
asio::io_service::strand m_strand;
ConnectionManager & m_connectionManager;
Task< Connection > m_task;
std::string m_id;
enum { m_maxSize = 1024 };
char m_buffer[ m_maxSize ];
};
Connection::Connection(
asio::io_service & ioService,
ConnectionManager & connectionManager
)
: m_socket( ioService )
, m_strand( ioService )
, m_connectionManager( connectionManager )
, m_task( this )
{
}
ip::tcp::socket & Connection::socket()
{
return m_socket;
}
void Connection::setId(
std::string const & id
)
{
m_id = id;
}
std::string const & Connection::getId() const
{
return m_id;
}
void Connection::start(
Connection::Action const action
)
{
switch( action )
{
case Action::Process:
{
process();
break;
}
case Action::ReadError:
{
parseError();
break;
}
case Action::Read:
{
auto const parse = boost::bind(
& Connection::parse,
shared_from_this(),
placeholders::error,
placeholders::bytes_transferred()
);
m_socket.async_read_some(
asio::buffer( m_buffer, m_maxSize ),
m_strand.wrap( parse )
);
break;
}
}
}
void Connection::read()
{
start( Action::Read );
}
void Connection::parseError()
{
m_task.parseError();
}
void Connection::process()
{
m_task.process();
}
void Connection::parse(
sys::error_code const & errorCode,
std::size_t const bytesTransferred
)
{
if( errorCode )
{
std::cerr << "Parse Error: " << errorCode.message() << std::endl;
disconnect();
}
else
{
start( m_task.parse( m_buffer, bytesTransferred ) );
}
}
void Connection::startAgain(
sys::error_code const & errorCode
)
{
if( errorCode )
{
std::cerr << "Start Again Error: " << errorCode.message() << std::endl;
disconnect();
}
else
{
start();
}
}
typedef Connection::ConnectionPtr ConnectionPtr;
class ConnectionManager
: public boost::noncopyable
{
typedef std::set< ConnectionPtr > ConnectionsPtr;
public:
template< typename Function, class... Args >
void forEach( Function&& func, Args && ...args )
{
boost::lock_guard< boost::mutex > lock( m_mutex );
for( auto & connection : m_connections )
{
func( connection, std::forward< Args >( args )... );
}
}
template< typename Predicate, typename Function, class... Args >
void forEachIf( Predicate && predicate, Function && func, Args && ...args )
{
boost::lock_guard< boost::mutex > lock( m_mutex );
for( auto & connection : m_connections )
{
if( predicate( connection ) )
{
func( connection, std::forward< Args >( args )... );
}
}
}
void add(
ConnectionPtr & connection
)
{
boost::lock_guard< boost::mutex > lock( m_mutex );
m_connections.insert( connection );
}
void remove(
ConnectionPtr const & connection
)
{
boost::lock_guard< boost::mutex > lock( m_mutex );
auto const pos = m_connections.find( connection );
if( pos != m_connections.end() ){
m_connections.erase( pos );
}
}
private:
boost::mutex m_mutex;
ConnectionsPtr m_connections;
};
void Connection::disconnect()
{
m_connectionManager.remove( shared_from_this() );
}
void Connection::response(
char const * const message,
std::size_t const size
)
{
auto const continuation = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
m_socket,
asio::buffer( message, size ),
continuation
);
}
void Connection::unicast(
std::string const & receiverId,
char const * const message,
std::size_t const size
)
{
auto const matchReceiver = [ this, & receiverId ]( ConnectionPtr const & connectionPtr )
{
return connectionPtr->getId() == receiverId;
};
auto sendMessage = [ this, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const stop = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
stop
);
};
m_connectionManager.forEachIf( matchReceiver, sendMessage );
}
void Connection::broadcast(
char const * const message,
std::size_t const size
)
{
auto const skipSender = [ this ]( ConnectionPtr const & connectionPtr )
{
return connectionPtr->socket().native_handle() != this->socket().native_handle();
};
auto sendMessage = [ this, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const continuation = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
continuation
);
};
m_connectionManager.forEachIf( skipSender, sendMessage );
}
void Connection::stop(
sys::error_code const & errorCode
)
{
m_connectionManager.remove( shared_from_this() );
}
class Server
{
public:
Server(
std::string const & port
)
: m_acceptor( m_ioService )
, m_signals( m_ioService )
{
m_signals.add( SIGINT );
m_signals.add( SIGTERM );
m_signals.add( SIGQUIT );
m_signals.async_wait(
boost::bind( & Server::disconnect, this )
);
ip::tcp::resolver resolver( m_ioService );
ip::tcp::resolver::query query( "127.0.0.1", port );
ip::tcp::endpoint endpoint = * resolver.resolve( query );
m_acceptor.open( endpoint.protocol() );
m_acceptor.set_option( ip::tcp::acceptor::reuse_address( true ) );
m_acceptor.bind( endpoint );
m_acceptor.listen();
startAccept();
}
void run()
{
boost::thread_group threadGroup;
auto const threadBody = boost::bind(
& asio::io_service::run,
& m_ioService
);
for( unsigned i = 0 ; i < 4 ; ++ i )
{
threadGroup.create_thread( threadBody );
}
threadGroup.join_all();
}
private:
void startAccept()
{
m_newConnection.reset( new Connection( m_ioService, m_connectionManager ) );
auto const onAccepted = boost::bind(
& Server::onAccepted,
this,
placeholders::error
);
m_acceptor.async_accept(
m_newConnection->socket(),
onAccepted
);
}
void onAccepted(
sys::error_code const & errorCode
)
{
if( ! errorCode )
{
m_connectionManager.add( m_newConnection );
m_newConnection->start();
}
startAccept();
}
void disconnect()
{
m_connectionManager.forEach(
boost::bind( & Connection::disconnect, _1 )
);
m_ioService.stop();
}
private:
asio::io_service m_ioService;
asio::ip::tcp::acceptor m_acceptor;
asio::signal_set m_signals;
ConnectionPtr m_newConnection;
ConnectionManager m_connectionManager;
};
int main( int argc, char* argv[] )
{
Server( argv[1] ).run();
}
<commit_msg>hello + name<commit_after>#include <set>
#include <sstream>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace placeholders = asio::placeholders;
namespace sys = boost::system;
namespace algorithm = boost::algorithm;
template< typename TConnection >
class Task
{
public:
Task( TConnection * connection )
: m_connection( connection )
{
}
static typename TConnection::Action start()
{
return TConnection::Action::Read;
}
typename TConnection::Action parse(
char const * const buffer,
std::size_t const bytesTransferred
)
{
std::istringstream iss( std::string( buffer, bytesTransferred ) );
char command, space, cr, lf;
iss >> command;
if( command == 'g' )
{
std::string id;
iss >> id;
m_connection->setId( id );
const std::string message = "Hello " + id;
m_connection->response( message.c_str(), message.size() );
m_connection->read();
}
else if( command == 'b' )
{
std::string message;
iss >> message;
m_connection->broadcast( message.c_str(), message.size() );
m_connection->read();
}
else if( command == 'u' )
{
std::string id;
std::string message;
iss >> id >> message;
m_connection->unicast( id, message.c_str(), message.size() );
m_connection->read();
}
else if( command == 'd' )
{
m_connection->disconnect();
}
else if( command == 'r' )
{
std::string message;
iss >> message;
m_connection->response( message.c_str(), message.size() );
m_connection->read();
}
else
{
char const * const message = "unknown";
m_connection->response( message, strlen( message ) );
m_connection->read();
}
return TConnection::Action::Process;
}
void parseError()
{
std::cerr
<< "Parse error"
<< std::endl;
}
void process()
{
}
private:
TConnection * m_connection;
};
class ConnectionManager;
class Connection
: public boost::enable_shared_from_this< Connection >
{
public:
typedef boost::shared_ptr< Connection > ConnectionPtr;
public:
enum class Action
{
Read,
ReadError,
Process
};
Connection(
asio::io_service & ioService,
ConnectionManager & connectionManager
);
ip::tcp::socket & socket();
void disconnect();
void stop();
void start(
Action const action = Task< Connection >::start()
);
public: // api
void setId(
std::string const & id
);
std::string const & getId() const ;
void read();
void parseError();
void process();
void response(
char const * const message,
std::size_t const size
);
void unicast(
std::string const & receiverId,
char const * const message,
std::size_t const size
);
void broadcast(
char const * const message,
std::size_t const size
);
private:
void parse(
sys::error_code const & errorCode,
std::size_t const bytesTransferred
);
void startAgain(
sys::error_code const & errorCode
);
void doNothing(
sys::error_code const & errorCode
)
{
if( errorCode )
{
std::cerr << "Do Nothing Error: " << errorCode.message() << std::endl;
disconnect();
}
}
private:
ip::tcp::socket m_socket;
asio::io_service::strand m_strand;
ConnectionManager & m_connectionManager;
Task< Connection > m_task;
std::string m_id;
enum { m_maxSize = 1024 };
char m_buffer[ m_maxSize ];
};
Connection::Connection(
asio::io_service & ioService,
ConnectionManager & connectionManager
)
: m_socket( ioService )
, m_strand( ioService )
, m_connectionManager( connectionManager )
, m_task( this )
{
}
ip::tcp::socket & Connection::socket()
{
return m_socket;
}
void Connection::setId(
std::string const & id
)
{
m_id = id;
}
std::string const & Connection::getId() const
{
return m_id;
}
void Connection::start(
Connection::Action const action
)
{
switch( action )
{
case Action::Process:
{
process();
break;
}
case Action::ReadError:
{
parseError();
break;
}
case Action::Read:
{
auto const parse = boost::bind(
& Connection::parse,
shared_from_this(),
placeholders::error,
placeholders::bytes_transferred()
);
m_socket.async_read_some(
asio::buffer( m_buffer, m_maxSize ),
m_strand.wrap( parse )
);
break;
}
}
}
void Connection::read()
{
start( Action::Read );
}
void Connection::parseError()
{
m_task.parseError();
}
void Connection::process()
{
m_task.process();
}
void Connection::parse(
sys::error_code const & errorCode,
std::size_t const bytesTransferred
)
{
if( errorCode )
{
std::cerr << "Parse Error: " << errorCode.message() << std::endl;
disconnect();
}
else
{
start( m_task.parse( m_buffer, bytesTransferred ) );
}
}
void Connection::startAgain(
sys::error_code const & errorCode
)
{
if( errorCode )
{
std::cerr << "Start Again Error: " << errorCode.message() << std::endl;
disconnect();
}
else
{
start();
}
}
typedef Connection::ConnectionPtr ConnectionPtr;
class ConnectionManager
: public boost::noncopyable
{
typedef std::set< ConnectionPtr > ConnectionsPtr;
public:
template< typename Function, class... Args >
void forEach( Function&& func, Args && ...args )
{
boost::lock_guard< boost::mutex > lock( m_mutex );
for( auto & connection : m_connections )
{
func( connection, std::forward< Args >( args )... );
}
}
template< typename Predicate, typename Function, class... Args >
void forEachIf( Predicate && predicate, Function && func, Args && ...args )
{
boost::lock_guard< boost::mutex > lock( m_mutex );
for( auto & connection : m_connections )
{
if( predicate( connection ) )
{
func( connection, std::forward< Args >( args )... );
}
}
}
void add(
ConnectionPtr & connection
)
{
boost::lock_guard< boost::mutex > lock( m_mutex );
m_connections.insert( connection );
}
void remove(
ConnectionPtr const & connection
)
{
boost::lock_guard< boost::mutex > lock( m_mutex );
auto const pos = m_connections.find( connection );
if( pos != m_connections.end() ){
m_connections.erase( pos );
}
}
private:
boost::mutex m_mutex;
ConnectionsPtr m_connections;
};
void Connection::disconnect()
{
m_connectionManager.remove( shared_from_this() );
}
void Connection::response(
char const * const message,
std::size_t const size
)
{
auto const continuation = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
m_socket,
asio::buffer( message, size ),
continuation
);
}
void Connection::unicast(
std::string const & receiverId,
char const * const message,
std::size_t const size
)
{
auto const matchReceiver = [ this, & receiverId ]( ConnectionPtr const & connectionPtr )
{
return connectionPtr->getId() == receiverId;
};
auto sendMessage = [ this, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const continuation = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
continuation
);
};
m_connectionManager.forEachIf( matchReceiver, sendMessage );
}
void Connection::broadcast(
char const * const message,
std::size_t const size
)
{
auto const skipSender = [ this ]( ConnectionPtr const & connectionPtr )
{
return connectionPtr->socket().native_handle() != this->socket().native_handle();
};
auto sendMessage = [ this, & size, & message ]( ConnectionPtr const & connectionPtr )
{
auto const continuation = boost::bind(
& Connection::doNothing,
shared_from_this(),
placeholders::error
);
asio::async_write(
connectionPtr->socket(),
asio::buffer( message, size ),
continuation
);
};
m_connectionManager.forEachIf( skipSender, sendMessage );
}
void Connection::stop()
{
char const * const message = "Goodbye.";
response( message, strlen( message ) );
}
class Server
{
public:
Server(
std::string const & port
)
: m_strand( m_ioService )
, m_acceptor( m_ioService )
, m_signals( m_ioService )
{
m_signals.add( SIGINT );
m_signals.add( SIGTERM );
m_signals.add( SIGQUIT );
m_signals.async_wait(
boost::bind( & Server::stop, this )
);
ip::tcp::resolver resolver( m_ioService );
ip::tcp::resolver::query query( "127.0.0.1", port );
ip::tcp::endpoint endpoint = * resolver.resolve( query );
m_acceptor.open( endpoint.protocol() );
m_acceptor.set_option( ip::tcp::acceptor::reuse_address( true ) );
m_acceptor.bind( endpoint );
m_acceptor.listen();
startAccept();
}
void run()
{
boost::thread_group threadGroup;
auto const threadBody = boost::bind(
& asio::io_service::run,
& m_ioService
);
for( unsigned i = 0 ; i < 4 ; ++ i )
{
threadGroup.create_thread( threadBody );
}
threadGroup.join_all();
}
private:
void startAccept()
{
m_newConnection.reset( new Connection( m_ioService, m_connectionManager ) );
auto const onAccepted = boost::bind(
& Server::onAccepted,
this,
placeholders::error
);
m_acceptor.async_accept(
m_newConnection->socket(),
onAccepted
);
}
void onAccepted(
sys::error_code const & errorCode
)
{
if( ! errorCode )
{
m_connectionManager.add( m_newConnection );
m_newConnection->start();
}
startAccept();
}
void stop()
{
m_ioService.stop();
}
private:
asio::io_service m_ioService;
asio::io_service::strand m_strand;
asio::ip::tcp::acceptor m_acceptor;
asio::signal_set m_signals;
ConnectionPtr m_newConnection;
ConnectionManager m_connectionManager;
};
int main( int argc, char* argv[] )
{
Server( argv[1] ).run();
}
<|endoftext|> |
<commit_before>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 150 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
cout << "In loadWindow's secret base, index is: " << i-base << endl;
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
}
/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
}
/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
fd_set stReadFDS;
struct timeval stTimeOut;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(0, &stReadFDS);
base = 0;
int finale = -1;
while(base * BUFSIZE < length) {
FD_ZERO(&stReadFDS);
FD_SET(0, &stReadFDS);
loadWindow();
if(p.str()[0] == '\0') finale = p.getSequenceNum();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
for(int x = 0; x < WIN_SIZE; x++) {
cout << "begin loop no. " << x << endl;
int t = select(1, &stReadFDS, NULL, NULL, &stTimeOut);
if (t != 0) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
}
} else {
cout << "=== ACK TIMEOUT" << endl;
}
cout << "b: " << b << endl;
if(b[0] == '\0') continue;
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
if(finale > 0 && base == finale) break;
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<commit_msg>i know you won't wait for me<commit_after>#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n"
#define PORT 10038
#define PAKSIZE 512
#define ACK 0
#define NAK 1
#define BUFSIZE 505
#define FILENAME "Testfile"
#define TIMEOUT 150 //in ms
#define WIN_SIZE 16
using namespace std;
bool isvpack(unsigned char * p);
bool init(int argc, char** argv);
bool loadFile();
bool getFile();
bool sendFile();
bool isAck();
void handleAck();
void handleNak(int& x);
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);
Packet createPacket(int index);
void loadWindow();
bool sendPacket();
bool getGet();
struct sockaddr_in a;
struct sockaddr_in ca;
socklen_t calen;
int rlen;
int s;
bool ack;
string fstr;
char * file;
int probCorrupt;
int probLoss;
int probDelay;
int delayT;
Packet p;
Packet window[16];
int length;
bool dropPck;
bool delayPck;
int toms;
unsigned char b[BUFSIZE];
int base;
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
sendFile();
return 0;
}
bool init(int argc, char** argv){
if(argc != 6) {
cout << USAGE << endl;
return false;
}
char * probCorruptStr = argv[2];
probCorrupt = boost::lexical_cast<int>(probCorruptStr);
char * probLossStr = argv[3];
probLoss = boost::lexical_cast<int>(probLossStr);
char * probDelayStr = argv[4];
probDelay = boost::lexical_cast<int>(probDelayStr);
char* delayTStr = argv[5];
delayT = boost::lexical_cast<int>(delayTStr);
struct timeval timeout;
timeout.tv_usec = TIMEOUT * 1000;
toms = TIMEOUT;
/* Create our socket. */
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return 0;
}
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
/*
* Bind our socket to an IP (whatever the computer decides)
* and a specified port.
*
*/
if (!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY);
a.sin_port = htons(PORT);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {
cout << "Socket binding failed. (socket s, address a)" << endl;
return 0;
}
fstr = string(file);
cout << "File: " << endl << fstr << endl;
base = 0;
dropPck = false;
calen = sizeof(ca);
getGet();
return true;
}
bool getGet(){
unsigned char packet[PAKSIZE + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
return (rlen > 0) ? true : false;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[7];
memcpy(css, &p[1], 6);
css[6] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[2], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == 0) return false; //doesn't matter, only for the old version (netwark)
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * css = new char[6];
memcpy(css, &packet[1], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
cout << "Sent response: ";
if(isvpack(packet)) {
ack = ACK;
//seqNum = (seqNum) ? false : true;
file << dataPull;
} else {
ack = NAK;
}
cout << ((ack == ACK) ? "ACK" : "NAK") << endl;
Packet p (false, reinterpret_cast<const char *>(dataPull));
p.setCheckSum(boost::lexical_cast<int>(css));
p.setAckNack(ack);
if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
void loadWindow(){
for(int i = base; i < base + WIN_SIZE; i++) {
window[i-base] = createPacket(i);
if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) {
cout << "In loadWindow's secret base, index is: " << i-base << endl;
for(++i; i < base + WIN_SIZE; i++){
window[i-base].loadDataBuffer("\0");
}
}
/*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/
}
/*cout << "packet " << base + 1 << ": " << window[1].str() << endl;
cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/
}
bool sendFile() {
/*Currently causes the program to only send the first 16 packets of file out
requires additional code later to sendFile again with updated window*/
fd_set stReadFDS;
struct timeval stTimeOut;
FD_ZERO(&stReadFDS);
stTimeOut.tv_sec = 0;
stTimeOut.tv_usec = 1000 * TIMEOUT;
FD_SET(0, &stReadFDS);
base = 0;
int finale = -1;
while(base * BUFSIZE < length) {
loadWindow();
if(p.str()[0] == '\0') finale = p.getSequenceNum();
for(int x = 0; x < WIN_SIZE; x++) {
p = window[x];
if(!sendPacket()) continue;
}
for(int x = 0; x < WIN_SIZE; x++) {
FD_ZERO(&stReadFDS);
FD_SET(0, &stReadFDS);
cout << "begin loop no. " << x << endl;
int t = select(1, &stReadFDS, NULL, NULL, &stTimeOut);
if (t != 0) {
if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {
cout << "=== ACK TIMEOUT" << endl;
}
} else {
cout << "=== ACK TIMEOUT" << endl;
}
cout << "b: " << b << endl;
if(b[0] == '\0') continue;
if(isAck()) {
handleAck();
} else {
handleAck();
//handleNak(x);
}
if(finale > 0 && base == finale) break;
memset(b, 0, BUFSIZE);
}
}
if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Final package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
Packet createPacket(int index){
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(mstr.length() < BUFSIZE) {
cout << "Null terminated mstr." << endl;
mstr[length - (index * BUFSIZE)] = '\0';
}
cout << "index: " << index << endl;
return Packet (index, mstr.c_str());
}
bool sendPacket(){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl;
int pc = probCorrupt; int pl = probLoss; int pd = probDelay;
bool* pckStatus = gremlin(&p, pc, pl, pd);
dropPck = pckStatus[0];
delayPck = pckStatus[1];
if (dropPck == true) return false;
if (delayPck == true) p.setAckNack(1);
if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
}
bool isAck() {
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
int ack = boost::lexical_cast<int>(b);
if(base < ack) base = ack;
cout << "Window base: " << base << endl;
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){
bool* packStatus = new bool[2];
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
packStatus[0] = false;
packStatus[1] = false;
if(r <= (lossProb)){
packStatus[0] = true;
cout << "Dropped!" << endl;
}
else if(r <= (delayProb)){
packStatus[1] = true;
cout << "Delayed!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
//cout << "Message: " << pack->getDataBuffer() << endl;
return packStatus;
}<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9, packaged on Novemeber, 2005.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_light.cpp implementation of the GLC_Light class.
#include <QtDebug>
#include "glc_light.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light(const char *pName ,const GLfloat *pAmbiantColor)
:GLC_Object(pName)
, m_LumiereID(GL_LIGHT1) // Default Light ID
, m_ListeID(0) // By default display list ID= 0
, m_bListeIsValid(false) // By default display list is not valid
{
//! \todo modify class to support multi light
// Color Initialisation
if (pAmbiantColor != 0)
{
m_fColAmbiente[0]= pAmbiantColor[0];
m_fColAmbiente[1]= pAmbiantColor[1];
m_fColAmbiente[2]= pAmbiantColor[2];
m_fColAmbiente[3]= pAmbiantColor[3];
}
else
{ // By default light's color is dark grey
m_fColAmbiente[0]= 0.2f;
m_fColAmbiente[1]= 0.2f;
m_fColAmbiente[2]= 0.2f;
m_fColAmbiente[3]= 1.0f;
}
// Other are white
// Diffuse Color
m_fColDiffuse[0]= 1.0f;
m_fColDiffuse[1]= 1.0f;
m_fColDiffuse[2]= 1.0f;
m_fColDiffuse[3]= 1.0f;
// Specular Color
m_fColSpeculaire[0]= 1.0f;
m_fColSpeculaire[1]= 1.0f;
m_fColSpeculaire[2]= 1.0f;
m_fColSpeculaire[3]= 1.0f;
// Color position
m_fPos[0]= 0.0f;
m_fPos[1]= 0.0f;
m_fPos[2]= 0.0f;
m_fPos[3]= 1.0f;
}
GLC_Light::~GLC_Light(void)
{
DeleteListe();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set the lihgt position by a 4D vector
void GLC_Light::SetPos(const GLC_Vector4d &VectPos)
{
m_fPos[0]= static_cast<GLfloat>(VectPos.GetX());
m_fPos[1]= static_cast<GLfloat>(VectPos.GetY());
m_fPos[2]= static_cast<GLfloat>(VectPos.GetZ());
m_fPos[3]= static_cast<GLfloat>(VectPos.GetW());
m_bListeIsValid = false;
}
// Set the lihgt position by a 3 GLfloat
void GLC_Light::SetPos(GLfloat x, GLfloat y, GLfloat z)
{
m_fPos[0]= x;
m_fPos[1]= y;
m_fPos[2]= z;
m_bListeIsValid = false;
}
// Set light's ambiant color by an array of GLfloat
void GLC_Light::SetColAmbiante(const GLfloat* pfCol)
{
m_fColAmbiente[0]= pfCol[0];
m_fColAmbiente[1]= pfCol[1];
m_fColAmbiente[2]= pfCol[2];
m_fColAmbiente[3]= pfCol[3];
m_bListeIsValid = false;
}
// Set light's diffuse color by an array of GLfloat
void GLC_Light::SetColDiffuse(const GLfloat* pfCol)
{
m_fColDiffuse[0]= pfCol[0];
m_fColDiffuse[1]= pfCol[1];
m_fColDiffuse[2]= pfCol[2];
m_fColDiffuse[3]= pfCol[3];
m_bListeIsValid = false;
}
// Set light's specular color by an array of GLfloat
void GLC_Light::SetColSpeculaire(const GLfloat* pfCol)
{
m_fColSpeculaire[0]= pfCol[0];
m_fColSpeculaire[1]= pfCol[1];
m_fColSpeculaire[2]= pfCol[2];
m_fColSpeculaire[3]= pfCol[3];
m_bListeIsValid = false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create light's OpenGL list
bool GLC_Light::CreationListe(GLenum Mode)
{
if(!m_ListeID) // OpenGL list not created
{
m_ListeID= glGenLists(1);
if (!m_ListeID) // OpenGL List Id not get
{
GlDraw();
qDebug("GLC_Lumiere::CreationListe Display list not create");
return false; // Light execution without OpenGL list creation
}
}
// OpenGL list creation and execution
glNewList(m_ListeID, Mode);
// Light execution
GlDraw();
glEndList();
// Indicateur de la validit de la liste
m_bListeIsValid= true;
//! \todo add error handler
return true; // OpenGL list created
}
// Execute OpenGL light
bool GLC_Light::GlExecute(GLenum Mode)
{
// Object Name
glLoadName(GetID());
if (!m_bListeIsValid)
{
// OpenGL list is not valid
CreationListe(Mode);
}
else
{
glCallList(m_ListeID);
}
//! \todo Add error handler here
return true;
}
// OpenGL light set up
void GLC_Light::GlDraw(void)
{
// Color
glLightfv(m_LumiereID, GL_AMBIENT, m_fColAmbiente); // Setup The Ambient Light
glLightfv(m_LumiereID, GL_DIFFUSE, m_fColDiffuse); // Setup The Diffuse Light
glLightfv(m_LumiereID, GL_SPECULAR, m_fColSpeculaire); // Setup The specular Light
// Position
glLightfv(m_LumiereID, GL_POSITION, m_fPos); // Position The Light
}
<commit_msg>Rename some members.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9, packaged on Novemeber, 2005.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_light.cpp implementation of the GLC_Light class.
#include <QtDebug>
#include "glc_light.h"
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light(const char *pName ,const GLfloat *pAmbiantColor)
:GLC_Object(pName)
, m_LightID(GL_LIGHT1) // Default Light ID
, m_ListID(0) // By default display list ID= 0
, m_ListIsValid(false) // By default display list is not valid
{
//! \todo modify class to support multi light
// Color Initialisation
if (pAmbiantColor != 0)
{
m_AmbientColor[0]= pAmbiantColor[0];
m_AmbientColor[1]= pAmbiantColor[1];
m_AmbientColor[2]= pAmbiantColor[2];
m_AmbientColor[3]= pAmbiantColor[3];
}
else
{ // By default light's color is dark grey
m_AmbientColor[0]= 0.2f;
m_AmbientColor[1]= 0.2f;
m_AmbientColor[2]= 0.2f;
m_AmbientColor[3]= 1.0f;
}
// Other are white
// Diffuse Color
m_DiffuseColor[0]= 1.0f;
m_DiffuseColor[1]= 1.0f;
m_DiffuseColor[2]= 1.0f;
m_DiffuseColor[3]= 1.0f;
// Specular Color
m_SpecularColor[0]= 1.0f;
m_SpecularColor[1]= 1.0f;
m_SpecularColor[2]= 1.0f;
m_SpecularColor[3]= 1.0f;
// Color position
m_Position[0]= 0.0f;
m_Position[1]= 0.0f;
m_Position[2]= 0.0f;
m_Position[3]= 1.0f;
}
GLC_Light::~GLC_Light(void)
{
DeleteList();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Set the lihgt position by a 4D vector
void GLC_Light::SetPosition(const GLC_Vector4d &VectPos)
{
m_Position[0]= static_cast<GLfloat>(VectPos.GetX());
m_Position[1]= static_cast<GLfloat>(VectPos.GetY());
m_Position[2]= static_cast<GLfloat>(VectPos.GetZ());
m_Position[3]= static_cast<GLfloat>(VectPos.GetW());
m_ListIsValid = false;
}
// Set the lihgt position by a 3 GLfloat
void GLC_Light::SetPosition(GLfloat x, GLfloat y, GLfloat z)
{
m_Position[0]= x;
m_Position[1]= y;
m_Position[2]= z;
m_ListIsValid = false;
}
// Set light's ambiant color by an array of GLfloat
void GLC_Light::SetAmbientColor(const GLfloat* pfCol)
{
m_AmbientColor[0]= pfCol[0];
m_AmbientColor[1]= pfCol[1];
m_AmbientColor[2]= pfCol[2];
m_AmbientColor[3]= pfCol[3];
m_ListIsValid = false;
}
// Set light's diffuse color by an array of GLfloat
void GLC_Light::SetDiffuseColor(const GLfloat* pfCol)
{
m_DiffuseColor[0]= pfCol[0];
m_DiffuseColor[1]= pfCol[1];
m_DiffuseColor[2]= pfCol[2];
m_DiffuseColor[3]= pfCol[3];
m_ListIsValid = false;
}
// Set light's specular color by an array of GLfloat
void GLC_Light::SetSpecularColor(const GLfloat* pfCol)
{
m_SpecularColor[0]= pfCol[0];
m_SpecularColor[1]= pfCol[1];
m_SpecularColor[2]= pfCol[2];
m_SpecularColor[3]= pfCol[3];
m_ListIsValid = false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// Create light's OpenGL list
bool GLC_Light::CreationList(GLenum Mode)
{
if(!m_ListID) // OpenGL list not created
{
m_ListID= glGenLists(1);
if (!m_ListID) // OpenGL List Id not get
{
GlDraw();
qDebug("GLC_Lumiere::CreationListe Display list not create");
return false; // Light execution without OpenGL list creation
}
}
// OpenGL list creation and execution
glNewList(m_ListID, Mode);
// Light execution
GlDraw();
glEndList();
// Indicateur de la validit de la liste
m_ListIsValid= true;
//! \todo add error handler
return true; // OpenGL list created
}
// Execute OpenGL light
bool GLC_Light::GlExecute(GLenum Mode)
{
// Object Name
glLoadName(GetID());
if (!m_ListIsValid)
{
// OpenGL list is not valid
CreationList(Mode);
}
else
{
glCallList(m_ListID);
}
//! \todo Add error handler here
return true;
}
// OpenGL light set up
void GLC_Light::GlDraw(void)
{
// Color
glLightfv(m_LightID, GL_AMBIENT, m_AmbientColor); // Setup The Ambient Light
glLightfv(m_LightID, GL_DIFFUSE, m_DiffuseColor); // Setup The Diffuse Light
glLightfv(m_LightID, GL_SPECULAR, m_SpecularColor); // Setup The specular Light
// Position
glLightfv(m_LightID, GL_POSITION, m_Position); // Position The Light
}
<|endoftext|> |
<commit_before>class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
if (gas.empty()) {
return -1;
}
int start_index = 0;
int total = 0;
int charge = 0;
for(size_t i = 0; i < gas.size(); i++) {
charge += gas[i] - cost[i];
if (charge < 0) {
total += charge;
charge = 0;
start_index = i+1;
}
}
total += charge;
if (total < 0) {
return -1;
}
return start_index;
}
};
<commit_msg>Gas Station<commit_after>class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
if (gas.empty()) {
return -1;
}
int start_index = 0;
int total = 0;
int charge = 0;
for(size_t i = 0; i < gas.size(); i++) {
charge += gas[i] - cost[i];
if (charge < 0) {
total += charge;
charge = 0;
start_index = i+1;
}
}
total += charge;
if (total < 0) {
return -1;
}
return start_index;
}
};
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int cur = 0, index = 0, total = 0;
for (int i = 0; i < gas.size(); ++i) {
int left = gas[i] - cost[i];
cur += left;
total += left;
if (cur < 0) {
index = i+1;
cur = 0;
}
}
if (total < 0)
return -1;
return index;
}
};
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <bitset>
#include "hamt.hpp"
static const auto show = [](auto indices) {
std::size_t shift = 0;
for(auto i: indices) {
std::cout << i << "/" << (i << shift) << ", ";
if(shift)
shift += 5;
else
shift += 4;
}
std::cout << std::endl;
};
TEST(hamt, iter) {
const std::size_t indices[] = {0, 4, 15, 16, 24, 31};
const double values[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::size_t mask = 0;
for(auto i: indices) {
mask |= 1ul << i;
}
sparse::storage<double, 32, 6> test(
mask, values[0], values[1], values[2], values[3], values[4], values[5]);
const std::size_t* ri = indices;
const double* rj = values;
test.iter(0, [&](std::size_t i, double j) {
// std::cout << i << ": " << j << std::endl;
ASSERT_EQ(i, *ri++);
ASSERT_EQ(j, *rj++);
});
hamt::array<double, 5, 4> x;
x = x.set(1, 1.0);
x = x.set(2, 2.0);
x = x.set(16, 3.0);
x = x.set(32, 32.0);
x = x.set(47, 33.0);
x = x.set(48, 33.0);
x = x.set(100000, 10.0);
using traits = hamt::traits<5, 4>;
std::clog << std::bitset<64>(traits::masks[0]) << std::endl;
std::clog << std::bitset<64>(traits::masks[1]) << std::endl;
std::clog << std::bitset<64>(traits::masks[2]) << std::endl;
show(traits::split(47, traits::level_indices{}));
show(traits::split(48, traits::level_indices{}));
std::clog << x.get(48) << std::endl;
x.iter([](auto i, auto j) { std::clog << i << " " << j << std::endl; });
}
TEST(hamt, quirks) {
hamt::array<double> x;
using traits = hamt::traits<5, 4>;
const std::size_t key = 105965433143312;
x = x.set(105965433143312, 1.0);
std::clog << std::hex << key << std::endl;
std::clog << std::bitset<64>(key) << std::endl;
show(traits::split(key, traits::level_indices{}));
std::clog << x.get(key) << std::endl;
}
<commit_msg>tests<commit_after>#include <gtest/gtest.h>
#include <bitset>
#include "hamt.hpp"
static const auto show = [](auto indices) {
std::size_t shift = 0;
for(auto i: indices) {
std::cout << i << "/" << (i << shift) << ", ";
if(shift)
shift += 5;
else
shift += 4;
}
std::cout << std::endl;
};
TEST(hamt, iter) {
const std::size_t indices[] = {0, 4, 15, 16, 24, 31};
const double values[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0};
std::size_t mask = 0;
for(auto i: indices) {
mask |= 1ul << i;
}
sparse::storage<double, 32, 6> test(
mask, values[0], values[1], values[2], values[3], values[4], values[5]);
const std::size_t* ri = indices;
const double* rj = values;
test.iter(0, [&](std::size_t i, double j) {
// std::cout << i << ": " << j << std::endl;
ASSERT_EQ(i, *ri++);
ASSERT_EQ(j, *rj++);
});
hamt::array<double, 5, 4> x;
x = x.set(1, 1.0);
x = x.set(2, 2.0);
x = x.set(16, 3.0);
x = x.set(32, 32.0);
x = x.set(47, 33.0);
x = x.set(48, 33.0);
x = x.set(100000, 10.0);
using traits = hamt::traits<5, 4>;
std::clog << std::bitset<64>(traits::masks[0]) << std::endl;
std::clog << std::bitset<64>(traits::masks[1]) << std::endl;
std::clog << std::bitset<64>(traits::masks[2]) << std::endl;
show(traits::split(47, traits::level_indices{}));
show(traits::split(48, traits::level_indices{}));
std::clog << x.get(48) << std::endl;
x.iter([](auto i, auto j) {
std::clog << i << " " << j << std::endl;
});
}
TEST(hamt, quirks) {
hamt::array<double> x;
using traits = hamt::traits<5, 4>;
const std::size_t keys[] = {105965433143312, 105965433145616};
for(auto key: keys) {
x = x.set(key, 1.0);
}
for(auto key: keys) {
std::clog << x.get(key) << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/mobile/delete_command_request.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
DeleteCommandRequest::DeleteCommandRequest(
const MessageSharedPtr& message, ApplicationManager& application_manager)
: CommandRequestImpl(message, application_manager)
, is_ui_send_(false)
, is_vr_send_(false)
, is_ui_received_(false)
, is_vr_received_(false)
, ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
, vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
DeleteCommandRequest::~DeleteCommandRequest() {}
void DeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
const int32_t cmd_id =
(*message_)[strings::msg_params][strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
smart_objects::SmartObject msg_params =
smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
msg_params[strings::app_id] = application->app_id();
// we should specify amount of required responses in the 1st request
uint32_t chaining_counter = 0;
if ((*command).keyExists(strings::menu_params)) {
++chaining_counter;
}
if ((*command).keyExists(strings::vr_commands)) {
++chaining_counter;
}
/* Need to set all flags before sending request to HMI
* for correct processing this flags in method on_event */
if ((*command).keyExists(strings::menu_params)) {
is_ui_send_ = true;
}
// check vr params
if ((*command).keyExists(strings::vr_commands)) {
is_vr_send_ = true;
}
if (is_ui_send_) {
SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);
}
if (is_vr_send_) {
// VR params
msg_params[strings::grammar_id] = application->get_grammar_id();
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);
}
}
bool DeleteCommandRequest::PrepareResponseParameters(
mobile_apis::Result::eType& result_code, std::string& info) {
using namespace helpers;
ResponseInfo ui_delete_info(ui_result_, HmiInterfaces::HMI_INTERFACE_UI);
ResponseInfo vr_delete_info(vr_result_, HmiInterfaces::HMI_INTERFACE_VR);
const bool result =
PrepareResultForMobileResponse(ui_delete_info, vr_delete_info);
const bool is_vr_or_ui_warning =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
hmi_apis::Common_Result::WARNINGS, ui_result_, vr_result_);
info = MergeInfos(ui_info_, vr_info_);
if (is_vr_or_ui_warning && !ui_delete_info.is_unsupported_resource &&
!vr_delete_info.is_unsupported_resource) {
LOG4CXX_DEBUG(logger_, "VR or UI result is warning");
result_code = mobile_apis::Result::WARNINGS;
return result;
}
result_code = PrepareResultCodeForResponse(ui_delete_info, vr_delete_info);
LOG4CXX_DEBUG(logger_, "Result is " << (result ? "true" : "false"));
return result;
}
void DeleteCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_DeleteCommand: {
is_ui_received_ = true;
ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
LOG4CXX_DEBUG(logger_,
"Received UI_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(ui_result_));
GetInfo(message, ui_info_);
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
is_vr_received_ = true;
vr_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
LOG4CXX_DEBUG(logger_,
"Received VR_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(vr_result_));
GetInfo(message, vr_info_);
break;
}
default: {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
if (IsPendingResponseExist()) {
LOG4CXX_DEBUG(logger_, "Still awaiting for other responses.");
return;
}
ApplicationSharedPtr application =
application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
return;
}
smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
const int32_t cmd_id = msg_params[strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_,
"Command id " << cmd_id << " not found for "
"application with connection key "
<< connection_key());
return;
}
mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
std::string info;
const bool result = PrepareResponseParameters(result_code, info);
if (result) {
application->RemoveCommand(msg_params[strings::cmd_id].asInt());
}
SendResponse(
result, result_code, info.empty() ? NULL : info.c_str(), &msg_params);
if (result) {
application->UpdateHash();
}
}
bool DeleteCommandRequest::IsPendingResponseExist() {
LOG4CXX_AUTO_TRACE(logger_);
return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;
}
} // namespace commands
} // namespace application_manager
<commit_msg>Fix problem with merging info for delete command (#903)<commit_after>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/mobile/delete_command_request.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
DeleteCommandRequest::DeleteCommandRequest(
const MessageSharedPtr& message, ApplicationManager& application_manager)
: CommandRequestImpl(message, application_manager)
, is_ui_send_(false)
, is_vr_send_(false)
, is_ui_received_(false)
, is_vr_received_(false)
, ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
, vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
DeleteCommandRequest::~DeleteCommandRequest() {}
void DeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
const int32_t cmd_id =
(*message_)[strings::msg_params][strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
smart_objects::SmartObject msg_params =
smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
msg_params[strings::app_id] = application->app_id();
// we should specify amount of required responses in the 1st request
uint32_t chaining_counter = 0;
if ((*command).keyExists(strings::menu_params)) {
++chaining_counter;
}
if ((*command).keyExists(strings::vr_commands)) {
++chaining_counter;
}
/* Need to set all flags before sending request to HMI
* for correct processing this flags in method on_event */
if ((*command).keyExists(strings::menu_params)) {
is_ui_send_ = true;
}
// check vr params
if ((*command).keyExists(strings::vr_commands)) {
is_vr_send_ = true;
}
if (is_ui_send_) {
SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);
}
if (is_vr_send_) {
// VR params
msg_params[strings::grammar_id] = application->get_grammar_id();
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);
}
}
bool DeleteCommandRequest::PrepareResponseParameters(
mobile_apis::Result::eType& result_code, std::string& info) {
using namespace helpers;
ResponseInfo ui_delete_info(ui_result_, HmiInterfaces::HMI_INTERFACE_UI);
ResponseInfo vr_delete_info(vr_result_, HmiInterfaces::HMI_INTERFACE_VR);
const bool result =
PrepareResultForMobileResponse(ui_delete_info, vr_delete_info);
const bool is_vr_or_ui_warning =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
hmi_apis::Common_Result::WARNINGS, ui_result_, vr_result_);
info = MergeInfos(ui_delete_info, ui_info_, vr_delete_info, vr_info_);
if (is_vr_or_ui_warning && !ui_delete_info.is_unsupported_resource &&
!vr_delete_info.is_unsupported_resource) {
LOG4CXX_DEBUG(logger_, "VR or UI result is warning");
result_code = mobile_apis::Result::WARNINGS;
return result;
}
result_code = PrepareResultCodeForResponse(ui_delete_info, vr_delete_info);
LOG4CXX_DEBUG(logger_, "Result is " << (result ? "true" : "false"));
return result;
}
void DeleteCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_DeleteCommand: {
is_ui_received_ = true;
ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
LOG4CXX_DEBUG(logger_,
"Received UI_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(ui_result_));
GetInfo(message, ui_info_);
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
is_vr_received_ = true;
vr_result_ = static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
LOG4CXX_DEBUG(logger_,
"Received VR_DeleteCommand event with result "
<< MessageHelper::HMIResultToString(vr_result_));
GetInfo(message, vr_info_);
break;
}
default: {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
if (IsPendingResponseExist()) {
LOG4CXX_DEBUG(logger_, "Still awaiting for other responses.");
return;
}
ApplicationSharedPtr application =
application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
return;
}
smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
const int32_t cmd_id = msg_params[strings::cmd_id].asInt();
smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
LOG4CXX_ERROR(logger_,
"Command id " << cmd_id << " not found for "
"application with connection key "
<< connection_key());
return;
}
mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
std::string info;
const bool result = PrepareResponseParameters(result_code, info);
if (result) {
application->RemoveCommand(msg_params[strings::cmd_id].asInt());
}
SendResponse(
result, result_code, info.empty() ? NULL : info.c_str(), &msg_params);
if (result) {
application->UpdateHash();
}
}
bool DeleteCommandRequest::IsPendingResponseExist() {
LOG4CXX_AUTO_TRACE(logger_);
return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;
}
} // namespace commands
} // namespace application_manager
<|endoftext|> |
<commit_before>//
// main.cpp
// Unit Tests
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>
/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
// Make sure that the read simulation finishes
REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
*/
TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
REQUIRE( createReferenceGenome(10000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}
TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.02) == 0);
}
TEST_CASE( "Generate sequence reads", "[perfectReads]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 10, 100, 300, "normalRef") == 0);
//generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}
TEST_CASE( " Mapping first set of reads", "[mapReads]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}
TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}
TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}
/*
TEST_CASE( "Create heterozygous R1", "[createHet]") {
REQUIRE( createHeterozygousGenome("normalRef_R1.fastq", "mutatedRef_R1.fastq", "hetRef_R1.fastq") == 0);
}
TEST_CASE( "Create heterozygous R2", "[createHet]") {
REQUIRE( createHeterozygousGenome("normalRef_R2.fastq", "mutatedRef_R2.fastq", "hetRef_R2.fastq") == 0);
}
TEST_CASE( " Mapping het reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "hetRef_R1.fastq", "hetRef_R2.fastq", "het.bam", "25") == 0);
}
*/
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 5000 as a max because we don't want to exclude any loci for this test
}
TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}
<commit_msg>Minor changes<commit_after>//
// main.cpp
// Unit Tests
//
// Created by Evan McCartney-Melstad on 12/31/14.
// Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "../cPWP/generateSimulatedData.h"
#include "../cPWP/bamsToBin.h"
#include "../cPWP/calcPWP.h"
#include "catch.hpp"
#include <string>
#include <iostream>
#include <fstream>
/*
TEST_CASE( "Simulated reads are generated", "[generateReads]" ) {
// Make sure that the read simulation finishes
REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0);
}
*/
TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") {
REQUIRE( createReferenceGenome(10000000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 );
}
TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") {
REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.02) == 0);
}
TEST_CASE( "Generate sequence reads", "[perfectReads]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 10, 100, 300, "normalRef") == 0);
//generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);
}
TEST_CASE( " Mapping first set of reads", "[mapReads]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "normalRef_R1.fastq", "normalRef_R2.fastq", "normal.bam", "25") == 0);
}
TEST_CASE( "Generate sequence reads 2", "[perfectReads2]") {
REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0);
}
/*
TEST_CASE( " Mapping second set of reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "mutatedRef_R1.fastq", "mutatedRef_R2.fastq", "mutated.bam", "25") == 0);
}
*/
TEST_CASE( "Create heterozygous R1", "[createHet]") {
REQUIRE( createHeterozygousGenome("normalRef_R1.fastq", "mutatedRef_R1.fastq", "hetRef_R1.fastq") == 0);
}
TEST_CASE( "Create heterozygous R2", "[createHet]") {
REQUIRE( createHeterozygousGenome("normalRef_R2.fastq", "mutatedRef_R2.fastq", "hetRef_R2.fastq") == 0);
}
TEST_CASE( " Mapping het reads", "[mapReads2]") {
REQUIRE( mapReads("simulatedReferenceGenome.fasta", "hetRef_R1.fastq", "hetRef_R2.fastq", "het.bam", "25") == 0);
}
TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) {
REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0);
}
TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") {
REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 2, 5000) == 0); // 5000 as a max because we don't want to exclude any loci for this test
}
TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") {
REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 0, 2, "testingOut.pwp", 30) == 0);
}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<commit_msg>Add session pause and resume to python bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/session.hpp>
#include <libtorrent/torrent.hpp>
#include <libtorrent/storage.hpp>
#include <libtorrent/ip_filter.hpp>
#include <boost/python.hpp>
#include "gil.hpp"
using namespace boost::python;
using namespace libtorrent;
extern char const* session_status_doc;
extern char const* session_status_has_incoming_connections_doc;
extern char const* session_status_upload_rate_doc;
extern char const* session_status_download_rate_doc;
extern char const* session_status_payload_upload_rate_doc;
extern char const* session_status_payload_download_rate_doc;
extern char const* session_status_total_download_doc;
extern char const* session_status_total_upload_doc;
extern char const* session_status_total_payload_download_doc;
extern char const* session_status_total_payload_upload_doc;
extern char const* session_status_num_peers_doc;
extern char const* session_status_dht_nodes_doc;
extern char const* session_status_cache_nodes_doc;
extern char const* session_status_dht_torrents_doc;
extern char const* session_doc;
extern char const* session_init_doc;
extern char const* session_listen_on_doc;
extern char const* session_is_listening_doc;
extern char const* session_listen_port_doc;
extern char const* session_status_m_doc;
extern char const* session_start_dht_doc;
extern char const* session_stop_dht_doc;
extern char const* session_dht_state_doc;
extern char const* session_add_dht_router_doc;
extern char const* session_add_torrent_doc;
extern char const* session_remove_torrent_doc;
extern char const* session_set_download_rate_limit_doc;
extern char const* session_download_rate_limit_doc;
extern char const* session_set_upload_rate_limit_doc;
extern char const* session_upload_rate_limit_doc;
extern char const* session_set_max_uploads_doc;
extern char const* session_set_max_connections_doc;
extern char const* session_set_max_half_open_connections_doc;
extern char const* session_num_connections_doc;
extern char const* session_set_settings_doc;
extern char const* session_set_pe_settings_doc;
extern char const* session_get_pe_settings_doc;
extern char const* session_set_severity_level_doc;
extern char const* session_pop_alert_doc;
extern char const* session_start_upnp_doc;
extern char const* session_start_lsd_doc;
extern char const* session_stop_lsd_doc;
extern char const* session_stop_upnp_doc;
extern char const* session_start_natpmp_doc;
extern char const* session_stop_natpmp_doc;
extern char const* session_set_ip_filter_doc;
namespace
{
bool listen_on(session& s, int min_, int max_, char const* interface)
{
allow_threading_guard guard;
return s.listen_on(std::make_pair(min_, max_), interface);
}
#ifndef TORRENT_DISABLE_DHT
void add_dht_router(session& s, std::string router_, int port_)
{
allow_threading_guard guard;
return s.add_dht_router(std::make_pair(router_, port_));
}
#endif
struct invoke_extension_factory
{
invoke_extension_factory(object const& callback)
: cb(callback)
{}
boost::shared_ptr<torrent_plugin> operator()(torrent* t, void*)
{
lock_gil lock;
return extract<boost::shared_ptr<torrent_plugin> >(cb(ptr(t)))();
}
object cb;
};
void add_extension(session& s, object const& e)
{
allow_threading_guard guard;
s.add_extension(invoke_extension_factory(e));
}
torrent_handle add_torrent(session& s, dict params)
{
add_torrent_params p;
if (params.has_key("ti"))
p.ti = new torrent_info(extract<torrent_info const&>(params["ti"]));
std::string url;
if (params.has_key("tracker_url"))
{
url = extract<std::string>(params["tracker_url"]);
p.tracker_url = url.c_str();
}
if (params.has_key("info_hash"))
p.info_hash = extract<sha1_hash>(params["info_hash"]);
std::string name;
if (params.has_key("name"))
{
name = extract<std::string>(params["name"]);
p.name = name.c_str();
}
p.save_path = fs::path(extract<std::string>(params["save_path"]));
std::vector<char> resume_buf;
if (params.has_key("resume_data"))
{
std::string resume = extract<std::string>(params["resume_data"]);
resume_buf.resize(resume.size());
std::memcpy(&resume_buf[0], &resume[0], resume.size());
p.resume_data = &resume_buf;
}
p.storage_mode = extract<storage_mode_t>(params["storage_mode"]);
p.paused = params["paused"];
p.auto_managed = params["auto_managed"];
p.duplicate_is_error = params["duplicate_is_error"];
return s.add_torrent(p);
}
void start_natpmp(session& s)
{
allow_threading_guard guard;
s.start_natpmp();
return;
}
void start_upnp(session& s)
{
allow_threading_guard guard;
s.start_upnp();
return;
}
list get_torrents(session& s)
{
list ret;
std::vector<torrent_handle> torrents = s.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin(); i != torrents.end(); ++i)
{
ret.append(*i);
}
return ret;
}
#ifndef TORRENT_DISABLE_GEO_IP
bool load_asnum_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_asnum_db(file.c_str());
}
bool load_country_db(session& s, std::string file)
{
allow_threading_guard guard;
return s.load_country_db(file.c_str());
}
#endif
} // namespace unnamed
void bind_session()
{
class_<session_status>("session_status", session_status_doc)
.def_readonly(
"has_incoming_connections", &session_status::has_incoming_connections
, session_status_has_incoming_connections_doc
)
.def_readonly(
"upload_rate", &session_status::upload_rate
, session_status_upload_rate_doc
)
.def_readonly(
"download_rate", &session_status::download_rate
, session_status_download_rate_doc
)
.def_readonly(
"payload_upload_rate", &session_status::payload_upload_rate
, session_status_payload_upload_rate_doc
)
.def_readonly(
"payload_download_rate", &session_status::payload_download_rate
, session_status_payload_download_rate_doc
)
.def_readonly(
"total_download", &session_status::total_download
, session_status_total_download_doc
)
.def_readonly(
"total_upload", &session_status::total_upload
, session_status_total_upload_doc
)
.def_readonly(
"total_payload_download", &session_status::total_payload_download
, session_status_total_payload_download_doc
)
.def_readonly(
"total_payload_upload", &session_status::total_payload_upload
, session_status_total_payload_upload_doc
)
.def_readonly(
"num_peers", &session_status::num_peers
, session_status_num_peers_doc
)
#ifndef TORRENT_DISABLE_DHT
.def_readonly(
"dht_nodes", &session_status::dht_nodes
, session_status_dht_nodes_doc
)
.def_readonly(
"dht_cache_nodes", &session_status::dht_node_cache
, session_status_cache_nodes_doc
)
.def_readonly(
"dht_torrents", &session_status::dht_torrents
, session_status_dht_torrents_doc
)
#endif
;
enum_<storage_mode_t>("storage_mode_t")
.value("storage_mode_allocate", storage_mode_allocate)
.value("storage_mode_sparse", storage_mode_sparse)
.value("storage_mode_compact", storage_mode_compact)
;
enum_<session::options_t>("options_t")
.value("none", session::none)
.value("delete_files", session::delete_files)
;
class_<session, boost::noncopyable>("session", session_doc, no_init)
.def(
init<fingerprint>(arg("fingerprint")=fingerprint("LT",0,1,0,0), session_init_doc)
)
.def(
"listen_on", &listen_on
, (arg("min"), "max", arg("interface") = (char const*)0)
, session_listen_on_doc
)
.def("is_listening", allow_threads(&session::is_listening), session_is_listening_doc)
.def("listen_port", allow_threads(&session::listen_port), session_listen_port_doc)
.def("status", allow_threads(&session::status), session_status_m_doc)
#ifndef TORRENT_DISABLE_DHT
.def(
"add_dht_router", &add_dht_router
, (arg("router"), "port")
, session_add_dht_router_doc
)
.def("start_dht", allow_threads(&session::start_dht), session_start_dht_doc)
.def("stop_dht", allow_threads(&session::stop_dht), session_stop_dht_doc)
.def("dht_state", allow_threads(&session::dht_state), session_dht_state_doc)
.def("set_dht_proxy", allow_threads(&session::set_dht_proxy))
#endif
.def("add_torrent", &add_torrent, session_add_torrent_doc)
.def("remove_torrent", allow_threads(&session::remove_torrent), arg("option") = session::none
, session_remove_torrent_doc)
.def(
"set_download_rate_limit", allow_threads(&session::set_download_rate_limit)
, session_set_download_rate_limit_doc
)
.def(
"download_rate_limit", allow_threads(&session::download_rate_limit)
, session_download_rate_limit_doc
)
.def(
"set_upload_rate_limit", allow_threads(&session::set_upload_rate_limit)
, session_set_upload_rate_limit_doc
)
.def(
"upload_rate_limit", allow_threads(&session::upload_rate_limit)
, session_upload_rate_limit_doc
)
.def(
"set_max_uploads", allow_threads(&session::set_max_uploads)
, session_set_max_uploads_doc
)
.def(
"set_max_connections", allow_threads(&session::set_max_connections)
, session_set_max_connections_doc
)
.def(
"set_max_half_open_connections", allow_threads(&session::set_max_half_open_connections)
, session_set_max_half_open_connections_doc
)
.def(
"num_connections", allow_threads(&session::num_connections)
, session_num_connections_doc
)
.def("set_settings", allow_threads(&session::set_settings), session_set_settings_doc)
#ifndef TORRENT_DISABLE_ENCRYPTION
.def("set_pe_settings", allow_threads(&session::set_pe_settings), session_set_pe_settings_doc)
.def("get_pe_settings", allow_threads(&session::get_pe_settings), return_value_policy<copy_const_reference>())
#endif
#ifndef TORRENT_DISABLE_GEO_IP
.def("load_asnum_db", &load_asnum_db)
.def("load_country_db", &load_country_db)
#endif
.def("load_state", allow_threads(&session::load_state))
.def("state", allow_threads(&session::state))
.def(
"set_severity_level", allow_threads(&session::set_severity_level)
, session_set_severity_level_doc
)
.def("pop_alert", allow_threads(&session::pop_alert), session_pop_alert_doc)
.def("add_extension", &add_extension)
.def("set_peer_proxy", allow_threads(&session::set_peer_proxy))
.def("set_tracker_proxy", allow_threads(&session::set_tracker_proxy))
.def("set_web_seed_proxy", allow_threads(&session::set_web_seed_proxy))
.def("start_upnp", &start_upnp, session_start_upnp_doc)
.def("stop_upnp", allow_threads(&session::stop_upnp), session_stop_upnp_doc)
.def("start_lsd", allow_threads(&session::start_lsd), session_start_lsd_doc)
.def("stop_lsd", allow_threads(&session::stop_lsd), session_stop_lsd_doc)
.def("start_natpmp", &start_natpmp, session_start_natpmp_doc)
.def("stop_natpmp", allow_threads(&session::stop_natpmp), session_stop_natpmp_doc)
.def("set_ip_filter", allow_threads(&session::set_ip_filter), session_set_ip_filter_doc)
.def("find_torrent", allow_threads(&session::find_torrent))
.def("get_torrents", &get_torrents)
.def("pause", allow_threads(&session::pause))
.def("resume", allow_threads(&session::resume))
.def("is_paused", allow_threads(&session::is_paused))
;
register_ptr_to_python<std::auto_ptr<alert> >();
}
<|endoftext|> |
<commit_before>#ifndef _VINECPP_HEADER_HPP_
#define _VINECPP_HEADER_HPP_
// headers
#ifndef DBL_MAX
#define DBL_MAX 1.79769e+308
#endif
#include <iostream>
#include <string>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>
#include <nlopt.hpp>
#include <algorithm>
#include <utility>
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include<fstream>
#include<time.h>
// headers from the boost library
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/students_t.hpp>
//#include <boost/math/special_functions/detail/t_distribution_inv.hpp>
#include <boost/math/tools/roots.hpp>
#include <boost/random.hpp>
// gsl library
//#include <stdio.h>
//#include <gsl/gsl_cdf.h>
// User written headers
#include "VineCPP_helper.hpp"
#include "PC.hpp"
#include "PathToBoundsAndSeed.hpp"
#endif
<commit_msg>Position of DBL_MAX definition changed<commit_after>#ifndef _VINECPP_HEADER_HPP_
#define _VINECPP_HEADER_HPP_
// headers
#include <iostream>
#include <string>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>
#include <nlopt.hpp>
#include <algorithm>
#include <utility>
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include<fstream>
#include<time.h>
// headers from the boost library
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/students_t.hpp>
//#include <boost/math/special_functions/detail/t_distribution_inv.hpp>
#include <boost/math/tools/roots.hpp>
#include <boost/random.hpp>
// gsl library
//#include <stdio.h>
//#include <gsl/gsl_cdf.h>
#ifndef DBL_MAX
#define DBL_MAX 1.79769e+308
#endif
// User written headers
#include "VineCPP_helper.hpp"
#include "PC.hpp"
#include "PathToBoundsAndSeed.hpp"
#endif
<|endoftext|> |
<commit_before>/*
Empath - Mailer for KDE
Copyright 1999, 2000
Rik Hemsley <rik@kde.org>
Wilco Greven <j.w.greven@student.utwente.nl>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef __GNUG__
# pragma implementation "EmpathMainWidget.h"
#endif
// Qt includes
#include <qheader.h>
#include <qvaluelist.h>
#include <qlayout.h>
#include <qsplitter.h>
// KDE includes
#include <kconfig.h>
#include <kglobal.h>
// Local includes
#include "EmpathURL.h"
#include "EmpathConfig.h"
#include "EmpathMainWidget.h"
#include "EmpathFolderWidget.h"
#include "EmpathMessageViewWidget.h"
#include "EmpathMessageListWidget.h"
#include "EmpathIndex.h"
EmpathMainWidget::EmpathMainWidget(QWidget * parent)
: QWidget(parent, "MainWidget")
{
QSplitter * hSplit = new QSplitter(this, "hSplit");
(new QVBoxLayout(this))->addWidget(hSplit);
EmpathFolderWidget * folderWidget = new EmpathFolderWidget(hSplit);
QSplitter * vSplit = new QSplitter(Qt::Vertical, hSplit, "vSplit");
messageListWidget_ = new EmpathMessageListWidget(vSplit);
EmpathMessageViewWidget * messageViewWidget =
new EmpathMessageViewWidget(EmpathURL(), vSplit);
QObject::connect(
folderWidget, SIGNAL(showFolder(const EmpathURL &)),
this, SLOT(s_showFolder(const EmpathURL &)));
QObject::connect(
messageListWidget_, SIGNAL(changeView(const QString &)),
this, SLOT(s_changeView(const QString &)));
}
EmpathMainWidget::~EmpathMainWidget()
{
// Empty.
}
void
EmpathMainWidget::s_showFolder(const EmpathURL & url)
{
currentFolder_ = url;
EmpathFolder * f(empath->folder(url));
if (0 == f) {
empathDebug("Can't find folder `" + url.asString() + "'");
return;
}
empathDebug("Doing showFolder...");
messageListWidget_->s_showFolder(f->index()->dict());
}
void
EmpathMainWidget::s_changeView(const QString & id)
{
EmpathURL u(currentFolder_);
u.setMessageID(id);
messageViewWidget_->s_setMessage(u);
}
// vim:ts=4:sw=4:tw=78
<commit_msg>Duh. Fixed the problem where when you select a message to view, you get a free segfault.<commit_after>/*
Empath - Mailer for KDE
Copyright 1999, 2000
Rik Hemsley <rik@kde.org>
Wilco Greven <j.w.greven@student.utwente.nl>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifdef __GNUG__
# pragma implementation "EmpathMainWidget.h"
#endif
// Qt includes
#include <qheader.h>
#include <qvaluelist.h>
#include <qlayout.h>
#include <qsplitter.h>
// KDE includes
#include <kconfig.h>
#include <kglobal.h>
// Local includes
#include "EmpathURL.h"
#include "EmpathConfig.h"
#include "EmpathMainWidget.h"
#include "EmpathFolderWidget.h"
#include "EmpathMessageViewWidget.h"
#include "EmpathMessageListWidget.h"
#include "EmpathIndex.h"
EmpathMainWidget::EmpathMainWidget(QWidget * parent)
: QWidget(parent, "MainWidget")
{
QSplitter * hSplit = new QSplitter(this, "hSplit");
(new QVBoxLayout(this))->addWidget(hSplit);
EmpathFolderWidget * folderWidget = new EmpathFolderWidget(hSplit);
QSplitter * vSplit = new QSplitter(Qt::Vertical, hSplit, "vSplit");
messageListWidget_ = new EmpathMessageListWidget(vSplit);
messageViewWidget_ =
new EmpathMessageViewWidget(EmpathURL(), vSplit);
QObject::connect(
folderWidget, SIGNAL(showFolder(const EmpathURL &)),
this, SLOT(s_showFolder(const EmpathURL &)));
QObject::connect(
messageListWidget_, SIGNAL(changeView(const QString &)),
this, SLOT(s_changeView(const QString &)));
}
EmpathMainWidget::~EmpathMainWidget()
{
// Empty.
}
void
EmpathMainWidget::s_showFolder(const EmpathURL & url)
{
currentFolder_ = url;
EmpathFolder * f(empath->folder(url));
if (0 == f) {
empathDebug("Can't find folder `" + url.asString() + "'");
return;
}
empathDebug("Doing showFolder...");
messageListWidget_->s_showFolder(f->index()->dict());
}
void
EmpathMainWidget::s_changeView(const QString & id)
{
EmpathURL u(currentFolder_);
u.setMessageID(id);
messageViewWidget_->s_setMessage(u);
}
// vim:ts=4:sw=4:tw=78
<|endoftext|> |
<commit_before>#include "sexpr.hpp"
#include "parse.hpp"
namespace {
template<char ... c>
static int matches(int x) {
static const char data[] = {c..., 0};
for(const char* i = data; *i; ++i) {
if(*i == x) return true;
}
return false;
}
}
maybe<sexpr> sexpr::parse(std::istream& in) {
using namespace parser;
static const auto separator_parser = // parser::debug("sep") |=
noskip(chr<std::isspace>());
static const auto real_parser = // parser::debug("real") |=
value<double>();
static const auto number_parser = // debug("num") |=
real_parser >> [](real num) {
const long cast = num;
const sexpr value = num == real(cast) ? sexpr(cast) : sexpr(num);
return pure(value);
};
static const auto initial_parser = chr<std::isalpha>();
static const auto rest_parser = chr<std::isalnum>();
static const auto symbol_parser = initial_parser >> [](char c) {
return noskip(*rest_parser >> [c](std::deque<char>&& rest) {
const std::string tmp = c + std::string(rest.begin(), rest.end());
return pure(symbol(tmp));
});
};
static const auto op_parser =
chr<matches<'+', '-', '*', '/', '=', '<', '>', '%' >>() >> [](char c) {
return pure(symbol(std::string(1, c)));
}
| (token("!=") | token("<=") | token(">=")) >> [](const char* s) {
return pure(symbol(s));
};
static const auto attr_parser = chr<matches<':'>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static const auto as_expr = parser::cast<sexpr>();
static auto expr_parser = any<sexpr>();
static const auto lparen = // debug("lparen") |=
token("(");
static const auto rparen = // debug("rparen") |=
token(")");
static const auto exprs_parser = // debug("exprs") |=
parser::ref(expr_parser) % separator_parser;
static const auto list_parser = // debug("list") |=
lparen >>= exprs_parser >> drop(rparen)
>> [](std::deque<sexpr>&& es) {
return pure(make_list(es.begin(), es.end()));
};
static const auto once =
(expr_parser =
// debug("expr") |=
(symbol_parser >> as_expr)
| (attr_parser >> as_expr)
| (op_parser >> as_expr)
| number_parser
| (list_parser >> as_expr)
, 0); (void) once;
// debug::stream = &std::clog;
return expr_parser(in);
}
<commit_msg>fixed integer/double parsing<commit_after>#include "sexpr.hpp"
#include "parse.hpp"
namespace {
template<char ... c>
static int matches(int x) {
static const char data[] = {c..., 0};
for(const char* i = data; *i; ++i) {
if(*i == x) return true;
}
return false;
}
}
template<class T>
static const std::ios::pos_type try_parse(std::istream& in) {
const parser::stream_state backup(in);
T t;
in >> t;
return parser::stream_state(in).pos;
}
maybe<sexpr> sexpr::parse(std::istream& in) {
using namespace parser;
static const auto separator_parser = // parser::debug("sep") |=
noskip(chr<std::isspace>());
static const auto integer_parser = // parser::debug("real") |=
value<integer>();
static const auto real_parser = // parser::debug("real") |=
value<double>();
static const auto as_expr = parser::cast<sexpr>();
static const auto number_parser = [](std::istream& in) {
const auto pr = try_parse<real>(in);
const auto pi = try_parse<integer>(in);
if(pr == pi) return (integer_parser >> as_expr)(in);
return (real_parser >> as_expr)(in);
};
static const auto initial_parser = chr<std::isalpha>();
static const auto rest_parser = chr<std::isalnum>();
static const auto symbol_parser = initial_parser >> [](char c) {
return noskip(*rest_parser >> [c](std::deque<char>&& rest) {
const std::string tmp = c + std::string(rest.begin(), rest.end());
return pure(symbol(tmp));
});
};
static const auto op_parser =
chr<matches<'+', '-', '*', '/', '=', '<', '>', '%' >>() >> [](char c) {
return pure(symbol(std::string(1, c)));
}
| (token("!=") | token("<=") | token(">=")) >> [](const char* s) {
return pure(symbol(s));
};
static const auto attr_parser = chr<matches<':'>>() >> [](char c) {
return symbol_parser >> [c](symbol s) {
return pure(symbol(c + std::string(s.get())));
};
};
static auto expr_parser = any<sexpr>();
static const auto lparen = // debug("lparen") |=
token("(");
static const auto rparen = // debug("rparen") |=
token(")");
static const auto exprs_parser = // debug("exprs") |=
parser::ref(expr_parser) % separator_parser;
static const auto list_parser = // debug("list") |=
lparen >>= exprs_parser >> drop(rparen)
>> [](std::deque<sexpr>&& es) {
return pure(make_list(es.begin(), es.end()));
};
static const auto once =
(expr_parser =
// debug("expr") |=
(symbol_parser >> as_expr)
| (attr_parser >> as_expr)
| (op_parser >> as_expr)
| number_parser
| (list_parser >> as_expr)
, 0); (void) once;
// debug::stream = &std::clog;
return expr_parser(in);
}
<|endoftext|> |
<commit_before>#include "builtin/class.hpp"
#include "builtin/object.hpp"
#include "builtin/stat.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "ontology.hpp"
namespace rubinius {
void Stat::init(STATE) {
GO(stat_class).set(ontology::new_class(state, "Stat", G(object), G(rubinius)));
G(stat_class)->set_object_type(state, StatType);
}
Fixnum* Stat::stat(STATE, String* p) {
path(state, p);
return Fixnum::from(::stat(p->c_str_null_safe(state), &st_));
}
Fixnum* Stat::fstat(STATE, Integer* fd) {
return Fixnum::from(::fstat(fd->to_native(), &st_));
}
Fixnum* Stat::lstat(STATE, String* p) {
path(state, p);
return Fixnum::from(::lstat(p->c_str_null_safe(state), &st_));
}
Integer* Stat::stat_dev(STATE) {
return Integer::from(state, st_.st_dev);
}
Integer* Stat::stat_ino(STATE) {
return Integer::from(state, st_.st_ino);
}
Integer* Stat::stat_mode(STATE) {
return Integer::from(state, st_.st_mode);
}
Integer* Stat::stat_nlink(STATE) {
return Integer::from(state, st_.st_nlink);
}
Integer* Stat::stat_uid(STATE) {
return Integer::from(state, st_.st_uid);
}
Integer* Stat::stat_gid(STATE) {
return Integer::from(state, st_.st_gid);
}
Integer* Stat::stat_rdev(STATE) {
return Integer::from(state, st_.st_rdev);
}
Integer* Stat::stat_size(STATE) {
return Integer::from(state, st_.st_size);
}
Integer* Stat::stat_blksize(STATE) {
return Integer::from(state, st_.st_blksize);
}
Integer* Stat::stat_blocks(STATE) {
return Integer::from(state, st_.st_blocks);
}
Time* Stat::stat_atime(STATE) {
return Time::at(state, st_.st_atime);
}
Time* Stat::stat_mtime(STATE) {
return Time::at(state, st_.st_mtime);
}
Time* Stat::stat_ctime(STATE) {
return Time::at(state, st_.st_ctime);
}
Object* Stat::stat_birthtime(STATE) {
#ifdef HAVE_ST_BIRTHTIME
struct timespec ts = st_.st_birthtimespec;
return Time::at(state, ts.tv_sec, ts.tv_nsec);
#else
return Primitives::failure();
#endif
}
}
<commit_msg>Add nanosecond support for Stat::[amc]time<commit_after>#include "builtin/class.hpp"
#include "builtin/object.hpp"
#include "builtin/stat.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "ontology.hpp"
namespace rubinius {
void Stat::init(STATE) {
GO(stat_class).set(ontology::new_class(state, "Stat", G(object), G(rubinius)));
G(stat_class)->set_object_type(state, StatType);
}
Fixnum* Stat::stat(STATE, String* p) {
path(state, p);
return Fixnum::from(::stat(p->c_str_null_safe(state), &st_));
}
Fixnum* Stat::fstat(STATE, Integer* fd) {
return Fixnum::from(::fstat(fd->to_native(), &st_));
}
Fixnum* Stat::lstat(STATE, String* p) {
path(state, p);
return Fixnum::from(::lstat(p->c_str_null_safe(state), &st_));
}
Integer* Stat::stat_dev(STATE) {
return Integer::from(state, st_.st_dev);
}
Integer* Stat::stat_ino(STATE) {
return Integer::from(state, st_.st_ino);
}
Integer* Stat::stat_mode(STATE) {
return Integer::from(state, st_.st_mode);
}
Integer* Stat::stat_nlink(STATE) {
return Integer::from(state, st_.st_nlink);
}
Integer* Stat::stat_uid(STATE) {
return Integer::from(state, st_.st_uid);
}
Integer* Stat::stat_gid(STATE) {
return Integer::from(state, st_.st_gid);
}
Integer* Stat::stat_rdev(STATE) {
return Integer::from(state, st_.st_rdev);
}
Integer* Stat::stat_size(STATE) {
return Integer::from(state, st_.st_size);
}
Integer* Stat::stat_blksize(STATE) {
return Integer::from(state, st_.st_blksize);
}
Integer* Stat::stat_blocks(STATE) {
return Integer::from(state, st_.st_blocks);
}
Time* Stat::stat_atime(STATE) {
#ifdef HAVE_STRUCT_STAT_ST_ATIM
return Time::at(state, st_.st_atim.tv_sec, st_.st_atim.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_ATIMESPEC
return Time::at(state, st_.st_atimespec.tv_sec, st_.st_atimespec.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_ATIMENSEC
return Time::at(state, st_.st_atime, static_cast<long>(st_.st_atimensec));
#else
return Time::at(state, st_.st_atime);
#endif
}
Time* Stat::stat_mtime(STATE) {
#ifdef HAVE_STRUCT_STAT_ST_MTIM
return Time::at(state, st_.st_mtim.tv_sec, st_.st_mtim.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIMESPEC
return Time::at(state, st_.st_mtimespec.tv_sec, st_.st_mtimespec.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIMENSEC
return Time::at(state, st_.st_mtime, static_cast<long>(st_.st_mtimensec));
#else
return Time::at(state, st_.st_mtime);
#endif
}
Time* Stat::stat_ctime(STATE) {
#ifdef HAVE_STRUCT_STAT_ST_CTIM
return Time::at(state, st_.st_ctim.tv_sec, st_.st_ctim.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_CTIMESPEC
return Time::at(state, st_.st_ctimespec.tv_sec, st_.st_ctimespec.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_CTIMENSEC
return Time::at(state, st_.st_ctime, static_cast<long>(st_.st_ctimensec));
#else
return Time::at(state, st_.st_ctime);
#endif
}
Object* Stat::stat_birthtime(STATE) {
#ifdef HAVE_ST_BIRTHTIME
struct timespec ts = st_.st_birthtimespec;
return Time::at(state, ts.tv_sec, ts.tv_nsec);
#else
return Primitives::failure();
#endif
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <sstream>
#include "oaa.h"
#include "simple_label.h"
#include "cache.h"
#include "v_hashmap.h"
#include "vw.h"
using namespace std;
namespace OAA {
struct oaa{
uint32_t k;
uint32_t increment;
uint32_t total_increment;
learner base;
vw* all;
};
char* bufread_label(mc_label* ld, char* c)
{
ld->label = *(float *)c;
c += sizeof(ld->label);
ld->weight = *(float *)c;
c += sizeof(ld->weight);
return c;
}
size_t read_cached_label(shared_data*, void* v, io_buf& cache)
{
mc_label* ld = (mc_label*) v;
char *c;
size_t total = sizeof(ld->label)+sizeof(ld->weight);
if (buf_read(cache, c, total) < total)
return 0;
c = bufread_label(ld,c);
return total;
}
float weight(void* v)
{
mc_label* ld = (mc_label*) v;
return (ld->weight > 0) ? ld->weight : 0.f;
}
float initial(void* v)
{
return 0.;
}
char* bufcache_label(mc_label* ld, char* c)
{
*(float *)c = ld->label;
c += sizeof(ld->label);
*(float *)c = ld->weight;
c += sizeof(ld->weight);
return c;
}
void cache_label(void* v, io_buf& cache)
{
char *c;
mc_label* ld = (mc_label*) v;
buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight));
c = bufcache_label(ld,c);
}
void default_label(void* v)
{
mc_label* ld = (mc_label*) v;
ld->label = -1;
ld->weight = 1.;
}
void delete_label(void* v)
{
}
void parse_label(parser* p, shared_data*, void* v, v_array<substring>& words)
{
mc_label* ld = (mc_label*)v;
switch(words.size()) {
case 0:
break;
case 1:
ld->label = (float)int_of_substring(words[0]);
ld->weight = 1.0;
break;
case 2:
ld->label = (float)int_of_substring(words[0]);
ld->weight = float_of_substring(words[1]);
break;
default:
cerr << "malformed example!\n";
cerr << "words.size() = " << words.size() << endl;
}
}
void print_update(vw& all, example *ec)
{
if (all.sd->weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs)
{
mc_label* ld = (mc_label*) ec->ld;
char label_buf[32];
if (ld->label == INT_MAX)
strcpy(label_buf," unknown");
else
sprintf(label_buf,"%8ld",(long int)ld->label);
fprintf(stderr, "%-10.6f %-10.6f %8ld %8.1f %s %8ld %8lu\n",
all.sd->sum_loss/all.sd->weighted_examples,
all.sd->sum_loss_since_last_dump / (all.sd->weighted_examples - all.sd->old_weighted_examples),
(long int)all.sd->example_number,
all.sd->weighted_examples,
label_buf,
(long int)ec->final_prediction,
(long unsigned int)ec->num_features);
all.sd->sum_loss_since_last_dump = 0.0;
all.sd->old_weighted_examples = all.sd->weighted_examples;
all.sd->dump_interval *= 2;
}
}
void output_example(vw& all, example* ec)
{
if (command_example(&all,ec))
return;
mc_label* ld = (mc_label*)ec->ld;
all.sd->weighted_examples += ld->weight;
all.sd->total_features += ec->num_features;
size_t loss = 1;
if (ld->label == ec->final_prediction)
loss = 0;
all.sd->sum_loss += loss;
all.sd->sum_loss_since_last_dump += loss;
for (int* sink = all.final_prediction_sink.begin; sink != all.final_prediction_sink.end; sink++)
all.print(*sink, ec->final_prediction, 0, ec->tag);
all.sd->example_number++;
print_update(all, ec);
}
void learn_with_output(oaa* d, example* ec, bool shouldOutput)
{
vw* all = d->all;
if (command_example(all,ec))
{
d->base.learn(ec);
return;
}
mc_label* mc_label_data = (mc_label*)ec->ld;
float prediction = 1;
float score = INT_MIN;
if (mc_label_data->label == 0 || (mc_label_data->label > d->k && mc_label_data->label != (uint32_t)-1))
cout << "label " << mc_label_data->label << " is not in {1,"<< d->k << "} This won't work right." << endl;
string outputString;
stringstream outputStringStream(outputString);
for (size_t i = 1; i <= d->k; i++)
{
label_data simple_temp;
simple_temp.initial = 0.;
if (mc_label_data->label == i)
simple_temp.label = 1;
else
simple_temp.label = -1;
simple_temp.weight = mc_label_data->weight;
ec->ld = &simple_temp;
if (i != 1)
update_example_indicies(all->audit, ec, d->increment);
d->base.learn(ec);
if (ec->partial_prediction > score)
{
score = ec->partial_prediction;
prediction = (float)i;
}
if (shouldOutput) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec->partial_prediction;
}
ec->partial_prediction = 0.;
}
ec->ld = mc_label_data;
ec->final_prediction = prediction;
update_example_indicies(all->audit, ec, -d->total_increment);
if (shouldOutput)
all->print_text(all->raw_prediction, outputStringStream.str(), ec->tag);
}
void learn(void* d, example* ec) {
learn_with_output((oaa*)d, ec, false);
}
void drive(vw* all, void* d)
{
example* ec = NULL;
while ( true )
{
if ((ec = VW::get_example(all->p)) != NULL)//semiblocking operation.
{
learn_with_output((oaa*)d, ec, all->raw_prediction > 0);
if (!command_example(all, ec))
output_example(*all, ec);
VW::finish_example(*all, ec);
}
else if (parser_done(all->p))
return;
else
;
}
}
void finish(void* data)
{
oaa* o=(oaa*)data;
o->base.finish();
free(o);
}
learner setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)
{
oaa* data = (oaa*)calloc(1, sizeof(oaa));
//first parse for number of actions
if( vm_file.count("oaa") ) {
data->k = (uint32_t)vm_file["oaa"].as<size_t>();
if( vm.count("oaa") && (uint32_t)vm["oaa"].as<size_t>() != data->k )
std::cerr << "warning: you specified a different number of actions through --oaa than the one loaded from predictor. Pursuing with loaded value of: " << data->k << endl;
}
else {
data->k = (uint32_t)vm["oaa"].as<size_t>();
//append oaa with nb_actions to options_from_file so it is saved to regressor later
std::stringstream ss;
ss << " --oaa " << data->k;
all.options_from_file.append(ss.str());
}
data->all = &all;
*(all.p->lp) = mc_label_parser;
data->increment = all.reg.stride * all.weights_per_problem;
all.weights_per_problem *= data->k;
data->total_increment = data->increment*(data->k-1);
data->base = all.l;
learner l(data, drive, learn, finish, all.l.sl);
return l;
}
}
<commit_msg>make --oaa work<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <sstream>
#include "oaa.h"
#include "simple_label.h"
#include "cache.h"
#include "v_hashmap.h"
#include "vw.h"
using namespace std;
namespace OAA {
struct oaa{
uint32_t k;
uint32_t increment;
uint32_t total_increment;
learner base;
vw* all;
};
char* bufread_label(mc_label* ld, char* c)
{
ld->label = *(float *)c;
c += sizeof(ld->label);
ld->weight = *(float *)c;
c += sizeof(ld->weight);
return c;
}
size_t read_cached_label(shared_data*, void* v, io_buf& cache)
{
mc_label* ld = (mc_label*) v;
char *c;
size_t total = sizeof(ld->label)+sizeof(ld->weight);
if (buf_read(cache, c, total) < total)
return 0;
c = bufread_label(ld,c);
return total;
}
float weight(void* v)
{
mc_label* ld = (mc_label*) v;
return (ld->weight > 0) ? ld->weight : 0.f;
}
float initial(void* v)
{
return 0.;
}
char* bufcache_label(mc_label* ld, char* c)
{
*(float *)c = ld->label;
c += sizeof(ld->label);
*(float *)c = ld->weight;
c += sizeof(ld->weight);
return c;
}
void cache_label(void* v, io_buf& cache)
{
char *c;
mc_label* ld = (mc_label*) v;
buf_write(cache, c, sizeof(ld->label)+sizeof(ld->weight));
c = bufcache_label(ld,c);
}
void default_label(void* v)
{
mc_label* ld = (mc_label*) v;
ld->label = -1;
ld->weight = 1.;
}
void delete_label(void* v)
{
}
void parse_label(parser* p, shared_data*, void* v, v_array<substring>& words)
{
mc_label* ld = (mc_label*)v;
switch(words.size()) {
case 0:
break;
case 1:
ld->label = (float)int_of_substring(words[0]);
ld->weight = 1.0;
break;
case 2:
ld->label = (float)int_of_substring(words[0]);
ld->weight = float_of_substring(words[1]);
break;
default:
cerr << "malformed example!\n";
cerr << "words.size() = " << words.size() << endl;
}
}
void print_update(vw& all, example *ec)
{
if (all.sd->weighted_examples > all.sd->dump_interval && !all.quiet && !all.bfgs)
{
mc_label* ld = (mc_label*) ec->ld;
char label_buf[32];
if (ld->label == INT_MAX)
strcpy(label_buf," unknown");
else
sprintf(label_buf,"%8ld",(long int)ld->label);
if(!all.holdout_set_off && all.current_pass >= 1)
{
fprintf(stderr, "%-10.6f %-10.6f %8ld %8.1f %s %8ld %8lu h\n",
all.sd->holdout_sum_loss/all.sd->weighted_holdout_examples,
all.sd->holdout_sum_loss_since_last_dump / all.sd->weighted_holdout_examples_since_last_dump,
(long int)all.sd->example_number,
all.sd->weighted_examples,
label_buf,
(long int)ec->final_prediction,
(long unsigned int)ec->num_features);
all.sd->weighted_holdout_examples_since_last_dump = 0;
all.sd->holdout_sum_loss_since_last_dump = 0.0;
}
else
fprintf(stderr, "%-10.6f %-10.6f %8ld %8.1f %s %8ld %8lu\n",
all.sd->sum_loss/all.sd->weighted_examples,
all.sd->sum_loss_since_last_dump / (all.sd->weighted_examples - all.sd->old_weighted_examples),
(long int)all.sd->example_number,
all.sd->weighted_examples,
label_buf,
(long int)ec->final_prediction,
(long unsigned int)ec->num_features);
all.sd->sum_loss_since_last_dump = 0.0;
all.sd->old_weighted_examples = all.sd->weighted_examples;
all.sd->dump_interval *= 2;
}
}
void output_example(vw& all, example* ec)
{
if (command_example(&all,ec))
return;
mc_label* ld = (mc_label*)ec->ld;
size_t loss = 1;
if (ld->label == ec->final_prediction)
loss = 0;
if(ec->test_only)
{
all.sd->weighted_holdout_examples += ec->global_weight;//test weight seen
all.sd->weighted_holdout_examples_since_last_dump += ec->global_weight;
all.sd->weighted_holdout_examples_since_last_pass += ec->global_weight;
all.sd->holdout_sum_loss += loss;
all.sd->holdout_sum_loss_since_last_dump += loss;
all.sd->holdout_sum_loss_since_last_pass += loss;//since last pass
}
else
{
all.sd->weighted_examples += ld->weight;
all.sd->total_features += ec->num_features;
all.sd->sum_loss += loss;
all.sd->sum_loss_since_last_dump += loss;
all.sd->example_number++;
}
for (int* sink = all.final_prediction_sink.begin; sink != all.final_prediction_sink.end; sink++)
all.print(*sink, ec->final_prediction, 0, ec->tag);
print_update(all, ec);
}
void learn_with_output(oaa* d, example* ec, bool shouldOutput)
{
vw* all = d->all;
if (command_example(all,ec))
{
d->base.learn(ec);
return;
}
mc_label* mc_label_data = (mc_label*)ec->ld;
float prediction = 1;
float score = INT_MIN;
if (mc_label_data->label == 0 || (mc_label_data->label > d->k && mc_label_data->label != (uint32_t)-1))
cout << "label " << mc_label_data->label << " is not in {1,"<< d->k << "} This won't work right." << endl;
string outputString;
stringstream outputStringStream(outputString);
for (size_t i = 1; i <= d->k; i++)
{
label_data simple_temp;
simple_temp.initial = 0.;
if (mc_label_data->label == i)
simple_temp.label = 1;
else
simple_temp.label = -1;
simple_temp.weight = mc_label_data->weight;
ec->ld = &simple_temp;
if (i != 1)
update_example_indicies(all->audit, ec, d->increment);
d->base.learn(ec);
if (ec->partial_prediction > score)
{
score = ec->partial_prediction;
prediction = (float)i;
}
if (shouldOutput) {
if (i > 1) outputStringStream << ' ';
outputStringStream << i << ':' << ec->partial_prediction;
}
ec->partial_prediction = 0.;
}
ec->ld = mc_label_data;
ec->final_prediction = prediction;
update_example_indicies(all->audit, ec, -d->total_increment);
if (shouldOutput)
all->print_text(all->raw_prediction, outputStringStream.str(), ec->tag);
}
void learn(void* d, example* ec) {
learn_with_output((oaa*)d, ec, false);
}
void drive(vw* all, void* d)
{
example* ec = NULL;
while ( true )
{
if(all-> early_terminate)
{
all->p->done = true;
all->final_regressor_name = "";//skip finalize_regressor
all->text_regressor_name = "";
all->inv_hash_regressor_name = "";
return;
}
if ((ec = VW::get_example(all->p)) != NULL)//semiblocking operation.
{
learn_with_output((oaa*)d, ec, all->raw_prediction > 0);
if (!command_example(all, ec))
output_example(*all, ec);
VW::finish_example(*all, ec);
}
else if (parser_done(all->p))
return;
else
;
}
}
void finish(void* data)
{
oaa* o=(oaa*)data;
o->base.finish();
free(o);
}
learner setup(vw& all, std::vector<std::string>&opts, po::variables_map& vm, po::variables_map& vm_file)
{
oaa* data = (oaa*)calloc(1, sizeof(oaa));
//first parse for number of actions
if( vm_file.count("oaa") ) {
data->k = (uint32_t)vm_file["oaa"].as<size_t>();
if( vm.count("oaa") && (uint32_t)vm["oaa"].as<size_t>() != data->k )
std::cerr << "warning: you specified a different number of actions through --oaa than the one loaded from predictor. Pursuing with loaded value of: " << data->k << endl;
}
else {
data->k = (uint32_t)vm["oaa"].as<size_t>();
//append oaa with nb_actions to options_from_file so it is saved to regressor later
std::stringstream ss;
ss << " --oaa " << data->k;
all.options_from_file.append(ss.str());
}
data->all = &all;
*(all.p->lp) = mc_label_parser;
data->increment = all.reg.stride * all.weights_per_problem;
all.weights_per_problem *= data->k;
data->total_increment = data->increment*(data->k-1);
data->base = all.l;
learner l(data, drive, learn, finish, all.l.sl);
return l;
}
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
int main(int argc, char *argv[])
{
// Global menubar is broken for qt5 apps in Ubuntu Unity, see:
// https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
// This workaround enables a local menubar.
qputenv("UBUNTU_MENUPROXY","0");
// Don't write .pyc files.
qputenv("PYTHONDONTWRITEBYTECODE", "1");
QApplication app(argc, argv);
QString app_dir = app.applicationDirPath();
QString main_qml = "/qml/main.qml";
QString path_prefix;
QString url_prefix;
app.setApplicationName("YubiKey Manager");
app.setApplicationVersion(APP_VERSION);
app.setOrganizationName("Yubico");
app.setOrganizationDomain("com.yubico");
// A lock file is used, to ensure only one running instance at the time.
QString tmpDir = QDir::tempPath();
QLockFile lockFile(tmpDir + "/ykman-gui.lock");
if(!lockFile.tryLock(100)) {
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("YubiKey Manager is already running.");
msgBox.exec();
return 1;
}
if (QFileInfo::exists(":" + main_qml)) {
// Embedded resources
path_prefix = ":";
url_prefix = "qrc://";
} else if (QFileInfo::exists(app_dir + main_qml)) {
// Try relative to executable
path_prefix = app_dir;
url_prefix = app_dir;
} else { //Assume qml/main.qml in cwd.
app_dir = ".";
path_prefix = ".";
url_prefix = ".";
}
app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("appDir", app_dir);
engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
engine.rootContext()->setContextProperty("appVersion", APP_VERSION);
engine.load(QUrl(url_prefix + main_qml));
QCommandLineParser parser;
parser.setApplicationDescription("Cross-platform application for YubiKey configuration");
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({
{"log-level", QCoreApplication::translate("main", "Set log level to <LEVEL>"), QCoreApplication::translate("main", "LEVEL")},
{"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")},
});
parser.process(app);
if (parser.isSet("log-level")) {
if (parser.isSet("log-file")) {
QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, parser.value("log-level")), Q_ARG(QVariant, parser.value("log-file")));
} else {
QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, parser.value("log-level")));
}
} else {
QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging");
}
return app.exec();
}
<commit_msg>Run CLI parser before starting GUI<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
int main(int argc, char *argv[])
{
// Global menubar is broken for qt5 apps in Ubuntu Unity, see:
// https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
// This workaround enables a local menubar.
qputenv("UBUNTU_MENUPROXY","0");
// Don't write .pyc files.
qputenv("PYTHONDONTWRITEBYTECODE", "1");
QApplication app(argc, argv);
QString app_dir = app.applicationDirPath();
QString main_qml = "/qml/main.qml";
QString path_prefix;
QString url_prefix;
app.setApplicationName("YubiKey Manager");
app.setApplicationVersion(APP_VERSION);
app.setOrganizationName("Yubico");
app.setOrganizationDomain("com.yubico");
QCommandLineParser parser;
parser.setApplicationDescription("Cross-platform application for YubiKey configuration");
parser.addHelpOption();
parser.addVersionOption();
parser.addOptions({
{"log-level", QCoreApplication::translate("main", "Set log level to <LEVEL>"), QCoreApplication::translate("main", "LEVEL")},
{"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")},
});
parser.process(app);
// A lock file is used, to ensure only one running instance at the time.
QString tmpDir = QDir::tempPath();
QLockFile lockFile(tmpDir + "/ykman-gui.lock");
if(!lockFile.tryLock(100)) {
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("YubiKey Manager is already running.");
msgBox.exec();
return 1;
}
if (QFileInfo::exists(":" + main_qml)) {
// Embedded resources
path_prefix = ":";
url_prefix = "qrc://";
} else if (QFileInfo::exists(app_dir + main_qml)) {
// Try relative to executable
path_prefix = app_dir;
url_prefix = app_dir;
} else { //Assume qml/main.qml in cwd.
app_dir = ".";
path_prefix = ".";
url_prefix = ".";
}
app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("appDir", app_dir);
engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
engine.rootContext()->setContextProperty("appVersion", APP_VERSION);
engine.load(QUrl(url_prefix + main_qml));
if (parser.isSet("log-level")) {
if (parser.isSet("log-file")) {
QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, parser.value("log-level")), Q_ARG(QVariant, parser.value("log-file")));
} else {
QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, parser.value("log-level")));
}
} else {
QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging");
}
return app.exec();
}
<|endoftext|> |
<commit_before>// Copyright (C) 2019, Antonio Coratelli
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include <bkm/MainWindow.h>
#include <bkm/MenuItemFileOpen.h>
#include <bkm/MenuItemFolderContent.h>
#include <bkm/MenuItemGithub.h>
#include <bkm/MenuItemLabel.h>
#include <bkm/MenuItemQuit.h>
#include <bkm/OpenServiceProvider.h>
#include <CLI11.hpp>
#include <gtkmm/application.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
Glib::RefPtr<Gtk::Application> gApp;
static void quit_on_signal(int s) {
std::cout << __func__ << " " << s << std::endl;
gApp->quit();
}
int main(int argc, char const* const* argv) try {
CLI::App app{"bookmarks-indicator\n\nA handy tool to quickly open the files you use regularly.\n\n"};
auto app_config = std::string{"$HOME/.bookmarks-indicator.cfg"};
auto app_opener_file = std::string{"xdg-open"};
auto app_opener_folder_in_explorer = std::string{"xdg-open"};
auto app_opener_folder_in_terminal = std::string{"gnome-terminal"};
auto app_icon = std::string{"bookmark-new"};
app.add_option("-c", app_config,
"Configuration file path, default: '" + app_config + "'");
app.add_option("-o", app_opener_file,
"Command to open regular files, default: '" + app_opener_file + "'");
app.add_option("-f", app_opener_folder_in_explorer,
"Command to open folders in explorer, default: '" + app_opener_folder_in_explorer + "'");
app.add_option("-t", app_opener_folder_in_terminal,
"Command to open folders in terminal, default: '" + app_opener_folder_in_terminal + "'");
app.add_option("-i", app_icon,
"Icon of the indicator, can be a path or a gtk icon identifier, default: '" + app_icon + "'");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError &e) {
return app.exit(e);
}
std::vector<std::string> config_lines;
std::ifstream ifs{bkm::expand_env(app_config)};
for (std::string line; bool{ifs}; std::getline(ifs, line)) {
line = bkm::trim_spaces(line);
line = bkm::expand_env(line);
config_lines.push_back(line);
}
auto osp = std::make_shared<bkm::OpenServiceProvider>(
app_opener_file,
app_opener_folder_in_explorer,
app_opener_folder_in_terminal);
gApp = Gtk::Application::create("com.coratelli.antonio.bookmarks-indicator");
::signal(SIGINT, quit_on_signal);
::signal(SIGTERM, quit_on_signal);
bkm::MainWindow main_window(app_icon);
for (auto const& line : config_lines) {
if (line == "---") {
main_window.append(new Gtk::SeparatorMenuItem());
} else if (line.substr(0, 3) == "---") {
auto label = bkm::trim_spaces(line.substr(3));
main_window.append(new Gtk::SeparatorMenuItem());
main_window.append(new bkm::MenuItemLabel(label));
} else if (bkm::is_regular_file(line.c_str())) {
main_window.append(new bkm::MenuItemFileOpen(osp, line));
} else if (bkm::is_directory(line.c_str())) {
main_window.append(new bkm::MenuItemFolderContent(osp, line));
}
}
main_window.append(new Gtk::SeparatorMenuItem());
main_window.append(new bkm::MenuItemGitHub(osp));
main_window.append(new bkm::MenuItemQuit());
return gApp->run(main_window);
} catch(...) {
return -1;
}
<commit_msg>Add debug messages<commit_after>// Copyright (C) 2019, Antonio Coratelli
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include <bkm/MainWindow.h>
#include <bkm/MenuItemFileOpen.h>
#include <bkm/MenuItemFolderContent.h>
#include <bkm/MenuItemGithub.h>
#include <bkm/MenuItemLabel.h>
#include <bkm/MenuItemQuit.h>
#include <bkm/OpenServiceProvider.h>
#include <CLI11.hpp>
#include <gtkmm/application.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
Glib::RefPtr<Gtk::Application> gApp;
static void quit_on_signal(int s) {
std::cout << __func__ << " " << s << std::endl;
gApp->quit();
}
int main(int argc, char const* const* argv) try {
CLI::App app{"bookmarks-indicator\n\nA handy tool to quickly open the files you use regularly.\n\n"};
auto app_config = std::string{"$HOME/.bookmarks-indicator.cfg"};
auto app_opener_file = std::string{"xdg-open"};
auto app_opener_folder_in_explorer = std::string{"xdg-open"};
auto app_opener_folder_in_terminal = std::string{"gnome-terminal"};
auto app_icon = std::string{"bookmark-new"};
app.add_option("-c", app_config,
"Configuration file path, default: '" + app_config + "'");
app.add_option("-o", app_opener_file,
"Command to open regular files, default: '" + app_opener_file + "'");
app.add_option("-f", app_opener_folder_in_explorer,
"Command to open folders in explorer, default: '" + app_opener_folder_in_explorer + "'");
app.add_option("-t", app_opener_folder_in_terminal,
"Command to open folders in terminal, default: '" + app_opener_folder_in_terminal + "'");
app.add_option("-i", app_icon,
"Icon of the indicator, can be a path or a gtk icon identifier, default: '" + app_icon + "'");
try {
app.parse(argc, argv);
} catch (const CLI::ParseError &e) {
return app.exit(e);
}
std::vector<std::string> config_lines;
std::ifstream ifs{bkm::expand_env(app_config)};
for (std::string line; bool{ifs}; std::getline(ifs, line)) {
line = bkm::trim_spaces(line);
line = bkm::expand_env(line);
config_lines.push_back(line);
}
auto osp = std::make_shared<bkm::OpenServiceProvider>(
app_opener_file,
app_opener_folder_in_explorer,
app_opener_folder_in_terminal);
gApp = Gtk::Application::create("com.coratelli.antonio.bookmarks-indicator");
::signal(SIGINT, quit_on_signal);
::signal(SIGTERM, quit_on_signal);
bkm::MainWindow main_window(app_icon);
for (auto const& line : config_lines) {
if (line == "---") {
std::cout << ">>> Add bkm::SeparatorMenuItem" << std::endl;
main_window.append(new Gtk::SeparatorMenuItem());
} else if (line.substr(0, 3) == "---") {
auto label = bkm::trim_spaces(line.substr(3));
std::cout << ">>> Add bkm::SeparatorMenuItem" << std::endl;
main_window.append(new Gtk::SeparatorMenuItem());
std::cout << ">>> Add bkm::MenuItemLabel(" << label << ")" << std::endl;
main_window.append(new bkm::MenuItemLabel(label));
} else if (bkm::is_regular_file(line.c_str())) {
std::cout << ">>> Add bkm::MenuItemFileOpen(" << line << ")" << std::endl;
main_window.append(new bkm::MenuItemFileOpen(osp, line));
} else if (bkm::is_directory(line.c_str())) {
std::cout << ">>> Add bkm::MenuItemFolderContent(" << line << ")" << std::endl;
main_window.append(new bkm::MenuItemFolderContent(osp, line));
}
}
std::cout << ">>> Add bkm::SeparatorMenuItem" << std::endl;
main_window.append(new Gtk::SeparatorMenuItem());
std::cout << ">>> Add bkm::MenuItemGitHub" << std::endl;
main_window.append(new bkm::MenuItemGitHub(osp));
std::cout << ">>> Add bkm::MenuItemQuit" << std::endl;
main_window.append(new bkm::MenuItemQuit());
std::cout << "Ready!" << std::endl;
return gApp->run(main_window);
} catch(...) {
return -1;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <bitset>
#include "base/crc.h"
#include "bsp/bsp_uart.h"
#include "main.hpp"
#include "program_flash/boot_table.hpp"
static void CheckBootSettings()
{
auto settingsValid = Bootloader.Settings.CheckMagicNumber();
if (settingsValid)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Boot settings tagged with magic number\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Boot settings tagged with magic number\n");
}
auto primaryBootSlots = Bootloader.Settings.BootSlots();
if (primaryBootSlots == 0b111)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Primary boot slots set to 0,1,2\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Primary boot slots set to 0,1,2 (actual: 0x%X)\n", primaryBootSlots);
}
auto failsafeBootSlots = Bootloader.Settings.FailsafeBootSlots();
if (failsafeBootSlots == 0b111000)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Failsafe boot slots set to 3,4,5\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Failsafe boot slots set to 3,4,5 (actual: 0x%X)\n", failsafeBootSlots);
}
auto bootCounter = Bootloader.Settings.BootCounter();
if (bootCounter == 0)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Boot counter set to 0\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Boot counter set to 0 (actual: %ld)\n", bootCounter);
}
auto lastConfirmedBootCounter = Bootloader.Settings.LastConfirmedBootCounter();
if (lastConfirmedBootCounter == 0)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Last confirmed boot counter set to 0\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Last confirmed boot counter set to 0 (actual: %ld)\n", lastConfirmedBootCounter);
}
}
static std::array<uint8_t, 3> DecodeSlotsMask(std::uint8_t mask)
{
std::array<uint8_t, 3> result{0, 0, 0};
std::bitset<program_flash::BootTable::EntriesCount> slots(mask);
auto j = 0;
for (std::uint8_t i = 0; i < program_flash::BootTable::EntriesCount; i++)
{
if (slots[i])
{
result[j] = i;
j++;
}
if (j == 3)
break;
}
return result;
}
static void CheckBootSlots()
{
std::array<bool, 6> slotValid;
std::array<std::uint16_t, 6> crc;
for (auto i = 0; i < program_flash::BootTable::EntriesCount; i++)
{
slotValid[i] = false;
auto entry = Bootloader.BootTable.Entry(i);
if (!entry.IsValid())
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Boot slot %d: Not valid\n", i);
continue;
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[OK ] Boot slot %d: Valid\n", i);
}
auto expectedCrc = entry.Crc();
auto actualCrc = entry.CalculateCrc();
if (expectedCrc != actualCrc)
{
BSP_UART_Printf<40>(
BSP_UART_DEBUG, "[FAIL] Boot slot %d: CRC mismatch (expected: 0x%X, actual: 0x%X)\n", i, expectedCrc, actualCrc);
continue;
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[OK ] Boot slot %d: CRC match (0x%X)\n", i, expectedCrc);
}
crc[i] = actualCrc;
slotValid[i] = true;
}
auto slots = DecodeSlotsMask(Bootloader.Settings.BootSlots());
auto allValid = slotValid[slots[0]] && slotValid[slots[1]] && slotValid[slots[2]];
auto crcMatch = (crc[slots[0]] == crc[slots[1]]) && (crc[slots[1]] == crc[slots[2]]);
if (allValid && crcMatch)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Primary boot slots valid & CRC match\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Primary boot slots valid & CRC match\n");
}
slots = DecodeSlotsMask(Bootloader.Settings.FailsafeBootSlots());
allValid = slotValid[slots[0]] && slotValid[slots[1]] && slotValid[slots[2]];
crcMatch = (crc[slots[0]] == crc[slots[1]]) && (crc[slots[1]] == crc[slots[2]]);
if (allValid && crcMatch)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Failsafe boot slots valid & CRC match\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Failsafe boot slots valid & CRC match\n");
}
}
static void CheckBootloader()
{
std::array<std::uint16_t, program_flash::BootTable::BootloaderCopies> crc;
for (auto i = 0; i < program_flash::BootTable::BootloaderCopies; i++)
{
auto copy = Bootloader.BootTable.GetBootloaderCopy(i);
crc[i] = copy.CalculateCrc();
}
auto r = std::minmax_element(crc.begin(), crc.end());
if (*r.first == *r.second)
{
BSP_UART_Printf<50>(BSP_UART_DEBUG, "[OK ] Bootloader copies all the same (0x%X)\n", *r.first);
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Bootloader copies not the same (CRCs:");
for (auto i = 0U; i < crc.size(); i++)
{
BSP_UART_Printf<10>(BSP_UART_DEBUG, " 0x%X", crc[i]);
}
BSP_UART_Puts(BSP_UART_DEBUG, ")\n");
}
auto mcuCrc = CRC_calc(reinterpret_cast<std::uint8_t*>(0), reinterpret_cast<std::uint8_t*>(program_flash::BootloaderCopy::Size));
if (mcuCrc == *r.first)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Bootloader in MCU matches copies\n");
}
else
{
BSP_UART_Printf<80>(BSP_UART_DEBUG, "[FAIL] Bootloader in MCU does not match copies (MCU: 0x%X Copy: 0x%X)\n", mcuCrc, *r.first);
}
}
void Check()
{
BSP_UART_Puts(BSP_UART_DEBUG, "\nChecking OBC:\n");
CheckBootSettings();
CheckBootSlots();
CheckBootloader();
}
<commit_msg>[boot] Fix boot loader hang in health check on boot slot CRC mismatch.<commit_after>#include <algorithm>
#include <bitset>
#include "base/crc.h"
#include "bsp/bsp_uart.h"
#include "main.hpp"
#include "program_flash/boot_table.hpp"
static void CheckBootSettings()
{
auto settingsValid = Bootloader.Settings.CheckMagicNumber();
if (settingsValid)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Boot settings tagged with magic number\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Boot settings tagged with magic number\n");
}
auto primaryBootSlots = Bootloader.Settings.BootSlots();
if (primaryBootSlots == 0b111)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Primary boot slots set to 0,1,2\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Primary boot slots set to 0,1,2 (actual: 0x%X)\n", primaryBootSlots);
}
auto failsafeBootSlots = Bootloader.Settings.FailsafeBootSlots();
if (failsafeBootSlots == 0b111000)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Failsafe boot slots set to 3,4,5\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Failsafe boot slots set to 3,4,5 (actual: 0x%X)\n", failsafeBootSlots);
}
auto bootCounter = Bootloader.Settings.BootCounter();
if (bootCounter == 0)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Boot counter set to 0\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Boot counter set to 0 (actual: %ld)\n", bootCounter);
}
auto lastConfirmedBootCounter = Bootloader.Settings.LastConfirmedBootCounter();
if (lastConfirmedBootCounter == 0)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Last confirmed boot counter set to 0\n");
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Last confirmed boot counter set to 0 (actual: %ld)\n", lastConfirmedBootCounter);
}
}
static std::array<uint8_t, 3> DecodeSlotsMask(std::uint8_t mask)
{
std::array<uint8_t, 3> result{0, 0, 0};
std::bitset<program_flash::BootTable::EntriesCount> slots(mask);
auto j = 0;
for (std::uint8_t i = 0; i < program_flash::BootTable::EntriesCount; i++)
{
if (slots[i])
{
result[j] = i;
j++;
}
if (j == 3)
break;
}
return result;
}
static void CheckBootSlots()
{
std::array<bool, 6> slotValid;
std::array<std::uint16_t, 6> crc;
for (auto i = 0; i < program_flash::BootTable::EntriesCount; i++)
{
slotValid[i] = false;
auto entry = Bootloader.BootTable.Entry(i);
if (!entry.IsValid())
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[FAIL] Boot slot %d: Not valid\n", i);
continue;
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[OK ] Boot slot %d: Valid\n", i);
}
auto expectedCrc = entry.Crc();
auto actualCrc = entry.CalculateCrc();
if (expectedCrc != actualCrc)
{
BSP_UART_Printf<80>(
BSP_UART_DEBUG, "[FAIL] Boot slot %d: CRC mismatch (expected: 0x%X, actual: 0x%X)\n", i, expectedCrc, actualCrc);
continue;
}
else
{
BSP_UART_Printf<40>(BSP_UART_DEBUG, "[OK ] Boot slot %d: CRC match (0x%X)\n", i, expectedCrc);
}
crc[i] = actualCrc;
slotValid[i] = true;
}
auto slots = DecodeSlotsMask(Bootloader.Settings.BootSlots());
auto allValid = slotValid[slots[0]] && slotValid[slots[1]] && slotValid[slots[2]];
auto crcMatch = (crc[slots[0]] == crc[slots[1]]) && (crc[slots[1]] == crc[slots[2]]);
if (allValid && crcMatch)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Primary boot slots valid & CRC match\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Primary boot slots valid & CRC match\n");
}
slots = DecodeSlotsMask(Bootloader.Settings.FailsafeBootSlots());
allValid = slotValid[slots[0]] && slotValid[slots[1]] && slotValid[slots[2]];
crcMatch = (crc[slots[0]] == crc[slots[1]]) && (crc[slots[1]] == crc[slots[2]]);
if (allValid && crcMatch)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Failsafe boot slots valid & CRC match\n");
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Failsafe boot slots valid & CRC match\n");
}
}
static void CheckBootloader()
{
std::array<std::uint16_t, program_flash::BootTable::BootloaderCopies> crc;
for (auto i = 0; i < program_flash::BootTable::BootloaderCopies; i++)
{
auto copy = Bootloader.BootTable.GetBootloaderCopy(i);
crc[i] = copy.CalculateCrc();
}
auto r = std::minmax_element(crc.begin(), crc.end());
if (*r.first == *r.second)
{
BSP_UART_Printf<50>(BSP_UART_DEBUG, "[OK ] Bootloader copies all the same (0x%X)\n", *r.first);
}
else
{
BSP_UART_Puts(BSP_UART_DEBUG, "[FAIL] Bootloader copies not the same (CRCs:");
for (auto i = 0U; i < crc.size(); i++)
{
BSP_UART_Printf<10>(BSP_UART_DEBUG, " 0x%X", crc[i]);
}
BSP_UART_Puts(BSP_UART_DEBUG, ")\n");
}
auto mcuCrc = CRC_calc(reinterpret_cast<std::uint8_t*>(0), reinterpret_cast<std::uint8_t*>(program_flash::BootloaderCopy::Size));
if (mcuCrc == *r.first)
{
BSP_UART_Puts(BSP_UART_DEBUG, "[OK ] Bootloader in MCU matches copies\n");
}
else
{
BSP_UART_Printf<80>(BSP_UART_DEBUG, "[FAIL] Bootloader in MCU does not match copies (MCU: 0x%X Copy: 0x%X)\n", mcuCrc, *r.first);
}
}
void Check()
{
BSP_UART_Puts(BSP_UART_DEBUG, "\nChecking OBC:\n");
CheckBootSettings();
CheckBootSlots();
CheckBootloader();
}
<|endoftext|> |
<commit_before>#include "MidasTreeView.h"
#include <QtGui>
#include <QItemSelection>
#include <QContextMenuEvent>
#include <QModelIndex>
#include "MIDASDesktopUI.h"
#include "MidasTreeItem.h"
#include "MidasTreeModel.h"
#include "MidasCommunityTreeItem.h"
#include "MidasCollectionTreeItem.h"
#include "MidasItemTreeItem.h"
#include "Logger.h"
#include "Utils.h"
#include "MidasClientGlobal.h"
#include "mwsWebAPI.h"
#include "mwsCommunity.h"
#include "mwsBitstream.h"
#include "mwsCollection.h"
#include "mwsItem.h"
#include "mdoObject.h"
#include "mdoCommunity.h"
#include "mdoCollection.h"
#include "mdoItem.h"
#include "mdoBitstream.h"
#include "midasUtils.h"
#include <iostream>
/** Constructor */
MidasTreeView::MidasTreeView(QWidget * parent):QTreeView(parent)
{
// The tree model
m_Model = new MidasTreeModel;
this->setModel(m_Model);
m_WebAPI = NULL;
this->setSelectionMode( QTreeView::SingleSelection );
connect (this, SIGNAL( collapsed(const QModelIndex&)),
this->model(), SLOT(itemCollapsed(const QModelIndex&)) );
connect (this, SIGNAL( expanded(const QModelIndex&)),
this->model(), SLOT(itemExpanded (const QModelIndex&)) );
connect (this->model(), SIGNAL( fetchedMore() ),
this, SLOT( alertFetchedMore() ) );
// define action to be triggered when tree item is selected
QItemSelectionModel * itemSelectionModel = this->selectionModel();
connect(itemSelectionModel,
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this, SLOT(updateSelection(const QItemSelection&, const QItemSelection& )));
}
/** Destructor */
MidasTreeView::~MidasTreeView()
{
delete m_Model;
}
/** Set the web API */
void MidasTreeView::SetWebAPI(mws::WebAPI* api)
{
m_Model->SetWebAPI(api);
m_WebAPI = api;
}
/** Initialize the tree */
bool MidasTreeView::Initialize()
{
if(!m_WebAPI)
{
std::cerr << "WebAPI not set" << std::endl;
return false;
}
m_Model->Populate();
return true;
}
void MidasTreeView::Update()
{
this->Clear();
this->Initialize();
}
/** Clear */
void MidasTreeView::Clear()
{
this->m_Model->clear(QModelIndex());
disconnect(this);
this->reset();
}
bool MidasTreeView::isModelIndexSelected() const
{
QItemSelectionModel * selectionModel = this->selectionModel();
assert(selectionModel != NULL);
return (selectionModel->selectedIndexes().size() > 0);
}
const QModelIndex MidasTreeView::getSelectedModelIndex() const
{
QItemSelectionModel * selectionModel = this->selectionModel();
assert(selectionModel != NULL);
QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
assert(selectedIndexes.size() == 1);
return selectedIndexes.first();
}
const MidasTreeItem * MidasTreeView::getSelectedMidasTreeItem() const
{
return reinterpret_cast<MidasTreeModel*>(
this->model())->midasTreeItem(this->getSelectedModelIndex());
}
void MidasTreeView::updateSelection(const QItemSelection &selected,
const QItemSelection &deselected)
{
assert(this->selectionMode() == QTreeView::SingleSelection);
QModelIndex index;
QModelIndexList items = selected.indexes();
if (items.size() > 0)
{
MidasTreeItem * item = const_cast<MidasTreeItem*>( m_Model->midasTreeItem(items.first()) );
emit midasTreeItemSelected(item);
MidasCommunityTreeItem * communityTreeItem = NULL;
MidasCollectionTreeItem * collectionTreeItem = NULL;
MidasItemTreeItem * itemTreeItem = NULL;
if ((communityTreeItem = dynamic_cast<MidasCommunityTreeItem*>(item)) != NULL)
{
emit midasCommunityTreeItemSelected(communityTreeItem);
}
else if ((collectionTreeItem = dynamic_cast<MidasCollectionTreeItem*>(item)) != NULL)
{
emit midasCollectionTreeItemSelected(collectionTreeItem);
}
else if ((itemTreeItem = dynamic_cast<MidasItemTreeItem*>(item)) != NULL)
{
emit midasItemTreeItemSelected(itemTreeItem);
}
}
else
{
emit midasNoTreeItemSelected();
}
}
void MidasTreeView::contextMenuEvent(QContextMenuEvent* e)
{
emit midasTreeViewContextMenu(e);
}
void MidasTreeView::decorateByUuid(std::string uuid)
{
this->m_Model->decorateByUuid(uuid);
}
void MidasTreeView::alertFetchedMore()
{
emit fetchedMore();
}
void MidasTreeView::selectByObject(mdo::Object* object)
{
std::vector<std::string> path; //path of uuids to the root
mdo::Community* comm = NULL;
mdo::Collection* coll = NULL;
mdo::Item* item = NULL;
mdo::Bitstream* bitstream = NULL;
while(true)
{
if((comm = dynamic_cast<mdo::Community*>(object)) != NULL)
{
mws::Community remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(comm);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = comm->GetParentCommunity();
path.push_back(comm->GetUuid());
}
else if((coll = dynamic_cast<mdo::Collection*>(object)) != NULL)
{
mws::Collection remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(coll);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = coll->GetParentCommunity();
path.push_back(coll->GetUuid());
}
else if((item = dynamic_cast<mdo::Item*>(object)) != NULL)
{
mws::Item remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(item);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = item->GetParentCollection();
path.push_back(item->GetUuid());
}
else if((bitstream = dynamic_cast<mdo::Bitstream*>(object)) != NULL)
{
mws::Bitstream remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(bitstream);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = bitstream->GetParentItem();
path.push_back(bitstream->GetUuid());
}
if(object == NULL)
{
break;
}
}
for(std::vector<std::string>::reverse_iterator i = path.rbegin();
i != path.rend(); ++i) //TODO rend +/- 1?
{
expand(m_Model->getIndexByUuid(*i));
}
selectionModel()->select(m_Model->getIndexByUuid(*(path.begin())),
QItemSelectionModel::Select | QItemSelectionModel::Clear);
}
<commit_msg>ENH: Selection by uuid is currently broken in the tree view-- turn it off for now<commit_after>#include "MidasTreeView.h"
#include <QtGui>
#include <QItemSelection>
#include <QContextMenuEvent>
#include <QModelIndex>
#include "MIDASDesktopUI.h"
#include "MidasTreeItem.h"
#include "MidasTreeModel.h"
#include "MidasCommunityTreeItem.h"
#include "MidasCollectionTreeItem.h"
#include "MidasItemTreeItem.h"
#include "Logger.h"
#include "Utils.h"
#include "MidasClientGlobal.h"
#include "mwsWebAPI.h"
#include "mwsCommunity.h"
#include "mwsBitstream.h"
#include "mwsCollection.h"
#include "mwsItem.h"
#include "mdoObject.h"
#include "mdoCommunity.h"
#include "mdoCollection.h"
#include "mdoItem.h"
#include "mdoBitstream.h"
#include "midasUtils.h"
#include <iostream>
/** Constructor */
MidasTreeView::MidasTreeView(QWidget * parent):QTreeView(parent)
{
// The tree model
m_Model = new MidasTreeModel;
this->setModel(m_Model);
m_WebAPI = NULL;
this->setSelectionMode( QTreeView::SingleSelection );
connect (this, SIGNAL( collapsed(const QModelIndex&)),
this->model(), SLOT(itemCollapsed(const QModelIndex&)) );
connect (this, SIGNAL( expanded(const QModelIndex&)),
this->model(), SLOT(itemExpanded (const QModelIndex&)) );
connect (this->model(), SIGNAL( fetchedMore() ),
this, SLOT( alertFetchedMore() ) );
// define action to be triggered when tree item is selected
QItemSelectionModel * itemSelectionModel = this->selectionModel();
connect(itemSelectionModel,
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this, SLOT(updateSelection(const QItemSelection&, const QItemSelection& )));
}
/** Destructor */
MidasTreeView::~MidasTreeView()
{
delete m_Model;
}
/** Set the web API */
void MidasTreeView::SetWebAPI(mws::WebAPI* api)
{
m_Model->SetWebAPI(api);
m_WebAPI = api;
}
/** Initialize the tree */
bool MidasTreeView::Initialize()
{
if(!m_WebAPI)
{
std::cerr << "WebAPI not set" << std::endl;
return false;
}
m_Model->Populate();
return true;
}
void MidasTreeView::Update()
{
this->Clear();
this->Initialize();
}
/** Clear */
void MidasTreeView::Clear()
{
this->m_Model->clear(QModelIndex());
disconnect(this);
this->reset();
}
bool MidasTreeView::isModelIndexSelected() const
{
QItemSelectionModel * selectionModel = this->selectionModel();
assert(selectionModel != NULL);
return (selectionModel->selectedIndexes().size() > 0);
}
const QModelIndex MidasTreeView::getSelectedModelIndex() const
{
QItemSelectionModel * selectionModel = this->selectionModel();
assert(selectionModel != NULL);
QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
assert(selectedIndexes.size() == 1);
return selectedIndexes.first();
}
const MidasTreeItem * MidasTreeView::getSelectedMidasTreeItem() const
{
return reinterpret_cast<MidasTreeModel*>(
this->model())->midasTreeItem(this->getSelectedModelIndex());
}
void MidasTreeView::updateSelection(const QItemSelection &selected,
const QItemSelection &deselected)
{
assert(this->selectionMode() == QTreeView::SingleSelection);
QModelIndex index;
QModelIndexList items = selected.indexes();
if (items.size() > 0)
{
MidasTreeItem * item = const_cast<MidasTreeItem*>( m_Model->midasTreeItem(items.first()) );
emit midasTreeItemSelected(item);
MidasCommunityTreeItem * communityTreeItem = NULL;
MidasCollectionTreeItem * collectionTreeItem = NULL;
MidasItemTreeItem * itemTreeItem = NULL;
if ((communityTreeItem = dynamic_cast<MidasCommunityTreeItem*>(item)) != NULL)
{
emit midasCommunityTreeItemSelected(communityTreeItem);
}
else if ((collectionTreeItem = dynamic_cast<MidasCollectionTreeItem*>(item)) != NULL)
{
emit midasCollectionTreeItemSelected(collectionTreeItem);
}
else if ((itemTreeItem = dynamic_cast<MidasItemTreeItem*>(item)) != NULL)
{
emit midasItemTreeItemSelected(itemTreeItem);
}
}
else
{
emit midasNoTreeItemSelected();
}
}
void MidasTreeView::contextMenuEvent(QContextMenuEvent* e)
{
emit midasTreeViewContextMenu(e);
}
void MidasTreeView::decorateByUuid(std::string uuid)
{
this->m_Model->decorateByUuid(uuid);
}
void MidasTreeView::alertFetchedMore()
{
emit fetchedMore();
}
void MidasTreeView::selectByObject(mdo::Object* object)
{
std::vector<std::string> path; //path of uuids to the root
mdo::Community* comm = NULL;
mdo::Collection* coll = NULL;
mdo::Item* item = NULL;
mdo::Bitstream* bitstream = NULL;
while(true)
{
if((comm = dynamic_cast<mdo::Community*>(object)) != NULL)
{
mws::Community remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(comm);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = comm->GetParentCommunity();
path.push_back(comm->GetUuid());
}
else if((coll = dynamic_cast<mdo::Collection*>(object)) != NULL)
{
mws::Collection remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(coll);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = coll->GetParentCommunity();
path.push_back(coll->GetUuid());
}
else if((item = dynamic_cast<mdo::Item*>(object)) != NULL)
{
mws::Item remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(item);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = item->GetParentCollection();
path.push_back(item->GetUuid());
}
else if((bitstream = dynamic_cast<mdo::Bitstream*>(object)) != NULL)
{
mws::Bitstream remote;
remote.SetWebAPI(mws::WebAPI::Instance());
remote.SetObject(bitstream);
if(path.size() == 0)
{
remote.Fetch();
}
remote.FetchParent();
object = bitstream->GetParentItem();
path.push_back(bitstream->GetUuid());
}
if(object == NULL)
{
break;
}
}
for(std::vector<std::string>::reverse_iterator i = path.rbegin();
i != path.rend(); ++i) //TODO rend +/- 1?
{
expand(m_Model->getIndexByUuid(*i));
}
/*QModelIndex index = m_Model->getIndexByUuid(*(path.begin()));
if(index.isValid())
{
selectionModel()->select(index,
QItemSelectionModel::Select | QItemSelectionModel::Clear);
}*/
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com>
Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "volumefadereffect.h"
#include "xineengine.h"
namespace Phonon
{
namespace Xine
{
enum ParameterIds {
VolumeParameter = 0,
FadeCurveParameter = 1,
FadeToParameter = 2,
FadeTimeParameter = 3,
StartFadeParameter = 4
};
VolumeFaderEffectXT::VolumeFaderEffectXT()
: EffectXT("KVolumeFader"),
m_parameters(Phonon::VolumeFaderEffect::Fade3Decibel, 1.0f, 1.0f, 0)
{
}
VolumeFaderEffect::VolumeFaderEffect(QObject *parent)
: Effect(new VolumeFaderEffectXT, parent)
{
const QVariant one = 1.0;
const QVariant dZero = 0.0;
const QVariant iZero = 0;
addParameter(EffectParameter(VolumeParameter, tr( "Volume" ), 0, one, dZero, one));
addParameter(EffectParameter(FadeCurveParameter, tr( "Fade Curve" ),
EffectParameter::IntegerHint, iZero, iZero, 3));
addParameter(EffectParameter(FadeToParameter, tr( "Fade To Volume" ), 0, one, dZero, one));
addParameter(EffectParameter(FadeTimeParameter, tr( "Fade Time" ),
EffectParameter::IntegerHint, iZero, iZero, 10000));
addParameter(EffectParameter(StartFadeParameter, tr( "Start Fade" ),
EffectParameter::ToggledHint, iZero, iZero, 1));
}
VolumeFaderEffect::~VolumeFaderEffect()
{
}
QVariant VolumeFaderEffect::parameterValue(const EffectParameter &p) const
{
K_XT(const VolumeFaderEffect);
const int parameterId = p.id();
qDebug() << parameterId;
switch (static_cast<ParameterIds>(parameterId)) {
case VolumeParameter:
return static_cast<double>(volume());
case FadeCurveParameter:
return static_cast<int>(fadeCurve());
case FadeToParameter:
return static_cast<double>(xt->m_parameters.fadeTo);
case FadeTimeParameter:
return xt->m_parameters.fadeTime;
case StartFadeParameter:
return 0;
}
return QVariant();
}
void VolumeFaderEffect::setParameterValue(const EffectParameter &p, const QVariant &newValue)
{
K_XT(VolumeFaderEffect);
const int parameterId = p.id();
qDebug() << parameterId << newValue;
switch (static_cast<ParameterIds>(parameterId)) {
case VolumeParameter:
setVolume(newValue.toDouble());
break;
case FadeCurveParameter:
setFadeCurve(static_cast<Phonon::VolumeFaderEffect::FadeCurve>(newValue.toInt()));
break;
case FadeToParameter:
xt->m_parameters.fadeTo = newValue.toDouble();
break;
case FadeTimeParameter:
xt->m_parameters.fadeTime = newValue.toInt();
break;
case StartFadeParameter:
if (newValue.toBool()) {
fadeTo(xt->m_parameters.fadeTo, xt->m_parameters.fadeTime);
}
break;
default:
qWarning() << "request for unknown parameter " << parameterId;
break;
}
}
void VolumeFaderEffectXT::createInstance()
{
xine_audio_port_t *audioPort = fakeAudioPort();
Q_ASSERT(0 == m_plugin);
qDebug() << audioPort << " fadeTime = " << m_parameters.fadeTime;
m_plugin = xine_post_init(m_xine, "VolumeFader", 1, &audioPort, 0);
xine_post_in_t *paraInput = xine_post_input(m_plugin, "parameters");
Q_ASSERT(paraInput);
Q_ASSERT(paraInput->type == XINE_POST_DATA_PARAMETERS);
Q_ASSERT(paraInput->data);
m_pluginApi = reinterpret_cast<xine_post_api_t *>(paraInput->data);
m_pluginApi->set_parameters(m_plugin, &m_parameters);
}
void VolumeFaderEffect::getParameters() const
{
K_XT(const VolumeFaderEffect);
if (xt->m_pluginApi) {
xt->m_pluginApi->get_parameters(xt->m_plugin, &xt->m_parameters);
}
}
float VolumeFaderEffect::volume() const
{
K_XT(const VolumeFaderEffect);
//qDebug();
getParameters();
return xt->m_parameters.currentVolume;
}
void VolumeFaderEffect::setVolume(float volume)
{
K_XT(VolumeFaderEffect);
//qDebug() << volume;
xt->m_parameters.currentVolume = volume;
}
Phonon::VolumeFaderEffect::FadeCurve VolumeFaderEffect::fadeCurve() const
{
K_XT(const VolumeFaderEffect);
//qDebug();
getParameters();
return xt->m_parameters.fadeCurve;
}
void VolumeFaderEffect::setFadeCurve(Phonon::VolumeFaderEffect::FadeCurve curve)
{
K_XT(VolumeFaderEffect);
//qDebug() << curve;
xt->m_parameters.fadeCurve = curve;
}
void VolumeFaderEffect::fadeTo(float volume, int fadeTime)
{
K_XT(VolumeFaderEffect);
//qDebug() << volume << fadeTime;
xt->m_parameters.fadeTo = volume;
xt->m_parameters.fadeTime = fadeTime;
if (xt->m_pluginApi) {
xt->m_pluginApi->set_parameters(xt->m_plugin, &xt->m_parameters);
}
}
void VolumeFaderEffectXT::rewireTo(SourceNodeXT *source)
{
if (!source->audioOutputPort()) {
return;
}
EffectXT::rewireTo(source);
Q_ASSERT(m_pluginApi);
Q_ASSERT(m_plugin);
m_pluginApi->set_parameters(m_plugin, &m_parameters);
}
}} //namespace Phonon::Xine
#include "volumefadereffect.moc"
// vim: sw=4 ts=4
<commit_msg>- Fix mistake with removal of K letter in fader plugin naming<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Tim Beaulen <tbscope@gmail.com>
Copyright (C) 2006-2007 Matthias Kretz <kretz@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "volumefadereffect.h"
#include "xineengine.h"
namespace Phonon
{
namespace Xine
{
enum ParameterIds {
VolumeParameter = 0,
FadeCurveParameter = 1,
FadeToParameter = 2,
FadeTimeParameter = 3,
StartFadeParameter = 4
};
VolumeFaderEffectXT::VolumeFaderEffectXT()
: EffectXT("KVolumeFader"),
m_parameters(Phonon::VolumeFaderEffect::Fade3Decibel, 1.0f, 1.0f, 0)
{
}
VolumeFaderEffect::VolumeFaderEffect(QObject *parent)
: Effect(new VolumeFaderEffectXT, parent)
{
const QVariant one = 1.0;
const QVariant dZero = 0.0;
const QVariant iZero = 0;
addParameter(EffectParameter(VolumeParameter, tr( "Volume" ), 0, one, dZero, one));
addParameter(EffectParameter(FadeCurveParameter, tr( "Fade Curve" ),
EffectParameter::IntegerHint, iZero, iZero, 3));
addParameter(EffectParameter(FadeToParameter, tr( "Fade To Volume" ), 0, one, dZero, one));
addParameter(EffectParameter(FadeTimeParameter, tr( "Fade Time" ),
EffectParameter::IntegerHint, iZero, iZero, 10000));
addParameter(EffectParameter(StartFadeParameter, tr( "Start Fade" ),
EffectParameter::ToggledHint, iZero, iZero, 1));
}
VolumeFaderEffect::~VolumeFaderEffect()
{
}
QVariant VolumeFaderEffect::parameterValue(const EffectParameter &p) const
{
K_XT(const VolumeFaderEffect);
const int parameterId = p.id();
qDebug() << parameterId;
switch (static_cast<ParameterIds>(parameterId)) {
case VolumeParameter:
return static_cast<double>(volume());
case FadeCurveParameter:
return static_cast<int>(fadeCurve());
case FadeToParameter:
return static_cast<double>(xt->m_parameters.fadeTo);
case FadeTimeParameter:
return xt->m_parameters.fadeTime;
case StartFadeParameter:
return 0;
}
return QVariant();
}
void VolumeFaderEffect::setParameterValue(const EffectParameter &p, const QVariant &newValue)
{
K_XT(VolumeFaderEffect);
const int parameterId = p.id();
qDebug() << parameterId << newValue;
switch (static_cast<ParameterIds>(parameterId)) {
case VolumeParameter:
setVolume(newValue.toDouble());
break;
case FadeCurveParameter:
setFadeCurve(static_cast<Phonon::VolumeFaderEffect::FadeCurve>(newValue.toInt()));
break;
case FadeToParameter:
xt->m_parameters.fadeTo = newValue.toDouble();
break;
case FadeTimeParameter:
xt->m_parameters.fadeTime = newValue.toInt();
break;
case StartFadeParameter:
if (newValue.toBool()) {
fadeTo(xt->m_parameters.fadeTo, xt->m_parameters.fadeTime);
}
break;
default:
qWarning() << "request for unknown parameter " << parameterId;
break;
}
}
void VolumeFaderEffectXT::createInstance()
{
xine_audio_port_t *audioPort = fakeAudioPort();
Q_ASSERT(0 == m_plugin);
qDebug() << audioPort << " fadeTime = " << m_parameters.fadeTime;
m_plugin = xine_post_init(m_xine, "KVolumeFader", 1, &audioPort, 0);
xine_post_in_t *paraInput = xine_post_input(m_plugin, "parameters");
Q_ASSERT(paraInput);
Q_ASSERT(paraInput->type == XINE_POST_DATA_PARAMETERS);
Q_ASSERT(paraInput->data);
m_pluginApi = reinterpret_cast<xine_post_api_t *>(paraInput->data);
m_pluginApi->set_parameters(m_plugin, &m_parameters);
}
void VolumeFaderEffect::getParameters() const
{
K_XT(const VolumeFaderEffect);
if (xt->m_pluginApi) {
xt->m_pluginApi->get_parameters(xt->m_plugin, &xt->m_parameters);
}
}
float VolumeFaderEffect::volume() const
{
K_XT(const VolumeFaderEffect);
//qDebug();
getParameters();
return xt->m_parameters.currentVolume;
}
void VolumeFaderEffect::setVolume(float volume)
{
K_XT(VolumeFaderEffect);
//qDebug() << volume;
xt->m_parameters.currentVolume = volume;
}
Phonon::VolumeFaderEffect::FadeCurve VolumeFaderEffect::fadeCurve() const
{
K_XT(const VolumeFaderEffect);
//qDebug();
getParameters();
return xt->m_parameters.fadeCurve;
}
void VolumeFaderEffect::setFadeCurve(Phonon::VolumeFaderEffect::FadeCurve curve)
{
K_XT(VolumeFaderEffect);
//qDebug() << curve;
xt->m_parameters.fadeCurve = curve;
}
void VolumeFaderEffect::fadeTo(float volume, int fadeTime)
{
K_XT(VolumeFaderEffect);
//qDebug() << volume << fadeTime;
xt->m_parameters.fadeTo = volume;
xt->m_parameters.fadeTime = fadeTime;
if (xt->m_pluginApi) {
xt->m_pluginApi->set_parameters(xt->m_plugin, &xt->m_parameters);
}
}
void VolumeFaderEffectXT::rewireTo(SourceNodeXT *source)
{
if (!source->audioOutputPort()) {
return;
}
EffectXT::rewireTo(source);
Q_ASSERT(m_pluginApi);
Q_ASSERT(m_plugin);
m_pluginApi->set_parameters(m_plugin, &m_parameters);
}
}} //namespace Phonon::Xine
#include "volumefadereffect.moc"
// vim: sw=4 ts=4
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_gui_updatedata.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ihi $ $Date: 2006-12-20 14:24:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if ! defined INCLUDED_DP_GUI_UPDATEDATA_HXX
#define INCLUDED_DP_GUI_UPDATEDATA_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
namespace com { namespace sun { namespace star { namespace deployment {
class XPackageManager;
class XPackage;
}}}}
namespace com { namespace sun { namespace star { namespace xml { namespace dom {
class XNode;
}}}}}
namespace dp_gui {
struct UpdateData
{
::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > aInstalledPackage;
::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackageManager > aPackageManager;
// The content of the update information
::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > aUpdateInfo;
//The URL of the locally downloaded extension. It will only be set if there were no errors
//during the download
::rtl::OUString sLocalURL;
};
}
#endif
<commit_msg>INTEGRATION: CWS jl79 (1.2.202); FILE MERGED 2007/11/07 07:56:42 jl 1.2.202.1: #i82775#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_gui_updatedata.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ihi $ $Date: 2007-11-22 15:02:07 $
*
* 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
*
************************************************************************/
#if ! defined INCLUDED_DP_GUI_UPDATEDATA_HXX
#define INCLUDED_DP_GUI_UPDATEDATA_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include "rtl/ustring.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
namespace com { namespace sun { namespace star { namespace deployment {
class XPackageManager;
class XPackage;
}}}}
namespace com { namespace sun { namespace star { namespace xml { namespace dom {
class XNode;
}}}}}
namespace dp_gui {
struct UpdateData
{
::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > aInstalledPackage;
::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackageManager > aPackageManager;
// The content of the update information
::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::XNode > aUpdateInfo;
//The URL of the locally downloaded extension. It will only be set if there were no errors
//during the download
::rtl::OUString sLocalURL;
//The URL of the website wher the download can be obtained.
::rtl::OUString sWebsiteURL;
};
}
#endif
<|endoftext|> |
<commit_before>#include "PackUIWindowTask.h"
#include "PackUI.h"
#include "pack_ui_cfg.h"
#include <ee/FileHelper.h>
#include <ee/std_functor.h>
#include <ee/StringHelper.h>
#include <ee/Exception.h>
#include <algorithm>
namespace erespacker
{
PackUIWindowTask::PackUIWindowTask(const std::string& filepath, const Json::Value& value)
: PackUITask(filepath)
, m_wrapper_id(-1)
{
m_name = value["name"].asString();
m_width = value["view"]["width"].asInt();
m_height = value["view"]["height"].asInt();
m_wrapper_filepath = GetWrapperFilepath(filepath);
PackUI::Instance()->Instance()->AddListener(m_wrapper_filepath, this);
LoadItems(value, ee::FileHelper::GetFileDir(filepath));
}
PackUIWindowTask::~PackUIWindowTask()
{
for_each(m_items.begin(), m_items.end(), ee::DeletePointerFunctor<Item>());
}
void PackUIWindowTask::OnKnownPackID(const std::string& filepath, int id)
{
if (filepath == m_wrapper_filepath) {
m_wrapper_id = id;
return;
}
for (int i = 0, n = m_items.size(); i < n; ++i) {
Item* item = m_items[i];
if (item->filepath == filepath) {
item->id = id;
}
}
}
void PackUIWindowTask::Output(const std::string& dir, Json::Value& value) const
{
if (m_wrapper_id == -1) {
throw ee::Exception("Unknown uiwnd id, wrapper_file %s", m_wrapper_filepath.c_str());
}
Json::Value val;
val["type"] = UI_WINDOW;
val["name"] = ee::StringHelper::ToUtf8(m_name);
val["width"] = m_width;
val["height"] = m_height;
val["id"] = m_wrapper_id;
for (int i = 0, n = m_items.size(); i < n; ++i) {
Item* item = m_items[i];
if (item->id == -1) {
throw ee::Exception("Unknown uiwnd's item id, wrapper_file %s, name %s, filepath %s",
m_wrapper_filepath.c_str(), item->name.c_str(), item->filepath.c_str());
}
if (item->anchor == -1) {
throw ee::Exception("Unknown uiwnd's item anchor, wrapper_file %s, name %s, filepath %s, repeated name",
m_wrapper_filepath.c_str(), item->name.c_str(), item->filepath.c_str());
}
Json::Value item_val;
item_val["id"] = item->id;
item_val["anchor"] = item->anchor;
val["sprite"][i] = item_val;
}
value[value.size()] = val;
}
std::string PackUIWindowTask::GetWrapperFilepath(const std::string& filepath)
{
std::string filename = filepath.substr(0, filepath.find_last_of('_'));
return ee::FileHelper::FormatFilepathAbsolute(filename + "_wrapper_complex[gen].json");
}
void PackUIWindowTask::LoadItems(const Json::Value& value, const std::string& dir)
{
int idx = 0;
Json::Value spr_val = value["sprite"][idx++];
while (!spr_val.isNull()) {
Item* item = new Item;
item->name = spr_val["name"].asString();
item->filepath = spr_val["filepath"].asString();
item->id = -1;
item->anchor = -1;
item->filepath = ee::FileHelper::GetAbsolutePath(dir, item->filepath);
item->filepath = ee::FileHelper::FormatFilepathAbsolute(item->filepath);
PackUI::Instance()->Instance()->AddListener(item->filepath, this);
m_items.push_back(item);
spr_val = value["sprite"][idx++];
}
for (int i = 0; i < 9; ++i)
{
Json::Value anchor_val = value["anchor"][i];
if (anchor_val.isNull()) {
continue;
}
int idx = 0;
Json::Value spr_val = anchor_val[idx++];
while (!spr_val.isNull()) {
std::string name = spr_val["name"].asString();
Item* item = NULL;
for (int j = 0, m = m_items.size(); j < m; ++j) {
if (name == m_items[j]->name) {
item = m_items[j];
break;
}
}
assert(item);
item->anchor = i;
spr_val = anchor_val[idx++];
}
}
idx = 0;
Json::Value ref_val = value["ref_spr"][idx++];
while (!ref_val.isNull()) {
std::string filepath = ref_val["filepath"].asString();
filepath = ee::FileHelper::GetAbsolutePath(dir, filepath);
Json::Value ext_val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, ext_val);
fin.close();
LoadItems(ext_val, ee::FileHelper::GetFileDir(filepath));
ref_val = value["ref_spr"][idx++];
}
}
}<commit_msg>[ADDED] exception for pack<commit_after>#include "PackUIWindowTask.h"
#include "PackUI.h"
#include "pack_ui_cfg.h"
#include <ee/FileHelper.h>
#include <ee/std_functor.h>
#include <ee/StringHelper.h>
#include <ee/Exception.h>
#include <algorithm>
namespace erespacker
{
PackUIWindowTask::PackUIWindowTask(const std::string& filepath, const Json::Value& value)
: PackUITask(filepath)
, m_wrapper_id(-1)
{
m_name = value["name"].asString();
m_width = value["view"]["width"].asInt();
m_height = value["view"]["height"].asInt();
m_wrapper_filepath = GetWrapperFilepath(filepath);
PackUI::Instance()->Instance()->AddListener(m_wrapper_filepath, this);
LoadItems(value, ee::FileHelper::GetFileDir(filepath));
}
PackUIWindowTask::~PackUIWindowTask()
{
for_each(m_items.begin(), m_items.end(), ee::DeletePointerFunctor<Item>());
}
void PackUIWindowTask::OnKnownPackID(const std::string& filepath, int id)
{
if (filepath == m_wrapper_filepath) {
m_wrapper_id = id;
return;
}
for (int i = 0, n = m_items.size(); i < n; ++i) {
Item* item = m_items[i];
if (item->filepath == filepath) {
item->id = id;
}
}
}
void PackUIWindowTask::Output(const std::string& dir, Json::Value& value) const
{
if (m_wrapper_id == -1) {
throw ee::Exception("Unknown uiwnd id, wrapper_file %s", m_wrapper_filepath.c_str());
}
Json::Value val;
val["type"] = UI_WINDOW;
val["name"] = ee::StringHelper::ToUtf8(m_name);
val["width"] = m_width;
val["height"] = m_height;
val["id"] = m_wrapper_id;
for (int i = 0, n = m_items.size(); i < n; ++i) {
Item* item = m_items[i];
if (item->id == -1) {
throw ee::Exception("Unknown uiwnd's item id, wrapper_file %s, name %s, filepath %s",
m_wrapper_filepath.c_str(), item->name.c_str(), item->filepath.c_str());
}
if (item->anchor == -1) {
throw ee::Exception("Unknown uiwnd's item anchor, wrapper_file %s, name %s, filepath %s, repeated name",
m_wrapper_filepath.c_str(), item->name.c_str(), item->filepath.c_str());
}
Json::Value item_val;
item_val["id"] = item->id;
item_val["anchor"] = item->anchor;
val["sprite"][i] = item_val;
}
value[value.size()] = val;
}
std::string PackUIWindowTask::GetWrapperFilepath(const std::string& filepath)
{
std::string filename = filepath.substr(0, filepath.find_last_of('_'));
return ee::FileHelper::FormatFilepathAbsolute(filename + "_wrapper_complex[gen].json");
}
void PackUIWindowTask::LoadItems(const Json::Value& value, const std::string& dir)
{
int idx = 0;
Json::Value spr_val = value["sprite"][idx++];
while (!spr_val.isNull()) {
Item* item = new Item;
item->name = spr_val["name"].asString();
item->filepath = spr_val["filepath"].asString();
item->id = -1;
item->anchor = -1;
item->filepath = ee::FileHelper::GetAbsolutePath(dir, item->filepath);
item->filepath = ee::FileHelper::FormatFilepathAbsolute(item->filepath);
PackUI::Instance()->Instance()->AddListener(item->filepath, this);
m_items.push_back(item);
spr_val = value["sprite"][idx++];
}
for (int i = 0; i < 9; ++i)
{
Json::Value anchor_val = value["anchor"][i];
if (anchor_val.isNull()) {
continue;
}
int idx = 0;
Json::Value spr_val = anchor_val[idx++];
while (!spr_val.isNull()) {
std::string name = spr_val["name"].asString();
Item* item = NULL;
for (int j = 0, m = m_items.size(); j < m; ++j) {
if (name == m_items[j]->name) {
item = m_items[j];
break;
}
}
if (!item) {
std::string str = "PackUIWindowTask::LoadItems, fail to load: " + item->filepath + ", with name: " + name;
throw ee::Exception(str);
}
item->anchor = i;
spr_val = anchor_val[idx++];
}
}
idx = 0;
Json::Value ref_val = value["ref_spr"][idx++];
while (!ref_val.isNull()) {
std::string filepath = ref_val["filepath"].asString();
filepath = ee::FileHelper::GetAbsolutePath(dir, filepath);
Json::Value ext_val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, ext_val);
fin.close();
LoadItems(ext_val, ee::FileHelper::GetFileDir(filepath));
ref_val = value["ref_spr"][idx++];
}
}
}<|endoftext|> |
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/lir/testing/lir_test.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/literals.h"
#include "elang/lir/transforms/lowering_x64_pass.h"
#include "elang/lir/transforms/register_allocator.h"
#include "elang/lir/transforms/register_assignments.h"
#include "elang/lir/transforms/stack_allocator.h"
#include "elang/lir/transforms/stack_assignments.h"
#include "elang/lir/target.h"
namespace elang {
namespace lir {
//////////////////////////////////////////////////////////////////////
//
// LirRegisterAllocatorX64Test
//
class LirRegisterAllocatorX64Test : public testing::LirTest {
protected:
LirRegisterAllocatorX64Test() = default;
private:
DISALLOW_COPY_AND_ASSIGN(LirRegisterAllocatorX64Test);
};
// Test cases...
TEST_F(LirRegisterAllocatorX64Test, NumberOfArguments) {
auto const function = CreateFunctionEmptySample();
Editor editor(factory(), function);
editor.Edit(function->entry_block());
editor.Append(factory()->NewPCopyInstruction(
{Target::ArgumentAt(Value::Int32Type(), 0),
Target::ArgumentAt(Value::Int64Type(), 1)},
{Value::SmallInt32(42), Value::SmallInt64(39)}));
editor.Append(factory()->NewCallInstruction({}, Value::SmallInt64(56)));
EXPECT_EQ("", Commit(&editor));
RegisterAssignments assignments;
StackAssignments stack_assignments;
RegisterAllocator allocator(&editor, &assignments, &stack_assignments);
allocator.Run();
EXPECT_EQ(16, stack_assignments.maximum_arguments_size());
}
// function1:
// block1:
// // In: {}
// // Out: {block2}
// entry
// pcopy %r1l, %r2l = RCX, RDX
// assign %r4l = %r1l
// add %r5l = %r4l, %r2l
// mov %r3l = %r5l
// mov RAX = %r3l
// ret block2
// block2:
// // In: {block1}
// // Out: {}
// exit
TEST_F(LirRegisterAllocatorX64Test, SampleAdd) {
auto const function = CreateFunctionSampleAdd();
{
Editor editor(factory(), function);
RunPassForTesting<LoweringX64Pass>(&editor);
}
EXPECT_EQ(
"function1:\n"
"block1:\n"
" // In: {}\n"
" // Out: {block2}\n"
" entry r1l, r2l =\n"
// TODO(eval1749) we should allocate |R1|, |R2| instead of |R10|, |R11|.
"* mov r10l = r1l\n"
"* mov r11l = r2l\n"
" pcopy r10l, r11l = r1l, r2l\n"
" mov r10l = r10l\n"
" add r10l = r10l, r11l\n"
" mov r10l = r10l\n"
" mov r0l = r10l\n"
" ret block2\n"
"block2:\n"
" // In: {block1}\n"
" // Out: {}\n"
" exit\n",
Allocate(function));
}
// function1:
// block1:
// // In: {}
// // Out: {block3}
// entry
// jmp block3
// block3:
// // In: {block1, block4}
// // Out: {block5}
// jmp block5
// block4:
// // In: {}
// // Out: {block3, block6}
// br %b2, block6, block3
// block6:
// // In: {block4}
// // Out: {block5}
// jmp block5
// block5:
// // In: {block3, block6}
// // Out: {block2}
// phi %r1 = block6 42, block3 39
// mov EAX = %r1
// ret block2
// block2:
// // In: {block5}
// // Out: {}
// exit
TEST_F(LirRegisterAllocatorX64Test, WithCriticalEdge) {
auto const function = CreateFunctionWithCriticalEdge();
{
Editor editor(factory(), function);
RunPassForTesting<LoweringX64Pass>(&editor);
}
EXPECT_EQ(
"function1:\n"
"block1:\n"
" // In: {}\n"
" // Out: {block3}\n"
" entry\n"
" jmp block3\n"
"block3:\n"
" // In: {block1, block7}\n"
" // Out: {block4, block5}\n"
" br %b2, block5, block4\n"
"block4:\n"
" // In: {block3}\n"
" // Out: {block7, block8}\n"
" br %b3, block8, block7\n"
"block8:\n"
" // In: {block4}\n"
" // Out: {block6}\n"
"* lit r10 = #42\n"
" jmp block6\n"
"block7:\n"
" // In: {block4}\n"
" // Out: {block3}\n"
" jmp block3\n"
"block5:\n"
" // In: {block3}\n"
" // Out: {block6}\n"
"* lit r10 = #39\n"
" jmp block6\n"
"block6:\n"
" // In: {block5, block8}\n"
" // Out: {block2}\n"
" phi r10 = block8 #42, block5 #39\n"
" mov r0 = r10\n"
" ret block2\n"
"block2:\n"
" // In: {block6}\n"
" // Out: {}\n"
" exit\n",
Allocate(function));
}
} // namespace lir
} // namespace elang
<commit_msg>fixup! elang/lir: Make |Target::kFloatCallerSavedRegisters| and |Target::kGeneralCallerSavedRegisters| to have correct list of registers.<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "elang/lir/testing/lir_test.h"
#include "elang/lir/editor.h"
#include "elang/lir/factory.h"
#include "elang/lir/literals.h"
#include "elang/lir/transforms/lowering_x64_pass.h"
#include "elang/lir/transforms/register_allocator.h"
#include "elang/lir/transforms/register_assignments.h"
#include "elang/lir/transforms/stack_allocator.h"
#include "elang/lir/transforms/stack_assignments.h"
#include "elang/lir/target.h"
namespace elang {
namespace lir {
//////////////////////////////////////////////////////////////////////
//
// LirRegisterAllocatorX64Test
//
class LirRegisterAllocatorX64Test : public testing::LirTest {
protected:
LirRegisterAllocatorX64Test() = default;
private:
DISALLOW_COPY_AND_ASSIGN(LirRegisterAllocatorX64Test);
};
// Test cases...
TEST_F(LirRegisterAllocatorX64Test, NumberOfArguments) {
auto const function = CreateFunctionEmptySample();
Editor editor(factory(), function);
editor.Edit(function->entry_block());
editor.Append(factory()->NewPCopyInstruction(
{Target::ArgumentAt(Value::Int32Type(), 0),
Target::ArgumentAt(Value::Int64Type(), 1)},
{Value::SmallInt32(42), Value::SmallInt64(39)}));
editor.Append(factory()->NewCallInstruction({}, Value::SmallInt64(56)));
EXPECT_EQ("", Commit(&editor));
RegisterAssignments assignments;
StackAssignments stack_assignments;
RegisterAllocator allocator(&editor, &assignments, &stack_assignments);
allocator.Run();
EXPECT_EQ(16, stack_assignments.maximum_arguments_size());
}
// function1:
// block1:
// // In: {}
// // Out: {block2}
// entry
// pcopy %r1l, %r2l = RCX, RDX
// assign %r4l = %r1l
// add %r5l = %r4l, %r2l
// mov %r3l = %r5l
// mov RAX = %r3l
// ret block2
// block2:
// // In: {block1}
// // Out: {}
// exit
TEST_F(LirRegisterAllocatorX64Test, SampleAdd) {
auto const function = CreateFunctionSampleAdd();
{
Editor editor(factory(), function);
RunPassForTesting<LoweringX64Pass>(&editor);
}
EXPECT_EQ(
"function1:\n"
"block1:\n"
" // In: {}\n"
" // Out: {block2}\n"
" entry r1l, r2l =\n"
"* mov r0l = r1l\n"
"* mov r1l = r2l\n"
" pcopy r0l, r1l = r1l, r2l\n"
" mov r0l = r0l\n"
" add r0l = r0l, r1l\n"
" mov r0l = r0l\n"
" mov r0l = r0l\n"
" ret block2\n"
"block2:\n"
" // In: {block1}\n"
" // Out: {}\n"
" exit\n",
Allocate(function));
}
// function1:
// block1:
// // In: {}
// // Out: {block3}
// entry
// jmp block3
// block3:
// // In: {block1, block4}
// // Out: {block5}
// jmp block5
// block4:
// // In: {}
// // Out: {block3, block6}
// br %b2, block6, block3
// block6:
// // In: {block4}
// // Out: {block5}
// jmp block5
// block5:
// // In: {block3, block6}
// // Out: {block2}
// phi %r1 = block6 42, block3 39
// mov EAX = %r1
// ret block2
// block2:
// // In: {block5}
// // Out: {}
// exit
TEST_F(LirRegisterAllocatorX64Test, WithCriticalEdge) {
auto const function = CreateFunctionWithCriticalEdge();
{
Editor editor(factory(), function);
RunPassForTesting<LoweringX64Pass>(&editor);
}
EXPECT_EQ(
"function1:\n"
"block1:\n"
" // In: {}\n"
" // Out: {block3}\n"
" entry\n"
" jmp block3\n"
"block3:\n"
" // In: {block1, block7}\n"
" // Out: {block4, block5}\n"
" br %b2, block5, block4\n"
"block4:\n"
" // In: {block3}\n"
" // Out: {block7, block8}\n"
" br %b3, block8, block7\n"
"block8:\n"
" // In: {block4}\n"
" // Out: {block6}\n"
"* lit r0 = #42\n"
" jmp block6\n"
"block7:\n"
" // In: {block4}\n"
" // Out: {block3}\n"
" jmp block3\n"
"block5:\n"
" // In: {block3}\n"
" // Out: {block6}\n"
"* lit r0 = #39\n"
" jmp block6\n"
"block6:\n"
" // In: {block5, block8}\n"
" // Out: {block2}\n"
" phi r0 = block8 #42, block5 #39\n"
// TODO(eval1749) We should remove |mov r0 = r0|, which sets return value.
" mov r0 = r0\n"
" ret block2\n"
"block2:\n"
" // In: {block6}\n"
" // Out: {}\n"
" exit\n",
Allocate(function));
}
} // namespace lir
} // namespace elang
<|endoftext|> |
<commit_before>/*
* This file is part of the Phatbooks project and is distributed under the
* terms of the license contained in the file LICENSE.txt distributed
* with this package.
*
* Author: Matthew Harvey <matthew@matthewharvey.net>
*
* Copyright (c) 2012-2013, Matthew Harvey.
*
* 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 GUARD_app_hpp_19666019230925488
#define GUARD_app_hpp_19666019230925488
#include "phatbooks_database_connection.hpp"
#include "gui/error_reporter.hpp"
#include "gui/frame.hpp"
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <jewel/version.hpp>
#include <wx/app.h>
#include <wx/config.h>
#include <wx/intl.h>
#include <wx/snglinst.h>
#include <wx/string.h>
#include <memory>
namespace phatbooks
{
// begin forward declarations
class PhatbooksDatabaseConnection;
// end forward declarations
class App: public wxApp
{
public:
App();
App(App const&) = delete;
App(App&&) = delete;
App& operator=(App const&) = delete;
App& operator=(App&&) = delete;
~App() = default;
/**
* @returns name of the application as presented to the
* user.
*/
static wxString application_name();
/**
* @returns a Version struct indicating the version.
*/
static jewel::Version version();
/**
* @returns filename extension to be used with files
* belonging to this application. Includes
* the '.'.
*/
static wxString filename_extension();
/**
* @returns the default directory in which application files
* should be saved unless specified otherwise by the user. This
* would generally correspond to the user's home directory. If
* an initialized optional is returned, then the directory is
* guaranteed to exist at the time it is returned. If an uninitialized
* optional is returned, then an existing default home directory could
* not be determined. If initialized, then the value of the optional
* will be an absolute filepath.
*/
static boost::optional<boost::filesystem::path> default_directory();
bool OnInit() override;
int OnRun() override;
int OnExit() override;
void set_database_filepath
( boost::filesystem::path const& p_database_filepath
);
wxLocale const& locale() const;
PhatbooksDatabaseConnection& database_connection();
private:
/**
* @returns the filepath of the application file last opened by the
* user, stored in a boost::optional. The returned optional
* is uninitialized if the user has yet to open an application file,
* or if the last opened file cannot be found.
*/
static boost::optional<boost::filesystem::path> last_opened_file();
/**
* Record a filepath as being the last application file opened by the
* user.
*
* Precondition: p_path should be an absolute path.
*/
static void set_last_opened_file(boost::filesystem::path const& p_path);
void configure_logging();
void make_backup(boost::filesystem::path const& p_original_filepath);
static wxConfig& config();
boost::filesystem::path elicit_existing_filepath();
bool m_exiting_cleanly;
wxSingleInstanceChecker* m_single_instance_checker;
std::unique_ptr<PhatbooksDatabaseConnection> m_database_connection;
boost::optional<boost::filesystem::path> m_database_filepath;
boost::optional<boost::filesystem::path> m_backup_filepath;
gui::ErrorReporter m_error_reporter;
wxLocale m_locale;
};
// Implements App& wxGetApp()
wxDECLARE_APP(App);
} // namespace phatbooks
#endif // GUARD_app_hpp_19666019230925488
<commit_msg>Minor #include edit.<commit_after>/*
* This file is part of the Phatbooks project and is distributed under the
* terms of the license contained in the file LICENSE.txt distributed
* with this package.
*
* Author: Matthew Harvey <matthew@matthewharvey.net>
*
* Copyright (c) 2012-2013, Matthew Harvey.
*
* 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 GUARD_app_hpp_19666019230925488
#define GUARD_app_hpp_19666019230925488
#include "phatbooks_database_connection.hpp"
#include "gui/error_reporter.hpp"
#include "gui/frame.hpp"
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <jewel/version_fwd.hpp>
#include <wx/app.h>
#include <wx/config.h>
#include <wx/intl.h>
#include <wx/snglinst.h>
#include <wx/string.h>
#include <memory>
namespace phatbooks
{
// begin forward declarations
class PhatbooksDatabaseConnection;
// end forward declarations
class App: public wxApp
{
public:
App();
App(App const&) = delete;
App(App&&) = delete;
App& operator=(App const&) = delete;
App& operator=(App&&) = delete;
~App() = default;
/**
* @returns name of the application as presented to the
* user.
*/
static wxString application_name();
/**
* @returns a Version struct indicating the version.
*/
static jewel::Version version();
/**
* @returns filename extension to be used with files
* belonging to this application. Includes
* the '.'.
*/
static wxString filename_extension();
/**
* @returns the default directory in which application files
* should be saved unless specified otherwise by the user. This
* would generally correspond to the user's home directory. If
* an initialized optional is returned, then the directory is
* guaranteed to exist at the time it is returned. If an uninitialized
* optional is returned, then an existing default home directory could
* not be determined. If initialized, then the value of the optional
* will be an absolute filepath.
*/
static boost::optional<boost::filesystem::path> default_directory();
bool OnInit() override;
int OnRun() override;
int OnExit() override;
void set_database_filepath
( boost::filesystem::path const& p_database_filepath
);
wxLocale const& locale() const;
PhatbooksDatabaseConnection& database_connection();
private:
/**
* @returns the filepath of the application file last opened by the
* user, stored in a boost::optional. The returned optional
* is uninitialized if the user has yet to open an application file,
* or if the last opened file cannot be found.
*/
static boost::optional<boost::filesystem::path> last_opened_file();
/**
* Record a filepath as being the last application file opened by the
* user.
*
* Precondition: p_path should be an absolute path.
*/
static void set_last_opened_file(boost::filesystem::path const& p_path);
void configure_logging();
void make_backup(boost::filesystem::path const& p_original_filepath);
static wxConfig& config();
boost::filesystem::path elicit_existing_filepath();
bool m_exiting_cleanly;
wxSingleInstanceChecker* m_single_instance_checker;
std::unique_ptr<PhatbooksDatabaseConnection> m_database_connection;
boost::optional<boost::filesystem::path> m_database_filepath;
boost::optional<boost::filesystem::path> m_backup_filepath;
gui::ErrorReporter m_error_reporter;
wxLocale m_locale;
};
// Implements App& wxGetApp()
wxDECLARE_APP(App);
} // namespace phatbooks
#endif // GUARD_app_hpp_19666019230925488
<|endoftext|> |
<commit_before>// -*-mode: c++; indent-tabs-mode: nil; -*-
#include <iostream>
#include <fstream>
#include <sys/types.h> // opendir
#include <dirent.h> // opendir
#include <sys/types.h> // stat
#include <sys/stat.h> // stat
#include <unistd.h> // stat
#include <limits.h> // realpath
#include <stdlib.h> // realpath
#include <string.h> // strerror_r
#include <errno.h> // errno
#include <set>
#include <vector>
#include <map>
#include <limits.h> // PATH_MAX http://stackoverflow.com/a/9449307/257924
bool realPathToString(const std::string & inPath, std::string & realPath, bool verbose)
{
realPath.resize(PATH_MAX);
// Get the realPath for duplicate detection.
const char * tmp = realpath(inPath.c_str(), &(realPath[0]));
// Warn about bad links:
if (!tmp) {
char strbuf[1024];
const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf));
if (verbose) {
std::cerr << "WARNING: Failed resolve: " << inPath << " : " << errstring << std::endl;
}
realPath = "";
return false;
}
return true;
}
namespace VerboseNS {
enum VerbosityLevel {
E_NONE = 0
, E_VERBOSE = 1 << 0
, E_DEBUG = 1 << 1
};
class VerbosityTracker
{
public:
VerbosityTracker() : _verbosity(E_NONE) {}
bool isAtVerbosity(int level) { return (_verbosity & level) != 0; }
void setVerbosity(int value)
{
_verbosity = value;
}
#define DEFINE_SET_VERBOSITY_METHOD(TYPE) \
TYPE & setVerbosity(int value) \
{ \
_verbosity.setVerbosity(value); \
return *this; \
}
private:
int _verbosity;
};
};
class UniqueFileVisitor
{
public:
virtual bool visit(const std::string & absPath) = 0;
};
class UniqueFileScanner
{
public:
UniqueFileScanner()
: _visitor(NULL)
{}
UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor)
{
_visitor = visitor;
return *this;
}
DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner);
bool scan(const std::string & inDir)
{
DIR * dirfp = opendir(inDir.c_str());
if (!dirfp) {
std::cerr << "ERROR: Failed to open directory: " << inDir << std::endl;
return false;
}
struct dirent entry;
struct dirent *result = NULL;
int readdir_retval = 0;
struct stat statbuf;
std::string absPath;
std::string realPath;
while ((readdir_retval = readdir_r(dirfp, &entry, &result)) == 0 && result) {
std::string basename = entry.d_name;
// Skip directories we obviously should not traverse into:
if (basename == "." || basename == ".." || basename == ".git")
continue;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << std::endl;
}
// Fully-qualify the directory entry in preparation for calling stat:
absPath = inDir;
absPath += "/";
absPath += basename;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "absPath " << absPath << std::endl;
}
// Identify the type of file it is:
int status = stat(absPath.c_str(), &statbuf);
if (status == 0) { // stat succeeded
// Get the realPath for duplicate detection.
if (!realPathToString(absPath, realPath, _verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)))
continue;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "realPath " << realPath << std::endl;
}
// Avoid parsing the same file or directory twice (can happen via symbolic links):
SetT::iterator iter = _seen.find(realPath);
if(iter != _seen.end()) {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Skipping previously processed file or directory: " << realPath << std::endl;
}
continue;
}
_seen.insert(realPath);
if ( S_ISDIR(statbuf.st_mode) ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "directory absPath " << absPath << std::endl;
}
// recurse:
if (!scan(absPath)) {
return false;
}
} else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "parsable absPath " << absPath << std::endl;
}
if (!_visitor->visit(absPath))
return false;
} else {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Skipping non-regular file: " << absPath << std::endl;
}
continue;
}
} else { // stat failed
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cerr << "WARNING: Failed to stat: " << absPath << std::endl;
}
continue;
}
}
if (readdir_retval) {
std::cerr << "ERROR: Failed to read from directory: " << inDir << std::endl;
return false;
}
closedir(dirfp);
return true;
}
private:
typedef std::set<std::string> SetT;
SetT _seen;
UniqueFileVisitor * _visitor; // not owned by this object.
VerboseNS::VerbosityTracker _verbosity;
};
class OrgIDParser : public UniqueFileVisitor
{
public:
OrgIDParser() {}
virtual bool visit(const std::string & absPath)
{
// Only work on Org-mode files:
static const char * orgExtension = ".org";
std::size_t pos;
if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Processing " << absPath << std::endl;
}
// Parse the file:
return parse(absPath);
}
return true;
}
bool parse(const std::string & absPath)
{
std::ifstream stream(absPath.c_str(), std::ifstream::binary);
if (!stream) {
std::cerr << "ERROR: Failed to open: " << absPath << std::endl;
return false;
}
// Get length of file:
stream.seekg (0, stream.end);
std::streampos length = stream.tellg();
stream.seekg (0, stream.beg);
// Allocate memory:
std::string buffer(length, 0);
// Read data as a block:
stream.read(&(buffer[0]), length);
stream.close();
// Print content:
// std::cout.write(&(buffer[0]), length);
// std::cout << "<<<" << buffer << ">>>" << std::endl;
// :PROPERTIES:
// :ID: subdir_t-est1-note-2d73-dd0f5b698f14
// :END:
std::size_t propBegPos = 0;
std::size_t propEndPos = std::string::npos;
std::size_t idLabelBegPos = std::string::npos;
std::size_t idValueBegPos = std::string::npos;
std::size_t idValueEndPos = std::string::npos;
for ( ; (propBegPos = buffer.find(":PROPERTIES:\n", propBegPos)) != std::string::npos; propBegPos++) {
if ((propEndPos = buffer.find(":END:\n", propBegPos)) == std::string::npos) {
std::cerr << "ERROR: Lacking :END: starting at position " << propBegPos << " in file " << absPath << std::endl;
return false;
}
static const char * idLabel = ":ID:";
if ((idLabelBegPos = buffer.find(idLabel, propBegPos)) == std::string::npos || idLabelBegPos > propEndPos) {
// No id found within this current property list, so move on.
continue;
}
if ((idValueBegPos = buffer.find_first_not_of(" \t", idLabelBegPos + sizeof(idLabel))) == std::string::npos || idValueBegPos > propEndPos) {
std::cerr << "ERROR: ID lacks a value starting at position " << idLabelBegPos << " in file " << absPath << std::endl;
return false;
}
if ((idValueEndPos = buffer.find_first_of(" \t\n", idValueBegPos)) == std::string::npos || idValueEndPos > propEndPos) {
std::cerr << "ERROR: ID value premature termination at position " << idValueBegPos << " in file " << absPath << std::endl;
return false;
}
std::string id = buffer.substr(idValueBegPos, idValueEndPos - idValueBegPos);
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "absPath " << absPath << " id " << id << std::endl;
}
IdSetT & ids = _map[absPath]; // Create a IdSetT if one does not exist
if (ids.find(id) != ids.end()) {
std::cerr << "ERROR: Duplicate ID value " << id << " at position " << idValueBegPos << " in file " << absPath << std::endl;
return false;
}
ids.insert(id);
}
return true;
}
bool writeIdAlistFile(const std::string & alistPath)
{
std::ofstream stream(alistPath.c_str());
if (!stream) {
std::cerr << "ERROR: Cannot open " << alistPath << " for writing." << std::endl;
return false;
}
bool first = true;
stream << "(";
for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur)
{
const std::string & absPath = cur->first;
if (!first) {
stream << std::endl << " ";
}
stream << "(\"" << absPath << "\"";
IdSetT & ids = cur->second;
for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur)
{
stream << " \"" << *cur << "\"";
}
stream << ")";
first = false;
}
stream << ")" << std::endl;
return true;
}
DEFINE_SET_VERBOSITY_METHOD(OrgIDParser);
private:
VerboseNS::VerbosityTracker _verbosity;
typedef std::set<std::string> IdSetT;
typedef std::map<std::string, IdSetT > FileToIdSetT;
FileToIdSetT _map;
};
int main(int argc, char *argv[], char *const envp[])
{
int verbosity = VerboseNS::E_NONE;
bool readingDirectories = false;
typedef std::vector<std::string> DirectoryListT;
DirectoryListT directories;
std::string idAlistPath;
for (int i = 1; i < argc; i++)
{
std::string arg = argv[i];
if (arg.empty()) break;
if (readingDirectories) {
directories.push_back(arg);
} else {
if (arg == "--") {
readingDirectories = true;
} else if (arg == "-verbose") {
verbosity |= VerboseNS::E_VERBOSE;
} else if (arg == "-debug") {
verbosity |= VerboseNS::E_DEBUG;
} else if (arg == "-o") {
if (i + 1 >= argc) {
std::cerr << "ERROR: -o requires a value." << std::endl;
return 1;
}
idAlistPath = argv[++i];
} else {
std::cerr << "ERROR: Unrecognized option " << arg << std::endl;
return 1;
}
}
}
if (directories.empty()) {
std::cerr << "ERROR: No directories specified." << std::endl;
return 1;
}
if (idAlistPath.empty()) {
std::cerr << "ERROR: No alistfile specified." << std::endl;
return 1;
}
// OrgIDParser will house the results:
OrgIDParser parser;
parser.setVerbosity(verbosity);
// UniqueFileScanner scans for files and removes duplicates, visiting each
// with the parser:
UniqueFileScanner scanner;
scanner
.setVerbosity(verbosity)
.setVisitor(&parser);
for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur)
{
int success = scanner.scan(*cur);
if (!success) {
return 1;
}
}
// Write out the alist file:
parser.writeIdAlistFile(idAlistPath);
return 0;
} // end main
<commit_msg>expand "." input directories<commit_after>// -*-mode: c++; indent-tabs-mode: nil; -*-
#include <iostream>
#include <fstream>
#include <sys/types.h> // opendir
#include <dirent.h> // opendir
#include <sys/types.h> // stat
#include <sys/stat.h> // stat
#include <unistd.h> // stat
#include <limits.h> // realpath
#include <stdlib.h> // realpath
#include <string.h> // strerror_r
#include <errno.h> // errno
#include <set>
#include <vector>
#include <map>
#include <limits.h> // PATH_MAX http://stackoverflow.com/a/9449307/257924
bool realPathToString(const std::string & inPath, std::string & realPath, bool verbose)
{
realPath.resize(PATH_MAX);
// Get the realPath for duplicate detection.
const char * tmp = realpath(inPath.c_str(), &(realPath[0]));
// Warn about bad links:
if (!tmp) {
char strbuf[1024];
const char * errstring = strerror_r(errno, strbuf, sizeof(strbuf));
if (verbose) {
std::cerr << "WARNING: Failed resolve: " << inPath << " : " << errstring << std::endl;
}
realPath = "";
return false;
}
realPath.resize(strlen(&(realPath[0])));
return true;
}
namespace VerboseNS {
enum VerbosityLevel {
E_NONE = 0
, E_VERBOSE = 1 << 0
, E_DEBUG = 1 << 1
};
class VerbosityTracker
{
public:
VerbosityTracker() : _verbosity(E_NONE) {}
bool isAtVerbosity(int level) { return (_verbosity & level) != 0; }
void setVerbosity(int value)
{
_verbosity = value;
}
#define DEFINE_SET_VERBOSITY_METHOD(TYPE) \
TYPE & setVerbosity(int value) \
{ \
_verbosity.setVerbosity(value); \
return *this; \
}
private:
int _verbosity;
};
};
class UniqueFileVisitor
{
public:
virtual bool visit(const std::string & absPath) = 0;
};
class UniqueFileScanner
{
public:
UniqueFileScanner()
: _visitor(NULL)
{}
UniqueFileScanner & setVisitor(UniqueFileVisitor * visitor)
{
_visitor = visitor;
return *this;
}
DEFINE_SET_VERBOSITY_METHOD(UniqueFileScanner);
bool scan(const std::string & inDir)
{
DIR * dirfp = opendir(inDir.c_str());
if (!dirfp) {
std::cerr << "ERROR: Failed to open directory: " << inDir << std::endl;
return false;
}
struct dirent entry;
struct dirent *result = NULL;
int readdir_retval = 0;
struct stat statbuf;
std::string absPath;
std::string realPath;
while ((readdir_retval = readdir_r(dirfp, &entry, &result)) == 0 && result) {
std::string basename = entry.d_name;
// Skip directories we obviously should not traverse into:
if (basename == "." || basename == ".." || basename == ".git")
continue;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << std::endl;
}
// Fully-qualify the directory entry in preparation for calling stat:
absPath = inDir;
absPath += "/";
absPath += basename;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "absPath " << absPath << std::endl;
}
// Identify the type of file it is:
int status = stat(absPath.c_str(), &statbuf);
if (status == 0) { // stat succeeded
// Get the realPath for duplicate detection.
if (!realPathToString(absPath, realPath, _verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)))
continue;
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "realPath " << realPath << std::endl;
}
// Avoid parsing the same file or directory twice (can happen via symbolic links):
SetT::iterator iter = _seen.find(realPath);
if(iter != _seen.end()) {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Skipping previously processed file or directory: " << realPath << std::endl;
}
continue;
}
_seen.insert(realPath);
if ( S_ISDIR(statbuf.st_mode) ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "directory absPath " << absPath << std::endl;
}
// recurse:
if (!scan(absPath)) {
return false;
}
} else if ( S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "parsable absPath " << absPath << std::endl;
}
if (!_visitor->visit(absPath))
return false;
} else {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Skipping non-regular file: " << absPath << std::endl;
}
continue;
}
} else { // stat failed
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cerr << "WARNING: Failed to stat: " << absPath << std::endl;
}
continue;
}
}
if (readdir_retval) {
std::cerr << "ERROR: Failed to read from directory: " << inDir << std::endl;
return false;
}
closedir(dirfp);
return true;
}
private:
typedef std::set<std::string> SetT;
SetT _seen;
UniqueFileVisitor * _visitor; // not owned by this object.
VerboseNS::VerbosityTracker _verbosity;
};
class OrgIDParser : public UniqueFileVisitor
{
public:
OrgIDParser() {}
virtual bool visit(const std::string & absPath)
{
// Only work on Org-mode files:
static const char * orgExtension = ".org";
std::size_t pos;
if ( (pos = absPath.rfind(orgExtension)) != std::string::npos ) {
if (_verbosity.isAtVerbosity(VerboseNS::E_VERBOSE)) {
std::cout << "Processing " << absPath << std::endl;
}
// Parse the file:
return parse(absPath);
}
return true;
}
bool parse(const std::string & absPath)
{
std::ifstream stream(absPath.c_str(), std::ifstream::binary);
if (!stream) {
std::cerr << "ERROR: Failed to open: " << absPath << std::endl;
return false;
}
// Get length of file:
stream.seekg (0, stream.end);
std::streampos length = stream.tellg();
stream.seekg (0, stream.beg);
// Allocate memory:
std::string buffer(length, 0);
// Read data as a block:
stream.read(&(buffer[0]), length);
stream.close();
// Print content:
// std::cout.write(&(buffer[0]), length);
// std::cout << "<<<" << buffer << ">>>" << std::endl;
// :PROPERTIES:
// :ID: subdir_t-est1-note-2d73-dd0f5b698f14
// :END:
std::size_t propBegPos = 0;
std::size_t propEndPos = std::string::npos;
std::size_t idLabelBegPos = std::string::npos;
std::size_t idValueBegPos = std::string::npos;
std::size_t idValueEndPos = std::string::npos;
for ( ; (propBegPos = buffer.find(":PROPERTIES:\n", propBegPos)) != std::string::npos; propBegPos++) {
if ((propEndPos = buffer.find(":END:\n", propBegPos)) == std::string::npos) {
std::cerr << "ERROR: Lacking :END: starting at position " << propBegPos << " in file " << absPath << std::endl;
return false;
}
static const char * idLabel = ":ID:";
if ((idLabelBegPos = buffer.find(idLabel, propBegPos)) == std::string::npos || idLabelBegPos > propEndPos) {
// No id found within this current property list, so move on.
continue;
}
if ((idValueBegPos = buffer.find_first_not_of(" \t", idLabelBegPos + sizeof(idLabel))) == std::string::npos || idValueBegPos > propEndPos) {
std::cerr << "ERROR: ID lacks a value starting at position " << idLabelBegPos << " in file " << absPath << std::endl;
return false;
}
if ((idValueEndPos = buffer.find_first_of(" \t\n", idValueBegPos)) == std::string::npos || idValueEndPos > propEndPos) {
std::cerr << "ERROR: ID value premature termination at position " << idValueBegPos << " in file " << absPath << std::endl;
return false;
}
std::string id = buffer.substr(idValueBegPos, idValueEndPos - idValueBegPos);
if (_verbosity.isAtVerbosity(VerboseNS::E_DEBUG)) {
std::cout << "absPath " << absPath << " id " << id << std::endl;
}
IdSetT & ids = _map[absPath]; // Create a IdSetT if one does not exist
if (ids.find(id) != ids.end()) {
std::cerr << "ERROR: Duplicate ID value " << id << " at position " << idValueBegPos << " in file " << absPath << std::endl;
return false;
}
ids.insert(id);
}
return true;
}
bool writeIdAlistFile(const std::string & alistPath)
{
std::ofstream stream(alistPath.c_str());
if (!stream) {
std::cerr << "ERROR: Cannot open " << alistPath << " for writing." << std::endl;
return false;
}
bool first = true;
stream << "(";
for (FileToIdSetT::iterator cur = _map.begin(); cur != _map.end(); ++cur)
{
const std::string & absPath = cur->first;
if (!first) {
stream << std::endl << " ";
}
stream << "(\"" << absPath << "\"";
IdSetT & ids = cur->second;
for (IdSetT::iterator cur = ids.begin(); cur != ids.end(); ++cur)
{
stream << " \"" << *cur << "\"";
}
stream << ")";
first = false;
}
stream << ")" << std::endl;
return true;
}
DEFINE_SET_VERBOSITY_METHOD(OrgIDParser);
private:
VerboseNS::VerbosityTracker _verbosity;
typedef std::set<std::string> IdSetT;
typedef std::map<std::string, IdSetT > FileToIdSetT;
FileToIdSetT _map;
};
int main(int argc, char *argv[], char *const envp[])
{
int verbosity = VerboseNS::E_NONE;
bool readingDirectories = false;
typedef std::vector<std::string> DirectoryListT;
DirectoryListT directories;
std::string idAlistPath;
for (int i = 1; i < argc; i++)
{
std::string arg = argv[i];
if (arg.empty()) break;
if (readingDirectories) {
// Get the realPath for things like ".":
std::string realPath;
if (!realPathToString(arg, realPath, true))
continue;
std::cerr << "realPath " << realPath << std::endl;
directories.push_back(arg);
} else {
if (arg == "--") {
readingDirectories = true;
} else if (arg == "-verbose") {
verbosity |= VerboseNS::E_VERBOSE;
} else if (arg == "-debug") {
verbosity |= VerboseNS::E_DEBUG;
} else if (arg == "-o") {
if (i + 1 >= argc) {
std::cerr << "ERROR: -o requires a value." << std::endl;
return 1;
}
idAlistPath = argv[++i];
} else {
std::cerr << "ERROR: Unrecognized option " << arg << std::endl;
return 1;
}
}
}
if (directories.empty()) {
std::cerr << "ERROR: No directories specified." << std::endl;
return 1;
}
if (idAlistPath.empty()) {
std::cerr << "ERROR: No alistfile specified." << std::endl;
return 1;
}
// OrgIDParser will house the results:
OrgIDParser parser;
parser.setVerbosity(verbosity);
// UniqueFileScanner scans for files and removes duplicates, visiting each
// with the parser:
UniqueFileScanner scanner;
scanner
.setVerbosity(verbosity)
.setVisitor(&parser);
for (DirectoryListT::iterator cur = directories.begin(); cur != directories.end(); ++cur)
{
int success = scanner.scan(*cur);
if (!success) {
return 1;
}
}
// Write out the alist file:
parser.writeIdAlistFile(idAlistPath);
return 0;
} // end main
<|endoftext|> |
<commit_before>#include "global_vars.h"
#include "index_table.h"
#include <cmath>
#include <cassert>
// Construct the index tables as maps, which are automatically sorted.
IndexTable::IndexTable(const double cofm_i[], const int axis_i[], const int NumLos_i, const double box):
cofm(cofm_i), axis(axis_i), NumLos(NumLos_i), boxsize(box)
{
for(int i=0;i<NumLos;i++){
if(axis[i] == 1)
index_table_xx.insert(std::pair<const double, const int>(cofm[3*i+1], i));
else
index_table.insert(std::pair<const double, const int>(cofm[3*i], i));
}
assert(index_table_xx.size() + index_table.size() == NumLos);
return;
}
/*Returns a std::map of lines close to the coordinates xx, yy, zz.
* the key is the line index, and the value is the distance from the two axes not projected along*/
void IndexTable::get_nearby_from_range(std::multimap<const double, const int>::iterator low, std::multimap<const double, const int>::iterator high, std::map<int, double>& nearby, const float pos[], const float hh, const float first)
{
for(std::multimap<const double, const int>::iterator it = low; it != high;++it)
{
const int iproc=it->second;
/*If close in the second coord, save line*/
/*Load a sightline from the table.*/
const int iaxis = axis[iproc];
float second;
double lproj2;
if (iaxis == 3){
second = pos[1];
lproj2 = cofm[3*iproc+1];
}
else{
second = pos[2];
lproj2 = cofm[3*iproc+2];
}
const double lproj = it->first;
if(second_close(second, lproj2, hh)){
double dr2 = calc_dr2(first-lproj, second-lproj2);
if (dr2 <= hh*hh){
nearby[iproc]=dr2;
}
}
}
}
inline bool IndexTable::second_close(const float second, const double lproj2, const float hh)
{
/* Now check that xx-hh < proj < xx + hh */
float ffp=second+hh;
//Periodic wrap
if(ffp > boxsize)
if(lproj2 < ffp - boxsize)
return true;
float ffm=second-hh;
if(ffm < 0)
if(lproj2 > ffm + boxsize)
return true;
if (lproj2 > ffm && lproj2 < ffp)
return true;
else
return false;
}
inline double IndexTable::calc_dr2(const double d1, const double d2)
{
double dr, dr2;
/* Distance to projection axis */
dr = fabs(d1);
if(dr > 0.5*boxsize)
dr = boxsize - dr; /* Keep dr between 0 and box/2 */
dr2 = dr*dr;
dr = fabs(d2);
if (dr > 0.5*boxsize)
dr = boxsize - dr; /* between 0 and box/2 */
dr2 += (dr*dr);
return dr2;
}
void IndexTable::get_nearby(float first, std::multimap<const double, const int>& sort_los, std::map<int, double>& nearby, const float pos[], const float hh)
{
/*Now find the elements where dr < 2 hh, wrapping with respect to boxsize*/
/* First find highest index where xx + 2 hh > priax */
float ffp=first+hh;
if(ffp > boxsize)
ffp-=boxsize;
/* Now find lowest index in what remains where xx - 2 hh < priax */
float ffm=first-hh;
if(ffm < 0)
ffm+=boxsize;
std::multimap<const double, const int>::iterator low,high;
//An iterator to the first element not less than ffm
low=sort_los.lower_bound(ffm);
//An iterator to the first element greater than ffp
high=sort_los.lower_bound(ffp);
//If periodic wrapping occurred, we want to go through zero
if(ffm <= ffp) {
get_nearby_from_range(low, high, nearby, pos, hh, first);
}
else {
get_nearby_from_range(sort_los.begin(), high, nearby, pos, hh, first);
get_nearby_from_range(low, sort_los.end(), nearby, pos, hh, first);
}
}
/*This function takes a particle position and returns a list of the indices of lines near it in index_nr_lines
* Near is defined as: dx^2+dy^2 < 4h^2 */
std::map<int,double> IndexTable::get_near_lines(const float pos[],const float hh)
{
std::map<int, double> nearby;
if(index_table.size() > 0){
get_nearby(pos[0],index_table, nearby, pos, hh);
}
if(index_table_xx.size() > 0){
get_nearby(pos[1],index_table_xx, nearby, pos, hh);
}
return nearby;
}
//Find a list of particles near each line
std::valarray< std::vector<std::pair<int, double> > > IndexTable::get_near_particles(const float pos[], const float hh[], const long long npart)
{
//List of lines. Each element contains a list of particles and their distances to the line.
std::valarray< std::vector<std::pair<int, double> > > line_near_parts(NumLos);
//find lists
#pragma omp parallel for
for(long long i=0; i < npart; i++){
//Get list of lines near this particle
std::map<int, double> nearby=get_near_lines(&(pos[3*i]),hh[i]);
if(nearby.size()){
#pragma omp critical
{
//Insert the particles into the list of particle lists
for(std::map <int, double>::iterator it = nearby.begin(); it != nearby.end(); ++it)
line_near_parts[it->first].push_back(std::pair<int, double>(i, it->second));
}
}
}
return line_near_parts;
}
<commit_msg>Minor tweak<commit_after>#include "global_vars.h"
#include "index_table.h"
#include <cmath>
#include <cassert>
// Construct the index tables as maps, which are automatically sorted.
IndexTable::IndexTable(const double cofm_i[], const int axis_i[], const int NumLos_i, const double box):
cofm(cofm_i), axis(axis_i), NumLos(NumLos_i), boxsize(box)
{
for(int i=0;i<NumLos;i++){
if(axis[i] == 1)
index_table_xx.insert(std::pair<const double, const int>(cofm[3*i+1], i));
else
index_table.insert(std::pair<const double, const int>(cofm[3*i], i));
}
assert(index_table_xx.size() + index_table.size() == (unsigned int) NumLos);
return;
}
/*Returns a std::map of lines close to the coordinates xx, yy, zz.
* the key is the line index, and the value is the distance from the two axes not projected along*/
void IndexTable::get_nearby_from_range(std::multimap<const double, const int>::iterator low, std::multimap<const double, const int>::iterator high, std::map<int, double>& nearby, const float pos[], const float hh, const float first)
{
for(std::multimap<const double, const int>::iterator it = low; it != high;++it)
{
const int iproc=it->second;
/*If close in the second coord, save line*/
/*Load a sightline from the table.*/
const int iaxis = axis[iproc];
float second;
double lproj2;
if (iaxis == 3){
second = pos[1];
lproj2 = cofm[3*iproc+1];
}
else{
second = pos[2];
lproj2 = cofm[3*iproc+2];
}
const double lproj = it->first;
if(second_close(second, lproj2, hh)){
double dr2 = calc_dr2(first-lproj, second-lproj2);
if (dr2 <= hh*hh){
nearby[iproc]=dr2;
}
}
}
}
inline bool IndexTable::second_close(const float second, const double lproj2, const float hh)
{
/* Now check that xx-hh < proj < xx + hh */
float ffp=second+hh;
//Periodic wrap
if(ffp > boxsize)
if(lproj2 < ffp - boxsize)
return true;
float ffm=second-hh;
if(ffm < 0)
if(lproj2 > ffm + boxsize)
return true;
if (lproj2 > ffm && lproj2 < ffp)
return true;
else
return false;
}
inline double IndexTable::calc_dr2(const double d1, const double d2)
{
double dr, dr2;
/* Distance to projection axis */
dr = fabs(d1);
if(dr > 0.5*boxsize)
dr = boxsize - dr; /* Keep dr between 0 and box/2 */
dr2 = dr*dr;
dr = fabs(d2);
if (dr > 0.5*boxsize)
dr = boxsize - dr; /* between 0 and box/2 */
dr2 += (dr*dr);
return dr2;
}
void IndexTable::get_nearby(float first, std::multimap<const double, const int>& sort_los, std::map<int, double>& nearby, const float pos[], const float hh)
{
/*Now find the elements where dr < 2 hh, wrapping with respect to boxsize*/
/* First find highest index where xx + 2 hh > priax */
float ffp=first+hh;
if(ffp > boxsize)
ffp-=boxsize;
/* Now find lowest index in what remains where xx - 2 hh < priax */
float ffm=first-hh;
if(ffm < 0)
ffm+=boxsize;
std::multimap<const double, const int>::iterator low,high;
//An iterator to the first element not less than ffm
low=sort_los.lower_bound(ffm);
//An iterator to the first element greater than ffp
high=sort_los.lower_bound(ffp);
//If periodic wrapping occurred, we want to go through zero
if(ffm <= ffp) {
get_nearby_from_range(low, high, nearby, pos, hh, first);
}
else {
get_nearby_from_range(sort_los.begin(), high, nearby, pos, hh, first);
get_nearby_from_range(low, sort_los.end(), nearby, pos, hh, first);
}
}
/*This function takes a particle position and returns a list of the indices of lines near it in index_nr_lines
* Near is defined as: dx^2+dy^2 < 4h^2 */
std::map<int,double> IndexTable::get_near_lines(const float pos[],const float hh)
{
std::map<int, double> nearby;
if(index_table.size() > 0){
get_nearby(pos[0],index_table, nearby, pos, hh);
}
if(index_table_xx.size() > 0){
get_nearby(pos[1],index_table_xx, nearby, pos, hh);
}
return nearby;
}
//Find a list of particles near each line
std::valarray< std::vector<std::pair<int, double> > > IndexTable::get_near_particles(const float pos[], const float hh[], const long long npart)
{
//List of lines. Each element contains a list of particles and their distances to the line.
std::valarray< std::vector<std::pair<int, double> > > line_near_parts(NumLos);
//find lists
#pragma omp parallel for
for(long long i=0; i < npart; i++){
//Get list of lines near this particle
std::map<int, double> nearby=get_near_lines(&(pos[3*i]),hh[i]);
if(nearby.size()){
#pragma omp critical
{
//Insert the particles into the list of particle lists
for(std::map <int, double>::const_iterator it = nearby.begin(); it != nearby.end(); ++it)
line_near_parts[it->first].push_back(std::pair<int, double>(i, it->second));
}
}
}
return line_near_parts;
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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 "mbed/SPI.h"
#include "minar/minar.h"
#if DEVICE_SPI
namespace mbed {
#if DEVICE_SPI_ASYNCH && TRANSACTION_QUEUE_SIZE_SPI
CircularBuffer<SPI::transaction_t, TRANSACTION_QUEUE_SIZE_SPI> SPI::_transaction_buffer;
#endif
SPI::SPI(PinName mosi, PinName miso, PinName sclk) :
_spi(),
#if DEVICE_SPI_ASYNCH
_irq(this),
_usage(DMA_USAGE_NEVER),
#endif
_bits(8),
_mode(0),
_order(SPI_MSB),
_hz(1000000) {
spi_init(&_spi, mosi, miso, sclk);
spi_format(&_spi, _bits, _mode, _order);
spi_frequency(&_spi, _hz);
}
void SPI::format(int bits, int mode, spi_bitorder_t order) {
_bits = bits;
_mode = mode;
_order = order;
SPI::_owner = NULL; // Not that elegant, but works. rmeyer
aquire();
}
void SPI::frequency(int hz) {
_hz = hz;
SPI::_owner = NULL; // Not that elegant, but works. rmeyer
aquire();
}
SPI* SPI::_owner = NULL;
// ignore the fact there are multiple physical spis, and always update if it wasnt us last
void SPI::aquire() {
if (_owner != this) {
spi_format(&_spi, _bits, _mode, _order);
spi_frequency(&_spi, _hz);
_owner = this;
}
}
int SPI::write(int value) {
aquire();
return spi_master_write(&_spi, value);
}
#if DEVICE_SPI_ASYNCH
int SPI::transfer(const SPI::SPITransferAdder &td)
{
if (spi_active(&_spi)) {
return queue_transfer(td._td);
}
start_transfer(td._td);
return 0;
}
void SPI::abort_transfer()
{
spi_abort_asynch(&_spi);
#if TRANSACTION_QUEUE_SIZE_SPI
dequeue_transaction();
#endif
}
void SPI::clear_transfer_buffer()
{
#if TRANSACTION_QUEUE_SIZE_SPI
_transaction_buffer.reset();
#endif
}
void SPI::abort_all_transfers()
{
clear_transfer_buffer();
abort_transfer();
}
int SPI::set_dma_usage(DMAUsage usage)
{
if (spi_active(&_spi)) {
return -1;
}
_usage = usage;
return 0;
}
int SPI::queue_transfer(const transaction_data_t &td)
{
#if TRANSACTION_QUEUE_SIZE_SPI
transaction_t transaction(this, td);
if (_transaction_buffer.full()) {
return -1; // the buffer is full
} else {
_transaction_buffer.push(transaction);
return 0;
}
#else
return -1;
#endif
}
void SPI::start_transfer(const transaction_data_t &td)
{
aquire();
_current_transaction = td;
_irq.callback(&SPI::irq_handler_asynch);
spi_master_transfer(&_spi, td.tx_buffer.buf, td.tx_buffer.length, td.rx_buffer.buf, td.rx_buffer.length,
_irq.entry(), td.event, _usage);
}
#if TRANSACTION_QUEUE_SIZE_SPI
void SPI::start_transaction(transaction_data_t *data)
{
start_transfer(*data);
}
void SPI::dequeue_transaction()
{
transaction_t t;
if (_transaction_buffer.pop(t)) {
SPI* obj = t.get_object();
transaction_data_t* data = t.get_transaction();
obj->start_transaction(data);
}
}
#endif
void SPI::irq_handler_asynch(void)
{
int event = spi_irq_handler_asynch(&_spi);
if (_current_transaction.callback && (event & SPI_EVENT_ALL)) {
minar::Scheduler::postCallback(
_current_transaction.callback.bind(_current_transaction.tx_buffer, _current_transaction.rx_buffer,
event & SPI_EVENT_ALL));
}
#if TRANSACTION_QUEUE_SIZE_SPI
if (event & (SPI_EVENT_ALL | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE)) {
// SPI peripheral is free (event happend), dequeue transaction
dequeue_transaction();
}
#endif
}
SPI::SPITransferAdder::SPITransferAdder(SPI *owner) :
_applied(false), _rc(0), _owner(owner)
{
_td.tx_buffer.length = 0;
_td.rx_buffer.length = 0;
_td.callback = event_callback_t((void (*)(Buffer, Buffer, int))NULL);
}
const SPI::SPITransferAdder & SPI::SPITransferAdder::operator =(const SPI::SPITransferAdder &a)
{
_td = a._td;
_owner = a._owner;
_applied = 0;
return *this;
}
SPI::SPITransferAdder::SPITransferAdder(const SPITransferAdder &a)
{
*this = a;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::tx(void *txBuf, size_t txSize)
{
MBED_ASSERT(!_td.tx_buffer.length);
_td.tx_buffer.buf = txBuf;
_td.tx_buffer.length = txSize;
return *this;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::rx(void *rxBuf, size_t rxSize)
{
MBED_ASSERT(!_td.rx_buffer.length);
_td.rx_buffer.buf = rxBuf;
_td.rx_buffer.length = rxSize;
return *this;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::callback(const event_callback_t &cb, int event)
{
MBED_ASSERT(!_td.callback);
_td.callback = cb;
_td.event = event;
return *this;
}
int SPI::SPITransferAdder::apply()
{
if (!_applied) {
_applied = true;
_rc = _owner->transfer(*this);
}
return _rc;
}
SPI::SPITransferAdder::~SPITransferAdder()
{
apply();
}
SPI::SPITransferAdder SPI::transfer()
{
SPITransferAdder a(this);
return a;
}
#endif
} // namespace mbed
#endif
<commit_msg>SPI - include assert header<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2006-2013 ARM Limited
*
* 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 "mbed/SPI.h"
#include "minar/minar.h"
#include "mbed/mbed_assert.h"
#if DEVICE_SPI
namespace mbed {
#if DEVICE_SPI_ASYNCH && TRANSACTION_QUEUE_SIZE_SPI
CircularBuffer<SPI::transaction_t, TRANSACTION_QUEUE_SIZE_SPI> SPI::_transaction_buffer;
#endif
SPI::SPI(PinName mosi, PinName miso, PinName sclk) :
_spi(),
#if DEVICE_SPI_ASYNCH
_irq(this),
_usage(DMA_USAGE_NEVER),
#endif
_bits(8),
_mode(0),
_order(SPI_MSB),
_hz(1000000) {
spi_init(&_spi, mosi, miso, sclk);
spi_format(&_spi, _bits, _mode, _order);
spi_frequency(&_spi, _hz);
}
void SPI::format(int bits, int mode, spi_bitorder_t order) {
_bits = bits;
_mode = mode;
_order = order;
SPI::_owner = NULL; // Not that elegant, but works. rmeyer
aquire();
}
void SPI::frequency(int hz) {
_hz = hz;
SPI::_owner = NULL; // Not that elegant, but works. rmeyer
aquire();
}
SPI* SPI::_owner = NULL;
// ignore the fact there are multiple physical spis, and always update if it wasnt us last
void SPI::aquire() {
if (_owner != this) {
spi_format(&_spi, _bits, _mode, _order);
spi_frequency(&_spi, _hz);
_owner = this;
}
}
int SPI::write(int value) {
aquire();
return spi_master_write(&_spi, value);
}
#if DEVICE_SPI_ASYNCH
int SPI::transfer(const SPI::SPITransferAdder &td)
{
if (spi_active(&_spi)) {
return queue_transfer(td._td);
}
start_transfer(td._td);
return 0;
}
void SPI::abort_transfer()
{
spi_abort_asynch(&_spi);
#if TRANSACTION_QUEUE_SIZE_SPI
dequeue_transaction();
#endif
}
void SPI::clear_transfer_buffer()
{
#if TRANSACTION_QUEUE_SIZE_SPI
_transaction_buffer.reset();
#endif
}
void SPI::abort_all_transfers()
{
clear_transfer_buffer();
abort_transfer();
}
int SPI::set_dma_usage(DMAUsage usage)
{
if (spi_active(&_spi)) {
return -1;
}
_usage = usage;
return 0;
}
int SPI::queue_transfer(const transaction_data_t &td)
{
#if TRANSACTION_QUEUE_SIZE_SPI
transaction_t transaction(this, td);
if (_transaction_buffer.full()) {
return -1; // the buffer is full
} else {
_transaction_buffer.push(transaction);
return 0;
}
#else
return -1;
#endif
}
void SPI::start_transfer(const transaction_data_t &td)
{
aquire();
_current_transaction = td;
_irq.callback(&SPI::irq_handler_asynch);
spi_master_transfer(&_spi, td.tx_buffer.buf, td.tx_buffer.length, td.rx_buffer.buf, td.rx_buffer.length,
_irq.entry(), td.event, _usage);
}
#if TRANSACTION_QUEUE_SIZE_SPI
void SPI::start_transaction(transaction_data_t *data)
{
start_transfer(*data);
}
void SPI::dequeue_transaction()
{
transaction_t t;
if (_transaction_buffer.pop(t)) {
SPI* obj = t.get_object();
transaction_data_t* data = t.get_transaction();
obj->start_transaction(data);
}
}
#endif
void SPI::irq_handler_asynch(void)
{
int event = spi_irq_handler_asynch(&_spi);
if (_current_transaction.callback && (event & SPI_EVENT_ALL)) {
minar::Scheduler::postCallback(
_current_transaction.callback.bind(_current_transaction.tx_buffer, _current_transaction.rx_buffer,
event & SPI_EVENT_ALL));
}
#if TRANSACTION_QUEUE_SIZE_SPI
if (event & (SPI_EVENT_ALL | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE)) {
// SPI peripheral is free (event happend), dequeue transaction
dequeue_transaction();
}
#endif
}
SPI::SPITransferAdder::SPITransferAdder(SPI *owner) :
_applied(false), _rc(0), _owner(owner)
{
_td.tx_buffer.length = 0;
_td.rx_buffer.length = 0;
_td.callback = event_callback_t((void (*)(Buffer, Buffer, int))NULL);
}
const SPI::SPITransferAdder & SPI::SPITransferAdder::operator =(const SPI::SPITransferAdder &a)
{
_td = a._td;
_owner = a._owner;
_applied = 0;
return *this;
}
SPI::SPITransferAdder::SPITransferAdder(const SPITransferAdder &a)
{
*this = a;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::tx(void *txBuf, size_t txSize)
{
MBED_ASSERT(!_td.tx_buffer.length);
_td.tx_buffer.buf = txBuf;
_td.tx_buffer.length = txSize;
return *this;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::rx(void *rxBuf, size_t rxSize)
{
MBED_ASSERT(!_td.rx_buffer.length);
_td.rx_buffer.buf = rxBuf;
_td.rx_buffer.length = rxSize;
return *this;
}
SPI::SPITransferAdder & SPI::SPITransferAdder::callback(const event_callback_t &cb, int event)
{
MBED_ASSERT(!_td.callback);
_td.callback = cb;
_td.event = event;
return *this;
}
int SPI::SPITransferAdder::apply()
{
if (!_applied) {
_applied = true;
_rc = _owner->transfer(*this);
}
return _rc;
}
SPI::SPITransferAdder::~SPITransferAdder()
{
apply();
}
SPI::SPITransferAdder SPI::transfer()
{
SPITransferAdder a(this);
return a;
}
#endif
} // namespace mbed
#endif
<|endoftext|> |
<commit_before>#include "stdafx.h"
static double GetTime()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart / f.QuadPart;
}
static float INVALID_POS = -99999.f;
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return sqrt(maxSq);
}
App::App() : scale(1), radius(1), lastX(INVALID_POS), lastY(INVALID_POS), sprite(nullptr), font(nullptr), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
ZeroMemory(mesh, sizeof(mesh));
lastTime = GetTime();
}
App::~App()
{
}
void App::Init(const char* fileName)
{
Destroy();
debugRenderer.Init();
gridRenderer.Init();
g_type = "mesh";
sprite = new SpriteBatch(deviceMan11.GetContext());
font = new SpriteFont(deviceMan11.GetDevice(), L"resource\\font.spritefont");
meshTiny = new MeshX("resource\\tiny.x");
if (fileName) {
const char* ext = strrchr(fileName, '.');
if (ext && !_stricmp(ext, ".bvh")) {
Bvh* bvh = new Bvh(fileName);
mesh[0] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
} else {
mesh[0] = new MeshX(fileName);
}
} else {
const char* bvhNames[] = {
"D:\\github\\aachan.bvh",
"D:\\github\\kashiyuka.bvh",
"D:\\github\\nocchi.bvh",
};
for (int i = 0; i < dimof(bvhNames); i++) {
Bvh* bvh = new Bvh(bvhNames[i]);
mesh[i] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
}
}
radius = CalcRadius(mesh[0]);
scale = std::max(0.00001f, radius);
height = radius / 2;
lastTime = GetTime();
}
void App::MouseWheel(float delta)
{
if (delta > 0) {
scale /= 1.1f;
}
if (delta < 0) {
scale *= 1.1f;
}
}
void App::LButtonDown(float x, float y)
{
lastX = x;
lastY = y;
}
void App::LButtonUp(float x, float y)
{
MouseMove(x, y);
lastX = lastY = INVALID_POS;
}
void App::MouseMove(float x, float y)
{
if (lastX <= INVALID_POS || lastY <= INVALID_POS) {
return;
}
rotX += (x - lastX) * XM_PI * 2.0f;
rotY += (y - lastY) * XM_PI * 2.0f;
lastX = x;
lastY = y;
}
inline Vec2 GetScreenPos(const Mat& mLocal)
{
Mat mW, mV, mP, mViewport;
matrixMan.Get(MatrixMan::WORLD, mW);
matrixMan.Get(MatrixMan::VIEW, mV);
matrixMan.Get(MatrixMan::PROJ, mP);
mViewport._11 = SCR_W / 2;
mViewport._22 = -SCR_H / 2;
mViewport._41 = SCR_W / 2;
mViewport._42 = SCR_H / 2;
Mat m = mLocal * mW * mV * mP * mViewport;
Vec2 p;
p.x = m._41 / m._44;
p.y = m._42 / m._44;
return p;
}
void App::DrawBoneNames(Bvh* bvh)
{
const std::vector<BvhFrame>& frames = bvh->GetFrames();
for (auto& it : frames) {
if (it.childId < 0) {
continue;
}
Vec2 pos = GetScreenPos(it.result);
WCHAR wname[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, it.name, -1, wname, dimof(wname));
XMVECTOR size = font->MeasureString(wname);
pos.x -= XMVectorGetX(size) / 2;
pos.y -= XMVectorGetY(size) / 2;
XMFLOAT2 origin = {0, 0};
font->DrawString(sprite, wname, pos, Colors::Black, 0, origin, 0.7f);
pos.x += 1.0f;
pos.y += 1.0f;
font->DrawString(sprite, wname, pos, Colors::White, 0, origin, 0.7f);
}
}
void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
const std::vector<Frame>& frames = meshX->GetFrames();
for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
const Frame& f = frames[id];
Vec2 pos = GetScreenPos(result.boneMat[id]);
WCHAR wname[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, f.name, -1, wname, dimof(wname));
if (wname[0] == '\0') {
wcscpy(wname, L"[NO NAME]");
}
XMVECTOR size = font->MeasureString(wname);
pos.x -= XMVectorGetX(size) / 2;
pos.y -= XMVectorGetY(size) / 2;
XMFLOAT2 origin = {0, 0};
font->DrawString(sprite, wname, pos, Colors::Black, 0, origin, 0.7f);
pos.x += 1.0f;
pos.y += 1.0f;
font->DrawString(sprite, wname, pos, Colors::White, 0, origin, 0.7f);
}
}
void App::DrawCameraParams()
{
Mat v;
matrixMan.Get(MatrixMan::VIEW, v);
Mat mInv = inv(v);
char buf[128];
WCHAR wBuf[128];
XMFLOAT2 origin = {0, 0};
sprintf(buf, "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, dimof(wBuf));
Vec2 pos = {5, 5};
font->DrawString(sprite, wBuf, pos, Colors::White, 0, origin, 1.0f);
sprintf(buf, "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, dimof(wBuf));
pos.y = 30;
font->DrawString(sprite, wBuf, pos, Colors::White, 0, origin, 1.0f);
}
void App::Update()
{
if (GetKeyState('P') & 0x80) {
g_type = "pivot";
}
if (GetKeyState('M') & 0x80) {
g_type = "mesh";
}
if (GetKeyState('B') & 0x80) {
g_type = "bone";
}
for (auto& i : {'0', '1', '2', '3', '4', '9'}) {
if (GetKeyState(i) & 0x80) {
animationNumber = i - '0';
}
}
}
void App::Draw()
{
double currentTime = GetTime();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
if (GetKeyState(VK_RETURN) & 0x01) {
trackTime += deltaTime;
}
matrixMan.Set(MatrixMan::WORLD, Mat());
float dist = 3 * scale;
Mat cam = translate(0, height, -dist) * q2m(Quat(Vec3(1,0,0), rotY)) * q2m(Quat(Vec3(0,1,0), rotX));
matrixMan.Set(MatrixMan::VIEW, fastInv(cam));
matrixMan.Set(MatrixMan::PROJ, XMMatrixPerspectiveFovLH(45 * XM_PI / 180, (float)SCR_W / SCR_H, dist / 1000, dist * 1000));
sprite->Begin();
for (int i = 0; i < dimof(mesh); i++) {
Mesh* it = mesh[i];
MeshX* meshX = meshTiny;
MeshXAnimResult meshXAnimResult;
if (it && meshX) {
Bvh* bvh = dynamic_cast<Bvh*>(it);
if (bvh) {
bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
if (animationNumber == 9) {
meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
} else {
meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
}
meshX->Draw(meshXAnimResult);
if (GetKeyState('T') & 0x01) {
DrawBoneNames(bvh);
}
}
}
if (meshX && (GetKeyState('T') & 0x01)) {
DrawBoneNames(meshX, meshXAnimResult);
}
}
DrawCameraParams();
sprite->End();
gridRenderer.Draw();
}
void App::Destroy()
{
for (auto& it : mesh) {
SAFE_DELETE(it);
}
SAFE_DELETE(meshTiny);
SAFE_DELETE(font);
SAFE_DELETE(sprite);
debugRenderer.Destroy();
gridRenderer.Destroy();
}
std::string g_type;
<commit_msg>for verifying fastInv<commit_after>#include "stdafx.h"
static double GetTime()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart / f.QuadPart;
}
static float INVALID_POS = -99999.f;
static float CalcRadius(const Mesh* m)
{
const Block& b = m->GetRawDatas();
float maxSq = 0;
for (auto& it : b.vertices) {
float sq = lengthSq(it.xyz);
maxSq = std::max(maxSq, sq);
}
return sqrt(maxSq);
}
App::App() : scale(1), radius(1), lastX(INVALID_POS), lastY(INVALID_POS), sprite(nullptr), font(nullptr), animationNumber(0), trackTime(0), meshTiny(nullptr)
{
ZeroMemory(mesh, sizeof(mesh));
lastTime = GetTime();
}
App::~App()
{
}
void App::Init(const char* fileName)
{
Destroy();
debugRenderer.Init();
gridRenderer.Init();
g_type = "mesh";
sprite = new SpriteBatch(deviceMan11.GetContext());
font = new SpriteFont(deviceMan11.GetDevice(), L"resource\\font.spritefont");
meshTiny = new MeshX("resource\\tiny.x");
if (fileName) {
const char* ext = strrchr(fileName, '.');
if (ext && !_stricmp(ext, ".bvh")) {
Bvh* bvh = new Bvh(fileName);
mesh[0] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[0]);
} else {
mesh[0] = new MeshX(fileName);
}
} else {
const char* bvhNames[] = {
"D:\\github\\aachan.bvh",
"D:\\github\\kashiyuka.bvh",
"D:\\github\\nocchi.bvh",
};
for (int i = 0; i < dimof(bvhNames); i++) {
Bvh* bvh = new Bvh(bvhNames[i]);
mesh[i] = bvh;
bvh->ResetAnim();
meshTiny->SyncLocalAxisWithBvh(bvh, bind[i]);
}
}
radius = CalcRadius(mesh[0]);
scale = std::max(0.00001f, radius);
height = radius / 2;
lastTime = GetTime();
}
void App::MouseWheel(float delta)
{
if (delta > 0) {
scale /= 1.1f;
}
if (delta < 0) {
scale *= 1.1f;
}
}
void App::LButtonDown(float x, float y)
{
lastX = x;
lastY = y;
}
void App::LButtonUp(float x, float y)
{
MouseMove(x, y);
lastX = lastY = INVALID_POS;
}
void App::MouseMove(float x, float y)
{
if (lastX <= INVALID_POS || lastY <= INVALID_POS) {
return;
}
rotX += (x - lastX) * XM_PI * 2.0f;
rotY += (y - lastY) * XM_PI * 2.0f;
lastX = x;
lastY = y;
}
inline Vec2 GetScreenPos(const Mat& mLocal)
{
Mat mW, mV, mP, mViewport;
matrixMan.Get(MatrixMan::WORLD, mW);
matrixMan.Get(MatrixMan::VIEW, mV);
matrixMan.Get(MatrixMan::PROJ, mP);
mViewport._11 = SCR_W / 2;
mViewport._22 = -SCR_H / 2;
mViewport._41 = SCR_W / 2;
mViewport._42 = SCR_H / 2;
Mat m = mLocal * mW * mV * mP * mViewport;
Vec2 p;
p.x = m._41 / m._44;
p.y = m._42 / m._44;
return p;
}
void App::DrawBoneNames(Bvh* bvh)
{
const std::vector<BvhFrame>& frames = bvh->GetFrames();
for (auto& it : frames) {
if (it.childId < 0) {
continue;
}
Vec2 pos = GetScreenPos(it.result);
WCHAR wname[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, it.name, -1, wname, dimof(wname));
XMVECTOR size = font->MeasureString(wname);
pos.x -= XMVectorGetX(size) / 2;
pos.y -= XMVectorGetY(size) / 2;
XMFLOAT2 origin = {0, 0};
font->DrawString(sprite, wname, pos, Colors::Black, 0, origin, 0.7f);
pos.x += 1.0f;
pos.y += 1.0f;
font->DrawString(sprite, wname, pos, Colors::White, 0, origin, 0.7f);
}
}
void App::DrawBoneNames(const MeshX* meshX, const MeshXAnimResult& result)
{
const std::vector<Frame>& frames = meshX->GetFrames();
for (BONE_ID id = 0; id < (BONE_ID)frames.size(); id++) {
const Frame& f = frames[id];
Vec2 pos = GetScreenPos(result.boneMat[id]);
WCHAR wname[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, f.name, -1, wname, dimof(wname));
if (wname[0] == '\0') {
wcscpy(wname, L"[NO NAME]");
}
XMVECTOR size = font->MeasureString(wname);
pos.x -= XMVectorGetX(size) / 2;
pos.y -= XMVectorGetY(size) / 2;
XMFLOAT2 origin = {0, 0};
font->DrawString(sprite, wname, pos, Colors::Black, 0, origin, 0.7f);
pos.x += 1.0f;
pos.y += 1.0f;
font->DrawString(sprite, wname, pos, Colors::White, 0, origin, 0.7f);
}
}
void App::DrawCameraParams()
{
Mat v;
matrixMan.Get(MatrixMan::VIEW, v);
Mat mInv = inv(v);
char buf[128];
WCHAR wBuf[128];
XMFLOAT2 origin = {0, 0};
sprintf(buf, "cam pos(via inv view):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, dimof(wBuf));
Vec2 pos = {5, 5};
font->DrawString(sprite, wBuf, pos, Colors::White, 0, origin, 1.0f);
mInv = fastInv(v);
sprintf(buf, "cam pos(by fastInv):%f, %f, %f dir:%f, %f, %f", mInv._41, mInv._42, mInv._43, mInv._31, mInv._32, mInv._33);
MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, dimof(wBuf));
pos.y = 25;
font->DrawString(sprite, wBuf, pos, Colors::White, 0, origin, 1.0f);
sprintf(buf, "cam dir(view mtx direct): %f, %f, %f", v._13, v._23, v._33);
MultiByteToWideChar(CP_ACP, 0, buf, -1, wBuf, dimof(wBuf));
pos.y = 45;
font->DrawString(sprite, wBuf, pos, Colors::White, 0, origin, 1.0f);
}
void App::Update()
{
if (GetKeyState('P') & 0x80) {
g_type = "pivot";
}
if (GetKeyState('M') & 0x80) {
g_type = "mesh";
}
if (GetKeyState('B') & 0x80) {
g_type = "bone";
}
for (auto& i : {'0', '1', '2', '3', '4', '9'}) {
if (GetKeyState(i) & 0x80) {
animationNumber = i - '0';
}
}
}
void App::Draw()
{
double currentTime = GetTime();
double deltaTime = currentTime - lastTime;
lastTime = currentTime;
if (GetKeyState(VK_RETURN) & 0x01) {
trackTime += deltaTime;
}
matrixMan.Set(MatrixMan::WORLD, Mat());
float dist = 3 * scale;
Mat cam = translate(0, height, -dist) * q2m(Quat(Vec3(1,0,0), rotY)) * q2m(Quat(Vec3(0,1,0), rotX));
matrixMan.Set(MatrixMan::VIEW, fastInv(cam));
matrixMan.Set(MatrixMan::PROJ, XMMatrixPerspectiveFovLH(45 * XM_PI / 180, (float)SCR_W / SCR_H, dist / 1000, dist * 1000));
sprite->Begin();
for (int i = 0; i < dimof(mesh); i++) {
Mesh* it = mesh[i];
MeshX* meshX = meshTiny;
MeshXAnimResult meshXAnimResult;
if (it && meshX) {
Bvh* bvh = dynamic_cast<Bvh*>(it);
if (bvh) {
bvh->Draw(animationNumber == 9 ? 0 : animationNumber, trackTime);
if (animationNumber == 9) {
meshX->CalcAnimationFromBvh(bvh, bind[i], trackTime, meshXAnimResult, 270 / radius);
} else {
meshX->CalcAnimation(animationNumber, trackTime, meshXAnimResult);
}
meshX->Draw(meshXAnimResult);
if (GetKeyState('T') & 0x01) {
DrawBoneNames(bvh);
}
}
}
if (meshX && (GetKeyState('T') & 0x01)) {
DrawBoneNames(meshX, meshXAnimResult);
}
}
DrawCameraParams();
sprite->End();
gridRenderer.Draw();
}
void App::Destroy()
{
for (auto& it : mesh) {
SAFE_DELETE(it);
}
SAFE_DELETE(meshTiny);
SAFE_DELETE(font);
SAFE_DELETE(sprite);
debugRenderer.Destroy();
gridRenderer.Destroy();
}
std::string g_type;
<|endoftext|> |
<commit_before>
/**
* Example to demonstrate a XPCC driver for HD44780 displays,
* including displays with I2C PCA8574 port expanders.
*
* This example uses I2cMaster2 of STM32F407
*
* SDA PB11
* SCL PB10
*
* GND and +5V are connected to the the port expander of the display.
*
*/
#include <xpcc/architecture.hpp>
#include <xpcc/driver/display.hpp>
#include <xpcc/io/iostream.hpp>
#include <xpcc/debug/logger.hpp>
#include <xpcc/driver/gpio/pca8574.hpp>
#include "../../stm32f4_discovery.hpp"
xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device;
xpcc::IOStream stream(device);
// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(device);
xpcc::log::Logger xpcc::log::info(device);
xpcc::log::Logger xpcc::log::warning(device);
xpcc::log::Logger xpcc::log::error(device);
// Set the log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::DEBUG
using namespace Board;
typedef I2cMaster2 MyI2cMaster;
// typedef xpcc::SoftwareI2cMaster<GpioB10, GpioB11> MyI2cMaster;
// define the pins used by the LCD when not using a port expander
namespace lcd
{
typedef GpioOutputC7 Backlight;
typedef GpioOutputC6 E;
typedef GpioOutputC5 Rw;
typedef GpioOutputC4 Rs;
// note: an 8bit data port
typedef GpioPort<GpioOutputC0, 8> Data8Bit;
// and a 4 bit data port
typedef GpioPort<GpioOutputC4, 4> Data4Bit;
}
typedef xpcc::Pca8574<MyI2cMaster> GpioExpander;
GpioExpander gpioExpander;
namespace expander
{
// Instances for each pin
typedef GpioExpander::P0< gpioExpander > Rs;
typedef GpioExpander::P1< gpioExpander > Rw;
typedef GpioExpander::P2< gpioExpander > E;
typedef GpioExpander::P3< gpioExpander > Backlight;
typedef GpioExpander::P4< gpioExpander > Pin4;
typedef GpioExpander::P5< gpioExpander > Pin5;
typedef GpioExpander::P6< gpioExpander > Pin6;
// you can also declare the pin like this, however it is too verbose
typedef xpcc::GpioExpanderPin< GpioExpander, gpioExpander, GpioExpander::Pin::P7 > Pin7;
// typedef GpioExpander::P7< gpioExpander > Pin7;
// Form a GpioPort out of four single pins.
typedef GpioExpander::Port< gpioExpander,
GpioExpander::Pin::P4, 4 > Data4BitGpio;
// You can also use SoftwareGpioPort, note however, that every pin is set separately,
// so this requires four times as many bus accesses as the optimized version above.
// typedef xpcc::SoftwareGpioPort<Pin7, Pin6, Pin5, Pin4> Data4BitGpio;
}
// You can choose either port width simply by using it.
// The driver will handle it internally.
// create a LCD object with an 8bit data port
// xpcc::Hd44780< lcd::Data8Bit, lcd::Rw, lcd::Rs, lcd::E > display(20, 4);
// create a LCD object with an 4bit data port
// xpcc::Hd44780< lcd::Data4Bit, lcd::Rw, lcd::Rs, lcd::E > display(20, 4);
// create a LCD object with an 4bit data port at a I2C Gpio port expander
xpcc::Hd44780< expander::Data4BitGpio, expander::Rw, expander::Rs, expander::E > display(20, 4);
class ThreadOne : public xpcc::pt::Protothread
{
public:
ThreadOne()
{
}
bool
update()
{
PT_BEGIN();
XPCC_LOG_DEBUG << "Ping the device from ThreadOne" << xpcc::endl;
// ping the device until it responds
while (true)
{
// we wait until the task started
if (PT_CALL(gpioExpander.ping())) {
break;
}
XPCC_LOG_DEBUG << "Device did not respond" << xpcc::endl;
// otherwise, try again in 100ms
this->timeout.restart(1000);
PT_WAIT_UNTIL(this->timeout.isExpired());
}
XPCC_LOG_DEBUG << "Device responded" << xpcc::endl;
expander::Backlight::set();
// Initialize twice as some display are not initialised after first try.
display.initialize();
display.initialize();
// Fill CGRAM
display.writeCGRAM(0, cgA);
display.writeCGRAM(1, cgB);
display.setCursor(0, 0);
// Write the standard welcome message ;-)
display << "Hello xpcc.io **\n";
// Write two special characters in second row
display.setCursor(0, 1);
display.write(0);
display.write(1);
counter = 0;
while (true)
{
display.setCursor(3, 1);
display << counter << " ";
counter++;
this->timeout.restart(1000);
PT_WAIT_UNTIL(this->timeout.isExpired());
}
PT_END();
}
private:
xpcc::ShortTimeout timeout;
uint8_t counter;
// Bitmaps for special characters
uint8_t cgA[8] = {0, 0b00100, 0b01110, 0b11111, 0b11111, 0b01110, 0b00100, 0};
uint8_t cgB[8] = {0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55};
};
ThreadOne one;
int
main()
{
Board::initialize();
GpioOutputA2::connect(Usart2::Tx);
Usart2::initialize<Board::systemClock, xpcc::Uart::B115200>(10);
XPCC_LOG_INFO << "\n\nWelcome to HD44780 I2C demo!\n\n";
GpioB11::connect(MyI2cMaster::Sda, Gpio::InputType::PullUp);
GpioB10::connect(MyI2cMaster::Scl, Gpio::InputType::PullUp);
MyI2cMaster::initialize<Board::systemClock, 100000>();
xpcc::ShortPeriodicTimer tmr(500);
while(true)
{
one.update();
if (tmr.execute()) {
Board::LedOrange::toggle();
}
}
}
<commit_msg>Example: F4: Set default pin states.<commit_after>
/**
* Example to demonstrate a XPCC driver for HD44780 displays,
* including displays with I2C PCA8574 port expanders.
*
* This example uses I2cMaster2 of STM32F407
*
* SDA PB11
* SCL PB10
*
* GND and +5V are connected to the the port expander of the display.
*
*/
#include <xpcc/architecture.hpp>
#include <xpcc/driver/display.hpp>
#include <xpcc/io/iostream.hpp>
#include <xpcc/debug/logger.hpp>
#include <xpcc/driver/gpio/pca8574.hpp>
#include "../../stm32f4_discovery.hpp"
xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device;
xpcc::IOStream stream(device);
// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(device);
xpcc::log::Logger xpcc::log::info(device);
xpcc::log::Logger xpcc::log::warning(device);
xpcc::log::Logger xpcc::log::error(device);
// Set the log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::DEBUG
using namespace Board;
typedef I2cMaster2 MyI2cMaster;
// typedef xpcc::SoftwareI2cMaster<GpioB10, GpioB11> MyI2cMaster;
// define the pins used by the LCD when not using a port expander
namespace lcd
{
typedef GpioOutputC7 Backlight;
typedef GpioOutputC6 E;
typedef GpioOutputC5 Rw;
typedef GpioOutputC4 Rs;
// note: an 8bit data port
typedef GpioPort<GpioOutputC0, 8> Data8Bit;
// and a 4 bit data port
typedef GpioPort<GpioOutputC4, 4> Data4Bit;
}
typedef xpcc::Pca8574<MyI2cMaster> GpioExpander;
GpioExpander gpioExpander;
namespace expander
{
// Instances for each pin
typedef GpioExpander::P0< gpioExpander > Rs;
typedef GpioExpander::P1< gpioExpander > Rw;
typedef GpioExpander::P2< gpioExpander > E;
typedef GpioExpander::P3< gpioExpander > Backlight;
typedef GpioExpander::P4< gpioExpander > Pin4;
typedef GpioExpander::P5< gpioExpander > Pin5;
typedef GpioExpander::P6< gpioExpander > Pin6;
// you can also declare the pin like this, however it is too verbose
typedef xpcc::GpioExpanderPin< GpioExpander, gpioExpander, GpioExpander::Pin::P7 > Pin7;
// typedef GpioExpander::P7< gpioExpander > Pin7;
// Form a GpioPort out of four single pins.
typedef GpioExpander::Port< gpioExpander,
GpioExpander::Pin::P4, 4 > Data4BitGpio;
// You can also use SoftwareGpioPort, note however, that every pin is set separately,
// so this requires four times as many bus accesses as the optimized version above.
// typedef xpcc::SoftwareGpioPort<Pin7, Pin6, Pin5, Pin4> Data4BitGpio;
}
// You can choose either port width simply by using it.
// The driver will handle it internally.
// create a LCD object with an 8bit data port
// xpcc::Hd44780< lcd::Data8Bit, lcd::Rw, lcd::Rs, lcd::E > display(20, 4);
// create a LCD object with an 4bit data port
// xpcc::Hd44780< lcd::Data4Bit, lcd::Rw, lcd::Rs, lcd::E > display(20, 4);
// create a LCD object with an 4bit data port at a I2C Gpio port expander
xpcc::Hd44780< expander::Data4BitGpio, expander::Rw, expander::Rs, expander::E > display(20, 4);
class ThreadOne : public xpcc::pt::Protothread
{
public:
ThreadOne()
{
}
bool
update()
{
PT_BEGIN();
XPCC_LOG_DEBUG << "Ping the device from ThreadOne" << xpcc::endl;
// ping the device until it responds
while (true)
{
// we wait until the task started
if (PT_CALL(gpioExpander.ping())) {
break;
}
XPCC_LOG_DEBUG << "Device did not respond" << xpcc::endl;
// otherwise, try again in 100ms
this->timeout.restart(1000);
PT_WAIT_UNTIL(this->timeout.isExpired());
}
XPCC_LOG_DEBUG << "Device responded" << xpcc::endl;
// Actually, this is not needed because of hardware defaults, but this is better style.
expander::Backlight::setOutput();
expander::Data4BitGpio::setOutput();
// Actually, this is not needed because of initialze of display driver.
expander::Rs::setOutput();
expander::Rw::setOutput();
expander::E::setOutput();
// Actually, this is not needed because of hardware defaults.
expander::Backlight::set();
// Initialize twice as some display are not initialised after first try.
display.initialize();
display.initialize();
// Fill CGRAM
display.writeCGRAM(0, cgA);
display.writeCGRAM(1, cgB);
display.setCursor(0, 0);
// Write the standard welcome message ;-)
display << "Hello xpcc.io **\n";
// Write two special characters in second row
display.setCursor(0, 1);
display.write(0);
display.write(1);
counter = 0;
while (true)
{
display.setCursor(3, 1);
display << counter << " ";
counter++;
this->timeout.restart(1000);
PT_WAIT_UNTIL(this->timeout.isExpired());
}
PT_END();
}
private:
xpcc::ShortTimeout timeout;
uint8_t counter;
// Bitmaps for special characters
uint8_t cgA[8] = {0, 0b00100, 0b01110, 0b11111, 0b11111, 0b01110, 0b00100, 0};
uint8_t cgB[8] = {0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55};
};
ThreadOne one;
int
main()
{
Board::initialize();
GpioOutputA2::connect(Usart2::Tx);
Usart2::initialize<Board::systemClock, xpcc::Uart::B115200>(10);
XPCC_LOG_INFO << "\n\nWelcome to HD44780 I2C demo!\n\n";
GpioB11::connect(MyI2cMaster::Sda, Gpio::InputType::PullUp);
GpioB10::connect(MyI2cMaster::Scl, Gpio::InputType::PullUp);
MyI2cMaster::initialize<Board::systemClock, 100000>();
xpcc::ShortPeriodicTimer tmr(500);
while(true)
{
one.update();
if (tmr.execute()) {
Board::LedOrange::toggle();
}
}
}
<|endoftext|> |
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_MATH_FNV_HPP
#define OUZEL_MATH_FNV_HPP
#include <cstdint>
namespace ouzel
{
namespace fnv
{
template <typename T> constexpr T prime;
template <typename T> constexpr T offsetBasis;
template <> constexpr uint32_t prime<uint32_t> = 16777619u;
template <> constexpr uint32_t offsetBasis<uint32_t> = 2166136261u;
template <> constexpr uint64_t prime<uint64_t> = 1099511628211u;
template <> constexpr uint64_t offsetBasis<uint64_t> = 14695981039346656037u;
// Fowler / Noll / Vo (FNV) hash
template <typename Result, typename Value>
constexpr Result hash(const Value value, size_t i = 0, Result result = offsetBasis<Result>) noexcept
{
return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * prime<Result>) ^ ((value >> (i * 8)) & 0xFF)) : result;
}
} // namespace fnv
} // namespace ouzel
#endif // OUZEL_MATH_FNV_HPP
<commit_msg>Add FNV constants to inline namespace<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_MATH_FNV_HPP
#define OUZEL_MATH_FNV_HPP
#include <cstdint>
namespace ouzel
{
namespace fnv
{
inline namespace detail
{
template <typename T> constexpr T prime;
template <typename T> constexpr T offsetBasis;
template <> constexpr uint32_t prime<uint32_t> = 16777619u;
template <> constexpr uint32_t offsetBasis<uint32_t> = 2166136261u;
template <> constexpr uint64_t prime<uint64_t> = 1099511628211u;
template <> constexpr uint64_t offsetBasis<uint64_t> = 14695981039346656037u;
}
// Fowler / Noll / Vo (FNV) hash
template <typename Result, typename Value>
constexpr Result hash(const Value value, size_t i = 0, Result result = offsetBasis<Result>) noexcept
{
return (i < sizeof(Value)) ? hash<Result>(value, i + 1, (result * prime<Result>) ^ ((value >> (i * 8)) & 0xFF)) : result;
}
} // namespace fnv
} // namespace ouzel
#endif // OUZEL_MATH_FNV_HPP
<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright (c) 2019, Acer Yun-Tse Yang All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <type_traits>
#include <utility>
namespace sqlite3cpp {
namespace detail {
template <int>
struct placeholder_tmpl {};
template<int... Ints>
using indexes = std::integer_sequence<int, Ints...>;
template<int Max>
using make_indexes_t = std::make_integer_sequence<int, Max>;
}
} // namespace sqlite3cpp::detail
// custome placeholders
namespace std {
template <int N>
struct is_placeholder<sqlite3cpp::detail::placeholder_tmpl<N>>
: integral_constant<int, N + 1> {};
}
namespace sqlite3cpp {
namespace detail {
/**
* tuple enumerate
*/
template <class F, class Tuple, int... I>
constexpr decltype(auto) enumerate_impl(F &&f, Tuple &&t,
std::integer_sequence<int, I...>) {
return (
std::invoke(std::forward<F>(f), I, std::get<I>(std::forward<Tuple>(t))),
...);
}
template <class F, class Tuple>
constexpr decltype(auto) enumerate(F &&f, Tuple &&t) {
return detail::enumerate_impl(
std::forward<F>(f), std::forward<Tuple>(t),
std::make_integer_sequence<
int, std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
/**
* Helpers for retrieve column values.
*/
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int &val) {
val = sqlite3_column_int(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int64_t &val) {
val = sqlite3_column_int64(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
double &val) {
val = sqlite3_column_double(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string &val) {
char const* res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
throw error(ec);
}
val.assign(res, sqlite3_column_bytes(stmt, index));
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string_view &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
throw error(ec);
}
val = std::string_view{
(char const *)sqlite3_column_text(stmt, index),
(std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string> &val) {
char const* res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
val.reset();
}
val = std::string{res,
(std::string::size_type)sqlite3_column_bytes(stmt, index)};
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string_view> &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
val.reset();
}
val = std::string_view{
res, (std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
}
/*
* Helpers for binding values to sqlite3_stmt.
*/
inline void bind_to_stmt(sqlite3_stmt *stmt, int i) {}
inline int bind_val(sqlite3_stmt *stmt, int index, int val) {
return sqlite3_bind_int(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, double val) {
return sqlite3_bind_double(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string const &val) {
return sqlite3_bind_text(stmt, index, val.c_str(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string_view const &val) {
return sqlite3_bind_text(stmt, index, val.data(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, char const *val) {
return sqlite3_bind_text(stmt, index, val, -1, SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::nullptr_t _) {
return sqlite3_bind_null(stmt, index);
}
template <typename T, typename... Args>
void bind_to_stmt(sqlite3_stmt *stmt, int index, T &&val, Args &&... args) {
int ec = 0;
if (0 != (ec = bind_val(stmt, index, std::forward<T>(val)))) throw error(ec);
bind_to_stmt(stmt, index + 1, std::forward<Args>(args)...);
}
/**
* Helpers for converting value from sqlite3_value.
*/
template <typename T>
struct Type {};
inline int get(Type<int>, sqlite3_value **v, int const index) {
return sqlite3_value_int(v[index]);
}
inline int64_t get(Type<int64_t>, sqlite3_value **v, int const index) {
return sqlite3_value_int64(v[index]);
}
inline double get(Type<double>, sqlite3_value **v, int const index) {
return sqlite3_value_double(v[index]);
}
inline std::string get(Type<std::string>, sqlite3_value **v, int const index) {
return std::string((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
inline std::string_view get(Type<std::string_view>, sqlite3_value **v, int const index) {
return std::string_view((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
/**
* Helpers for setting result of scalar functions.
*/
inline void result(int val, sqlite3_context *ctx) {
sqlite3_result_int(ctx, val);
}
inline void result(int64_t val, sqlite3_context *ctx) {
sqlite3_result_int64(ctx, val);
}
inline void result(double val, sqlite3_context *ctx) {
sqlite3_result_double(ctx, val);
}
inline void result(std::string const &val, sqlite3_context *ctx) {
sqlite3_result_text(ctx, val.c_str(), val.size(), SQLITE_TRANSIENT);
}
/**
* Magic for typesafe invoking lambda/std::function from sqlite3
* (registered via sqlite3_create_function).
*/
template <typename R, typename... Args, int... Is>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv,
indexes<Is...>) {
// TODO Check argc
// Expand argv per index
return func(get(Type<Args>{}, argv, Is)...);
}
template <typename R, typename... Args>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv) {
return invoke(func, argc, argv, make_indexes_t<sizeof...(Args)>{});
}
template <typename R, typename... Args>
database::xfunc_t make_invoker(std::function<R(Args...)> &&func) {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
result(invoke(func, argc, argv), ctx);
};
}
template <typename... Args>
database::xfunc_t make_invoker(std::function<void(Args...)> &&func) {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
invoke(func, argc, argv);
};
}
/**
* Function traits for supporting lambda.
*/
// For generic types that are functors, delegate to its 'operator()'
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
// for pointers to member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for pointers to const member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...) const> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for function pointers
template <typename R, typename... Args>
struct function_traits<R (*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
/**
* Member function binder helpers (auto expand by passed function prototype)
*/
template <typename F, typename C, int... Is>
typename function_traits<F>::f_type bind_this(F f, C *this_, indexes<Is...>) {
return std::bind(f, this_, placeholder_tmpl<Is>{}...);
}
template <typename F, typename C>
typename function_traits<F>::f_type bind_this(F f, C *this_) {
using traits = function_traits<F>;
return bind_this(f, this_, make_indexes_t<traits::arity>{});
}
}
} // namespace sqlite3cpp::detail
namespace sqlite3cpp {
/**
* row impl
*/
template <typename... Cols>
std::tuple<Cols...> row::to() const {
// TODO: Report errors
std::tuple<Cols...> result;
detail::enumerate(
[this](int index, auto &&... tuple_value) {
(detail::get_col_val_aux(m_stmt, m_db, index, tuple_value), ...);
},
result);
return result;
}
/**
* cursor impl
*/
template <typename... Args>
cursor &cursor::execute(std::string const &sql, Args &&... args) {
sqlite3_stmt *stmt = 0;
int ec = 0;
if (0 != (ec = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &stmt, 0)))
throw error(ec);
m_stmt.reset(stmt);
detail::bind_to_stmt(m_stmt.get(), 1, std::forward<Args>(args)...);
step();
return *this;
}
/**
* database impl
*/
template <typename... Args>
cursor database::execute(std::string const &sql, Args &&... args) {
cursor c = make_cursor();
c.execute(sql, std::forward<Args>(args)...);
return c;
}
template <typename FUNC>
void database::create_scalar(std::string const &name, FUNC func, int flags) {
using traits = detail::function_traits<FUNC>;
auto *xfunc_ptr =
new xfunc_t(detail::make_invoker(typename traits::f_type(func)));
int ec = 0;
if (0 != (ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)xfunc_ptr, &database::forward, 0, 0, &dispose))) {
delete xfunc_ptr;
throw error(ec);
}
}
template <typename AG>
void database::create_aggregate(std::string const &name, int flags) {
using detail::make_invoker;
using detail::bind_this;
using detail::result;
using traits = detail::function_traits<decltype(&AG::step)>;
aggregate_wrapper_t *wrapper = new aggregate_wrapper_t;
AG *inst = new AG;
wrapper->reset = [inst]() { *inst = AG(); };
wrapper->release = [inst]() { delete inst; };
wrapper->step = make_invoker(bind_this(&AG::step, inst));
wrapper->fin = [inst](sqlite3_context *ctx) {
result(inst->finalize(), ctx);
};
int ec = 0;
if (0 != (ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)wrapper, 0, &step_ag, &final_ag, &dispose_ag))) {
delete inst;
delete wrapper;
throw error(ec);
}
}
} // namespace sqlite3cpp
<commit_msg>Remove unnecessary unpack.<commit_after>/*****************************************************************************
* Copyright (c) 2019, Acer Yun-Tse Yang All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <type_traits>
#include <utility>
namespace sqlite3cpp {
namespace detail {
template <int>
struct placeholder_tmpl {};
template<int... Ints>
using indexes = std::integer_sequence<int, Ints...>;
template<int Max>
using make_indexes_t = std::make_integer_sequence<int, Max>;
}
} // namespace sqlite3cpp::detail
// custome placeholders
namespace std {
template <int N>
struct is_placeholder<sqlite3cpp::detail::placeholder_tmpl<N>>
: integral_constant<int, N + 1> {};
}
namespace sqlite3cpp {
namespace detail {
/**
* tuple enumerate
*/
template <class F, class Tuple, int... I>
constexpr decltype(auto) enumerate_impl(F &&f, Tuple &&t,
std::integer_sequence<int, I...>) {
return (
std::invoke(std::forward<F>(f), I, std::get<I>(std::forward<Tuple>(t))),
...);
}
template <class F, class Tuple>
constexpr decltype(auto) enumerate(F &&f, Tuple &&t) {
return detail::enumerate_impl(
std::forward<F>(f), std::forward<Tuple>(t),
std::make_integer_sequence<
int, std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
/**
* Helpers for retrieve column values.
*/
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int &val) {
val = sqlite3_column_int(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
int64_t &val) {
val = sqlite3_column_int64(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *, int index,
double &val) {
val = sqlite3_column_double(stmt, index);
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string &val) {
char const* res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
throw error(ec);
}
val.assign(res, sqlite3_column_bytes(stmt, index));
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::string_view &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
throw error(ec);
}
val = std::string_view{
(char const *)sqlite3_column_text(stmt, index),
(std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string> &val) {
char const* res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
val.reset();
}
val = std::string{res,
(std::string::size_type)sqlite3_column_bytes(stmt, index)};
}
inline void get_col_val_aux(sqlite3_stmt *stmt, sqlite3 *db, int index,
std::optional<std::string_view> &val) {
char const *res = (char const *)sqlite3_column_text(stmt, index);
if (!res) {
int ec = sqlite3_errcode(db);
if (ec != SQLITE_OK)
val.reset();
}
val = std::string_view{
res, (std::string_view::size_type)sqlite3_column_bytes(stmt, index)};
}
/*
* Helpers for binding values to sqlite3_stmt.
*/
inline void bind_to_stmt(sqlite3_stmt *stmt, int i) {}
inline int bind_val(sqlite3_stmt *stmt, int index, int val) {
return sqlite3_bind_int(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, double val) {
return sqlite3_bind_double(stmt, index, val);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string const &val) {
return sqlite3_bind_text(stmt, index, val.c_str(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::string_view const &val) {
return sqlite3_bind_text(stmt, index, val.data(), val.size(), SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, char const *val) {
return sqlite3_bind_text(stmt, index, val, -1, SQLITE_STATIC);
}
inline int bind_val(sqlite3_stmt *stmt, int index, std::nullptr_t _) {
return sqlite3_bind_null(stmt, index);
}
template <typename T, typename... Args>
void bind_to_stmt(sqlite3_stmt *stmt, int index, T &&val, Args &&... args) {
int ec = 0;
if (0 != (ec = bind_val(stmt, index, std::forward<T>(val)))) throw error(ec);
bind_to_stmt(stmt, index + 1, std::forward<Args>(args)...);
}
/**
* Helpers for converting value from sqlite3_value.
*/
template <typename T>
struct Type {};
inline int get(Type<int>, sqlite3_value **v, int const index) {
return sqlite3_value_int(v[index]);
}
inline int64_t get(Type<int64_t>, sqlite3_value **v, int const index) {
return sqlite3_value_int64(v[index]);
}
inline double get(Type<double>, sqlite3_value **v, int const index) {
return sqlite3_value_double(v[index]);
}
inline std::string get(Type<std::string>, sqlite3_value **v, int const index) {
return std::string((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
inline std::string_view get(Type<std::string_view>, sqlite3_value **v, int const index) {
return std::string_view((char const *)sqlite3_value_text(v[index]),
(size_t)sqlite3_value_bytes(v[index]));
}
/**
* Helpers for setting result of scalar functions.
*/
inline void result(int val, sqlite3_context *ctx) {
sqlite3_result_int(ctx, val);
}
inline void result(int64_t val, sqlite3_context *ctx) {
sqlite3_result_int64(ctx, val);
}
inline void result(double val, sqlite3_context *ctx) {
sqlite3_result_double(ctx, val);
}
inline void result(std::string const &val, sqlite3_context *ctx) {
sqlite3_result_text(ctx, val.c_str(), val.size(), SQLITE_TRANSIENT);
}
/**
* Magic for typesafe invoking lambda/std::function from sqlite3
* (registered via sqlite3_create_function).
*/
template <typename R, typename... Args, int... Is>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv,
indexes<Is...>) {
// TODO Check argc
// Expand argv per index
return func(get(Type<Args>{}, argv, Is)...);
}
template <typename R, typename... Args>
R invoke(std::function<R(Args...)> func, int argc, sqlite3_value **argv) {
return invoke(func, argc, argv, make_indexes_t<sizeof...(Args)>{});
}
template <typename R, typename... Args>
database::xfunc_t make_invoker(std::function<R(Args...)> &&func) {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
result(invoke(func, argc, argv), ctx);
};
}
template <typename... Args>
database::xfunc_t make_invoker(std::function<void(Args...)> &&func) {
return [func](sqlite3_context *ctx, int argc, sqlite3_value **argv) {
invoke(func, argc, argv);
};
}
/**
* Function traits for supporting lambda.
*/
// For generic types that are functors, delegate to its 'operator()'
template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {};
// for pointers to member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for pointers to const member function
template <typename C, typename R, typename... Args>
struct function_traits<R (C::*)(Args...) const> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
// for function pointers
template <typename R, typename... Args>
struct function_traits<R (*)(Args...)> {
typedef std::function<R(Args...)> f_type;
static const size_t arity = sizeof...(Args);
};
/**
* Member function binder helpers (auto expand by passed function prototype)
*/
template <typename F, typename C, int... Is>
typename function_traits<F>::f_type bind_this(F f, C *this_, indexes<Is...>) {
return std::bind(f, this_, placeholder_tmpl<Is>{}...);
}
template <typename F, typename C>
typename function_traits<F>::f_type bind_this(F f, C *this_) {
using traits = function_traits<F>;
return bind_this(f, this_, make_indexes_t<traits::arity>{});
}
}
} // namespace sqlite3cpp::detail
namespace sqlite3cpp {
/**
* row impl
*/
template <typename... Cols>
std::tuple<Cols...> row::to() const {
// TODO: Report errors
std::tuple<Cols...> result;
detail::enumerate(
[this](int index, auto &&tuple_value) {
detail::get_col_val_aux(m_stmt, m_db, index, tuple_value);
},
result);
return result;
}
/**
* cursor impl
*/
template <typename... Args>
cursor &cursor::execute(std::string const &sql, Args &&... args) {
sqlite3_stmt *stmt = 0;
int ec = 0;
if (0 != (ec = sqlite3_prepare_v2(m_db, sql.c_str(), sql.size(), &stmt, 0)))
throw error(ec);
m_stmt.reset(stmt);
detail::bind_to_stmt(m_stmt.get(), 1, std::forward<Args>(args)...);
step();
return *this;
}
/**
* database impl
*/
template <typename... Args>
cursor database::execute(std::string const &sql, Args &&... args) {
cursor c = make_cursor();
c.execute(sql, std::forward<Args>(args)...);
return c;
}
template <typename FUNC>
void database::create_scalar(std::string const &name, FUNC func, int flags) {
using traits = detail::function_traits<FUNC>;
auto *xfunc_ptr =
new xfunc_t(detail::make_invoker(typename traits::f_type(func)));
int ec = 0;
if (0 != (ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)xfunc_ptr, &database::forward, 0, 0, &dispose))) {
delete xfunc_ptr;
throw error(ec);
}
}
template <typename AG>
void database::create_aggregate(std::string const &name, int flags) {
using detail::make_invoker;
using detail::bind_this;
using detail::result;
using traits = detail::function_traits<decltype(&AG::step)>;
aggregate_wrapper_t *wrapper = new aggregate_wrapper_t;
AG *inst = new AG;
wrapper->reset = [inst]() { *inst = AG(); };
wrapper->release = [inst]() { delete inst; };
wrapper->step = make_invoker(bind_this(&AG::step, inst));
wrapper->fin = [inst](sqlite3_context *ctx) {
result(inst->finalize(), ctx);
};
int ec = 0;
if (0 != (ec = sqlite3_create_function_v2(
m_db.get(), name.c_str(), (int)traits::arity, flags,
(void *)wrapper, 0, &step_ag, &final_ag, &dispose_ag))) {
delete inst;
delete wrapper;
throw error(ec);
}
}
} // namespace sqlite3cpp
<|endoftext|> |
<commit_before>
#include "../ccrrt/CBiRRT.h"
using namespace ccrrt;
using namespace Eigen;
CBiRRT::CBiRRT(int maxTreeSize, double maxStepSize, double collisionCheckStepSize) :
ConstrainedRRT(maxTreeSize, maxStepSize, collisionCheckStepSize)
{
_projected_constraints = NULL;
max_projection_attempts = 10;
gamma = 0.05;
stuck_distance = maxStepSize/5;
}
void CBiRRT::setProjectedConstraints(Constraint *constraints)
{
_projected_constraints = constraints;
}
bool CBiRRT::constraintProjector(JointConfig &config, const JointConfig &parentConfig)
{
if(_projected_constraints==NULL)
return true;
size_t count=0;
VectorXd gradient(_domainSize);
Constraint::validity_t result = _projected_constraints->getCostGradient(gradient, config);
while(result == Constraint::INVALID)
{
if(!checkIfInRange(config, parentConfig))
return false;
++count;
if(count > max_projection_attempts)
return false;
config = config - gamma*gradient;
result = _projected_constraints->getCostGradient(gradient, config);
if( (config-parentConfig).norm() < stuck_distance )
return false;
}
return true;
}
RRT_Result_t CBiRRT::growTrees()
{
RRT_Result_t check = checkStatus();
if(check != RRT_NOT_FINISHED)
return check;
JointConfig refConfig(_domainSize);
for(size_t i=0; i<trees.size(); ++i)
{
if(checkIfMaxed(i))
continue;
randomizeConfig(refConfig);
RRTNode* node;
if( trees[i]->getClosestNode(node, refConfig) < _numPrecThresh )
continue;
attemptConnect(node, refConfig, i);
if(node == NULL)
continue;
if(treeTypeTracker[i] == RRT_START_TREE)
{
RRTNode* connection = lookForTreeConnection(node, RRT_GOAL_TREE);
if(connection != NULL)
{
constructSolution(node, connection);
return RRT_SOLVED;
}
}
else if(treeTypeTracker[i] == RRT_GOAL_TREE)
{
RRTNode* connection = lookForTreeConnection(node, RRT_START_TREE);
if(connection != NULL)
{
constructSolution(connection, node);
return RRT_SOLVED;
}
}
}
++_iterations;
return RRT_NOT_FINISHED;
}
<commit_msg>checking limits<commit_after>
#include "../ccrrt/CBiRRT.h"
using namespace ccrrt;
using namespace Eigen;
CBiRRT::CBiRRT(int maxTreeSize, double maxStepSize, double collisionCheckStepSize) :
ConstrainedRRT(maxTreeSize, maxStepSize, collisionCheckStepSize)
{
_projected_constraints = NULL;
max_projection_attempts = 10;
gamma = 0.05;
stuck_distance = maxStepSize/5;
}
void CBiRRT::setProjectedConstraints(Constraint *constraints)
{
_projected_constraints = constraints;
}
bool CBiRRT::constraintProjector(JointConfig &config, const JointConfig &parentConfig)
{
if(_projected_constraints==NULL)
return true;
size_t count=0;
VectorXd gradient(_domainSize);
Constraint::validity_t result = _projected_constraints->getCostGradient(gradient, config);
while(result == Constraint::INVALID)
{
if(!checkIfInRange(config, parentConfig))
return false;
++count;
if(count > max_projection_attempts)
return false;
config = config - gamma*gradient;
for(size_t i=0; i<_domainSize; ++i)
{
if( config[i] < minConfig[i] || maxConfig[i] < config[i] )
return false;
}
result = _projected_constraints->getCostGradient(gradient, config);
if( (config-parentConfig).norm() < stuck_distance )
return false;
}
return true;
}
RRT_Result_t CBiRRT::growTrees()
{
RRT_Result_t check = checkStatus();
if(check != RRT_NOT_FINISHED)
return check;
JointConfig refConfig(_domainSize);
for(size_t i=0; i<trees.size(); ++i)
{
if(checkIfMaxed(i))
continue;
randomizeConfig(refConfig);
RRTNode* node;
if( trees[i]->getClosestNode(node, refConfig) < _numPrecThresh )
continue;
attemptConnect(node, refConfig, i);
if(node == NULL)
continue;
if(treeTypeTracker[i] == RRT_START_TREE)
{
RRTNode* connection = lookForTreeConnection(node, RRT_GOAL_TREE);
if(connection != NULL)
{
constructSolution(node, connection);
return RRT_SOLVED;
}
}
else if(treeTypeTracker[i] == RRT_GOAL_TREE)
{
RRTNode* connection = lookForTreeConnection(node, RRT_START_TREE);
if(connection != NULL)
{
constructSolution(connection, node);
return RRT_SOLVED;
}
}
}
++_iterations;
return RRT_NOT_FINISHED;
}
<|endoftext|> |
<commit_before>/*
* DMXPro.cpp
*
* Created by Andrea Cuius
* The MIT License (MIT)
* Copyright (c) 2014 Nocte Studio Ltd.
*
* www.nocte.co.uk
*
*/
#include "cinder/app/App.h"
#include "cinder/Utilities.h"
#include <iostream>
#include "DMXPro.h"
#include "cinder/Log.h"
using namespace ci;
using namespace ci::app;
using namespace std;
const auto DMXPRO_START_MSG = 0x7E; // Start of message delimiter
const auto DMXPRO_END_MSG = 0xE7; // End of message delimiter
const auto DMXPRO_SEND_LABEL = 6; // Output Only Send DMX Packet Request
const auto DMXPRO_BAUD_RATE = 57600; // virtual COM doesn't control the usb, this is just a dummy value
const auto DMXPRO_FRAME_RATE = 35; // dmx send frame rate
const auto DMXPRO_START_CODE = 0;
const auto BodySize = size_t(512);
const auto DataSize = BodySize + 1; // account for start code in message size
const auto MessageHeader = std::array<uint8_t, 5> {
DMXPRO_START_MSG,
DMXPRO_SEND_LABEL,
(uint8_t)(DataSize & 0xFF), // data length least significant byte
(uint8_t)((DataSize >> 8) & 0xFF), // data length most significant byte
DMXPRO_START_CODE
};
const auto MessageFooter = std::array<uint8_t, 1> {
DMXPRO_END_MSG
};
const auto MessageSize = BodySize + MessageHeader.size() + MessageFooter.size();
DMXPro::DMXPro()
{
mTargetFrameTime = std::chrono::milliseconds(1000 / DMXPRO_FRAME_RATE);
mBody.assign(512, 0);
}
DMXPro::~DMXPro()
{
CI_LOG_I("Shutting down DMX connection: " << mSerialDeviceName);
stopLoop();
// For now, turn out the lights as the previous implementation did so.
// In future, perhaps it is better to let the user specify what to do.
fillBuffer(0);
writeData();
closeConnection();
}
void DMXPro::closeConnection() {
stopLoop();
if (mSerial) {
mSerial->flush();
mSerial.reset();
}
}
void DMXPro::startLoop() {
mRunSendDataThread = true;
mSendDataThread = std::thread(&DMXPro::dataSendLoop, this);
}
void DMXPro::stopLoop() {
mRunSendDataThread = false;
if (mSendDataThread.joinable()) {
mSendDataThread.join();
}
}
bool DMXPro::connect(const std::string &deviceName)
{
closeConnection();
mSerialDeviceName = deviceName;
try
{
const Serial::Device dev = Serial::findDeviceByNameContains(mSerialDeviceName);
mSerial = Serial::create( dev, DMXPRO_BAUD_RATE );
startLoop();
return true;
}
catch(const std::exception &exc)
{
CI_LOG_E("Error initializing DMX device: " << exc.what());
return false;
}
}
void DMXPro::dataSendLoop()
{
ci::ThreadSetup threadSetup;
CI_LOG_I("Starting DMX loop.");
mRunSendDataThread = true;
auto before = std::chrono::high_resolution_clock::now();
while (mSerial && mRunSendDataThread)
{
writeData();
auto after = std::chrono::high_resolution_clock::now();
auto actualFrameTime = after - before;
before = after;
std::this_thread::sleep_for(mTargetFrameTime - actualFrameTime);
}
CI_LOG_I("Exiting DMX loop.");
}
void DMXPro::writeData()
{
std::lock_guard<std::mutex> lock(mBodyMutex);
if (mSerial) {
mSerial->writeBytes(MessageHeader.data(), MessageHeader.size());
mSerial->writeBytes(mBody.data(), mBody.size());
mSerial->writeBytes(MessageFooter.data(), MessageFooter.size());
}
}
void DMXPro::bufferData(const uint8_t *data, size_t size)
{
std::lock_guard<std::mutex> lock(mBodyMutex);
size = std::min(size, mBody.size());
std::memcpy(mBody.data(), data, size);
}
void DMXPro::fillBuffer(uint8_t value)
{
std::lock_guard<std::mutex> lock(mBodyMutex);
std::memset(mBody.data(), value, mBody.size());
}
#pragma mark - DMX Color Buffer
DMXColorBuffer::DMXColorBuffer()
{
_data.fill(0);
}
void DMXColorBuffer::setValue(uint8_t value, size_t channel) {
channel = std::min(channel, _data.size() - 1);
_data[channel] = value;
}
void DMXColorBuffer::setValue(const ci::Color8u &color, size_t channel) {
channel = std::min(channel, _data.size() - 3);
_data[channel] = color.r;
_data[channel + 1] = color.g;
_data[channel + 2] = color.b;
}
<commit_msg>Remove constants only used in header.<commit_after>/*
* DMXPro.cpp
*
* Created by Andrea Cuius
* The MIT License (MIT)
* Copyright (c) 2014 Nocte Studio Ltd.
*
* www.nocte.co.uk
*
*/
#include "cinder/app/App.h"
#include "cinder/Utilities.h"
#include <iostream>
#include "DMXPro.h"
#include "cinder/Log.h"
using namespace ci;
using namespace ci::app;
using namespace std;
const auto DMXProDummyBaudRate = 57600;
const auto DMXProFrameRate = 35;
const auto BodySize = size_t(512);
const auto DataSize = BodySize + 1; // account for start code in message size
const auto MessageHeader = std::array<uint8_t, 5> {
0x7E, // Start of message
6, // Output Only Send DMX Packet Request
(uint8_t)(DataSize & 0xFF), // data length least significant byte
(uint8_t)((DataSize >> 8) & 0xFF), // data length most significant byte
0 // start code for data
};
const auto MessageFooter = std::array<uint8_t, 1> {
0xE7 // End of message
};
const auto MessageSize = BodySize + MessageHeader.size() + MessageFooter.size();
DMXPro::DMXPro()
{
mTargetFrameTime = std::chrono::milliseconds(1000 / DMXProFrameRate);
mBody.assign(BodySize, 0);
}
DMXPro::~DMXPro()
{
CI_LOG_I("Shutting down DMX connection: " << mSerialDeviceName);
stopLoop();
// For now, turn out the lights as the previous implementation did so.
// In future, perhaps it is better to let the user specify what to do.
fillBuffer(0);
writeData();
closeConnection();
}
void DMXPro::closeConnection() {
stopLoop();
if (mSerial) {
mSerial->flush();
mSerial.reset();
}
}
void DMXPro::startLoop() {
mRunSendDataThread = true;
mSendDataThread = std::thread(&DMXPro::dataSendLoop, this);
}
void DMXPro::stopLoop() {
mRunSendDataThread = false;
if (mSendDataThread.joinable()) {
mSendDataThread.join();
}
}
bool DMXPro::connect(const std::string &deviceName)
{
closeConnection();
mSerialDeviceName = deviceName;
try
{
const Serial::Device dev = Serial::findDeviceByNameContains(mSerialDeviceName);
mSerial = Serial::create(dev, DMXProDummyBaudRate);
startLoop();
return true;
}
catch(const std::exception &exc)
{
CI_LOG_E("Error initializing DMX device: " << exc.what());
return false;
}
}
void DMXPro::dataSendLoop()
{
ci::ThreadSetup threadSetup;
CI_LOG_I("Starting DMX loop.");
mRunSendDataThread = true;
auto before = std::chrono::high_resolution_clock::now();
while (mSerial && mRunSendDataThread)
{
writeData();
auto after = std::chrono::high_resolution_clock::now();
auto actualFrameTime = after - before;
before = after;
std::this_thread::sleep_for(mTargetFrameTime - actualFrameTime);
}
CI_LOG_I("Exiting DMX loop.");
}
void DMXPro::writeData()
{
std::lock_guard<std::mutex> lock(mBodyMutex);
if (mSerial) {
mSerial->writeBytes(MessageHeader.data(), MessageHeader.size());
mSerial->writeBytes(mBody.data(), mBody.size());
mSerial->writeBytes(MessageFooter.data(), MessageFooter.size());
}
}
void DMXPro::bufferData(const uint8_t *data, size_t size)
{
std::lock_guard<std::mutex> lock(mBodyMutex);
size = std::min(size, mBody.size());
std::memcpy(mBody.data(), data, size);
}
void DMXPro::fillBuffer(uint8_t value)
{
std::lock_guard<std::mutex> lock(mBodyMutex);
std::memset(mBody.data(), value, mBody.size());
}
#pragma mark - DMX Color Buffer
DMXColorBuffer::DMXColorBuffer()
{
_data.fill(0);
}
void DMXColorBuffer::setValue(uint8_t value, size_t channel) {
channel = std::min(channel, _data.size() - 1);
_data[channel] = value;
}
void DMXColorBuffer::setValue(const ci::Color8u &color, size_t channel) {
channel = std::min(channel, _data.size() - 3);
_data[channel] = color.r;
_data[channel + 1] = color.g;
_data[channel + 2] = color.b;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstdlib>
#include "Config.h"
#include "Device.h"
#include "Filesystem.h"
#include "InputManager.h"
#include "Log.h"
#include "OS.h"
#include "Renderer.h"
#include "DebugRenderer.h"
#include "Types.h"
#include "String.h"
#include "Args.h"
#include "Game.h"
#include "ArchiveResourceArchive.h"
#include "FileResourceArchive.h"
#include "ResourceManager.h"
#include "TextureResource.h"
#include "Keyboard.h"
#include "Mouse.h"
#include "Touch.h"
#include "Accelerometer.h"
#include "OsWindow.h"
namespace crown
{
static void (*game_init)(void) = NULL;
static void (*game_shutdown)(void) = NULL;
static void (*game_frame)(float) = NULL;
//-----------------------------------------------------------------------------
Device::Device() :
m_preferred_window_width(1000),
m_preferred_window_height(625),
m_preferred_window_fullscreen(0),
m_preferred_mode(MODE_RELEASE),
m_is_init(false),
m_is_running(false),
m_frame_count(0),
m_last_time(0),
m_current_time(0),
m_last_delta_time(0.0f),
m_filesystem(NULL),
m_input_manager(NULL),
m_renderer(NULL),
m_debug_renderer(NULL),
m_resource_manager(NULL),
m_resource_archive(NULL),
m_game_library(NULL)
{
// Select executable dir by default
string::strncpy(m_preferred_root_path, os::get_cwd(), os::MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Device::~Device()
{
}
//-----------------------------------------------------------------------------
bool Device::init(int argc, char** argv)
{
if (is_init())
{
Log::e("Crown Engine is already initialized.");
return false;
}
parse_command_line(argc, argv);
check_preferred_settings();
// Initialize
Log::i("Initializing Crown Engine %d.%d.%d...", CROWN_VERSION_MAJOR, CROWN_VERSION_MINOR, CROWN_VERSION_MICRO);
create_filesystem();
create_resource_manager();
create_input_manager();
create_window();
create_renderer();
create_debug_renderer();
Log::i("Crown Engine initialized.");
Log::i("Initializing Game...");
// Try to locate the game library
if (!m_filesystem->exists(GAME_LIBRARY_NAME))
{
Log::e("Unable to find the game library in the root path.", GAME_LIBRARY_NAME);
return false;
}
// Try to load the game library and bind functions
const char* game_library_path = m_filesystem->os_path(GAME_LIBRARY_NAME);
m_game_library = os::open_library(game_library_path);
if (m_game_library == NULL)
{
Log::e("Unable to load the game.");
return false;
}
*(void**)(&game_init) = os::lookup_symbol(m_game_library, "init");
*(void**)(&game_shutdown) = os::lookup_symbol(m_game_library, "shutdown");
*(void**)(&game_frame) = os::lookup_symbol(m_game_library, "frame");
// Initialize the game
game_init();
m_is_init = true;
start();
return true;
}
//-----------------------------------------------------------------------------
void Device::shutdown()
{
if (is_init() == false)
{
Log::e("Crown Engine is not initialized.");
return;
}
// Shutdowns the game
game_shutdown();
// Unload the game library
if (m_game_library)
{
os::close_library(m_game_library);
}
if (m_input_manager)
{
delete m_input_manager;
}
Log::i("Releasing DebugRenderer...");
if (m_debug_renderer)
{
delete m_debug_renderer;
}
Log::i("Releasing Renderer...");
if (m_renderer)
{
m_renderer->shutdown();
Renderer::destroy(m_renderer);
}
Log::i("Releasing Window...");
if (m_window)
{
delete m_window;
}
Log::i("Releasing ResourceManager...");
if (m_resource_archive)
{
delete m_resource_archive;
}
if (m_resource_manager)
{
delete m_resource_manager;
}
Log::i("Releasing Filesystem...");
if (m_filesystem)
{
delete m_filesystem;
}
m_is_init = false;
}
//-----------------------------------------------------------------------------
bool Device::is_init() const
{
return m_is_init;
}
//-----------------------------------------------------------------------------
Filesystem* Device::filesystem()
{
return m_filesystem;
}
//-----------------------------------------------------------------------------
ResourceManager* Device::resource_manager()
{
return m_resource_manager;
}
//-----------------------------------------------------------------------------
InputManager* Device::input_manager()
{
return m_input_manager;
}
//-----------------------------------------------------------------------------
OsWindow* Device::window()
{
return m_window;
}
//-----------------------------------------------------------------------------
Renderer* Device::renderer()
{
return m_renderer;
}
//-----------------------------------------------------------------------------
DebugRenderer* Device::debug_renderer()
{
return m_debug_renderer;
}
//-----------------------------------------------------------------------------
Keyboard* Device::keyboard()
{
return m_input_manager->keyboard();
}
//-----------------------------------------------------------------------------
Mouse* Device::mouse()
{
return m_input_manager->mouse();
}
//-----------------------------------------------------------------------------
Touch* Device::touch()
{
return m_input_manager->touch();
}
//-----------------------------------------------------------------------------
Accelerometer* Device::accelerometer()
{
return m_input_manager->accelerometer();
}
//-----------------------------------------------------------------------------
void Device::start()
{
if (is_init() == false)
{
Log::e("Cannot start uninitialized engine.");
return;
}
m_is_running = true;
m_last_time = os::milliseconds();
}
//-----------------------------------------------------------------------------
void Device::stop()
{
if (is_init() == false)
{
Log::e("Cannot stop uninitialized engine.");
return;
}
m_is_running = false;
}
//-----------------------------------------------------------------------------
bool Device::is_running() const
{
return m_is_running;
}
//-----------------------------------------------------------------------------
uint64_t Device::frame_count() const
{
return m_frame_count;
}
//-----------------------------------------------------------------------------
float Device::last_delta_time() const
{
return m_last_delta_time;
}
//-----------------------------------------------------------------------------
void Device::frame()
{
m_current_time = os::microseconds();
m_last_delta_time = (m_current_time - m_last_time) / 1000000.0f;
m_last_time = m_current_time;
m_resource_manager->check_load_queue();
m_resource_manager->bring_loaded_online();
m_window->frame();
m_input_manager->frame();
game_frame(last_delta_time());
m_debug_renderer->draw_all();
m_renderer->frame();
m_frame_count++;
}
//-----------------------------------------------------------------------------
ResourceId Device::load(const char* name)
{
return m_resource_manager->load(name);
}
//-----------------------------------------------------------------------------
void Device::unload(ResourceId name)
{
m_resource_manager->unload(name);
}
//-----------------------------------------------------------------------------
void Device::reload(ResourceId name)
{
(void)name;
}
//-----------------------------------------------------------------------------
bool Device::is_loaded(ResourceId name)
{
return m_resource_manager->is_loaded(name);
}
//-----------------------------------------------------------------------------
const void* Device::data(ResourceId name)
{
return m_resource_manager->data(name);
}
//-----------------------------------------------------------------------------
void Device::create_filesystem()
{
m_filesystem = new Filesystem(m_preferred_root_path);
Log::d("Filesystem created.");
Log::d("Filesystem root path: %s", m_filesystem->root_path());
}
//-----------------------------------------------------------------------------
void Device::create_resource_manager()
{
// Select appropriate resource archive
if (m_preferred_mode == MODE_DEVELOPMENT)
{
m_resource_archive = new FileResourceArchive(*m_filesystem);
}
else
{
m_resource_archive = new ArchiveResourceArchive(*m_filesystem);
}
// Create resource manager
m_resource_manager = new ResourceManager(*m_resource_archive, m_resource_allocator);
Log::d("Resource manager created.");
Log::d("Resource seed: %d", m_resource_manager->seed());
}
//-----------------------------------------------------------------------------
void Device::create_input_manager()
{
// Create input manager
m_input_manager = new InputManager();
Log::d("Input manager created.");
}
//-----------------------------------------------------------------------------
void Device::create_window()
{
m_window = new OsWindow(m_preferred_window_width, m_preferred_window_height);
CE_ASSERT(m_window != NULL, "Unable to create the window");
m_window->set_title("Crown Game Engine");
m_window->show();
Log::d("Window created.");
}
//-----------------------------------------------------------------------------
void Device::create_renderer()
{
m_renderer = Renderer::create();
m_renderer->init();
Log::d("Renderer created.");
}
//-----------------------------------------------------------------------------
void Device::create_debug_renderer()
{
// Create debug renderer
m_debug_renderer = new DebugRenderer(*m_renderer);
Log::d("Debug renderer created.");
}
//-----------------------------------------------------------------------------
void Device::parse_command_line(int argc, char** argv)
{
static ArgsOption options[] =
{
"help", AOA_NO_ARGUMENT, NULL, 'i',
"root-path", AOA_REQUIRED_ARGUMENT, NULL, 'r',
"width", AOA_REQUIRED_ARGUMENT, NULL, 'w',
"height", AOA_REQUIRED_ARGUMENT, NULL, 'h',
"fullscreen", AOA_NO_ARGUMENT, &m_preferred_window_fullscreen, 1,
"dev", AOA_NO_ARGUMENT, &m_preferred_mode, MODE_DEVELOPMENT,
NULL, 0, NULL, 0
};
Args args(argc, argv, "", options);
int32_t opt;
while ((opt = args.getopt()) != -1)
{
switch (opt)
{
case 0:
{
break;
}
// Root path
case 'r':
{
string::strcpy(m_preferred_root_path, args.optarg());
break;
}
// Window width
case 'w':
{
m_preferred_window_width = atoi(args.optarg());
break;
}
// Window height
case 'h':
{
m_preferred_window_height = atoi(args.optarg());
break;
}
case 'i':
case '?':
default:
{
print_help_message();
exit(EXIT_FAILURE);
}
}
}
}
//-----------------------------------------------------------------------------
void Device::check_preferred_settings()
{
if (!os::is_absolute_path(m_preferred_root_path))
{
Log::e("The root path must be absolute.");
exit(EXIT_FAILURE);
}
if (m_preferred_window_width == 0 || m_preferred_window_height == 0)
{
Log::e("Window width and height must be greater than zero.");
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------------------
void Device::print_help_message()
{
os::printf(
"Usage: crown [options]\n"
"Options:\n\n"
"All of the following options take precedence over\n"
"environment variables and configuration files.\n\n"
" --help Show this help.\n"
" --root-path <path> Use <path> as the filesystem root path.\n"
" --width <width> Set the <width> of the render window.\n"
" --height <width> Set the <height> of the render window.\n"
" --fullscreen Start in fullscreen.\n"
" --dev Run the engine in development mode\n");
}
Device g_device;
Device* device()
{
return &g_device;
}
} // namespace crown
<commit_msg>MAX_PATH_LENGTH is not in os namespace anymore<commit_after>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
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 <cstdlib>
#include "Config.h"
#include "Device.h"
#include "Filesystem.h"
#include "InputManager.h"
#include "Log.h"
#include "OS.h"
#include "Renderer.h"
#include "DebugRenderer.h"
#include "Types.h"
#include "String.h"
#include "Args.h"
#include "Game.h"
#include "ArchiveResourceArchive.h"
#include "FileResourceArchive.h"
#include "ResourceManager.h"
#include "TextureResource.h"
#include "Keyboard.h"
#include "Mouse.h"
#include "Touch.h"
#include "Accelerometer.h"
#include "OsWindow.h"
namespace crown
{
static void (*game_init)(void) = NULL;
static void (*game_shutdown)(void) = NULL;
static void (*game_frame)(float) = NULL;
//-----------------------------------------------------------------------------
Device::Device() :
m_preferred_window_width(1000),
m_preferred_window_height(625),
m_preferred_window_fullscreen(0),
m_preferred_mode(MODE_RELEASE),
m_is_init(false),
m_is_running(false),
m_frame_count(0),
m_last_time(0),
m_current_time(0),
m_last_delta_time(0.0f),
m_filesystem(NULL),
m_input_manager(NULL),
m_renderer(NULL),
m_debug_renderer(NULL),
m_resource_manager(NULL),
m_resource_archive(NULL),
m_game_library(NULL)
{
// Select executable dir by default
string::strncpy(m_preferred_root_path, os::get_cwd(), MAX_PATH_LENGTH);
}
//-----------------------------------------------------------------------------
Device::~Device()
{
}
//-----------------------------------------------------------------------------
bool Device::init(int argc, char** argv)
{
if (is_init())
{
Log::e("Crown Engine is already initialized.");
return false;
}
parse_command_line(argc, argv);
check_preferred_settings();
// Initialize
Log::i("Initializing Crown Engine %d.%d.%d...", CROWN_VERSION_MAJOR, CROWN_VERSION_MINOR, CROWN_VERSION_MICRO);
create_filesystem();
create_resource_manager();
create_input_manager();
create_window();
create_renderer();
create_debug_renderer();
Log::i("Crown Engine initialized.");
Log::i("Initializing Game...");
// Try to locate the game library
if (!m_filesystem->exists(GAME_LIBRARY_NAME))
{
Log::e("Unable to find the game library in the root path.", GAME_LIBRARY_NAME);
return false;
}
// Try to load the game library and bind functions
const char* game_library_path = m_filesystem->os_path(GAME_LIBRARY_NAME);
m_game_library = os::open_library(game_library_path);
if (m_game_library == NULL)
{
Log::e("Unable to load the game.");
return false;
}
*(void**)(&game_init) = os::lookup_symbol(m_game_library, "init");
*(void**)(&game_shutdown) = os::lookup_symbol(m_game_library, "shutdown");
*(void**)(&game_frame) = os::lookup_symbol(m_game_library, "frame");
// Initialize the game
game_init();
m_is_init = true;
start();
return true;
}
//-----------------------------------------------------------------------------
void Device::shutdown()
{
if (is_init() == false)
{
Log::e("Crown Engine is not initialized.");
return;
}
// Shutdowns the game
game_shutdown();
// Unload the game library
if (m_game_library)
{
os::close_library(m_game_library);
}
if (m_input_manager)
{
delete m_input_manager;
}
Log::i("Releasing DebugRenderer...");
if (m_debug_renderer)
{
delete m_debug_renderer;
}
Log::i("Releasing Renderer...");
if (m_renderer)
{
m_renderer->shutdown();
Renderer::destroy(m_renderer);
}
Log::i("Releasing Window...");
if (m_window)
{
delete m_window;
}
Log::i("Releasing ResourceManager...");
if (m_resource_archive)
{
delete m_resource_archive;
}
if (m_resource_manager)
{
delete m_resource_manager;
}
Log::i("Releasing Filesystem...");
if (m_filesystem)
{
delete m_filesystem;
}
m_is_init = false;
}
//-----------------------------------------------------------------------------
bool Device::is_init() const
{
return m_is_init;
}
//-----------------------------------------------------------------------------
Filesystem* Device::filesystem()
{
return m_filesystem;
}
//-----------------------------------------------------------------------------
ResourceManager* Device::resource_manager()
{
return m_resource_manager;
}
//-----------------------------------------------------------------------------
InputManager* Device::input_manager()
{
return m_input_manager;
}
//-----------------------------------------------------------------------------
OsWindow* Device::window()
{
return m_window;
}
//-----------------------------------------------------------------------------
Renderer* Device::renderer()
{
return m_renderer;
}
//-----------------------------------------------------------------------------
DebugRenderer* Device::debug_renderer()
{
return m_debug_renderer;
}
//-----------------------------------------------------------------------------
Keyboard* Device::keyboard()
{
return m_input_manager->keyboard();
}
//-----------------------------------------------------------------------------
Mouse* Device::mouse()
{
return m_input_manager->mouse();
}
//-----------------------------------------------------------------------------
Touch* Device::touch()
{
return m_input_manager->touch();
}
//-----------------------------------------------------------------------------
Accelerometer* Device::accelerometer()
{
return m_input_manager->accelerometer();
}
//-----------------------------------------------------------------------------
void Device::start()
{
if (is_init() == false)
{
Log::e("Cannot start uninitialized engine.");
return;
}
m_is_running = true;
m_last_time = os::milliseconds();
}
//-----------------------------------------------------------------------------
void Device::stop()
{
if (is_init() == false)
{
Log::e("Cannot stop uninitialized engine.");
return;
}
m_is_running = false;
}
//-----------------------------------------------------------------------------
bool Device::is_running() const
{
return m_is_running;
}
//-----------------------------------------------------------------------------
uint64_t Device::frame_count() const
{
return m_frame_count;
}
//-----------------------------------------------------------------------------
float Device::last_delta_time() const
{
return m_last_delta_time;
}
//-----------------------------------------------------------------------------
void Device::frame()
{
m_current_time = os::microseconds();
m_last_delta_time = (m_current_time - m_last_time) / 1000000.0f;
m_last_time = m_current_time;
m_resource_manager->check_load_queue();
m_resource_manager->bring_loaded_online();
m_window->frame();
m_input_manager->frame();
game_frame(last_delta_time());
m_debug_renderer->draw_all();
m_renderer->frame();
m_frame_count++;
}
//-----------------------------------------------------------------------------
ResourceId Device::load(const char* name)
{
return m_resource_manager->load(name);
}
//-----------------------------------------------------------------------------
void Device::unload(ResourceId name)
{
m_resource_manager->unload(name);
}
//-----------------------------------------------------------------------------
void Device::reload(ResourceId name)
{
(void)name;
}
//-----------------------------------------------------------------------------
bool Device::is_loaded(ResourceId name)
{
return m_resource_manager->is_loaded(name);
}
//-----------------------------------------------------------------------------
const void* Device::data(ResourceId name)
{
return m_resource_manager->data(name);
}
//-----------------------------------------------------------------------------
void Device::create_filesystem()
{
m_filesystem = new Filesystem(m_preferred_root_path);
Log::d("Filesystem created.");
Log::d("Filesystem root path: %s", m_filesystem->root_path());
}
//-----------------------------------------------------------------------------
void Device::create_resource_manager()
{
// Select appropriate resource archive
if (m_preferred_mode == MODE_DEVELOPMENT)
{
m_resource_archive = new FileResourceArchive(*m_filesystem);
}
else
{
m_resource_archive = new ArchiveResourceArchive(*m_filesystem);
}
// Create resource manager
m_resource_manager = new ResourceManager(*m_resource_archive, m_resource_allocator);
Log::d("Resource manager created.");
Log::d("Resource seed: %d", m_resource_manager->seed());
}
//-----------------------------------------------------------------------------
void Device::create_input_manager()
{
// Create input manager
m_input_manager = new InputManager();
Log::d("Input manager created.");
}
//-----------------------------------------------------------------------------
void Device::create_window()
{
m_window = new OsWindow(m_preferred_window_width, m_preferred_window_height);
CE_ASSERT(m_window != NULL, "Unable to create the window");
m_window->set_title("Crown Game Engine");
m_window->show();
Log::d("Window created.");
}
//-----------------------------------------------------------------------------
void Device::create_renderer()
{
m_renderer = Renderer::create();
m_renderer->init();
Log::d("Renderer created.");
}
//-----------------------------------------------------------------------------
void Device::create_debug_renderer()
{
// Create debug renderer
m_debug_renderer = new DebugRenderer(*m_renderer);
Log::d("Debug renderer created.");
}
//-----------------------------------------------------------------------------
void Device::parse_command_line(int argc, char** argv)
{
static ArgsOption options[] =
{
"help", AOA_NO_ARGUMENT, NULL, 'i',
"root-path", AOA_REQUIRED_ARGUMENT, NULL, 'r',
"width", AOA_REQUIRED_ARGUMENT, NULL, 'w',
"height", AOA_REQUIRED_ARGUMENT, NULL, 'h',
"fullscreen", AOA_NO_ARGUMENT, &m_preferred_window_fullscreen, 1,
"dev", AOA_NO_ARGUMENT, &m_preferred_mode, MODE_DEVELOPMENT,
NULL, 0, NULL, 0
};
Args args(argc, argv, "", options);
int32_t opt;
while ((opt = args.getopt()) != -1)
{
switch (opt)
{
case 0:
{
break;
}
// Root path
case 'r':
{
string::strcpy(m_preferred_root_path, args.optarg());
break;
}
// Window width
case 'w':
{
m_preferred_window_width = atoi(args.optarg());
break;
}
// Window height
case 'h':
{
m_preferred_window_height = atoi(args.optarg());
break;
}
case 'i':
case '?':
default:
{
print_help_message();
exit(EXIT_FAILURE);
}
}
}
}
//-----------------------------------------------------------------------------
void Device::check_preferred_settings()
{
if (!os::is_absolute_path(m_preferred_root_path))
{
Log::e("The root path must be absolute.");
exit(EXIT_FAILURE);
}
if (m_preferred_window_width == 0 || m_preferred_window_height == 0)
{
Log::e("Window width and height must be greater than zero.");
exit(EXIT_FAILURE);
}
}
//-----------------------------------------------------------------------------
void Device::print_help_message()
{
os::printf(
"Usage: crown [options]\n"
"Options:\n\n"
"All of the following options take precedence over\n"
"environment variables and configuration files.\n\n"
" --help Show this help.\n"
" --root-path <path> Use <path> as the filesystem root path.\n"
" --width <width> Set the <width> of the render window.\n"
" --height <width> Set the <height> of the render window.\n"
" --fullscreen Start in fullscreen.\n"
" --dev Run the engine in development mode\n");
}
Device g_device;
Device* device()
{
return &g_device;
}
} // namespace crown
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Martin Preisler <martin@preisler.me>
*
* This file is part of oclcrypto.
*
* 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 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 "oclcrypto/Device.h"
#include "oclcrypto/CLError.h"
#include "oclcrypto/Program.h"
#include <algorithm>
namespace oclcrypto
{
Device::Device(cl_platform_id platformID, cl_device_id deviceID):
mCLPlatformID(platformID),
mCLDeviceID(deviceID)
{
cl_context_properties contextProperties[] = {
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(mCLPlatformID),
0
};
cl_int err;
mCLContext = clCreateContext(contextProperties, 1, &mCLDeviceID, nullptr, nullptr, &err);
CLErrorGuard(err);
// TODO: command_queue_properties might be useful for profiling
mCLQueue = clCreateCommandQueue(mCLContext, mCLDeviceID, 0, &err);
CLErrorGuard(err);
}
Device::~Device()
{
for (ProgramVector::reverse_iterator it = mPrograms.rbegin();
it != mPrograms.rend(); ++it)
{
// don't use destroyProgram here because that would change the vector needlessly
delete *it;
}
mPrograms.clear();
for (DataBufferVector::reverse_iterator it = mDataBuffers.rbegin();
it != mDataBuffers.rend(); ++it)
{
// don't use deallocateBuffer here because that would change the vector needlessly
delete *it;
}
mDataBuffers.clear();
try
{
CLErrorGuard(clReleaseCommandQueue(mCLQueue));
CLErrorGuard(clReleaseContext(mCLContext));
//CLErrorGuard(clReleaseDevice(mCLDeviceID));
}
catch (...) // can't throw in dtor
{
// TODO: log the exceptions
}
}
Program& Device::createProgram(const std::string& source)
{
Program* ret = new Program(*this, source);
mPrograms.push_back(ret);
return *ret;
}
void Device::destroyProgram(Program& program)
{
ProgramVector::iterator it = std::find(mPrograms.begin(), mPrograms.end(), &program);
if (it == mPrograms.end())
throw std::invalid_argument(
"Given Program has already been destroyed by this Device or "
"it belongs to another Device."
);
mPrograms.erase(it);
delete &program;
}
cl_device_id Device::getCLDeviceID() const
{
return mCLDeviceID;
}
cl_context Device::getCLContext() const
{
return mCLContext;
}
cl_command_queue Device::getCLQueue() const
{
return mCLQueue;
}
DataBuffer& Device::allocateBufferRaw(const size_t size, const unsigned short memFlags)
{
DataBuffer* ret = new DataBuffer(*this, size, memFlags);
mDataBuffers.push_back(ret);
return *ret;
}
void Device::deallocateBuffer(DataBuffer& buffer)
{
DataBufferVector::iterator it = std::find(mDataBuffers.begin(), mDataBuffers.end(), &buffer);
if (it == mDataBuffers.end())
throw std::invalid_argument(
"Given DataBuffer has already been destroyed by this Device or "
"it belongs to another Device."
);
mDataBuffers.erase(it);
delete &buffer;
}
unsigned int Device::getCapacity() const
{
// TODO: This is completely arbitrary for now
return 3;
}
}
<commit_msg>Do not call clReleaseDevice in Device::~Device<commit_after>/*
* Copyright (C) 2014 Martin Preisler <martin@preisler.me>
*
* This file is part of oclcrypto.
*
* 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 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 "oclcrypto/Device.h"
#include "oclcrypto/CLError.h"
#include "oclcrypto/Program.h"
#include <algorithm>
namespace oclcrypto
{
Device::Device(cl_platform_id platformID, cl_device_id deviceID):
mCLPlatformID(platformID),
mCLDeviceID(deviceID)
{
cl_context_properties contextProperties[] = {
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(mCLPlatformID),
0
};
cl_int err;
mCLContext = clCreateContext(contextProperties, 1, &mCLDeviceID, nullptr, nullptr, &err);
CLErrorGuard(err);
// TODO: command_queue_properties might be useful for profiling
mCLQueue = clCreateCommandQueue(mCLContext, mCLDeviceID, 0, &err);
CLErrorGuard(err);
}
Device::~Device()
{
for (ProgramVector::reverse_iterator it = mPrograms.rbegin();
it != mPrograms.rend(); ++it)
{
// don't use destroyProgram here because that would change the vector needlessly
delete *it;
}
mPrograms.clear();
for (DataBufferVector::reverse_iterator it = mDataBuffers.rbegin();
it != mDataBuffers.rend(); ++it)
{
// don't use deallocateBuffer here because that would change the vector needlessly
delete *it;
}
mDataBuffers.clear();
try
{
CLErrorGuard(clReleaseCommandQueue(mCLQueue));
CLErrorGuard(clReleaseContext(mCLContext));
// We shall not call clReleaseDevice here, clReleaseDevice releases subdevices,
// not the main devices. Calling it here has strange effects on various OpenCL
// implementations
}
catch (...) // can't throw in dtor
{
// TODO: log the exceptions
}
}
Program& Device::createProgram(const std::string& source)
{
Program* ret = new Program(*this, source);
mPrograms.push_back(ret);
return *ret;
}
void Device::destroyProgram(Program& program)
{
ProgramVector::iterator it = std::find(mPrograms.begin(), mPrograms.end(), &program);
if (it == mPrograms.end())
throw std::invalid_argument(
"Given Program has already been destroyed by this Device or "
"it belongs to another Device."
);
mPrograms.erase(it);
delete &program;
}
cl_device_id Device::getCLDeviceID() const
{
return mCLDeviceID;
}
cl_context Device::getCLContext() const
{
return mCLContext;
}
cl_command_queue Device::getCLQueue() const
{
return mCLQueue;
}
DataBuffer& Device::allocateBufferRaw(const size_t size, const unsigned short memFlags)
{
DataBuffer* ret = new DataBuffer(*this, size, memFlags);
mDataBuffers.push_back(ret);
return *ret;
}
void Device::deallocateBuffer(DataBuffer& buffer)
{
DataBufferVector::iterator it = std::find(mDataBuffers.begin(), mDataBuffers.end(), &buffer);
if (it == mDataBuffers.end())
throw std::invalid_argument(
"Given DataBuffer has already been destroyed by this Device or "
"it belongs to another Device."
);
mDataBuffers.erase(it);
delete &buffer;
}
unsigned int Device::getCapacity() const
{
// TODO: This is completely arbitrary for now
return 3;
}
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Kein-Hong Man to use CharacterSet objects. Simpler and smaller but should not change behaviour.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "CharacterSet.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
// Accepts accented characters
CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefABCDEF");
CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#");
CharacterSet setEscapeSkip(CharacterSet::setNone, "\"'\\");
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!setNumber.Contains(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!setWord.Contains(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward();
}
} else if (setWordStart.Contains(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (setLuaOperator.Contains(sc.ch)) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|> |
<commit_before>#include <algorithm>
#include "Parser.h"
Parser::Parser()
: m_stopParser( false )
{
}
Parser::~Parser()
{
if ( m_thread == nullptr )
return;
{
std::lock_guard<std::mutex> lock( m_lock );
if ( m_tasks.empty() == true )
m_cond.notify_all();
m_stopParser = true;
}
m_thread->join();
}
void Parser::addService(std::unique_ptr<IMetadataService> service)
{
m_services.push_back( std::move( service ) );
std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b )
{
// We want higher priority first
return a->priority() < b->priority();
});
}
void Parser::parse(FilePtr file, IMetadataCb* cb)
{
std::lock_guard<std::mutex> lock( m_lock );
m_tasks.push_back( new Task( file, m_services, cb ) );
if ( m_thread == nullptr )
m_thread.reset( new std::thread( &Parser::run, this ) );
}
void Parser::run()
{
while ( m_stopParser == false )
{
Task* task = nullptr;
{
std::unique_lock<std::mutex> lock( m_lock );
if ( m_tasks.empty() == true )
{
m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; });
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
return;
}
// Otherwise it's safe to assume we have at least one element.
task = m_tasks.front();
m_tasks.erase(m_tasks.begin());
}
(*task->it)->run( task->file, task );
}
}
Parser::Task::Task( FilePtr file, Parser::ServiceList& serviceList, IMetadataCb* metadataCb )
: file(file)
, it( serviceList.begin() )
, end( serviceList.end() )
, cb( metadataCb )
{
}
void Parser::done( FilePtr file, ServiceStatus status, void* data )
{
Task *t = reinterpret_cast<Task*>( data );
if ( status == StatusTemporaryUnavailable || status == StatusFatal )
{
delete t;
return ;
}
++t->it;
if (t->it == t->end)
{
t->cb->onMetadataUpdated( file );
delete t;
return;
}
std::lock_guard<std::mutex> lock( m_lock );
m_tasks.push_back( t );
m_cond.notify_all();
}
<commit_msg>Parser: Don't assume there is at least one metadata service<commit_after>#include <algorithm>
#include "Parser.h"
Parser::Parser()
: m_stopParser( false )
{
}
Parser::~Parser()
{
if ( m_thread == nullptr )
return;
{
std::lock_guard<std::mutex> lock( m_lock );
if ( m_tasks.empty() == true )
m_cond.notify_all();
m_stopParser = true;
}
m_thread->join();
}
void Parser::addService(std::unique_ptr<IMetadataService> service)
{
m_services.push_back( std::move( service ) );
std::push_heap( m_services.begin(), m_services.end(), []( const ServicePtr& a, const ServicePtr& b )
{
// We want higher priority first
return a->priority() < b->priority();
});
}
void Parser::parse(FilePtr file, IMetadataCb* cb)
{
std::lock_guard<std::mutex> lock( m_lock );
if ( m_services.size() == 0 )
return;
m_tasks.push_back( new Task( file, m_services, cb ) );
if ( m_thread == nullptr )
m_thread.reset( new std::thread( &Parser::run, this ) );
}
void Parser::run()
{
while ( m_stopParser == false )
{
Task* task = nullptr;
{
std::unique_lock<std::mutex> lock( m_lock );
if ( m_tasks.empty() == true )
{
m_cond.wait( lock, [this]() { return m_tasks.empty() == false || m_stopParser == true; });
// We might have been woken up because the parser is being destroyed
if ( m_stopParser == true )
return;
}
// Otherwise it's safe to assume we have at least one element.
task = m_tasks.front();
m_tasks.erase(m_tasks.begin());
}
(*task->it)->run( task->file, task );
}
}
Parser::Task::Task( FilePtr file, Parser::ServiceList& serviceList, IMetadataCb* metadataCb )
: file(file)
, it( serviceList.begin() )
, end( serviceList.end() )
, cb( metadataCb )
{
}
void Parser::done( FilePtr file, ServiceStatus status, void* data )
{
Task *t = reinterpret_cast<Task*>( data );
if ( status == StatusTemporaryUnavailable || status == StatusFatal )
{
delete t;
return ;
}
++t->it;
if (t->it == t->end)
{
t->cb->onMetadataUpdated( file );
delete t;
return;
}
std::lock_guard<std::mutex> lock( m_lock );
m_tasks.push_back( t );
m_cond.notify_all();
}
<|endoftext|> |
<commit_before>#include "Player.hpp"
#include <iostream>
void Player::update (sf::Time deltaTime) {
// get input from globals and process:
sf::Vector2f tmpPos = getPosition();
int width = getWidth();
int height = getHeight();
int dir = -1;
if (input[0]) { tmpPos.x -= 1; dir = 3; }
if (input[1]) { tmpPos.x += 1; dir = 2; }
if (input[2]) { tmpPos.y -= 1; dir = 1; }
if (input[3]) { tmpPos.y += 1; dir = 0; }
// doggie follows the hero
if (dir > -1)
{
positionQueue.push(tmpPos);
directionQueue.push(direction);
}
if (tmpPos.x > screenWidth) tmpPos.x -= screenWidth;
if (tmpPos.x + width < 0) tmpPos.x += screenWidth;
if (tmpPos.y > screenHeight) tmpPos.y -= screenHeight;
if (tmpPos.y + height < 0) tmpPos.y += screenHeight;
setPosition(tmpPos.x, tmpPos.y);
doggieSprite->setPosition(positionQueue.front().x, positionQueue.front().y + 18);
if (dir > -1)
{
animationStep += 1;
doggieStep += 1;
direction = dir;
}
if (animationStep / slowFactor > 3) animationStep = 0; // animationStep wird immer um 1 hochgezählt, aber effektiv um den Faktor slowFactor verlangsamt
if (doggieStep / slowFactor > 5) doggieStep = 0;
//check for collisions:
if (mySprite != 0 && doggieSprite != 0)
{
doggieSprite->setTextureRect(sf::IntRect((directionQueue.front() + 4) * 16, DoggieAnimState[doggieStep / slowFactor] * 16, 16, 16));
window.draw(*doggieSprite);
if (!positionQueue.empty() && !directionQueue.empty() && positionQueue.size() > 16) // delay of doggie movement
{
directionQueue.pop();
positionQueue.pop();
}
mySprite->setTextureRect(sf::IntRect(direction * 16, PlayerAnimState[animationStep / slowFactor] * 32, 16, 32));
window.draw(*mySprite);
}
}
<commit_msg>player stands still<commit_after>#include "Player.hpp"
#include <iostream>
void Player::update (sf::Time deltaTime) {
// get input from globals and process:
sf::Vector2f tmpPos = getPosition();
int width = getWidth();
int height = getHeight();
int dir = -1;
if (input[0]) { tmpPos.x -= 1; dir = 3; }
if (input[1]) { tmpPos.x += 1; dir = 2; }
if (input[2]) { tmpPos.y -= 1; dir = 1; }
if (input[3]) { tmpPos.y += 1; dir = 0; }
// doggie follows the hero
if (dir > -1)
{
positionQueue.push(tmpPos);
directionQueue.push(direction);
}
if (tmpPos.x > screenWidth) tmpPos.x -= screenWidth;
if (tmpPos.x + width < 0) tmpPos.x += screenWidth;
if (tmpPos.y > screenHeight) tmpPos.y -= screenHeight;
if (tmpPos.y + height < 0) tmpPos.y += screenHeight;
setPosition(tmpPos.x, tmpPos.y);
doggieSprite->setPosition(positionQueue.front().x, positionQueue.front().y + 18);
if (dir > -1)
{
animationStep += 1;
doggieStep += 1;
direction = dir;
} else {
animationStep = 0;
doggieStep = 0;
}
if (animationStep / slowFactor > 3) animationStep = 0; // animationStep wird immer um 1 hochgezählt, aber effektiv um den Faktor slowFactor verlangsamt
if (doggieStep / slowFactor > 5) doggieStep = 0;
//check for collisions:
if (mySprite != 0 && doggieSprite != 0)
{
doggieSprite->setTextureRect(sf::IntRect((directionQueue.front() + 4) * 16, DoggieAnimState[doggieStep / slowFactor] * 16, 16, 16));
window.draw(*doggieSprite);
if (!positionQueue.empty() && !directionQueue.empty() && positionQueue.size() > 16) // delay of doggie movement
{
directionQueue.pop();
positionQueue.pop();
}
mySprite->setTextureRect(sf::IntRect(direction * 16, PlayerAnimState[animationStep / slowFactor] * 32, 16, 32));
window.draw(*mySprite);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE source in the root of the Project.
#include <boost/python.hpp>
#include <boost/optional.hpp>
#include <nix.hpp>
#include <nix/util/util.hpp>
#include <accessors.hpp>
#include <transmorgify.hpp>
#include <PyUtil.hpp>
using namespace nix;
using namespace boost::python;
namespace nixpy {
struct UnitWrap {};
bool isScalableSingleUnit(const std::string &unitA, const std::string &unitB) {
return util::isScalable(unitA, unitB);
}
bool isScalableMultiUnits(const std::vector<std::string> &unitsA, const std::vector<std::string> &unitsB) {
return util::isScalable(unitsA, unitsB);
}
std::vector<std::string> splitCompound(const std::string &unit) {
std::vector<std::string> parts;
util::splitCompoundUnit(unit, parts);
return parts;
}
struct NameWrap {};
void PyUtil::do_export() {
class_<UnitWrap> ("units")
.def("sanitizer", util::unitSanitizer).staticmethod("sanitizer")
.def("is_si", util::isSIUnit).staticmethod("is_si")
.def("is_atomic", util::isAtomicSIUnit).staticmethod("is_atomic")
.def("is_compound", util::isCompoundSIUnit).staticmethod("is_compound")
.def("scalable", &isScalableMultiUnits).staticmethod("scalable")
.def("scaling", util::getSIScaling).staticmethod("scaling")
.def("split_compound", &splitCompound).staticmethod("split_compound")
;
class_<NameWrap> ("names")
.def("sanitizer", util::nameSanitizer).staticmethod("sanitizer")
.def("check", util::nameCheck).staticmethod("check")
.def("create_id", util::createId).staticmethod("create_id")
;
}
}
<commit_msg>[util] expose split unit<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE source in the root of the Project.
#include <boost/python.hpp>
#include <boost/optional.hpp>
#include <nix.hpp>
#include <nix/util/util.hpp>
#include <accessors.hpp>
#include <transmorgify.hpp>
#include <PyUtil.hpp>
using namespace nix;
using namespace boost::python;
namespace nixpy {
struct UnitWrap {};
bool isScalableSingleUnit(const std::string &unitA, const std::string &unitB) {
return util::isScalable(unitA, unitB);
}
bool isScalableMultiUnits(const std::vector<std::string> &unitsA, const std::vector<std::string> &unitsB) {
return util::isScalable(unitsA, unitsB);
}
std::string baseUnit(const std::string &unit) {
std::string si, prefix, power;
util::splitUnit(unit, prefix, si, power);
return si;
}
std::string prefix(const std::string &unit) {
std::string si, prefix, power;
util::splitUnit(unit, prefix, si, power);
return prefix;
}
std::string power(const std::string &unit) {
std::string si, prefix, power;
util::splitUnit(unit, prefix, si, power);
return power;
}
std::vector<std::string> splitCompound(const std::string &unit) {
std::vector<std::string> parts;
util::splitCompoundUnit(unit, parts);
return parts;
}
struct NameWrap {};
void PyUtil::do_export() {
class_<UnitWrap> ("units")
.def("sanitizer", util::unitSanitizer).staticmethod("sanitizer")
.def("is_si", util::isSIUnit).staticmethod("is_si")
.def("is_atomic", util::isAtomicSIUnit).staticmethod("is_atomic")
.def("is_compound", util::isCompoundSIUnit).staticmethod("is_compound")
.def("scalable", &isScalableMultiUnits).staticmethod("scalable")
.def("scaling", util::getSIScaling).staticmethod("scaling")
.def("base_unit", &baseUnit).staticmethod("base_unit")
.def("prefix", &prefix).staticmethod("prefix")
.def("power", &power).staticmethod("power")
.def("split_compound", &splitCompound).staticmethod("split_compound")
;
class_<NameWrap> ("names")
.def("sanitizer", util::nameSanitizer).staticmethod("sanitizer")
.def("check", util::nameCheck).staticmethod("check")
.def("create_id", util::createId).staticmethod("create_id")
;
}
}
<|endoftext|> |
<commit_before>/*
* Koder is a code editor for Haiku based on Scintilla.
*
* Copyright (C) 2014-2015 Kacper Kasper <kacperkasper@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Styler.h"
#include <cstdlib>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <String.h>
#include "Editor.h"
#include "XmlDocument.h"
#include "XmlNode.h"
Styler::Styler(const char* path)
:
fDocument(new XmlDocument(path))
{
}
Styler::~Styler()
{
delete fDocument;
}
void
Styler::ApplyGlobal(Editor* editor)
{
uint32 count;
XmlNode* defaultStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle[@styleID='32']", &count);
int id, fg, bg, fs;
_GetAttributesFromNode(defaultStyle[0], &id, &fg, &bg, &fs);
editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) "DejaVu Sans Mono");
_SetAttributesInEditor(editor, id, fg, bg, fs);
editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
delete []defaultStyle;
XmlNode* globalStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle", &count);
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(globalStyle[i], &id, &fg, &bg, &fs);
if(id != 0 && id != 2069) {
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
else
{
BString name = globalStyle[i].GetAttribute("name");
if(name == "Current line background colour") {
editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
}
else if(name == "White space symbol") {
editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
}
else if(name == "Selected text colour") {
editor->SendMessage(SCI_SETSELFORE, true, fg);
editor->SendMessage(SCI_SETSELBACK, true, bg);
}
else if(name == "Caret colour") {
editor->SendMessage(SCI_SETCARETFORE, fg, 0);
}
else if(name == "Edge colour") {
editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
}
}
}
delete []globalStyle;
}
void
Styler::ApplyLanguage(Editor* editor, const char* lang)
{
BString xpath("/NotepadPlus/LexerStyles/LexerType[@name='%s']/WordsStyle");
xpath.ReplaceFirst("%s", lang);
uint32 count;
XmlNode* nodes = fDocument->GetNodesByXPath(xpath.String(), &count);
int id, fg, bg, fs;
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(nodes[i], &id, &fg, &bg, &fs);
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
delete []nodes;
}
void
Styler::_GetAttributesFromNode(XmlNode &node, int* styleId, int* fgColor, int* bgColor, int* fontStyle)
{
*styleId = strtol(node.GetAttribute("styleID").String(), NULL, 10);
*fgColor = strtol(node.GetAttribute("fgColor").String(), NULL, 16);
*bgColor = strtol(node.GetAttribute("bgColor").String(), NULL, 16);
*fontStyle = strtol(node.GetAttribute("fontStyle").String(), NULL, 10);
}
void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor, int bgColor, int fontStyle)
{
editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
if(fontStyle & 1) {
editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
}
if(fontStyle & 2) {
editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
}
if(fontStyle & 4) {
editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
}
}
<commit_msg>Use default system monospace font.<commit_after>/*
* Koder is a code editor for Haiku based on Scintilla.
*
* Copyright (C) 2014-2015 Kacper Kasper <kacperkasper@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "Styler.h"
#include <cstdlib>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <String.h>
#include "Editor.h"
#include "XmlDocument.h"
#include "XmlNode.h"
Styler::Styler(const char* path)
:
fDocument(new XmlDocument(path))
{
}
Styler::~Styler()
{
delete fDocument;
}
void
Styler::ApplyGlobal(Editor* editor)
{
uint32 count;
XmlNode* defaultStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle[@styleID='32']", &count);
int id, fg, bg, fs;
_GetAttributesFromNode(defaultStyle[0], &id, &fg, &bg, &fs);
font_family fixed;
be_fixed_font->GetFamilyAndStyle(&fixed, NULL);
editor->SendMessage(SCI_STYLESETFONT, id, (sptr_t) fixed);
_SetAttributesInEditor(editor, id, fg, bg, fs);
editor->SendMessage(SCI_STYLECLEARALL, 0, 0);
delete []defaultStyle;
XmlNode* globalStyle = fDocument->GetNodesByXPath("/NotepadPlus/GlobalStyles/WidgetStyle", &count);
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(globalStyle[i], &id, &fg, &bg, &fs);
if(id != 0 && id != 2069) {
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
else
{
BString name = globalStyle[i].GetAttribute("name");
if(name == "Current line background colour") {
editor->SendMessage(SCI_SETCARETLINEBACK, bg, 0);
//editor->SendMessage(SCI_SETCARETLINEBACKALPHA, 128, 0);
}
else if(name == "White space symbol") {
editor->SendMessage(SCI_SETWHITESPACEFORE, true, fg);
editor->SendMessage(SCI_SETWHITESPACEBACK, true, bg);
}
else if(name == "Selected text colour") {
editor->SendMessage(SCI_SETSELFORE, true, fg);
editor->SendMessage(SCI_SETSELBACK, true, bg);
}
else if(name == "Caret colour") {
editor->SendMessage(SCI_SETCARETFORE, fg, 0);
}
else if(name == "Edge colour") {
editor->SendMessage(SCI_SETEDGECOLOUR, fg, 0);
}
}
}
delete []globalStyle;
}
void
Styler::ApplyLanguage(Editor* editor, const char* lang)
{
BString xpath("/NotepadPlus/LexerStyles/LexerType[@name='%s']/WordsStyle");
xpath.ReplaceFirst("%s", lang);
uint32 count;
XmlNode* nodes = fDocument->GetNodesByXPath(xpath.String(), &count);
int id, fg, bg, fs;
for(int i = 0; i < count; i++) {
_GetAttributesFromNode(nodes[i], &id, &fg, &bg, &fs);
_SetAttributesInEditor(editor, id, fg, bg, fs);
}
delete []nodes;
}
void
Styler::_GetAttributesFromNode(XmlNode &node, int* styleId, int* fgColor, int* bgColor, int* fontStyle)
{
*styleId = strtol(node.GetAttribute("styleID").String(), NULL, 10);
*fgColor = strtol(node.GetAttribute("fgColor").String(), NULL, 16);
*bgColor = strtol(node.GetAttribute("bgColor").String(), NULL, 16);
*fontStyle = strtol(node.GetAttribute("fontStyle").String(), NULL, 10);
}
void
Styler::_SetAttributesInEditor(Editor* editor, int styleId, int fgColor, int bgColor, int fontStyle)
{
editor->SendMessage(SCI_STYLESETFORE, styleId, fgColor);
editor->SendMessage(SCI_STYLESETBACK, styleId, bgColor);
if(fontStyle & 1) {
editor->SendMessage(SCI_STYLESETBOLD, styleId, true);
}
if(fontStyle & 2) {
editor->SendMessage(SCI_STYLESETITALIC, styleId, true);
}
if(fontStyle & 4) {
editor->SendMessage(SCI_STYLESETUNDERLINE, styleId, true);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#include <string>
#include <cstring>
#include <stdlib.h>
// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
&& !defined __UCLIBCXX_MAJOR__
#include <cxxabi.h>
std::string demangle(char const* name)
{
// in case this string comes
// this is needed on linux
char const* start = strchr(name, '(');
if (start != 0)
{
++start;
}
else
{
// this is needed on macos x
start = strstr(name, "0x");
if (start != 0)
{
start = strchr(start, ' ');
if (start != 0) ++start;
else start = name;
}
else start = name;
}
char const* end = strchr(start, '+');
if (end) while (*(end-1) == ' ') --end;
std::string in;
if (end == 0) in.assign(start);
else in.assign(start, end);
size_t len;
int status;
char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
if (unmangled == 0) return in;
std::string ret(unmangled);
free(unmangled);
return ret;
}
#else
std::string demangle(char const* name) { return name; }
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"
// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>
void print_backtrace(char* out, int len)
{
void* stack[50];
int size = backtrace(stack, 50);
char** symbols = backtrace_symbols(stack, size);
for (int i = 1; i < size && len > 0; ++i)
{
int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
out += ret;
len -= ret;
}
free(symbols);
}
#else
void print_backtrace(FILE* out, char const* label) {}
#endif
#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif
void assert_fail(char const* expr, int line, char const* file, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
FILE* out = fopen(libtorrent_assert_log, "a+");
if (out == 0) out = stderr;
#else
FILE* out = stderr;
#endif
char stack[8192];
print_backtrace(stack, sizeof(stack));
fprintf(out, "assertion failed. Please file a bugreport at "
"http://code.rasterbar.com/libtorrent/newticket\n"
"Please include the following information:\n\n"
"version: " LIBTORRENT_VERSION "\n"
"%s\n"
"file: '%s'\n"
"line: %d\n"
"function: %s\n"
"expression: %s\n"
"%s%s\n"
"stack:\n"
"%s\n"
, LIBTORRENT_REVISION, file, line, function, expr
, value ? value : "", value ? "\n" : ""
, stack);
// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
if (out != stderr) fclose(out);
#else
// send SIGINT to the current process
// to break into the debugger
raise(SIGINT);
abort();
#endif
}
#else
void assert_fail(char const* expr, int line, char const* file, char const* function) {}
#endif
<commit_msg>fix windows build issue (one more try)<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#include <string>
#include <cstring>
#include <stdlib.h>
// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
&& !defined __UCLIBCXX_MAJOR__
#include <cxxabi.h>
std::string demangle(char const* name)
{
// in case this string comes
// this is needed on linux
char const* start = strchr(name, '(');
if (start != 0)
{
++start;
}
else
{
// this is needed on macos x
start = strstr(name, "0x");
if (start != 0)
{
start = strchr(start, ' ');
if (start != 0) ++start;
else start = name;
}
else start = name;
}
char const* end = strchr(start, '+');
if (end) while (*(end-1) == ' ') --end;
std::string in;
if (end == 0) in.assign(start);
else in.assign(start, end);
size_t len;
int status;
char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
if (unmangled == 0) return in;
std::string ret(unmangled);
free(unmangled);
return ret;
}
#else
std::string demangle(char const* name) { return name; }
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"
// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>
void print_backtrace(char* out, int len)
{
void* stack[50];
int size = backtrace(stack, 50);
char** symbols = backtrace_symbols(stack, size);
for (int i = 1; i < size && len > 0; ++i)
{
int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
out += ret;
len -= ret;
}
free(symbols);
}
#else
void print_backtrace(char* out, int len) {}
#endif
#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif
void assert_fail(char const* expr, int line, char const* file, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
FILE* out = fopen(libtorrent_assert_log, "a+");
if (out == 0) out = stderr;
#else
FILE* out = stderr;
#endif
char stack[8192];
print_backtrace(stack, sizeof(stack));
fprintf(out, "assertion failed. Please file a bugreport at "
"http://code.rasterbar.com/libtorrent/newticket\n"
"Please include the following information:\n\n"
"version: " LIBTORRENT_VERSION "\n"
"%s\n"
"file: '%s'\n"
"line: %d\n"
"function: %s\n"
"expression: %s\n"
"%s%s\n"
"stack:\n"
"%s\n"
, LIBTORRENT_REVISION, file, line, function, expr
, value ? value : "", value ? "\n" : ""
, stack);
// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
if (out != stderr) fclose(out);
#else
// send SIGINT to the current process
// to break into the debugger
raise(SIGINT);
abort();
#endif
}
#else
void assert_fail(char const* expr, int line, char const* file, char const* function) {}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 Vince Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "auxpow.h"
#include "init.h"
using namespace std;
using namespace boost;
unsigned char pchMergedMiningHeader[] = { 0xfa, 0xbe, 'm', 'm' } ;
void RemoveMergedMiningHeader(vector<unsigned char>& vchAux)
{
if (vchAux.begin() != std::search(vchAux.begin(), vchAux.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
throw runtime_error("merged mining aux too short");
vchAux.erase(vchAux.begin(), vchAux.begin() + sizeof(pchMergedMiningHeader));
}
bool CAuxPow::Check(uint256 hashAuxBlock, int nChainID)
{
if (nIndex != 0)
return error("AuxPow is not a generate");
if (!TestNet() && parentBlockHeader.GetChainID() == nChainID)
return error("Aux POW parent has our chain ID");
if (vChainMerkleBranch.size() > 30)
return error("Aux POW chain merkle branch too long");
// Check that the chain merkle root is in the coinbase
uint256 nRootHash = CBlock::CheckMerkleBranch(hashAuxBlock, vChainMerkleBranch, nChainIndex);
vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
// Check that we are in the parent block merkle tree
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlockHeader.hashMerkleRoot)
return error("Aux POW merkle root incorrect");
const CScript script = vin[0].scriptSig;
// Check that the same work is not submitted twice to our chain.
//
CScript::const_iterator pcHead =
std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
CScript::const_iterator pc =
std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
if (pcHead == script.end())
return error("MergedMiningHeader missing from parent coinbase");
if (pc == script.end())
return error("Aux POW missing chain merkle root in parent coinbase");
if (pcHead != script.end())
{
// Enforce only one chain merkle root by checking that a single instance of the merged
// mining header exists just before.
if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
return error("Multiple merged mining headers in coinbase");
if (pcHead + sizeof(pchMergedMiningHeader) != pc)
return error("Merged mining header is not just before chain merkle root");
}
else
{
// For backward compatibility.
// Enforce only one chain merkle root by checking that it starts early in the coinbase.
// 8-12 bytes are enough to encode extraNonce and nBits.
if (pc - script.begin() > 20)
return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
}
// Ensure we are at a deterministic point in the merkle leaves by hashing
// a nonce and our chain ID and comparing to the index.
pc += vchRootHash.size();
if (script.end() - pc < 8)
return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
int nSize;
memcpy(&nSize, &pc[0], 4);
if (nSize != (1 << vChainMerkleBranch.size()))
return error("Aux POW merkle branch size does not match parent coinbase");
int nNonce;
memcpy(&nNonce, &pc[4], 4);
// Choose a pseudo-random slot in the chain merkle tree
// but have it be fixed for a size/nonce/chain combination.
//
// This prevents the same work from being used twice for the
// same chain while reducing the chance that two chains clash
// for the same slot.
unsigned int rand = nNonce;
rand = rand * 1103515245 + 12345;
rand += nChainID;
rand = rand * 1103515245 + 12345;
if (nChainIndex != (rand % nSize))
return error("Aux POW wrong index");
return true;
}
CScript MakeCoinbaseWithAux(unsigned int nHeight, unsigned int nExtraNonce, vector<unsigned char>& vchAux)
{
vector<unsigned char> vchAuxWithHeader(UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
vchAuxWithHeader.insert(vchAuxWithHeader.end(), vchAux.begin(), vchAux.end());
// Push OP_2 just in case we want versioning later
return CScript() << nHeight << CScriptNum(nExtraNonce) << COINBASE_FLAGS << OP_2 << vchAuxWithHeader;
}
void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, vector<unsigned char>& vchAux)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(nHeight, nExtraNonce, vchAux);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
<commit_msg>Correct AuxPoW coinbase script concatenation operators.<commit_after>// Copyright (c) 2011 Vince Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "auxpow.h"
#include "init.h"
using namespace std;
using namespace boost;
unsigned char pchMergedMiningHeader[] = { 0xfa, 0xbe, 'm', 'm' } ;
void RemoveMergedMiningHeader(vector<unsigned char>& vchAux)
{
if (vchAux.begin() != std::search(vchAux.begin(), vchAux.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
throw runtime_error("merged mining aux too short");
vchAux.erase(vchAux.begin(), vchAux.begin() + sizeof(pchMergedMiningHeader));
}
bool CAuxPow::Check(uint256 hashAuxBlock, int nChainID)
{
if (nIndex != 0)
return error("AuxPow is not a generate");
if (!TestNet() && parentBlockHeader.GetChainID() == nChainID)
return error("Aux POW parent has our chain ID");
if (vChainMerkleBranch.size() > 30)
return error("Aux POW chain merkle branch too long");
// Check that the chain merkle root is in the coinbase
uint256 nRootHash = CBlock::CheckMerkleBranch(hashAuxBlock, vChainMerkleBranch, nChainIndex);
vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
// Check that we are in the parent block merkle tree
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlockHeader.hashMerkleRoot)
return error("Aux POW merkle root incorrect");
const CScript script = vin[0].scriptSig;
// Check that the same work is not submitted twice to our chain.
//
CScript::const_iterator pcHead =
std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
CScript::const_iterator pc =
std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
if (pcHead == script.end())
return error("MergedMiningHeader missing from parent coinbase");
if (pc == script.end())
return error("Aux POW missing chain merkle root in parent coinbase");
if (pcHead != script.end())
{
// Enforce only one chain merkle root by checking that a single instance of the merged
// mining header exists just before.
if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
return error("Multiple merged mining headers in coinbase");
if (pcHead + sizeof(pchMergedMiningHeader) != pc)
return error("Merged mining header is not just before chain merkle root");
}
else
{
// For backward compatibility.
// Enforce only one chain merkle root by checking that it starts early in the coinbase.
// 8-12 bytes are enough to encode extraNonce and nBits.
if (pc - script.begin() > 20)
return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
}
// Ensure we are at a deterministic point in the merkle leaves by hashing
// a nonce and our chain ID and comparing to the index.
pc += vchRootHash.size();
if (script.end() - pc < 8)
return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
int nSize;
memcpy(&nSize, &pc[0], 4);
if (nSize != (1 << vChainMerkleBranch.size()))
return error("Aux POW merkle branch size does not match parent coinbase");
int nNonce;
memcpy(&nNonce, &pc[4], 4);
// Choose a pseudo-random slot in the chain merkle tree
// but have it be fixed for a size/nonce/chain combination.
//
// This prevents the same work from being used twice for the
// same chain while reducing the chance that two chains clash
// for the same slot.
unsigned int rand = nNonce;
rand = rand * 1103515245 + 12345;
rand += nChainID;
rand = rand * 1103515245 + 12345;
if (nChainIndex != (rand % nSize))
return error("Aux POW wrong index");
return true;
}
CScript MakeCoinbaseWithAux(unsigned int nHeight, unsigned int nExtraNonce, vector<unsigned char>& vchAux)
{
vector<unsigned char> vchAuxWithHeader(UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
vchAuxWithHeader.insert(vchAuxWithHeader.end(), vchAux.begin(), vchAux.end());
CScript script = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
// Push OP_2 just in case we want versioning later
script = script << OP_2 << vchAuxWithHeader;
return script;
}
void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, vector<unsigned char>& vchAux)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(nHeight, nExtraNonce, vchAux);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<commit_msg>CBase58Data::SetString: cleanse the full vector<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchTemp.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inspectorhelpwindow.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2006-12-13 12:00: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
*
************************************************************************/
#ifndef INSPECTORHELPWINDOW_HXX
#include "inspectorhelpwindow.hxx"
#endif
#ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX
#include "modulepcr.hxx"
#endif
#ifndef EXTENSIONS_PROPRESID_HRC
#include "propresid.hrc"
#endif
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace pcr
{
//........................................................................
/** === begin UNO using === **/
/** === end UNO using === **/
//====================================================================
//= InspectorHelpWindow
//====================================================================
//--------------------------------------------------------------------
InspectorHelpWindow::InspectorHelpWindow( Window* _pParent )
:Window( _pParent, WB_DIALOGCONTROL )
,m_aSeparator( this )
,m_aHelpText( this, WB_LEFT | WB_READONLY | WB_AUTOVSCROLL )
,m_nMinLines( 3 )
,m_nMaxLines( 8 )
{
m_aSeparator.SetText( String( PcrRes( RID_STR_HELP_SECTION_LABEL ) ) );
m_aSeparator.Show();
m_aHelpText.SetControlBackground( m_aSeparator.GetBackground().GetColor() );
m_aHelpText.Show();
}
//--------------------------------------------------------------------
void InspectorHelpWindow::SetText( const XubString& _rStr )
{
m_aHelpText.SetText( _rStr );
}
//--------------------------------------------------------------------
void InspectorHelpWindow::SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines )
{
m_nMinLines = _nMinLines;
m_nMaxLines = _nMaxLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getHelpTextBorderHeight()
{
sal_Int32 nTop(0), nBottom(0), nDummy(0);
m_aHelpText.GetBorder( nDummy, nTop, nDummy, nBottom );
return nTop + nBottom;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getSpaceAboveTextWindow()
{
Size aSeparatorSize( LogicToPixel( Size( 0, 8 ), MAP_APPFONT ) );
Size a3AppFontSize( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );
return aSeparatorSize.Height() + a3AppFontSize.Height();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetMinimalHeightPixel()
{
return impl_getMinimalTextWindowHeight() + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetMaximalHeightPixel()
{
return impl_getMaximalTextWindowHeight() + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getMinimalTextWindowHeight()
{
return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMinLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getMaximalTextWindowHeight()
{
return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMaxLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetOptimalHeightPixel()
{
// --- calc the height as needed for the mere text window
long nMinTextWindowHeight = impl_getMinimalTextWindowHeight();
long nMaxTextWindowHeight = impl_getMaximalTextWindowHeight();
Rectangle aTextRect( Point( 0, 0 ), m_aHelpText.GetOutputSizePixel() );
aTextRect = m_aHelpText.GetTextRect( aTextRect, m_aHelpText.GetText(),
TEXT_DRAW_LEFT | TEXT_DRAW_TOP | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK );
long nActTextWindowHeight = impl_getHelpTextBorderHeight() + aTextRect.GetHeight();
long nOptTextWindowHeight = ::std::max( nMinTextWindowHeight, ::std::min( nMaxTextWindowHeight, nActTextWindowHeight ) );
// --- then add the space above the text window
return nOptTextWindowHeight + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
void InspectorHelpWindow::Resize()
{
Size a3AppFont( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );
Rectangle aPlayground( Point( 0, 0 ), GetOutputSizePixel() );
Rectangle aSeparatorArea( aPlayground );
aSeparatorArea.Bottom() = aSeparatorArea.Top() + LogicToPixel( Size( 0, 8 ), MAP_APPFONT ).Height();
m_aSeparator.SetPosSizePixel( aSeparatorArea.TopLeft(), aSeparatorArea.GetSize() );
Rectangle aTextArea( aPlayground );
aTextArea.Top() = aSeparatorArea.Bottom() + a3AppFont.Height();
m_aHelpText.SetPosSizePixel( aTextArea.TopLeft(), aTextArea.GetSize() );
}
//........................................................................
} // namespace pcr
//........................................................................
<commit_msg>#i10000# add pch declaration<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: inspectorhelpwindow.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2006-12-15 02:13:45 $
*
* 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_extensions.hxx"
#ifndef INSPECTORHELPWINDOW_HXX
#include "inspectorhelpwindow.hxx"
#endif
#ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX
#include "modulepcr.hxx"
#endif
#ifndef EXTENSIONS_PROPRESID_HRC
#include "propresid.hrc"
#endif
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace pcr
{
//........................................................................
/** === begin UNO using === **/
/** === end UNO using === **/
//====================================================================
//= InspectorHelpWindow
//====================================================================
//--------------------------------------------------------------------
InspectorHelpWindow::InspectorHelpWindow( Window* _pParent )
:Window( _pParent, WB_DIALOGCONTROL )
,m_aSeparator( this )
,m_aHelpText( this, WB_LEFT | WB_READONLY | WB_AUTOVSCROLL )
,m_nMinLines( 3 )
,m_nMaxLines( 8 )
{
m_aSeparator.SetText( String( PcrRes( RID_STR_HELP_SECTION_LABEL ) ) );
m_aSeparator.Show();
m_aHelpText.SetControlBackground( m_aSeparator.GetBackground().GetColor() );
m_aHelpText.Show();
}
//--------------------------------------------------------------------
void InspectorHelpWindow::SetText( const XubString& _rStr )
{
m_aHelpText.SetText( _rStr );
}
//--------------------------------------------------------------------
void InspectorHelpWindow::SetLimits( sal_Int32 _nMinLines, sal_Int32 _nMaxLines )
{
m_nMinLines = _nMinLines;
m_nMaxLines = _nMaxLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getHelpTextBorderHeight()
{
sal_Int32 nTop(0), nBottom(0), nDummy(0);
m_aHelpText.GetBorder( nDummy, nTop, nDummy, nBottom );
return nTop + nBottom;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getSpaceAboveTextWindow()
{
Size aSeparatorSize( LogicToPixel( Size( 0, 8 ), MAP_APPFONT ) );
Size a3AppFontSize( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );
return aSeparatorSize.Height() + a3AppFontSize.Height();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetMinimalHeightPixel()
{
return impl_getMinimalTextWindowHeight() + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetMaximalHeightPixel()
{
return impl_getMaximalTextWindowHeight() + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getMinimalTextWindowHeight()
{
return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMinLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::impl_getMaximalTextWindowHeight()
{
return impl_getHelpTextBorderHeight() + m_aHelpText.GetTextHeight() * m_nMaxLines;
}
//--------------------------------------------------------------------
long InspectorHelpWindow::GetOptimalHeightPixel()
{
// --- calc the height as needed for the mere text window
long nMinTextWindowHeight = impl_getMinimalTextWindowHeight();
long nMaxTextWindowHeight = impl_getMaximalTextWindowHeight();
Rectangle aTextRect( Point( 0, 0 ), m_aHelpText.GetOutputSizePixel() );
aTextRect = m_aHelpText.GetTextRect( aTextRect, m_aHelpText.GetText(),
TEXT_DRAW_LEFT | TEXT_DRAW_TOP | TEXT_DRAW_MULTILINE | TEXT_DRAW_WORDBREAK );
long nActTextWindowHeight = impl_getHelpTextBorderHeight() + aTextRect.GetHeight();
long nOptTextWindowHeight = ::std::max( nMinTextWindowHeight, ::std::min( nMaxTextWindowHeight, nActTextWindowHeight ) );
// --- then add the space above the text window
return nOptTextWindowHeight + impl_getSpaceAboveTextWindow();
}
//--------------------------------------------------------------------
void InspectorHelpWindow::Resize()
{
Size a3AppFont( LogicToPixel( Size( 3, 3 ), MAP_APPFONT ) );
Rectangle aPlayground( Point( 0, 0 ), GetOutputSizePixel() );
Rectangle aSeparatorArea( aPlayground );
aSeparatorArea.Bottom() = aSeparatorArea.Top() + LogicToPixel( Size( 0, 8 ), MAP_APPFONT ).Height();
m_aSeparator.SetPosSizePixel( aSeparatorArea.TopLeft(), aSeparatorArea.GetSize() );
Rectangle aTextArea( aPlayground );
aTextArea.Top() = aSeparatorArea.Bottom() + a3AppFont.Height();
m_aHelpText.SetPosSizePixel( aTextArea.TopLeft(), aTextArea.GetSize() );
}
//........................................................................
} // namespace pcr
//........................................................................
<|endoftext|> |
<commit_before>/// \file buffer.cpp
/// Contains the main code for the Buffer.
#include <fcntl.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <sys/time.h>
#include "buffer_stream.h"
/// Holds all code unique to the Buffer.
namespace Buffer{
volatile bool buffer_running = true; ///< Set to false when shutting down.
Stream * thisStream = 0;
Socket::Server SS; ///< The server socket.
/// Gets the current system time in milliseconds.
unsigned int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec + t.tv_usec/1000;
}//getNowMS
///A simple signal handler that ignores all signals.
void termination_handler (int signum){
switch (signum){
case SIGKILL: buffer_running = false; break;
case SIGPIPE: return; break;
default: return; break;
}
}
void handleStats(void * empty){
if (empty != 0){return;}
Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
while (buffer_running){
usleep(1000000); //sleep one second
if (!StatsSocket.connected()){
StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
}
if (StatsSocket.connected()){
StatsSocket.write(Stream::get()->getStats()+"\n\n");
}
}
}
void handleUser(void * v_usr){
user * usr = (user*)v_usr;
std::cerr << "Thread launched for user " << usr->MyStr << ", socket number " << usr->S.getSocket() << std::endl;
usr->myRing = thisStream->getRing();
if (!usr->S.write(thisStream->getHeader())){
usr->Disconnect("failed to receive the header!");
return;
}
while (usr->S.connected()){
usleep(5000); //sleep 5ms
if (usr->S.canRead()){
usr->inbuffer.clear();
char charbuf;
while ((usr->S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){
usr->inbuffer += charbuf;
}
if (usr->inbuffer != ""){
if (usr->inbuffer[0] == 'P'){
std::cout << "Push attempt from IP " << usr->inbuffer.substr(2) << std::endl;
if (thisStream->checkWaitingIP(usr->inbuffer.substr(2))){
if (thisStream->setInput(usr->S)){
std::cout << "Push accepted!" << std::endl;
usr->S = Socket::Connection(-1);
return;
}else{
usr->Disconnect("Push denied - push already in progress!");
}
}else{
usr->Disconnect("Push denied - invalid IP address!");
}
}
if (usr->inbuffer[0] == 'S'){
usr->tmpStats = Stats(usr->inbuffer.substr(2));
unsigned int secs = usr->tmpStats.conntime - usr->lastStats.conntime;
if (secs < 1){secs = 1;}
usr->curr_up = (usr->tmpStats.up - usr->lastStats.up) / secs;
usr->curr_down = (usr->tmpStats.down - usr->lastStats.down) / secs;
usr->lastStats = usr->tmpStats;
thisStream->saveStats(usr->MyStr, usr->tmpStats);
}
}
}
usr->Send();
}
thisStream->cleanUsers();
std::cerr << "User " << usr->MyStr << " disconnected, socket number " << usr->S.getSocket() << std::endl;
}
/// Loop reading DTSC data from stdin and processing it at the correct speed.
void handleStdin(void * empty){
if (empty != 0){return;}
unsigned int lastPacketTime = 0;//time in MS last packet was parsed
unsigned int currPacketTime = 0;//time of the last parsed packet (current packet)
unsigned int prevPacketTime = 0;//time of the previously parsed packet (current packet - 1)
std::string inBuffer;
char charBuffer[1024*10];
unsigned int charCount;
unsigned int now;
while (std::cin.good() && buffer_running){
//slow down packet receiving to real-time
now = getNowMS();
if ((now - lastPacketTime >= currPacketTime - prevPacketTime) || (currPacketTime <= prevPacketTime)){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
lastPacketTime = now;
prevPacketTime = currPacketTime;
currPacketTime = thisStream->getStream()->getTime();
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
std::cin.read(charBuffer, 1024*10);
charCount = std::cin.gcount();
inBuffer.append(charBuffer, charCount);
}
}else{
if (((currPacketTime - prevPacketTime) - (now - lastPacketTime)) > 999){
usleep(999000);
}else{
usleep(((currPacketTime - prevPacketTime) - (now - lastPacketTime)) * 999);
}
}
}
buffer_running = false;
SS.close();
}
/// Loop reading DTSC data from an IP push address.
/// No changes to the speed are made.
void handlePushin(void * empty){
if (empty != 0){return;}
std::string inBuffer;
while (buffer_running){
if (thisStream->getIPInput().connected()){
if (inBuffer.size() > 0){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
usleep(1000000);//1s wait
}
}
SS.close();
}
/// Starts a loop, waiting for connections to send data to.
int Start(int argc, char ** argv) {
//first make sure no segpipe signals will kill us
struct sigaction new_action;
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGPIPE, &new_action, NULL);
sigaction (SIGKILL, &new_action, NULL);
//then check and parse the commandline
if (argc < 2) {
std::cout << "usage: " << argv[0] << " streamName [awaiting_IP]" << std::endl;
return 1;
}
std::string name = argv[1];
SS = Socket::makeStream(name);
thisStream = Stream::get();
thisStream->setName(name);
Socket::Connection incoming;
Socket::Connection std_input(fileno(stdin));
tthread::thread StatsThread = tthread::thread(handleStats, 0);
tthread::thread * StdinThread = 0;
if (argc < 3){
StdinThread = new tthread::thread(handleStdin, 0);
}else{
thisStream->setWaitingIP(argv[2]);
StdinThread = new tthread::thread(handlePushin, 0);
}
while (buffer_running && SS.connected()){
//check for new connections, accept them if there are any
//starts a thread for every accepted connection
incoming = SS.accept(false);
if (incoming.connected()){
user * usr_ptr = new user(incoming);
thisStream->addUser(usr_ptr);
usr_ptr->Thread = new tthread::thread(handleUser, (void *)usr_ptr);
}
}//main loop
// disconnect listener
buffer_running = false;
std::cout << "End of input file - buffer shutting down" << std::endl;
SS.close();
StatsThread.join();
StdinThread->join();
delete thisStream;
return 0;
}
};//Buffer namespace
/// Entry point for Buffer, simply calls Buffer::Start().
int main(int argc, char ** argv){
return Buffer::Start(argc, argv);
}//main
<commit_msg>Should fix all buffer-related timing issues.<commit_after>/// \file buffer.cpp
/// Contains the main code for the Buffer.
#include <fcntl.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sstream>
#include <sys/time.h>
#include "buffer_stream.h"
/// Holds all code unique to the Buffer.
namespace Buffer{
volatile bool buffer_running = true; ///< Set to false when shutting down.
Stream * thisStream = 0;
Socket::Server SS; ///< The server socket.
/// Gets the current system time in milliseconds.
long long int getNowMS(){
timeval t;
gettimeofday(&t, 0);
return t.tv_sec * 1000 + t.tv_usec/1000;
}//getNowMS
///A simple signal handler that ignores all signals.
void termination_handler (int signum){
switch (signum){
case SIGKILL: buffer_running = false; break;
case SIGPIPE: return; break;
default: return; break;
}
}
void handleStats(void * empty){
if (empty != 0){return;}
Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
while (buffer_running){
usleep(1000000); //sleep one second
if (!StatsSocket.connected()){
StatsSocket = Socket::Connection("/tmp/mist/statistics", true);
}
if (StatsSocket.connected()){
StatsSocket.write(Stream::get()->getStats()+"\n\n");
}
}
}
void handleUser(void * v_usr){
user * usr = (user*)v_usr;
std::cerr << "Thread launched for user " << usr->MyStr << ", socket number " << usr->S.getSocket() << std::endl;
usr->myRing = thisStream->getRing();
if (!usr->S.write(thisStream->getHeader())){
usr->Disconnect("failed to receive the header!");
return;
}
while (usr->S.connected()){
usleep(5000); //sleep 5ms
if (usr->S.canRead()){
usr->inbuffer.clear();
char charbuf;
while ((usr->S.iread(&charbuf, 1) == 1) && charbuf != '\n' ){
usr->inbuffer += charbuf;
}
if (usr->inbuffer != ""){
if (usr->inbuffer[0] == 'P'){
std::cout << "Push attempt from IP " << usr->inbuffer.substr(2) << std::endl;
if (thisStream->checkWaitingIP(usr->inbuffer.substr(2))){
if (thisStream->setInput(usr->S)){
std::cout << "Push accepted!" << std::endl;
usr->S = Socket::Connection(-1);
return;
}else{
usr->Disconnect("Push denied - push already in progress!");
}
}else{
usr->Disconnect("Push denied - invalid IP address!");
}
}
if (usr->inbuffer[0] == 'S'){
usr->tmpStats = Stats(usr->inbuffer.substr(2));
unsigned int secs = usr->tmpStats.conntime - usr->lastStats.conntime;
if (secs < 1){secs = 1;}
usr->curr_up = (usr->tmpStats.up - usr->lastStats.up) / secs;
usr->curr_down = (usr->tmpStats.down - usr->lastStats.down) / secs;
usr->lastStats = usr->tmpStats;
thisStream->saveStats(usr->MyStr, usr->tmpStats);
}
}
}
usr->Send();
}
thisStream->cleanUsers();
std::cerr << "User " << usr->MyStr << " disconnected, socket number " << usr->S.getSocket() << std::endl;
}
/// Loop reading DTSC data from stdin and processing it at the correct speed.
void handleStdin(void * empty){
if (empty != 0){return;}
long long int timeDiff = 0;//difference between local time and stream time
unsigned int lastPacket = 0;//last parsed packet timestamp
std::string inBuffer;
char charBuffer[1024*10];
unsigned int charCount;
long long int now;
while (std::cin.good() && buffer_running){
//slow down packet receiving to real-time
now = getNowMS();
if ((now - timeDiff >= lastPacket) || (lastPacket - (now - timeDiff) > 5000)){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
lastPacket = thisStream->getStream()->getTime();
if ((now - timeDiff - lastPacket) > 5000 || (now - timeDiff - lastPacket < -5000)){
timeDiff = now - lastPacket;
}
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
std::cin.read(charBuffer, 1024*10);
charCount = std::cin.gcount();
inBuffer.append(charBuffer, charCount);
}
}else{
if ((lastPacket - (now - timeDiff)) > 999){
usleep(999000);
}else{
usleep((lastPacket - (now - timeDiff)) * 1000);
}
}
}
buffer_running = false;
SS.close();
}
/// Loop reading DTSC data from an IP push address.
/// No changes to the speed are made.
void handlePushin(void * empty){
if (empty != 0){return;}
std::string inBuffer;
while (buffer_running){
if (thisStream->getIPInput().connected()){
if (inBuffer.size() > 0){
thisStream->getWriteLock();
if (thisStream->getStream()->parsePacket(inBuffer)){
thisStream->getStream()->outPacket(0);
thisStream->dropWriteLock(true);
}else{
thisStream->dropWriteLock(false);
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
thisStream->getIPInput().iread(inBuffer);
usleep(1000);//1ms wait
}
}else{
usleep(1000000);//1s wait
}
}
SS.close();
}
/// Starts a loop, waiting for connections to send data to.
int Start(int argc, char ** argv) {
//first make sure no segpipe signals will kill us
struct sigaction new_action;
new_action.sa_handler = termination_handler;
sigemptyset (&new_action.sa_mask);
new_action.sa_flags = 0;
sigaction (SIGPIPE, &new_action, NULL);
sigaction (SIGKILL, &new_action, NULL);
//then check and parse the commandline
if (argc < 2) {
std::cout << "usage: " << argv[0] << " streamName [awaiting_IP]" << std::endl;
return 1;
}
std::string name = argv[1];
SS = Socket::makeStream(name);
thisStream = Stream::get();
thisStream->setName(name);
Socket::Connection incoming;
Socket::Connection std_input(fileno(stdin));
tthread::thread StatsThread = tthread::thread(handleStats, 0);
tthread::thread * StdinThread = 0;
if (argc < 3){
StdinThread = new tthread::thread(handleStdin, 0);
}else{
thisStream->setWaitingIP(argv[2]);
StdinThread = new tthread::thread(handlePushin, 0);
}
while (buffer_running && SS.connected()){
//check for new connections, accept them if there are any
//starts a thread for every accepted connection
incoming = SS.accept(false);
if (incoming.connected()){
user * usr_ptr = new user(incoming);
thisStream->addUser(usr_ptr);
usr_ptr->Thread = new tthread::thread(handleUser, (void *)usr_ptr);
}
}//main loop
// disconnect listener
buffer_running = false;
std::cout << "End of input file - buffer shutting down" << std::endl;
SS.close();
StatsThread.join();
StdinThread->join();
delete thisStream;
return 0;
}
};//Buffer namespace
/// Entry point for Buffer, simply calls Buffer::Start().
int main(int argc, char ** argv){
return Buffer::Start(argc, argv);
}//main
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_collection.cpp implementation of the GLC_Collection class.
#include <QtDebug>
#include "glc_collection.h"
//////////////////////////////////////////////////////////////////////
// Constructor/Destructor
//////////////////////////////////////////////////////////////////////
GLC_Collection::GLC_Collection()
: m_ListID(0)
, m_ListIsValid(false)
, m_pBoundingBox(NULL)
{
}
GLC_Collection::~GLC_Collection()
{
// Delete all collection's elements and the collection bounding box
erase();
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add geometrys to the collection
bool GLC_Collection::addGLC_Geom(GLC_Geometry* pGeom)
{
CNodeMap::iterator iGeom= m_TheMap.find(pGeom->getID());
if (iGeom == m_TheMap.end())
{ // Ok, la cl n'est pas prise
// Create an GLC_CollectionNode
GLC_CollectionNode* p_CollectionNode= new GLC_CollectionNode(pGeom);
// Add the collection Node
m_TheMap.insert(pGeom->getID(), p_CollectionNode);
qDebug("GLC_Collection::AddGLC_Geom : Element Ajout avec succs");
// Validit de la liste
m_ListIsValid= false;
return true;
}
else
{ // KO, la cl est prise
qDebug("GLC_Collection::AddGLC_Geom : Element already in collection");
return false;
}
}
// Delete geometry from the collection
bool GLC_Collection::delGLC_Geom(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, the key exist
delete iGeom.value(); // delete the collection Node
m_TheMap.remove(Key); // Delete the conteneur
// Search the list
// List validity
m_ListIsValid= false;
qDebug("GLC_Collection::DelGLC_Geom : Element succesfuly deleted");
return true;
}
else
{ // KO, key doesn't exist
qDebug("GLC_Collection::DelGLC_Geom : Element not deleted");
return false;
}
}
// Remove geometry from the collection
bool GLC_Collection::remGLC_Geom(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, the key exist
// don't delete collection node
m_TheMap.remove(Key); // Supprime le conteneur
// List validity
m_ListIsValid= false;
//qDebug("GLC_Collection::remGLC_Geom : Element Supprim avec succs");
return true;
}
else
{ // KO, key doesn't exist
qDebug("GLC_Collection::RemGLC_Geom : Element not deleted");
return false;
}
}
// Clear the collection
void GLC_Collection::erase(void)
{
// Suppression des gomtries
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
// Supprime l'objet
delete iEntry.value();
++iEntry;
}
// Vide la table de hachage principale
m_TheMap.clear();
// Fin de la Suppression des gomtries
// Supprime la liste d'affichage
deleteList();
// Fin des Suppressions des sous listes d'affichages
// delete the boundingBox
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::getElement(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, la cl est trouv
return iGeom.value()->getGeometry();
}
else
{ // KO, la cl n'est pas trouv
return NULL;
}
}
// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::getElement(int Index)
{
// Warning, performance will be poor
int CurrentPos= 0;
CNodeMap::iterator iEntry= m_TheMap.begin();
GLC_Geometry* pGeom= NULL;
while ((iEntry != m_TheMap.constEnd()) && (CurrentPos <= Index ))
{
// retrieve the object
if(CurrentPos == Index) pGeom= iEntry.value()->getGeometry();
++iEntry;
++CurrentPos;
}
return pGeom;
}
//! return the collection Bounding Box
GLC_BoundingBox GLC_Collection::getBoundingBox(void)
{
if (!((m_pBoundingBox != NULL) && m_ListIsValid) && (getNumber() > 0))
{
CNodeMap::iterator iEntry= m_TheMap.begin();
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
m_pBoundingBox= new GLC_BoundingBox();
while (iEntry != m_TheMap.constEnd())
{
// Combine Collection BoundingBox with element Bounding Box
m_pBoundingBox->combine(iEntry.value()->getBoundingBox());
++iEntry;
}
if (m_pBoundingBox->isEmpty())
{
delete m_pBoundingBox;
GLC_Vector4d lower(-0.5, -0.5, -0.5);
GLC_Vector4d upper(0.5, 0.5, 0.5);
m_pBoundingBox= new GLC_BoundingBox(lower, upper);
}
}
else if (!((m_pBoundingBox != NULL) && m_ListIsValid))
{
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
GLC_Vector4d lower(-0.5, -0.5, -0.5);
GLC_Vector4d upper(0.5, 0.5, 0.5);
m_pBoundingBox= new GLC_BoundingBox(lower, upper);
}
return *m_pBoundingBox;
}
//////////////////////////////////////////////////////////////////////
// Fonctions OpenGL
//////////////////////////////////////////////////////////////////////
void GLC_Collection::glExecute(void)
{
//qDebug() << "GLC_Collection::glExecute";
if (getNumber() > 0)
{
createMemberLists(); // Si ncessaire
//CreateSubLists(); // Si ncessaire
if (m_ListIsValid)
{ // La liste de la collection OK
glCallList(m_ListID);
}
else
{
if(memberIsUpToDate())
{
createList();
// delete the boundingBox
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
else
{
m_ListIsValid= false;
qDebug("GLC_Collection::GlExecute : CreatMemberList KO -> display list not use");
}
}
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::GlExecute OPENGL ERROR %s", errString);
}
}
}
// Affiche les lments de la collection
void GLC_Collection::glDraw(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
m_pBoundingBox= new GLC_BoundingBox();
while (iEntry != m_TheMap.constEnd())
{
iEntry.value()->glExecute();
// Combine Collection BoundingBox with element Bounding Box
m_pBoundingBox->combine(iEntry.value()->getBoundingBox());
++iEntry;
}
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::GlDraw OPENGL ERROR %s", errString);
}
}
// Cration des listes d'affichages des membres
void GLC_Collection::createMemberLists(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
//qDebug("GLC_Collection::CreateMemberList ENTER");
while (iEntry != m_TheMap.constEnd())
{
if(!iEntry.value()->getListValidity())
{
iEntry.value()->glExecute(GL_COMPILE);
}
// Passe au Suivant
iEntry++;
}
// Gestion erreur OpenGL
if (glGetError() != GL_NO_ERROR)
{
qDebug("GLC_Collection::CreateMemberList OPENGL ERROR");
}
}
/*
// Cration des sous listes d'affichages
void GLC_Collection::CreateSubLists(void)
{
//qDebug() << "GLC_Collection::CreateSubLists";
CNodeMap::iterator iEntry= m_TheMap.begin();
CListeMap::iterator iListEntry;
GLuint ListeID= 0;
while (iEntry != m_TheMap.constEnd())
{
if(!iEntry.value()->getValidity())
{
iListEntry= m_ListMap.find(iEntry.key());
assert(iListEntry != m_ListMap.constEnd());
if (iListEntry.value() == 0)
{// Numro non gnr
qDebug() << "GLC_Collection::CreateSubLists: List not found";
ListeID= glGenLists(1);
m_ListMap[iListEntry.key()]= ListeID;
m_ListIsValid= false;
}
else
{
ListeID= iListEntry.value();
}
// Cration de la liste
glNewList(ListeID, GL_COMPILE);
iEntry.value()->glExecute(GL_COMPILE);
glEndList();
qDebug("GLC_Collection::CreateSubLists : Display list %u created", ListeID);
}
// Passe au Suivant
iEntry++;
}
// Gestion erreur OpenGL
if (glGetError() != GL_NO_ERROR)
{
qDebug("GLC_Collection::CreateSubLists ERREUR OPENGL");
}
}
*/
//////////////////////////////////////////////////////////////////////
// Fonctions de services prives
//////////////////////////////////////////////////////////////////////
// Verifie si les listes membres sont jour
bool GLC_Collection::memberIsUpToDate(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
if(iEntry.value()->getListValidity() || !iEntry.value()->getGeometry()->isVisible())
{ // Gomtrie valide ou non visible.
iEntry++;
}
else
{
qDebug("GLC_Collection::MemberListIsUpToDate : Child display list not updated");
return false;
}
}
return true; // Toutes les listes sont jour
}
/*
// Verifie si les membres sont jour
bool GLC_Collection::memberIsUpToDate(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
if(iEntry.value()->getValidity() || !iEntry.value()->isVisible())
{ // Membre valide ou non visible.
iEntry++;
}
else
{
//qDebug("GLC_Collection::memberIsUpToDate : Prop Geom d'un enfant non jour");
return false;
}
}
return true; // Toutes les Membres sont jour
}
*/
// Cration de la liste d'affichage de la collection
bool GLC_Collection::createList(void)
{
qDebug("GLC_Collection::CreateList");
if(!m_ListID) // La liste n'a jamais t cr
{
m_ListID= glGenLists(1);
if (!m_ListID) // ID de liste non obtenu
{
glDraw();
qDebug("GLC_Collection::CreateList : Display list nor created");
return false; // Gomtrie affich mais pas de liste de cr
}
}
// Cration de la liste
glNewList(m_ListID, GL_COMPILE_AND_EXECUTE);
// Affichage des lments de la collection
glDraw();
glEndList();
// Validit de la liste
m_ListIsValid= true;
//qDebug("GLC_Collection::createList : Liste d'affichage %u cr", m_ListID);
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::CreateList OPENGL ERROR %s\n", errString);
}
return true; // Gomtrie affich et liste cr
}
<commit_msg>GLC_Collection::createMemberLists : Bug fix when getListValidity() is false, the bounding box is invalid and deleted.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_collection.cpp implementation of the GLC_Collection class.
#include <QtDebug>
#include "glc_collection.h"
//////////////////////////////////////////////////////////////////////
// Constructor/Destructor
//////////////////////////////////////////////////////////////////////
GLC_Collection::GLC_Collection()
: m_ListID(0)
, m_ListIsValid(false)
, m_pBoundingBox(NULL)
{
}
GLC_Collection::~GLC_Collection()
{
// Delete all collection's elements and the collection bounding box
erase();
}
//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add geometrys to the collection
bool GLC_Collection::addGLC_Geom(GLC_Geometry* pGeom)
{
CNodeMap::iterator iGeom= m_TheMap.find(pGeom->getID());
if (iGeom == m_TheMap.end())
{ // Ok, la cl n'est pas prise
// Create an GLC_CollectionNode
GLC_CollectionNode* p_CollectionNode= new GLC_CollectionNode(pGeom);
// Add the collection Node
m_TheMap.insert(pGeom->getID(), p_CollectionNode);
qDebug("GLC_Collection::AddGLC_Geom : Element Ajout avec succs");
// Validit de la liste
m_ListIsValid= false;
return true;
}
else
{ // KO, la cl est prise
qDebug("GLC_Collection::AddGLC_Geom : Element already in collection");
return false;
}
}
// Delete geometry from the collection
bool GLC_Collection::delGLC_Geom(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, the key exist
delete iGeom.value(); // delete the collection Node
m_TheMap.remove(Key); // Delete the conteneur
// Search the list
// List validity
m_ListIsValid= false;
qDebug("GLC_Collection::DelGLC_Geom : Element succesfuly deleted");
return true;
}
else
{ // KO, key doesn't exist
qDebug("GLC_Collection::DelGLC_Geom : Element not deleted");
return false;
}
}
// Remove geometry from the collection
bool GLC_Collection::remGLC_Geom(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, the key exist
// don't delete collection node
m_TheMap.remove(Key); // Supprime le conteneur
// List validity
m_ListIsValid= false;
//qDebug("GLC_Collection::remGLC_Geom : Element Supprim avec succs");
return true;
}
else
{ // KO, key doesn't exist
qDebug("GLC_Collection::RemGLC_Geom : Element not deleted");
return false;
}
}
// Clear the collection
void GLC_Collection::erase(void)
{
// Suppression des gomtries
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
// Supprime l'objet
delete iEntry.value();
++iEntry;
}
// Vide la table de hachage principale
m_TheMap.clear();
// Fin de la Suppression des gomtries
// Supprime la liste d'affichage
deleteList();
// Fin des Suppressions des sous listes d'affichages
// delete the boundingBox
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::getElement(GLC_uint Key)
{
CNodeMap::iterator iGeom= m_TheMap.find(Key);
if (iGeom != m_TheMap.end())
{ // Ok, la cl est trouv
return iGeom.value()->getGeometry();
}
else
{ // KO, la cl n'est pas trouv
return NULL;
}
}
// Retourne le pointeur d'un lment de la collection
GLC_Geometry* GLC_Collection::getElement(int Index)
{
// Warning, performance will be poor
int CurrentPos= 0;
CNodeMap::iterator iEntry= m_TheMap.begin();
GLC_Geometry* pGeom= NULL;
while ((iEntry != m_TheMap.constEnd()) && (CurrentPos <= Index ))
{
// retrieve the object
if(CurrentPos == Index) pGeom= iEntry.value()->getGeometry();
++iEntry;
++CurrentPos;
}
return pGeom;
}
//! return the collection Bounding Box
GLC_BoundingBox GLC_Collection::getBoundingBox(void)
{
if (!((m_pBoundingBox != NULL) && m_ListIsValid) && (getNumber() > 0))
{
CNodeMap::iterator iEntry= m_TheMap.begin();
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
m_pBoundingBox= new GLC_BoundingBox();
while (iEntry != m_TheMap.constEnd())
{
// Combine Collection BoundingBox with element Bounding Box
m_pBoundingBox->combine(iEntry.value()->getBoundingBox());
++iEntry;
}
if (m_pBoundingBox->isEmpty())
{
delete m_pBoundingBox;
GLC_Vector4d lower(-0.5, -0.5, -0.5);
GLC_Vector4d upper(0.5, 0.5, 0.5);
m_pBoundingBox= new GLC_BoundingBox(lower, upper);
}
}
else if (!((m_pBoundingBox != NULL) && m_ListIsValid))
{
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
GLC_Vector4d lower(-0.5, -0.5, -0.5);
GLC_Vector4d upper(0.5, 0.5, 0.5);
m_pBoundingBox= new GLC_BoundingBox(lower, upper);
}
return *m_pBoundingBox;
}
//////////////////////////////////////////////////////////////////////
// Fonctions OpenGL
//////////////////////////////////////////////////////////////////////
void GLC_Collection::glExecute(void)
{
//qDebug() << "GLC_Collection::glExecute";
if (getNumber() > 0)
{
createMemberLists(); // Si ncessaire
//CreateSubLists(); // Si ncessaire
if (m_ListIsValid)
{ // La liste de la collection OK
glCallList(m_ListID);
}
else
{
if(memberIsUpToDate())
{
createList();
// delete the boundingBox
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
else
{
m_ListIsValid= false;
qDebug("GLC_Collection::GlExecute : CreatMemberList KO -> display list not use");
}
}
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::GlExecute OPENGL ERROR %s", errString);
}
}
}
// Affiche les lments de la collection
void GLC_Collection::glDraw(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
m_pBoundingBox= new GLC_BoundingBox();
while (iEntry != m_TheMap.constEnd())
{
iEntry.value()->glExecute();
// Combine Collection BoundingBox with element Bounding Box
m_pBoundingBox->combine(iEntry.value()->getBoundingBox());
++iEntry;
}
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::GlDraw OPENGL ERROR %s", errString);
}
}
// Cration des listes d'affichages des membres
void GLC_Collection::createMemberLists(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
//qDebug("GLC_Collection::CreateMemberList ENTER");
while (iEntry != m_TheMap.constEnd())
{
if(!iEntry.value()->getListValidity())
{
iEntry.value()->glExecute(GL_COMPILE);
if (m_pBoundingBox != NULL)
{
delete m_pBoundingBox;
m_pBoundingBox= NULL;
}
}
// Passe au Suivant
iEntry++;
}
// Gestion erreur OpenGL
if (glGetError() != GL_NO_ERROR)
{
qDebug("GLC_Collection::CreateMemberList OPENGL ERROR");
}
}
/*
// Cration des sous listes d'affichages
void GLC_Collection::CreateSubLists(void)
{
//qDebug() << "GLC_Collection::CreateSubLists";
CNodeMap::iterator iEntry= m_TheMap.begin();
CListeMap::iterator iListEntry;
GLuint ListeID= 0;
while (iEntry != m_TheMap.constEnd())
{
if(!iEntry.value()->getValidity())
{
iListEntry= m_ListMap.find(iEntry.key());
assert(iListEntry != m_ListMap.constEnd());
if (iListEntry.value() == 0)
{// Numro non gnr
qDebug() << "GLC_Collection::CreateSubLists: List not found";
ListeID= glGenLists(1);
m_ListMap[iListEntry.key()]= ListeID;
m_ListIsValid= false;
}
else
{
ListeID= iListEntry.value();
}
// Cration de la liste
glNewList(ListeID, GL_COMPILE);
iEntry.value()->glExecute(GL_COMPILE);
glEndList();
qDebug("GLC_Collection::CreateSubLists : Display list %u created", ListeID);
}
// Passe au Suivant
iEntry++;
}
// Gestion erreur OpenGL
if (glGetError() != GL_NO_ERROR)
{
qDebug("GLC_Collection::CreateSubLists ERREUR OPENGL");
}
}
*/
//////////////////////////////////////////////////////////////////////
// Fonctions de services prives
//////////////////////////////////////////////////////////////////////
// Verifie si les listes membres sont jour
bool GLC_Collection::memberIsUpToDate(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
if(iEntry.value()->getListValidity() || !iEntry.value()->getGeometry()->isVisible())
{ // Gomtrie valide ou non visible.
iEntry++;
}
else
{
qDebug("GLC_Collection::MemberListIsUpToDate : Child display list not updated");
return false;
}
}
return true; // Toutes les listes sont jour
}
/*
// Verifie si les membres sont jour
bool GLC_Collection::memberIsUpToDate(void)
{
CNodeMap::iterator iEntry= m_TheMap.begin();
while (iEntry != m_TheMap.constEnd())
{
if(iEntry.value()->getValidity() || !iEntry.value()->isVisible())
{ // Membre valide ou non visible.
iEntry++;
}
else
{
//qDebug("GLC_Collection::memberIsUpToDate : Prop Geom d'un enfant non jour");
return false;
}
}
return true; // Toutes les Membres sont jour
}
*/
// Cration de la liste d'affichage de la collection
bool GLC_Collection::createList(void)
{
qDebug("GLC_Collection::CreateList");
if(!m_ListID) // La liste n'a jamais t cr
{
m_ListID= glGenLists(1);
if (!m_ListID) // ID de liste non obtenu
{
glDraw();
qDebug("GLC_Collection::CreateList : Display list nor created");
return false; // Gomtrie affich mais pas de liste de cr
}
}
// Cration de la liste
glNewList(m_ListID, GL_COMPILE_AND_EXECUTE);
// Affichage des lments de la collection
glDraw();
glEndList();
// Validit de la liste
m_ListIsValid= true;
//qDebug("GLC_Collection::createList : Liste d'affichage %u cr", m_ListID);
// Gestion erreur OpenGL
GLenum errCode;
if ((errCode= glGetError()) != GL_NO_ERROR)
{
const GLubyte* errString;
errString = gluErrorString(errCode);
qDebug("GLC_Collection::CreateList OPENGL ERROR %s\n", errString);
}
return true; // Gomtrie affich et liste cr
}
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.9, packaged on May, 2008.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_stltoworld.cpp implementation of the GLC_StlToWorld class.
#include <QTextStream>
#include <QFileInfo>
#include <QGLContext>
#include <QDataStream>
#include "glc_mesh2.h"
#include "glc_stltoworld.h"
#include "glc_world.h"
#include "glc_fileformatexception.h"
GLC_StlToWorld::GLC_StlToWorld(const QGLContext *pContext)
: m_pWorld(NULL)
, m_FileName()
, m_pQGLContext(pContext)
, m_CurrentLineNumber(0)
, m_StlStream()
, m_pCurrentMesh(NULL)
, m_CurVertexIndex(0)
, m_CurNormalIndex(0)
{
}
GLC_StlToWorld::~GLC_StlToWorld()
{
clear();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_World from an input STL File
GLC_World* GLC_StlToWorld::CreateWorldFromStl(QFile &file)
{
clear();
m_FileName= file.fileName();
//////////////////////////////////////////////////////////////////
// Test if the file exist and can be opened
//////////////////////////////////////////////////////////////////
if (!file.open(QIODevice::ReadOnly))
{
QString message(QString("GLC_StlToWorld::CreateWorldFromStl File ") + m_FileName + QString(" doesn't exist"));
GLC_FileFormatException fileFormatException(message, m_FileName);
throw(fileFormatException);
}
//////////////////////////////////////////////////////////////////
// Init member
//////////////////////////////////////////////////////////////////
m_pWorld= new GLC_World;
// Create Working variables
int currentQuantumValue= 0;
int previousQuantumValue= 0;
int numberOfLine= 0;
// Attach the stream to the file
m_StlStream.setDevice(&file);
// QString buffer
QString lineBuff;
//////////////////////////////////////////////////////////////////
// Count the number of lines of the STL file
//////////////////////////////////////////////////////////////////
while (!m_StlStream.atEnd())
{
++numberOfLine;
m_StlStream.readLine();
}
//////////////////////////////////////////////////////////////////
// Reset the stream
//////////////////////////////////////////////////////////////////
m_StlStream.resetStatus();
m_StlStream.seek(0);
//////////////////////////////////////////////////////////////////
// Read Buffer and create the world
//////////////////////////////////////////////////////////////////
emit currentQuantum(currentQuantumValue);
m_CurrentLineNumber= 0;
// Search Object section in the STL
// Test if the STL File is ASCII or Binary
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff.trimmed();
if (!lineBuff.startsWith("solid"))
{
// The STL File is not ASCII trying to load Binary STL File
m_pCurrentMesh= new GLC_Mesh2();
file.reset();
LoadBinariStl(file);
}
else
{
// The STL File is ASCII
lineBuff.remove(0, 5);
lineBuff.trimmed();
m_pCurrentMesh= new GLC_Mesh2();
m_pCurrentMesh->setName(lineBuff);
// Read the mesh facet
while (!m_StlStream.atEnd())
{
scanFacet();
currentQuantumValue = static_cast<int>((static_cast<double>(m_CurrentLineNumber) / numberOfLine) * 100);
if (currentQuantumValue > previousQuantumValue)
{
emit currentQuantum(currentQuantumValue);
}
previousQuantumValue= currentQuantumValue;
}
}
file.close();
GLC_Instance instance(m_pCurrentMesh);
m_pCurrentMesh= NULL;
m_pWorld->rootProduct()->addChildPart(instance);
return m_pWorld;
}
/////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// clear stlToWorld allocate memmory and reset member
void GLC_StlToWorld::clear()
{
if (NULL != m_pCurrentMesh)
{
delete m_pCurrentMesh;
m_pCurrentMesh= NULL;
}
m_pWorld= NULL;
m_FileName.clear();
m_CurrentLineNumber= 0;
m_pCurrentMesh= NULL;
m_CurVertexIndex= 0;
m_CurNormalIndex= 0;
}
// Scan a line previously extracted from STL file
void GLC_StlToWorld::scanFacet()
{
////////////////////////////////////////////// Test end of solid section////////////////////
++m_CurrentLineNumber;
QString lineBuff(m_StlStream.readLine());
lineBuff= lineBuff.trimmed();
// Test if this is the end of STL File
if (lineBuff.startsWith("endsolid"))
{
return;
}
////////////////////////////////////////////// Facet Normal////////////////////////////////
// lineBuff Must begin with "facet normal"
if (!lineBuff.startsWith("facet normal"))
{
QString message= "GLC_StlToWorld::scanFacet : \"facet normal\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
lineBuff.remove(0,12); // Remove first 12 chars
lineBuff= lineBuff.trimmed();
m_pCurrentMesh->addNormal(m_CurNormalIndex++, extract3dVect(lineBuff));
////////////////////////////////////////////// Outer Loop////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed();
// lineBuff Must begin with "outer loop"
if (!lineBuff.startsWith("outer loop"))
{
QString message= "GLC_StlToWorld::scanFacet : \"outer loop\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
////////////////////////////////////////////// Vertex ////////////////////////////////
QVector<int> vectorMaterial;
QVector<int> vectorCoordinate;
QVector<int> vectorNormal;
for (int i= 0; i < 3; ++i)
{
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed();
// lineBuff Must begin with "vertex"
if (!lineBuff.startsWith("vertex"))
{
QString message= "GLC_StlToWorld::scanFacet : \"vertex\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
lineBuff.remove(0,6); // Remove first 6 chars
lineBuff= lineBuff.trimmed();
vectorCoordinate.append(m_CurVertexIndex);
vectorMaterial.append(-1); // There is no material information
vectorNormal.append(m_CurNormalIndex - 1);
m_pCurrentMesh->addVertex(m_CurVertexIndex++, extract3dVect(lineBuff));
}
// Add the face to the current mesh
m_pCurrentMesh->addFace(vectorMaterial, vectorCoordinate, vectorNormal);
////////////////////////////////////////////// End Loop////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed();
// lineBuff Must begin with "endloop"
if (!lineBuff.startsWith("endloop"))
{
QString message= "GLC_StlToWorld::scanFacet : \"endloop\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
////////////////////////////////////////////// End Facet////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed();
// lineBuff Must begin with "endfacet"
if (!lineBuff.startsWith("endfacet"))
{
QString message= "GLC_StlToWorld::scanFacet : \"endfacet\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
}
// Extract a Vector from a string
GLC_Vector3d GLC_StlToWorld::extract3dVect(QString &line)
{
double x=0.0;
double y=0.0;
double z=0.0;
GLC_Vector3d vectResult;
QTextStream stringVecteur(&line);
QString xString, yString, zString;
if (((stringVecteur >> xString >> yString >> zString).status() == QTextStream::Ok))
{
bool xOk, yOk, zOk;
x= xString.toDouble(&xOk);
y= yString.toDouble(&yOk);
z= zString.toDouble(&zOk);
if (!(xOk && yOk && zOk))
{
QString message= "GLC_StlToWorld::extract3dVect : failed to convert vector component to double";
message.append("\nAt ligne : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
else
{
vectResult.setVect(x, y, z);
}
}
return vectResult;
}
// Load Binarie STL File
void GLC_StlToWorld::LoadBinariStl(QFile &file)
{
// Create Working variables
int currentQuantumValue= 0;
int previousQuantumValue= 0;
QDataStream stlBinFile(&file);
// Pehaps just for mac ??
stlBinFile.setByteOrder(QDataStream::LittleEndian);
// Skip 80 Bytes STL header
int SkipedData= stlBinFile.skipRawData(80);
qDebug() << SkipedData;
// Check if an error occur
if (-1 == SkipedData)
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to skip Header of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
// Read the number of facet
quint32 numberOfFacet= 0;
stlBinFile >> numberOfFacet;
qDebug() << numberOfFacet;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the number of facets of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
for (quint32 i= 0; i < numberOfFacet; ++i)
{
// Extract the facet normal
float x, y, z;
stlBinFile >> x >> y >> z;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the Normal of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
m_pCurrentMesh->addNormal(m_CurNormalIndex++, GLC_Vector3d(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z)));
QVector<int> vectorMaterial;
QVector<int> vectorCoordinate;
QVector<int> vectorNormal;
// Extract the 3 Vertexs
for (int j= 0; j < 3; ++j)
{
stlBinFile >> x >> y >> z;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the Vertex of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
vectorCoordinate.append(m_CurVertexIndex);
vectorMaterial.append(-1); // There is no material information
vectorNormal.append(m_CurNormalIndex - 1);
m_pCurrentMesh->addVertex(m_CurVertexIndex++, GLC_Vector3d(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z)));
}
currentQuantumValue = static_cast<int>((static_cast<double>(i + 1) / numberOfFacet) * 100);
if (currentQuantumValue > previousQuantumValue)
{
emit currentQuantum(currentQuantumValue);
}
previousQuantumValue= currentQuantumValue;
// Add the face to the current mesh
m_pCurrentMesh->addFace(vectorMaterial, vectorCoordinate, vectorNormal);
// Skip 2 fill-bytes not needed !!!!
stlBinFile.skipRawData(2);
}
}
<commit_msg>Improve stl file format support. Convert all ASCII STL key word in lower case.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.9, packaged on May, 2008.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_stltoworld.cpp implementation of the GLC_StlToWorld class.
#include <QTextStream>
#include <QFileInfo>
#include <QGLContext>
#include <QDataStream>
#include "glc_mesh2.h"
#include "glc_stltoworld.h"
#include "glc_world.h"
#include "glc_fileformatexception.h"
GLC_StlToWorld::GLC_StlToWorld(const QGLContext *pContext)
: m_pWorld(NULL)
, m_FileName()
, m_pQGLContext(pContext)
, m_CurrentLineNumber(0)
, m_StlStream()
, m_pCurrentMesh(NULL)
, m_CurVertexIndex(0)
, m_CurNormalIndex(0)
{
}
GLC_StlToWorld::~GLC_StlToWorld()
{
clear();
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_World from an input STL File
GLC_World* GLC_StlToWorld::CreateWorldFromStl(QFile &file)
{
clear();
m_FileName= file.fileName();
//////////////////////////////////////////////////////////////////
// Test if the file exist and can be opened
//////////////////////////////////////////////////////////////////
if (!file.open(QIODevice::ReadOnly))
{
QString message(QString("GLC_StlToWorld::CreateWorldFromStl File ") + m_FileName + QString(" doesn't exist"));
GLC_FileFormatException fileFormatException(message, m_FileName);
throw(fileFormatException);
}
//////////////////////////////////////////////////////////////////
// Init member
//////////////////////////////////////////////////////////////////
m_pWorld= new GLC_World;
// Create Working variables
int currentQuantumValue= 0;
int previousQuantumValue= 0;
int numberOfLine= 0;
// Attach the stream to the file
m_StlStream.setDevice(&file);
// QString buffer
QString lineBuff;
//////////////////////////////////////////////////////////////////
// Count the number of lines of the STL file
//////////////////////////////////////////////////////////////////
while (!m_StlStream.atEnd())
{
++numberOfLine;
m_StlStream.readLine();
}
//////////////////////////////////////////////////////////////////
// Reset the stream
//////////////////////////////////////////////////////////////////
m_StlStream.resetStatus();
m_StlStream.seek(0);
//////////////////////////////////////////////////////////////////
// Read Buffer and create the world
//////////////////////////////////////////////////////////////////
emit currentQuantum(currentQuantumValue);
m_CurrentLineNumber= 0;
// Search Object section in the STL
// Test if the STL File is ASCII or Binary
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed().toLower();
if (!lineBuff.startsWith("solid"))
{
// The STL File is not ASCII trying to load Binary STL File
m_pCurrentMesh= new GLC_Mesh2();
file.reset();
LoadBinariStl(file);
GLC_Instance instance(m_pCurrentMesh);
m_pCurrentMesh= NULL;
m_pWorld->rootProduct()->addChildPart(instance);
}
else
{
// The STL File is ASCII
lineBuff.remove(0, 5);
lineBuff= lineBuff.trimmed();
m_pCurrentMesh= new GLC_Mesh2();
m_pCurrentMesh->setName(lineBuff);
// Read the mesh facet
while (!m_StlStream.atEnd())
{
scanFacet();
currentQuantumValue = static_cast<int>((static_cast<double>(m_CurrentLineNumber) / numberOfLine) * 100);
if (currentQuantumValue > previousQuantumValue)
{
emit currentQuantum(currentQuantumValue);
}
previousQuantumValue= currentQuantumValue;
}
}
file.close();
return m_pWorld;
}
/////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// clear stlToWorld allocate memmory and reset member
void GLC_StlToWorld::clear()
{
if (NULL != m_pCurrentMesh)
{
delete m_pCurrentMesh;
m_pCurrentMesh= NULL;
}
m_pWorld= NULL;
m_FileName.clear();
m_CurrentLineNumber= 0;
m_pCurrentMesh= NULL;
m_CurVertexIndex= 0;
m_CurNormalIndex= 0;
}
// Scan a line previously extracted from STL file
void GLC_StlToWorld::scanFacet()
{
////////////////////////////////////////////// Test end of solid section////////////////////
++m_CurrentLineNumber;
QString lineBuff(m_StlStream.readLine());
lineBuff= lineBuff.trimmed().toLower();
// Test if this is the end of current solid
if (lineBuff.startsWith("endsolid") || lineBuff.startsWith("end solid"))
{
GLC_Instance instance(m_pCurrentMesh);
m_pCurrentMesh= NULL;
m_pWorld->rootProduct()->addChildPart(instance);
return;
}
// Test if this is the start of new solid
if (lineBuff.startsWith("solid"))
{
// The STL File is ASCII
lineBuff.remove(0, 5);
lineBuff= lineBuff.trimmed();
m_pCurrentMesh= new GLC_Mesh2();
m_pCurrentMesh->setName(lineBuff);
return;
}
////////////////////////////////////////////// Facet Normal////////////////////////////////
// lineBuff Must begin with "facet normal"
if (!lineBuff.startsWith("facet normal"))
{
QString message= "GLC_StlToWorld::scanFacet : \"facet normal\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
lineBuff.remove(0,12); // Remove first 12 chars
lineBuff= lineBuff.trimmed().toLower();
m_pCurrentMesh->addNormal(m_CurNormalIndex++, extract3dVect(lineBuff));
////////////////////////////////////////////// Outer Loop////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed().toLower();
// lineBuff Must begin with "outer loop"
if (!lineBuff.startsWith("outer loop"))
{
QString message= "GLC_StlToWorld::scanFacet : \"outer loop\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
////////////////////////////////////////////// Vertex ////////////////////////////////
QVector<int> vectorMaterial;
QVector<int> vectorCoordinate;
QVector<int> vectorNormal;
for (int i= 0; i < 3; ++i)
{
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed().toLower();
// lineBuff Must begin with "vertex"
if (!lineBuff.startsWith("vertex"))
{
QString message= "GLC_StlToWorld::scanFacet : \"vertex\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
lineBuff.remove(0,6); // Remove first 6 chars
lineBuff= lineBuff.trimmed();
vectorCoordinate.append(m_CurVertexIndex);
vectorMaterial.append(-1); // There is no material information
vectorNormal.append(m_CurNormalIndex - 1);
m_pCurrentMesh->addVertex(m_CurVertexIndex++, extract3dVect(lineBuff));
}
// Add the face to the current mesh
m_pCurrentMesh->addFace(vectorMaterial, vectorCoordinate, vectorNormal);
////////////////////////////////////////////// End Loop////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed().toLower();
// lineBuff Must begin with "endloop"
if (!lineBuff.startsWith("endloop"))
{
QString message= "GLC_StlToWorld::scanFacet : \"endloop\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
////////////////////////////////////////////// End Facet////////////////////////////////
++m_CurrentLineNumber;
lineBuff= m_StlStream.readLine();
lineBuff= lineBuff.trimmed().toLower();
// lineBuff Must begin with "endfacet"
if (!lineBuff.startsWith("endfacet"))
{
QString message= "GLC_StlToWorld::scanFacet : \"endfacet\" not found!";
message.append("\nAt line : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
}
// Extract a Vector from a string
GLC_Vector3d GLC_StlToWorld::extract3dVect(QString &line)
{
double x=0.0;
double y=0.0;
double z=0.0;
GLC_Vector3d vectResult;
QTextStream stringVecteur(&line);
QString xString, yString, zString;
if (((stringVecteur >> xString >> yString >> zString).status() == QTextStream::Ok))
{
bool xOk, yOk, zOk;
x= xString.toDouble(&xOk);
y= yString.toDouble(&yOk);
z= zString.toDouble(&zOk);
if (!(xOk && yOk && zOk))
{
QString message= "GLC_StlToWorld::extract3dVect : failed to convert vector component to double";
message.append("\nAt ligne : ");
message.append(QString::number(m_CurrentLineNumber));
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
else
{
vectResult.setVect(x, y, z);
}
}
return vectResult;
}
// Load Binarie STL File
void GLC_StlToWorld::LoadBinariStl(QFile &file)
{
// Create Working variables
int currentQuantumValue= 0;
int previousQuantumValue= 0;
QDataStream stlBinFile(&file);
// Pehaps just for mac ??
stlBinFile.setByteOrder(QDataStream::LittleEndian);
// Skip 80 Bytes STL header
int SkipedData= stlBinFile.skipRawData(80);
qDebug() << SkipedData;
// Check if an error occur
if (-1 == SkipedData)
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to skip Header of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
// Read the number of facet
quint32 numberOfFacet= 0;
stlBinFile >> numberOfFacet;
qDebug() << numberOfFacet;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the number of facets of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
for (quint32 i= 0; i < numberOfFacet; ++i)
{
// Extract the facet normal
float x, y, z;
stlBinFile >> x >> y >> z;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the Normal of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
m_pCurrentMesh->addNormal(m_CurNormalIndex++, GLC_Vector3d(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z)));
QVector<int> vectorMaterial;
QVector<int> vectorCoordinate;
QVector<int> vectorNormal;
// Extract the 3 Vertexs
for (int j= 0; j < 3; ++j)
{
stlBinFile >> x >> y >> z;
// Check if an error occur
if (QDataStream::Ok != stlBinFile.status())
{
QString message= "GLC_StlToWorld::LoadBinariStl : Failed to read the Vertex of binary STL";
GLC_FileFormatException fileFormatException(message, m_FileName);
clear();
throw(fileFormatException);
}
vectorCoordinate.append(m_CurVertexIndex);
vectorMaterial.append(-1); // There is no material information
vectorNormal.append(m_CurNormalIndex - 1);
m_pCurrentMesh->addVertex(m_CurVertexIndex++, GLC_Vector3d(static_cast<double>(x), static_cast<double>(y), static_cast<double>(z)));
}
currentQuantumValue = static_cast<int>((static_cast<double>(i + 1) / numberOfFacet) * 100);
if (currentQuantumValue > previousQuantumValue)
{
emit currentQuantum(currentQuantumValue);
}
previousQuantumValue= currentQuantumValue;
// Add the face to the current mesh
m_pCurrentMesh->addFace(vectorMaterial, vectorCoordinate, vectorNormal);
// Skip 2 fill-bytes not needed !!!!
stlBinFile.skipRawData(2);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 256
#define H 160
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(30));
for (int y = -H*2; y < H; y += 80) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/80 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<commit_msg>update test<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"
/*
* Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of
* precision when scaling very large images (where the dx might get very small.
*/
#define W 257
#define H 161
class GiantBitmapGM : public skiagm::GM {
SkBitmap* fBM;
SkShader::TileMode fMode;
bool fDoFilter;
bool fDoRotate;
const SkBitmap& getBitmap() {
if (NULL == fBM) {
fBM = new SkBitmap;
fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H);
fBM->allocPixels();
fBM->eraseColor(SK_ColorWHITE);
const SkColor colors[] = {
SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN
};
SkCanvas canvas(*fBM);
SkPaint paint;
paint.setAntiAlias(true);
paint.setStrokeWidth(SkIntToScalar(20));
#if 0
for (int y = -H*2; y < H; y += 50) {
SkScalar yy = SkIntToScalar(y);
paint.setColor(colors[y/50 & 0x3]);
canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W),
paint);
}
#else
for (int x = -W; x < W; x += 60) {
paint.setColor(colors[x/60 & 0x3]);
SkScalar xx = SkIntToScalar(x);
canvas.drawLine(xx, 0, xx, SkIntToScalar(H),
paint);
}
#endif
}
return *fBM;
}
public:
GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) {
fMode = mode;
fDoFilter = doFilter;
fDoRotate = doRotate;
}
virtual ~GiantBitmapGM() {
SkDELETE(fBM);
}
protected:
virtual SkString onShortName() {
SkString str("giantbitmap_");
switch (fMode) {
case SkShader::kClamp_TileMode:
str.append("clamp");
break;
case SkShader::kRepeat_TileMode:
str.append("repeat");
break;
case SkShader::kMirror_TileMode:
str.append("mirror");
break;
default:
break;
}
str.append(fDoFilter ? "_bilerp" : "_point");
str.append(fDoRotate ? "_rotate" : "_scale");
return str;
}
virtual SkISize onISize() { return SkISize::Make(640, 480); }
virtual void onDraw(SkCanvas* canvas) {
SkPaint paint;
SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode);
SkMatrix m;
if (fDoRotate) {
// m.setRotate(SkIntToScalar(30), 0, 0);
m.setSkew(SK_Scalar1, 0, 0, 0);
// m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3);
} else {
SkScalar scale = 11*SK_Scalar1/12;
m.setScale(scale, scale);
}
s->setLocalMatrix(m);
paint.setShader(s)->unref();
paint.setFilterBitmap(fDoFilter);
canvas->translate(SkIntToScalar(50), SkIntToScalar(50));
SkRect r = SkRect::MakeXYWH(-50, -50, 32, 16);
// canvas->drawRect(r, paint); return;
canvas->drawPaint(paint);
}
private:
typedef GM INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); }
static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); }
static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); }
static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); }
static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); }
static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); }
static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); }
static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); }
static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); }
static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); }
static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); }
static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); }
static skiagm::GMRegistry reg000(G000);
static skiagm::GMRegistry reg100(G100);
static skiagm::GMRegistry reg200(G200);
static skiagm::GMRegistry reg010(G010);
static skiagm::GMRegistry reg110(G110);
static skiagm::GMRegistry reg210(G210);
static skiagm::GMRegistry reg001(G001);
static skiagm::GMRegistry reg101(G101);
static skiagm::GMRegistry reg201(G201);
static skiagm::GMRegistry reg011(G011);
static skiagm::GMRegistry reg111(G111);
static skiagm::GMRegistry reg211(G211);
<|endoftext|> |
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "../include/gnelib/gneintern.h"
#include "../include/gnelib/ConnectionEventGenerator.h"
#include "../include/gnelib/ConnectionStats.h"
#include "../include/gnelib/PacketParser.h"
#include "../include/gnelib/GNE.h"
#include "../include/gnelib/Address.h"
#include "../include/gnelib/Error.h"
#include "../include/gnelib/PingPacket.h"
namespace GNE {
namespace PacketParser {
//this is declared here only so the user cannot access it, and the "real"
//function can do checking on the ID given to it.
void registerGNEPackets();
}
guint32 userVersion = 0;
ConnectionEventGenerator* eGen = NULL;
static bool initialized = false;
bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) {
if (!initialized) {
gnedbg(1, "GNE initalized");
atexit_ptr(shutdownGNE);
PacketParser::registerGNEPackets();
if (networkType != NO_NET) {
if (nlInit() == NL_FALSE)
return true;
if (nlSelectNetwork(networkType) == NL_FALSE)
return true;
nlEnable(NL_BLOCKING_IO);
nlEnable(NL_TCP_NO_DELAY);
//GNE sends its data in little endian format.
nlEnable(NL_LITTLE_ENDIAN_DATA);
nlDisable(NL_SOCKET_STATS);
eGen = new ConnectionEventGenerator();
eGen->start();
initialized = true; //We need only to set this to true if we are using HawkNL
}
return false;
}
return false;
}
void shutdownGNE() {
if (initialized) {
eGen->shutDown();
eGen->join();
delete eGen;
nlShutdown();
initialized = false;
gnedbg(1, "Closed GNE");
#ifdef _DEBUG
killDebug(); //closes debugging if it was opened
#endif
}
}
Address getLocalAddress() {
assert(initialized);
NLaddress nlAddr;
NLsocket temp = nlOpen(0, NL_RELIABLE);
nlGetLocalAddr(temp, &nlAddr);
nlClose(temp);
Address ret(nlAddr);
ret.setPort(0);
return ret;
}
ConnectionStats getGlobalStats() {
assert(initialized);
ConnectionStats ret;
ret.packetsSent = nlGetInteger(NL_PACKETS_SENT);
ret.bytesSent = nlGetInteger(NL_BYTES_SENT);
ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT);
ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT);
ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED);
ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED);
ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED);
ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED);
ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS);
return ret;
}
void enableStats() {
assert(initialized);
nlEnable(NL_SOCKET_STATS);
}
void disableStats() {
assert(initialized);
nlDisable(NL_SOCKET_STATS);
}
void clearStats() {
assert(initialized);
nlClear(NL_ALL_STATS);
}
int getOpenConnections() {
assert(initialized);
return nlGetInteger(NL_OPEN_SOCKETS);
}
GNEProtocolVersionNumber getGNEProtocolVersion() {
assert(initialized);
GNEProtocolVersionNumber ret;
ret.version = 0;
ret.subVersion = 0;
ret.build = 2;
return ret;
}
guint32 getUserVersion() {
assert(initialized);
return userVersion;
}
void setUserVersion(guint32 version) {
assert(initialized);
userVersion = version;
}
void checkVersions(const GNEProtocolVersionNumber& otherGNE,
guint32 otherUser) throw (Error) {
GNEProtocolVersionNumber us = getGNEProtocolVersion();
//Check the GNE version numbers
if (otherGNE.version != us.version ||
otherGNE.subVersion != us.subVersion ||
otherGNE.build != us.build) {
if ((otherGNE.version > us.version) ||
(otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) ||
(otherGNE.subVersion == us.subVersion && otherGNE.build > us.build))
throw Error(Error::GNETheirVersionHigh);
else
throw Error(Error::GNETheirVersionLow);
}
//Check the user version numbers
if (userVersion != otherUser) {
throw Error(Error::UserVersionMismatch);
}
}
}
<commit_msg>Updated build number.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "../include/gnelib/gneintern.h"
#include "../include/gnelib/ConnectionEventGenerator.h"
#include "../include/gnelib/ConnectionStats.h"
#include "../include/gnelib/PacketParser.h"
#include "../include/gnelib/GNE.h"
#include "../include/gnelib/Address.h"
#include "../include/gnelib/Error.h"
#include "../include/gnelib/PingPacket.h"
namespace GNE {
namespace PacketParser {
//this is declared here only so the user cannot access it, and the "real"
//function can do checking on the ID given to it.
void registerGNEPackets();
}
guint32 userVersion = 0;
ConnectionEventGenerator* eGen = NULL;
static bool initialized = false;
bool initGNE(NLenum networkType, int (*atexit_ptr)(void (*func)(void))) {
if (!initialized) {
gnedbg(1, "GNE initalized");
atexit_ptr(shutdownGNE);
PacketParser::registerGNEPackets();
if (networkType != NO_NET) {
if (nlInit() == NL_FALSE)
return true;
if (nlSelectNetwork(networkType) == NL_FALSE)
return true;
nlEnable(NL_BLOCKING_IO);
nlEnable(NL_TCP_NO_DELAY);
//GNE sends its data in little endian format.
nlEnable(NL_LITTLE_ENDIAN_DATA);
nlDisable(NL_SOCKET_STATS);
eGen = new ConnectionEventGenerator();
eGen->start();
initialized = true; //We need only to set this to true if we are using HawkNL
}
return false;
}
return false;
}
void shutdownGNE() {
if (initialized) {
eGen->shutDown();
eGen->join();
delete eGen;
nlShutdown();
initialized = false;
gnedbg(1, "Closed GNE");
#ifdef _DEBUG
killDebug(); //closes debugging if it was opened
#endif
}
}
Address getLocalAddress() {
assert(initialized);
NLaddress nlAddr;
NLsocket temp = nlOpen(0, NL_RELIABLE);
nlGetLocalAddr(temp, &nlAddr);
nlClose(temp);
Address ret(nlAddr);
ret.setPort(0);
return ret;
}
ConnectionStats getGlobalStats() {
assert(initialized);
ConnectionStats ret;
ret.packetsSent = nlGetInteger(NL_PACKETS_SENT);
ret.bytesSent = nlGetInteger(NL_BYTES_SENT);
ret.avgBytesSent = nlGetInteger(NL_AVE_BYTES_SENT);
ret.maxAvgBytesSent = nlGetInteger(NL_HIGH_BYTES_SENT);
ret.packetsRecv = nlGetInteger(NL_PACKETS_RECEIVED);
ret.bytesRecv = nlGetInteger(NL_BYTES_RECEIVED);
ret.avgBytesRecv = nlGetInteger(NL_AVE_BYTES_RECEIVED);
ret.maxAvgBytesRecv = nlGetInteger(NL_HIGH_BYTES_RECEIVED);
ret.openSockets = nlGetInteger(NL_OPEN_SOCKETS);
return ret;
}
void enableStats() {
assert(initialized);
nlEnable(NL_SOCKET_STATS);
}
void disableStats() {
assert(initialized);
nlDisable(NL_SOCKET_STATS);
}
void clearStats() {
assert(initialized);
nlClear(NL_ALL_STATS);
}
int getOpenConnections() {
assert(initialized);
return nlGetInteger(NL_OPEN_SOCKETS);
}
GNEProtocolVersionNumber getGNEProtocolVersion() {
assert(initialized);
GNEProtocolVersionNumber ret;
ret.version = 0;
ret.subVersion = 0;
ret.build = 3;
return ret;
}
guint32 getUserVersion() {
assert(initialized);
return userVersion;
}
void setUserVersion(guint32 version) {
assert(initialized);
userVersion = version;
}
void checkVersions(const GNEProtocolVersionNumber& otherGNE,
guint32 otherUser) throw (Error) {
GNEProtocolVersionNumber us = getGNEProtocolVersion();
//Check the GNE version numbers
if (otherGNE.version != us.version ||
otherGNE.subVersion != us.subVersion ||
otherGNE.build != us.build) {
if ((otherGNE.version > us.version) ||
(otherGNE.version == us.version && otherGNE.subVersion > us.subVersion) ||
(otherGNE.subVersion == us.subVersion && otherGNE.build > us.build))
throw Error(Error::GNETheirVersionHigh);
else
throw Error(Error::GNETheirVersionLow);
}
//Check the user version numbers
if (userVersion != otherUser) {
throw Error(Error::UserVersionMismatch);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 Plenluno All rights reserved.
#include <libnode/os.h>
#include <libnode/net.h>
#include "./gtest_common.h"
namespace libj {
namespace node {
TEST(GTestOs, TestOsInfo) {
String::CPtr hostname = os::hostname();
String::CPtr type = os::type();
String::CPtr release = os::release();
ASSERT_TRUE(!!hostname);
ASSERT_TRUE(!!type);
ASSERT_TRUE(!!release);
console::log(hostname);
console::log(type);
console::log(release);
}
TEST(GTestOs, TestNetworkInterface) {
LIBJ_STATIC_SYMBOL_DEF(symIPv4, "IPv4");
LIBJ_STATIC_SYMBOL_DEF(symIPv6, "IPv6");
LIBJ_STATIC_SYMBOL_DEF(symFamily, "family");
LIBJ_STATIC_SYMBOL_DEF(symAddress, "address");
LIBJ_STATIC_SYMBOL_DEF(symInternal, "internal");
JsObject::Ptr netif = os::networkInterface();
TypedSet<Map::Entry::CPtr>::CPtr es = netif->entrySet();
TypedIterator<Map::Entry::CPtr>::Ptr itr = es->iteratorTyped();
while (itr->hasNext()) {
Map::Entry::CPtr e = itr->nextTyped();
JsArray::Ptr a = toPtr<JsArray>(e->getValue());
ASSERT_TRUE(!!a);
for (Size i = 0; i < a->length(); i++) {
JsObject::Ptr o = a->getPtr<JsObject>(i);
String::CPtr family = o->getCPtr<String>(symFamily);
ASSERT_TRUE(family->equals(symIPv4) || family->equals(symIPv6));
if (family->equals(symIPv4)) {
ASSERT_TRUE(net::isIPv4(o->getCPtr<String>(symAddress)));
} else {
ASSERT_TRUE(net::isIPv6(o->getCPtr<String>(symAddress)));
}
ASSERT_TRUE(o->get(symInternal).is<Boolean>());
}
}
}
} // namespace node
} // namespace libj
<commit_msg>print the result of os::networkInterface<commit_after>// Copyright (c) 2013 Plenluno All rights reserved.
#include <libnode/os.h>
#include <libnode/net.h>
#include "./gtest_common.h"
namespace libj {
namespace node {
TEST(GTestOs, TestOsInfo) {
String::CPtr hostname = os::hostname();
String::CPtr type = os::type();
String::CPtr release = os::release();
ASSERT_TRUE(!!hostname);
ASSERT_TRUE(!!type);
ASSERT_TRUE(!!release);
console::log(hostname);
console::log(type);
console::log(release);
}
TEST(GTestOs, TestNetworkInterface) {
LIBJ_STATIC_SYMBOL_DEF(symIPv4, "IPv4");
LIBJ_STATIC_SYMBOL_DEF(symIPv6, "IPv6");
LIBJ_STATIC_SYMBOL_DEF(symFamily, "family");
LIBJ_STATIC_SYMBOL_DEF(symAddress, "address");
LIBJ_STATIC_SYMBOL_DEF(symInternal, "internal");
JsObject::Ptr netif = os::networkInterface();
console::log(json::stringify(netif));
TypedSet<Map::Entry::CPtr>::CPtr es = netif->entrySet();
TypedIterator<Map::Entry::CPtr>::Ptr itr = es->iteratorTyped();
while (itr->hasNext()) {
Map::Entry::CPtr e = itr->nextTyped();
JsArray::Ptr a = toPtr<JsArray>(e->getValue());
ASSERT_TRUE(!!a);
for (Size i = 0; i < a->length(); i++) {
JsObject::Ptr o = a->getPtr<JsObject>(i);
String::CPtr family = o->getCPtr<String>(symFamily);
ASSERT_TRUE(family->equals(symIPv4) || family->equals(symIPv6));
if (family->equals(symIPv4)) {
ASSERT_TRUE(net::isIPv4(o->getCPtr<String>(symAddress)));
} else {
ASSERT_TRUE(net::isIPv6(o->getCPtr<String>(symAddress)));
}
ASSERT_TRUE(o->get(symInternal).is<Boolean>());
}
}
}
} // namespace node
} // namespace libj
<|endoftext|> |
<commit_before>#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#define close closesocket
#define sleep Sleep
#else
#include <netdb.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include "client.h"
#define PROTOCOL_VERSION 7
#define MAX_RECV_SIZE 4096*1024
#define PACKETS (MAX_PENDING_CHUNKS * 2)
#define HEADER_SIZE 4
namespace konstructs {
using nonstd::nullopt;
Client::Client() : connected(false) {
worker_thread = new std::thread(&Client::recv_worker, this);
}
void Client::open_connection(const string &nick, const string &hash,
const string &hostname, const int port) {
struct hostent *host;
struct sockaddr_in address;
if ((host = gethostbyname(hostname.c_str())) == 0) {
#ifdef _WIN32
std::cerr << "WSAGetLastError: " << WSAGetLastError() << std::endl;
#endif
SHOWERROR("gethostbyname");
exit(1);
}
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = ((struct in_addr *)(host->h_addr_list[0]))->s_addr;
address.sin_port = htons(port);
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
SHOWERROR("socket");
throw std::runtime_error("Failed to create socket");
}
if (connect(sock, (struct sockaddr *)&address, sizeof(address)) == -1) {
SHOWERROR("connect");
throw std::runtime_error("Failed to connect");
}
version(PROTOCOL_VERSION, nick, hash);
}
size_t Client::recv_all(char* out_buf, const size_t size) {
int t = 0;
int length = 0;
while(t < size) {
if ((length = recv(sock, out_buf + t, size - t, 0)) <= 0) {
#ifdef _WIN32
if(WSAGetLastError() == WSAEINTR) {
continue;
}
#else
if(errno == EINTR) {
continue;
}
#endif
SHOWERROR("recv");
throw std::runtime_error("Failed to receive");
}
t += length;
}
return t;
}
void Client::process_chunk(Packet *packet) {
int p, q, k;
char *pos = packet->buffer();
p = ntohl(*((int*)pos));
pos += sizeof(int);
q = ntohl(*((int*)pos));
pos += sizeof(int);
k = ntohl(*((int*)pos));
pos += sizeof(int);
Vector3i position(p, q, k);
const int blocks_size = packet->size - 3 * sizeof(int);
auto chunk = make_shared<ChunkData>(position, pos, blocks_size);
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
chunks.push_back(chunk);
}
void Client::recv_worker() {
// Wait for an open connection
std::unique_lock<std::mutex> ulock_connected(mutex_connected);
cv_connected.wait(ulock_connected, [&]{ return connected; });
ulock_connected.unlock();
int size;
while (1) {
// Read header from network
recv_all((char*)&size, HEADER_SIZE);
size = ntohl(size);
if (size > MAX_RECV_SIZE) {
std::cerr << "package too large, received " << size << " bytes" << std::endl;
throw std::runtime_error("Packet too large");
}
char type;
// read 'size' bytes from the network
recv_all(&type, sizeof(char));
// Remove one byte type header'
size = size - 1;
auto packet = make_shared<Packet>(type,size);
// read 'size' bytes from the network
int r = recv_all(packet->buffer(), packet->size);
// move data over to packet_buffer
if(packet->type == 'C')
process_chunk(packet.get());
else {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
packets.push(packet);
}
}
}
vector<shared_ptr<Packet>> Client::receive(const int max) {
vector<shared_ptr<Packet>> head;
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
for(int i=0; i < max; i++) {
if(packets.empty()) break;
head.push_back(packets.front());
packets.pop();
}
return head;
}
optional<shared_ptr<ChunkData>> Client::receive_prio_chunk(const Vector3i pos) {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
for(auto it = chunks.begin(); it != chunks.end(); ++it) {
auto chunk = *it;
Vector3i chunk_position = chunk->position;
int dp = chunk_position[0] - pos[0];
int dq = chunk_position[1] - pos[1];
int dk = chunk_position[2] - pos[2];
if(dp >= -1 && dp <= 1 && dq >= -1 && dq <= 1 && dk >= -1 && dk <= 1) {
chunks.erase(it);
return optional<shared_ptr<ChunkData>>(chunk);
}
}
return nullopt;
}
vector<shared_ptr<ChunkData>> Client::receive_chunks(const int max) {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
auto maxIter = chunks.begin() + max;
auto endIter = chunks.end();
auto last = maxIter < endIter ? maxIter : endIter;
vector<shared_ptr<ChunkData>> head(chunks.begin(), last);
chunks.erase(chunks.begin(), last);
return head;
}
int Client::send_all(const char *data, int length) {
int count = 0;
while (count < length) {
int n = send(sock, data + count, length, 0);
if (n == -1) {
return -1;
}
count += n;
length -= n;
bytes_sent += n;
}
return 0;
}
void Client::send_string(const string &str) {
int header_size = htonl(str.size());
if (send_all((char*)&header_size, sizeof(header_size)) == -1) {
SHOWERROR("client_sendall");
throw std::runtime_error("Failed to send");
}
if (send_all(str.c_str(), str.size()) == -1) {
SHOWERROR("client_sendall");
throw std::runtime_error("Failed to send");
}
}
void Client::version(const int version, const string &nick, const string &hash) {
std::stringstream ss;
ss << "V," << version << "," << nick << "," << hash;
send_string(ss.str());
}
void Client::position(const Vector3f position,
const float rx, const float ry) {
std::stringstream ss;
ss << "P," << position[0] << "," << position[1] << "," << position[2] << "," << rx << "," << ry;
send_string(ss.str());
}
void Client::inventory_select(const int pos) {
std::stringstream ss;
ss << "A," << pos;
send_string(ss.str());
}
void Client::click_at(const int hit, const Vector3i pos,
const int button) {
std::stringstream ss;
ss << "M," << hit << "," << pos[0] << "," << pos[1] << "," << pos[2] << "," << button;
send_string(ss.str());
}
void Client::chunk(const Vector3i position) {
std::stringstream ss;
ss << "C," << position[0] << "," << position[1] << "," << position[2];
send_string(ss.str());
}
void Client::konstruct() {
send_string("K");
}
void Client::click_inventory(const int item) {
std::stringstream ss;
ss << "R," << item;
send_string(ss.str());
}
void Client::close_inventory() {
send_string("I");
}
void Client::talk(const string &text) {
std::stringstream ss;
ss << "T," << text;
send_string(ss.str());
}
bool Client::is_connected() {
std::unique_lock<std::mutex> ulck_connected(mutex_connected);
return connected;
}
void Client::set_connected(bool state) {
std::unique_lock<std::mutex> ulck_connected(mutex_connected);
connected = state;
cv_connected.notify_all();
}
};
<commit_msg>Use normal arithmetic rather than iterators<commit_after>#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#define close closesocket
#define sleep Sleep
#else
#include <netdb.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include <algorithm>
#include "client.h"
#define PROTOCOL_VERSION 7
#define MAX_RECV_SIZE 4096*1024
#define PACKETS (MAX_PENDING_CHUNKS * 2)
#define HEADER_SIZE 4
namespace konstructs {
using nonstd::nullopt;
Client::Client() : connected(false) {
worker_thread = new std::thread(&Client::recv_worker, this);
}
void Client::open_connection(const string &nick, const string &hash,
const string &hostname, const int port) {
struct hostent *host;
struct sockaddr_in address;
if ((host = gethostbyname(hostname.c_str())) == 0) {
#ifdef _WIN32
std::cerr << "WSAGetLastError: " << WSAGetLastError() << std::endl;
#endif
SHOWERROR("gethostbyname");
exit(1);
}
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_addr.s_addr = ((struct in_addr *)(host->h_addr_list[0]))->s_addr;
address.sin_port = htons(port);
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
SHOWERROR("socket");
throw std::runtime_error("Failed to create socket");
}
if (connect(sock, (struct sockaddr *)&address, sizeof(address)) == -1) {
SHOWERROR("connect");
throw std::runtime_error("Failed to connect");
}
version(PROTOCOL_VERSION, nick, hash);
}
size_t Client::recv_all(char* out_buf, const size_t size) {
int t = 0;
int length = 0;
while(t < size) {
if ((length = recv(sock, out_buf + t, size - t, 0)) <= 0) {
#ifdef _WIN32
if(WSAGetLastError() == WSAEINTR) {
continue;
}
#else
if(errno == EINTR) {
continue;
}
#endif
SHOWERROR("recv");
throw std::runtime_error("Failed to receive");
}
t += length;
}
return t;
}
void Client::process_chunk(Packet *packet) {
int p, q, k;
char *pos = packet->buffer();
p = ntohl(*((int*)pos));
pos += sizeof(int);
q = ntohl(*((int*)pos));
pos += sizeof(int);
k = ntohl(*((int*)pos));
pos += sizeof(int);
Vector3i position(p, q, k);
const int blocks_size = packet->size - 3 * sizeof(int);
auto chunk = make_shared<ChunkData>(position, pos, blocks_size);
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
chunks.push_back(chunk);
}
void Client::recv_worker() {
// Wait for an open connection
std::unique_lock<std::mutex> ulock_connected(mutex_connected);
cv_connected.wait(ulock_connected, [&]{ return connected; });
ulock_connected.unlock();
int size;
while (1) {
// Read header from network
recv_all((char*)&size, HEADER_SIZE);
size = ntohl(size);
if (size > MAX_RECV_SIZE) {
std::cerr << "package too large, received " << size << " bytes" << std::endl;
throw std::runtime_error("Packet too large");
}
char type;
// read 'size' bytes from the network
recv_all(&type, sizeof(char));
// Remove one byte type header'
size = size - 1;
auto packet = make_shared<Packet>(type,size);
// read 'size' bytes from the network
int r = recv_all(packet->buffer(), packet->size);
// move data over to packet_buffer
if(packet->type == 'C')
process_chunk(packet.get());
else {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
packets.push(packet);
}
}
}
vector<shared_ptr<Packet>> Client::receive(const int max) {
vector<shared_ptr<Packet>> head;
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
for(int i=0; i < max; i++) {
if(packets.empty()) break;
head.push_back(packets.front());
packets.pop();
}
return head;
}
optional<shared_ptr<ChunkData>> Client::receive_prio_chunk(const Vector3i pos) {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
for(auto it = chunks.begin(); it != chunks.end(); ++it) {
auto chunk = *it;
Vector3i chunk_position = chunk->position;
int dp = chunk_position[0] - pos[0];
int dq = chunk_position[1] - pos[1];
int dk = chunk_position[2] - pos[2];
if(dp >= -1 && dp <= 1 && dq >= -1 && dq <= 1 && dk >= -1 && dk <= 1) {
chunks.erase(it);
return optional<shared_ptr<ChunkData>>(chunk);
}
}
return nullopt;
}
vector<shared_ptr<ChunkData>> Client::receive_chunks(const int max) {
std::unique_lock<std::mutex> ulock_packets(packets_mutex);
int maxOrSize = std::min(max, (int)chunks.size());
auto last = chunks.begin() + maxOrSize;
vector<shared_ptr<ChunkData>> head(chunks.begin(), last);
chunks.erase(chunks.begin(), last);
return head;
}
int Client::send_all(const char *data, int length) {
int count = 0;
while (count < length) {
int n = send(sock, data + count, length, 0);
if (n == -1) {
return -1;
}
count += n;
length -= n;
bytes_sent += n;
}
return 0;
}
void Client::send_string(const string &str) {
int header_size = htonl(str.size());
if (send_all((char*)&header_size, sizeof(header_size)) == -1) {
SHOWERROR("client_sendall");
throw std::runtime_error("Failed to send");
}
if (send_all(str.c_str(), str.size()) == -1) {
SHOWERROR("client_sendall");
throw std::runtime_error("Failed to send");
}
}
void Client::version(const int version, const string &nick, const string &hash) {
std::stringstream ss;
ss << "V," << version << "," << nick << "," << hash;
send_string(ss.str());
}
void Client::position(const Vector3f position,
const float rx, const float ry) {
std::stringstream ss;
ss << "P," << position[0] << "," << position[1] << "," << position[2] << "," << rx << "," << ry;
send_string(ss.str());
}
void Client::inventory_select(const int pos) {
std::stringstream ss;
ss << "A," << pos;
send_string(ss.str());
}
void Client::click_at(const int hit, const Vector3i pos,
const int button) {
std::stringstream ss;
ss << "M," << hit << "," << pos[0] << "," << pos[1] << "," << pos[2] << "," << button;
send_string(ss.str());
}
void Client::chunk(const Vector3i position) {
std::stringstream ss;
ss << "C," << position[0] << "," << position[1] << "," << position[2];
send_string(ss.str());
}
void Client::konstruct() {
send_string("K");
}
void Client::click_inventory(const int item) {
std::stringstream ss;
ss << "R," << item;
send_string(ss.str());
}
void Client::close_inventory() {
send_string("I");
}
void Client::talk(const string &text) {
std::stringstream ss;
ss << "T," << text;
send_string(ss.str());
}
bool Client::is_connected() {
std::unique_lock<std::mutex> ulck_connected(mutex_connected);
return connected;
}
void Client::set_connected(bool state) {
std::unique_lock<std::mutex> ulck_connected(mutex_connected);
connected = state;
cv_connected.notify_all();
}
};
<|endoftext|> |
<commit_before>#include <Eigen/Sparse>
#include <iostream>
using namespace std;
int main() {
Eigen::SparseMatrix<double> m(1000000,1000);
cerr << "ok!\n";
}
<commit_msg>remove accidentally committed file<commit_after><|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include "uvxbridge.h"
#include "uvxlan.h"
static uint64_t
mac_parse(const char *input)
{
char *idx, *mac = strdup(input);
const char *del = ":";
uint64_t mac_num = 0;
uint8_t *mac_nump = (uint8_t *)&mac_num;
int i;
for (i = 0; ((idx = strsep(&mac, del)) != NULL) && i < ETHER_ADDR_LEN; i++)
mac_nump[i] = (uint8_t)strtol(idx, NULL, 16);
free(mac);
if (i < ETHER_ADDR_LEN)
return 0;
return mac_num;
}
/*
* beastie0:
*
* config: vale0:1
* ingress: vale0:2
* egress: vale2:0
* cmac: CA:FE:00:00:BE:EF
* pmac: CA:FE:00:00:BA:BE
*
* ifmac: BA:DB:AB:EC:AF:E1
* interface: 192.168.2.1 - gw: 192.168.2.254
* vxlan: 00:a0:98:69:52:53 -> 150
* ftable: 00:a0:98:11:1c:d8 -> 192.168.2.2
* physarp: 192.168.2.2 -> BA:DB:AB:EC:AF:E2
*
* ./uvxbridge -c vale0:1 -i vale0:2 -e vale2:0 -m CA:FE:00:00:BE:EF -p CA:FE:00:00:BA:BE -t 1
*
* beastie1:
*
* config: vale1:1
* ingress: vale1:2
* egress: vale2:1
* cmac: CA:FE:00:01:BE:EF
* pmac: CA:FE:00:01:BA:BE
*
* ifmac: BA:DB:AB:EC:AF:E2
* interface: 192.168.2.2 - gw: 192.168.2.254
* vxlan: 00:a0:98:11:1c:d8 -> 150
* ftable: 00:a0:98:69:52:53 -> 192.168.2.1
* physarp: 192.168.2.1 -> BA:DB:AB:EC:AF:E1
*
* ./uvxbridge -c vale1:1 -i vale1:2 -e vale2:1 -m CA:FE:00:01:BE:EF -p CA:FE:00:01:BA:BE -t 2
*
*/
void
configure_beastie0(vxstate_t *state)
{
rte_t *rte = &state->vs_dflt_rte;
intf_info_map_t *intftbl = &state->vs_intf_table;
ftablemap_t *ftablemap = &state->vs_ftables;
ftable_t ftable;
arp_t *l2tbl = &state->vs_l2_phys.l2t_v4;
uint64_t ptnet_mac0, ptnet_mac1, physarp;
vfe_t vfe;
intf_info_t *intfent;
uint32_t vxlanid = ntohl(150) >> 8;
uint32_t peerip;
state->vs_intf_mac = mac_parse("BA:DB:AB:EC:AF:E1");
rte->ri_mask.in4.s_addr = 0xffffff00;
rte->ri_laddr.in4.s_addr = inet_network("192.168.2.1");
rte->ri_raddr.in4.s_addr = inet_network("192.168.2.254");
rte->ri_prefixlen = 24;
rte->ri_flags = RI_VALID;
ptnet_mac0 = mac_parse("00:a0:98:69:52:53");
ptnet_mac1 = mac_parse("00:a0:98:11:1c:d8");
intfent = new intf_info();
intfent->ii_ent.fields.vxlanid = vxlanid;
intftbl->insert(pair<uint64_t, intf_info_t*>(ptnet_mac0, intfent));
bzero(&vfe, sizeof(vfe_t));
vfe.vfe_raddr.in4.s_addr = inet_network("192.168.2.2");
/* map beastie1 mac to 'host' for beastie1 */
ftable.insert(pair<uint64_t, vfe_t>(ptnet_mac1, vfe));
ftablemap->insert(pair<uint32_t, ftable_t>(vxlanid, ftable));
physarp = mac_parse("BA:DB:AB:EC:AF:E2");
peerip = inet_network("192.168.2.2");
l2tbl->insert(pair<uint32_t, uint64_t>(peerip, physarp));
}
void
configure_beastie1(vxstate_t *state)
{
rte_t *rte = &state->vs_dflt_rte;
intf_info_map_t *intftbl = &state->vs_intf_table;
ftablemap_t *ftablemap = &state->vs_ftables;
ftable_t ftable;
arp_t *l2tbl = &state->vs_l2_phys.l2t_v4;
uint64_t ptnet_mac0, ptnet_mac1, physarp;
vfe_t vfe;
intf_info_t *intfent;
uint32_t vxlanid = ntohl(150) >> 8;
uint32_t peerip;
state->vs_intf_mac = mac_parse("BA:DB:AB:EC:AF:E2");
rte->ri_mask.in4.s_addr = 0xffffff00;
rte->ri_laddr.in4.s_addr = inet_network("192.168.2.2");
rte->ri_raddr.in4.s_addr = inet_network("192.168.2.254");
rte->ri_prefixlen = 24;
rte->ri_flags = RI_VALID;
ptnet_mac0 = mac_parse("00:a0:98:69:52:53");
ptnet_mac1 = mac_parse("00:a0:98:11:1c:d8");
intfent = new intf_info();
intfent->ii_ent.fields.vxlanid = vxlanid;
intftbl->insert(pair<uint64_t, intf_info_t*>(ptnet_mac1, intfent));
bzero(&vfe, sizeof(vfe_t));
vfe.vfe_raddr.in4.s_addr = inet_network("192.168.2.1");
ftable.insert(pair<uint64_t, vfe_t>(ptnet_mac0, vfe));
ftablemap->insert(pair<uint32_t, ftable_t>(vxlanid, ftable));
physarp = mac_parse("BA:DB:AB:EC:AF:E1");
peerip = inet_network("192.168.2.1");
l2tbl->insert(pair<uint32_t, uint64_t>(peerip, physarp));
}
<commit_msg>try to make less confusing<commit_after>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include "uvxbridge.h"
#include "uvxlan.h"
static uint64_t
mac_parse(const char *input)
{
char *idx, *mac = strdup(input);
const char *del = ":";
uint64_t mac_num = 0;
uint8_t *mac_nump = (uint8_t *)&mac_num;
int i;
for (i = 0; ((idx = strsep(&mac, del)) != NULL) && i < ETHER_ADDR_LEN; i++)
mac_nump[i] = (uint8_t)strtol(idx, NULL, 16);
free(mac);
if (i < ETHER_ADDR_LEN)
return 0;
return mac_num;
}
/*
* beastie0 (vale0:0):
*
* ingress: vale0:1
* egress: vale2:0
*
* config: vale0:2 (provisioning agent can use vale0:3)
* cmac: CA:FE:00:00:BE:EF
* pmac: CA:FE:00:00:BA:BE
*
* ifmac: BA:DB:AB:EC:AF:E1
* interface: 192.168.2.1 - gw: 192.168.2.254
* vxlan: 00:a0:98:69:52:53 -> 150
* ftable: 00:a0:98:11:1c:d8 -> 192.168.2.2
* physarp: 192.168.2.2 -> BA:DB:AB:EC:AF:E2
*
* ./uvxbridge -c vale0:1 -i vale0:2 -e vale2:0 -m CA:FE:00:00:BE:EF -p CA:FE:00:00:BA:BE -t 1
*
* beastie1 (vale1:0):
*
* ingress: vale1:1
* egress: vale2:1
*
* config: vale1:2 (provisioning agent can use vale1:3)
* cmac: CA:FE:00:01:BE:EF
* pmac: CA:FE:00:01:BA:BE
*
* ifmac: BA:DB:AB:EC:AF:E2
* interface: 192.168.2.2 - gw: 192.168.2.254
* vxlan: 00:a0:98:11:1c:d8 -> 150
* ftable: 00:a0:98:69:52:53 -> 192.168.2.1
* physarp: 192.168.2.1 -> BA:DB:AB:EC:AF:E1
*
* ./uvxbridge -c vale1:1 -i vale1:2 -e vale2:1 -m CA:FE:00:01:BE:EF -p CA:FE:00:01:BA:BE -t 2
*
*/
void
configure_beastie0(vxstate_t *state)
{
rte_t *rte = &state->vs_dflt_rte;
intf_info_map_t *intftbl = &state->vs_intf_table;
ftablemap_t *ftablemap = &state->vs_ftables;
ftable_t ftable;
arp_t *l2tbl = &state->vs_l2_phys.l2t_v4;
uint64_t ptnet_mac0, ptnet_mac1, physarp;
vfe_t vfe;
intf_info_t *intfent;
uint32_t vxlanid = ntohl(150) >> 8;
uint32_t peerip;
state->vs_intf_mac = mac_parse("BA:DB:AB:EC:AF:E1");
rte->ri_mask.in4.s_addr = 0xffffff00;
rte->ri_laddr.in4.s_addr = inet_network("192.168.2.1");
rte->ri_raddr.in4.s_addr = inet_network("192.168.2.254");
rte->ri_prefixlen = 24;
rte->ri_flags = RI_VALID;
ptnet_mac0 = mac_parse("00:a0:98:69:52:53");
ptnet_mac1 = mac_parse("00:a0:98:11:1c:d8");
intfent = new intf_info();
intfent->ii_ent.fields.vxlanid = vxlanid;
intftbl->insert(pair<uint64_t, intf_info_t*>(ptnet_mac0, intfent));
bzero(&vfe, sizeof(vfe_t));
vfe.vfe_raddr.in4.s_addr = inet_network("192.168.2.2");
/* map beastie1 mac to 'host' for beastie1 */
ftable.insert(pair<uint64_t, vfe_t>(ptnet_mac1, vfe));
ftablemap->insert(pair<uint32_t, ftable_t>(vxlanid, ftable));
physarp = mac_parse("BA:DB:AB:EC:AF:E2");
peerip = inet_network("192.168.2.2");
l2tbl->insert(pair<uint32_t, uint64_t>(peerip, physarp));
}
void
configure_beastie1(vxstate_t *state)
{
rte_t *rte = &state->vs_dflt_rte;
intf_info_map_t *intftbl = &state->vs_intf_table;
ftablemap_t *ftablemap = &state->vs_ftables;
ftable_t ftable;
arp_t *l2tbl = &state->vs_l2_phys.l2t_v4;
uint64_t ptnet_mac0, ptnet_mac1, physarp;
vfe_t vfe;
intf_info_t *intfent;
uint32_t vxlanid = ntohl(150) >> 8;
uint32_t peerip;
state->vs_intf_mac = mac_parse("BA:DB:AB:EC:AF:E2");
rte->ri_mask.in4.s_addr = 0xffffff00;
rte->ri_laddr.in4.s_addr = inet_network("192.168.2.2");
rte->ri_raddr.in4.s_addr = inet_network("192.168.2.254");
rte->ri_prefixlen = 24;
rte->ri_flags = RI_VALID;
ptnet_mac0 = mac_parse("00:a0:98:69:52:53");
ptnet_mac1 = mac_parse("00:a0:98:11:1c:d8");
intfent = new intf_info();
intfent->ii_ent.fields.vxlanid = vxlanid;
intftbl->insert(pair<uint64_t, intf_info_t*>(ptnet_mac1, intfent));
bzero(&vfe, sizeof(vfe_t));
vfe.vfe_raddr.in4.s_addr = inet_network("192.168.2.1");
ftable.insert(pair<uint64_t, vfe_t>(ptnet_mac0, vfe));
ftablemap->insert(pair<uint32_t, ftable_t>(vxlanid, ftable));
physarp = mac_parse("BA:DB:AB:EC:AF:E1");
peerip = inet_network("192.168.2.1");
l2tbl->insert(pair<uint32_t, uint64_t>(peerip, physarp));
}
<|endoftext|> |
<commit_before>#pragma once
// ----------------------------------------------------------------------
namespace tree
{
// ----------------------------------------------------------------------
template <typename N, typename F1> inline void iterate_leaf(N&& aNode, F1&& f_name)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
iterate_leaf(node, std::forward<F1>(f_name));
}
}
}
// ----------------------------------------------------------------------
// stops iterating if f_name returns true
template <typename N, typename F1> inline bool iterate_leaf_stop(N&& aNode, F1&& f_name)
{
bool stop = false;
if (aNode.is_leaf()) {
stop = f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
if ((stop = iterate_leaf_stop(node, f_name)))
break;
}
}
return stop;
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F3> inline void iterate_leaf_post(N&& aNode, F1&& f_name, F3&& f_subtree_post)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
iterate_leaf_post(node, std::forward<F1>(f_name), std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F2> inline void iterate_leaf_pre(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
f_subtree_pre(std::forward<N>(aNode));
for (auto& node: aNode.subtree) {
iterate_leaf_pre(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
}
}
}
// ----------------------------------------------------------------------
// Stop descending the tree if f_subtree_pre returned false
template <typename N, typename F1, typename F2> inline void iterate_leaf_pre_stop(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
if (f_subtree_pre(std::forward<N>(aNode))) {
for (auto& node: aNode.subtree) {
iterate_leaf_pre_stop(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
}
}
}
}
// ----------------------------------------------------------------------
template <typename N, typename F3> inline void iterate_pre(N&& aNode, F3&& f_subtree_pre)
{
if (!aNode.is_leaf()) {
f_subtree_pre(std::forward<N>(aNode));
for (auto& node: aNode.subtree) {
iterate_pre(node, std::forward<F3>(f_subtree_pre));
}
}
}
// ----------------------------------------------------------------------
template <typename N, typename F3> inline void iterate_post(N&& aNode, F3&& f_subtree_post)
{
if (!aNode.is_leaf()) {
for (auto& node: aNode.subtree) {
iterate_post(node, std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F2, typename F3> inline void iterate_leaf_pre_post(N&& aNode, F1&& f_name, F2&& f_subtree_pre, F3&& f_subtree_post)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
f_subtree_pre(std::forward<N>(aNode));
for (auto node = aNode.subtree.begin(); node != aNode.subtree.end(); ++node) {
iterate_leaf_pre_post(*node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre), std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
} // namespace tree
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>tree::iterate_pre_path()<commit_after>#pragma once
// ----------------------------------------------------------------------
namespace tree
{
// ----------------------------------------------------------------------
template <typename N, typename F1> inline void iterate_leaf(N&& aNode, F1&& f_name)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
iterate_leaf(node, std::forward<F1>(f_name));
}
}
}
// ----------------------------------------------------------------------
// stops iterating if f_name returns true
template <typename N, typename F1> inline bool iterate_leaf_stop(N&& aNode, F1&& f_name)
{
bool stop = false;
if (aNode.is_leaf()) {
stop = f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
if ((stop = iterate_leaf_stop(node, f_name)))
break;
}
}
return stop;
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F3> inline void iterate_leaf_post(N&& aNode, F1&& f_name, F3&& f_subtree_post)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
for (auto& node: aNode.subtree) {
iterate_leaf_post(node, std::forward<F1>(f_name), std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F2> inline void iterate_leaf_pre(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
f_subtree_pre(std::forward<N>(aNode));
for (auto& node: aNode.subtree) {
iterate_leaf_pre(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
}
}
}
// ----------------------------------------------------------------------
// Stop descending the tree if f_subtree_pre returned false
template <typename N, typename F1, typename F2> inline void iterate_leaf_pre_stop(N&& aNode, F1&& f_name, F2&& f_subtree_pre)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
if (f_subtree_pre(std::forward<N>(aNode))) {
for (auto& node: aNode.subtree) {
iterate_leaf_pre_stop(node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre));
}
}
}
}
// ----------------------------------------------------------------------
template <typename N, typename F3> inline void iterate_pre(N&& aNode, F3&& f_subtree_pre)
{
if (!aNode.is_leaf()) {
f_subtree_pre(std::forward<N>(aNode));
for (auto& node: aNode.subtree) {
iterate_pre(node, std::forward<F3>(f_subtree_pre));
}
}
}
// ----------------------------------------------------------------------
template <typename N, typename F3> inline void iterate_pre_path(N&& aNode, F3&& f_subtree_pre, std::string path = std::string{})
{
constexpr const char path_parts[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (!aNode.is_leaf()) {
f_subtree_pre(std::forward<N>(aNode), path);
auto subpath_p = std::begin(path_parts);
std::string subpath_infix;
for (auto& node: aNode.subtree) {
iterate_pre_path(node, std::forward<F3>(f_subtree_pre), path + subpath_infix + *subpath_p);
++subpath_p;
if (!*subpath_p) {
subpath_p = std::begin(path_parts);
subpath_infix += '-';
}
}
}
}
// ----------------------------------------------------------------------
template <typename N, typename F3> inline void iterate_post(N&& aNode, F3&& f_subtree_post)
{
if (!aNode.is_leaf()) {
for (auto& node: aNode.subtree) {
iterate_post(node, std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
template <typename N, typename F1, typename F2, typename F3> inline void iterate_leaf_pre_post(N&& aNode, F1&& f_name, F2&& f_subtree_pre, F3&& f_subtree_post)
{
if (aNode.is_leaf()) {
f_name(std::forward<N>(aNode));
}
else {
f_subtree_pre(std::forward<N>(aNode));
for (auto node = aNode.subtree.begin(); node != aNode.subtree.end(); ++node) {
iterate_leaf_pre_post(*node, std::forward<F1>(f_name), std::forward<F2>(f_subtree_pre), std::forward<F3>(f_subtree_post));
}
f_subtree_post(std::forward<N>(aNode));
}
}
// ----------------------------------------------------------------------
} // namespace tree
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>/*
** Copyright 2011-2017 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/compression/stream.hh"
#include "com/centreon/broker/exceptions/interrupt.hh"
#include "com/centreon/broker/exceptions/shutdown.hh"
#include "com/centreon/broker/exceptions/timeout.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::compression;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Constructor.
*
* @param[in] level Compression level.
* @param[in] size Compression buffer size.
*/
stream::stream(int level, int size)
: _level(level), _shutdown(false), _size(size) {}
/**
* Copy constructor.
*
* @param[in] other Object to copy.
*/
stream::stream(stream const& other) : io::stream(other) {
_internal_copy(other);
}
/**
* Destructor.
*/
stream::~stream() {
try {
_flush();
}
// Ignore exception whatever the error might be.
catch (...) {}
}
/**
* Assignment operator.
*
* @param[in] other Object to copy.
*
* @return This object.
*/
stream& stream::operator=(stream const& other) {
if (this != &other) {
io::stream::operator=(other);
_internal_copy(other);
}
return (*this);
}
/**
* Read data.
*
* @param[out] data Data packet.
* @param[in] deadline Timeout.
*
* @return Respect io::stream::read()'s return value.
*/
bool stream::read(
misc::shared_ptr<io::data>& data,
time_t deadline) {
// Clear existing content.
data.clear();
try {
// Process buffer as long as data is corrupted
// or until an exception occurs.
bool corrupted(true);
int size(0);
while (corrupted) {
// Get compressed data length.
while (corrupted) {
_get_data(sizeof(qint32), deadline);
// We do not have enough data to get the next chunk's size.
// Stream is shutdown.
if (_rbuffer.size() < static_cast<int>(sizeof(qint32)))
throw (exceptions::shutdown() << "no more data to uncompress");
// Extract next chunk's size.
{
unsigned char const* buff((unsigned char const*)_rbuffer.data());
size = (buff[0] << 24)
| (buff[1] << 16)
| (buff[2] << 8)
| (buff[3]);
}
// Check if size is within bounds.
if ((size <= 0) || (size > max_data_size)) {
// Skip corrupted data, one byte at a time.
logging::error(logging::low)
<< "compression: " << this
<< " got corrupted packet size of " << size
<< " bytes, not in the 0-" << max_data_size
<< " range, skipping next byte";
_rbuffer.pop(1);
}
else
corrupted = false;
}
// Get compressed data.
_get_data(size + sizeof(qint32), deadline);
misc::shared_ptr<io::raw> r(new io::raw);
// The requested data size might have not been read entirely
// because of substream shutdown. This indicates that data is
// corrupted because the size is greater than the remaining
// payload size.
if (_rbuffer.size() >= static_cast<int>(size + sizeof(qint32))) {
r->QByteArray::operator=(qUncompress(
static_cast<uchar const*>(static_cast<void const*>((
_rbuffer.data() + sizeof(qint32)))),
size));
}
if (!r->size()) { // No data or uncompressed size of 0 means corrupted input.
logging::error(logging::low)
<< "compression: " << this
<< " got corrupted compressed data, skipping next byte";
_rbuffer.pop(1);
corrupted = true;
}
else {
logging::debug(logging::low) << "compression: " << this
<< " uncompressed " << size + sizeof(qint32) << " bytes to "
<< r->size() << " bytes";
data = r;
_rbuffer.pop(size + sizeof(qint32));
corrupted = false;
}
}
}
catch (exceptions::interrupt const& e) {
(void)e;
return (true);
}
catch (exceptions::timeout const& e) {
(void)e;
return (false);
}
catch (exceptions::shutdown const& e) {
_shutdown = true;
if (!_wbuffer.isEmpty()) {
misc::shared_ptr<io::raw> r(new io::raw);
*static_cast<QByteArray*>(r.data()) = _wbuffer;
data = r;
_wbuffer.clear();
}
else
throw ;
}
return (true);
}
/**
* Get statistics.
*
* @param[out] buffer Output buffer.
*/
void stream::statistics(io::properties& tree) const {
if (!_substream.isNull())
_substream->statistics(tree);
return ;
}
/**
* Flush the stream.
*
* @return The number of events acknowledged.
*/
int stream::flush() {
_flush();
return (0);
}
/**
* @brief Write data.
*
* The data can be buffered before being written to the subobject.
*
* @param[in] d Data to send.
*
* @return 1.
*/
int stream::write(misc::shared_ptr<io::data> const& d) {
if (!validate(d, "compression"))
return (1);
// Check if substream is shutdown.
if (_shutdown)
throw (exceptions::shutdown() << "cannot write to compression "
<< "stream: sub-stream is already shutdown");
// Process raw data only.
if (d->type() == io::raw::static_type()) {
io::raw const& r(d.ref_as<io::raw>());
// Check length.
if (r.size() > max_data_size)
throw (exceptions::msg() << "cannot compress buffers longer than "
<< max_data_size << " bytes: you should report this error "
<< "to Centreon Broker developers");
else if (r.size() > 0) {
// Append data to write buffer.
_wbuffer.append(r);
// Send compressed data if size limit is reached.
if (_wbuffer.size() >= _size)
_flush();
}
}
return (1);
}
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Flush data accumulated in write buffer.
*/
void stream::_flush() {
// Check for shutdown stream.
if (_shutdown)
throw (exceptions::shutdown() << "cannot flush compression "
<< "stream: sub-stream is already shutdown");
if (_wbuffer.size() > 0) {
// Compress data.
misc::shared_ptr<io::raw> compressed(new io::raw);
compressed->QByteArray::operator=(qCompress(_wbuffer, _level));
logging::debug(logging::low) << "compression: " << this
<< " compressed " << _wbuffer.size() << " bytes to "
<< compressed->size() << " bytes (level " << _level << ")";
_wbuffer.clear();
// Add compressed data size.
unsigned char buffer[4];
unsigned int size(compressed->size());
buffer[0] = size & 0xFF;
buffer[1] = (size >> 8) & 0xFF;
buffer[2] = (size >> 16) & 0xFF;
buffer[3] = (size >> 24) & 0xFF;
for (size_t i(0); i < sizeof(buffer); ++i)
compressed->prepend(buffer[i]);
// Send compressed data.
_substream->write(compressed);
}
return ;
}
/**
* Get data with a size.
*
* @param[in] size Data size to get.
* @param[in] deadline Timeout.
*/
void stream::_get_data(int size, time_t deadline) {
try {
while (_rbuffer.size() < size) {
misc::shared_ptr<io::data> d;
if (!_substream->read(d, deadline))
throw (exceptions::timeout());
else if (d.isNull())
throw (exceptions::interrupt());
else if (d->type() == io::raw::static_type()) {
misc::shared_ptr<io::raw> r(d.staticCast<io::raw>());
_rbuffer.push(*r);
}
}
}
// If the substream is shutdown, just indicates it and return already
// read data. Caller will handle missing data.
catch (exceptions::shutdown const& e) {
(void)e;
_shutdown = true;
}
return ;
}
/**
* Copy internal data members.
*
* @param[in] other Object to copy.
*/
void stream::_internal_copy(stream const& other) {
_level = other._level;
_rbuffer = other._rbuffer;
_size = other._size;
_wbuffer = other._wbuffer;
return ;
}
<commit_msg>core: add corruption detection log messages in compression layer.<commit_after>/*
** Copyright 2011-2017 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include "com/centreon/broker/compression/stream.hh"
#include "com/centreon/broker/exceptions/interrupt.hh"
#include "com/centreon/broker/exceptions/shutdown.hh"
#include "com/centreon/broker/exceptions/timeout.hh"
#include "com/centreon/broker/io/events.hh"
#include "com/centreon/broker/io/raw.hh"
#include "com/centreon/broker/logging/logging.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::compression;
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Constructor.
*
* @param[in] level Compression level.
* @param[in] size Compression buffer size.
*/
stream::stream(int level, int size)
: _level(level), _shutdown(false), _size(size) {}
/**
* Copy constructor.
*
* @param[in] other Object to copy.
*/
stream::stream(stream const& other) : io::stream(other) {
_internal_copy(other);
}
/**
* Destructor.
*/
stream::~stream() {
try {
_flush();
}
// Ignore exception whatever the error might be.
catch (...) {}
}
/**
* Assignment operator.
*
* @param[in] other Object to copy.
*
* @return This object.
*/
stream& stream::operator=(stream const& other) {
if (this != &other) {
io::stream::operator=(other);
_internal_copy(other);
}
return (*this);
}
/**
* Read data.
*
* @param[out] data Data packet.
* @param[in] deadline Timeout.
*
* @return Respect io::stream::read()'s return value.
*/
bool stream::read(
misc::shared_ptr<io::data>& data,
time_t deadline) {
// Clear existing content.
data.clear();
try {
// Process buffer as long as data is corrupted
// or until an exception occurs.
bool corrupted(true);
int size(0);
int skipped(0);
while (corrupted) {
// Get compressed data length.
while (corrupted) {
_get_data(sizeof(qint32), deadline);
// We do not have enough data to get the next chunk's size.
// Stream is shutdown.
if (_rbuffer.size() < static_cast<int>(sizeof(qint32)))
throw (exceptions::shutdown() << "no more data to uncompress");
// Extract next chunk's size.
{
unsigned char const* buff((unsigned char const*)_rbuffer.data());
size = (buff[0] << 24)
| (buff[1] << 16)
| (buff[2] << 8)
| (buff[3]);
}
// Check if size is within bounds.
if ((size <= 0) || (size > max_data_size)) {
// Skip corrupted data, one byte at a time.
logging::error(logging::low)
<< "compression: " << this
<< " got corrupted packet size of " << size
<< " bytes, not in the 0-" << max_data_size
<< " range, skipping next byte";
if (!skipped)
logging::error(logging::high) << "compression: peer "
<< peer() << " is sending corrupted data";
++skipped;
_rbuffer.pop(1);
}
else
corrupted = false;
}
// Get compressed data.
_get_data(size + sizeof(qint32), deadline);
misc::shared_ptr<io::raw> r(new io::raw);
// The requested data size might have not been read entirely
// because of substream shutdown. This indicates that data is
// corrupted because the size is greater than the remaining
// payload size.
if (_rbuffer.size() >= static_cast<int>(size + sizeof(qint32))) {
r->QByteArray::operator=(qUncompress(
static_cast<uchar const*>(static_cast<void const*>((
_rbuffer.data() + sizeof(qint32)))),
size));
}
if (!r->size()) { // No data or uncompressed size of 0 means corrupted input.
logging::error(logging::low)
<< "compression: " << this
<< " got corrupted compressed data, skipping next byte";
if (!skipped)
logging::error(logging::high) << "compression: peer "
<< peer() << " is sending corrupted data";
++skipped;
_rbuffer.pop(1);
corrupted = true;
}
else {
logging::debug(logging::low) << "compression: " << this
<< " uncompressed " << size + sizeof(qint32) << " bytes to "
<< r->size() << " bytes";
data = r;
_rbuffer.pop(size + sizeof(qint32));
corrupted = false;
}
}
if (skipped)
logging::info(logging::high) << "compression: peer " << peer()
<< " sent " << skipped
<< " corrupted compressed bytes, resuming processing";
}
catch (exceptions::interrupt const& e) {
(void)e;
return (true);
}
catch (exceptions::timeout const& e) {
(void)e;
return (false);
}
catch (exceptions::shutdown const& e) {
_shutdown = true;
if (!_wbuffer.isEmpty()) {
misc::shared_ptr<io::raw> r(new io::raw);
*static_cast<QByteArray*>(r.data()) = _wbuffer;
data = r;
_wbuffer.clear();
}
else
throw ;
}
return (true);
}
/**
* Get statistics.
*
* @param[out] buffer Output buffer.
*/
void stream::statistics(io::properties& tree) const {
if (!_substream.isNull())
_substream->statistics(tree);
return ;
}
/**
* Flush the stream.
*
* @return The number of events acknowledged.
*/
int stream::flush() {
_flush();
return (0);
}
/**
* @brief Write data.
*
* The data can be buffered before being written to the subobject.
*
* @param[in] d Data to send.
*
* @return 1.
*/
int stream::write(misc::shared_ptr<io::data> const& d) {
if (!validate(d, "compression"))
return (1);
// Check if substream is shutdown.
if (_shutdown)
throw (exceptions::shutdown() << "cannot write to compression "
<< "stream: sub-stream is already shutdown");
// Process raw data only.
if (d->type() == io::raw::static_type()) {
io::raw const& r(d.ref_as<io::raw>());
// Check length.
if (r.size() > max_data_size)
throw (exceptions::msg() << "cannot compress buffers longer than "
<< max_data_size << " bytes: you should report this error "
<< "to Centreon Broker developers");
else if (r.size() > 0) {
// Append data to write buffer.
_wbuffer.append(r);
// Send compressed data if size limit is reached.
if (_wbuffer.size() >= _size)
_flush();
}
}
return (1);
}
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Flush data accumulated in write buffer.
*/
void stream::_flush() {
// Check for shutdown stream.
if (_shutdown)
throw (exceptions::shutdown() << "cannot flush compression "
<< "stream: sub-stream is already shutdown");
if (_wbuffer.size() > 0) {
// Compress data.
misc::shared_ptr<io::raw> compressed(new io::raw);
compressed->QByteArray::operator=(qCompress(_wbuffer, _level));
logging::debug(logging::low) << "compression: " << this
<< " compressed " << _wbuffer.size() << " bytes to "
<< compressed->size() << " bytes (level " << _level << ")";
_wbuffer.clear();
// Add compressed data size.
unsigned char buffer[4];
unsigned int size(compressed->size());
buffer[0] = size & 0xFF;
buffer[1] = (size >> 8) & 0xFF;
buffer[2] = (size >> 16) & 0xFF;
buffer[3] = (size >> 24) & 0xFF;
for (size_t i(0); i < sizeof(buffer); ++i)
compressed->prepend(buffer[i]);
// Send compressed data.
_substream->write(compressed);
}
return ;
}
/**
* Get data with a size.
*
* @param[in] size Data size to get.
* @param[in] deadline Timeout.
*/
void stream::_get_data(int size, time_t deadline) {
try {
while (_rbuffer.size() < size) {
misc::shared_ptr<io::data> d;
if (!_substream->read(d, deadline))
throw (exceptions::timeout());
else if (d.isNull())
throw (exceptions::interrupt());
else if (d->type() == io::raw::static_type()) {
misc::shared_ptr<io::raw> r(d.staticCast<io::raw>());
_rbuffer.push(*r);
}
}
}
// If the substream is shutdown, just indicates it and return already
// read data. Caller will handle missing data.
catch (exceptions::shutdown const& e) {
(void)e;
_shutdown = true;
}
return ;
}
/**
* Copy internal data members.
*
* @param[in] other Object to copy.
*/
void stream::_internal_copy(stream const& other) {
_level = other._level;
_rbuffer = other._rbuffer;
_size = other._size;
_wbuffer = other._wbuffer;
return ;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
* Copyright 2020 Axel Waggershauser
*
* 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 "QRDetector.h"
#include "QRVersion.h"
#include "BitMatrix.h"
#include "BitMatrixCursor.h"
#include "DetectorResult.h"
#include "PerspectiveTransform.h"
#include "RegressionLine.h"
#include "ConcentricFinder.h"
#include "GridSampler.h"
#include "ZXNumeric.h"
#include "LogMatrix.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <map>
#include <utility>
namespace ZXing {
namespace QRCode {
static auto FindFinderPatterns(const BitMatrix& image, bool tryHarder)
{
constexpr int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
constexpr int MAX_MODULES = 20 * 4 + 17; // support up to version 20 for mobile clients
constexpr auto PATTERN = FixedPattern<5, 7>{1, 1, 3, 1, 1};
// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
// image, and then account for the center being 3 modules in size. This gives the smallest
// number of pixels the center could be, so skip this often. When trying harder, look for all
// QR versions regardless of how dense they are.
int height = image.height();
int skip = (3 * height) / (4 * MAX_MODULES);
if (skip < MIN_SKIP || tryHarder)
skip = MIN_SKIP;
std::vector<ConcentricPattern> res;
for (int y = skip - 1; y < height; y += skip) {
PatternRow row;
image.getPatternRow(y, row);
PatternView next = row;
while (next = FindLeftGuard(next, 0, PATTERN, 0.5), next.isValid()) {
PointF p(next.pixelsInFront() + next[0] + next[1] + next[2] / 2.0, y + 0.5);
// make sure p is not 'inside' an already found pattern area
if (FindIf(res, [p](const auto& old) { return distance(p, old) < old.size / 2; }) == res.end()) {
auto pattern = LocateConcentricPattern(image, PATTERN, p,
Reduce(next) * 3 / 2); // 1.5 for very skewed samples
if (pattern) {
log(*pattern, 3);
res.push_back(*pattern);
}
}
next.skipPair();
next.skipPair();
next.extend();
}
}
return res;
}
struct FinderPatternSet
{
ConcentricPattern bl, tl, tr;
};
using FinderPatternSets = std::vector<FinderPatternSet>;
/**
* @brief GenerateFinderPatternSets
* @param patterns list of ConcentricPattern objects, i.e. found finder pattern squares
* @return list of plausible finder pattern sets, sorted by decreasing plausibility
*/
static FinderPatternSets GenerateFinderPatternSets(std::vector<ConcentricPattern>&& patterns)
{
std::sort(patterns.begin(), patterns.end(), [](const auto& a, const auto& b) { return a.size < b.size; });
auto sets = std::multimap<double, FinderPatternSet>();
auto squaredDistance = [](PointF a, PointF b) { return dot((a - b), (a - b)); };
int nbPatterns = Size(patterns);
for (int i = 0; i < nbPatterns - 2; i++) {
for (int j = i + 1; j < nbPatterns - 1; j++) {
for (int k = j + 1; k < nbPatterns - 0; k++) {
const auto* a = &patterns[i];
const auto* b = &patterns[j];
const auto* c = &patterns[k];
// if the pattern sizes are too different to be part of the same symbol, skip this
// and the rest of the innermost loop (sorted list)
if (c->size > a->size * 2)
break;
// Orders the three points in an order [A,B,C] such that AB is less than AC
// and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
auto distAB = squaredDistance(*a, *b);
auto distBC = squaredDistance(*b, *c);
auto distAC = squaredDistance(*a, *c);
if (distBC >= distAB && distBC >= distAC) {
std::swap(a, b);
std::swap(distBC, distAC);
} else if (distAB >= distAC && distAB >= distBC) {
std::swap(b, c);
std::swap(distAB, distAC);
}
// a^2 + b^2 = c^2 (Pythagorean theorem), and a = b (isosceles triangle).
// Since any right triangle satisfies the formula c^2 - b^2 - a^2 = 0,
// we need to check both two equal sides separately.
// The value of |c^2 - 2 * b^2| + |c^2 - 2 * a^2| increases as dissimilarity
// from isosceles right triangle.
double d = std::abs(distAC - 2 * distAB) + std::abs(distAC - 2 * distBC);
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative then swap A and C.
if (cross(*c - *b, *a - *b) < 0)
std::swap(a, c);
sets.emplace(d, FinderPatternSet{*a, *b, *c});
// arbitrarily limit the number of potential sets
if (sets.size() > 16)
sets.erase(std::prev(sets.end()));
}
}
}
// convert from multimap to vector
FinderPatternSets res;
res.reserve(sets.size());
for (auto& [d, s] : sets)
res.push_back(s);
return res;
}
static double EstimateModuleSize(const BitMatrix& image, PointF a, PointF b)
{
BitMatrixCursorF cur(image, a, b - a);
cur.stepToEdge(3);
cur.turnBack();
cur.step();
assert(cur.isBlack());
auto pattern = cur.readPattern<std::array<int, 4>>();
return Reduce(pattern) / 6.0 * length(cur.d);
}
struct DimensionEstimate
{
int dim = 0;
double ms = 0;
int err = 0;
};
static DimensionEstimate EstimateDimension(const BitMatrix& image, PointF a, PointF b)
{
auto ms_a = EstimateModuleSize(image, a, b);
auto ms_b = EstimateModuleSize(image, b, a);
auto moduleSize = (ms_a + ms_b) / 2;
int dimension = std::lround(distance(a, b) / moduleSize) + 7;
int error = 1 - (dimension % 4);
return {dimension + error, moduleSize, std::abs(error)};
}
static RegressionLine traceLine(const BitMatrix& image, PointF p, PointF d, int edge)
{
BitMatrixCursorF cur(image, p, d - p);
RegressionLine line;
line.setDirectionInward(cur.back());
cur.stepToEdge(edge);
if (edge == 3) {
// collect points inside the black line -> go one step back
cur.turnBack();
cur.step();
}
for (auto dir : {Direction::LEFT, Direction::RIGHT}) {
auto c = BitMatrixCursorI(image, PointI(cur.p), PointI(mainDirection(cur.direction(dir))));
// if cur.d is near diagonal, it could be c.p is at a corner, i.e. c is not currently at an edge and hence,
// stepAlongEdge() would fail. Going either a step forward or backward should do the trick.
if (!c.edgeAt(dir)) {
c.step();
if (!c.edgeAt(dir)) {
c.step(-2);
if (!c.edgeAt(dir))
return {};
}
}
auto stepCount = std::lround(maxAbsComponent(cur.p - p));
do {
log(c.p, 2);
line.add(centered(c.p));
} while (--stepCount > 0 && c.stepAlongEdge(dir, true));
}
line.evaluate(1.0);
return line;
}
static DetectorResult SampleAtFinderPatternSet(const BitMatrix& image, const FinderPatternSet& fp)
{
auto top = EstimateDimension(image, fp.tl, fp.tr);
auto left = EstimateDimension(image, fp.tl, fp.bl);
auto best = top.err < left.err ? top : left;
int dimension = best.dim;
int moduleSize = static_cast<int>(best.ms + 1);
// generate 4 lines: outer and inner edge of the 1 module wide black line between the two outer and the inner
// (tl) finder pattern
auto bl2 = traceLine(image, fp.bl, fp.tl, 2);
auto bl3 = traceLine(image, fp.bl, fp.tl, 3);
auto tr2 = traceLine(image, fp.tr, fp.tl, 2);
auto tr3 = traceLine(image, fp.tr, fp.tl, 3);
auto quad = Rectangle(dimension, dimension, 3.5);
PointF br = fp.tr - fp.tl + fp.bl;
if (bl2.isValid() && tr2.isValid() && bl3.isValid() && tr3.isValid()) {
// intersect both outer and inner line pairs and take the center point between the two intersection points
br = (intersect(bl2, tr2) + intersect(bl3, tr3)) / 2;
log(br, 3);
quad[2] = quad[2] - PointF(3, 3);
// Everything except version 1 (21 modules) has an alignment pattern
if (dimension > 21) {
// in case we landed outside of the central black module of the alignment pattern, use the center
// of the next best circle (either outer or inner edge of the white part of the alignment pattern)
br = CenterOfRing(image, PointI(br), moduleSize * 4, 1, false).value_or(br);
br = LocateConcentricPattern(image, FixedPattern<3, 3>{1, 1, 1}, br, moduleSize * 3)
.value_or(ConcentricPattern{br});
}
}
return SampleGrid(image, dimension, dimension, {quad, {fp.tl, fp.tr, br, fp.bl}});
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
static DetectorResult DetectPure(const BitMatrix& image)
{
const int minSize = 21; // Number of modules in the smallest QRCode (Version 1)
int left, top, width, height;
if (!image.findBoundingBox(left, top, width, height, minSize) || width != height) {
return {};
}
// find the first white pixel on the diagonal
int moduleSize = 1;
while (moduleSize < width / minSize && image.get(left + moduleSize, top + moduleSize))
++moduleSize;
int matrixWidth = width / moduleSize;
int matrixHeight = height / moduleSize;
if (matrixWidth < minSize || matrixHeight < minSize) {
return {};
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int msh = moduleSize / 2;
int right = left + width - 1;
int bottom = top + height - 1;
// Now just read off the bits (this is a crop + subsample)
return {Deflate(image, matrixWidth, matrixHeight, top + msh, left + msh, moduleSize),
{{left, top}, {right, top}, {right, bottom}, {left, bottom}}};
}
DetectorResult Detector::Detect(const BitMatrix& image, bool tryHarder, bool isPure)
{
#ifdef PRINT_DEBUG
LogMatrixWriter lmw(log, image, 5, "qr-log.pnm");
#endif
if (isPure)
return DetectPure(image);
auto sets = GenerateFinderPatternSets(FindFinderPatterns(image, tryHarder));
if (sets.empty())
return {};
#ifdef PRINT_DEBUG
printf("size of sets: %d\n", Size(sets));
#endif
return SampleAtFinderPatternSet(image, sets[0]);
}
} // QRCode
} // ZXing
<commit_msg>QRDetector: consistent static function name CamlCasing<commit_after>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
* Copyright 2020 Axel Waggershauser
*
* 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 "QRDetector.h"
#include "QRVersion.h"
#include "BitMatrix.h"
#include "BitMatrixCursor.h"
#include "DetectorResult.h"
#include "PerspectiveTransform.h"
#include "RegressionLine.h"
#include "ConcentricFinder.h"
#include "GridSampler.h"
#include "ZXNumeric.h"
#include "LogMatrix.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <map>
#include <utility>
namespace ZXing {
namespace QRCode {
static auto FindFinderPatterns(const BitMatrix& image, bool tryHarder)
{
constexpr int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
constexpr int MAX_MODULES = 20 * 4 + 17; // support up to version 20 for mobile clients
constexpr auto PATTERN = FixedPattern<5, 7>{1, 1, 3, 1, 1};
// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
// image, and then account for the center being 3 modules in size. This gives the smallest
// number of pixels the center could be, so skip this often. When trying harder, look for all
// QR versions regardless of how dense they are.
int height = image.height();
int skip = (3 * height) / (4 * MAX_MODULES);
if (skip < MIN_SKIP || tryHarder)
skip = MIN_SKIP;
std::vector<ConcentricPattern> res;
for (int y = skip - 1; y < height; y += skip) {
PatternRow row;
image.getPatternRow(y, row);
PatternView next = row;
while (next = FindLeftGuard(next, 0, PATTERN, 0.5), next.isValid()) {
PointF p(next.pixelsInFront() + next[0] + next[1] + next[2] / 2.0, y + 0.5);
// make sure p is not 'inside' an already found pattern area
if (FindIf(res, [p](const auto& old) { return distance(p, old) < old.size / 2; }) == res.end()) {
auto pattern = LocateConcentricPattern(image, PATTERN, p,
Reduce(next) * 3 / 2); // 1.5 for very skewed samples
if (pattern) {
log(*pattern, 3);
res.push_back(*pattern);
}
}
next.skipPair();
next.skipPair();
next.extend();
}
}
return res;
}
struct FinderPatternSet
{
ConcentricPattern bl, tl, tr;
};
using FinderPatternSets = std::vector<FinderPatternSet>;
/**
* @brief GenerateFinderPatternSets
* @param patterns list of ConcentricPattern objects, i.e. found finder pattern squares
* @return list of plausible finder pattern sets, sorted by decreasing plausibility
*/
static FinderPatternSets GenerateFinderPatternSets(std::vector<ConcentricPattern>&& patterns)
{
std::sort(patterns.begin(), patterns.end(), [](const auto& a, const auto& b) { return a.size < b.size; });
auto sets = std::multimap<double, FinderPatternSet>();
auto squaredDistance = [](PointF a, PointF b) { return dot((a - b), (a - b)); };
int nbPatterns = Size(patterns);
for (int i = 0; i < nbPatterns - 2; i++) {
for (int j = i + 1; j < nbPatterns - 1; j++) {
for (int k = j + 1; k < nbPatterns - 0; k++) {
const auto* a = &patterns[i];
const auto* b = &patterns[j];
const auto* c = &patterns[k];
// if the pattern sizes are too different to be part of the same symbol, skip this
// and the rest of the innermost loop (sorted list)
if (c->size > a->size * 2)
break;
// Orders the three points in an order [A,B,C] such that AB is less than AC
// and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
auto distAB = squaredDistance(*a, *b);
auto distBC = squaredDistance(*b, *c);
auto distAC = squaredDistance(*a, *c);
if (distBC >= distAB && distBC >= distAC) {
std::swap(a, b);
std::swap(distBC, distAC);
} else if (distAB >= distAC && distAB >= distBC) {
std::swap(b, c);
std::swap(distAB, distAC);
}
// a^2 + b^2 = c^2 (Pythagorean theorem), and a = b (isosceles triangle).
// Since any right triangle satisfies the formula c^2 - b^2 - a^2 = 0,
// we need to check both two equal sides separately.
// The value of |c^2 - 2 * b^2| + |c^2 - 2 * a^2| increases as dissimilarity
// from isosceles right triangle.
double d = std::abs(distAC - 2 * distAB) + std::abs(distAC - 2 * distBC);
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative then swap A and C.
if (cross(*c - *b, *a - *b) < 0)
std::swap(a, c);
sets.emplace(d, FinderPatternSet{*a, *b, *c});
// arbitrarily limit the number of potential sets
if (sets.size() > 16)
sets.erase(std::prev(sets.end()));
}
}
}
// convert from multimap to vector
FinderPatternSets res;
res.reserve(sets.size());
for (auto& [d, s] : sets)
res.push_back(s);
return res;
}
static double EstimateModuleSize(const BitMatrix& image, PointF a, PointF b)
{
BitMatrixCursorF cur(image, a, b - a);
cur.stepToEdge(3);
cur.turnBack();
cur.step();
assert(cur.isBlack());
auto pattern = cur.readPattern<std::array<int, 4>>();
return Reduce(pattern) / 6.0 * length(cur.d);
}
struct DimensionEstimate
{
int dim = 0;
double ms = 0;
int err = 0;
};
static DimensionEstimate EstimateDimension(const BitMatrix& image, PointF a, PointF b)
{
auto ms_a = EstimateModuleSize(image, a, b);
auto ms_b = EstimateModuleSize(image, b, a);
auto moduleSize = (ms_a + ms_b) / 2;
int dimension = std::lround(distance(a, b) / moduleSize) + 7;
int error = 1 - (dimension % 4);
return {dimension + error, moduleSize, std::abs(error)};
}
static RegressionLine TraceLine(const BitMatrix& image, PointF p, PointF d, int edge)
{
BitMatrixCursorF cur(image, p, d - p);
RegressionLine line;
line.setDirectionInward(cur.back());
cur.stepToEdge(edge);
if (edge == 3) {
// collect points inside the black line -> go one step back
cur.turnBack();
cur.step();
}
for (auto dir : {Direction::LEFT, Direction::RIGHT}) {
auto c = BitMatrixCursorI(image, PointI(cur.p), PointI(mainDirection(cur.direction(dir))));
// if cur.d is near diagonal, it could be c.p is at a corner, i.e. c is not currently at an edge and hence,
// stepAlongEdge() would fail. Going either a step forward or backward should do the trick.
if (!c.edgeAt(dir)) {
c.step();
if (!c.edgeAt(dir)) {
c.step(-2);
if (!c.edgeAt(dir))
return {};
}
}
auto stepCount = std::lround(maxAbsComponent(cur.p - p));
do {
log(c.p, 2);
line.add(centered(c.p));
} while (--stepCount > 0 && c.stepAlongEdge(dir, true));
}
line.evaluate(1.0);
return line;
}
static DetectorResult SampleAtFinderPatternSet(const BitMatrix& image, const FinderPatternSet& fp)
{
auto top = EstimateDimension(image, fp.tl, fp.tr);
auto left = EstimateDimension(image, fp.tl, fp.bl);
auto best = top.err < left.err ? top : left;
int dimension = best.dim;
int moduleSize = static_cast<int>(best.ms + 1);
// generate 4 lines: outer and inner edge of the 1 module wide black line between the two outer and the inner
// (tl) finder pattern
auto bl2 = TraceLine(image, fp.bl, fp.tl, 2);
auto bl3 = TraceLine(image, fp.bl, fp.tl, 3);
auto tr2 = TraceLine(image, fp.tr, fp.tl, 2);
auto tr3 = TraceLine(image, fp.tr, fp.tl, 3);
auto quad = Rectangle(dimension, dimension, 3.5);
PointF br = fp.tr - fp.tl + fp.bl;
if (bl2.isValid() && tr2.isValid() && bl3.isValid() && tr3.isValid()) {
// intersect both outer and inner line pairs and take the center point between the two intersection points
br = (intersect(bl2, tr2) + intersect(bl3, tr3)) / 2;
log(br, 3);
quad[2] = quad[2] - PointF(3, 3);
// Everything except version 1 (21 modules) has an alignment pattern
if (dimension > 21) {
// in case we landed outside of the central black module of the alignment pattern, use the center
// of the next best circle (either outer or inner edge of the white part of the alignment pattern)
br = CenterOfRing(image, PointI(br), moduleSize * 4, 1, false).value_or(br);
br = LocateConcentricPattern(image, FixedPattern<3, 3>{1, 1, 1}, br, moduleSize * 3)
.value_or(ConcentricPattern{br});
}
}
return SampleGrid(image, dimension, dimension, {quad, {fp.tl, fp.tr, br, fp.bl}});
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
static DetectorResult DetectPure(const BitMatrix& image)
{
const int minSize = 21; // Number of modules in the smallest QRCode (Version 1)
int left, top, width, height;
if (!image.findBoundingBox(left, top, width, height, minSize) || width != height) {
return {};
}
// find the first white pixel on the diagonal
int moduleSize = 1;
while (moduleSize < width / minSize && image.get(left + moduleSize, top + moduleSize))
++moduleSize;
int matrixWidth = width / moduleSize;
int matrixHeight = height / moduleSize;
if (matrixWidth < minSize || matrixHeight < minSize) {
return {};
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int msh = moduleSize / 2;
int right = left + width - 1;
int bottom = top + height - 1;
// Now just read off the bits (this is a crop + subsample)
return {Deflate(image, matrixWidth, matrixHeight, top + msh, left + msh, moduleSize),
{{left, top}, {right, top}, {right, bottom}, {left, bottom}}};
}
DetectorResult Detector::Detect(const BitMatrix& image, bool tryHarder, bool isPure)
{
#ifdef PRINT_DEBUG
LogMatrixWriter lmw(log, image, 5, "qr-log.pnm");
#endif
if (isPure)
return DetectPure(image);
auto sets = GenerateFinderPatternSets(FindFinderPatterns(image, tryHarder));
if (sets.empty())
return {};
#ifdef PRINT_DEBUG
printf("size of sets: %d\n", Size(sets));
#endif
return SampleAtFinderPatternSet(image, sets[0]);
}
} // QRCode
} // ZXing
<|endoftext|> |
<commit_before>#ifndef context_hh_INCLUDED
#define context_hh_INCLUDED
#include "window.hh"
#include "input_handler.hh"
#include "user_interface.hh"
namespace Kakoune
{
// A Context is used to access non singleton objects for various services
// in commands.
//
// The Context object links an InputHandler, an Editor (which may be a Window),
// and a UserInterface. It may represent an interactive user window, or
// a hook execution or a macro replay.
struct Context
{
Context() {}
explicit Context(Editor& editor)
: m_editor(&editor) {}
Context(InputHandler& input_handler, Editor& editor, UserInterface& ui)
: m_input_handler(&input_handler), m_editor(&editor), m_ui(&ui) {}
// to allow func(Context(Editor(...)))
// make sure the context will not survive the next ';'
explicit Context(Editor&& editor)
: m_editor(&editor) {}
Context(const Context&) = delete;
Context(Context&&) = default;
Context& operator=(const Context&) = delete;
Buffer& buffer() const
{
if (not has_buffer())
throw runtime_error("no buffer in context");
return m_editor->buffer();
}
bool has_buffer() const { return (bool)m_editor; }
Editor& editor() const
{
if (not has_editor())
throw runtime_error("no editor in context");
return *m_editor.get();
}
bool has_editor() const { return (bool)m_editor; }
Window& window() const
{
if (not has_window())
throw runtime_error("no window in context");
return *dynamic_cast<Window*>(m_editor.get());
}
bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }
InputHandler& input_handler() const
{
if (not has_input_handler())
throw runtime_error("no input handler in context");
return *m_input_handler;
}
bool has_input_handler() const { return (bool)m_input_handler; }
UserInterface& ui() const
{
if (not has_ui())
throw runtime_error("no user interface in context");
return *m_ui;
}
bool has_ui() const { return (bool)m_ui; }
void change_editor(Editor& editor)
{
m_editor.reset(&editor);
}
void change_ui(UserInterface& ui)
{
m_ui.reset(&ui);
}
OptionManager& option_manager() const
{
if (has_window())
return window().option_manager();
if (has_buffer())
return buffer().option_manager();
return GlobalOptionManager::instance();
}
void print_status(const String& status) const
{
if (has_ui())
ui().print_status(status);
}
using Insertion = std::pair<InsertMode, std::vector<Key>>;
Insertion& last_insert() { return m_last_insert; }
void push_jump()
{
const SelectionAndCaptures& jump = editor().selections().back();
if (m_current_jump != m_jump_list.end())
{
auto begin = m_current_jump;
// when jump overlaps with m_current_jump, we replace m_current_jump
// instead of pushing after it.
if (&begin->first().buffer() != &jump.first().buffer() or
not overlaps(*begin, jump))
++begin;
m_jump_list.erase(begin, m_jump_list.end());
}
m_jump_list.push_back(jump);
m_current_jump = m_jump_list.end();
}
SelectionAndCaptures jump_forward()
{
if (m_current_jump != m_jump_list.end() and
m_current_jump + 1 != m_jump_list.end())
return *++m_current_jump;
throw runtime_error("no next jump");
}
SelectionAndCaptures jump_backward()
{
if (m_current_jump != m_jump_list.begin())
{
if (m_current_jump == m_jump_list.end())
{
push_jump();
--m_current_jump;
}
return *--m_current_jump;
}
throw runtime_error("no previous jump");
}
void forget_jumps_to_buffer(Buffer& buffer)
{
for (auto it = m_jump_list.begin(); it != m_jump_list.end();)
{
if (&it->first().buffer() == &buffer)
{
if (it < m_current_jump)
--m_current_jump;
else if (it == m_current_jump)
m_current_jump = m_jump_list.end()-1;
it = m_jump_list.erase(it);
}
else
++it;
}
}
int& numeric_param() { return m_numeric_param; }
private:
safe_ptr<Editor> m_editor;
safe_ptr<InputHandler> m_input_handler;
safe_ptr<UserInterface> m_ui;
Insertion m_last_insert = {InsertMode::Insert, {}};
int m_numeric_param = 0;
SelectionAndCapturesList m_jump_list;
SelectionAndCapturesList::iterator m_current_jump = m_jump_list.begin();
};
}
#endif // context_hh_INCLUDED
<commit_msg>Context: set dimensions of window on change_editor<commit_after>#ifndef context_hh_INCLUDED
#define context_hh_INCLUDED
#include "window.hh"
#include "input_handler.hh"
#include "user_interface.hh"
namespace Kakoune
{
// A Context is used to access non singleton objects for various services
// in commands.
//
// The Context object links an InputHandler, an Editor (which may be a Window),
// and a UserInterface. It may represent an interactive user window, or
// a hook execution or a macro replay.
struct Context
{
Context() {}
explicit Context(Editor& editor)
: m_editor(&editor) {}
Context(InputHandler& input_handler, Editor& editor, UserInterface& ui)
: m_input_handler(&input_handler), m_editor(&editor), m_ui(&ui) {}
// to allow func(Context(Editor(...)))
// make sure the context will not survive the next ';'
explicit Context(Editor&& editor)
: m_editor(&editor) {}
Context(const Context&) = delete;
Context(Context&&) = default;
Context& operator=(const Context&) = delete;
Buffer& buffer() const
{
if (not has_buffer())
throw runtime_error("no buffer in context");
return m_editor->buffer();
}
bool has_buffer() const { return (bool)m_editor; }
Editor& editor() const
{
if (not has_editor())
throw runtime_error("no editor in context");
return *m_editor.get();
}
bool has_editor() const { return (bool)m_editor; }
Window& window() const
{
if (not has_window())
throw runtime_error("no window in context");
return *dynamic_cast<Window*>(m_editor.get());
}
bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }
InputHandler& input_handler() const
{
if (not has_input_handler())
throw runtime_error("no input handler in context");
return *m_input_handler;
}
bool has_input_handler() const { return (bool)m_input_handler; }
UserInterface& ui() const
{
if (not has_ui())
throw runtime_error("no user interface in context");
return *m_ui;
}
bool has_ui() const { return (bool)m_ui; }
void change_editor(Editor& editor)
{
m_editor.reset(&editor);
if (has_window() && has_ui())
window().set_dimensions(ui().dimensions());
}
void change_ui(UserInterface& ui)
{
m_ui.reset(&ui);
}
OptionManager& option_manager() const
{
if (has_window())
return window().option_manager();
if (has_buffer())
return buffer().option_manager();
return GlobalOptionManager::instance();
}
void print_status(const String& status) const
{
if (has_ui())
ui().print_status(status);
}
using Insertion = std::pair<InsertMode, std::vector<Key>>;
Insertion& last_insert() { return m_last_insert; }
void push_jump()
{
const SelectionAndCaptures& jump = editor().selections().back();
if (m_current_jump != m_jump_list.end())
{
auto begin = m_current_jump;
// when jump overlaps with m_current_jump, we replace m_current_jump
// instead of pushing after it.
if (&begin->first().buffer() != &jump.first().buffer() or
not overlaps(*begin, jump))
++begin;
m_jump_list.erase(begin, m_jump_list.end());
}
m_jump_list.push_back(jump);
m_current_jump = m_jump_list.end();
}
SelectionAndCaptures jump_forward()
{
if (m_current_jump != m_jump_list.end() and
m_current_jump + 1 != m_jump_list.end())
return *++m_current_jump;
throw runtime_error("no next jump");
}
SelectionAndCaptures jump_backward()
{
if (m_current_jump != m_jump_list.begin())
{
if (m_current_jump == m_jump_list.end())
{
push_jump();
--m_current_jump;
}
return *--m_current_jump;
}
throw runtime_error("no previous jump");
}
void forget_jumps_to_buffer(Buffer& buffer)
{
for (auto it = m_jump_list.begin(); it != m_jump_list.end();)
{
if (&it->first().buffer() == &buffer)
{
if (it < m_current_jump)
--m_current_jump;
else if (it == m_current_jump)
m_current_jump = m_jump_list.end()-1;
it = m_jump_list.erase(it);
}
else
++it;
}
}
int& numeric_param() { return m_numeric_param; }
private:
safe_ptr<Editor> m_editor;
safe_ptr<InputHandler> m_input_handler;
safe_ptr<UserInterface> m_ui;
Insertion m_last_insert = {InsertMode::Insert, {}};
int m_numeric_param = 0;
SelectionAndCapturesList m_jump_list;
SelectionAndCapturesList::iterator m_current_jump = m_jump_list.begin();
};
}
#endif // context_hh_INCLUDED
<|endoftext|> |
<commit_before>#include "spriteStyle.h"
#include "platform.h"
#include "tile/tile.h"
#include "gl/shaderProgram.h"
#include "gl/texture.h"
#include "gl/vertexLayout.h"
#include "util/builders.h"
#include "view/view.h"
#include "labels/spriteLabel.h"
#include "glm/gtc/type_ptr.hpp"
namespace Tangram {
SpriteStyle::SpriteStyle(std::string _name, Blending _blendMode, GLenum _drawMode) : Style(_name, _blendMode, _drawMode) {
}
SpriteStyle::~SpriteStyle() {}
void SpriteStyle::constructVertexLayout() {
// 32 bytes, good for memory aligments
m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 2, GL_FLOAT, false, 0},
{"a_uv", 2, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
{"a_screenPosition", 2, GL_FLOAT, false, 0},
{"a_alpha", 1, GL_FLOAT, false, 0},
{"a_rotation", 1, GL_FLOAT, false, 0},
}));
}
void SpriteStyle::constructShaderProgram() {
std::string fragShaderSrcStr = stringFromResource("sprite.fs");
std::string vertShaderSrcStr = stringFromResource("point.vs");
m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
// TODO : load this from stylesheet
m_spriteAtlas = std::unique_ptr<SpriteAtlas>(new SpriteAtlas("poi_icons_32.png"));
m_spriteAtlas->addSpriteNode("plane", {0, 0}, {32, 32});
m_spriteAtlas->addSpriteNode("tree", {0, 185}, {32, 32});
m_spriteAtlas->addSpriteNode("sunburst", {0, 629}, {32, 32});
m_spriteAtlas->addSpriteNode("restaurant", {0, 777}, {32, 32});
m_spriteAtlas->addSpriteNode("cafe", {0, 814}, {32, 32});
m_spriteAtlas->addSpriteNode("museum", {0, 518}, {32, 32});
m_spriteAtlas->addSpriteNode("bar", {0, 887}, {32, 32});
m_spriteAtlas->addSpriteNode("train", {0, 74}, {32, 32});
m_spriteAtlas->addSpriteNode("bus", {0, 148}, {32, 32});
m_spriteAtlas->addSpriteNode("hospital", {0, 444}, {32, 32});
m_spriteAtlas->addSpriteNode("parking", {0, 1073}, {32, 32});
m_spriteAtlas->addSpriteNode("info", {0, 1110}, {32, 32});
m_spriteAtlas->addSpriteNode("hotel", {0, 259}, {32, 32});
m_spriteAtlas->addSpriteNode("bookstore", {0, 333}, {32, 32});
}
void SpriteStyle::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// TODO : make this configurable
std::vector<Label::Vertex> vertices;
// TODO : configure this
float spriteScale = .5f;
glm::vec2 offset = {0.f, 10.f};
const static std::string key("kind");
std::string spriteName;
if (!_rule.get(StyleParamKey::sprite, spriteName)) {
spriteName = _props.getString(key);
}
if (spriteName.empty() || !m_spriteAtlas->hasSpriteNode(spriteName)) {
return;
}
SpriteNode spriteNode = m_spriteAtlas->getSpriteNode(spriteName);
Label::Transform t = { glm::vec2(_point), glm::vec2(_point), offset };
auto& mesh = static_cast<LabelMesh&>(_mesh);
Label::Options options;
options.offset = offset;
std::unique_ptr<SpriteLabel> label(new SpriteLabel(t, spriteNode.m_size * spriteScale, mesh, _mesh.numVertices(), options));
auto size = spriteNode.m_size * spriteScale;
float halfWidth = size.x * .5f;
float halfHeight = size.y * .5f;
const glm::vec2& uvBL = spriteNode.m_uvBL;
const glm::vec2& uvTR = spriteNode.m_uvTR;
vertices.reserve(4);
vertices.push_back({{-halfWidth, -halfHeight}, {uvBL.x, uvBL.y}, options.color});
vertices.push_back({{-halfWidth, halfHeight}, {uvBL.x, uvTR.y}, options.color});
vertices.push_back({{halfWidth, -halfHeight}, {uvTR.x, uvBL.y}, options.color});
vertices.push_back({{halfWidth, halfHeight}, {uvTR.x, uvTR.y}, options.color});
mesh.addVertices(std::move(vertices), {});
mesh.addLabel(std::move(label));
}
void SpriteStyle::onBeginDrawFrame(const View& _view, const Scene& _scene) {
bool contextLost = Style::glContextLost();
m_spriteAtlas->bind();
static bool initUniformSampler = true;
if (initUniformSampler || contextLost) {
m_shaderProgram->setUniformi("u_tex", 0);
initUniformSampler = false;
}
if (m_dirtyViewport || contextLost) {
m_shaderProgram->setUniformMatrix4f("u_proj", glm::value_ptr(_view.getOrthoViewportMatrix()));
m_dirtyViewport = false;
}
Style::onBeginDrawFrame(_view, _scene);
}
}
<commit_msg>Update sprite transform with new constructor<commit_after>#include "spriteStyle.h"
#include "platform.h"
#include "tile/tile.h"
#include "gl/shaderProgram.h"
#include "gl/texture.h"
#include "gl/vertexLayout.h"
#include "util/builders.h"
#include "view/view.h"
#include "labels/spriteLabel.h"
#include "glm/gtc/type_ptr.hpp"
namespace Tangram {
SpriteStyle::SpriteStyle(std::string _name, Blending _blendMode, GLenum _drawMode) : Style(_name, _blendMode, _drawMode) {
}
SpriteStyle::~SpriteStyle() {}
void SpriteStyle::constructVertexLayout() {
// 32 bytes, good for memory aligments
m_vertexLayout = std::shared_ptr<VertexLayout>(new VertexLayout({
{"a_position", 2, GL_FLOAT, false, 0},
{"a_uv", 2, GL_FLOAT, false, 0},
{"a_color", 4, GL_UNSIGNED_BYTE, true, 0},
{"a_screenPosition", 2, GL_FLOAT, false, 0},
{"a_alpha", 1, GL_FLOAT, false, 0},
{"a_rotation", 1, GL_FLOAT, false, 0},
}));
}
void SpriteStyle::constructShaderProgram() {
std::string fragShaderSrcStr = stringFromResource("sprite.fs");
std::string vertShaderSrcStr = stringFromResource("point.vs");
m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);
// TODO : load this from stylesheet
m_spriteAtlas = std::unique_ptr<SpriteAtlas>(new SpriteAtlas("poi_icons_32.png"));
m_spriteAtlas->addSpriteNode("plane", {0, 0}, {32, 32});
m_spriteAtlas->addSpriteNode("tree", {0, 185}, {32, 32});
m_spriteAtlas->addSpriteNode("sunburst", {0, 629}, {32, 32});
m_spriteAtlas->addSpriteNode("restaurant", {0, 777}, {32, 32});
m_spriteAtlas->addSpriteNode("cafe", {0, 814}, {32, 32});
m_spriteAtlas->addSpriteNode("museum", {0, 518}, {32, 32});
m_spriteAtlas->addSpriteNode("bar", {0, 887}, {32, 32});
m_spriteAtlas->addSpriteNode("train", {0, 74}, {32, 32});
m_spriteAtlas->addSpriteNode("bus", {0, 148}, {32, 32});
m_spriteAtlas->addSpriteNode("hospital", {0, 444}, {32, 32});
m_spriteAtlas->addSpriteNode("parking", {0, 1073}, {32, 32});
m_spriteAtlas->addSpriteNode("info", {0, 1110}, {32, 32});
m_spriteAtlas->addSpriteNode("hotel", {0, 259}, {32, 32});
m_spriteAtlas->addSpriteNode("bookstore", {0, 333}, {32, 32});
}
void SpriteStyle::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
// TODO : make this configurable
std::vector<Label::Vertex> vertices;
// TODO : configure this
float spriteScale = .5f;
glm::vec2 offset = {0.f, 10.f};
const static std::string key("kind");
std::string spriteName;
if (!_rule.get(StyleParamKey::sprite, spriteName)) {
spriteName = _props.getString(key);
}
if (spriteName.empty() || !m_spriteAtlas->hasSpriteNode(spriteName)) {
return;
}
SpriteNode spriteNode = m_spriteAtlas->getSpriteNode(spriteName);
Label::Transform t = { glm::vec2(_point) };
auto& mesh = static_cast<LabelMesh&>(_mesh);
Label::Options options;
options.offset = offset;
std::unique_ptr<SpriteLabel> label(new SpriteLabel(t, spriteNode.m_size * spriteScale, mesh, _mesh.numVertices(), options));
auto size = spriteNode.m_size * spriteScale;
float halfWidth = size.x * .5f;
float halfHeight = size.y * .5f;
const glm::vec2& uvBL = spriteNode.m_uvBL;
const glm::vec2& uvTR = spriteNode.m_uvTR;
vertices.reserve(4);
vertices.push_back({{-halfWidth, -halfHeight}, {uvBL.x, uvBL.y}, options.color});
vertices.push_back({{-halfWidth, halfHeight}, {uvBL.x, uvTR.y}, options.color});
vertices.push_back({{halfWidth, -halfHeight}, {uvTR.x, uvBL.y}, options.color});
vertices.push_back({{halfWidth, halfHeight}, {uvTR.x, uvTR.y}, options.color});
mesh.addVertices(std::move(vertices), {});
mesh.addLabel(std::move(label));
}
void SpriteStyle::onBeginDrawFrame(const View& _view, const Scene& _scene) {
bool contextLost = Style::glContextLost();
m_spriteAtlas->bind();
static bool initUniformSampler = true;
if (initUniformSampler || contextLost) {
m_shaderProgram->setUniformi("u_tex", 0);
initUniformSampler = false;
}
if (m_dirtyViewport || contextLost) {
m_shaderProgram->setUniformMatrix4f("u_proj", glm::value_ptr(_view.getOrthoViewportMatrix()));
m_dirtyViewport = false;
}
Style::onBeginDrawFrame(_view, _scene);
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <functional>
#include <cstddef>
static constexpr int min = 1;
static constexpr int max = 255;
struct Hash {
inline std::size_t operator () (std::vector<char> const & str) const
{
return std::hash<std::string>()(std::string(str.cbegin(), str.cend()));
}
};
typedef std::unordered_map<std::vector<char>, std::pair<char, char>, Hash> Dictionary;
static void dictAdd(std::vector<char> const & str, Dictionary& dict, int& a, int& b)
{
if (a >= max + 1)
{
a = min;
++b;
if (b >= max + 1)
{
dict.clear();
b = min + 1;
}
}
dict[str] = std::make_pair(a, b);
++a;
}
std::string compress(std::string const & input)
{
Dictionary dict;
int a = min;
int b = min + 1;
std::vector<char> result;
result.push_back('c');
std::vector<char> word;
for (const char & c : input) {
std::vector<char> wc = word;
wc.push_back(c);
if (!(wc.size() == 1 || dict.find(wc) != dict.end()))
{
if (word.size() == 1)
{
result.push_back(word.at(0));
result.push_back(static_cast<char>(min));
}
else
{
auto& temp = dict[word];
result.push_back(temp.first);
result.push_back(temp.second);
}
dictAdd(wc, dict, a, b);
word.clear();
word.push_back(c);
}
else
word = wc;
}
if (word.size() == 1)
{
result.push_back(word.at(0));
result.push_back(static_cast<char>(min));
}
else
{
auto& temp = dict[word];
result.push_back(temp.first);
result.push_back(temp.second);
}
if (input.size() <= result.size())
return 'u' + input;
return std::string(result.cbegin(), result.cend());
}
<commit_msg>Add some comments<commit_after>#include <string>
#include <vector>
#include <unordered_map>
#include <utility> // std::make_pair
#include <functional> // std::hash
#include <cstddef> // std::size_t
// range of byte values used in compression output.
// if min = 0 then the compression output can contain null characters in the middle of the string
static constexpr int min = 1;
static constexpr int max = 255;
struct Hash {
inline std::size_t operator () (std::vector<char> const & str) const
{
return std::hash<std::string>()(std::string(str.cbegin(), str.cend()));
}
};
typedef std::unordered_map<std::vector<char>, std::pair<char, char>, Hash> Dictionary;
static void dictAdd(std::vector<char> const & str, Dictionary& dict, int& a, int& b)
{
if (a >= max + 1)
{
a = min;
++b;
if (b >= max + 1)
{
dict.clear();
b = min + 1;
}
}
dict[str] = std::make_pair(a, b);
++a;
}
std::string compress(std::string const & input)
{
Dictionary dict;
int a = min;
int b = min + 1;
std::vector<char> result;
result.push_back('c');
std::vector<char> word;
for (const char & c : input) {
std::vector<char> wc = word;
wc.push_back(c);
if (!(wc.size() == 1 || dict.find(wc) != dict.end()))
{
if (word.size() == 1)
{
result.push_back(word.at(0));
result.push_back(static_cast<char>(min));
}
else
{
auto& temp = dict[word];
result.push_back(temp.first);
result.push_back(temp.second);
}
dictAdd(wc, dict, a, b);
word.clear();
word.push_back(c);
}
else
word = wc;
}
if (word.size() == 1)
{
result.push_back(word.at(0));
result.push_back(static_cast<char>(min));
}
else
{
auto& temp = dict[word];
result.push_back(temp.first);
result.push_back(temp.second);
}
if (input.size() <= result.size())
return 'u' + input;
return std::string(result.cbegin(), result.cend());
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkImage.h"
#include <mitkImageCast.h>
#include "mitkBaseData.h"
#include <mitkDiffusionPropertyHelper.h>
#include <itkTensorReconstructionWithEigenvalueCorrectionFilter.h>
#include <itkDiffusionTensor3DReconstructionImageFilter.h>
#include <itkDiffusionTensor3D.h>
#include <itkImageFileWriter.h>
#include <itkNrrdImageIO.h>
#include "mitkCommandLineParser.h"
#include <itksys/SystemTools.hxx>
#include <mitkIOUtil.h>
#include <mitkLocaleSwitch.h>
/**
* Convert files from one ending to the other
*/
int main(int argc, char* argv[])
{
mitkCommandLineParser parser;
parser.setArgumentPrefix("--", "-");
parser.addArgument("", "i", mitkCommandLineParser::String, "Input image", "input raw dwi", us::Any(), false, false, false, mitkCommandLineParser::Input);
parser.addArgument("", "o", mitkCommandLineParser::String, "Output image", "output image", us::Any(), false, false, false, mitkCommandLineParser::Output);
parser.addArgument("b0_threshold", "", mitkCommandLineParser::Int, "b0 threshold", "baseline image intensity threshold", 0);
parser.addArgument("correct_negative_eigenv", "", mitkCommandLineParser::Bool, "Correct negative eigenvalues", "correct negative eigenvalues", us::Any(false));
parser.setCategory("Signal Modelling");
parser.setTitle("Tensor Reconstruction");
parser.setDescription("");
parser.setContributor("MIC");
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
std::string inFileName = us::any_cast<std::string>(parsedArgs["i"]);
std::string outfilename = us::any_cast<std::string>(parsedArgs["o"]);
if (!itksys::SystemTools::GetFilenamePath(outfilename).empty())
outfilename = itksys::SystemTools::GetFilenamePath(outfilename)+"/"+itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
else
outfilename = itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
outfilename += ".dti";
int threshold = 0;
if (parsedArgs.count("b0Threshold"))
threshold = us::any_cast<int>(parsedArgs["b0Threshold"]);
bool correct_negative_eigenv = false;
if (parsedArgs.count("correct_negative_eigenv"))
correct_negative_eigenv = us::any_cast<bool>(parsedArgs["correct_negative_eigenv"]);
try
{
mitk::Image::Pointer dwi = mitk::IOUtil::Load<mitk::Image>(inFileName);
mitk::DiffusionPropertyHelper::ImageType::Pointer itkVectorImagePointer = mitk::DiffusionPropertyHelper::ImageType::New();
mitk::CastToItkImage(dwi, itkVectorImagePointer);
if (correct_negative_eigenv)
{
typedef itk::TensorReconstructionWithEigenvalueCorrectionFilter< short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(dwi));
filter->SetGradientImage( mitk::DiffusionPropertyHelper::GetGradientContainer(dwi), itkVectorImagePointer);
filter->SetB0Threshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
mitk::LocaleSwitch localeSwitch("C");
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
else {
typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetGradientImage( mitk::DiffusionPropertyHelper::GetGradientContainer(dwi), itkVectorImagePointer );
filter->SetBValue( mitk::DiffusionPropertyHelper::GetReferenceBValue( dwi ));
filter->SetThreshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
mitk::LocaleSwitch localeSwitch("C");
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
}
catch ( itk::ExceptionObject &err)
{
std::cout << "Exception: " << err;
}
catch ( std::exception err)
{
std::cout << "Exception: " << err.what();
}
catch ( ... )
{
std::cout << "Exception!";
}
return EXIT_SUCCESS;
}
<commit_msg>Fix argument name<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkImage.h"
#include <mitkImageCast.h>
#include "mitkBaseData.h"
#include <mitkDiffusionPropertyHelper.h>
#include <itkTensorReconstructionWithEigenvalueCorrectionFilter.h>
#include <itkDiffusionTensor3DReconstructionImageFilter.h>
#include <itkDiffusionTensor3D.h>
#include <itkImageFileWriter.h>
#include <itkNrrdImageIO.h>
#include "mitkCommandLineParser.h"
#include <itksys/SystemTools.hxx>
#include <mitkIOUtil.h>
#include <mitkLocaleSwitch.h>
/**
* Convert files from one ending to the other
*/
int main(int argc, char* argv[])
{
mitkCommandLineParser parser;
parser.setArgumentPrefix("--", "-");
parser.addArgument("", "i", mitkCommandLineParser::String, "Input image", "input raw dwi", us::Any(), false, false, false, mitkCommandLineParser::Input);
parser.addArgument("", "o", mitkCommandLineParser::String, "Output image", "output image", us::Any(), false, false, false, mitkCommandLineParser::Output);
parser.addArgument("b0_threshold", "", mitkCommandLineParser::Int, "b0 threshold", "baseline image intensity threshold", 0);
parser.addArgument("correct_negative_eigenv", "", mitkCommandLineParser::Bool, "Correct negative eigenvalues", "correct negative eigenvalues", us::Any(false));
parser.setCategory("Signal Modelling");
parser.setTitle("Tensor Reconstruction");
parser.setDescription("");
parser.setContributor("MIC");
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
return EXIT_FAILURE;
std::string inFileName = us::any_cast<std::string>(parsedArgs["i"]);
std::string outfilename = us::any_cast<std::string>(parsedArgs["o"]);
if (!itksys::SystemTools::GetFilenamePath(outfilename).empty())
outfilename = itksys::SystemTools::GetFilenamePath(outfilename)+"/"+itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
else
outfilename = itksys::SystemTools::GetFilenameWithoutExtension(outfilename);
outfilename += ".dti";
int threshold = 0;
if (parsedArgs.count("b0_threshold"))
threshold = us::any_cast<int>(parsedArgs["b0_threshold"]);
bool correct_negative_eigenv = false;
if (parsedArgs.count("correct_negative_eigenv"))
correct_negative_eigenv = us::any_cast<bool>(parsedArgs["correct_negative_eigenv"]);
try
{
mitk::Image::Pointer dwi = mitk::IOUtil::Load<mitk::Image>(inFileName);
mitk::DiffusionPropertyHelper::ImageType::Pointer itkVectorImagePointer = mitk::DiffusionPropertyHelper::ImageType::New();
mitk::CastToItkImage(dwi, itkVectorImagePointer);
if (correct_negative_eigenv)
{
typedef itk::TensorReconstructionWithEigenvalueCorrectionFilter< short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetBValue(mitk::DiffusionPropertyHelper::GetReferenceBValue(dwi));
filter->SetGradientImage( mitk::DiffusionPropertyHelper::GetGradientContainer(dwi), itkVectorImagePointer);
filter->SetB0Threshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
mitk::LocaleSwitch localeSwitch("C");
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
else {
typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType;
TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New();
filter->SetGradientImage( mitk::DiffusionPropertyHelper::GetGradientContainer(dwi), itkVectorImagePointer );
filter->SetBValue( mitk::DiffusionPropertyHelper::GetReferenceBValue( dwi ));
filter->SetThreshold(threshold);
filter->Update();
// Save tensor image
itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();
io->SetFileType( itk::ImageIOBase::Binary );
io->UseCompressionOn();
mitk::LocaleSwitch localeSwitch("C");
itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::Pointer writer = itk::ImageFileWriter< itk::Image< itk::DiffusionTensor3D< float >, 3 > >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName(outfilename);
writer->SetImageIO(io);
writer->UseCompressionOn();
writer->Update();
}
}
catch ( itk::ExceptionObject &err)
{
std::cout << "Exception: " << err;
}
catch ( std::exception err)
{
std::cout << "Exception: " << err.what();
}
catch ( ... )
{
std::cout << "Exception!";
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// @(#)root/textinput:$Id$
// Author: Axel Naumann <axel@cern.ch>, 2011-05-21
/*************************************************************************
* Copyright (C) 1995-2011, 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 "Getline.h"
#include <algorithm>
#include <string>
#include <sstream>
#include "textinput/TextInput.h"
#include "textinput/TextInputContext.h"
#include "textinput/History.h"
#include "textinput/TerminalDisplay.h"
#include "textinput/StreamReader.h"
#include "textinput/Callbacks.h"
#include "Getline_color.h"
#include "TApplication.h"
extern "C" {
int (* Gl_in_key)(int ch) = 0;
int (* Gl_beep_hook)() = 0;
}
using namespace textinput;
namespace {
// TTabCom adapter.
class ROOTTabCompletion: public TabCompletion {
private:
ROOTTabCompletion(const ROOTTabCompletion&); // not implemented
ROOTTabCompletion& operator=(const ROOTTabCompletion&); // not implemented
public:
ROOTTabCompletion(): fLineBuf(new char[fgLineBufSize]) {}
virtual ~ROOTTabCompletion() { delete []fLineBuf; }
// Returns false on error
bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/,
EditorRange& r /*out*/,
std::vector<std::string>& displayCompletions /*out*/) {
strlcpy(fLineBuf, line.GetText().c_str(), fgLineBufSize);
int cursorInt = (int) cursor;
std::stringstream sstr;
size_t posFirstChange = gApplication->TabCompletionHook(fLineBuf, &cursorInt, sstr);
if (posFirstChange == (size_t) -1) {
// no change
return true;
}
line = std::string(fLineBuf);
std::string compLine;
while (std::getline(sstr, compLine)) {
displayCompletions.push_back(compLine);
}
std::sort(displayCompletions.begin(), displayCompletions.end());
size_t lenLineBuf = strlen(fLineBuf);
if (posFirstChange == (size_t) -2) {
// redraw whole line, incl prompt
r.fEdit.Extend(Range::AllWithPrompt());
r.fDisplay.Extend(Range::AllWithPrompt());
} else {
if (!lenLineBuf) {
r.fEdit.Extend(Range::AllText());
r.fDisplay.Extend(Range::AllText());
} else {
r.fEdit.Extend(Range(posFirstChange, Range::End()));
r.fDisplay.Extend(Range(posFirstChange, Range::End()));
}
}
cursor = (size_t)cursorInt;
line.GetColors().resize(lenLineBuf);
return true;
}
private:
static const size_t fgLineBufSize;
char* fLineBuf;
};
const size_t ROOTTabCompletion::fgLineBufSize = 16*1024;
// Helper to define the lifetime of the TextInput singleton.
class TextInputHolder {
public:
TextInputHolder():
fTextInput(*(fReader = StreamReader::Create()),
*(fDisplay = TerminalDisplay::Create()),
fgHistoryFile.c_str()) {
fTextInput.SetColorizer(&fCol);
fTextInput.SetCompletion(&fTabComp);
fTextInput.EnableAutoHistAdd(false);
History* Hist = fTextInput.GetContext()->GetHistory();
Hist->SetMaxDepth(fgSizeLines);
Hist->SetPruneLength(fgSaveLines);
}
~TextInputHolder() {
// Delete allocated objects.
delete fReader;
delete fDisplay;
}
const char* TakeInput(bool force = false) {
fTextInput.TakeInput(fInputLine, force);
fInputLine += "\n"; // ROOT wants a trailing newline.
return fInputLine.c_str();
}
void SetColors(const char* colorTab, const char* colorTabComp,
const char* colorBracket, const char* colorBadBracket,
const char* colorPrompt) {
fCol.SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket,
colorPrompt);
}
static void SetHistoryFile(const char* hist) {
fgHistoryFile = hist;
}
static void SetHistSize(int size, int save) {
fgSizeLines = size;
fgSaveLines = save;
}
static TextInputHolder& getHolder() {
// Controls initialization of static TextInput.
static TextInputHolder sTIHolder;
return sTIHolder;
}
static TextInput& get() {
return getHolder().fTextInput;
}
private:
TextInput fTextInput; // The singleton TextInput object.
Display* fDisplay; // Default TerminalDisplay
Reader* fReader; // Default StreamReader
std::string fInputLine; // Taken from TextInput
ROOT::TextInputColorizer fCol; // Colorizer
ROOTTabCompletion fTabComp; // Tab completion handler / TTabCom adapter
// Config values:
static std::string fgHistoryFile;
// # History file size, once HistSize is reached remove all but HistSave entries,
// # set to 0 to turn off command recording.
// # Can be overridden by environment variable ROOT_HIST=size[:save],
// # the ":save" part is optional.
// # Rint.HistSize: 500
// # Set to -1 for sensible default (80% of HistSize), set to 0 to disable history.
// # Rint.HistSave: 400
static int fgSizeLines;
static int fgSaveLines;
};
int TextInputHolder::fgSizeLines = 500;
int TextInputHolder::fgSaveLines = -1;
std::string TextInputHolder::fgHistoryFile;
}
/************************ extern "C" part *********************************/
extern "C" {
void
Gl_config(const char* which, int value) {
if (strcmp(which, "noecho") == 0) {
TextInputHolder::get().MaskInput(value);
} else {
// unsupported directive
printf("Gl_config unsupported: %s ?\n", which);
}
}
void
Gl_histadd(const char* buf) {
TextInputHolder::get().AddHistoryLine(buf);
}
/* Wrapper around textinput.
* Modes: -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup, 3 = clear input line
*/
const char*
Getlinem(EGetLineMode mode, const char* prompt) {
if (mode == kClear) {
TextInputHolder::getHolder().TakeInput(true);
return 0;
}
if (mode == kCleanUp) {
TextInputHolder::get().ReleaseInputOutput();
return 0;
}
if (mode == kOneChar) {
// Check first display: if !TTY, read full line.
const textinput::Display* disp
= TextInputHolder::get().GetContext()->GetDisplays()[0];
const textinput::TerminalDisplay* tdisp = 0;
if (disp) tdisp = dynamic_cast<const textinput::TerminalDisplay*>(disp);
if (tdisp && !tdisp->IsTTY()) {
mode = kLine1;
}
}
if (mode == kInit || mode == kLine1) {
if (prompt) {
TextInputHolder::get().SetPrompt(prompt);
}
// Trigger attach:
TextInputHolder::get().Redraw();
if (mode == kInit) {
return 0;
}
TextInputHolder::get().SetBlockingUntilEOL();
} else {
// mode == kOneChar
if (Gl_in_key) {
// We really need to go key by key:
TextInputHolder::get().SetMaxPendingCharsToRead(1);
} else {
// Can consume all pending characters
TextInputHolder::get().SetReadingAllPendingChars();
}
}
TextInput::EReadResult res = TextInputHolder::get().ReadInput();
if (Gl_in_key) {
(*Gl_in_key)(TextInputHolder::get().GetLastKey());
}
if (res == TextInput::kRRReadEOLDelimiter) {
return TextInputHolder::getHolder().TakeInput();
} else if (res == TextInput::kRREOF) {
// ROOT expects "" and then Gl_eol() returning true
return "";
}
return NULL;
}
const char*
Getline(const char* prompt) {
// Get a line of user input, showing prompt.
// Does not return after every character entered, but
// only returns once the user has hit return.
// For ROOT Getline.c backward compatibility reasons,
// the returned value is volatile and will be overwritten
// by the subsequent call to Getline() or Getlinem(),
// so copy the string if it needs to stay around.
// The returned value must not be deleted.
// The returned string contains a trailing newline '\n'.
return Getlinem(kLine1, prompt);
}
/******************* Simple C -> C++ forwards *********************************/
void
Gl_histsize(int size, int save) {
TextInputHolder::SetHistSize(size, save);
}
void
Gl_histinit(const char* file) {
// Has to be called before constructing TextInputHolder singleton.
TextInputHolder::SetHistoryFile(file);
}
int
Gl_eof() {
return TextInputHolder::get().GetReadState() == TextInput::kRREOF;
}
void
Gl_setColors(const char* colorTab, const char* colorTabComp, const char* colorBracket,
const char* colorBadBracket, const char* colorPrompt) {
// call to enhance.cxx to set colours
TextInputHolder::getHolder().SetColors(colorTab, colorTabComp, colorBracket,
colorBadBracket, colorPrompt);
}
/******************** Superseded interface *********************************/
void Gl_setwidth(int /*w*/) {
// ignored, handled by displays themselves.
}
void Gl_windowchanged() {
// ignored, handled by displays themselves.
}
} // extern "C"
<commit_msg>Make =delete intention clear by using =delete.<commit_after>// @(#)root/textinput:$Id$
// Author: Axel Naumann <axel@cern.ch>, 2011-05-21
/*************************************************************************
* Copyright (C) 1995-2011, 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 "Getline.h"
#include <algorithm>
#include <string>
#include <sstream>
#include "textinput/TextInput.h"
#include "textinput/TextInputContext.h"
#include "textinput/History.h"
#include "textinput/TerminalDisplay.h"
#include "textinput/StreamReader.h"
#include "textinput/Callbacks.h"
#include "Getline_color.h"
#include "TApplication.h"
extern "C" {
int (* Gl_in_key)(int ch) = 0;
int (* Gl_beep_hook)() = 0;
}
using namespace textinput;
namespace {
// TTabCom adapter.
class ROOTTabCompletion: public TabCompletion {
public:
ROOTTabCompletion(): fLineBuf(new char[fgLineBufSize]) {}
virtual ~ROOTTabCompletion() { delete []fLineBuf; }
ROOTTabCompletion(const ROOTTabCompletion&) = delete;
ROOTTabCompletion& operator=(const ROOTTabCompletion&) = delete;
// Returns false on error
bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/,
EditorRange& r /*out*/,
std::vector<std::string>& displayCompletions /*out*/) {
strlcpy(fLineBuf, line.GetText().c_str(), fgLineBufSize);
int cursorInt = (int) cursor;
std::stringstream sstr;
size_t posFirstChange = gApplication->TabCompletionHook(fLineBuf, &cursorInt, sstr);
if (posFirstChange == (size_t) -1) {
// no change
return true;
}
line = std::string(fLineBuf);
std::string compLine;
while (std::getline(sstr, compLine)) {
displayCompletions.push_back(compLine);
}
std::sort(displayCompletions.begin(), displayCompletions.end());
size_t lenLineBuf = strlen(fLineBuf);
if (posFirstChange == (size_t) -2) {
// redraw whole line, incl prompt
r.fEdit.Extend(Range::AllWithPrompt());
r.fDisplay.Extend(Range::AllWithPrompt());
} else {
if (!lenLineBuf) {
r.fEdit.Extend(Range::AllText());
r.fDisplay.Extend(Range::AllText());
} else {
r.fEdit.Extend(Range(posFirstChange, Range::End()));
r.fDisplay.Extend(Range(posFirstChange, Range::End()));
}
}
cursor = (size_t)cursorInt;
line.GetColors().resize(lenLineBuf);
return true;
}
private:
static const size_t fgLineBufSize;
char* fLineBuf;
};
const size_t ROOTTabCompletion::fgLineBufSize = 16*1024;
// Helper to define the lifetime of the TextInput singleton.
class TextInputHolder {
public:
TextInputHolder():
fTextInput(*(fReader = StreamReader::Create()),
*(fDisplay = TerminalDisplay::Create()),
fgHistoryFile.c_str()) {
fTextInput.SetColorizer(&fCol);
fTextInput.SetCompletion(&fTabComp);
fTextInput.EnableAutoHistAdd(false);
History* Hist = fTextInput.GetContext()->GetHistory();
Hist->SetMaxDepth(fgSizeLines);
Hist->SetPruneLength(fgSaveLines);
}
~TextInputHolder() {
// Delete allocated objects.
delete fReader;
delete fDisplay;
}
const char* TakeInput(bool force = false) {
fTextInput.TakeInput(fInputLine, force);
fInputLine += "\n"; // ROOT wants a trailing newline.
return fInputLine.c_str();
}
void SetColors(const char* colorTab, const char* colorTabComp,
const char* colorBracket, const char* colorBadBracket,
const char* colorPrompt) {
fCol.SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket,
colorPrompt);
}
static void SetHistoryFile(const char* hist) {
fgHistoryFile = hist;
}
static void SetHistSize(int size, int save) {
fgSizeLines = size;
fgSaveLines = save;
}
static TextInputHolder& getHolder() {
// Controls initialization of static TextInput.
static TextInputHolder sTIHolder;
return sTIHolder;
}
static TextInput& get() {
return getHolder().fTextInput;
}
private:
TextInput fTextInput; // The singleton TextInput object.
Display* fDisplay; // Default TerminalDisplay
Reader* fReader; // Default StreamReader
std::string fInputLine; // Taken from TextInput
ROOT::TextInputColorizer fCol; // Colorizer
ROOTTabCompletion fTabComp; // Tab completion handler / TTabCom adapter
// Config values:
static std::string fgHistoryFile;
// # History file size, once HistSize is reached remove all but HistSave entries,
// # set to 0 to turn off command recording.
// # Can be overridden by environment variable ROOT_HIST=size[:save],
// # the ":save" part is optional.
// # Rint.HistSize: 500
// # Set to -1 for sensible default (80% of HistSize), set to 0 to disable history.
// # Rint.HistSave: 400
static int fgSizeLines;
static int fgSaveLines;
};
int TextInputHolder::fgSizeLines = 500;
int TextInputHolder::fgSaveLines = -1;
std::string TextInputHolder::fgHistoryFile;
}
/************************ extern "C" part *********************************/
extern "C" {
void
Gl_config(const char* which, int value) {
if (strcmp(which, "noecho") == 0) {
TextInputHolder::get().MaskInput(value);
} else {
// unsupported directive
printf("Gl_config unsupported: %s ?\n", which);
}
}
void
Gl_histadd(const char* buf) {
TextInputHolder::get().AddHistoryLine(buf);
}
/* Wrapper around textinput.
* Modes: -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup, 3 = clear input line
*/
const char*
Getlinem(EGetLineMode mode, const char* prompt) {
if (mode == kClear) {
TextInputHolder::getHolder().TakeInput(true);
return 0;
}
if (mode == kCleanUp) {
TextInputHolder::get().ReleaseInputOutput();
return 0;
}
if (mode == kOneChar) {
// Check first display: if !TTY, read full line.
const textinput::Display* disp
= TextInputHolder::get().GetContext()->GetDisplays()[0];
const textinput::TerminalDisplay* tdisp = 0;
if (disp) tdisp = dynamic_cast<const textinput::TerminalDisplay*>(disp);
if (tdisp && !tdisp->IsTTY()) {
mode = kLine1;
}
}
if (mode == kInit || mode == kLine1) {
if (prompt) {
TextInputHolder::get().SetPrompt(prompt);
}
// Trigger attach:
TextInputHolder::get().Redraw();
if (mode == kInit) {
return 0;
}
TextInputHolder::get().SetBlockingUntilEOL();
} else {
// mode == kOneChar
if (Gl_in_key) {
// We really need to go key by key:
TextInputHolder::get().SetMaxPendingCharsToRead(1);
} else {
// Can consume all pending characters
TextInputHolder::get().SetReadingAllPendingChars();
}
}
TextInput::EReadResult res = TextInputHolder::get().ReadInput();
if (Gl_in_key) {
(*Gl_in_key)(TextInputHolder::get().GetLastKey());
}
if (res == TextInput::kRRReadEOLDelimiter) {
return TextInputHolder::getHolder().TakeInput();
} else if (res == TextInput::kRREOF) {
// ROOT expects "" and then Gl_eol() returning true
return "";
}
return NULL;
}
const char*
Getline(const char* prompt) {
// Get a line of user input, showing prompt.
// Does not return after every character entered, but
// only returns once the user has hit return.
// For ROOT Getline.c backward compatibility reasons,
// the returned value is volatile and will be overwritten
// by the subsequent call to Getline() or Getlinem(),
// so copy the string if it needs to stay around.
// The returned value must not be deleted.
// The returned string contains a trailing newline '\n'.
return Getlinem(kLine1, prompt);
}
/******************* Simple C -> C++ forwards *********************************/
void
Gl_histsize(int size, int save) {
TextInputHolder::SetHistSize(size, save);
}
void
Gl_histinit(const char* file) {
// Has to be called before constructing TextInputHolder singleton.
TextInputHolder::SetHistoryFile(file);
}
int
Gl_eof() {
return TextInputHolder::get().GetReadState() == TextInput::kRREOF;
}
void
Gl_setColors(const char* colorTab, const char* colorTabComp, const char* colorBracket,
const char* colorBadBracket, const char* colorPrompt) {
// call to enhance.cxx to set colours
TextInputHolder::getHolder().SetColors(colorTab, colorTabComp, colorBracket,
colorBadBracket, colorPrompt);
}
/******************** Superseded interface *********************************/
void Gl_setwidth(int /*w*/) {
// ignored, handled by displays themselves.
}
void Gl_windowchanged() {
// ignored, handled by displays themselves.
}
} // extern "C"
<|endoftext|> |
<commit_before>#include "mdns.hpp"
#include <net/if.h> // if_nametoindex()
#include <v8.h>
#include "mdns_utils.hpp"
#include "dns_service_ref.hpp"
#include "txt_record_ref.hpp"
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
# include "socket_watcher.hpp"
#endif
using namespace v8;
using namespace node;
namespace node_mdns {
// === dns_sd ===========================================
Handle<Value> DNSServiceRegister(Arguments const& args);
Handle<Value> DNSServiceRefSockFD(Arguments const& args);
Handle<Value> DNSServiceProcessResult(Arguments const& args);
Handle<Value> DNSServiceBrowse(Arguments const& args);
Handle<Value> DNSServiceRefDeallocate(Arguments const& args);
Handle<Value> DNSServiceResolve(Arguments const& args);
Handle<Value> DNSServiceEnumerateDomains(Arguments const& args);
#ifdef HAVE_DNSSERVICEGETADDRINFO
Handle<Value> DNSServiceGetAddrInfo(Arguments const& args);
#endif
Handle<Value> TXTRecordCreate(Arguments const& args);
Handle<Value> TXTRecordDeallocate(Arguments const& args);
//Handle<Value> TXTRecordGetCount(Arguments const& args);
Handle<Value> TXTRecordSetValue(Arguments const& args);
Handle<Value> TXTRecordGetLength(Arguments const& args);
// === posix ============================================
Handle<Value> if_nametoindex(Arguments const& args);
// === additions ========================================
Handle<Value> txtRecordBufferToObject(Arguments const& args);
Handle<Value> exportConstants(Arguments const& args);
Handle<Value> buildException(Arguments const& args);
// === locals ===========================================
void defineFunction(Handle<Object> target, const char * name, InvocationCallback f);
void addConstants(Handle<Object> target);
void
init(Handle<Object> target) {
HandleScope scope;
ServiceRef::Initialize( target );
TxtRecordRef::Initialize( target );
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
SocketWatcher::Initialize( target );
#endif
defineFunction(target, "DNSServiceRegister", DNSServiceRegister);
defineFunction(target, "DNSServiceRefSockFD", DNSServiceRefSockFD);
defineFunction(target, "DNSServiceProcessResult", DNSServiceProcessResult);
defineFunction(target, "DNSServiceBrowse", DNSServiceBrowse);
defineFunction(target, "DNSServiceRefDeallocate", DNSServiceRefDeallocate);
defineFunction(target, "DNSServiceResolve", DNSServiceResolve);
defineFunction(target, "DNSServiceEnumerateDomains", DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
defineFunction(target, "DNSServiceGetAddrInfo", DNSServiceGetAddrInfo);
#endif
defineFunction(target, "TXTRecordCreate", TXTRecordCreate);
defineFunction(target, "TXTRecordDeallocate", TXTRecordDeallocate);
//defineFunction(target, "TXTRecordGetCount", TXTRecordGetCount);
defineFunction(target, "TXTRecordSetValue", TXTRecordSetValue);
defineFunction(target, "TXTRecordGetLength", TXTRecordGetLength);
defineFunction(target, "if_nametoindex", if_nametoindex);
defineFunction(target, "txtRecordBufferToObject", txtRecordBufferToObject);
defineFunction(target, "buildException", buildException);
defineFunction(target, "exportConstants", exportConstants);
addConstants(target);
}
inline
void
defineFunction(Handle<Object> target, const char * name, InvocationCallback f) {
target->Set(String::NewSymbol(name),
FunctionTemplate::New(f)->GetFunction());
}
Handle<Value>
if_nametoindex(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsString()) {
return throwTypeError("argument 1 must be a string (interface name)");
}
String::Utf8Value interfaceName(args[0]->ToString());
unsigned int index = ::if_nametoindex(*interfaceName);
if (index == 0) {
return throwError((std::string("interface '") + *interfaceName + "' does not exist").c_str());
}
return scope.Close( Integer::New(index));
}
Handle<Value>
buildException(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsInt32()) {
return throwTypeError("argument 1 must be an integer (DNSServiceErrorType)");
}
DNSServiceErrorType error = args[0]->Int32Value();
return scope.Close(buildException(error));
}
void
addConstants(Handle<Object> target) {
// DNS Classes
NODE_DEFINE_CONSTANT(target, kDNSServiceClass_IN);
// DNS Error Codes
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoError);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unknown);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchName);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoMemory);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadParam);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadReference);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadState);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadFlags);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unsupported);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NotInitialized);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_AlreadyRegistered);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NameConflict);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Invalid);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Firewall);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Incompatible);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadInterfaceIndex);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Refused);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchRecord);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoAuth);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchKey);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATTraversal);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_DoubleNAT);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadTime);
#ifdef kDNSServiceErr_BadSig
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadSig);
#endif
#ifdef kDNSServiceErr_BadKey
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadKey);
#endif
#ifdef kDNSServiceErr_Transient
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Transient);
#endif
#ifdef kDNSServiceErr_ServiceNotRunning
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_ServiceNotRunning);
#endif
#ifdef kDNSServiceErr_NATPortMappingUnsupported
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingUnsupported);
#endif
#ifdef kDNSServiceErr_NATPortMappingDisabled
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingDisabled);
#endif
#ifdef kDNSServiceErr_NoRouter
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoRouter);
#endif
#ifdef kDNSServiceErr_PollingMode
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_PollingMode);
#endif
// DNS Service Types
NODE_DEFINE_CONSTANT(target, kDNSServiceType_A);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MD);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MF);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_CNAME);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SOA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NULL);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_WKS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_PTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_HINFO);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MINFO);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TXT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RP);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AFSDB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_X25);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ISDN);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP_PTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SIG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_KEY);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_PX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_GPOS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AAAA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_LOC);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NXT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_EID);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NIMLOC);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SRV);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ATMA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NAPTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_KX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_CERT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_A6);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNAME);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SINK);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_OPT);
#ifdef kDNSServiceType_APL
NODE_DEFINE_CONSTANT(target, kDNSServiceType_APL);
#endif
#ifdef kDNSServiceType_DS
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DS);
#endif
#ifdef kDNSServiceType_SSHFP
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SSHFP);
#endif
#ifdef kDNSServiceType_IPSECKEY
NODE_DEFINE_CONSTANT(target, kDNSServiceType_IPSECKEY);
#endif
#ifdef kDNSServiceType_RRSIG
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RRSIG);
#endif
#ifdef kDNSServiceType_NSEC
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC);
#endif
#ifdef kDNSServiceType_DNSKEY
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNSKEY);
#endif
#ifdef kDNSServiceType_DHCID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DHCID);
#endif
#ifdef kDNSServiceType_NSEC3
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3);
#endif
#ifdef kDNSServiceType_NSEC3PARAM
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3PARAM);
#endif
#ifdef kDNSServiceType_HIP
NODE_DEFINE_CONSTANT(target, kDNSServiceType_HIP);
#endif
#ifdef kDNSServiceType_SPF
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SPF);
#endif
#ifdef kDNSServiceType_UINFO
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UINFO);
#endif
#ifdef kDNSServiceType_UID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UID);
#endif
#ifdef kDNSServiceType_GID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_GID);
#endif
#ifdef kDNSServiceType_UNSPEC
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UNSPEC);
#endif
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TKEY);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TSIG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_IXFR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AXFR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ANY);
// General Flags
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsMoreComing);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAdd);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsDefault);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNoAutoRename);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShared);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsUnique);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsBrowseDomains);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsRegistrationDomains);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsLongLivedQuery);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAllowRemoteQuery);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForceMulticast);
#ifdef kDNSServiceFlagsForce
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForce);
#endif
#ifdef kDNSServiceFlagsReturnIntermediates
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsReturnIntermediates);
#endif
#ifdef kDNSServiceFlagsNonBrowsable
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNonBrowsable);
#endif
#ifdef kDNSServiceFlagsShareConnection
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShareConnection);
#endif
#ifdef kDNSServiceFlagsSuppressUnusable
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsSuppressUnusable);
#endif
}
Handle<Value>
exportConstants(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsObject()) {
return throwTypeError("argument 1 must be an object.");
}
addConstants(args[0]->ToObject());
return Undefined();
}
} // end of namespace node_mdns
NODE_MODULE(dns_sd_bindings,node_mdns::init);
<commit_msg>[iface] fixed build with historic node versions<commit_after>#include "mdns.hpp"
#ifndef WIN32
# include <sys/types.h>
# include <sys/socket.h>
# include <net/if.h> // if_nametoindex()
#endif
#include <v8.h>
#include "mdns_utils.hpp"
#include "dns_service_ref.hpp"
#include "txt_record_ref.hpp"
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
# include "socket_watcher.hpp"
#endif
using namespace v8;
using namespace node;
namespace node_mdns {
// === dns_sd ===========================================
Handle<Value> DNSServiceRegister(Arguments const& args);
Handle<Value> DNSServiceRefSockFD(Arguments const& args);
Handle<Value> DNSServiceProcessResult(Arguments const& args);
Handle<Value> DNSServiceBrowse(Arguments const& args);
Handle<Value> DNSServiceRefDeallocate(Arguments const& args);
Handle<Value> DNSServiceResolve(Arguments const& args);
Handle<Value> DNSServiceEnumerateDomains(Arguments const& args);
#ifdef HAVE_DNSSERVICEGETADDRINFO
Handle<Value> DNSServiceGetAddrInfo(Arguments const& args);
#endif
Handle<Value> TXTRecordCreate(Arguments const& args);
Handle<Value> TXTRecordDeallocate(Arguments const& args);
//Handle<Value> TXTRecordGetCount(Arguments const& args);
Handle<Value> TXTRecordSetValue(Arguments const& args);
Handle<Value> TXTRecordGetLength(Arguments const& args);
// === posix ============================================
Handle<Value> if_nametoindex(Arguments const& args);
// === additions ========================================
Handle<Value> txtRecordBufferToObject(Arguments const& args);
Handle<Value> exportConstants(Arguments const& args);
Handle<Value> buildException(Arguments const& args);
// === locals ===========================================
void defineFunction(Handle<Object> target, const char * name, InvocationCallback f);
void addConstants(Handle<Object> target);
void
init(Handle<Object> target) {
HandleScope scope;
ServiceRef::Initialize( target );
TxtRecordRef::Initialize( target );
#ifdef NODE_MDNS_USE_SOCKET_WATCHER
SocketWatcher::Initialize( target );
#endif
defineFunction(target, "DNSServiceRegister", DNSServiceRegister);
defineFunction(target, "DNSServiceRefSockFD", DNSServiceRefSockFD);
defineFunction(target, "DNSServiceProcessResult", DNSServiceProcessResult);
defineFunction(target, "DNSServiceBrowse", DNSServiceBrowse);
defineFunction(target, "DNSServiceRefDeallocate", DNSServiceRefDeallocate);
defineFunction(target, "DNSServiceResolve", DNSServiceResolve);
defineFunction(target, "DNSServiceEnumerateDomains", DNSServiceEnumerateDomains);
#ifdef HAVE_DNSSERVICEGETADDRINFO
defineFunction(target, "DNSServiceGetAddrInfo", DNSServiceGetAddrInfo);
#endif
defineFunction(target, "TXTRecordCreate", TXTRecordCreate);
defineFunction(target, "TXTRecordDeallocate", TXTRecordDeallocate);
//defineFunction(target, "TXTRecordGetCount", TXTRecordGetCount);
defineFunction(target, "TXTRecordSetValue", TXTRecordSetValue);
defineFunction(target, "TXTRecordGetLength", TXTRecordGetLength);
defineFunction(target, "if_nametoindex", if_nametoindex);
defineFunction(target, "txtRecordBufferToObject", txtRecordBufferToObject);
defineFunction(target, "buildException", buildException);
defineFunction(target, "exportConstants", exportConstants);
addConstants(target);
}
inline
void
defineFunction(Handle<Object> target, const char * name, InvocationCallback f) {
target->Set(String::NewSymbol(name),
FunctionTemplate::New(f)->GetFunction());
}
Handle<Value>
if_nametoindex(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsString()) {
return throwTypeError("argument 1 must be a string (interface name)");
}
String::Utf8Value interfaceName(args[0]->ToString());
unsigned int index = ::if_nametoindex(*interfaceName);
if (index == 0) {
return throwError((std::string("interface '") + *interfaceName + "' does not exist").c_str());
}
return scope.Close( Integer::New(index));
}
Handle<Value>
buildException(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsInt32()) {
return throwTypeError("argument 1 must be an integer (DNSServiceErrorType)");
}
DNSServiceErrorType error = args[0]->Int32Value();
return scope.Close(buildException(error));
}
void
addConstants(Handle<Object> target) {
// DNS Classes
NODE_DEFINE_CONSTANT(target, kDNSServiceClass_IN);
// DNS Error Codes
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoError);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unknown);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchName);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoMemory);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadParam);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadReference);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadState);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadFlags);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Unsupported);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NotInitialized);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_AlreadyRegistered);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NameConflict);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Invalid);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Firewall);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Incompatible);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadInterfaceIndex);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Refused);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchRecord);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoAuth);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoSuchKey);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATTraversal);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_DoubleNAT);
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadTime);
#ifdef kDNSServiceErr_BadSig
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadSig);
#endif
#ifdef kDNSServiceErr_BadKey
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_BadKey);
#endif
#ifdef kDNSServiceErr_Transient
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_Transient);
#endif
#ifdef kDNSServiceErr_ServiceNotRunning
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_ServiceNotRunning);
#endif
#ifdef kDNSServiceErr_NATPortMappingUnsupported
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingUnsupported);
#endif
#ifdef kDNSServiceErr_NATPortMappingDisabled
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NATPortMappingDisabled);
#endif
#ifdef kDNSServiceErr_NoRouter
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_NoRouter);
#endif
#ifdef kDNSServiceErr_PollingMode
NODE_DEFINE_CONSTANT(target, kDNSServiceErr_PollingMode);
#endif
// DNS Service Types
NODE_DEFINE_CONSTANT(target, kDNSServiceType_A);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MD);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MF);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_CNAME);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SOA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NULL);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_WKS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_PTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_HINFO);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MINFO);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TXT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RP);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AFSDB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_X25);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ISDN);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSAP_PTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SIG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_KEY);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_PX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_GPOS);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AAAA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_LOC);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NXT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_EID);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NIMLOC);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SRV);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ATMA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NAPTR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_KX);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_CERT);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_A6);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNAME);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SINK);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_OPT);
#ifdef kDNSServiceType_APL
NODE_DEFINE_CONSTANT(target, kDNSServiceType_APL);
#endif
#ifdef kDNSServiceType_DS
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DS);
#endif
#ifdef kDNSServiceType_SSHFP
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SSHFP);
#endif
#ifdef kDNSServiceType_IPSECKEY
NODE_DEFINE_CONSTANT(target, kDNSServiceType_IPSECKEY);
#endif
#ifdef kDNSServiceType_RRSIG
NODE_DEFINE_CONSTANT(target, kDNSServiceType_RRSIG);
#endif
#ifdef kDNSServiceType_NSEC
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC);
#endif
#ifdef kDNSServiceType_DNSKEY
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DNSKEY);
#endif
#ifdef kDNSServiceType_DHCID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_DHCID);
#endif
#ifdef kDNSServiceType_NSEC3
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3);
#endif
#ifdef kDNSServiceType_NSEC3PARAM
NODE_DEFINE_CONSTANT(target, kDNSServiceType_NSEC3PARAM);
#endif
#ifdef kDNSServiceType_HIP
NODE_DEFINE_CONSTANT(target, kDNSServiceType_HIP);
#endif
#ifdef kDNSServiceType_SPF
NODE_DEFINE_CONSTANT(target, kDNSServiceType_SPF);
#endif
#ifdef kDNSServiceType_UINFO
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UINFO);
#endif
#ifdef kDNSServiceType_UID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UID);
#endif
#ifdef kDNSServiceType_GID
NODE_DEFINE_CONSTANT(target, kDNSServiceType_GID);
#endif
#ifdef kDNSServiceType_UNSPEC
NODE_DEFINE_CONSTANT(target, kDNSServiceType_UNSPEC);
#endif
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TKEY);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_TSIG);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_IXFR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_AXFR);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILB);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_MAILA);
NODE_DEFINE_CONSTANT(target, kDNSServiceType_ANY);
// General Flags
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsMoreComing);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAdd);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsDefault);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNoAutoRename);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShared);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsUnique);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsBrowseDomains);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsRegistrationDomains);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsLongLivedQuery);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsAllowRemoteQuery);
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForceMulticast);
#ifdef kDNSServiceFlagsForce
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsForce);
#endif
#ifdef kDNSServiceFlagsReturnIntermediates
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsReturnIntermediates);
#endif
#ifdef kDNSServiceFlagsNonBrowsable
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsNonBrowsable);
#endif
#ifdef kDNSServiceFlagsShareConnection
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsShareConnection);
#endif
#ifdef kDNSServiceFlagsSuppressUnusable
NODE_DEFINE_CONSTANT(target, kDNSServiceFlagsSuppressUnusable);
#endif
}
Handle<Value>
exportConstants(Arguments const& args) {
HandleScope scope;
if (argumentCountMismatch(args, 1)) {
return throwArgumentCountMismatchException(args, 1);
}
if ( ! args[0]->IsObject()) {
return throwTypeError("argument 1 must be an object.");
}
addConstants(args[0]->ToObject());
return Undefined();
}
} // end of namespace node_mdns
NODE_MODULE(dns_sd_bindings,node_mdns::init);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.