text stringlengths 54 60.6k |
|---|
<commit_before>#include "utp_uv.h"
#include "nan.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#if (NODE_MODULE_VERSION <= NODE_0_10_MODULE_VERSION)
#define UV_LEGACY
#endif
#define UTP_UV_TIMEOUT_INTERVAL 500
#define IP_STRING(ip) (const char *) (ip == NULL ? "127.0.0.1" : ip)
#define DEBUG(msg) fprintf(stderr, "debug utp_uv: %s\n", (const char *) msg);
static void
on_uv_close (uv_handle_t *handle) {
utp_uv_t *self = (utp_uv_t *) handle->data;
if (self->context) {
utp_destroy(self->context);
self->context = NULL;
if (self->on_close) self->on_close(self);
}
}
static void
really_destroy (utp_uv_t *self) {
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
// TODO: do these need error handling?
uv_timer_stop(timer);
uv_udp_recv_stop(handle);
uv_close((uv_handle_t *) handle, on_uv_close);
}
#ifndef UV_LEGACY
static void
on_uv_alloc (uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
utp_uv_t *self = (utp_uv_t *) handle->data;
buf->base = (char *) &(self->buffer);
buf->len = UTP_UV_BUFFER_SIZE;
}
#endif
static void
on_uv_read (uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags) {
utp_uv_t *self = (utp_uv_t *) handle->data;
int ret;
if (nread < 0) {
if (self->on_error) self->on_error(self);
return;
}
if (nread == 0) {
utp_issue_deferred_acks(self->context);
return;
}
ret = utp_process_udp(self->context, (const unsigned char *) buf->base, nread, addr, sizeof(struct sockaddr));
if (ret) return;
// not a utp message -> call on_message
if (!self->on_message) return;
struct sockaddr_in *addr_in = (struct sockaddr_in *) addr;
int port = ntohs(addr_in->sin_port);
char ip[17];
uv_ip4_name(addr_in, (char *) &ip, 17);
self->on_message(self, buf->base, (size_t) nread, port, (char *) &ip);
}
static void
on_uv_interval (uv_timer_t *req) {
utp_uv_t *self = (utp_uv_t *) req->data;
utp_check_timeouts(self->context);
}
#ifdef UV_LEGACY
static uv_buf_t
on_uv_alloc_compat (uv_handle_t* handle, size_t suggested_size) {
utp_uv_t *self = (utp_uv_t *) handle->data;
return uv_buf_init((char *) &(self->buffer), UTP_UV_BUFFER_SIZE);
}
static void
on_uv_read_compat (uv_udp_t* handle, ssize_t nread, uv_buf_t buf, struct sockaddr* addr, unsigned flags) {
on_uv_read(handle, nread, &buf, addr, flags);
}
static void
on_uv_interval_compat (uv_timer_t *req, int status) {
on_uv_interval(req);
}
#endif
static uint64
on_utp_read (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (self->on_socket_read) self->on_socket_read(self, a->socket, (char *) a->buf, a->len);
utp_read_drained(a->socket);
return 0;
}
static uint64
on_utp_state_change (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
switch (a->state) {
case UTP_STATE_CONNECT:
if (self->on_socket_connect) self->on_socket_connect(self, a->socket);
break;
case UTP_STATE_WRITABLE:
if (self->on_socket_writable) self->on_socket_writable(self, a->socket);
break;
case UTP_STATE_EOF:
if (self->on_socket_end) self->on_socket_end(self, a->socket);
break;
case UTP_STATE_DESTROYING:
self->sockets--;
if (!self->sockets && self->destroyed) really_destroy(self);
if (self->on_socket_close) self->on_socket_close(self, a->socket);
break;
default:
DEBUG("unknown state change");
break;
}
return 0;
}
static uint64
on_utp_log (utp_callback_arguments *a) {
DEBUG(a->buf);
return 0;
}
static uint64
on_utp_accept (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (!self->on_socket) return 0;
self->sockets++;
self->on_socket(self, a->socket);
return 0;
}
static uint64
on_utp_firewall (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (!self->on_socket || self->firewalled) return 1;
return 0;
}
NAN_INLINE static uint64
on_utp_sendto (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
uv_buf_t buf = {
.base = (char *) a->buf,
.len = a->len
};
#ifdef UV_LEGACY
struct sockaddr_in *addr = (struct sockaddr_in *) a->address;
uv_udp_send(NULL, &(self->handle), &buf, 1, *addr, NULL);
#else
uv_udp_try_send(&(self->handle), &buf, 1, a->address);
#endif
return 0;
}
static uint64
on_utp_error (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
utp_socket *socket = a->socket;
if (self->on_socket_error) self->on_socket_error(self, socket, a->error_code);
return 0;
}
int
utp_uv_init (utp_uv_t *self) {
int ret;
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
// clear state
self->firewalled = 0;
self->sockets = 0;
self->destroyed = 0;
self->on_message = NULL;
self->on_error = NULL;
self->on_close = NULL;
self->on_socket = NULL;
self->on_socket_error = NULL;
self->on_socket_read = NULL;
self->on_socket_writable = NULL;
self->on_socket_end = NULL;
self->on_socket_close = NULL;
self->on_socket_connect = NULL;
// init utp
self->context = utp_init(2);
utp_context_set_userdata(self->context, self);
utp_set_callback(self->context, UTP_ON_STATE_CHANGE, &on_utp_state_change);
utp_set_callback(self->context, UTP_ON_READ, &on_utp_read);
utp_set_callback(self->context, UTP_ON_FIREWALL, &on_utp_firewall);
utp_set_callback(self->context, UTP_ON_ACCEPT, &on_utp_accept);
utp_set_callback(self->context, UTP_SENDTO, &on_utp_sendto);
utp_set_callback(self->context, UTP_ON_ERROR, &on_utp_error);
ret = uv_timer_init(uv_default_loop(), timer);
if (ret) return ret;
ret = uv_udp_init(uv_default_loop(), handle);
if (ret) return ret;
handle->data = self;
timer->data = self;
return 0;
}
utp_socket_stats*
utp_uv_socket_stats (utp_uv_t *self, utp_socket *socket) {
return utp_get_stats(socket);
}
utp_socket *
utp_uv_connect (utp_uv_t *self, int port, char *ip) {
struct sockaddr_in addr;
int ret;
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return NULL;
#endif
utp_socket *socket = utp_create_socket(self->context);
if (socket == NULL) return NULL;
ret = utp_connect(socket, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (ret) return NULL;
self->sockets++;
return socket;
}
void
utp_uv_debug (utp_uv_t *self) {
utp_context_set_option(self->context, UTP_LOG_DEBUG, 1);
utp_set_callback(self->context, UTP_LOG, &on_utp_log);
}
int
utp_uv_bind (utp_uv_t *self, int port, char *ip) {
struct sockaddr_in addr;
int ret;
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return ret;
#endif
#ifdef UV_LEGACY
ret = uv_udp_bind(handle, addr, 0);
#else
ret = uv_udp_bind(handle, (const struct sockaddr*) &addr, 0);
#endif
if (ret) return ret;
#ifdef UV_LEGACY
ret = uv_udp_recv_start(handle, on_uv_alloc_compat, on_uv_read_compat);
#else
ret = uv_udp_recv_start(handle, on_uv_alloc, on_uv_read);
#endif
if (ret) return ret;
#ifdef UV_LEGACY
ret = uv_timer_start(timer, on_uv_interval_compat, UTP_UV_TIMEOUT_INTERVAL, UTP_UV_TIMEOUT_INTERVAL);
#else
ret = uv_timer_start(timer, on_uv_interval, UTP_UV_TIMEOUT_INTERVAL, UTP_UV_TIMEOUT_INTERVAL);
#endif
if (ret) return ret;
return 0;
}
int
utp_uv_address (utp_uv_t *self, int *port, char *ip) {
int ret;
uv_udp_t *handle = &(self->handle);
struct sockaddr name;
int name_len = sizeof(name);
ret = uv_udp_getsockname(handle, &name, &name_len);
if (ret) return ret;
struct sockaddr_in *name_in = (struct sockaddr_in *) &name;
*port = ntohs(name_in->sin_port);
if (ip != NULL) uv_ip4_name(name_in, ip, 17);
return 0;
}
NAN_INLINE int
utp_uv_socket_writev (utp_uv_t *self, utp_socket *socket, struct utp_iovec *bufs, size_t bufs_len) {
return utp_writev(socket, bufs, bufs_len);
}
NAN_INLINE int
utp_uv_socket_write (utp_uv_t *self, utp_socket *socket, char *data, size_t len) {
return utp_write(socket, data, len);
}
void
utp_uv_socket_end (utp_uv_t *self, utp_socket *socket) {
utp_close(socket);
}
void
utp_uv_ref (utp_uv_t *self) {
uv_ref((uv_handle_t *) &(self->handle));
uv_ref((uv_handle_t *) &(self->timer));
}
void
utp_uv_unref (utp_uv_t *self) {
uv_unref((uv_handle_t *) &(self->handle));
uv_unref((uv_handle_t *) &(self->timer));
}
void
utp_uv_destroy (utp_uv_t *self) {
if (self->destroyed) return;
self->destroyed = 1;
self->on_socket = NULL;
if (!self->sockets) really_destroy(self);
}
NAN_INLINE int
utp_uv_send (utp_uv_t *self, char *data, size_t len, int port, char *ip) {
struct sockaddr_in addr;
uv_udp_t *handle = &(self->handle);
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
int ret;
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return -1;
#endif
uv_buf_t buf = {
.base = data,
.len = len
};
#ifdef UV_LEGACY
uv_udp_send(NULL, handle, &buf, 1, addr, NULL);
return len;
#else
return uv_udp_try_send(handle, (const uv_buf_t *) &buf, 1, (const struct sockaddr *) &addr);
#endif
}
// int
// utp_uv_send_buffered (utp_uv_t *self, uv_udp_send_t* req, char *data, size_t len, int port, char *ip, uv_udp_send_cb callback) {
// int ret;
// struct sockaddr_in addr;
// uv_udp_t *handle = &(self->handle);
// ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
// if (ret) return -1;
// uv_buf_t buf = {
// .base = data,
// .len = len
// };
// return uv_udp_send(req, &(self->handle), &buf, 1);
// }
<commit_msg>remove force inlines<commit_after>#include "utp_uv.h"
#include "nan.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#if (NODE_MODULE_VERSION <= NODE_0_10_MODULE_VERSION)
#define UV_LEGACY
#endif
#define UTP_UV_TIMEOUT_INTERVAL 500
#define IP_STRING(ip) (const char *) (ip == NULL ? "127.0.0.1" : ip)
#define DEBUG(msg) fprintf(stderr, "debug utp_uv: %s\n", (const char *) msg);
static void
on_uv_close (uv_handle_t *handle) {
utp_uv_t *self = (utp_uv_t *) handle->data;
if (self->context) {
utp_destroy(self->context);
self->context = NULL;
if (self->on_close) self->on_close(self);
}
}
static void
really_destroy (utp_uv_t *self) {
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
// TODO: do these need error handling?
uv_timer_stop(timer);
uv_udp_recv_stop(handle);
uv_close((uv_handle_t *) handle, on_uv_close);
}
#ifndef UV_LEGACY
static void
on_uv_alloc (uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {
utp_uv_t *self = (utp_uv_t *) handle->data;
buf->base = (char *) &(self->buffer);
buf->len = UTP_UV_BUFFER_SIZE;
}
#endif
static void
on_uv_read (uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags) {
utp_uv_t *self = (utp_uv_t *) handle->data;
int ret;
if (nread < 0) {
if (self->on_error) self->on_error(self);
return;
}
if (nread == 0) {
utp_issue_deferred_acks(self->context);
return;
}
ret = utp_process_udp(self->context, (const unsigned char *) buf->base, nread, addr, sizeof(struct sockaddr));
if (ret) return;
// not a utp message -> call on_message
if (!self->on_message) return;
struct sockaddr_in *addr_in = (struct sockaddr_in *) addr;
int port = ntohs(addr_in->sin_port);
char ip[17];
uv_ip4_name(addr_in, (char *) &ip, 17);
self->on_message(self, buf->base, (size_t) nread, port, (char *) &ip);
}
static void
on_uv_interval (uv_timer_t *req) {
utp_uv_t *self = (utp_uv_t *) req->data;
utp_check_timeouts(self->context);
}
#ifdef UV_LEGACY
static uv_buf_t
on_uv_alloc_compat (uv_handle_t* handle, size_t suggested_size) {
utp_uv_t *self = (utp_uv_t *) handle->data;
return uv_buf_init((char *) &(self->buffer), UTP_UV_BUFFER_SIZE);
}
static void
on_uv_read_compat (uv_udp_t* handle, ssize_t nread, uv_buf_t buf, struct sockaddr* addr, unsigned flags) {
on_uv_read(handle, nread, &buf, addr, flags);
}
static void
on_uv_interval_compat (uv_timer_t *req, int status) {
on_uv_interval(req);
}
#endif
static uint64
on_utp_read (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (self->on_socket_read) self->on_socket_read(self, a->socket, (char *) a->buf, a->len);
utp_read_drained(a->socket);
return 0;
}
static uint64
on_utp_state_change (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
switch (a->state) {
case UTP_STATE_CONNECT:
if (self->on_socket_connect) self->on_socket_connect(self, a->socket);
break;
case UTP_STATE_WRITABLE:
if (self->on_socket_writable) self->on_socket_writable(self, a->socket);
break;
case UTP_STATE_EOF:
if (self->on_socket_end) self->on_socket_end(self, a->socket);
break;
case UTP_STATE_DESTROYING:
self->sockets--;
if (!self->sockets && self->destroyed) really_destroy(self);
if (self->on_socket_close) self->on_socket_close(self, a->socket);
break;
default:
DEBUG("unknown state change");
break;
}
return 0;
}
static uint64
on_utp_log (utp_callback_arguments *a) {
DEBUG(a->buf);
return 0;
}
static uint64
on_utp_accept (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (!self->on_socket) return 0;
self->sockets++;
self->on_socket(self, a->socket);
return 0;
}
static uint64
on_utp_firewall (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
if (!self->on_socket || self->firewalled) return 1;
return 0;
}
static uint64
on_utp_sendto (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
uv_buf_t buf = {
.base = (char *) a->buf,
.len = a->len
};
#ifdef UV_LEGACY
struct sockaddr_in *addr = (struct sockaddr_in *) a->address;
uv_udp_send(NULL, &(self->handle), &buf, 1, *addr, NULL);
#else
uv_udp_try_send(&(self->handle), &buf, 1, a->address);
#endif
return 0;
}
static uint64
on_utp_error (utp_callback_arguments *a) {
utp_uv_t *self = (utp_uv_t *) utp_context_get_userdata(a->context);
utp_socket *socket = a->socket;
if (self->on_socket_error) self->on_socket_error(self, socket, a->error_code);
return 0;
}
int
utp_uv_init (utp_uv_t *self) {
int ret;
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
// clear state
self->firewalled = 0;
self->sockets = 0;
self->destroyed = 0;
self->on_message = NULL;
self->on_error = NULL;
self->on_close = NULL;
self->on_socket = NULL;
self->on_socket_error = NULL;
self->on_socket_read = NULL;
self->on_socket_writable = NULL;
self->on_socket_end = NULL;
self->on_socket_close = NULL;
self->on_socket_connect = NULL;
// init utp
self->context = utp_init(2);
utp_context_set_userdata(self->context, self);
utp_set_callback(self->context, UTP_ON_STATE_CHANGE, &on_utp_state_change);
utp_set_callback(self->context, UTP_ON_READ, &on_utp_read);
utp_set_callback(self->context, UTP_ON_FIREWALL, &on_utp_firewall);
utp_set_callback(self->context, UTP_ON_ACCEPT, &on_utp_accept);
utp_set_callback(self->context, UTP_SENDTO, &on_utp_sendto);
utp_set_callback(self->context, UTP_ON_ERROR, &on_utp_error);
ret = uv_timer_init(uv_default_loop(), timer);
if (ret) return ret;
ret = uv_udp_init(uv_default_loop(), handle);
if (ret) return ret;
handle->data = self;
timer->data = self;
return 0;
}
utp_socket_stats*
utp_uv_socket_stats (utp_uv_t *self, utp_socket *socket) {
return utp_get_stats(socket);
}
utp_socket *
utp_uv_connect (utp_uv_t *self, int port, char *ip) {
struct sockaddr_in addr;
int ret;
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return NULL;
#endif
utp_socket *socket = utp_create_socket(self->context);
if (socket == NULL) return NULL;
ret = utp_connect(socket, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (ret) return NULL;
self->sockets++;
return socket;
}
void
utp_uv_debug (utp_uv_t *self) {
utp_context_set_option(self->context, UTP_LOG_DEBUG, 1);
utp_set_callback(self->context, UTP_LOG, &on_utp_log);
}
int
utp_uv_bind (utp_uv_t *self, int port, char *ip) {
struct sockaddr_in addr;
int ret;
uv_udp_t *handle = &(self->handle);
uv_timer_t *timer = &(self->timer);
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return ret;
#endif
#ifdef UV_LEGACY
ret = uv_udp_bind(handle, addr, 0);
#else
ret = uv_udp_bind(handle, (const struct sockaddr*) &addr, 0);
#endif
if (ret) return ret;
#ifdef UV_LEGACY
ret = uv_udp_recv_start(handle, on_uv_alloc_compat, on_uv_read_compat);
#else
ret = uv_udp_recv_start(handle, on_uv_alloc, on_uv_read);
#endif
if (ret) return ret;
#ifdef UV_LEGACY
ret = uv_timer_start(timer, on_uv_interval_compat, UTP_UV_TIMEOUT_INTERVAL, UTP_UV_TIMEOUT_INTERVAL);
#else
ret = uv_timer_start(timer, on_uv_interval, UTP_UV_TIMEOUT_INTERVAL, UTP_UV_TIMEOUT_INTERVAL);
#endif
if (ret) return ret;
return 0;
}
int
utp_uv_address (utp_uv_t *self, int *port, char *ip) {
int ret;
uv_udp_t *handle = &(self->handle);
struct sockaddr name;
int name_len = sizeof(name);
ret = uv_udp_getsockname(handle, &name, &name_len);
if (ret) return ret;
struct sockaddr_in *name_in = (struct sockaddr_in *) &name;
*port = ntohs(name_in->sin_port);
if (ip != NULL) uv_ip4_name(name_in, ip, 17);
return 0;
}
int
utp_uv_socket_writev (utp_uv_t *self, utp_socket *socket, struct utp_iovec *bufs, size_t bufs_len) {
return utp_writev(socket, bufs, bufs_len);
}
int
utp_uv_socket_write (utp_uv_t *self, utp_socket *socket, char *data, size_t len) {
return utp_write(socket, data, len);
}
void
utp_uv_socket_end (utp_uv_t *self, utp_socket *socket) {
utp_close(socket);
}
void
utp_uv_ref (utp_uv_t *self) {
uv_ref((uv_handle_t *) &(self->handle));
uv_ref((uv_handle_t *) &(self->timer));
}
void
utp_uv_unref (utp_uv_t *self) {
uv_unref((uv_handle_t *) &(self->handle));
uv_unref((uv_handle_t *) &(self->timer));
}
void
utp_uv_destroy (utp_uv_t *self) {
if (self->destroyed) return;
self->destroyed = 1;
self->on_socket = NULL;
if (!self->sockets) really_destroy(self);
}
int
utp_uv_send (utp_uv_t *self, char *data, size_t len, int port, char *ip) {
struct sockaddr_in addr;
uv_udp_t *handle = &(self->handle);
#ifdef UV_LEGACY
addr = uv_ip4_addr(IP_STRING(ip), port);
#else
int ret;
ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
if (ret) return -1;
#endif
uv_buf_t buf = {
.base = data,
.len = len
};
#ifdef UV_LEGACY
uv_udp_send(NULL, handle, &buf, 1, addr, NULL);
return len;
#else
return uv_udp_try_send(handle, (const uv_buf_t *) &buf, 1, (const struct sockaddr *) &addr);
#endif
}
// int
// utp_uv_send_buffered (utp_uv_t *self, uv_udp_send_t* req, char *data, size_t len, int port, char *ip, uv_udp_send_cb callback) {
// int ret;
// struct sockaddr_in addr;
// uv_udp_t *handle = &(self->handle);
// ret = uv_ip4_addr(IP_STRING(ip), port, &addr);
// if (ret) return -1;
// uv_buf_t buf = {
// .base = data,
// .len = len
// };
// return uv_udp_send(req, &(self->handle), &buf, 1);
// }
<|endoftext|> |
<commit_before>#include "window.hh"
#include "assert.hh"
#include "filters.hh"
#include <algorithm>
#include <sstream>
namespace Kakoune
{
BufferIterator Selection::begin() const
{
return std::min(m_first, m_last);
}
BufferIterator Selection::end() const
{
return std::max(m_first, m_last) + 1;
}
void Selection::offset(int offset)
{
m_first += offset;
m_last += offset;
}
struct scoped_undo_group
{
scoped_undo_group(Buffer& buffer)
: m_buffer(buffer) { m_buffer.begin_undo_group(); }
~scoped_undo_group() { m_buffer.end_undo_group(); }
private:
Buffer& m_buffer;
};
class HighlightSelections
{
public:
HighlightSelections(Window& window)
: m_window(window)
{
}
void operator()(DisplayBuffer& display_buffer)
{
SelectionList sorted_selections = m_window.m_selections;
std::sort(sorted_selections.begin(), sorted_selections.end(),
[](const Selection& lhs, const Selection& rhs) { return lhs.begin() < rhs.begin(); });
auto atom_it = display_buffer.begin();
auto sel_it = sorted_selections.begin();
while (atom_it != display_buffer.end()
and sel_it != sorted_selections.end())
{
Selection& sel = *sel_it;
DisplayAtom& atom = *atom_it;
// [###------]
if (atom.begin() >= sel.begin() and atom.begin() < sel.end() and atom.end() > sel.end())
{
atom_it = display_buffer.split(atom_it, sel.end());
atom_it->attribute() |= Attributes::Underline;
++atom_it;
++sel_it;
}
// [---###---]
else if (atom.begin() < sel.begin() and atom.end() > sel.end())
{
atom_it = display_buffer.split(atom_it, sel.begin());
atom_it = display_buffer.split(atom_it + 1, sel.end());
atom_it->attribute() |= Attributes::Underline;
++atom_it;
++sel_it;
}
// [------###]
else if (atom.begin() < sel.begin() and atom.end() > sel.begin())
{
atom_it = display_buffer.split(atom_it, sel.begin()) + 1;
atom_it->attribute() |= Attributes::Underline;
++atom_it;
}
// [#########]
else if (atom.begin() >= sel.begin() and atom.end() <= sel.end())
{
atom_it->attribute() |= Attributes::Underline;
++atom_it;
}
// [---------]
else if (atom.begin() >= sel.end())
++sel_it;
// [---------]
else if (atom.end() <= sel.begin())
++atom_it;
else
assert(false);
}
}
private:
const Window& m_window;
};
Window::Window(Buffer& buffer)
: m_buffer(buffer),
m_position(0, 0),
m_dimensions(0, 0),
m_current_inserter(nullptr)
{
m_selections.push_back(Selection(buffer.begin(), buffer.begin()));
m_filters.push_back(colorize_cplusplus);
m_filters.push_back(expand_tabulations);
m_filters.push_back(HighlightSelections(*this));
m_filters.push_back(show_line_numbers);
}
void Window::check_invariant() const
{
assert(not m_selections.empty());
}
DisplayCoord Window::cursor_position() const
{
check_invariant();
return line_and_column_at(cursor_iterator());
}
BufferIterator Window::cursor_iterator() const
{
check_invariant();
return m_selections.back().last();
}
void Window::erase()
{
scoped_undo_group undo_group(m_buffer);
erase_noundo();
}
void Window::erase_noundo()
{
check_invariant();
for (auto& sel : m_selections)
{
m_buffer.erase(sel.begin(), sel.end());
sel = Selection(sel.begin(), sel.begin());
}
scroll_to_keep_cursor_visible_ifn();
}
template<typename Iterator>
static DisplayCoord measure_string(Iterator begin, Iterator end)
{
DisplayCoord result(0, 0);
while (begin != end)
{
if (*begin == '\n')
{
++result.line;
result.column = 0;
}
else
++result.column;
++begin;
}
return result;
}
static DisplayCoord measure_string(const Window::String& string)
{
return measure_string(string.begin(), string.end());
}
void Window::insert(const String& string)
{
scoped_undo_group undo_group(m_buffer);
insert_noundo(string);
}
void Window::insert_noundo(const String& string)
{
for (auto& sel : m_selections)
{
m_buffer.insert(sel.begin(), string);
sel.offset(string.length());
}
scroll_to_keep_cursor_visible_ifn();
}
void Window::append(const String& string)
{
scoped_undo_group undo_group(m_buffer);
append_noundo(string);
}
void Window::append_noundo(const String& string)
{
for (auto& sel : m_selections)
m_buffer.insert(sel.end(), string);
scroll_to_keep_cursor_visible_ifn();
}
bool Window::undo()
{
return m_buffer.undo();
}
bool Window::redo()
{
return m_buffer.redo();
}
BufferIterator Window::iterator_at(const DisplayCoord& window_pos) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return m_buffer.begin();
if (DisplayCoord(0,0) <= window_pos)
{
for (auto atom_it = m_display_buffer.begin();
atom_it != m_display_buffer.end(); ++atom_it)
{
if (window_pos < atom_it->coord())
{
const DisplayAtom& atom = *(atom_it - 1);
return atom.iterator_at(window_pos);
}
}
}
return m_buffer.iterator_at(m_position + BufferCoord(window_pos));
}
DisplayCoord Window::line_and_column_at(const BufferIterator& iterator) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return DisplayCoord(0, 0);
if (iterator >= m_display_buffer.front().begin() and
iterator < m_display_buffer.back().end())
{
for (auto& atom : m_display_buffer)
{
if (atom.end() > iterator)
{
assert(atom.begin() <= iterator);
return atom.line_and_column_at(iterator);
}
}
}
BufferCoord coord = m_buffer.line_and_column_at(iterator);
return DisplayCoord(coord.line - m_position.line,
coord.column - m_position.column);
}
void Window::clear_selections()
{
check_invariant();
Selection sel = Selection(m_selections.back().last(),
m_selections.back().last());
m_selections.clear();
m_selections.push_back(std::move(sel));
}
void Window::select(const Selector& selector, bool append)
{
check_invariant();
if (not append)
{
Selection sel = selector(m_selections.back().last());
m_selections.clear();
m_selections.push_back(std::move(sel));
}
else
{
for (auto& sel : m_selections)
{
sel = Selection(sel.first(), selector(sel.last()).last());
}
}
scroll_to_keep_cursor_visible_ifn();
}
BufferString Window::selection_content() const
{
check_invariant();
return m_buffer.string(m_selections.back().begin(),
m_selections.back().end());
}
void Window::move_cursor(const DisplayCoord& offset, bool append)
{
if (not append)
{
BufferCoord pos = m_buffer.line_and_column_at(cursor_iterator());
move_cursor_to(m_buffer.iterator_at(pos + BufferCoord(offset)));
}
else
{
for (auto& sel : m_selections)
{
BufferCoord pos = m_buffer.line_and_column_at(sel.last());
sel = Selection(sel.first(), m_buffer.iterator_at(pos + BufferCoord(offset)));
}
scroll_to_keep_cursor_visible_ifn();
}
}
void Window::move_cursor_to(const BufferIterator& iterator)
{
m_selections.clear();
m_selections.push_back(Selection(iterator, iterator));
scroll_to_keep_cursor_visible_ifn();
}
void Window::update_display_buffer()
{
m_display_buffer.clear();
BufferIterator begin = m_buffer.iterator_at(m_position);
BufferIterator end = m_buffer.iterator_at(m_position +
BufferCoord(m_dimensions.line, m_dimensions.column+1));
if (begin == end)
return;
m_display_buffer.append(DisplayAtom(DisplayCoord(0,0), begin, end));
for (auto& filter : m_filters)
{
filter(m_display_buffer);
m_display_buffer.check_invariant();
}
}
void Window::set_dimensions(const DisplayCoord& dimensions)
{
m_dimensions = dimensions;
}
void Window::scroll_to_keep_cursor_visible_ifn()
{
check_invariant();
DisplayCoord cursor = line_and_column_at(m_selections.back().last());
if (cursor.line < 0)
{
m_position.line = std::max(m_position.line + cursor.line, 0);
}
else if (cursor.line >= m_dimensions.line)
{
m_position.line += cursor.line - (m_dimensions.line - 1);
}
if (cursor.column < 0)
{
m_position.column = std::max(m_position.column + cursor.column, 0);
}
else if (cursor.column >= m_dimensions.column)
{
m_position.column += cursor.column - (m_dimensions.column - 1);
}
}
std::string Window::status_line() const
{
BufferCoord cursor = m_buffer.line_and_column_at(m_selections.back().end());
std::ostringstream oss;
oss << m_buffer.name();
if (m_buffer.is_modified())
oss << " [+]";
oss << " -- " << cursor.line << "," << cursor.column
<< " -- " << m_selections.size() << " sel -- ";
if (m_current_inserter)
oss << "[Insert]";
return oss.str();
}
IncrementalInserter::IncrementalInserter(Window& window, Mode mode)
: m_window(window)
{
assert(not m_window.m_current_inserter);
m_window.m_current_inserter = this;
m_window.check_invariant();
m_window.m_buffer.begin_undo_group();
if (mode == Mode::Change)
window.erase_noundo();
for (auto& sel : m_window.m_selections)
{
BufferIterator pos;
switch (mode)
{
case Mode::Insert: pos = sel.begin(); break;
case Mode::Append: pos = sel.end(); break;
case Mode::Change: pos = sel.begin(); break;
case Mode::OpenLineBelow:
pos = sel.end();
while (not pos.is_end() and *pos != '\n')
++pos;
++pos;
window.m_buffer.insert(pos, "\n");
break;
case Mode::OpenLineAbove:
pos = sel.begin();
while (not pos.is_begin() and *pos != '\n')
--pos;
window.m_buffer.insert(pos, "\n");
++pos;
break;
}
sel = Selection(pos, pos);
}
}
IncrementalInserter::~IncrementalInserter()
{
assert(m_window.m_current_inserter == this);
m_window.m_current_inserter = nullptr;
m_window.m_buffer.end_undo_group();
}
void IncrementalInserter::insert(const Window::String& string)
{
m_window.insert_noundo(string);
}
void IncrementalInserter::erase()
{
move_cursor(DisplayCoord(0, -1));
m_window.erase_noundo();
}
void IncrementalInserter::move_cursor(const DisplayCoord& offset)
{
for (auto& sel : m_window.m_selections)
{
DisplayCoord pos = m_window.line_and_column_at(sel.last());
BufferIterator it = m_window.iterator_at(pos + offset);
sel = Selection(it, it);
}
}
}
<commit_msg>Window: fix status_line cursor position<commit_after>#include "window.hh"
#include "assert.hh"
#include "filters.hh"
#include <algorithm>
#include <sstream>
namespace Kakoune
{
BufferIterator Selection::begin() const
{
return std::min(m_first, m_last);
}
BufferIterator Selection::end() const
{
return std::max(m_first, m_last) + 1;
}
void Selection::offset(int offset)
{
m_first += offset;
m_last += offset;
}
struct scoped_undo_group
{
scoped_undo_group(Buffer& buffer)
: m_buffer(buffer) { m_buffer.begin_undo_group(); }
~scoped_undo_group() { m_buffer.end_undo_group(); }
private:
Buffer& m_buffer;
};
class HighlightSelections
{
public:
HighlightSelections(Window& window)
: m_window(window)
{
}
void operator()(DisplayBuffer& display_buffer)
{
SelectionList sorted_selections = m_window.m_selections;
std::sort(sorted_selections.begin(), sorted_selections.end(),
[](const Selection& lhs, const Selection& rhs) { return lhs.begin() < rhs.begin(); });
auto atom_it = display_buffer.begin();
auto sel_it = sorted_selections.begin();
while (atom_it != display_buffer.end()
and sel_it != sorted_selections.end())
{
Selection& sel = *sel_it;
DisplayAtom& atom = *atom_it;
// [###------]
if (atom.begin() >= sel.begin() and atom.begin() < sel.end() and atom.end() > sel.end())
{
atom_it = display_buffer.split(atom_it, sel.end());
atom_it->attribute() |= Attributes::Underline;
++atom_it;
++sel_it;
}
// [---###---]
else if (atom.begin() < sel.begin() and atom.end() > sel.end())
{
atom_it = display_buffer.split(atom_it, sel.begin());
atom_it = display_buffer.split(atom_it + 1, sel.end());
atom_it->attribute() |= Attributes::Underline;
++atom_it;
++sel_it;
}
// [------###]
else if (atom.begin() < sel.begin() and atom.end() > sel.begin())
{
atom_it = display_buffer.split(atom_it, sel.begin()) + 1;
atom_it->attribute() |= Attributes::Underline;
++atom_it;
}
// [#########]
else if (atom.begin() >= sel.begin() and atom.end() <= sel.end())
{
atom_it->attribute() |= Attributes::Underline;
++atom_it;
}
// [---------]
else if (atom.begin() >= sel.end())
++sel_it;
// [---------]
else if (atom.end() <= sel.begin())
++atom_it;
else
assert(false);
}
}
private:
const Window& m_window;
};
Window::Window(Buffer& buffer)
: m_buffer(buffer),
m_position(0, 0),
m_dimensions(0, 0),
m_current_inserter(nullptr)
{
m_selections.push_back(Selection(buffer.begin(), buffer.begin()));
m_filters.push_back(colorize_cplusplus);
m_filters.push_back(expand_tabulations);
m_filters.push_back(HighlightSelections(*this));
m_filters.push_back(show_line_numbers);
}
void Window::check_invariant() const
{
assert(not m_selections.empty());
}
DisplayCoord Window::cursor_position() const
{
check_invariant();
return line_and_column_at(cursor_iterator());
}
BufferIterator Window::cursor_iterator() const
{
check_invariant();
return m_selections.back().last();
}
void Window::erase()
{
scoped_undo_group undo_group(m_buffer);
erase_noundo();
}
void Window::erase_noundo()
{
check_invariant();
for (auto& sel : m_selections)
{
m_buffer.erase(sel.begin(), sel.end());
sel = Selection(sel.begin(), sel.begin());
}
scroll_to_keep_cursor_visible_ifn();
}
template<typename Iterator>
static DisplayCoord measure_string(Iterator begin, Iterator end)
{
DisplayCoord result(0, 0);
while (begin != end)
{
if (*begin == '\n')
{
++result.line;
result.column = 0;
}
else
++result.column;
++begin;
}
return result;
}
static DisplayCoord measure_string(const Window::String& string)
{
return measure_string(string.begin(), string.end());
}
void Window::insert(const String& string)
{
scoped_undo_group undo_group(m_buffer);
insert_noundo(string);
}
void Window::insert_noundo(const String& string)
{
for (auto& sel : m_selections)
{
m_buffer.insert(sel.begin(), string);
sel.offset(string.length());
}
scroll_to_keep_cursor_visible_ifn();
}
void Window::append(const String& string)
{
scoped_undo_group undo_group(m_buffer);
append_noundo(string);
}
void Window::append_noundo(const String& string)
{
for (auto& sel : m_selections)
m_buffer.insert(sel.end(), string);
scroll_to_keep_cursor_visible_ifn();
}
bool Window::undo()
{
return m_buffer.undo();
}
bool Window::redo()
{
return m_buffer.redo();
}
BufferIterator Window::iterator_at(const DisplayCoord& window_pos) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return m_buffer.begin();
if (DisplayCoord(0,0) <= window_pos)
{
for (auto atom_it = m_display_buffer.begin();
atom_it != m_display_buffer.end(); ++atom_it)
{
if (window_pos < atom_it->coord())
{
const DisplayAtom& atom = *(atom_it - 1);
return atom.iterator_at(window_pos);
}
}
}
return m_buffer.iterator_at(m_position + BufferCoord(window_pos));
}
DisplayCoord Window::line_and_column_at(const BufferIterator& iterator) const
{
if (m_display_buffer.begin() == m_display_buffer.end())
return DisplayCoord(0, 0);
if (iterator >= m_display_buffer.front().begin() and
iterator < m_display_buffer.back().end())
{
for (auto& atom : m_display_buffer)
{
if (atom.end() > iterator)
{
assert(atom.begin() <= iterator);
return atom.line_and_column_at(iterator);
}
}
}
BufferCoord coord = m_buffer.line_and_column_at(iterator);
return DisplayCoord(coord.line - m_position.line,
coord.column - m_position.column);
}
void Window::clear_selections()
{
check_invariant();
Selection sel = Selection(m_selections.back().last(),
m_selections.back().last());
m_selections.clear();
m_selections.push_back(std::move(sel));
}
void Window::select(const Selector& selector, bool append)
{
check_invariant();
if (not append)
{
Selection sel = selector(m_selections.back().last());
m_selections.clear();
m_selections.push_back(std::move(sel));
}
else
{
for (auto& sel : m_selections)
{
sel = Selection(sel.first(), selector(sel.last()).last());
}
}
scroll_to_keep_cursor_visible_ifn();
}
BufferString Window::selection_content() const
{
check_invariant();
return m_buffer.string(m_selections.back().begin(),
m_selections.back().end());
}
void Window::move_cursor(const DisplayCoord& offset, bool append)
{
if (not append)
{
BufferCoord pos = m_buffer.line_and_column_at(cursor_iterator());
move_cursor_to(m_buffer.iterator_at(pos + BufferCoord(offset)));
}
else
{
for (auto& sel : m_selections)
{
BufferCoord pos = m_buffer.line_and_column_at(sel.last());
sel = Selection(sel.first(), m_buffer.iterator_at(pos + BufferCoord(offset)));
}
scroll_to_keep_cursor_visible_ifn();
}
}
void Window::move_cursor_to(const BufferIterator& iterator)
{
m_selections.clear();
m_selections.push_back(Selection(iterator, iterator));
scroll_to_keep_cursor_visible_ifn();
}
void Window::update_display_buffer()
{
m_display_buffer.clear();
BufferIterator begin = m_buffer.iterator_at(m_position);
BufferIterator end = m_buffer.iterator_at(m_position +
BufferCoord(m_dimensions.line, m_dimensions.column+1));
if (begin == end)
return;
m_display_buffer.append(DisplayAtom(DisplayCoord(0,0), begin, end));
for (auto& filter : m_filters)
{
filter(m_display_buffer);
m_display_buffer.check_invariant();
}
}
void Window::set_dimensions(const DisplayCoord& dimensions)
{
m_dimensions = dimensions;
}
void Window::scroll_to_keep_cursor_visible_ifn()
{
check_invariant();
DisplayCoord cursor = line_and_column_at(m_selections.back().last());
if (cursor.line < 0)
{
m_position.line = std::max(m_position.line + cursor.line, 0);
}
else if (cursor.line >= m_dimensions.line)
{
m_position.line += cursor.line - (m_dimensions.line - 1);
}
if (cursor.column < 0)
{
m_position.column = std::max(m_position.column + cursor.column, 0);
}
else if (cursor.column >= m_dimensions.column)
{
m_position.column += cursor.column - (m_dimensions.column - 1);
}
}
std::string Window::status_line() const
{
BufferCoord cursor = m_buffer.line_and_column_at(m_selections.back().last());
std::ostringstream oss;
oss << m_buffer.name();
if (m_buffer.is_modified())
oss << " [+]";
oss << " -- " << cursor.line << "," << cursor.column
<< " -- " << m_selections.size() << " sel -- ";
if (m_current_inserter)
oss << "[Insert]";
return oss.str();
}
IncrementalInserter::IncrementalInserter(Window& window, Mode mode)
: m_window(window)
{
assert(not m_window.m_current_inserter);
m_window.m_current_inserter = this;
m_window.check_invariant();
m_window.m_buffer.begin_undo_group();
if (mode == Mode::Change)
window.erase_noundo();
for (auto& sel : m_window.m_selections)
{
BufferIterator pos;
switch (mode)
{
case Mode::Insert: pos = sel.begin(); break;
case Mode::Append: pos = sel.end(); break;
case Mode::Change: pos = sel.begin(); break;
case Mode::OpenLineBelow:
pos = sel.end();
while (not pos.is_end() and *pos != '\n')
++pos;
++pos;
window.m_buffer.insert(pos, "\n");
break;
case Mode::OpenLineAbove:
pos = sel.begin();
while (not pos.is_begin() and *pos != '\n')
--pos;
window.m_buffer.insert(pos, "\n");
++pos;
break;
}
sel = Selection(pos, pos);
}
}
IncrementalInserter::~IncrementalInserter()
{
assert(m_window.m_current_inserter == this);
m_window.m_current_inserter = nullptr;
m_window.m_buffer.end_undo_group();
}
void IncrementalInserter::insert(const Window::String& string)
{
m_window.insert_noundo(string);
}
void IncrementalInserter::erase()
{
move_cursor(DisplayCoord(0, -1));
m_window.erase_noundo();
}
void IncrementalInserter::move_cursor(const DisplayCoord& offset)
{
for (auto& sel : m_window.m_selections)
{
DisplayCoord pos = m_window.line_and_column_at(sel.last());
BufferIterator it = m_window.iterator_at(pos + offset);
sel = Selection(it, it);
}
}
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP
/**
* \defgroup prob_dists Probability Distributions
*/
/**
* \ingroup prob_dists
* \defgroup multivar_dists Multivariate Distributions
* Distributions with Matrix inputs
*/
/**
* \ingroup prob_dists
* \defgroup univar_dists Univariate Distributions
* Distributions with scalar, vector, or array input.
*/
#include <stan/math/rev.hpp>
#endif
<commit_msg>Removed newline in stan/math.hpp<commit_after>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP
/**
* \defgroup prob_dists Probability Distributions
*/
/**
* \ingroup prob_dists
* \defgroup multivar_dists Multivariate Distributions
* Distributions with Matrix inputs
*/
/**
* \ingroup prob_dists
* \defgroup univar_dists Univariate Distributions
* Distributions with scalar, vector, or array input.
*/
#include <stan/math/rev.hpp>
#endif<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2016 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file static_if.hpp
* \brief Contains a C++14 implementation of a poor static if.
*/
#ifndef CPP_STATIC_IF_HPP
#define CPP_STATIC_IF_HPP
namespace cpp {
namespace static_if_detail {
/*!
* \brief Identify functor
*/
struct identity {
/*!
* \brief Returns exactly what was passsed as argument
*/
template <typename T>
T operator()(T&& x) const {
return std::forward<T>(x);
}
};
/*!
* \brief Helper for static if
*
* This base type is when the condition is true
*/
template <bool Cond>
struct statement {
/*!
* \brief Execute the if part of the statement
* \param f The functor to execute
*/
template <typename F>
void then(const F& f) {
f(identity());
}
/*!
* \brief Execute the else part of the statement
* \param f The functor to execute
*/
template <typename F>
void else_(const F& f) {
cpp_unused(f);
}
};
/*!
* \brief Helper for static if
*
* Specialization for condition is false
*/
template <>
struct statement<false> {
/*!
* \brief Execute the if part of the statement
* \param f The functor to execute
*/
template <typename F>
void then(const F& f) {
cpp_unused(f);
}
/*!
* \brief Execute the else part of the statement
* \param f The functor to execute
*/
template <typename F>
void else_(const F& f) {
f(identity());
}
};
} //end of namespace static_if_detail
/*!
* \brief Execute the lambda if the static condition is verified
*
* This should be usd to auto lambda to ensure instantiation is only made for
* the "true" branch
*
* \tparam Cond The static condition
* \param f The lambda to execute if true
* \return a statement object to execute else_ if necessary
*/
template <bool Cond, typename F>
static_if_detail::statement<Cond> static_if(F const& f) {
static_if_detail::statement<Cond> if_;
if_.then(f);
return if_;
}
} //end of namespace cpp
#endif //CPP_STATIC_IF_HPP
<commit_msg>Fix include issue<commit_after>//=======================================================================
// Copyright (c) 2013-2016 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file static_if.hpp
* \brief Contains a C++14 implementation of a poor static if.
*/
#ifndef CPP_STATIC_IF_HPP
#define CPP_STATIC_IF_HPP
#include "assert.hpp" // For cpp_unused
namespace cpp {
namespace static_if_detail {
/*!
* \brief Identify functor
*/
struct identity {
/*!
* \brief Returns exactly what was passsed as argument
*/
template <typename T>
T operator()(T&& x) const {
return std::forward<T>(x);
}
};
/*!
* \brief Helper for static if
*
* This base type is when the condition is true
*/
template <bool Cond>
struct statement {
/*!
* \brief Execute the if part of the statement
* \param f The functor to execute
*/
template <typename F>
void then(const F& f) {
f(identity());
}
/*!
* \brief Execute the else part of the statement
* \param f The functor to execute
*/
template <typename F>
void else_(const F& f) {
cpp_unused(f);
}
};
/*!
* \brief Helper for static if
*
* Specialization for condition is false
*/
template <>
struct statement<false> {
/*!
* \brief Execute the if part of the statement
* \param f The functor to execute
*/
template <typename F>
void then(const F& f) {
cpp_unused(f);
}
/*!
* \brief Execute the else part of the statement
* \param f The functor to execute
*/
template <typename F>
void else_(const F& f) {
f(identity());
}
};
} //end of namespace static_if_detail
/*!
* \brief Execute the lambda if the static condition is verified
*
* This should be usd to auto lambda to ensure instantiation is only made for
* the "true" branch
*
* \tparam Cond The static condition
* \param f The lambda to execute if true
* \return a statement object to execute else_ if necessary
*/
template <bool Cond, typename F>
static_if_detail::statement<Cond> static_if(F const& f) {
static_if_detail::statement<Cond> if_;
if_.then(f);
return if_;
}
} //end of namespace cpp
#endif //CPP_STATIC_IF_HPP
<|endoftext|> |
<commit_before><commit_msg>went back to original slow glue ema<commit_after><|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
#include <vector>
#include <limits>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <dune/common/static_assert.hh>
#include <boost/static_assert.hpp>
#include <boost/fusion/include/void.hpp>
#include <boost/format.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <dune/common/deprecated.hh>
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd && arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd && row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
{}
template < class stl_container_type >
MinMaxAvg( const stl_container_type& elements )
{
dune_static_assert( (boost::is_same< ElementType, typename stl_container_type::value_type >::value),
"cannot assign mismatching types" );
acc_ = std::for_each( elements.begin(), elements.end(), acc_ );
}
ElementType min () const { return boost::accumulators::min(acc_); }
ElementType max () const { return boost::accumulators::max(acc_); }
ElementType average () const { return boost::accumulators::mean(acc_); }
void DUNE_DEPRECATED push( const ElementType& el ) {
acc_( el );
}
void operator()( const ElementType& el ) {
acc_( el );
}
template < class Stream >
void output( Stream& stream ) {
stream << boost::format( "min: %e\tmax: %e\tavg: %e\n" ) % min() % max() % average();
}
protected:
typedef boost::accumulators::stats<
boost::accumulators::tag::max,
boost::accumulators::tag::min,
boost::accumulators::tag::mean >
StatsType;
boost::accumulators::accumulator_set< ElementType,StatsType > acc_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
<commit_msg>adds comparison with abs/rel tolerances<commit_after>#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
#include <vector>
#include <limits>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <dune/common/static_assert.hh>
#include <boost/static_assert.hpp>
#include <boost/fusion/include/void.hpp>
#include <boost/format.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <dune/common/deprecated.hh>
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd && arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd && row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
{}
template < class stl_container_type >
MinMaxAvg( const stl_container_type& elements )
{
dune_static_assert( (boost::is_same< ElementType, typename stl_container_type::value_type >::value),
"cannot assign mismatching types" );
acc_ = std::for_each( elements.begin(), elements.end(), acc_ );
}
ElementType min () const { return boost::accumulators::min(acc_); }
ElementType max () const { return boost::accumulators::max(acc_); }
ElementType average () const { return boost::accumulators::mean(acc_); }
void DUNE_DEPRECATED push( const ElementType& el ) {
acc_( el );
}
void operator()( const ElementType& el ) {
acc_( el );
}
template < class Stream >
void output( Stream& stream ) {
stream << boost::format( "min: %e\tmax: %e\tavg: %e\n" ) % min() % max() % average();
}
protected:
typedef boost::accumulators::stats<
boost::accumulators::tag::max,
boost::accumulators::tag::min,
boost::accumulators::tag::mean >
StatsType;
boost::accumulators::accumulator_set< ElementType,StatsType > acc_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
template < class T >
bool aboutEqual( const T& x, const T& y,
T relative_tolerance = 1e-10,
T absolute_tolerance = 1e-10 )
{
return ( std::fabs (x - y) <=
std::max(absolute_tolerance,
relative_tolerance
* std::max(std::fabs(x), std::fabs(y))) );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
<|endoftext|> |
<commit_before>/**
* \file stuff.hh
* \brief contains some stuff
**/
#ifndef STUFF_MISC_HH_INCLUDED
#define STUFF_MISC_HH_INCLUDED
#include <cstring>
#include <map>
#include <assert.h>
#include <algorithm>
#include <dune/common/fixedarray.hh>
#include "static_assert.hh"
#include <cstddef>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <cerrno>
#include <limits>
#include <string.h>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstdio>
namespace Stuff
{
//! simple and dumb std::string to anything conversion
template < class ReturnType >
ReturnType fromString(const std::string& s)
{
std::stringstream ss;
ss << s;
ReturnType r;
ss >> r;
return r;
}
//! simple and dumb anything to std::string conversion
template < class ReturnType >
std::string toString(const ReturnType& s)
{
std::stringstream ss;
ss << s;
std::string r;
ss >> r;
return r;
}
/** stupid element-index-in-conatiner search
\todo stl implementation?
**/
template < class Container, class Element >
int getIdx( const Container& ct, const Element& e )
{
int idx = 0;
for ( typename Container::const_iterator it = ct.begin(); it != ct.end(); ++it, ++idx )
{
if ( *it == e )
return idx;
}
return -1;
}
//! no idea what this was for
template < typename T >
std::string getParameterString( const std::string& prefix, T min, T max, T inc )
{
std::stringstream ss;
ss << prefix << " ";
for ( ; min < max ; min+=inc ) {
ss << min << ", " ;
}
return ss.str();
}
/** \brief string to AnyType tokenizer
A given string is split according to a list of delimiters. Each token is coerced into class parameter
TokenType and saved in a vector which is exposed via iterator-like mechanism
\see StringTokenizer, a shorthand tyoedef for string to string tokenisation
**/
template < class TokenType >
class Tokenizer {
protected:
typedef std::vector<TokenType>
Tokens;
typedef typename Tokens::iterator
TokenIterator;
public:
Tokenizer( const std::string tokenstring,
const std::string delimiters )
{
//code taken from http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
// Skip delimiters at beginning.
std::string::size_type lastPos = tokenstring.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = tokenstring.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens_.push_back( fromString<TokenType>( tokenstring.substr(lastPos, pos - lastPos) ) );
// Skip delimiters. Note the "not_of"
lastPos = tokenstring.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = tokenstring.find_first_of(delimiters, lastPos);
}
currentToken_ = tokens_.begin();
}
Tokens getTokens() {
return tokens_;
}
bool hasMoreTokens() {
return currentToken_ != tokens_.end();
}
TokenType getNextToken() {
TokenType ret = *currentToken_;
++currentToken_;
return ret;
}
protected:
TokenIterator currentToken_;
Tokens tokens_;
};
typedef Tokenizer<std::string>
StringTokenizer;
//! for backward compat only
template < class ContainerType >
void MergeVector( ContainerType& target, const ContainerType& a )
{
target.insert( target.end(), a.begin(), a.end() );
}
//! stupid timing helper
struct TimeGuard {
const time_t cur_time;
TimeGuard()
:cur_time ( time( NULL ) )
{}
~TimeGuard()
{
time_t delta = time( NULL ) - cur_time;
std::cout << ctime ( &delta ) << std::endl;
}
};
//! \todo seems borked, resutls in gigantic amount of compile errors?!
template < class StlContainer, class T >
void fill_entirely ( StlContainer& c, const T& value )
{
std::fill( c.begin(), c.end(), value );
}
template < class T, int N >
/** this allows subscription indices to wrap around
\example N=4: wraparound_array[4] == wraparound_array[0] && wraparound_array[-1] == wraparound_array[3]
**/
struct wraparound_array : public Dune::array<T,N> {
typedef Dune::array<T,N>
BaseType;
wraparound_array( const BaseType other )
{
for( size_t i = 0; i < N; ++i )
this->operator [](i) = other[i];
}
typename BaseType::reference operator [] (std::size_t i)
{
return BaseType::operator []( i % N );
}
typename BaseType::reference operator [] (int i)
{
std::size_t real_index = i;
if ( i < 0 )
real_index = static_cast<size_t>(N - ( ( ( i * -1 ) % N ) + 1) ) ;
return BaseType::operator []( real_index );
}
typename BaseType::const_reference operator [] (std::size_t i) const
{
return BaseType::operator []( i % N );
}
typename BaseType::const_reference operator [] (int i) const
{
std::size_t real_index = i;
if ( i < 0 )
real_index = static_cast<size_t>(N - ( ( ( i * -1 ) % N ) + 1) ) ;
return BaseType::operator []( real_index );
}
};
//! type safe (this will not compile for degraded-to-pointer arrays) way of getting array length
template <class T, size_t N>
size_t arrayLength (T (&/*array*/) [N]) {
return N;
}
} // end namepspace stuff
#endif // end of stuff.hh
<commit_msg>fix wraparound_array missing ctor<commit_after>/**
* \file stuff.hh
* \brief contains some stuff
**/
#ifndef STUFF_MISC_HH_INCLUDED
#define STUFF_MISC_HH_INCLUDED
#include <cstring>
#include <map>
#include <assert.h>
#include <algorithm>
#include <dune/common/fixedarray.hh>
#include "static_assert.hh"
#include <cstddef>
#include <fstream>
#include <iostream>
#include <ostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <cerrno>
#include <limits>
#include <string.h>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/types.h>
#include <cstdio>
namespace Stuff
{
//! simple and dumb std::string to anything conversion
template < class ReturnType >
ReturnType fromString(const std::string& s)
{
std::stringstream ss;
ss << s;
ReturnType r;
ss >> r;
return r;
}
//! simple and dumb anything to std::string conversion
template < class ReturnType >
std::string toString(const ReturnType& s)
{
std::stringstream ss;
ss << s;
std::string r;
ss >> r;
return r;
}
/** stupid element-index-in-conatiner search
\todo stl implementation?
**/
template < class Container, class Element >
int getIdx( const Container& ct, const Element& e )
{
int idx = 0;
for ( typename Container::const_iterator it = ct.begin(); it != ct.end(); ++it, ++idx )
{
if ( *it == e )
return idx;
}
return -1;
}
//! no idea what this was for
template < typename T >
std::string getParameterString( const std::string& prefix, T min, T max, T inc )
{
std::stringstream ss;
ss << prefix << " ";
for ( ; min < max ; min+=inc ) {
ss << min << ", " ;
}
return ss.str();
}
/** \brief string to AnyType tokenizer
A given string is split according to a list of delimiters. Each token is coerced into class parameter
TokenType and saved in a vector which is exposed via iterator-like mechanism
\see StringTokenizer, a shorthand tyoedef for string to string tokenisation
**/
template < class TokenType >
class Tokenizer {
protected:
typedef std::vector<TokenType>
Tokens;
typedef typename Tokens::iterator
TokenIterator;
public:
Tokenizer( const std::string tokenstring,
const std::string delimiters )
{
//code taken from http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
// Skip delimiters at beginning.
std::string::size_type lastPos = tokenstring.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = tokenstring.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens_.push_back( fromString<TokenType>( tokenstring.substr(lastPos, pos - lastPos) ) );
// Skip delimiters. Note the "not_of"
lastPos = tokenstring.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = tokenstring.find_first_of(delimiters, lastPos);
}
currentToken_ = tokens_.begin();
}
Tokens getTokens() {
return tokens_;
}
bool hasMoreTokens() {
return currentToken_ != tokens_.end();
}
TokenType getNextToken() {
TokenType ret = *currentToken_;
++currentToken_;
return ret;
}
protected:
TokenIterator currentToken_;
Tokens tokens_;
};
typedef Tokenizer<std::string>
StringTokenizer;
//! for backward compat only
template < class ContainerType >
void MergeVector( ContainerType& target, const ContainerType& a )
{
target.insert( target.end(), a.begin(), a.end() );
}
//! stupid timing helper
struct TimeGuard {
const time_t cur_time;
TimeGuard()
:cur_time ( time( NULL ) )
{}
~TimeGuard()
{
time_t delta = time( NULL ) - cur_time;
std::cout << ctime ( &delta ) << std::endl;
}
};
//! \todo seems borked, resutls in gigantic amount of compile errors?!
template < class StlContainer, class T >
void fill_entirely ( StlContainer& c, const T& value )
{
std::fill( c.begin(), c.end(), value );
}
template < class T, int N >
/** this allows subscription indices to wrap around
\example N=4: wraparound_array[4] == wraparound_array[0] && wraparound_array[-1] == wraparound_array[3]
**/
struct wraparound_array : public Dune::array<T,N> {
typedef Dune::array<T,N>
BaseType;
wraparound_array()
{
for( size_t i = 0; i < N; ++i )
this->operator [](i) = T();
}
wraparound_array( const BaseType other )
{
for( size_t i = 0; i < N; ++i )
this->operator [](i) = other[i];
}
typename BaseType::reference operator [] (std::size_t i)
{
return BaseType::operator []( i % N );
}
typename BaseType::reference operator [] (int i)
{
std::size_t real_index = i;
if ( i < 0 )
real_index = static_cast<size_t>(N - ( ( ( i * -1 ) % N ) + 1) ) ;
return BaseType::operator []( real_index );
}
typename BaseType::const_reference operator [] (std::size_t i) const
{
return BaseType::operator []( i % N );
}
typename BaseType::const_reference operator [] (int i) const
{
std::size_t real_index = i;
if ( i < 0 )
real_index = static_cast<size_t>(N - ( ( ( i * -1 ) % N ) + 1) ) ;
return BaseType::operator []( real_index );
}
};
//! type safe (this will not compile for degraded-to-pointer arrays) way of getting array length
template <class T, size_t N>
size_t arrayLength (T (&/*array*/) [N]) {
return N;
}
} // end namepspace stuff
#endif // end of stuff.hh
<|endoftext|> |
<commit_before>#include <boost/interprocess/containers/deque.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/interprocess_fwd.hpp>
#include "mpkeys.h"
#include <sys/statvfs.h>
#include <unordered_map>
#include <sstream>
#include "pin.H"
#include "shared_unordered_map.h"
#include "multiprocess_shared.h"
#include "ipc_queues.h"
#include "BufferManagerProducer.h"
#include "feeder.h"
namespace xiosim
{
namespace buffer_management
{
static void copyProducerToFile(pid_t tid, bool checkSpace);
static void copyProducerToFileReal(pid_t tid, bool checkSpace);
static void copyProducerToFileFake(pid_t tid);
static void writeHandshake(pid_t tid, int fd, handshake_container_t* handshake);
static int getKBFreeSpace(boost::interprocess::string path);
static void reserveHandshake(pid_t tid);
static shm_string genFileName(boost::interprocess::string path);
static std::unordered_map<pid_t, Buffer*> produceBuffer_;
static std::unordered_map<pid_t, int> writeBufferSize_;
static std::unordered_map<pid_t, void*> writeBuffer_;
static vector<boost::interprocess::string> bridgeDirs_;
static boost::interprocess::string gpid_;
void InitBufferManagerProducer(void)
{
InitBufferManager();
produceBuffer_.reserve(MAX_CORES);
writeBufferSize_.reserve(MAX_CORES);
writeBuffer_.reserve(MAX_CORES);
bridgeDirs_.push_back("/dev/shm/");
bridgeDirs_.push_back("/tmp/");
bridgeDirs_.push_back("./");
int pid = getpgrp();
ostringstream iss;
iss << pid;
gpid_ = iss.str().c_str();
assert(gpid_.length() > 0);
cerr << " Creating temp files with prefix " << gpid_ << "_*" << endl;
}
void DeinitBufferManagerProducer()
{
DeinitBufferManager();
for(int i = 0; i < (int)bridgeDirs_.size(); i++) {
boost::interprocess::string cmd = "/bin/rm -rf " + bridgeDirs_[i] + gpid_ + "_* &";
int retVal = system(cmd.c_str());
(void)retVal;
assert(retVal == 0);
}
}
void AllocateThreadProducer(pid_t tid)
{
int bufferCapacity = AllocateThread(tid);
produceBuffer_[tid] = new Buffer(bufferCapacity);
resetPool(tid);
writeBufferSize_[tid] = 4096;
writeBuffer_[tid] = malloc(4096);
assert(writeBuffer_[tid]);
/* send IPC message to allocate consumer-side */
ipc_message_t msg;
msg.BufferManagerAllocateThread(tid, bufferCapacity);
SendIPCMessage(msg);
}
handshake_container_t* back(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
assert(queueSizes_[tid] > 0);
handshake_container_t* returnVal = produceBuffer_[tid]->back();
lk_unlock(&locks_[tid]);
return returnVal;
}
/* On the producer side, get a buffer which we can start
* filling directly.
*/
handshake_container_t* get_buffer(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
// Push is guaranteed to succeed because each call to
// get_buffer() is followed by a call to producer_done()
// which will make space if full
handshake_container_t* result = produceBuffer_[tid]->get_buffer();
produceBuffer_[tid]->push_done();
queueSizes_[tid]++;
assert(pool_[tid] > 0);
pool_[tid]--;
lk_unlock(&locks_[tid]);
return result;
}
/* On the producer side, signal that we are done filling the
* current buffer. If we have ran out of space, make space
* for a new buffer, so get_buffer() cannot fail.
*/
void producer_done(pid_t tid, bool keepLock)
{
lk_lock(&locks_[tid], tid+1);
ASSERTX(!produceBuffer_[tid]->empty());
handshake_container_t* last = produceBuffer_[tid]->back();
ASSERTX(last->flags.valid);
if(!keepLock) {
reserveHandshake(tid);
}
if(produceBuffer_[tid]->full()) {// || ( (consumeBuffer_[tid]->size() == 0) && (fileEntryCount_[tid] == 0))) {
#if defined(DEBUG) || defined(ZESTO_PIN_DBG)
int produceSize = produceBuffer_[tid]->size();
#endif
bool checkSpace = !keepLock;
copyProducerToFile(tid, checkSpace);
assert(fileEntryCount_[tid] > 0);
assert(fileEntryCount_[tid] >= produceSize);
assert(produceBuffer_[tid]->size() == 0);
}
assert(!produceBuffer_[tid]->full());
lk_unlock(&locks_[tid]);
}
/* On the producer side, flush all buffers associated
* with a thread to the backing file.
*/
void flushBuffers(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
if(produceBuffer_[tid]->size() > 0) {
copyProducerToFile(tid, false);
}
lk_unlock(&locks_[tid]);
}
void resetPool(pid_t tid)
{
int poolFactor = 1;
if(KnobNumCores.Value() > 1) {
poolFactor = 6;
}
/* Assume produceBuffer->capacity == consumeBuffer->capacity */
pool_[tid] = (2 * produceBuffer_[tid]->capacity()) * poolFactor;
// pool_[tid] = 2000000000;
}
/* On the producer side, if we have filled up the in-memory
* buffer, wait until some of it gets consumed. If not,
* try and increase the backing file size.
*/
static void reserveHandshake(pid_t tid)
{
int64_t queueLimit;
if(KnobNumCores.Value() > 1) {
queueLimit = 5000000001;
}
else {
queueLimit = 5000000001;
}
if(pool_[tid] > 0) {
return;
}
// while(pool_[tid] == 0) {
while(true) {
assert(queueSizes_[tid] > 0);
lk_unlock(&locks_[tid]);
enable_consumers();
disable_producers();
PIN_Sleep(1000);
lk_lock(&locks_[tid], tid+1);
if(*popped_) {
*popped_ = false;
continue;
}
disable_consumers();
enable_producers();
// if(num_cores == 1 || (!*useRealFile_)) {
// continue;
// }
if(queueSizes_[tid] < queueLimit) {
pool_[tid] += 50000;
#ifdef ZESTO_PIN_DBG
cerr << tid << " [reserveHandshake()]: Increasing file up to " << queueSizes_[tid] + pool_[tid] << endl;
#endif
break;
}
cerr << tid << " [reserveHandshake()]: File size too big to expand, abort():" << queueSizes_[tid] << endl;
abort();
}
}
static void copyProducerToFile(pid_t tid, bool checkSpace)
{
if(*useRealFile_) {
copyProducerToFileReal(tid, checkSpace);
}
else {
copyProducerToFileFake(tid);
}
}
static void copyProducerToFileFake(pid_t tid)
{
while(produceBuffer_[tid]->size() > 0) {
handshake_container_t* handshake = produceBuffer_[tid]->front();
handshake_container_t* handfake = fakeFile_[tid]->get_buffer();
handshake->CopyTo(handfake);
fakeFile_[tid]->push_done();
produceBuffer_[tid]->pop();
fileEntryCount_[tid]++;
}
}
static void copyProducerToFileReal(pid_t tid, bool checkSpace)
{
int result;
bool madeFile = false;
if(checkSpace) {
for(int i = 0; i < (int)bridgeDirs_.size(); i++) {
int space = getKBFreeSpace(bridgeDirs_[i]);
if(space > 2000000) { // 2 GB
fileNames_[tid].push_back(genFileName(bridgeDirs_[i]));
madeFile = true;
break;
}
//cerr << "Out of space on " + bridgeDirs_[i] + " !!!" << endl;
}
if(madeFile == false) {
cerr << "Nowhere left for the poor file bridge :(" << endl;
abort();
}
}
else {
fileNames_[tid].push_back(genFileName(bridgeDirs_[0]));
}
fileCounts_[tid].push_back(0);
int fd = open(fileNames_[tid].back().c_str(), O_WRONLY | O_CREAT, 0777);
if(fd == -1) {
cerr << "Opened to write: " << fileNames_[tid].back();
cerr << "Pipe open error: " << fd << " Errcode:" << strerror(errno) << endl;
abort();
}
while(!produceBuffer_[tid]->empty()) {
writeHandshake(tid, fd, produceBuffer_[tid]->front());
produceBuffer_[tid]->pop();
fileCounts_[tid].back() += 1;
fileEntryCount_[tid]++;
}
result = close(fd);
if(result != 0) {
cerr << "Close error: " << " Errcode:" << strerror(errno) << endl;
abort();
}
// sync() if we put the file somewhere besides /dev/shm
if(fileNames_[tid].back().find("shm") == shm_string::npos) {
sync();
}
assert(produceBuffer_[tid]->size() == 0);
assert(fileEntryCount_[tid] >= 0);
}
static ssize_t do_write(const int fd, const void* buff, const size_t size)
{
ssize_t bytesWritten = 0;
do {
ssize_t res = write(fd, (void*)((char*)buff + bytesWritten), size - bytesWritten);
if(res == -1)
return -1;
bytesWritten += res;
} while (bytesWritten < (ssize_t)size);
return bytesWritten;
}
static void writeHandshake(pid_t tid, int fd, handshake_container_t* handshake)
{
int mapSize = handshake->mem_buffer.size();
const int handshakeBytes = sizeof(P2Z_HANDSHAKE);
const int flagBytes = sizeof(handshake_flags_t);
const int mapEntryBytes = sizeof(UINT32) + sizeof(UINT8);
int mapBytes = mapSize * mapEntryBytes;
int totalBytes = sizeof(int) + handshakeBytes + flagBytes + mapBytes;
assert(totalBytes <= 4096);
void * writeBuffer = writeBuffer_[tid];
void * buffPosition = writeBuffer;
memcpy((char*)buffPosition, &(mapSize), sizeof(int));
buffPosition = (char*)buffPosition + sizeof(int);
memcpy((char*)buffPosition, &(handshake->handshake), handshakeBytes);
buffPosition = (char*)buffPosition + handshakeBytes;
memcpy((char*)buffPosition, &(handshake->flags), flagBytes);
buffPosition = (char*)buffPosition + flagBytes;
std::map<UINT32, UINT8>::iterator it;
for(it = handshake->mem_buffer.begin(); it != handshake->mem_buffer.end(); it++) {
memcpy((char*)buffPosition, &(it->first), sizeof(UINT32));
buffPosition = (char*)buffPosition + sizeof(UINT32);
memcpy((char*)buffPosition, &(it->second), sizeof(UINT8));
buffPosition = (char*)buffPosition + sizeof(UINT8);
}
assert(((unsigned long long int)writeBuffer) + totalBytes == ((unsigned long long int)buffPosition));
int bytesWritten = do_write(fd, writeBuffer, totalBytes);
if(bytesWritten == -1) {
cerr << "Pipe write error: " << bytesWritten << " Errcode:" << strerror(errno) << endl;
abort();
}
if(bytesWritten != totalBytes) {
cerr << "File write error: " << bytesWritten << " expected:" << totalBytes << endl;
cerr << fileNames_[tid].back() << endl;
abort();
}
}
static int getKBFreeSpace(boost::interprocess::string path)
{
struct statvfs fsinfo;
statvfs(path.c_str(), &fsinfo);
return (fsinfo.f_bsize * fsinfo.f_bfree / 1024);
}
static shm_string genFileName(boost::interprocess::string path)
{
char* temp = tempnam(path.c_str(), gpid_.c_str());
boost::interprocess::string res = boost::interprocess::string(temp);
assert(res.find(path) != boost::interprocess::string::npos);
res.insert(path.length() + gpid_.length(), "_");
res = res + ".helix";
shm_string shared_res(res.c_str(), global_shm->get_allocator<void>());
free(temp);
return shared_res;
}
}
}
<commit_msg>Change /dev/shm file extension for easier cleaning.<commit_after>#include <boost/interprocess/containers/deque.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/interprocess_fwd.hpp>
#include "mpkeys.h"
#include <sys/statvfs.h>
#include <unordered_map>
#include <sstream>
#include "pin.H"
#include "shared_unordered_map.h"
#include "multiprocess_shared.h"
#include "ipc_queues.h"
#include "BufferManagerProducer.h"
#include "feeder.h"
namespace xiosim
{
namespace buffer_management
{
static void copyProducerToFile(pid_t tid, bool checkSpace);
static void copyProducerToFileReal(pid_t tid, bool checkSpace);
static void copyProducerToFileFake(pid_t tid);
static void writeHandshake(pid_t tid, int fd, handshake_container_t* handshake);
static int getKBFreeSpace(boost::interprocess::string path);
static void reserveHandshake(pid_t tid);
static shm_string genFileName(boost::interprocess::string path);
static std::unordered_map<pid_t, Buffer*> produceBuffer_;
static std::unordered_map<pid_t, int> writeBufferSize_;
static std::unordered_map<pid_t, void*> writeBuffer_;
static vector<boost::interprocess::string> bridgeDirs_;
static boost::interprocess::string gpid_;
void InitBufferManagerProducer(void)
{
InitBufferManager();
produceBuffer_.reserve(MAX_CORES);
writeBufferSize_.reserve(MAX_CORES);
writeBuffer_.reserve(MAX_CORES);
bridgeDirs_.push_back("/dev/shm/");
bridgeDirs_.push_back("/tmp/");
bridgeDirs_.push_back("./");
int pid = getpgrp();
ostringstream iss;
iss << pid;
gpid_ = iss.str().c_str();
assert(gpid_.length() > 0);
cerr << " Creating temp files with prefix " << gpid_ << "_*" << endl;
}
void DeinitBufferManagerProducer()
{
DeinitBufferManager();
for(int i = 0; i < (int)bridgeDirs_.size(); i++) {
boost::interprocess::string cmd = "/bin/rm -rf " + bridgeDirs_[i] + gpid_ + "_* &";
int retVal = system(cmd.c_str());
(void)retVal;
assert(retVal == 0);
}
}
void AllocateThreadProducer(pid_t tid)
{
int bufferCapacity = AllocateThread(tid);
produceBuffer_[tid] = new Buffer(bufferCapacity);
resetPool(tid);
writeBufferSize_[tid] = 4096;
writeBuffer_[tid] = malloc(4096);
assert(writeBuffer_[tid]);
/* send IPC message to allocate consumer-side */
ipc_message_t msg;
msg.BufferManagerAllocateThread(tid, bufferCapacity);
SendIPCMessage(msg);
}
handshake_container_t* back(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
assert(queueSizes_[tid] > 0);
handshake_container_t* returnVal = produceBuffer_[tid]->back();
lk_unlock(&locks_[tid]);
return returnVal;
}
/* On the producer side, get a buffer which we can start
* filling directly.
*/
handshake_container_t* get_buffer(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
// Push is guaranteed to succeed because each call to
// get_buffer() is followed by a call to producer_done()
// which will make space if full
handshake_container_t* result = produceBuffer_[tid]->get_buffer();
produceBuffer_[tid]->push_done();
queueSizes_[tid]++;
assert(pool_[tid] > 0);
pool_[tid]--;
lk_unlock(&locks_[tid]);
return result;
}
/* On the producer side, signal that we are done filling the
* current buffer. If we have ran out of space, make space
* for a new buffer, so get_buffer() cannot fail.
*/
void producer_done(pid_t tid, bool keepLock)
{
lk_lock(&locks_[tid], tid+1);
ASSERTX(!produceBuffer_[tid]->empty());
handshake_container_t* last = produceBuffer_[tid]->back();
ASSERTX(last->flags.valid);
if(!keepLock) {
reserveHandshake(tid);
}
if(produceBuffer_[tid]->full()) {// || ( (consumeBuffer_[tid]->size() == 0) && (fileEntryCount_[tid] == 0))) {
#if defined(DEBUG) || defined(ZESTO_PIN_DBG)
int produceSize = produceBuffer_[tid]->size();
#endif
bool checkSpace = !keepLock;
copyProducerToFile(tid, checkSpace);
assert(fileEntryCount_[tid] > 0);
assert(fileEntryCount_[tid] >= produceSize);
assert(produceBuffer_[tid]->size() == 0);
}
assert(!produceBuffer_[tid]->full());
lk_unlock(&locks_[tid]);
}
/* On the producer side, flush all buffers associated
* with a thread to the backing file.
*/
void flushBuffers(pid_t tid)
{
lk_lock(&locks_[tid], tid+1);
if(produceBuffer_[tid]->size() > 0) {
copyProducerToFile(tid, false);
}
lk_unlock(&locks_[tid]);
}
void resetPool(pid_t tid)
{
int poolFactor = 1;
if(KnobNumCores.Value() > 1) {
poolFactor = 6;
}
/* Assume produceBuffer->capacity == consumeBuffer->capacity */
pool_[tid] = (2 * produceBuffer_[tid]->capacity()) * poolFactor;
// pool_[tid] = 2000000000;
}
/* On the producer side, if we have filled up the in-memory
* buffer, wait until some of it gets consumed. If not,
* try and increase the backing file size.
*/
static void reserveHandshake(pid_t tid)
{
int64_t queueLimit;
if(KnobNumCores.Value() > 1) {
queueLimit = 5000000001;
}
else {
queueLimit = 5000000001;
}
if(pool_[tid] > 0) {
return;
}
// while(pool_[tid] == 0) {
while(true) {
assert(queueSizes_[tid] > 0);
lk_unlock(&locks_[tid]);
enable_consumers();
disable_producers();
PIN_Sleep(1000);
lk_lock(&locks_[tid], tid+1);
if(*popped_) {
*popped_ = false;
continue;
}
disable_consumers();
enable_producers();
// if(num_cores == 1 || (!*useRealFile_)) {
// continue;
// }
if(queueSizes_[tid] < queueLimit) {
pool_[tid] += 50000;
#ifdef ZESTO_PIN_DBG
cerr << tid << " [reserveHandshake()]: Increasing file up to " << queueSizes_[tid] + pool_[tid] << endl;
#endif
break;
}
cerr << tid << " [reserveHandshake()]: File size too big to expand, abort():" << queueSizes_[tid] << endl;
abort();
}
}
static void copyProducerToFile(pid_t tid, bool checkSpace)
{
if(*useRealFile_) {
copyProducerToFileReal(tid, checkSpace);
}
else {
copyProducerToFileFake(tid);
}
}
static void copyProducerToFileFake(pid_t tid)
{
while(produceBuffer_[tid]->size() > 0) {
handshake_container_t* handshake = produceBuffer_[tid]->front();
handshake_container_t* handfake = fakeFile_[tid]->get_buffer();
handshake->CopyTo(handfake);
fakeFile_[tid]->push_done();
produceBuffer_[tid]->pop();
fileEntryCount_[tid]++;
}
}
static void copyProducerToFileReal(pid_t tid, bool checkSpace)
{
int result;
bool madeFile = false;
if(checkSpace) {
for(int i = 0; i < (int)bridgeDirs_.size(); i++) {
int space = getKBFreeSpace(bridgeDirs_[i]);
if(space > 2000000) { // 2 GB
fileNames_[tid].push_back(genFileName(bridgeDirs_[i]));
madeFile = true;
break;
}
//cerr << "Out of space on " + bridgeDirs_[i] + " !!!" << endl;
}
if(madeFile == false) {
cerr << "Nowhere left for the poor file bridge :(" << endl;
abort();
}
}
else {
fileNames_[tid].push_back(genFileName(bridgeDirs_[0]));
}
fileCounts_[tid].push_back(0);
int fd = open(fileNames_[tid].back().c_str(), O_WRONLY | O_CREAT, 0777);
if(fd == -1) {
cerr << "Opened to write: " << fileNames_[tid].back();
cerr << "Pipe open error: " << fd << " Errcode:" << strerror(errno) << endl;
abort();
}
while(!produceBuffer_[tid]->empty()) {
writeHandshake(tid, fd, produceBuffer_[tid]->front());
produceBuffer_[tid]->pop();
fileCounts_[tid].back() += 1;
fileEntryCount_[tid]++;
}
result = close(fd);
if(result != 0) {
cerr << "Close error: " << " Errcode:" << strerror(errno) << endl;
abort();
}
// sync() if we put the file somewhere besides /dev/shm
if(fileNames_[tid].back().find("shm") == shm_string::npos) {
sync();
}
assert(produceBuffer_[tid]->size() == 0);
assert(fileEntryCount_[tid] >= 0);
}
static ssize_t do_write(const int fd, const void* buff, const size_t size)
{
ssize_t bytesWritten = 0;
do {
ssize_t res = write(fd, (void*)((char*)buff + bytesWritten), size - bytesWritten);
if(res == -1)
return -1;
bytesWritten += res;
} while (bytesWritten < (ssize_t)size);
return bytesWritten;
}
static void writeHandshake(pid_t tid, int fd, handshake_container_t* handshake)
{
int mapSize = handshake->mem_buffer.size();
const int handshakeBytes = sizeof(P2Z_HANDSHAKE);
const int flagBytes = sizeof(handshake_flags_t);
const int mapEntryBytes = sizeof(UINT32) + sizeof(UINT8);
int mapBytes = mapSize * mapEntryBytes;
int totalBytes = sizeof(int) + handshakeBytes + flagBytes + mapBytes;
assert(totalBytes <= 4096);
void * writeBuffer = writeBuffer_[tid];
void * buffPosition = writeBuffer;
memcpy((char*)buffPosition, &(mapSize), sizeof(int));
buffPosition = (char*)buffPosition + sizeof(int);
memcpy((char*)buffPosition, &(handshake->handshake), handshakeBytes);
buffPosition = (char*)buffPosition + handshakeBytes;
memcpy((char*)buffPosition, &(handshake->flags), flagBytes);
buffPosition = (char*)buffPosition + flagBytes;
std::map<UINT32, UINT8>::iterator it;
for(it = handshake->mem_buffer.begin(); it != handshake->mem_buffer.end(); it++) {
memcpy((char*)buffPosition, &(it->first), sizeof(UINT32));
buffPosition = (char*)buffPosition + sizeof(UINT32);
memcpy((char*)buffPosition, &(it->second), sizeof(UINT8));
buffPosition = (char*)buffPosition + sizeof(UINT8);
}
assert(((unsigned long long int)writeBuffer) + totalBytes == ((unsigned long long int)buffPosition));
int bytesWritten = do_write(fd, writeBuffer, totalBytes);
if(bytesWritten == -1) {
cerr << "Pipe write error: " << bytesWritten << " Errcode:" << strerror(errno) << endl;
abort();
}
if(bytesWritten != totalBytes) {
cerr << "File write error: " << bytesWritten << " expected:" << totalBytes << endl;
cerr << fileNames_[tid].back() << endl;
abort();
}
}
static int getKBFreeSpace(boost::interprocess::string path)
{
struct statvfs fsinfo;
statvfs(path.c_str(), &fsinfo);
return (fsinfo.f_bsize * fsinfo.f_bfree / 1024);
}
static shm_string genFileName(boost::interprocess::string path)
{
char* temp = tempnam(path.c_str(), gpid_.c_str());
boost::interprocess::string res = boost::interprocess::string(temp);
assert(res.find(path) != boost::interprocess::string::npos);
res.insert(path.length() + gpid_.length(), "_");
res = res + ".xiosim";
shm_string shared_res(res.c_str(), global_shm->get_allocator<void>());
free(temp);
return shared_res;
}
}
}
<|endoftext|> |
<commit_before>#ifndef ITER_TAKEWHILE_H_
#define ITER_TAKEWHILE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
//Forward declarations of TakeWhile and takewhile
template <typename FilterFunc, typename Container>
class TakeWhile;
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class TakeWhile {
private:
Container container;
FilterFunc filter_func;
friend TakeWhile takewhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend TakeWhile<FF, std::initializer_list<T>> takewhile(
FF, std::initializer_list<T>);
// Value constructor for use only in the takewhile function
TakeWhile(FilterFunc filter_func, Container container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
using iter_type = iterator_type<Container>;
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
FilterFunc filter_func;
void check_current() {
if (!this->filter_func(*this->sub_iter)) {
this->sub_iter = this->sub_end;
}
}
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
if (this->sub_iter != this->sub_end) {
// only do the check if not already at the end
this->check_current();
}
}
iterator_deref<Container> operator*() {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
this->check_current();
return *this;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
// Helper function to instantiate a TakeWhile
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif
<commit_msg>adds takewhile iter postfix ++ and ==<commit_after>#ifndef ITER_TAKEWHILE_H_
#define ITER_TAKEWHILE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
//Forward declarations of TakeWhile and takewhile
template <typename FilterFunc, typename Container>
class TakeWhile;
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class TakeWhile {
private:
Container container;
FilterFunc filter_func;
friend TakeWhile takewhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend TakeWhile<FF, std::initializer_list<T>> takewhile(
FF, std::initializer_list<T>);
TakeWhile(FilterFunc filter_func, Container container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
FilterFunc filter_func;
void check_current() {
if (!this->filter_func(*this->sub_iter)) {
this->sub_iter = this->sub_end;
}
}
public:
Iterator(iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
if (this->sub_iter != this->sub_end) {
// only do the check if not already at the end
this->check_current();
}
}
iterator_deref<Container> operator*() {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
this->check_current();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif
<|endoftext|> |
<commit_before>#include "CollectionInterval.hpp"
#include "MainLoop.hpp"
#include "NotifyStatusInfo.hpp"
#include "common/PlayerRuntimeError.hpp"
#include "common/dt/DateTime.hpp"
#include "common/dt/Timer.hpp"
#include "common/fs/FileSystem.hpp"
#include "common/fs/StorageUsageInfo.hpp"
#include "common/logger/Logging.hpp"
#include "common/logger/XmlLogsRetriever.hpp"
#include "common/storage/FileCache.hpp"
#include "common/system/System.hpp"
#include "config/AppConfig.hpp"
#include "cms/xmds/XmdsRequestSender.hpp"
#include "stat/Recorder.hpp"
#include "stat/records/XmlFormatter.hpp"
namespace ph = std::placeholders;
CollectionInterval::CollectionInterval(XmdsRequestSender& xmdsSender,
Stats::Recorder& statsRecorder,
FileCache& fileCache,
const FilePath& resourceDirectory) :
xmdsSender_{xmdsSender},
statsRecorder_{statsRecorder},
fileCache_{fileCache},
intervalTimer_{std::make_unique<Timer>()},
collectInterval_{DefaultInterval},
running_{false},
status_{},
currentLayoutId_{EmptyLayoutId},
resourceDirectory_{resourceDirectory}
{
assert(intervalTimer_);
}
bool CollectionInterval::running() const
{
return running_;
}
void CollectionInterval::stop()
{
workerThread_.reset();
}
void CollectionInterval::startTimer()
{
intervalTimer_->startOnce(std::chrono::seconds(collectInterval_), [this]() { collectNow(); });
}
void CollectionInterval::collectNow()
{
if (!running_)
{
running_ = true;
workerThread_ = std::make_unique<JoinableThread>([=]() {
Log::debug("[CollectionInterval] Started");
auto registerDisplayResult =
xmdsSender_.registerDisplay(AppConfig::codeVersion(), AppConfig::releaseVersion(), "Display").get();
onDisplayRegistered(registerDisplayResult);
});
}
}
void CollectionInterval::sessionFinished(const PlayerError& error)
{
running_ = false;
startTimer();
Log::debug("[CollectionInterval] Finished. Next collection will start in {} seconds", collectInterval_);
MainLoop::pushToUiThread([this, error]() { collectionFinished_(error); });
}
void CollectionInterval::onDisplayRegistered(const ResponseResult<RegisterDisplay::Result>& registerDisplay)
{
auto [error, result] = registerDisplay;
if (!error)
{
auto displayError = displayStatus(result.status);
if (!displayError)
{
Log::debug("[XMDS::RegisterDisplay] Success");
status_.registered = true;
status_.lastChecked = DateTime::now();
MainLoop::pushToUiThread([this, result = std::move(result.playerSettings)]() { settingsUpdated_(result); });
auto requiredFilesResult = xmdsSender_.requiredFiles().get();
auto scheduleResult = xmdsSender_.schedule().get();
onSchedule(scheduleResult);
onRequiredFiles(requiredFilesResult);
submitLogs();
submitStats();
notifyStatus();
}
sessionFinished(displayError);
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::setCurrentLayoutId(const LayoutId& currentLayoutId)
{
currentLayoutId_ = currentLayoutId;
}
PlayerError CollectionInterval::displayStatus(const RegisterDisplay::Result::Status& status)
{
using DisplayCode = RegisterDisplay::Result::Status::Code;
switch (status.code)
{
case DisplayCode::Ready: return {};
case DisplayCode::Added:
case DisplayCode::Waiting: return {"CMS", status.message};
default: return {"CMS", "Unknown error with RegisterDisplay"};
}
}
void CollectionInterval::updateInterval(int collectInterval)
{
if (collectInterval_ != collectInterval)
{
Log::debug("[CollectionInterval] Interval updated to {} seconds", collectInterval);
collectInterval_ = collectInterval;
}
}
// TODO potential data race here
CmsStatus CollectionInterval::status() const
{
return status_;
}
SignalSettingsUpdated& CollectionInterval::settingsUpdated()
{
return settingsUpdated_;
}
SignalScheduleAvailable& CollectionInterval::scheduleAvailable()
{
return scheduleAvailable_;
}
SignalCollectionFinished& CollectionInterval::collectionFinished()
{
return collectionFinished_;
}
SignalFilesDownloaded& CollectionInterval::filesDownloaded()
{
return filesDownloaded_;
}
void CollectionInterval::onRequiredFiles(const ResponseResult<RequiredFiles::Result>& requiredFiles)
{
auto [error, result] = requiredFiles;
if (!error)
{
Log::debug("[XMDS::RequiredFiles] Received");
RequiredFilesDownloader downloader{xmdsSender_, fileCache_};
auto&& files = result.requiredFiles();
auto&& resources = result.requiredResources();
status_.requiredFiles = files.size() + resources.size();
auto resourcesResult = downloader.download(resources);
auto filesResult = downloader.download(files);
resourcesResult.wait();
filesResult.wait();
updateMediaInventory(result);
MainLoop::pushToUiThread([this]() { filesDownloaded_(); });
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::updateMediaInventory(const RequiredFiles::Result& result)
{
MediaInventoryItems items;
for (auto&& file : result.requiredFiles())
{
items.emplace_back(file, fileCache_.valid(file.name()));
}
for (auto&& file : result.requiredResources())
{
items.emplace_back(file, fileCache_.valid(file.name()));
}
onSubmitted("MediaInventory", xmdsSender_.mediaInventory(std::move(items)).get());
}
void CollectionInterval::onSchedule(const ResponseResult<Schedule::Result>& schedule)
{
auto [error, result] = schedule;
if (!error)
{
Log::debug("[XMDS::Schedule] Received");
MainLoop::pushToUiThread([this, result = std::move(result)]() {
scheduleAvailable_(LayoutSchedule::fromString(result.scheduleXml));
});
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::submitLogs()
{
XmlLogsRetriever logsRetriever;
auto submitLogsResult = xmdsSender_.submitLogs(logsRetriever.retrieveLogs()).get();
onSubmitted("SubmitLogs", submitLogsResult);
}
void CollectionInterval::submitStats()
{
try
{
const auto recordsCount = statsRecorder_.recordsCount();
if (recordsCount > 0)
{
const auto RecordsToSend = [recordsCount]() -> size_t {
if (recordsCount > 500)
return 300;
else
return recordsCount > 50 ? 50 : recordsCount;
}();
Log::debug("[CollectionInterval] Total records: {} Records to send {}", recordsCount, RecordsToSend);
auto records = statsRecorder_.records(RecordsToSend);
statsRecorder_.removeFromQueue(RecordsToSend);
Stats::XmlFormatter formatter;
auto submitStatsResult = xmdsSender_.submitStats(formatter.format(records)).get();
onSubmitted("SubmitStats", submitStatsResult);
}
}
catch (const std::exception& e)
{
Log::error(e.what());
Log::error("[CollectionInterval] Failed to submit stats", e.what());
}
}
void CollectionInterval::notifyStatus()
{
NotifyStatusInfo notifyInfo;
// FIXME: store it in collection interval until XMDS refactoring
notifyInfo.currentLayoutId = currentLayoutId_;
notifyInfo.deviceName = System::hostname();
notifyInfo.spaceUsageInfo = FileSystem::storageUsageFor(resourceDirectory_);
notifyInfo.timezone = DateTime::currentTimezone();
auto notifyStatusResult = xmdsSender_.notifyStatus(notifyInfo.string()).get();
onSubmitted("NotifyStatus", notifyStatusResult);
}
template <typename Result>
void CollectionInterval::onSubmitted(std::string_view requestName, const ResponseResult<Result>& submitResult)
{
auto [error, result] = submitResult;
if (!error)
{
if (result.success)
{
Log::debug("[XMDS::{}] Submitted", requestName);
}
else
{
Log::error("[XMDS::{}] Not submited due to unknown error", requestName);
}
}
else
{
sessionFinished(error);
}
}
<commit_msg>fix: remove unused param in log message<commit_after>#include "CollectionInterval.hpp"
#include "MainLoop.hpp"
#include "NotifyStatusInfo.hpp"
#include "common/PlayerRuntimeError.hpp"
#include "common/dt/DateTime.hpp"
#include "common/dt/Timer.hpp"
#include "common/fs/FileSystem.hpp"
#include "common/fs/StorageUsageInfo.hpp"
#include "common/logger/Logging.hpp"
#include "common/logger/XmlLogsRetriever.hpp"
#include "common/storage/FileCache.hpp"
#include "common/system/System.hpp"
#include "config/AppConfig.hpp"
#include "cms/xmds/XmdsRequestSender.hpp"
#include "stat/Recorder.hpp"
#include "stat/records/XmlFormatter.hpp"
namespace ph = std::placeholders;
CollectionInterval::CollectionInterval(XmdsRequestSender& xmdsSender,
Stats::Recorder& statsRecorder,
FileCache& fileCache,
const FilePath& resourceDirectory) :
xmdsSender_{xmdsSender},
statsRecorder_{statsRecorder},
fileCache_{fileCache},
intervalTimer_{std::make_unique<Timer>()},
collectInterval_{DefaultInterval},
running_{false},
status_{},
currentLayoutId_{EmptyLayoutId},
resourceDirectory_{resourceDirectory}
{
assert(intervalTimer_);
}
bool CollectionInterval::running() const
{
return running_;
}
void CollectionInterval::stop()
{
workerThread_.reset();
}
void CollectionInterval::startTimer()
{
intervalTimer_->startOnce(std::chrono::seconds(collectInterval_), [this]() { collectNow(); });
}
void CollectionInterval::collectNow()
{
if (!running_)
{
running_ = true;
workerThread_ = std::make_unique<JoinableThread>([=]() {
Log::debug("[CollectionInterval] Started");
auto registerDisplayResult =
xmdsSender_.registerDisplay(AppConfig::codeVersion(), AppConfig::releaseVersion(), "Display").get();
onDisplayRegistered(registerDisplayResult);
});
}
}
void CollectionInterval::sessionFinished(const PlayerError& error)
{
running_ = false;
startTimer();
Log::debug("[CollectionInterval] Finished. Next collection will start in {} seconds", collectInterval_);
MainLoop::pushToUiThread([this, error]() { collectionFinished_(error); });
}
void CollectionInterval::onDisplayRegistered(const ResponseResult<RegisterDisplay::Result>& registerDisplay)
{
auto [error, result] = registerDisplay;
if (!error)
{
auto displayError = displayStatus(result.status);
if (!displayError)
{
Log::debug("[XMDS::RegisterDisplay] Success");
status_.registered = true;
status_.lastChecked = DateTime::now();
MainLoop::pushToUiThread([this, result = std::move(result.playerSettings)]() { settingsUpdated_(result); });
auto requiredFilesResult = xmdsSender_.requiredFiles().get();
auto scheduleResult = xmdsSender_.schedule().get();
onSchedule(scheduleResult);
onRequiredFiles(requiredFilesResult);
submitLogs();
submitStats();
notifyStatus();
}
sessionFinished(displayError);
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::setCurrentLayoutId(const LayoutId& currentLayoutId)
{
currentLayoutId_ = currentLayoutId;
}
PlayerError CollectionInterval::displayStatus(const RegisterDisplay::Result::Status& status)
{
using DisplayCode = RegisterDisplay::Result::Status::Code;
switch (status.code)
{
case DisplayCode::Ready: return {};
case DisplayCode::Added:
case DisplayCode::Waiting: return {"CMS", status.message};
default: return {"CMS", "Unknown error with RegisterDisplay"};
}
}
void CollectionInterval::updateInterval(int collectInterval)
{
if (collectInterval_ != collectInterval)
{
Log::debug("[CollectionInterval] Interval updated to {} seconds", collectInterval);
collectInterval_ = collectInterval;
}
}
// TODO potential data race here
CmsStatus CollectionInterval::status() const
{
return status_;
}
SignalSettingsUpdated& CollectionInterval::settingsUpdated()
{
return settingsUpdated_;
}
SignalScheduleAvailable& CollectionInterval::scheduleAvailable()
{
return scheduleAvailable_;
}
SignalCollectionFinished& CollectionInterval::collectionFinished()
{
return collectionFinished_;
}
SignalFilesDownloaded& CollectionInterval::filesDownloaded()
{
return filesDownloaded_;
}
void CollectionInterval::onRequiredFiles(const ResponseResult<RequiredFiles::Result>& requiredFiles)
{
auto [error, result] = requiredFiles;
if (!error)
{
Log::debug("[XMDS::RequiredFiles] Received");
RequiredFilesDownloader downloader{xmdsSender_, fileCache_};
auto&& files = result.requiredFiles();
auto&& resources = result.requiredResources();
status_.requiredFiles = files.size() + resources.size();
auto resourcesResult = downloader.download(resources);
auto filesResult = downloader.download(files);
resourcesResult.wait();
filesResult.wait();
updateMediaInventory(result);
MainLoop::pushToUiThread([this]() { filesDownloaded_(); });
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::updateMediaInventory(const RequiredFiles::Result& result)
{
MediaInventoryItems items;
for (auto&& file : result.requiredFiles())
{
items.emplace_back(file, fileCache_.valid(file.name()));
}
for (auto&& file : result.requiredResources())
{
items.emplace_back(file, fileCache_.valid(file.name()));
}
onSubmitted("MediaInventory", xmdsSender_.mediaInventory(std::move(items)).get());
}
void CollectionInterval::onSchedule(const ResponseResult<Schedule::Result>& schedule)
{
auto [error, result] = schedule;
if (!error)
{
Log::debug("[XMDS::Schedule] Received");
MainLoop::pushToUiThread([this, result = std::move(result)]() {
scheduleAvailable_(LayoutSchedule::fromString(result.scheduleXml));
});
}
else
{
sessionFinished(error);
}
}
void CollectionInterval::submitLogs()
{
XmlLogsRetriever logsRetriever;
auto submitLogsResult = xmdsSender_.submitLogs(logsRetriever.retrieveLogs()).get();
onSubmitted("SubmitLogs", submitLogsResult);
}
void CollectionInterval::submitStats()
{
try
{
const auto recordsCount = statsRecorder_.recordsCount();
if (recordsCount > 0)
{
const auto RecordsToSend = [recordsCount]() -> size_t {
if (recordsCount > 500)
return 300;
else
return recordsCount > 50 ? 50 : recordsCount;
}();
Log::debug("[CollectionInterval] Total records: {} Records to send {}", recordsCount, RecordsToSend);
auto records = statsRecorder_.records(RecordsToSend);
statsRecorder_.removeFromQueue(RecordsToSend);
Stats::XmlFormatter formatter;
auto submitStatsResult = xmdsSender_.submitStats(formatter.format(records)).get();
onSubmitted("SubmitStats", submitStatsResult);
}
}
catch (const std::exception& e)
{
Log::error(e.what());
Log::error("[CollectionInterval] Failed to submit stats");
}
}
void CollectionInterval::notifyStatus()
{
NotifyStatusInfo notifyInfo;
// FIXME: store it in collection interval until XMDS refactoring
notifyInfo.currentLayoutId = currentLayoutId_;
notifyInfo.deviceName = System::hostname();
notifyInfo.spaceUsageInfo = FileSystem::storageUsageFor(resourceDirectory_);
notifyInfo.timezone = DateTime::currentTimezone();
auto notifyStatusResult = xmdsSender_.notifyStatus(notifyInfo.string()).get();
onSubmitted("NotifyStatus", notifyStatusResult);
}
template <typename Result>
void CollectionInterval::onSubmitted(std::string_view requestName, const ResponseResult<Result>& submitResult)
{
auto [error, result] = submitResult;
if (!error)
{
if (result.success)
{
Log::debug("[XMDS::{}] Submitted", requestName);
}
else
{
Log::error("[XMDS::{}] Not submited due to unknown error", requestName);
}
}
else
{
sessionFinished(error);
}
}
<|endoftext|> |
<commit_before>#ifndef CLOTHO_BIT_WALKER_HPP_
#define CLOTHO_BIT_WALKER_HPP_
#include "clotho/utility/set_bit_node.h"
namespace clotho {
namespace utility {
template < unsigned int B >
class bit_block_walker;
template < >
class bit_block_walker< 8 > : public set_bit_node_array {
public:
typedef unsigned char block_type;
static const unsigned int max_nodes = 256; // 2^8
protected:
static set_bit_node m_nodes[ max_nodes ];
static bool init() {
static bool is_init = init_array( m_nodes, max_nodes );
return _is_init;
}
};
template < >
class bit_block_walker< 16 > : public set_bit_node_array {
public:
typedef unsigned short block_type;
static const unsigned int max_nodes = 256 * 256; // 2^16
protected:
static set_bit_node m_nodes[ max_nodes ];
static bool init() {
static bool _is_init = init_array(m_nodes, max_nodes);
return _is_init;
}
};
template < unsigned int U >
class sub_block_walker;
template <>
class sub_block_walker< 1 > {
};
template <>
class sub_block_walker< 2 > {
};
template <>
class sub_block_walker< 4 > {
public:
template < class Block, class OP >
static void apply(
};
template < class Block, class SubBlock >
class block_walker {
public:
typedef Block block_type;
typedef SubBlock sub_block_type;
typedef sub_block_walker< sizeof(Block) / sizeof(SubBlock) > sub_walker_type;
template < class OP >
static void apply( block_type _bits, OP oper ) {
sub_walker_type::apply( _bits, oper );
}
};
} // namespace utility {
} // namespace clotho {
#endif // CLOTHO_BIT_WALKER_HPP_
<commit_msg>Finished walking algorithms<commit_after>#ifndef CLOTHO_BIT_WALKER_HPP_
#define CLOTHO_BIT_WALKER_HPP_
#include <iostream>
#include <cassert>
#include "clotho/utility/set_bit_node.h"
namespace clotho {
namespace utility {
template < unsigned int B >
class bit_block_walker {
public:
typedef size_t walkable_block_type;
static const unsigned int bits_per_block = B;
template < class OP >
void operator()( walkable_block_type _bits, OP & oper, unsigned int offset = 0 ) {
if( !_bits ) return;
unsigned int i = B, j = offset;
while( i-- ) {
if( _bits & 1 ) {
oper( j );
}
_bits >>= 1;
++j;
}
}
};
template < >
class bit_block_walker< 8 > {
public:
typedef unsigned char walkable_block_type;
static const unsigned int bits_per_block = 8;
static const unsigned int max_nodes = 256; // 2^8
static set_bit_node (&getNode())[ max_nodes ] {
static bool i = node_array_initializer::init_array( m_nodes, max_nodes );
return m_nodes;
}
template < class OP >
void operator()( walkable_block_type _bits, OP & oper, unsigned int offset = 0 ) {
if( !_bits ) return;
set_bit_node * v = getNode() + _bits;
do {
oper( offset + v->bit_index );
if( v->next == 0 ) break;
offset += v->bit_shift_next;
v = getNode() + v->next;
} while( true );
}
protected:
static set_bit_node m_nodes[ max_nodes ];
};
set_bit_node bit_block_walker< 8 >::m_nodes[ bit_block_walker< 8 >::max_nodes ];
template < >
class bit_block_walker< 16 > {
public:
typedef unsigned short walkable_block_type;
static const unsigned int bits_per_block = 16;
static const unsigned int max_nodes = 256 * 256; // 2^16
static set_bit_node (&getNode())[ max_nodes ] {
static bool i = node_array_initializer::init_array(m_nodes, max_nodes);
return m_nodes;
}
template < class OP >
void operator()( walkable_block_type _bits, OP & oper, unsigned int offset = 0 ) {
if( !_bits ) return;
set_bit_node * v = getNode() + _bits;
do {
oper( offset + v->bit_index );
if( v->next == 0 ) break;
offset += v->bit_shift_next;
v = getNode() + v->next;
} while( true );
}
protected:
static set_bit_node m_nodes[ max_nodes ];
};
set_bit_node bit_block_walker< 16 >::m_nodes[ bit_block_walker< 16 >::max_nodes ];
template < class Block, class SubBlock >
class block_walker {
public:
typedef Block block_type;
typedef SubBlock sub_block_type;
static const unsigned int bits_per_block = sizeof( block_type ) * 8;
static const unsigned int bits_per_subblock = sizeof( sub_block_type ) * 8;
typedef bit_block_walker< bits_per_subblock > bit_walker_type;
static const unsigned int subblocks_per_block = (bits_per_block / bit_walker_type::bits_per_block);
template < class OP >
static void apply( block_type _bits, OP & oper ) {
if(! _bits ) return;
unsigned int i = subblocks_per_block, offset = 0;
bit_walker_type bw;
while( i-- ) {
typename bit_walker_type::walkable_block_type sb = (typename bit_walker_type::walkable_block_type)_bits;
bw( sb, oper, offset );
_bits >>= bits_per_subblock;
if( ! _bits ) break;
offset += bits_per_subblock;
}
}
};
} // namespace utility {
} // namespace clotho {
#endif // CLOTHO_BIT_WALKER_HPP_
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "dll/base_conf.hpp" //The configuration helpers
#include "dll/rbm/rbm_base.hpp" //The base class
#include "dll/layer_traits.hpp" //layer_traits
#include "dll/util/checks.hpp" //nan_check
#include "dll/util/timers.hpp" //auto_timer
namespace dll {
/*!
* \brief Standard version of Convolutional Restricted Boltzmann Machine
*
* This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class,
* using CRTP to inject features into its children.
*/
template <typename Parent, typename Desc>
struct standard_conv_rbm : public rbm_base<Parent, Desc> {
using desc = Desc; ///< The descriptor of the layer
using parent_t = Parent; ///< The parent type
using this_type = standard_conv_rbm<parent_t, desc>; ///< The type of this layer
using base_type = rbm_base<parent_t, Desc>; ///< The base type
using weight = typename desc::weight; ///< The data type for this layer
using input_one_t = typename rbm_base_traits<parent_t>::input_one_t; ///< The type of one input
using output_one_t = typename rbm_base_traits<parent_t>::output_one_t; ///< The type of one output
using hidden_output_one_t = typename rbm_base_traits<parent_t>::hidden_output_one_t; ///< The type of an hidden output
using input_t = typename rbm_base_traits<parent_t>::input_t; ///< The type of the input
using output_t = typename rbm_base_traits<parent_t>::output_t; ///< The type of the output
static constexpr unit_type visible_unit = desc::visible_unit; ///< The visible unit type
static constexpr unit_type hidden_unit = desc::hidden_unit; ///< The hidden unit type
static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN,
"Only binary and linear visible units are supported");
static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit),
"Only binary hidden units are supported");
double std_gaussian = 0.2;
double c_sigm = 1.0;
//Constructors
/*!
* \brief Construct a new standard convolutional RBM
*/
standard_conv_rbm() {
//Note: Convolutional RBM needs lower learning rate than standard RBM
//Better initialization of learning rate
base_type::learning_rate =
visible_unit == unit_type::GAUSSIAN ? 1e-5
: is_relu(hidden_unit) ? 1e-4
: /* Only Gaussian Units needs lower rate */ 1e-3;
}
//Utility functions
/*!
* \brief Reconstruct the given input
*/
template <typename Sample>
void reconstruct(const Sample& items) {
reconstruct(items, as_derived());
}
/*!
* \brief Display the current visible unit activations
*/
void display_visible_unit_activations() const {
display_visible_unit_activations(as_derived());
}
/*!
* \brief Display the current visible unit samples
*/
void display_visible_unit_samples() const {
display_visible_unit_samples(as_derived());
}
/*!
* \brief Display the current hidden unit activations
*/
void display_hidden_unit_activations() const {
display_hidden_unit_samples(as_derived());
}
/*!
* \brief Display the current hidden unit samples
*/
void display_hidden_unit_samples() const {
display_hidden_unit_samples(as_derived());
}
//Various functions
/*!
* \brief Compute the activations of several input at once
* \param input The container of inputs
* \param h_a The output activations
* \param h_s The output samples
*/
void activate_many(const input_t& input, output_t& h_a, output_t& h_s) const {
for (size_t i = 0; i < input.size(); ++i) {
as_derived().activate_one(input[i], h_a[i], h_s[i]);
}
}
/*!
* \brief Compute the activations of several input at once
* \param input The container of inputs
* \param h_a The output activations
*/
void activate_many(const input_t& input, output_t& h_a) const {
for (size_t i = 0; i < input.size(); ++i) {
as_derived().activate_one(input[i], h_a[i]);
}
}
/*!
* \brief Batch activation of inputs
* \param h_a The output activations
* \param input The batch of input
*/
template <typename V, typename H, cpp_enable_if(etl::dimensions<V>() == 4)>
void batch_activate_hidden(H& h_a, const V& input) const {
as_derived().template batch_activate_hidden<true, false>(h_a, h_a, input, input);
}
/*!
* \brief Batch activation of inputs
* \param h_a The output activations
* \param input The batch of input
*/
template <typename V, typename H, cpp_enable_if(etl::dimensions<V>() == 2)>
void batch_activate_hidden(H& h_a, const V& input) const {
decltype(auto) rbm = as_derived();
rbm.template batch_activate_hidden<true, false>(h_a, h_a,
etl::reshape(input, etl::dim<0>(input), get_nc(rbm), get_nv1(rbm), get_nv2(rbm)),
etl::reshape(input, etl::dim<0>(input), get_nc(rbm), get_nv1(rbm), get_nv2(rbm)));
}
template<typename Input, typename Out>
weight energy(const Input& v, const Out& h) const {
return as_derived().energy_impl(v, h);
}
/*!
* \brief Return the free energy of the given input
*/
template <typename V>
weight free_energy(const V& v) const {
return as_derived().free_energy_impl(v);
}
/*!
* \brief Return the free energy of the current input
*/
weight free_energy() const {
return free_energy(as_derived().v1);
}
friend base_type;
private:
//Since the sub classes do not have the same fields, it is not possible
//to put the fields in standard_rbm, therefore, it is necessary to use template
//functions to implement the details
template<typename Input>
static double reconstruction_error_impl(const Input& items, parent_t& rbm) {
cpp_assert(items.size() == input_size(rbm), "The size of the training sample must match visible units");
//Set the state of the visible units
rbm.v1 = items;
rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
return etl::mean((rbm.v1 - rbm.v2_a) >> (rbm.v1 - rbm.v2_a));
}
/*!
* \brief Reconstruct the given input
*/
template <typename Sample>
static void reconstruct(const Sample& items, parent_t& rbm) {
cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units");
cpp::stop_watch<> watch;
//Set the state of the visible units
rbm.v1 = items;
rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s);
std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl;
}
/*!
* \brief Display the current visible unit activations
*/
static void display_visible_unit_activations(const parent_t& rbm) {
for (size_t channel = 0; channel < parent_t::NC; ++channel) {
std::cout << "Channel " << channel << std::endl;
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.v2_a(channel, i, j) << " ";
}
std::cout << std::endl;
}
}
}
/*!
* \brief Display the current visible unit samples
*/
static void display_visible_unit_samples(const parent_t& rbm) {
for (size_t channel = 0; channel < parent_t::NC; ++channel) {
std::cout << "Channel " << channel << std::endl;
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.v2_s(channel, i, j) << " ";
}
std::cout << std::endl;
}
}
}
/*!
* \brief Display the current hidden unit activations
*/
static void display_hidden_unit_activations(const parent_t& rbm) {
for (size_t k = 0; k < get_k(rbm); ++k) {
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.h2_a(k)(i, j) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl
<< std::endl;
}
}
/*!
* \brief Display the current hidden unit samples
*/
static void display_hidden_unit_samples(const parent_t& rbm) {
for (size_t k = 0; k < get_k(rbm); ++k) {
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.h2_s(k)(i, j) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl
<< std::endl;
}
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
parent_t& as_derived() {
return *static_cast<parent_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const parent_t& as_derived() const {
return *static_cast<const parent_t*>(this);
}
};
} //end of dll namespace
<commit_msg>Remove unused fields<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "dll/base_conf.hpp" //The configuration helpers
#include "dll/rbm/rbm_base.hpp" //The base class
#include "dll/layer_traits.hpp" //layer_traits
#include "dll/util/checks.hpp" //nan_check
#include "dll/util/timers.hpp" //auto_timer
namespace dll {
/*!
* \brief Standard version of Convolutional Restricted Boltzmann Machine
*
* This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class,
* using CRTP to inject features into its children.
*/
template <typename Parent, typename Desc>
struct standard_conv_rbm : public rbm_base<Parent, Desc> {
using desc = Desc; ///< The descriptor of the layer
using parent_t = Parent; ///< The parent type
using this_type = standard_conv_rbm<parent_t, desc>; ///< The type of this layer
using base_type = rbm_base<parent_t, Desc>; ///< The base type
using weight = typename desc::weight; ///< The data type for this layer
using input_one_t = typename rbm_base_traits<parent_t>::input_one_t; ///< The type of one input
using output_one_t = typename rbm_base_traits<parent_t>::output_one_t; ///< The type of one output
using hidden_output_one_t = typename rbm_base_traits<parent_t>::hidden_output_one_t; ///< The type of an hidden output
using input_t = typename rbm_base_traits<parent_t>::input_t; ///< The type of the input
using output_t = typename rbm_base_traits<parent_t>::output_t; ///< The type of the output
static constexpr unit_type visible_unit = desc::visible_unit; ///< The visible unit type
static constexpr unit_type hidden_unit = desc::hidden_unit; ///< The hidden unit type
static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN,
"Only binary and linear visible units are supported");
static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit),
"Only binary hidden units are supported");
//Constructors
/*!
* \brief Construct a new standard convolutional RBM
*/
standard_conv_rbm() {
//Note: Convolutional RBM needs lower learning rate than standard RBM
//Better initialization of learning rate
base_type::learning_rate =
visible_unit == unit_type::GAUSSIAN ? 1e-5
: is_relu(hidden_unit) ? 1e-4
: /* Only Gaussian Units needs lower rate */ 1e-3;
}
//Utility functions
/*!
* \brief Reconstruct the given input
*/
template <typename Sample>
void reconstruct(const Sample& items) {
reconstruct(items, as_derived());
}
/*!
* \brief Display the current visible unit activations
*/
void display_visible_unit_activations() const {
display_visible_unit_activations(as_derived());
}
/*!
* \brief Display the current visible unit samples
*/
void display_visible_unit_samples() const {
display_visible_unit_samples(as_derived());
}
/*!
* \brief Display the current hidden unit activations
*/
void display_hidden_unit_activations() const {
display_hidden_unit_samples(as_derived());
}
/*!
* \brief Display the current hidden unit samples
*/
void display_hidden_unit_samples() const {
display_hidden_unit_samples(as_derived());
}
//Various functions
/*!
* \brief Compute the activations of several input at once
* \param input The container of inputs
* \param h_a The output activations
* \param h_s The output samples
*/
void activate_many(const input_t& input, output_t& h_a, output_t& h_s) const {
for (size_t i = 0; i < input.size(); ++i) {
as_derived().activate_one(input[i], h_a[i], h_s[i]);
}
}
/*!
* \brief Compute the activations of several input at once
* \param input The container of inputs
* \param h_a The output activations
*/
void activate_many(const input_t& input, output_t& h_a) const {
for (size_t i = 0; i < input.size(); ++i) {
as_derived().activate_one(input[i], h_a[i]);
}
}
/*!
* \brief Batch activation of inputs
* \param h_a The output activations
* \param input The batch of input
*/
template <typename V, typename H, cpp_enable_if(etl::dimensions<V>() == 4)>
void batch_activate_hidden(H& h_a, const V& input) const {
as_derived().template batch_activate_hidden<true, false>(h_a, h_a, input, input);
}
/*!
* \brief Batch activation of inputs
* \param h_a The output activations
* \param input The batch of input
*/
template <typename V, typename H, cpp_enable_if(etl::dimensions<V>() == 2)>
void batch_activate_hidden(H& h_a, const V& input) const {
decltype(auto) rbm = as_derived();
rbm.template batch_activate_hidden<true, false>(h_a, h_a,
etl::reshape(input, etl::dim<0>(input), get_nc(rbm), get_nv1(rbm), get_nv2(rbm)),
etl::reshape(input, etl::dim<0>(input), get_nc(rbm), get_nv1(rbm), get_nv2(rbm)));
}
template<typename Input, typename Out>
weight energy(const Input& v, const Out& h) const {
return as_derived().energy_impl(v, h);
}
/*!
* \brief Return the free energy of the given input
*/
template <typename V>
weight free_energy(const V& v) const {
return as_derived().free_energy_impl(v);
}
/*!
* \brief Return the free energy of the current input
*/
weight free_energy() const {
return free_energy(as_derived().v1);
}
friend base_type;
private:
//Since the sub classes do not have the same fields, it is not possible
//to put the fields in standard_rbm, therefore, it is necessary to use template
//functions to implement the details
template<typename Input>
static double reconstruction_error_impl(const Input& items, parent_t& rbm) {
cpp_assert(items.size() == input_size(rbm), "The size of the training sample must match visible units");
//Set the state of the visible units
rbm.v1 = items;
rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
return etl::mean((rbm.v1 - rbm.v2_a) >> (rbm.v1 - rbm.v2_a));
}
/*!
* \brief Reconstruct the given input
*/
template <typename Sample>
static void reconstruct(const Sample& items, parent_t& rbm) {
cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units");
cpp::stop_watch<> watch;
//Set the state of the visible units
rbm.v1 = items;
rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1);
rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s);
rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s);
std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl;
}
/*!
* \brief Display the current visible unit activations
*/
static void display_visible_unit_activations(const parent_t& rbm) {
for (size_t channel = 0; channel < parent_t::NC; ++channel) {
std::cout << "Channel " << channel << std::endl;
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.v2_a(channel, i, j) << " ";
}
std::cout << std::endl;
}
}
}
/*!
* \brief Display the current visible unit samples
*/
static void display_visible_unit_samples(const parent_t& rbm) {
for (size_t channel = 0; channel < parent_t::NC; ++channel) {
std::cout << "Channel " << channel << std::endl;
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.v2_s(channel, i, j) << " ";
}
std::cout << std::endl;
}
}
}
/*!
* \brief Display the current hidden unit activations
*/
static void display_hidden_unit_activations(const parent_t& rbm) {
for (size_t k = 0; k < get_k(rbm); ++k) {
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.h2_a(k)(i, j) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl
<< std::endl;
}
}
/*!
* \brief Display the current hidden unit samples
*/
static void display_hidden_unit_samples(const parent_t& rbm) {
for (size_t k = 0; k < get_k(rbm); ++k) {
for (size_t i = 0; i < get_nv1(rbm); ++i) {
for (size_t j = 0; j < get_nv2(rbm); ++j) {
std::cout << rbm.h2_s(k)(i, j) << " ";
}
std::cout << std::endl;
}
std::cout << std::endl
<< std::endl;
}
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
parent_t& as_derived() {
return *static_cast<parent_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const parent_t& as_derived() const {
return *static_cast<const parent_t*>(this);
}
};
} //end of dll namespace
<|endoftext|> |
<commit_before>/**
* @file icomponent_base.hpp
* @brief Component(Shared Library) base interface
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details Component base interface class
*/
#ifndef _COSSB_ICOMPONENT_BASE_HPP_
#define _COSSB_ICOMPONENT_BASE_HPP_
#endif /* _COSSB_ICOMPONENT_BASE_HPP_ */
<commit_msg>add empty base component interface<commit_after>/**
* @file icomponent_base.hpp
* @brief Component(Shared Library) base interface
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details Component base interface class
*/
#ifndef _COSSB_ICOMPONENT_BASE_HPP_
#define _COSSB_ICOMPONENT_BASE_HPP_
namespace cossb {
namespace interface {
class icomponent {
};
} /* namespace interface */
} /* namespace cossb */
#endif /* _COSSB_ICOMPONENT_BASE_HPP_ */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#include <vector>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"
namespace libtorrent
{
namespace aux
{
struct session_impl;
struct checker_impl;
}
struct TORRENT_EXPORT duplicate_torrent: std::exception
{
virtual const char* what() const throw()
{ return "torrent already exists in session"; }
};
struct TORRENT_EXPORT invalid_handle: std::exception
{
virtual const char* what() const throw()
{ return "invalid torrent handle used"; }
};
struct TORRENT_EXPORT torrent_status
{
torrent_status()
: state(queued_for_checking)
, paused(false)
, progress(0.f)
, total_download(0)
, total_upload(0)
, total_payload_download(0)
, total_payload_upload(0)
, total_failed_bytes(0)
, total_redundant_bytes(0)
, download_rate(0)
, upload_rate(0)
, download_payload_rate(0)
, upload_payload_rate(0)
, num_peers(0)
, num_complete(-1)
, num_incomplete(-1)
, pieces(0)
, num_pieces(0)
, total_done(0)
, total_wanted_done(0)
, total_wanted(0)
, num_seeds(0)
, distributed_copies(0.f)
, block_size(0)
{}
enum state_t
{
queued_for_checking,
checking_files,
connecting_to_tracker,
downloading_metadata,
downloading,
finished,
seeding,
allocating
};
state_t state;
bool paused;
float progress;
boost::posix_time::time_duration next_announce;
boost::posix_time::time_duration announce_interval;
std::string current_tracker;
// transferred this session!
// total, payload plus protocol
size_type total_download;
size_type total_upload;
// payload only
size_type total_payload_download;
size_type total_payload_upload;
// the amount of payload bytes that
// has failed their hash test
size_type total_failed_bytes;
// the number of payload bytes that
// has been received redundantly.
size_type total_redundant_bytes;
// current transfer rate
// payload plus protocol
float download_rate;
float upload_rate;
// the rate of payload that is
// sent and received
float download_payload_rate;
float upload_payload_rate;
// the number of peers this torrent
// is connected to.
int num_peers;
// if the tracker sends scrape info in its
// announce reply, these fields will be
// set to the total number of peers that
// have the whole file and the total number
// of peers that are still downloading
int num_complete;
int num_incomplete;
const std::vector<bool>* pieces;
// this is the number of pieces the client has
// downloaded. it is equal to:
// std::accumulate(pieces->begin(), pieces->end());
int num_pieces;
// the number of bytes of the file we have
// including pieces that may have been filtered
// after we downloaded them
size_type total_done;
// the number of bytes we have of those that we
// want. i.e. not counting bytes from pieces that
// are filtered as not wanted.
size_type total_wanted_done;
// the total number of bytes we want to download
// this may be smaller than the total torrent size
// in case any pieces are filtered as not wanted
size_type total_wanted;
// the number of peers this torrent is connected to
// that are seeding.
int num_seeds;
// the number of distributed copies of the file.
// note that one copy may be spread out among many peers.
//
// the whole number part tells how many copies
// there are of the rarest piece(s)
//
// the fractional part tells the fraction of pieces that
// have more copies than the rarest piece(s).
float distributed_copies;
// the block size that is used in this torrent. i.e.
// the number of bytes each piece request asks for
// and each bit in the download queue bitfield represents
int block_size;
};
struct TORRENT_EXPORT partial_piece_info
{
enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
int piece_index;
int blocks_in_piece;
std::bitset<max_blocks_per_piece> requested_blocks;
std::bitset<max_blocks_per_piece> finished_blocks;
tcp::endpoint peer[max_blocks_per_piece];
int num_downloads[max_blocks_per_piece];
};
struct TORRENT_EXPORT torrent_handle
{
friend class invariant_access;
friend class aux::session_impl;
friend class torrent;
torrent_handle(): m_ses(0), m_chk(0) {}
void get_peer_info(std::vector<peer_info>& v) const;
bool send_chat_message(tcp::endpoint ip, std::string message) const;
torrent_status status() const;
void get_download_queue(std::vector<partial_piece_info>& queue) const;
// fills the specified vector with the download progress [0, 1]
// of each file in the torrent. The files are ordered as in
// the torrent_info.
void file_progress(std::vector<float>& progress);
std::vector<announce_entry> const& trackers() const;
void replace_trackers(std::vector<announce_entry> const&) const;
void add_url_seed(std::string const& url);
bool has_metadata() const;
const torrent_info& get_torrent_info() const;
bool is_valid() const;
bool is_seed() const;
bool is_paused() const;
void pause() const;
void resume() const;
// marks the piece with the given index as filtered
// it will not be downloaded
void filter_piece(int index, bool filter) const;
void filter_pieces(std::vector<bool> const& pieces) const;
bool is_piece_filtered(int index) const;
std::vector<bool> filtered_pieces() const;
// marks the file with the given index as filtered
// it will not be downloaded
void filter_files(std::vector<bool> const& files) const;
// set the interface to bind outgoing connections
// to.
void use_interface(const char* net_interface) const;
entry write_resume_data() const;
// kind of similar to get_torrent_info() but this
// is lower level, returning the exact info-part of
// the .torrent file. When hashed, this buffer
// will produce the info hash. The reference is valid
// only as long as the torrent is running.
std::vector<char> const& metadata() const;
// forces this torrent to reannounce
// (make a rerequest from the tracker)
void force_reannounce() const;
// forces a reannounce in the specified amount of time.
// This overrides the default announce interval, and no
// announce will take place until the given time has
// timed out.
void force_reannounce(boost::posix_time::time_duration) const;
// TODO: add a feature where the user can tell the torrent
// to finish all pieces currently in the pipeline, and then
// abort the torrent.
void set_upload_limit(int limit) const;
void set_download_limit(int limit) const;
void set_sequenced_download_threshold(int threshold) const;
void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
void set_peer_download_limit(tcp::endpoint ip, int limit) const;
// manually connect a peer
void connect_peer(tcp::endpoint const& adr) const;
// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
// the ratio is uploaded / downloaded. less than 1 is not allowed
void set_ratio(float up_down_ratio) const;
boost::filesystem::path save_path() const;
// -1 means unlimited unchokes
void set_max_uploads(int max_uploads) const;
// -1 means unlimited connections
void set_max_connections(int max_connections) const;
void set_tracker_login(std::string const& name
, std::string const& password) const;
// post condition: save_path() == save_path if true is returned
bool move_storage(boost::filesystem::path const& save_path) const;
const sha1_hash& info_hash() const
{ return m_info_hash; }
bool operator==(const torrent_handle& h) const
{ return m_info_hash == h.m_info_hash; }
bool operator!=(const torrent_handle& h) const
{ return m_info_hash != h.m_info_hash; }
bool operator<(const torrent_handle& h) const
{ return m_info_hash < h.m_info_hash; }
private:
torrent_handle(aux::session_impl* s,
aux::checker_impl* c,
const sha1_hash& h)
: m_ses(s)
, m_chk(c)
, m_info_hash(h)
{
assert(m_ses != 0);
}
#ifndef NDEBUG
void check_invariant() const;
#endif
aux::session_impl* m_ses;
aux::checker_impl* m_chk;
sha1_hash m_info_hash;
};
}
#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<commit_msg>fixed warning on msvc8<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#include <vector>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"
namespace libtorrent
{
namespace aux
{
struct session_impl;
struct checker_impl;
}
struct TORRENT_EXPORT duplicate_torrent: std::exception
{
virtual const char* what() const throw()
{ return "torrent already exists in session"; }
};
struct TORRENT_EXPORT invalid_handle: std::exception
{
virtual const char* what() const throw()
{ return "invalid torrent handle used"; }
};
struct TORRENT_EXPORT torrent_status
{
torrent_status()
: state(queued_for_checking)
, paused(false)
, progress(0.f)
, total_download(0)
, total_upload(0)
, total_payload_download(0)
, total_payload_upload(0)
, total_failed_bytes(0)
, total_redundant_bytes(0)
, download_rate(0)
, upload_rate(0)
, download_payload_rate(0)
, upload_payload_rate(0)
, num_peers(0)
, num_complete(-1)
, num_incomplete(-1)
, pieces(0)
, num_pieces(0)
, total_done(0)
, total_wanted_done(0)
, total_wanted(0)
, num_seeds(0)
, distributed_copies(0.f)
, block_size(0)
{}
enum state_t
{
queued_for_checking,
checking_files,
connecting_to_tracker,
downloading_metadata,
downloading,
finished,
seeding,
allocating
};
state_t state;
bool paused;
float progress;
boost::posix_time::time_duration next_announce;
boost::posix_time::time_duration announce_interval;
std::string current_tracker;
// transferred this session!
// total, payload plus protocol
size_type total_download;
size_type total_upload;
// payload only
size_type total_payload_download;
size_type total_payload_upload;
// the amount of payload bytes that
// has failed their hash test
size_type total_failed_bytes;
// the number of payload bytes that
// has been received redundantly.
size_type total_redundant_bytes;
// current transfer rate
// payload plus protocol
float download_rate;
float upload_rate;
// the rate of payload that is
// sent and received
float download_payload_rate;
float upload_payload_rate;
// the number of peers this torrent
// is connected to.
int num_peers;
// if the tracker sends scrape info in its
// announce reply, these fields will be
// set to the total number of peers that
// have the whole file and the total number
// of peers that are still downloading
int num_complete;
int num_incomplete;
const std::vector<bool>* pieces;
// this is the number of pieces the client has
// downloaded. it is equal to:
// std::accumulate(pieces->begin(), pieces->end());
int num_pieces;
// the number of bytes of the file we have
// including pieces that may have been filtered
// after we downloaded them
size_type total_done;
// the number of bytes we have of those that we
// want. i.e. not counting bytes from pieces that
// are filtered as not wanted.
size_type total_wanted_done;
// the total number of bytes we want to download
// this may be smaller than the total torrent size
// in case any pieces are filtered as not wanted
size_type total_wanted;
// the number of peers this torrent is connected to
// that are seeding.
int num_seeds;
// the number of distributed copies of the file.
// note that one copy may be spread out among many peers.
//
// the whole number part tells how many copies
// there are of the rarest piece(s)
//
// the fractional part tells the fraction of pieces that
// have more copies than the rarest piece(s).
float distributed_copies;
// the block size that is used in this torrent. i.e.
// the number of bytes each piece request asks for
// and each bit in the download queue bitfield represents
int block_size;
};
struct TORRENT_EXPORT partial_piece_info
{
enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
int piece_index;
int blocks_in_piece;
std::bitset<max_blocks_per_piece> requested_blocks;
std::bitset<max_blocks_per_piece> finished_blocks;
tcp::endpoint peer[max_blocks_per_piece];
int num_downloads[max_blocks_per_piece];
};
struct TORRENT_EXPORT torrent_handle
{
friend class invariant_access;
friend struct aux::session_impl;
friend class torrent;
torrent_handle(): m_ses(0), m_chk(0) {}
void get_peer_info(std::vector<peer_info>& v) const;
bool send_chat_message(tcp::endpoint ip, std::string message) const;
torrent_status status() const;
void get_download_queue(std::vector<partial_piece_info>& queue) const;
// fills the specified vector with the download progress [0, 1]
// of each file in the torrent. The files are ordered as in
// the torrent_info.
void file_progress(std::vector<float>& progress);
std::vector<announce_entry> const& trackers() const;
void replace_trackers(std::vector<announce_entry> const&) const;
void add_url_seed(std::string const& url);
bool has_metadata() const;
const torrent_info& get_torrent_info() const;
bool is_valid() const;
bool is_seed() const;
bool is_paused() const;
void pause() const;
void resume() const;
// marks the piece with the given index as filtered
// it will not be downloaded
void filter_piece(int index, bool filter) const;
void filter_pieces(std::vector<bool> const& pieces) const;
bool is_piece_filtered(int index) const;
std::vector<bool> filtered_pieces() const;
// marks the file with the given index as filtered
// it will not be downloaded
void filter_files(std::vector<bool> const& files) const;
// set the interface to bind outgoing connections
// to.
void use_interface(const char* net_interface) const;
entry write_resume_data() const;
// kind of similar to get_torrent_info() but this
// is lower level, returning the exact info-part of
// the .torrent file. When hashed, this buffer
// will produce the info hash. The reference is valid
// only as long as the torrent is running.
std::vector<char> const& metadata() const;
// forces this torrent to reannounce
// (make a rerequest from the tracker)
void force_reannounce() const;
// forces a reannounce in the specified amount of time.
// This overrides the default announce interval, and no
// announce will take place until the given time has
// timed out.
void force_reannounce(boost::posix_time::time_duration) const;
// TODO: add a feature where the user can tell the torrent
// to finish all pieces currently in the pipeline, and then
// abort the torrent.
void set_upload_limit(int limit) const;
void set_download_limit(int limit) const;
void set_sequenced_download_threshold(int threshold) const;
void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
void set_peer_download_limit(tcp::endpoint ip, int limit) const;
// manually connect a peer
void connect_peer(tcp::endpoint const& adr) const;
// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
// the ratio is uploaded / downloaded. less than 1 is not allowed
void set_ratio(float up_down_ratio) const;
boost::filesystem::path save_path() const;
// -1 means unlimited unchokes
void set_max_uploads(int max_uploads) const;
// -1 means unlimited connections
void set_max_connections(int max_connections) const;
void set_tracker_login(std::string const& name
, std::string const& password) const;
// post condition: save_path() == save_path if true is returned
bool move_storage(boost::filesystem::path const& save_path) const;
const sha1_hash& info_hash() const
{ return m_info_hash; }
bool operator==(const torrent_handle& h) const
{ return m_info_hash == h.m_info_hash; }
bool operator!=(const torrent_handle& h) const
{ return m_info_hash != h.m_info_hash; }
bool operator<(const torrent_handle& h) const
{ return m_info_hash < h.m_info_hash; }
private:
torrent_handle(aux::session_impl* s,
aux::checker_impl* c,
const sha1_hash& h)
: m_ses(s)
, m_chk(c)
, m_info_hash(h)
{
assert(m_ses != 0);
}
#ifndef NDEBUG
void check_invariant() const;
#endif
aux::session_impl* m_ses;
aux::checker_impl* m_chk;
sha1_hash m_info_hash;
};
}
#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TOLERANCE_ITERATOR_HPP
#define MAPNIK_TOLERANCE_ITERATOR_HPP
//mapnik
#include <mapnik/debug.hpp>
namespace mapnik
{
struct exponential_function
{
double operator()(double const& linear_position, double const& tolerance) const
{
return std::pow(1.3, linear_position) * linear_position / (4.0 * tolerance) + linear_position;
}
};
template <typename Function>
class tolerance_iterator
{
public:
tolerance_iterator(double label_position_tolerance, Function function)
: tolerance_(label_position_tolerance),
linear_position_(1.0),
value_(0),
initialized_(false),
values_tried_(0),
function_(function)
{
}
tolerance_iterator(double label_position_tolerance)
: tolerance_iterator(label_position_tolerance, Function())
{
}
~tolerance_iterator()
{
//std::cout << "values tried:" << values_tried_ << "\n";
}
double get() const
{
return -value_;
}
bool next()
{
++values_tried_;
if (values_tried_ > 255)
{
/* This point should not be reached during normal operation. But I can think of
* cases where very bad spacing and or tolerance values are choosen and the
* placement finder tries an excessive number of placements.
* 255 is an arbitrarily chosen limit.
*/
MAPNIK_LOG_WARN(placement_finder) << "Tried a huge number of placements. Please check "
"'label-position-tolerance' and 'spacing' parameters "
"of your TextSymbolizers.\n";
return false;
}
if (!initialized_)
{
initialized_ = true;
return true; //Always return value 0 as the first value.
}
if (value_ == 0)
{
value_ = function_(linear_position_, tolerance_);
return value_ <= tolerance_;
}
value_ = -value_;
if (value_ > 0)
{
linear_position_ += 1.0;
value_ = function_(linear_position_, tolerance_);
}
if (value_ > tolerance_)
{
return false;
}
return true;
}
void reset()
{
linear_position_ = 1.0;
value_ = .0;
initialized_ = false;
values_tried_ = 0;
}
private:
const double tolerance_;
double linear_position_;
double value_;
bool initialized_;
unsigned values_tried_;
Function function_;
};
}//ns mapnik
#endif // MAPNIK_TOLERANCE_ITERATOR_HPP
<commit_msg>Format<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TOLERANCE_ITERATOR_HPP
#define MAPNIK_TOLERANCE_ITERATOR_HPP
//mapnik
#include <mapnik/debug.hpp>
namespace mapnik
{
struct exponential_function
{
double operator()(double const& linear_position, double const& tolerance) const
{
return std::pow(1.3, linear_position) * linear_position /
(4.0 * tolerance) + linear_position;
}
};
template <typename Function>
class tolerance_iterator
{
public:
tolerance_iterator(double label_position_tolerance, Function function)
: tolerance_(label_position_tolerance),
linear_position_(1.0),
value_(0),
initialized_(false),
values_tried_(0),
function_(function)
{
}
tolerance_iterator(double label_position_tolerance)
: tolerance_iterator(label_position_tolerance, Function())
{
}
~tolerance_iterator()
{
//std::cout << "values tried:" << values_tried_ << "\n";
}
double get() const
{
return -value_;
}
bool next()
{
++values_tried_;
if (values_tried_ > 255)
{
/* This point should not be reached during normal operation. But I can think of
* cases where very bad spacing and or tolerance values are choosen and the
* placement finder tries an excessive number of placements.
* 255 is an arbitrarily chosen limit.
*/
MAPNIK_LOG_WARN(placement_finder) << "Tried a huge number of placements. Please check "
"'label-position-tolerance' and 'spacing' parameters "
"of your TextSymbolizers.\n";
return false;
}
if (!initialized_)
{
initialized_ = true;
return true; //Always return value 0 as the first value.
}
if (value_ == 0)
{
value_ = function_(linear_position_, tolerance_);
return value_ <= tolerance_;
}
value_ = -value_;
if (value_ > 0)
{
linear_position_ += 1.0;
value_ = function_(linear_position_, tolerance_);
}
if (value_ > tolerance_)
{
return false;
}
return true;
}
void reset()
{
linear_position_ = 1.0;
value_ = .0;
initialized_ = false;
values_tried_ = 0;
}
private:
const double tolerance_;
double linear_position_;
double value_;
bool initialized_;
unsigned values_tried_;
Function function_;
};
}//ns mapnik
#endif // MAPNIK_TOLERANCE_ITERATOR_HPP
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2012, Howard Butler, hobu.inc@gmail.com
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/Filter.hpp>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#ifdef PDAL_HAVE_GDAL
#pragma GCC diagnostic ignored "-Wfloat-equal"
#include <gdal.h>
#include <ogr_spatialref.h>
#include <pdal/GDALUtils.hpp>
#endif
namespace pdal
{
class PointBuffer;
namespace gdal
{
class GlobalDebug;
}
}
namespace pdal
{
namespace filters
{
// Provides GDAL-based raster overlay that places output data in
// specified dimensions. It also supports scaling the data by a multiplier
// on a per-dimension basis.
class PDAL_DLL Colorization : public Filter
{
struct BandInfo
{
std::string m_name;
Dimension::Id::Enum m_dim;
uint32_t m_band;
double m_scale;
};
public:
SET_STAGE_NAME("filters.colorization", "Fetch color information from a GDAL datasource")
SET_STAGE_LINK("http://pdal.io/stages/filters.colorization.html")
#ifdef PDAL_HAVE_GDAL
SET_STAGE_ENABLED(true)
#else
SET_STAGE_ENABLED(false)
#endif
Colorization(const Options& options) : Filter(options)
{}
static Options getDefaultOptions();
private:
virtual void initialize();
virtual void processOptions(const Options&);
virtual void ready(PointContext ctx);
virtual void filter(PointBuffer& buffer);
virtual void done(PointContext ctx);
bool getPixelAndLinePosition(double x, double y,
boost::array<double, 6> const& inverse, boost::int32_t& pixel,
boost::int32_t& line, void *ds);
std::string m_rasterFilename;
std::vector<BandInfo> m_bands;
boost::array<double, 6> m_forward_transform;
boost::array<double, 6> m_inverse_transform;
GDALDatasetH m_ds;
Colorization& operator=(const Colorization&); // not implemented
Colorization(const Colorization&); // not implemented
};
} // namespace filters
} // namespace pdal
<commit_msg>Provide a ctor for BandInfo.<commit_after>/******************************************************************************
* Copyright (c) 2012, Howard Butler, hobu.inc@gmail.com
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#pragma once
#include <pdal/Filter.hpp>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>
#ifdef PDAL_HAVE_GDAL
#pragma GCC diagnostic ignored "-Wfloat-equal"
#include <gdal.h>
#include <ogr_spatialref.h>
#include <pdal/GDALUtils.hpp>
#endif
namespace pdal
{
class PointBuffer;
namespace gdal
{
class GlobalDebug;
}
}
namespace pdal
{
namespace filters
{
// Provides GDAL-based raster overlay that places output data in
// specified dimensions. It also supports scaling the data by a multiplier
// on a per-dimension basis.
class PDAL_DLL Colorization : public Filter
{
struct BandInfo
{
BandInfo(const std::string& name, Dimension::Id::Enum dim, uint32_t band,
double scale) : m_name(name), m_dim(dim), m_band(band), m_scale(scale)
{}
std::string m_name;
Dimension::Id::Enum m_dim;
uint32_t m_band;
double m_scale;
};
public:
SET_STAGE_NAME("filters.colorization", "Fetch color information from a GDAL datasource")
SET_STAGE_LINK("http://pdal.io/stages/filters.colorization.html")
#ifdef PDAL_HAVE_GDAL
SET_STAGE_ENABLED(true)
#else
SET_STAGE_ENABLED(false)
#endif
Colorization(const Options& options) : Filter(options)
{}
static Options getDefaultOptions();
private:
virtual void initialize();
virtual void processOptions(const Options&);
virtual void ready(PointContext ctx);
virtual void filter(PointBuffer& buffer);
virtual void done(PointContext ctx);
bool getPixelAndLinePosition(double x, double y,
boost::array<double, 6> const& inverse, boost::int32_t& pixel,
boost::int32_t& line, void *ds);
std::string m_rasterFilename;
std::vector<BandInfo> m_bands;
boost::array<double, 6> m_forward_transform;
boost::array<double, 6> m_inverse_transform;
GDALDatasetH m_ds;
Colorization& operator=(const Colorization&); // not implemented
Colorization(const Colorization&); // not implemented
};
} // namespace filters
} // namespace pdal
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_DEBUG_INFO_HPP
#define RJ_GAME_DEBUG_INFO_HPP
#include <rectojump/core/render.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/shared/debug_text.hpp>
#include <mlk/tools/stl_string_utl.h>
namespace rj
{
class game;
class game_handler;
class debug_info
{
game& m_game;
sf::RectangleShape m_background{{100.f, 100.f}};
debug_text m_text;
public:
debug_info(game& g, data_manager& dm) :
m_game{g},
m_text{dm}
{
m_background.setPosition({1.f, 1.f});
m_background.setFillColor({255, 150, 123, 100});
m_background.setOutlineThickness(1);
m_background.setOutlineColor({255, 0, 0});
}
void update(dur);
void render()
{
render::render_object(m_game, m_background);
render::render_object(m_game, m_text);
}
};
}
#endif // RJ_GAME_DEBUG_INFO_HPP
<commit_msg>alpha<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_DEBUG_INFO_HPP
#define RJ_GAME_DEBUG_INFO_HPP
#include <rectojump/core/render.hpp>
#include <rectojump/global/common.hpp>
#include <rectojump/shared/debug_text.hpp>
#include <mlk/tools/stl_string_utl.h>
namespace rj
{
class game;
class game_handler;
class debug_info
{
game& m_game;
sf::RectangleShape m_background{{100.f, 100.f}};
debug_text m_text;
public:
debug_info(game& g, data_manager& dm) :
m_game{g},
m_text{dm}
{
m_background.setPosition({1.f, 1.f});
m_background.setFillColor({255, 150, 123, 220});
m_background.setOutlineThickness(1);
m_background.setOutlineColor({255, 0, 0});
}
void update(dur);
void render()
{
render::render_object(m_game, m_background);
render::render_object(m_game, m_text);
}
};
}
#endif // RJ_GAME_DEBUG_INFO_HPP
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <memory>
#include <vector>
#include "libs/catch/catch.hpp"
#include "libs/exceptionpp/exception.h"
#include "src/simpleconcurrentcache.h"
#include "src/simpleserialcache.h"
#include "src/simpleline.h"
TEST_CASE("cachepp|concurrentcache-multithread") {
std::shared_ptr<cachepp::SimpleConcurrentCache<cachepp::SimpleLine>> c (new cachepp::SimpleConcurrentCache<cachepp::SimpleLine>(2));
}
TEST_CASE("cachepp|concurrentcache-singlethread") {
std::shared_ptr<cachepp::SimpleConcurrentCache<cachepp::SimpleLine>> c (new cachepp::SimpleConcurrentCache<cachepp::SimpleLine>(2));
std::vector<std::shared_ptr<cachepp::SimpleLine>> v;
for(size_t i = 0; i < 10; ++i) {
v.push_back(std::shared_ptr<cachepp::SimpleLine> (new cachepp::SimpleLine(rand(), false)));
}
for(size_t i = 0; i < 10; ++i) {
REQUIRE(v.at(i)->get_is_loaded() == false);
}
// test cache line juggling
for(size_t i = 0; i < 10; ++i) {
c->acquire(v.at(i));
REQUIRE(v.at(i)->get_is_loaded() == true);
}
size_t loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 2);
c->clear();
loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 0);
// test selection policy
c->acquire(v.at(0));
c->acquire(v.at(1));
REQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);
c->access(v.at(0));
c->acquire(v.at(2));
REQUIRE(v.at(0)->get_is_loaded() == true);
REQUIRE(v.at(1)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
c->acquire(v.at(3));
REQUIRE(v.at(0)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
REQUIRE(v.at(3)->get_is_loaded() == true);
}
TEST_CASE("cachepp|serialcache") {
std::shared_ptr<cachepp::SimpleSerialCache<cachepp::SimpleLine>> c (new cachepp::SimpleSerialCache<cachepp::SimpleLine>(2));
std::vector<std::shared_ptr<cachepp::SimpleLine>> v;
for(size_t i = 0; i < 10; ++i) {
v.push_back(std::shared_ptr<cachepp::SimpleLine> (new cachepp::SimpleLine(rand(), false)));
}
for(size_t i = 0; i < 10; ++i) {
REQUIRE(v.at(i)->get_is_loaded() == false);
}
// test cache line juggling
for(size_t i = 0; i < 10; ++i) {
c->acquire(v.at(i));
REQUIRE(v.at(i)->get_is_loaded() == true);
}
size_t loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 2);
c->clear();
loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 0);
// test selection policy
c->acquire(v.at(0));
c->acquire(v.at(1));
REQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);
c->access(v.at(0));
c->acquire(v.at(2));
REQUIRE(v.at(0)->get_is_loaded() == true);
REQUIRE(v.at(1)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
c->acquire(v.at(3));
REQUIRE(v.at(0)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
REQUIRE(v.at(3)->get_is_loaded() == true);
}
<commit_msg>documentation edits + more tests -- may have mem mgmt issue<commit_after>#include <atomic>
#include <cstdlib>
#include <memory>
#include <vector>
#include "libs/catch/catch.hpp"
#include "libs/exceptionpp/exception.h"
#include "src/simpleconcurrentcache.h"
#include "src/simpleserialcache.h"
#include "src/simpleline.h"
void concurrentcache_multithread_worker(std::shared_ptr<std::atomic<size_t>> result, std::shared_ptr<cachepp::SimpleConcurrentCache<cachepp::SimpleLine>> c, std::vector<std::shared_ptr<cachepp::SimpleLine>> v) {
*result += 1;
}
TEST_CASE("cachepp|concurrentcache-multithread") {
size_t n_threads = 16;
size_t n_attempts = 1000;
std::shared_ptr<cachepp::SimpleConcurrentCache<cachepp::SimpleLine>> c (new cachepp::SimpleConcurrentCache<cachepp::SimpleLine>(2));
std::vector<std::shared_ptr<cachepp::SimpleLine>> q;
for(size_t i = 0; i < 10; ++i) {
q.push_back(std::shared_ptr<cachepp::SimpleLine> (new cachepp::SimpleLine(rand(), false)));
}
std::shared_ptr<std::atomic<size_t>> result (new std::atomic<size_t>());
for(size_t attempt = 0; attempt < n_attempts; ++attempt) {
for(size_t i = 0; i < n_threads; ++i) {
concurrentcache_multithread_worker(result, c, v);
}
}
REQUIRE(*result == (n_attempts * n_threads));
}
TEST_CASE("cachepp|concurrentcache-singlethread") {
std::shared_ptr<cachepp::SimpleConcurrentCache<cachepp::SimpleLine>> c (new cachepp::SimpleConcurrentCache<cachepp::SimpleLine>(2));
std::vector<std::shared_ptr<cachepp::SimpleLine>> v;
for(size_t i = 0; i < 10; ++i) {
v.push_back(std::shared_ptr<cachepp::SimpleLine> (new cachepp::SimpleLine(rand(), false)));
}
for(size_t i = 0; i < 10; ++i) {
REQUIRE(v.at(i)->get_is_loaded() == false);
}
/**
* test cache line juggling
*/
for(size_t i = 0; i < 10; ++i) {
c->acquire(v.at(i));
REQUIRE(v.at(i)->get_is_loaded() == true);
}
size_t loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 2);
c->clear();
loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 0);
/**
* test selection policy
*/
c->acquire(v.at(0));
c->acquire(v.at(1));
REQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);
c->access(v.at(0));
c->acquire(v.at(2));
REQUIRE(v.at(0)->get_is_loaded() == true);
REQUIRE(v.at(1)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
c->acquire(v.at(3));
REQUIRE(v.at(0)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
REQUIRE(v.at(3)->get_is_loaded() == true);
}
TEST_CASE("cachepp|serialcache") {
std::shared_ptr<cachepp::SimpleSerialCache<cachepp::SimpleLine>> c (new cachepp::SimpleSerialCache<cachepp::SimpleLine>(2));
std::vector<std::shared_ptr<cachepp::SimpleLine>> v;
for(size_t i = 0; i < 10; ++i) {
v.push_back(std::shared_ptr<cachepp::SimpleLine> (new cachepp::SimpleLine(rand(), false)));
}
for(size_t i = 0; i < 10; ++i) {
REQUIRE(v.at(i)->get_is_loaded() == false);
}
/**
* test cache line juggling
*/
for(size_t i = 0; i < 10; ++i) {
c->acquire(v.at(i));
REQUIRE(v.at(i)->get_is_loaded() == true);
}
size_t loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 2);
c->clear();
loaded_lines = 0;
for(size_t i = 0; i < 10; ++i) {
loaded_lines += v.at(i)->get_is_loaded();
}
REQUIRE(loaded_lines == 0);
/**
* test selection policy
*/
c->acquire(v.at(0));
c->acquire(v.at(1));
REQUIRE_THROWS_AS(c->access(v.at(2)), exceptionpp::RuntimeError);
c->access(v.at(0));
c->acquire(v.at(2));
REQUIRE(v.at(0)->get_is_loaded() == true);
REQUIRE(v.at(1)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
c->acquire(v.at(3));
REQUIRE(v.at(0)->get_is_loaded() == false);
REQUIRE(v.at(2)->get_is_loaded() == true);
REQUIRE(v.at(3)->get_is_loaded() == true);
}
<|endoftext|> |
<commit_before>#include "stress-application.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-server/vtrc-listener.h"
#include "stress-service-impl.h"
#include "boost/program_options.hpp"
#include "boost/algorithm/string.hpp"
#include "vtrc-bind.h"
#include "vtrc-ref.h"
#include "vtrc-mutex.h"
#include "vtrc-atomic.h"
#include "boost/asio/error.hpp"
namespace stress {
using namespace vtrc;
namespace po = boost::program_options;
namespace {
server::listener_sptr create_from_string( const std::string &name,
server::application &app,
const vtrc_rpc::session_options &opts,
bool tcp_nodelay)
{
/// result endpoint
server::listener_sptr result;
std::vector<std::string> params;
size_t delim_pos = name.find_last_of( ':' );
if( delim_pos == std::string::npos ) {
/// local: <localname>
params.push_back( name );
} else {
/// tcp: <addres>:<port>
params.push_back( std::string( name.begin( ),
name.begin( ) + delim_pos ) );
params.push_back( std::string( name.begin( ) + delim_pos + 1,
name.end( ) ) );
}
if( params.size( ) == 1 ) { /// local endpoint
#ifndef _WIN32
::unlink( params[0].c_str( ) ); /// unlink old file socket
#endif
result = server::listeners::local::create(app, opts, params[0]);
} else if( params.size( ) == 2 ) { /// TCP
result = server::listeners::tcp::create( app, opts,
params[0],
boost::lexical_cast<unsigned short>(params[1]),
tcp_nodelay);
}
return result;
}
class app_impl: public server::application {
public:
app_impl( common::pool_pair &pp )
:server::application(pp)
{ }
vtrc::shared_ptr<common::rpc_service_wrapper>
get_service_by_name( common::connection_iface* conn,
const std::string &service_name )
{
if( service_name == stress::service_name( ) ) {
google::protobuf::Service *stress_serv =
stress::create_service( conn );
return vtrc::shared_ptr<common::rpc_service_wrapper>(
vtrc::make_shared<common::rpc_service_wrapper>(
stress_serv ) );
}
return vtrc::shared_ptr<common::rpc_service_wrapper>( );
}
};
}
struct application::impl {
common::pool_pair pp_;
app_impl app_;
std::vector<server::listener_sptr> listeners_;
vtrc::atomic<size_t> counter_;
common::delayed_call retry_timer_;
unsigned accept_errors_;
impl( unsigned io_threads )
:pp_(io_threads)
,app_(pp_)
,counter_(0)
,retry_timer_(pp_.get_io_service( ))
,accept_errors_(0)
{ }
impl( unsigned io_threads, unsigned rpc_threads )
:pp_(io_threads, rpc_threads)
,app_(pp_)
,counter_(0)
,retry_timer_(pp_.get_io_service( ))
{ }
void on_new_connection( server::listener_sptr l,
const common::connection_iface *c )
{
//vtrc::unique_lock<vtrc::mutex> lock(counter_lock_);
std::cout << "New connection: "
<< "\n\tep: " << l->name( )
<< "\n\tclient: " << c->name( )
<< "\n\ttotal: " << ++counter_
<< "\n"
;
}
void start_retry_accept( server::listener_sptr l, unsigned rto )
{
retry_timer_.call_from_now(
vtrc::bind( &impl::retry_timer_handler, this, l, rto, _1 ),
common::timer::milliseconds( rto ));
}
void retry_timer_handler( server::listener_sptr l, unsigned retry_to,
const boost::system::error_code &code)
{
if( !code ) {
std::cout << "Restarting " << l->name( ) << "...";
try {
l->start( );
std::cout << "Ok;\n";
} catch( const std::exception &ex ) {
std::cout << "failed; " << ex.what( )
<< "; Retrying...\n";
start_retry_accept( l, retry_to );
};
}
}
void on_accept_failed( server::listener_sptr l,
unsigned retry_to,
const boost::system::error_code &code )
{
std::cout << "Accept failed at " << l->name( )
<< " due " << code.message( ) << "\n";
start_retry_accept( l, retry_to );
}
void on_stop_connection( server::listener_sptr l,
const common::connection_iface *c )
{
//vtrc::unique_lock<vtrc::mutex> lock(counter_lock_);
std::cout << "Close connection: "
<< c->name( )
<< "; count: " << --counter_
<< "\n";
}
vtrc_rpc::session_options options( const po::variables_map ¶ms )
{
using server::listeners::default_options;
vtrc_rpc::session_options opts( default_options( ) );
if( params.count( "message-size" ) ) {
opts.set_max_message_length(
params["message-size"].as<unsigned>( ));
}
if( params.count( "stack-size" ) ) {
opts.set_max_stack_size(
params["stack-size"].as<unsigned>( ));
}
if( params.count( "read-size" ) ) {
opts.set_read_buffer_size(
params["read-size"].as<unsigned>( ));
}
return opts;
}
void run( const po::variables_map ¶ms )
{
typedef std::vector<std::string> string_vector;
typedef string_vector::const_iterator vec_citer;
string_vector ser = params["server"].as<string_vector>( );
bool use_only_pool = !!params.count( "only-pool" );
bool tcp_nodelay = !!params.count( "tcp-nodelay" );
using server::listeners::default_options;
vtrc_rpc::session_options opts( options( params ) );
unsigned retry_to = (params.count( "accept-retry" ) != 0)
? params["accept-retry"].as<unsigned>( )
: 1000;
for( vec_citer b(ser.begin( )), e(ser.end( )); b != e; ++b) {
std::cout << "Starting listener at '" << *b << "'...";
attach_start_listener( retry_to,
create_from_string( *b, app_, opts, tcp_nodelay) );
std::cout << "Ok\n";
}
if( use_only_pool ) {
pp_.get_io_pool( ).attach( );
} else {
pp_.get_rpc_pool( ).attach( );
}
pp_.join_all( );
}
void attach_start_listener( unsigned retry_to,
vtrc::server::listener_sptr listen )
{
listen->get_on_new_connection( ).connect(
vtrc::bind( &impl::on_new_connection, this, listen, _1 ));
listen->get_on_stop_connection( ).connect(
vtrc::bind( &impl::on_stop_connection, this, listen, _1 ));
listen->get_on_accept_failed( ).connect(
vtrc::bind( &impl::on_accept_failed, this,
listen, retry_to, _1 ));
listeners_.push_back( listen );
listen->start( );
}
void stop( )
{
typedef std::vector<server::listener_sptr>::const_iterator citer;
for( citer b(listeners_.begin( )), e(listeners_.end( )); b!=e; ++b){
(*b)->stop( );
}
retry_timer_.cancel( );
pp_.stop_all( );
pp_.join_all( );
}
};
application::application( unsigned io_threads )
:impl_(new impl(io_threads))
{ }
application::application( unsigned io_threads, unsigned rpc_threads )
:impl_(new impl(io_threads, rpc_threads))
{ }
application::~application()
{
delete impl_;
}
server::application &application::get_application( )
{
return impl_->app_;
}
const server::application &application::get_application( ) const
{
return impl_->app_;
}
void application::run( const po::variables_map ¶ms )
{
impl_->run( params );
}
void application::stop( )
{
impl_->stop( );
}
}
<commit_msg>examples<commit_after>#include "stress-application.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "vtrc-common/vtrc-pool-pair.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-connection-iface.h"
#include "vtrc-common/vtrc-delayed-call.h"
#include "vtrc-server/vtrc-application.h"
#include "vtrc-server/vtrc-listener-tcp.h"
#include "vtrc-server/vtrc-listener-local.h"
#include "vtrc-server/vtrc-listener.h"
#include "stress-service-impl.h"
#include "boost/program_options.hpp"
#include "boost/algorithm/string.hpp"
#include "vtrc-bind.h"
#include "vtrc-ref.h"
#include "vtrc-mutex.h"
#include "vtrc-atomic.h"
#include "boost/asio/error.hpp"
namespace stress {
using namespace vtrc;
namespace po = boost::program_options;
namespace gpb = google::protobuf;
namespace {
server::listener_sptr create_from_string( const std::string &name,
server::application &app,
const vtrc_rpc::session_options &opts,
bool tcp_nodelay)
{
/// result endpoint
server::listener_sptr result;
std::vector<std::string> params;
size_t delim_pos = name.find_last_of( ':' );
if( delim_pos == std::string::npos ) {
/// local: <localname>
params.push_back( name );
} else {
/// tcp: <addres>:<port>
params.push_back( std::string( name.begin( ),
name.begin( ) + delim_pos ) );
params.push_back( std::string( name.begin( ) + delim_pos + 1,
name.end( ) ) );
}
if( params.size( ) == 1 ) { /// local endpoint
#ifndef _WIN32
::unlink( params[0].c_str( ) ); /// unlink old file socket
#endif
result = server::listeners::local::create(app, opts, params[0]);
} else if( params.size( ) == 2 ) { /// TCP
result = server::listeners::tcp::create( app, opts,
params[0],
boost::lexical_cast<unsigned short>(params[1]),
tcp_nodelay);
}
return result;
}
class app_impl: public server::application {
public:
app_impl( common::pool_pair &pp )
:server::application(pp)
{ }
vtrc::shared_ptr<common::rpc_service_wrapper>
get_service_by_name( common::connection_iface* conn,
const std::string &service_name )
{
if( service_name == stress::service_name( ) ) {
gpb::Service *stress_serv = stress::create_service( conn );
return vtrc::shared_ptr<common::rpc_service_wrapper>(
vtrc::make_shared<common::rpc_service_wrapper>(
stress_serv ) );
}
return vtrc::shared_ptr<common::rpc_service_wrapper>( );
}
};
}
struct application::impl {
common::pool_pair pp_;
app_impl app_;
std::vector<server::listener_sptr> listeners_;
vtrc::atomic<size_t> counter_;
common::delayed_call retry_timer_;
unsigned accept_errors_;
impl( unsigned io_threads )
:pp_(io_threads)
,app_(pp_)
,counter_(0)
,retry_timer_(pp_.get_io_service( ))
,accept_errors_(0)
{ }
impl( unsigned io_threads, unsigned rpc_threads )
:pp_(io_threads, rpc_threads)
,app_(pp_)
,counter_(0)
,retry_timer_(pp_.get_io_service( ))
{ }
void on_new_connection( server::listener_sptr l,
const common::connection_iface *c )
{
//vtrc::unique_lock<vtrc::mutex> lock(counter_lock_);
std::cout << "New connection: "
<< "\n\tep: " << l->name( )
<< "\n\tclient: " << c->name( )
<< "\n\ttotal: " << ++counter_
<< "\n"
;
}
void start_retry_accept( server::listener_sptr l, unsigned rto )
{
retry_timer_.call_from_now(
vtrc::bind( &impl::retry_timer_handler, this, l, rto, _1 ),
common::timer::milliseconds( rto ));
}
void retry_timer_handler( server::listener_sptr l, unsigned retry_to,
const boost::system::error_code &code)
{
if( !code ) {
std::cout << "Restarting " << l->name( ) << "...";
try {
l->start( );
std::cout << "Ok;\n";
} catch( const std::exception &ex ) {
std::cout << "failed; " << ex.what( )
<< "; Retrying...\n";
start_retry_accept( l, retry_to );
};
}
}
void on_accept_failed( server::listener_sptr l,
unsigned retry_to,
const boost::system::error_code &code )
{
std::cout << "Accept failed at " << l->name( )
<< " due " << code.message( ) << "\n";
start_retry_accept( l, retry_to );
}
void on_stop_connection( server::listener_sptr l,
const common::connection_iface *c )
{
//vtrc::unique_lock<vtrc::mutex> lock(counter_lock_);
std::cout << "Close connection: "
<< c->name( )
<< "; count: " << --counter_
<< "\n";
}
vtrc_rpc::session_options options( const po::variables_map ¶ms )
{
using server::listeners::default_options;
vtrc_rpc::session_options opts( default_options( ) );
if( params.count( "message-size" ) ) {
opts.set_max_message_length(
params["message-size"].as<unsigned>( ));
}
if( params.count( "stack-size" ) ) {
opts.set_max_stack_size(
params["stack-size"].as<unsigned>( ));
}
if( params.count( "read-size" ) ) {
opts.set_read_buffer_size(
params["read-size"].as<unsigned>( ));
}
return opts;
}
void run( const po::variables_map ¶ms )
{
typedef std::vector<std::string> string_vector;
typedef string_vector::const_iterator vec_citer;
string_vector ser = params["server"].as<string_vector>( );
bool use_only_pool = !!params.count( "only-pool" );
bool tcp_nodelay = !!params.count( "tcp-nodelay" );
using server::listeners::default_options;
vtrc_rpc::session_options opts( options( params ) );
unsigned retry_to = (params.count( "accept-retry" ) != 0)
? params["accept-retry"].as<unsigned>( )
: 1000;
for( vec_citer b(ser.begin( )), e(ser.end( )); b != e; ++b) {
std::cout << "Starting listener at '" << *b << "'...";
attach_start_listener( retry_to,
create_from_string( *b, app_, opts, tcp_nodelay) );
std::cout << "Ok\n";
}
if( use_only_pool ) {
pp_.get_io_pool( ).attach( );
} else {
pp_.get_rpc_pool( ).attach( );
}
pp_.join_all( );
}
void attach_start_listener( unsigned retry_to,
vtrc::server::listener_sptr listen )
{
listen->get_on_new_connection( ).connect(
vtrc::bind( &impl::on_new_connection, this, listen, _1 ));
listen->get_on_stop_connection( ).connect(
vtrc::bind( &impl::on_stop_connection, this, listen, _1 ));
listen->get_on_accept_failed( ).connect(
vtrc::bind( &impl::on_accept_failed, this,
listen, retry_to, _1 ));
listeners_.push_back( listen );
listen->start( );
}
void stop( )
{
typedef std::vector<server::listener_sptr>::const_iterator citer;
for( citer b(listeners_.begin( )), e(listeners_.end( )); b!=e; ++b){
(*b)->stop( );
}
retry_timer_.cancel( );
pp_.stop_all( );
pp_.join_all( );
}
};
application::application( unsigned io_threads )
:impl_(new impl(io_threads))
{ }
application::application( unsigned io_threads, unsigned rpc_threads )
:impl_(new impl(io_threads, rpc_threads))
{ }
application::~application()
{
delete impl_;
}
server::application &application::get_application( )
{
return impl_->app_;
}
const server::application &application::get_application( ) const
{
return impl_->app_;
}
void application::run( const po::variables_map ¶ms )
{
impl_->run( params );
}
void application::stop( )
{
impl_->stop( );
}
}
<|endoftext|> |
<commit_before>/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (fuzz test support)
| | |__ | | | | | | version 2.0.0
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Run "make fuzz_testing" and follow the instructions.
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
*/
#include <json.hpp>
using json = nlohmann::json;
int main()
{
#ifdef __AFL_HAVE_MANUAL_CONTROL
while (__AFL_LOOP(1000))
{
#endif
try
{
json j(std::cin);
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument in parsing" << e.what() << '\n';
}
#ifdef __AFL_HAVE_MANUAL_CONTROL
}
#endif
}
<commit_msg>added serialization to fuzz testing<commit_after>/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++ (fuzz test support)
| | |__ | | | | | | version 2.0.0
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Run "make fuzz_testing" and follow the instructions.
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
*/
#include <json.hpp>
using json = nlohmann::json;
int main()
{
#ifdef __AFL_HAVE_MANUAL_CONTROL
while (__AFL_LOOP(1000))
{
#endif
try
{
json j(std::cin);
std::cout << j << std::endl;
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument in parsing" << e.what() << '\n';
}
#ifdef __AFL_HAVE_MANUAL_CONTROL
}
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/common/update_manifest.h"
#include "libxml/globals.h"
#include "testing/gtest/include/gtest/gtest.h"
static const char kValidXml[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
static const char valid_xml_with_hash[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' "
" hash_sha256='1234'/>"
" </app>"
"</gupdate>";
static const char kMissingAppId[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' />"
" </app>"
"</gupdate>";
static const char kInvalidCodebase[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' />"
" </app>"
"</gupdate>";
static const char kMissingVersion[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx' />"
" </app>"
"</gupdate>";
static const char kInvalidVersion[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx' "
" version='1.2.3.a'/>"
" </app>"
"</gupdate>";
static const char kUsesNamespacePrefix[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<g:gupdate xmlns:g='http://www.google.com/update2/response' protocol='2.0'>"
" <g:app appid='12345'>"
" <g:updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </g:app>"
"</g:gupdate>";
// Includes unrelated <app> tags from other xml namespaces - this should
// not cause problems.
static const char kSimilarTagnames[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response'"
" xmlns:a='http://a' protocol='2.0'>"
" <a:app/>"
" <b:app xmlns:b='http://b' />"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
// Includes a <daystart> tag.
static const char kWithDaystart[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <daystart elapsed_seconds='456' />"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
// Indicates no updates available - this should not be a parse error.
static const char kNoUpdate[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck status='noupdate' />"
" </app>"
"</gupdate>";
// Includes two <app> tags, one with an error.
static const char kTwoAppsOneError[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='aaaaaaaa' status='error-unknownApplication'>"
" <updatecheck status='error-unknownapplication'/>"
" </app>"
" <app appid='bbbbbbbb'>"
" <updatecheck codebase='http://example.com/b_3.1.crx' version='3.1'/>"
" </app>"
"</gupdate>";
TEST(ExtensionUpdateManifestTest, TestUpdateManifest) {
UpdateManifest parser;
// Test parsing of a number of invalid xml cases
EXPECT_FALSE(parser.Parse(std::string()));
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kMissingAppId));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kInvalidCodebase));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kMissingVersion));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kInvalidVersion));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
// Parse some valid XML, and check that all params came out as expected
EXPECT_TRUE(parser.Parse(kValidXml));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
const UpdateManifest::Result* firstResult = &parser.results().list.at(0);
EXPECT_EQ(GURL("http://example.com/extension_1.2.3.4.crx"),
firstResult->crx_url);
EXPECT_EQ("1.2.3.4", firstResult->version);
EXPECT_EQ("2.0.143.0", firstResult->browser_min_version);
// Parse some xml that uses namespace prefixes.
EXPECT_TRUE(parser.Parse(kUsesNamespacePrefix));
EXPECT_TRUE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kSimilarTagnames));
EXPECT_TRUE(parser.errors().empty());
xmlCleanupGlobals();
// Parse xml with hash value
EXPECT_TRUE(parser.Parse(valid_xml_with_hash));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
firstResult = &parser.results().list.at(0);
EXPECT_EQ("1234", firstResult->package_hash);
// Parse xml with a <daystart> element.
EXPECT_TRUE(parser.Parse(kWithDaystart));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
EXPECT_EQ(parser.results().daystart_elapsed_seconds, 456);
// Parse a no-update response.
EXPECT_TRUE(parser.Parse(kNoUpdate));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
firstResult = &parser.results().list.at(0);
EXPECT_EQ(firstResult->extension_id, "12345");
EXPECT_EQ(firstResult->version, "");
// Parse xml with one error and one success <app> tag.
EXPECT_TRUE(parser.Parse(kTwoAppsOneError));
EXPECT_FALSE(parser.errors().empty());
EXPECT_EQ(1u, parser.results().list.size());
firstResult = &parser.results().list.at(0);
EXPECT_EQ(firstResult->extension_id, "bbbbbbbb");
}
<commit_msg>extensions: Remove xmlCleanupGlobals() call.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/common/update_manifest.h"
#include "testing/gtest/include/gtest/gtest.h"
static const char kValidXml[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
static const char valid_xml_with_hash[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' "
" hash_sha256='1234'/>"
" </app>"
"</gupdate>";
static const char kMissingAppId[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' />"
" </app>"
"</gupdate>";
static const char kInvalidCodebase[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' />"
" </app>"
"</gupdate>";
static const char kMissingVersion[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx' />"
" </app>"
"</gupdate>";
static const char kInvalidVersion[] =
"<?xml version='1.0'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345' status='ok'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx' "
" version='1.2.3.a'/>"
" </app>"
"</gupdate>";
static const char kUsesNamespacePrefix[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<g:gupdate xmlns:g='http://www.google.com/update2/response' protocol='2.0'>"
" <g:app appid='12345'>"
" <g:updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </g:app>"
"</g:gupdate>";
// Includes unrelated <app> tags from other xml namespaces - this should
// not cause problems.
static const char kSimilarTagnames[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response'"
" xmlns:a='http://a' protocol='2.0'>"
" <a:app/>"
" <b:app xmlns:b='http://b' />"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
// Includes a <daystart> tag.
static const char kWithDaystart[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <daystart elapsed_seconds='456' />"
" <app appid='12345'>"
" <updatecheck codebase='http://example.com/extension_1.2.3.4.crx'"
" version='1.2.3.4' prodversionmin='2.0.143.0' />"
" </app>"
"</gupdate>";
// Indicates no updates available - this should not be a parse error.
static const char kNoUpdate[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='12345'>"
" <updatecheck status='noupdate' />"
" </app>"
"</gupdate>";
// Includes two <app> tags, one with an error.
static const char kTwoAppsOneError[] =
"<?xml version='1.0' encoding='UTF-8'?>"
"<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>"
" <app appid='aaaaaaaa' status='error-unknownApplication'>"
" <updatecheck status='error-unknownapplication'/>"
" </app>"
" <app appid='bbbbbbbb'>"
" <updatecheck codebase='http://example.com/b_3.1.crx' version='3.1'/>"
" </app>"
"</gupdate>";
TEST(ExtensionUpdateManifestTest, TestUpdateManifest) {
UpdateManifest parser;
// Test parsing of a number of invalid xml cases
EXPECT_FALSE(parser.Parse(std::string()));
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kMissingAppId));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kInvalidCodebase));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kMissingVersion));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kInvalidVersion));
EXPECT_TRUE(parser.results().list.empty());
EXPECT_FALSE(parser.errors().empty());
// Parse some valid XML, and check that all params came out as expected
EXPECT_TRUE(parser.Parse(kValidXml));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
const UpdateManifest::Result* firstResult = &parser.results().list.at(0);
EXPECT_EQ(GURL("http://example.com/extension_1.2.3.4.crx"),
firstResult->crx_url);
EXPECT_EQ("1.2.3.4", firstResult->version);
EXPECT_EQ("2.0.143.0", firstResult->browser_min_version);
// Parse some xml that uses namespace prefixes.
EXPECT_TRUE(parser.Parse(kUsesNamespacePrefix));
EXPECT_TRUE(parser.errors().empty());
EXPECT_TRUE(parser.Parse(kSimilarTagnames));
EXPECT_TRUE(parser.errors().empty());
// Parse xml with hash value
EXPECT_TRUE(parser.Parse(valid_xml_with_hash));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
firstResult = &parser.results().list.at(0);
EXPECT_EQ("1234", firstResult->package_hash);
// Parse xml with a <daystart> element.
EXPECT_TRUE(parser.Parse(kWithDaystart));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
EXPECT_EQ(parser.results().daystart_elapsed_seconds, 456);
// Parse a no-update response.
EXPECT_TRUE(parser.Parse(kNoUpdate));
EXPECT_TRUE(parser.errors().empty());
EXPECT_FALSE(parser.results().list.empty());
firstResult = &parser.results().list.at(0);
EXPECT_EQ(firstResult->extension_id, "12345");
EXPECT_EQ(firstResult->version, "");
// Parse xml with one error and one success <app> tag.
EXPECT_TRUE(parser.Parse(kTwoAppsOneError));
EXPECT_FALSE(parser.errors().empty());
EXPECT_EQ(1u, parser.results().list.size());
firstResult = &parser.results().list.at(0);
EXPECT_EQ(firstResult->extension_id, "bbbbbbbb");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/webui_login_view.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/accessibility/accessibility_util.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/session_manager_client.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/status/status_area_view_chromeos.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/common/render_messages.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/render_view_host_observer.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/chromeos/legacy_window_manager/wm_ipc.h"
#include "ui/views/widget/native_widget_gtk.h"
#endif
#if defined(USE_VIRTUAL_KEYBOARD)
#include "chrome/browser/ui/virtual_keyboard/virtual_keyboard_manager.h"
#endif
#if defined(USE_AURA)
#include "chrome/browser/ui/views/aura/chrome_shell_delegate.h"
#endif
namespace {
const char kViewClassName[] = "browser/chromeos/login/WebUILoginView";
// These strings must be kept in sync with handleAccelerator() in oobe.js.
const char kAccelNameAccessibility[] = "accessibility";
const char kAccelNameCancel[] = "cancel";
const char kAccelNameEnrollment[] = "enrollment";
// Observes IPC messages from the FrameSniffer and notifies JS if error
// appears.
class SnifferObserver : public content::RenderViewHostObserver {
public:
SnifferObserver(RenderViewHost* host, WebUI* webui)
: content::RenderViewHostObserver(host), webui_(webui) {
DCHECK(webui_);
Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
UTF8ToUTF16("gaia-frame")));
}
virtual ~SnifferObserver() {}
// IPC::Channel::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SnifferObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnError)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
private:
void OnError(int error) {
base::FundamentalValue error_value(error);
webui_->CallJavascriptFunction("login.ErrorMessageScreen.onFrameError",
error_value);
}
WebUI* webui_;
};
// A View class which places its first child at the right most position.
class RightAlignedView : public views::View {
public:
virtual void Layout() OVERRIDE;
virtual void ChildPreferredSizeChanged(View* child) OVERRIDE;
};
void RightAlignedView::Layout() {
if (has_children()) {
views::View* child = child_at(0);
gfx::Size preferred_size = child->GetPreferredSize();
child->SetBounds(width() - preferred_size.width(),
0, preferred_size.width(), preferred_size.height());
}
}
void RightAlignedView::ChildPreferredSizeChanged(View* child) {
Layout();
}
} // namespace
namespace chromeos {
// static
const int WebUILoginView::kStatusAreaCornerPadding = 5;
// WebUILoginView public: ------------------------------------------------------
WebUILoginView::WebUILoginView()
: status_area_(NULL),
webui_login_(NULL),
login_window_(NULL),
status_window_(NULL),
host_window_frozen_(false),
status_area_visibility_on_init_(true) {
#if defined(USE_VIRTUAL_KEYBOARD)
// Make sure the singleton VirtualKeyboardManager object is created.
VirtualKeyboardManager::GetInstance();
#endif
accel_map_[ui::Accelerator(ui::VKEY_Z, false, true, true)] =
kAccelNameAccessibility;
accel_map_[ui::Accelerator(ui::VKEY_ESCAPE, false, false, false)] =
kAccelNameCancel;
accel_map_[ui::Accelerator(ui::VKEY_E, false, true, true)] =
kAccelNameEnrollment;
for (AccelMap::iterator i(accel_map_.begin()); i != accel_map_.end(); ++i)
AddAccelerator(i->first);
}
WebUILoginView::~WebUILoginView() {
if (status_window_)
status_window_->CloseNow();
status_window_ = NULL;
}
void WebUILoginView::Init(views::Widget* login_window) {
login_window_ = login_window;
webui_login_ = new DOMView();
AddChildView(webui_login_);
webui_login_->Init(ProfileManager::GetDefaultProfile(), NULL);
webui_login_->SetVisible(true);
TabContents* tab_contents = webui_login_->dom_contents()->tab_contents();
tab_contents->SetDelegate(this);
tab_watcher_.reset(new TabFirstRenderWatcher(tab_contents, this));
}
std::string WebUILoginView::GetClassName() const {
return kViewClassName;
}
bool WebUILoginView::AcceleratorPressed(
const ui::Accelerator& accelerator) {
AccelMap::const_iterator entry = accel_map_.find(accelerator);
if (entry == accel_map_.end())
return false;
if (!webui_login_)
return true;
WebUI* web_ui = GetWebUI();
if (web_ui) {
base::StringValue accel_name(entry->second);
web_ui->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
accel_name);
}
return true;
}
gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
return GetWidget()->GetNativeWindow();
}
void WebUILoginView::OnWindowCreated() {
#if defined(TOOLKIT_USES_GTK)
// Freezes host window update until the tab is rendered.
host_window_frozen_ = static_cast<views::NativeWidgetGtk*>(
GetWidget()->native_widget())->SuppressFreezeUpdates();
#else
// TODO(saintlou): Unclear if we need this for the !gtk case.
// According to nkostylev it prevents the renderer from flashing with a
// white solid background until the content is fully rendered.
#endif
}
void WebUILoginView::UpdateWindowType() {
#if defined(TOOLKIT_USES_GTK)
std::vector<int> params;
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_WEBUI,
¶ms);
#endif
}
void WebUILoginView::LoadURL(const GURL & url) {
webui_login_->LoadURL(url);
webui_login_->RequestFocus();
}
WebUI* WebUILoginView::GetWebUI() {
return webui_login_->dom_contents()->tab_contents()->web_ui();
}
void WebUILoginView::SetStatusAreaEnabled(bool enable) {
if (status_area_)
status_area_->MakeButtonsActive(enable);
}
void WebUILoginView::SetStatusAreaVisible(bool visible) {
if (status_area_)
status_area_->SetVisible(visible);
else
status_area_visibility_on_init_ = visible;
}
// WebUILoginView protected: ---------------------------------------------------
void WebUILoginView::Layout() {
DCHECK(webui_login_);
webui_login_->SetBoundsRect(bounds());
}
void WebUILoginView::OnLocaleChanged() {
// Proxy settings dialog contains localized strings.
proxy_settings_dialog_.reset();
SchedulePaint();
}
void WebUILoginView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
// Overridden from StatusAreaButton::Delegate:
bool WebUILoginView::ShouldExecuteStatusAreaCommand(
const views::View* button_view, int command_id) const {
if (command_id == StatusAreaButton::Delegate::SHOW_NETWORK_OPTIONS)
return true;
return false;
}
void WebUILoginView::ExecuteStatusAreaCommand(
const views::View* button_view, int command_id) {
if (command_id == StatusAreaButton::Delegate::SHOW_NETWORK_OPTIONS) {
if (proxy_settings_dialog_.get() == NULL) {
proxy_settings_dialog_.reset(new ProxySettingsDialog(NULL,
GetNativeWindow()));
}
proxy_settings_dialog_->Show();
}
}
gfx::Font WebUILoginView::GetStatusAreaFont(const gfx::Font& font) const {
return font;
}
StatusAreaButton::TextStyle WebUILoginView::GetStatusAreaTextStyle() const {
return StatusAreaButton::GRAY_PLAIN;
}
void WebUILoginView::ButtonVisibilityChanged(views::View* button_view) {
if (status_area_)
status_area_->UpdateButtonVisibility();
}
void WebUILoginView::OnRenderHostCreated(RenderViewHost* host) {
new SnifferObserver(host, GetWebUI());
}
void WebUILoginView::OnTabMainFrameLoaded() {
VLOG(1) << "WebUI login main frame loaded.";
}
void WebUILoginView::OnTabMainFrameFirstRender() {
VLOG(1) << "WebUI login main frame rendered.";
StatusAreaViewChromeos::SetScreenMode(
StatusAreaViewChromeos::LOGIN_MODE_WEBUI);
// In aura there's a global status area shown already.
#if defined(USE_AURA)
status_area_ = ChromeShellDelegate::instance()->GetStatusArea();
status_area_->SetVisible(status_area_visibility_on_init_);
#else
InitStatusArea();
#endif
#if defined(TOOLKIT_USES_GTK)
if (host_window_frozen_) {
host_window_frozen_ = false;
// Unfreezes the host window since tab is rendered now.
views::NativeWidgetGtk::UpdateFreezeUpdatesProperty(
GetNativeWindow(), false);
}
#endif
bool emit_login_visible = false;
// In aura, there will be no window-manager. So chrome needs to emit the
// 'login-prompt-visible' signal. This needs to happen here, after the page
// has completed rendering itself.
#if defined(USE_AURA)
emit_login_visible = true;
#endif
if (emit_login_visible)
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
->EmitLoginPromptVisible();
OobeUI* oobe_ui = static_cast<OobeUI*>(GetWebUI());
// Notify OOBE that the login frame has been rendered. Currently
// this is used to start camera presence check.
oobe_ui->OnLoginPromptVisible();
}
void WebUILoginView::InitStatusArea() {
DCHECK(status_area_ == NULL);
DCHECK(status_window_ == NULL);
StatusAreaViewChromeos* status_area_chromeos = new StatusAreaViewChromeos();
status_area_chromeos->Init(this);
status_area_ = status_area_chromeos;
status_area_->SetVisible(status_area_visibility_on_init_);
// Width of |status_window| is meant to be large enough.
// The current value of status_area_->GetPreferredSize().width()
// will be too small when button status is changed.
// (e.g. when CapsLock indicator appears)
gfx::Size widget_size(width()/2,
status_area_->GetPreferredSize().height());
const int widget_x = base::i18n::IsRTL() ?
kStatusAreaCornerPadding :
width() - widget_size.width() - kStatusAreaCornerPadding;
gfx::Rect widget_bounds(widget_x, kStatusAreaCornerPadding,
widget_size.width(), widget_size.height());
// TODO(nkostylev|oshima): Make status area in the same window as
// |webui_login_| once RenderWidgetHostViewViews and compositor are
// ready. This will also avoid having to override the status area
// widget type for the lock screen.
views::Widget::InitParams widget_params(GetStatusAreaWidgetType());
widget_params.bounds = widget_bounds;
widget_params.transparent = true;
widget_params.parent_widget = login_window_;
status_window_ = new views::Widget;
status_window_->Init(widget_params);
#if defined(TOOLKIT_USES_GTK)
std::vector<int> params;
params.push_back(1); // Show while screen is locked.
chromeos::WmIpc::instance()->SetWindowType(
status_window_->GetNativeView(),
chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
¶ms);
#endif
views::View* contents_view = new RightAlignedView;
contents_view->AddChildView(status_area_);
status_window_->SetContentsView(contents_view);
status_window_->Show();
}
views::Widget::InitParams::Type WebUILoginView::GetStatusAreaWidgetType() {
return views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
}
// WebUILoginView private: -----------------------------------------------------
bool WebUILoginView::HandleContextMenu(const ContextMenuParams& params) {
// Do not show the context menu.
#ifndef NDEBUG
return false;
#else
return true;
#endif
}
bool WebUILoginView::IsPopupOrPanel(const TabContents* source) const {
return true;
}
bool WebUILoginView::TakeFocus(bool reverse) {
if (status_area_ && status_area_->visible()) {
// Forward the focus to the status area.
base::Callback<void(bool)> return_focus_cb =
base::Bind(&WebUILoginView::ReturnFocus, base::Unretained(this));
status_area_->TakeFocus(reverse, return_focus_cb);
status_area_->GetWidget()->Activate();
}
return true;
}
void WebUILoginView::ReturnFocus(bool reverse) {
// Return the focus to the web contents.
webui_login_->dom_contents()->tab_contents()->
FocusThroughTabTraversal(reverse);
GetWidget()->Activate();
}
void WebUILoginView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
GetFocusManager());
// Make sure error bubble is cleared on keyboard event. This is needed
// when the focus is inside an iframe. Only clear on KeyDown to prevent hiding
// an immediate authentication error (See crbug.com/103643).
if (event.type == WebKit::WebInputEvent::KeyDown) {
WebUI* web_ui = GetWebUI();
if (web_ui)
web_ui->CallJavascriptFunction("cr.ui.Oobe.clearErrors");
}
}
} // namespace chromeos
<commit_msg>[aura] Prevent crash when changing focuses elements on sign in screen.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/webui_login_view.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chromeos/accessibility/accessibility_util.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/session_manager_client.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/status/status_area_view_chromeos.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/views/dom_view.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/common/render_messages.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/public/browser/render_view_host_observer.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/views/widget/widget.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/chromeos/legacy_window_manager/wm_ipc.h"
#include "ui/views/widget/native_widget_gtk.h"
#endif
#if defined(USE_VIRTUAL_KEYBOARD)
#include "chrome/browser/ui/virtual_keyboard/virtual_keyboard_manager.h"
#endif
#if defined(USE_AURA)
#include "chrome/browser/ui/views/aura/chrome_shell_delegate.h"
#endif
namespace {
const char kViewClassName[] = "browser/chromeos/login/WebUILoginView";
// These strings must be kept in sync with handleAccelerator() in oobe.js.
const char kAccelNameAccessibility[] = "accessibility";
const char kAccelNameCancel[] = "cancel";
const char kAccelNameEnrollment[] = "enrollment";
// Observes IPC messages from the FrameSniffer and notifies JS if error
// appears.
class SnifferObserver : public content::RenderViewHostObserver {
public:
SnifferObserver(RenderViewHost* host, WebUI* webui)
: content::RenderViewHostObserver(host), webui_(webui) {
DCHECK(webui_);
Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
UTF8ToUTF16("gaia-frame")));
}
virtual ~SnifferObserver() {}
// IPC::Channel::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(SnifferObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FrameLoadingError, OnError)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
private:
void OnError(int error) {
base::FundamentalValue error_value(error);
webui_->CallJavascriptFunction("login.ErrorMessageScreen.onFrameError",
error_value);
}
WebUI* webui_;
};
// A View class which places its first child at the right most position.
class RightAlignedView : public views::View {
public:
virtual void Layout() OVERRIDE;
virtual void ChildPreferredSizeChanged(View* child) OVERRIDE;
};
void RightAlignedView::Layout() {
if (has_children()) {
views::View* child = child_at(0);
gfx::Size preferred_size = child->GetPreferredSize();
child->SetBounds(width() - preferred_size.width(),
0, preferred_size.width(), preferred_size.height());
}
}
void RightAlignedView::ChildPreferredSizeChanged(View* child) {
Layout();
}
} // namespace
namespace chromeos {
// static
const int WebUILoginView::kStatusAreaCornerPadding = 5;
// WebUILoginView public: ------------------------------------------------------
WebUILoginView::WebUILoginView()
: status_area_(NULL),
webui_login_(NULL),
login_window_(NULL),
status_window_(NULL),
host_window_frozen_(false),
status_area_visibility_on_init_(true) {
#if defined(USE_VIRTUAL_KEYBOARD)
// Make sure the singleton VirtualKeyboardManager object is created.
VirtualKeyboardManager::GetInstance();
#endif
accel_map_[ui::Accelerator(ui::VKEY_Z, false, true, true)] =
kAccelNameAccessibility;
accel_map_[ui::Accelerator(ui::VKEY_ESCAPE, false, false, false)] =
kAccelNameCancel;
accel_map_[ui::Accelerator(ui::VKEY_E, false, true, true)] =
kAccelNameEnrollment;
for (AccelMap::iterator i(accel_map_.begin()); i != accel_map_.end(); ++i)
AddAccelerator(i->first);
}
WebUILoginView::~WebUILoginView() {
if (status_window_)
status_window_->CloseNow();
status_window_ = NULL;
}
void WebUILoginView::Init(views::Widget* login_window) {
login_window_ = login_window;
webui_login_ = new DOMView();
AddChildView(webui_login_);
webui_login_->Init(ProfileManager::GetDefaultProfile(), NULL);
webui_login_->SetVisible(true);
TabContents* tab_contents = webui_login_->dom_contents()->tab_contents();
tab_contents->SetDelegate(this);
tab_watcher_.reset(new TabFirstRenderWatcher(tab_contents, this));
}
std::string WebUILoginView::GetClassName() const {
return kViewClassName;
}
bool WebUILoginView::AcceleratorPressed(
const ui::Accelerator& accelerator) {
AccelMap::const_iterator entry = accel_map_.find(accelerator);
if (entry == accel_map_.end())
return false;
if (!webui_login_)
return true;
WebUI* web_ui = GetWebUI();
if (web_ui) {
base::StringValue accel_name(entry->second);
web_ui->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
accel_name);
}
return true;
}
gfx::NativeWindow WebUILoginView::GetNativeWindow() const {
return GetWidget()->GetNativeWindow();
}
void WebUILoginView::OnWindowCreated() {
#if defined(TOOLKIT_USES_GTK)
// Freezes host window update until the tab is rendered.
host_window_frozen_ = static_cast<views::NativeWidgetGtk*>(
GetWidget()->native_widget())->SuppressFreezeUpdates();
#else
// TODO(saintlou): Unclear if we need this for the !gtk case.
// According to nkostylev it prevents the renderer from flashing with a
// white solid background until the content is fully rendered.
#endif
}
void WebUILoginView::UpdateWindowType() {
#if defined(TOOLKIT_USES_GTK)
std::vector<int> params;
WmIpc::instance()->SetWindowType(
GTK_WIDGET(GetNativeWindow()),
WM_IPC_WINDOW_LOGIN_WEBUI,
¶ms);
#endif
}
void WebUILoginView::LoadURL(const GURL & url) {
webui_login_->LoadURL(url);
webui_login_->RequestFocus();
}
WebUI* WebUILoginView::GetWebUI() {
return webui_login_->dom_contents()->tab_contents()->web_ui();
}
void WebUILoginView::SetStatusAreaEnabled(bool enable) {
if (status_area_)
status_area_->MakeButtonsActive(enable);
}
void WebUILoginView::SetStatusAreaVisible(bool visible) {
if (status_area_)
status_area_->SetVisible(visible);
else
status_area_visibility_on_init_ = visible;
}
// WebUILoginView protected: ---------------------------------------------------
void WebUILoginView::Layout() {
DCHECK(webui_login_);
webui_login_->SetBoundsRect(bounds());
}
void WebUILoginView::OnLocaleChanged() {
// Proxy settings dialog contains localized strings.
proxy_settings_dialog_.reset();
SchedulePaint();
}
void WebUILoginView::ChildPreferredSizeChanged(View* child) {
Layout();
SchedulePaint();
}
// Overridden from StatusAreaButton::Delegate:
bool WebUILoginView::ShouldExecuteStatusAreaCommand(
const views::View* button_view, int command_id) const {
if (command_id == StatusAreaButton::Delegate::SHOW_NETWORK_OPTIONS)
return true;
return false;
}
void WebUILoginView::ExecuteStatusAreaCommand(
const views::View* button_view, int command_id) {
if (command_id == StatusAreaButton::Delegate::SHOW_NETWORK_OPTIONS) {
if (proxy_settings_dialog_.get() == NULL) {
proxy_settings_dialog_.reset(new ProxySettingsDialog(NULL,
GetNativeWindow()));
}
proxy_settings_dialog_->Show();
}
}
gfx::Font WebUILoginView::GetStatusAreaFont(const gfx::Font& font) const {
return font;
}
StatusAreaButton::TextStyle WebUILoginView::GetStatusAreaTextStyle() const {
return StatusAreaButton::GRAY_PLAIN;
}
void WebUILoginView::ButtonVisibilityChanged(views::View* button_view) {
if (status_area_)
status_area_->UpdateButtonVisibility();
}
void WebUILoginView::OnRenderHostCreated(RenderViewHost* host) {
new SnifferObserver(host, GetWebUI());
}
void WebUILoginView::OnTabMainFrameLoaded() {
VLOG(1) << "WebUI login main frame loaded.";
}
void WebUILoginView::OnTabMainFrameFirstRender() {
VLOG(1) << "WebUI login main frame rendered.";
StatusAreaViewChromeos::SetScreenMode(
StatusAreaViewChromeos::LOGIN_MODE_WEBUI);
// In aura there's a global status area shown already.
#if defined(USE_AURA)
status_area_ = ChromeShellDelegate::instance()->GetStatusArea();
status_area_->SetVisible(status_area_visibility_on_init_);
#else
InitStatusArea();
#endif
#if defined(TOOLKIT_USES_GTK)
if (host_window_frozen_) {
host_window_frozen_ = false;
// Unfreezes the host window since tab is rendered now.
views::NativeWidgetGtk::UpdateFreezeUpdatesProperty(
GetNativeWindow(), false);
}
#endif
bool emit_login_visible = false;
// In aura, there will be no window-manager. So chrome needs to emit the
// 'login-prompt-visible' signal. This needs to happen here, after the page
// has completed rendering itself.
#if defined(USE_AURA)
emit_login_visible = true;
#endif
if (emit_login_visible)
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()
->EmitLoginPromptVisible();
OobeUI* oobe_ui = static_cast<OobeUI*>(GetWebUI());
// Notify OOBE that the login frame has been rendered. Currently
// this is used to start camera presence check.
oobe_ui->OnLoginPromptVisible();
}
void WebUILoginView::InitStatusArea() {
DCHECK(status_area_ == NULL);
DCHECK(status_window_ == NULL);
StatusAreaViewChromeos* status_area_chromeos = new StatusAreaViewChromeos();
status_area_chromeos->Init(this);
status_area_ = status_area_chromeos;
status_area_->SetVisible(status_area_visibility_on_init_);
// Width of |status_window| is meant to be large enough.
// The current value of status_area_->GetPreferredSize().width()
// will be too small when button status is changed.
// (e.g. when CapsLock indicator appears)
gfx::Size widget_size(width()/2,
status_area_->GetPreferredSize().height());
const int widget_x = base::i18n::IsRTL() ?
kStatusAreaCornerPadding :
width() - widget_size.width() - kStatusAreaCornerPadding;
gfx::Rect widget_bounds(widget_x, kStatusAreaCornerPadding,
widget_size.width(), widget_size.height());
// TODO(nkostylev|oshima): Make status area in the same window as
// |webui_login_| once RenderWidgetHostViewViews and compositor are
// ready. This will also avoid having to override the status area
// widget type for the lock screen.
views::Widget::InitParams widget_params(GetStatusAreaWidgetType());
widget_params.bounds = widget_bounds;
widget_params.transparent = true;
widget_params.parent_widget = login_window_;
status_window_ = new views::Widget;
status_window_->Init(widget_params);
#if defined(TOOLKIT_USES_GTK)
std::vector<int> params;
params.push_back(1); // Show while screen is locked.
chromeos::WmIpc::instance()->SetWindowType(
status_window_->GetNativeView(),
chromeos::WM_IPC_WINDOW_CHROME_INFO_BUBBLE,
¶ms);
#endif
views::View* contents_view = new RightAlignedView;
contents_view->AddChildView(status_area_);
status_window_->SetContentsView(contents_view);
status_window_->Show();
}
views::Widget::InitParams::Type WebUILoginView::GetStatusAreaWidgetType() {
return views::Widget::InitParams::TYPE_WINDOW_FRAMELESS;
}
// WebUILoginView private: -----------------------------------------------------
bool WebUILoginView::HandleContextMenu(const ContextMenuParams& params) {
// Do not show the context menu.
#ifndef NDEBUG
return false;
#else
return true;
#endif
}
bool WebUILoginView::IsPopupOrPanel(const TabContents* source) const {
return true;
}
bool WebUILoginView::TakeFocus(bool reverse) {
#if defined(USE_AURA)
// With Aura StatusArea widget is TYPE_CONTROL thus not considered top level
// and doesn't have focus manager (see Widget::is_top_level() comment).
// TODO(nkostylev): Make status area accessible on Aura.
// http://crbug.com/108166
ReturnFocus(reverse);
#else
if (status_area_ && status_area_->visible()) {
// Forward the focus to the status area.
base::Callback<void(bool)> return_focus_cb =
base::Bind(&WebUILoginView::ReturnFocus, base::Unretained(this));
status_area_->TakeFocus(reverse, return_focus_cb);
status_area_->GetWidget()->Activate();
}
#endif
return true;
}
void WebUILoginView::ReturnFocus(bool reverse) {
// Return the focus to the web contents.
webui_login_->dom_contents()->tab_contents()->
FocusThroughTabTraversal(reverse);
GetWidget()->Activate();
}
void WebUILoginView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
GetFocusManager());
// Make sure error bubble is cleared on keyboard event. This is needed
// when the focus is inside an iframe. Only clear on KeyDown to prevent hiding
// an immediate authentication error (See crbug.com/103643).
if (event.type == WebKit::WebInputEvent::KeyDown) {
WebUI* web_ui = GetWebUI();
if (web_ui)
web_ui->CallJavascriptFunction("cr.ui.Oobe.clearErrors");
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/common/chrome_switches.h"
namespace prerender {
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerender)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerender);
if (switch_value == switches::kPrerenderSwitchValueAuto) {
#if defined(OS_CHROMEOS)
// Prerender is temporarily disabled on CrOS.
// http://crosbug.com/12483
prerender_option = PRERENDER_OPTION_DISABLED;
#else
prerender_option = PRERENDER_OPTION_AUTO;
#endif
} else if (switch_value == switches::kPrerenderSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value == switches::kPrerenderSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO: {
const base::FieldTrial::Probability kPrefetchDivisor = 1000;
const base::FieldTrial::Probability kYesPrefetchProbability = 0;
const base::FieldTrial::Probability kPrerenderExperimentProbability = 0;
const base::FieldTrial::Probability kPrerenderControlProbability = 0;
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", kPrefetchDivisor,
"ContentPrefetchDisabled", 2011, 6, 30));
const int kNoPrefetchGroup = trial->kDefaultGroupNumber;
const int kYesPrefetchGroup =
trial->AppendGroup("ContentPrefetchEnabled", kYesPrefetchProbability);
const int kPrerenderExperimentGroup =
trial->AppendGroup("ContentPrefetchPrerender",
kPrerenderExperimentProbability);
const int kPrerenderControlGroup =
trial->AppendGroup("ContentPrefetchPrerenderControl",
kPrerenderControlProbability);
const int trial_group = trial->group();
if (trial_group == kYesPrefetchGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
} else if (trial_group == kNoPrefetchGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_DISABLED);
} else if (trial_group == kPrerenderExperimentGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControlGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else {
NOTREACHED();
}
break;
}
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
}
} // namespace prerender
<commit_msg>Bump up prerender field trial control and experiment groups to 5% each.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prerender/prerender_field_trial.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/common/chrome_switches.h"
namespace prerender {
void ConfigurePrefetchAndPrerender(const CommandLine& command_line) {
enum PrerenderOption {
PRERENDER_OPTION_AUTO,
PRERENDER_OPTION_DISABLED,
PRERENDER_OPTION_ENABLED,
PRERENDER_OPTION_PREFETCH_ONLY,
};
PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;
if (command_line.HasSwitch(switches::kPrerender)) {
const std::string switch_value =
command_line.GetSwitchValueASCII(switches::kPrerender);
if (switch_value == switches::kPrerenderSwitchValueAuto) {
#if defined(OS_CHROMEOS)
// Prerender is temporarily disabled on CrOS.
// http://crosbug.com/12483
prerender_option = PRERENDER_OPTION_DISABLED;
#else
prerender_option = PRERENDER_OPTION_AUTO;
#endif
} else if (switch_value == switches::kPrerenderSwitchValueDisabled) {
prerender_option = PRERENDER_OPTION_DISABLED;
} else if (switch_value.empty() ||
switch_value == switches::kPrerenderSwitchValueEnabled) {
// The empty string means the option was provided with no value, and that
// means enable.
prerender_option = PRERENDER_OPTION_ENABLED;
} else if (switch_value == switches::kPrerenderSwitchValuePrefetchOnly) {
prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;
} else {
prerender_option = PRERENDER_OPTION_DISABLED;
LOG(ERROR) << "Invalid --prerender option received on command line: "
<< switch_value;
LOG(ERROR) << "Disabling prerendering!";
}
}
switch (prerender_option) {
case PRERENDER_OPTION_AUTO: {
const base::FieldTrial::Probability kPrefetchDivisor = 1000;
const base::FieldTrial::Probability kYesPrefetchProbability = 0;
const base::FieldTrial::Probability kPrerenderExperimentProbability = 50;
const base::FieldTrial::Probability kPrerenderControlProbability = 50;
scoped_refptr<base::FieldTrial> trial(
new base::FieldTrial("Prefetch", kPrefetchDivisor,
"ContentPrefetchDisabled", 2011, 6, 30));
const int kNoPrefetchGroup = trial->kDefaultGroupNumber;
const int kYesPrefetchGroup =
trial->AppendGroup("ContentPrefetchEnabled", kYesPrefetchProbability);
const int kPrerenderExperimentGroup =
trial->AppendGroup("ContentPrefetchPrerender",
kPrerenderExperimentProbability);
const int kPrerenderControlGroup =
trial->AppendGroup("ContentPrefetchPrerenderControl",
kPrerenderControlProbability);
const int trial_group = trial->group();
if (trial_group == kYesPrefetchGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
} else if (trial_group == kNoPrefetchGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_DISABLED);
} else if (trial_group == kPrerenderExperimentGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);
} else if (trial_group == kPrerenderControlGroup) {
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(
PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);
} else {
NOTREACHED();
}
break;
}
case PRERENDER_OPTION_DISABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(false);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
case PRERENDER_OPTION_ENABLED:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);
break;
case PRERENDER_OPTION_PREFETCH_ONLY:
ResourceDispatcherHost::set_is_prefetch_enabled(true);
PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);
break;
default:
NOTREACHED();
}
UMA_HISTOGRAM_ENUMERATION("Prerender.Sessions",
PrerenderManager::GetMode(),
PrerenderManager::PRERENDER_MODE_MAX);
}
} // namespace prerender
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/nacl_debug_exception_handler_win.h"
#include "base/bind.h"
#include "base/process_util.h"
#include "base/threading/platform_thread.h"
#include "base/win/scoped_handle.h"
#include "native_client/src/trusted/service_runtime/win/debug_exception_handler.h"
namespace {
class DebugExceptionHandler : public base::PlatformThread::Delegate {
public:
DebugExceptionHandler(base::ProcessHandle nacl_process,
const std::string& startup_info,
base::MessageLoopProxy* message_loop,
const base::Callback<void(bool)>& on_connected)
: nacl_process_(nacl_process),
startup_info_(startup_info),
message_loop_(message_loop),
on_connected_(on_connected) {
}
virtual void ThreadMain() OVERRIDE {
// In the Windows API, the set of processes being debugged is
// thread-local, so we have to attach to the process (using
// DebugActiveProcess()) on the same thread on which
// NaClDebugLoop() receives debug events for the process.
bool attached = false;
int pid = GetProcessId(nacl_process_);
if (pid == 0) {
LOG(ERROR) << "Invalid process handle";
} else {
if (!DebugActiveProcess(pid)) {
LOG(ERROR) << "Failed to connect to the process";
} else {
attached = true;
}
}
message_loop_->PostTask(FROM_HERE, base::Bind(on_connected_, attached));
if (attached) {
// TODO(mseaborn): Clean up the NaCl side to remove the need for
// a const_cast here.
NaClDebugExceptionHandlerRun(
nacl_process_,
reinterpret_cast<void*>(const_cast<char*>(startup_info_.data())),
startup_info_.size());
}
delete this;
}
private:
base::win::ScopedHandle nacl_process_;
std::string startup_info_;
base::MessageLoopProxy* message_loop_;
base::Callback<void(bool)> on_connected_;
DISALLOW_COPY_AND_ASSIGN(DebugExceptionHandler);
};
} // namespace
void NaClStartDebugExceptionHandlerThread(
base::ProcessHandle nacl_process,
const std::string& startup_info,
base::MessageLoopProxy* message_loop,
const base::Callback<void(bool)>& on_connected) {
// The new PlatformThread will take ownership of the
// DebugExceptionHandler object, which will delete itself on exit.
DebugExceptionHandler* handler = new DebugExceptionHandler(
nacl_process, startup_info, message_loop, on_connected);
if (!base::PlatformThread::CreateNonJoinable(0, handler)) {
on_connected.Run(false);
delete handler;
}
}
<commit_msg>NaCl: Update comment so it doesn't refer to a removed function<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/nacl_debug_exception_handler_win.h"
#include "base/bind.h"
#include "base/process_util.h"
#include "base/threading/platform_thread.h"
#include "base/win/scoped_handle.h"
#include "native_client/src/trusted/service_runtime/win/debug_exception_handler.h"
namespace {
class DebugExceptionHandler : public base::PlatformThread::Delegate {
public:
DebugExceptionHandler(base::ProcessHandle nacl_process,
const std::string& startup_info,
base::MessageLoopProxy* message_loop,
const base::Callback<void(bool)>& on_connected)
: nacl_process_(nacl_process),
startup_info_(startup_info),
message_loop_(message_loop),
on_connected_(on_connected) {
}
virtual void ThreadMain() OVERRIDE {
// In the Windows API, the set of processes being debugged is
// thread-local, so we have to attach to the process (using
// DebugActiveProcess()) on the same thread on which
// NaClDebugExceptionHandlerRun() receives debug events for the
// process.
bool attached = false;
int pid = GetProcessId(nacl_process_);
if (pid == 0) {
LOG(ERROR) << "Invalid process handle";
} else {
if (!DebugActiveProcess(pid)) {
LOG(ERROR) << "Failed to connect to the process";
} else {
attached = true;
}
}
message_loop_->PostTask(FROM_HERE, base::Bind(on_connected_, attached));
if (attached) {
// TODO(mseaborn): Clean up the NaCl side to remove the need for
// a const_cast here.
NaClDebugExceptionHandlerRun(
nacl_process_,
reinterpret_cast<void*>(const_cast<char*>(startup_info_.data())),
startup_info_.size());
}
delete this;
}
private:
base::win::ScopedHandle nacl_process_;
std::string startup_info_;
base::MessageLoopProxy* message_loop_;
base::Callback<void(bool)> on_connected_;
DISALLOW_COPY_AND_ASSIGN(DebugExceptionHandler);
};
} // namespace
void NaClStartDebugExceptionHandlerThread(
base::ProcessHandle nacl_process,
const std::string& startup_info,
base::MessageLoopProxy* message_loop,
const base::Callback<void(bool)>& on_connected) {
// The new PlatformThread will take ownership of the
// DebugExceptionHandler object, which will delete itself on exit.
DebugExceptionHandler* handler = new DebugExceptionHandler(
nacl_process, startup_info, message_loop, on_connected);
if (!base::PlatformThread::CreateNonJoinable(0, handler)) {
on_connected.Run(false);
delete handler;
}
}
<|endoftext|> |
<commit_before>#include "ezOptionParser_clean.hpp"
#include "xiosim/libsim.h"
#include "xiosim/memory.h"
#include "xiosim/sim.h"
#include "xiosim/slices.h"
#include "xiosim/synchronization.h"
#include "xiosim/zesto-structs.h"
#include "BufferManagerConsumer.h"
#include "allocators_impl.h"
#include "ipc_queues.h"
#include "multiprocess_shared.h"
#include "scheduler.h"
#include "timing_sim.h"
const char sim_name[] = "XIOSim";
static sim_thread_state_t thread_states[MAX_CORES];
inline sim_thread_state_t* get_sim_tls(int coreID) { return &thread_states[coreID]; }
using namespace std;
using namespace xiosim; // Until we namespace everything
BaseAllocator* core_allocator = NULL;
/* ========================================================================== */
/* The loop running each simulated core. */
void* SimulatorLoop(void* arg) {
int coreID = static_cast<int>(reinterpret_cast<long>(arg));
sim_thread_state_t* tstate = get_sim_tls(coreID);
while (true) {
/* Check kill flag */
lk_lock(&tstate->lock, 1);
if (!tstate->is_running) {
xiosim::libsim::deactivate_core(coreID);
tstate->sim_stopped = true;
lk_unlock(&tstate->lock);
return NULL;
}
lk_unlock(&tstate->lock);
/* Check for messages coming from producer processes
* and execute accordingly */
CheckIPCMessageQueue(true, coreID);
// Get the latest thread we are running from the scheduler
pid_t instrument_tid = GetCoreThread(coreID);
if (instrument_tid == INVALID_THREADID) {
xio_sleep(10);
continue;
}
/* Process all handshakes in the in-memory consumeBuffer_ at once.
* If there are none, the first call to fron will populate the buffer.
* Doing this helps reduce contention on the IPCMessageQueue lock, which we
* don't need to bang on too frequently. */
int consumerHandshakes = xiosim::buffer_management::GetConsumerSize(instrument_tid);
if (consumerHandshakes == 0) {
xiosim::buffer_management::Front(instrument_tid);
consumerHandshakes = xiosim::buffer_management::GetConsumerSize(instrument_tid);
}
assert(consumerHandshakes > 0);
for (int i = 0; i < consumerHandshakes; i++) {
handshake_container_t* handshake = xiosim::buffer_management::Front(instrument_tid);
assert(handshake != NULL);
assert(handshake->flags.valid);
// Check thread exit flag
if (handshake->flags.killThread) {
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// Let the scheduler send something else to this core
DescheduleActiveThread(coreID);
break;
}
if (handshake->flags.giveCoreUp) {
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// Let the scheduler send something else to this core
GiveUpCore(coreID, handshake->flags.giveUpReschedule);
break;
}
// First instruction, map stack pages, and flag we're not safe to kill
if (handshake->flags.isFirstInsn) {
md_addr_t esp = handshake->rSP;
md_addr_t bos;
lk_lock(lk_thread_bos, 1);
bos = thread_bos->at(instrument_tid);
lk_unlock(lk_thread_bos);
xiosim::memory::map_stack(handshake->asid, esp, bos);
lk_lock(&tstate->lock, 1);
tstate->sim_stopped = false;
lk_unlock(&tstate->lock);
}
// Actual simulation happens here
xiosim::libsim::simulate_handshake(coreID, handshake);
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// The scheduler has decided it's our time to let go of this core.
if (NeedsReschedule(coreID)) {
GiveUpCore(coreID, true);
break;
}
}
}
return NULL;
}
/* ========================================================================== */
/* Create simulator threads, and wait until they finish. */
void SpawnSimulatorThreads(int numCores) {
pthread_t* threads = new pthread_t[numCores];
/* Spawn all threads */
for (int i = 0; i < numCores; i++) {
pthread_t child;
int res = pthread_create(&child, NULL, SimulatorLoop, reinterpret_cast<void*>(i));
if (res != 0) {
cerr << "Failed spawning sim thread " << i << endl;
abort();
}
cerr << "Spawned sim thread " << i << endl;
threads[i] = child;
}
/* and sleep until the simulation finishes */
for (int i = 0; i < numCores; i++) {
pthread_join(threads[i], NULL);
}
}
/* ========================================================================== */
/* Invariant: we are not simulating anything here. Either:
* - Not in a pinpoints ROI.
* - Anything after PauseSimulation.
* This implies all cores are inactive. And handshake buffers are already
* drained. */
void StopSimulation(bool kill_sim_threads, int caller_coreID) {
if (kill_sim_threads) {
/* Signal simulator threads to die */
for (int coreID = 0; coreID < num_cores; coreID++) {
sim_thread_state_t* curr_tstate = get_sim_tls(coreID);
lk_lock(&curr_tstate->lock, 1);
curr_tstate->is_running = false;
lk_unlock(&curr_tstate->lock);
}
/* Spin until SimulatorLoop actually finishes */
volatile bool is_stopped;
do {
is_stopped = true;
for (int coreID = 0; coreID < num_cores; coreID++) {
if (coreID == caller_coreID)
continue;
sim_thread_state_t* curr_tstate = get_sim_tls(coreID);
lk_lock(&curr_tstate->lock, 1);
is_stopped &= curr_tstate->sim_stopped;
lk_unlock(&curr_tstate->lock);
}
} while (!is_stopped);
}
xiosim::libsim::deinit();
if (kill_sim_threads)
exit(EXIT_SUCCESS);
}
/* ========================================================================== */
/** The command line arguments passed upon invocation need paring because (1)
*the
* command line can have arguments for SimpleScalar and (2) Pin cannot see the
* SimpleScalar's arguments otherwise it will barf; it'll expect KNOB
* declarations for those arguments. Thereforce, we follow a convention that
* anything declared past "-s" and before "--" on the command line must be
* passed along as SimpleScalar's argument list.
*
* SimpleScalar's arguments are extracted out of the command line in twos steps:
* First, we create a new argument vector that can be passed to SimpleScalar.
* This is done by calloc'ing and copying the arguments over. Thereafter, in the
* second stage we nullify SimpleScalar's arguments from the original (Pin's)
* command line so that Pin doesn't see during its own command line parsing
* stage. */
typedef pair<unsigned int, char**> SSARGS;
SSARGS MakeSimpleScalarArgcArgv(unsigned int argc, const char* argv[]) {
using std::string;
char** ssArgv = 0;
unsigned int ssArgBegin = 0;
unsigned int ssArgc = 0;
unsigned int ssArgEnd = argc;
for (unsigned int i = 0; i < argc; i++) {
if ((string(argv[i]) == "-s") || (string(argv[i]) == "--")) {
ssArgBegin = i + 1; // Points to a valid arg
break;
}
}
if (ssArgBegin) {
ssArgc = (ssArgEnd - ssArgBegin) // Specified command line args
+ (2); // Null terminator for argv
} else {
// Coming here implies the command line has not been setup properly even
// to run Pin, so return. Pin will complain appropriately.
return make_pair(argc, const_cast<char**>(argv));
}
// This buffer will hold SimpleScalar's argv
ssArgv = reinterpret_cast<char**>(calloc(ssArgc, sizeof(char*)));
if (ssArgv == NULL) {
std::cerr << "Calloc argv failed" << std::endl;
abort();
}
unsigned int ssArgIndex = 0;
ssArgv[ssArgIndex++] = const_cast<char*>(sim_name); // Does not matter; just for sanity
for (unsigned int pin = ssArgBegin; pin < ssArgEnd; pin++) {
if (string(argv[pin]) != "--") {
string* argvCopy = new string(argv[pin]);
ssArgv[ssArgIndex++] = const_cast<char*>(argvCopy->c_str());
}
}
// Terminate the argv. Ending must terminate with a pointer *referencing* a
// NULL. Simply terminating the end of argv[n] w/ NULL violates conventions
ssArgv[ssArgIndex++] = new char('\0');
return make_pair(ssArgc, ssArgv);
}
/* ========================================================================== */
int main(int argc, const char* argv[]) {
ez::ezOptionParser opts;
opts.overview = "XIOSim timing_sim options";
opts.syntax = "XXX";
opts.add("-1", 1, 1, 0, "Harness PID", "-harness_pid");
opts.add("1", 1, 1, 0, "Number of cores simulated", "-num_cores");
opts.parse(argc, argv);
int harness_pid;
opts.get("-harness_pid")->getInt(harness_pid);
int num_cores;
opts.get("-num_cores")->getInt(num_cores);
InitSharedState(false, harness_pid, num_cores);
xiosim::buffer_management::InitBufferManagerConsumer(harness_pid);
// Prepare args for libsim
SSARGS ssargs = MakeSimpleScalarArgcArgv(argc, argv);
xiosim::libsim::init(ssargs.first, ssargs.second);
InitScheduler(num_cores);
// The following core/uncore power values correspond to 20% of total system
// power going to the uncore.
core_allocator = &(AllocatorParser::Get(knobs.allocator,
knobs.allocator_opt_target,
knobs.speedup_model,
1, // core_power
num_cores / (1 / 0.2 - 1), // uncore_power
num_cores));
SpawnSimulatorThreads(num_cores);
return 0;
}
void CheckIPCMessageQueue(bool isEarly, int caller_coreID) {
/* Grab a message from IPC queue in shared memory */
while (true) {
ipc_message_t ipcMessage;
MessageQueue* q = isEarly ? ipcEarlyMessageQueue : ipcMessageQueue;
lk_lock(lk_ipcMessageQueue, 1);
if (q->empty()) {
lk_unlock(lk_ipcMessageQueue);
break;
}
ipcMessage = q->front();
q->pop_front();
lk_unlock(lk_ipcMessageQueue);
#ifdef IPC_DEBUG
lk_lock(printing_lock, 1);
std::cerr << "IPC message, ID: " << ipcMessage.id << " early: " << isEarly << std::endl;
lk_unlock(printing_lock);
#endif
std::vector<int> ack_list;
bool ack_list_valid = false;
/* And execute the appropriate call based on the protocol
* defined in interface.h */
switch (ipcMessage.id) {
/* Sim control related */
case SLICE_START:
start_slice(ipcMessage.arg0);
break;
case SLICE_END:
end_slice(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
/* Shadow page table related */
case MMAP:
xiosim::memory::notify_mmap(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2, ipcMessage.arg3);
break;
case MUNMAP:
xiosim::memory::notify_munmap(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2, ipcMessage.arg3);
break;
case UPDATE_BRK:
xiosim::memory::update_brk(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
/* Warm caches */
case WARM_LLC:
xiosim::libsim::simulate_warmup(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
case STOP_SIMULATION:
StopSimulation(ipcMessage.arg0, caller_coreID);
break;
case ACTIVATE_CORE:
xiosim::libsim::activate_core(ipcMessage.arg0);
break;
case DEACTIVATE_CORE:
xiosim::libsim::deactivate_core(ipcMessage.arg0);
break;
case SCHEDULE_NEW_THREAD:
ScheduleNewThread(ipcMessage.arg0);
break;
case SCHEDULE_PROCESS_THREADS: {
list<pid_t> threads;
for (unsigned int i = 0; i < ipcMessage.MAX_ARR_SIZE; i++) {
int32_t tid = (int32_t)ipcMessage.arg_array[i];
if (tid != -1)
threads.push_back(tid);
}
xiosim::ScheduleProcessThreads(ipcMessage.arg0, threads);
} break;
case ALLOCATE_THREAD:
xiosim::buffer_management::AllocateThreadConsumer(ipcMessage.arg0, ipcMessage.arg1);
break;
case THREAD_AFFINITY:
xiosim::SetThreadAffinity(ipcMessage.arg0, ipcMessage.arg1);
break;
case ALLOCATE_CORES: {
vector<double> scaling;
for (unsigned int i = 0; i < ipcMessage.MAX_ARR_SIZE; i++) {
double speedup = ipcMessage.arg_array[i];
if (speedup != -1)
scaling.push_back(speedup);
}
core_allocator->AllocateCoresForProcess(ipcMessage.arg0, scaling, ipcMessage.arg1);
ack_list = core_allocator->get_processes_to_unblock(ipcMessage.arg0);
ack_list_valid = true;
break;
}
case DEALLOCATE_CORES:
core_allocator->DeallocateCoresForProcess(ipcMessage.arg0);
break;
default:
abort();
break;
}
/* Handle blocking message acknowledgement. */
if (ipcMessage.blocking) {
/* Typically, a blocking message is ack-ed straight away and
* all is good with the world. */
if (!ack_list_valid) {
lk_lock(lk_ipcMessageQueue, 1);
assert(ackMessages->at(ipcMessage) == false);
ackMessages->at(ipcMessage) = true;
lk_unlock(lk_ipcMessageQueue);
} else {
/* Some messages are special. They want to ack a (possibly empty)
* list of messages of the same type (say, ack everyone after we are
* done with the last one). */
lk_lock(lk_ipcMessageQueue, 1);
for (int unblock_asid : ack_list) {
for (auto ack_it = ackMessages->begin(); ack_it != ackMessages->end();
++ack_it) {
if (ack_it->first.id == ipcMessage.id &&
ack_it->first.arg0 == unblock_asid) {
assert(ack_it->second == false);
ackMessages->at(ack_it->first) = true;
}
}
}
lk_unlock(lk_ipcMessageQueue);
}
}
}
}
<commit_msg>Fix handshake use-after-invalidate.<commit_after>#include "ezOptionParser_clean.hpp"
#include "xiosim/libsim.h"
#include "xiosim/memory.h"
#include "xiosim/sim.h"
#include "xiosim/slices.h"
#include "xiosim/synchronization.h"
#include "xiosim/zesto-structs.h"
#include "BufferManagerConsumer.h"
#include "allocators_impl.h"
#include "ipc_queues.h"
#include "multiprocess_shared.h"
#include "scheduler.h"
#include "timing_sim.h"
const char sim_name[] = "XIOSim";
static sim_thread_state_t thread_states[MAX_CORES];
inline sim_thread_state_t* get_sim_tls(int coreID) { return &thread_states[coreID]; }
using namespace std;
using namespace xiosim; // Until we namespace everything
BaseAllocator* core_allocator = NULL;
/* ========================================================================== */
/* The loop running each simulated core. */
void* SimulatorLoop(void* arg) {
int coreID = static_cast<int>(reinterpret_cast<long>(arg));
sim_thread_state_t* tstate = get_sim_tls(coreID);
while (true) {
/* Check kill flag */
lk_lock(&tstate->lock, 1);
if (!tstate->is_running) {
xiosim::libsim::deactivate_core(coreID);
tstate->sim_stopped = true;
lk_unlock(&tstate->lock);
return NULL;
}
lk_unlock(&tstate->lock);
/* Check for messages coming from producer processes
* and execute accordingly */
CheckIPCMessageQueue(true, coreID);
// Get the latest thread we are running from the scheduler
pid_t instrument_tid = GetCoreThread(coreID);
if (instrument_tid == INVALID_THREADID) {
xio_sleep(10);
continue;
}
/* Process all handshakes in the in-memory consumeBuffer_ at once.
* If there are none, the first call to fron will populate the buffer.
* Doing this helps reduce contention on the IPCMessageQueue lock, which we
* don't need to bang on too frequently. */
int consumerHandshakes = xiosim::buffer_management::GetConsumerSize(instrument_tid);
if (consumerHandshakes == 0) {
xiosim::buffer_management::Front(instrument_tid);
consumerHandshakes = xiosim::buffer_management::GetConsumerSize(instrument_tid);
}
assert(consumerHandshakes > 0);
for (int i = 0; i < consumerHandshakes; i++) {
handshake_container_t* handshake = xiosim::buffer_management::Front(instrument_tid);
assert(handshake != NULL);
assert(handshake->flags.valid);
// Check thread exit flag
if (handshake->flags.killThread) {
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// Let the scheduler send something else to this core
DescheduleActiveThread(coreID);
break;
}
if (handshake->flags.giveCoreUp) {
bool should_reschedule = handshake->flags.giveUpReschedule;
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// Let the scheduler send something else to this core
GiveUpCore(coreID, should_reschedule);
break;
}
// First instruction, map stack pages, and flag we're not safe to kill
if (handshake->flags.isFirstInsn) {
md_addr_t esp = handshake->rSP;
md_addr_t bos;
lk_lock(lk_thread_bos, 1);
bos = thread_bos->at(instrument_tid);
lk_unlock(lk_thread_bos);
xiosim::memory::map_stack(handshake->asid, esp, bos);
lk_lock(&tstate->lock, 1);
tstate->sim_stopped = false;
lk_unlock(&tstate->lock);
}
// Actual simulation happens here
xiosim::libsim::simulate_handshake(coreID, handshake);
// invalidate the handshake
xiosim::buffer_management::Pop(instrument_tid);
// The scheduler has decided it's our time to let go of this core.
if (NeedsReschedule(coreID)) {
GiveUpCore(coreID, true);
break;
}
}
}
return NULL;
}
/* ========================================================================== */
/* Create simulator threads, and wait until they finish. */
void SpawnSimulatorThreads(int numCores) {
pthread_t* threads = new pthread_t[numCores];
/* Spawn all threads */
for (int i = 0; i < numCores; i++) {
pthread_t child;
int res = pthread_create(&child, NULL, SimulatorLoop, reinterpret_cast<void*>(i));
if (res != 0) {
cerr << "Failed spawning sim thread " << i << endl;
abort();
}
cerr << "Spawned sim thread " << i << endl;
threads[i] = child;
}
/* and sleep until the simulation finishes */
for (int i = 0; i < numCores; i++) {
pthread_join(threads[i], NULL);
}
}
/* ========================================================================== */
/* Invariant: we are not simulating anything here. Either:
* - Not in a pinpoints ROI.
* - Anything after PauseSimulation.
* This implies all cores are inactive. And handshake buffers are already
* drained. */
void StopSimulation(bool kill_sim_threads, int caller_coreID) {
if (kill_sim_threads) {
/* Signal simulator threads to die */
for (int coreID = 0; coreID < num_cores; coreID++) {
sim_thread_state_t* curr_tstate = get_sim_tls(coreID);
lk_lock(&curr_tstate->lock, 1);
curr_tstate->is_running = false;
lk_unlock(&curr_tstate->lock);
}
/* Spin until SimulatorLoop actually finishes */
volatile bool is_stopped;
do {
is_stopped = true;
for (int coreID = 0; coreID < num_cores; coreID++) {
if (coreID == caller_coreID)
continue;
sim_thread_state_t* curr_tstate = get_sim_tls(coreID);
lk_lock(&curr_tstate->lock, 1);
is_stopped &= curr_tstate->sim_stopped;
lk_unlock(&curr_tstate->lock);
}
} while (!is_stopped);
}
xiosim::libsim::deinit();
if (kill_sim_threads)
exit(EXIT_SUCCESS);
}
/* ========================================================================== */
/** The command line arguments passed upon invocation need paring because (1)
*the
* command line can have arguments for SimpleScalar and (2) Pin cannot see the
* SimpleScalar's arguments otherwise it will barf; it'll expect KNOB
* declarations for those arguments. Thereforce, we follow a convention that
* anything declared past "-s" and before "--" on the command line must be
* passed along as SimpleScalar's argument list.
*
* SimpleScalar's arguments are extracted out of the command line in twos steps:
* First, we create a new argument vector that can be passed to SimpleScalar.
* This is done by calloc'ing and copying the arguments over. Thereafter, in the
* second stage we nullify SimpleScalar's arguments from the original (Pin's)
* command line so that Pin doesn't see during its own command line parsing
* stage. */
typedef pair<unsigned int, char**> SSARGS;
SSARGS MakeSimpleScalarArgcArgv(unsigned int argc, const char* argv[]) {
using std::string;
char** ssArgv = 0;
unsigned int ssArgBegin = 0;
unsigned int ssArgc = 0;
unsigned int ssArgEnd = argc;
for (unsigned int i = 0; i < argc; i++) {
if ((string(argv[i]) == "-s") || (string(argv[i]) == "--")) {
ssArgBegin = i + 1; // Points to a valid arg
break;
}
}
if (ssArgBegin) {
ssArgc = (ssArgEnd - ssArgBegin) // Specified command line args
+ (2); // Null terminator for argv
} else {
// Coming here implies the command line has not been setup properly even
// to run Pin, so return. Pin will complain appropriately.
return make_pair(argc, const_cast<char**>(argv));
}
// This buffer will hold SimpleScalar's argv
ssArgv = reinterpret_cast<char**>(calloc(ssArgc, sizeof(char*)));
if (ssArgv == NULL) {
std::cerr << "Calloc argv failed" << std::endl;
abort();
}
unsigned int ssArgIndex = 0;
ssArgv[ssArgIndex++] = const_cast<char*>(sim_name); // Does not matter; just for sanity
for (unsigned int pin = ssArgBegin; pin < ssArgEnd; pin++) {
if (string(argv[pin]) != "--") {
string* argvCopy = new string(argv[pin]);
ssArgv[ssArgIndex++] = const_cast<char*>(argvCopy->c_str());
}
}
// Terminate the argv. Ending must terminate with a pointer *referencing* a
// NULL. Simply terminating the end of argv[n] w/ NULL violates conventions
ssArgv[ssArgIndex++] = new char('\0');
return make_pair(ssArgc, ssArgv);
}
/* ========================================================================== */
int main(int argc, const char* argv[]) {
ez::ezOptionParser opts;
opts.overview = "XIOSim timing_sim options";
opts.syntax = "XXX";
opts.add("-1", 1, 1, 0, "Harness PID", "-harness_pid");
opts.add("1", 1, 1, 0, "Number of cores simulated", "-num_cores");
opts.parse(argc, argv);
int harness_pid;
opts.get("-harness_pid")->getInt(harness_pid);
int num_cores;
opts.get("-num_cores")->getInt(num_cores);
InitSharedState(false, harness_pid, num_cores);
xiosim::buffer_management::InitBufferManagerConsumer(harness_pid);
// Prepare args for libsim
SSARGS ssargs = MakeSimpleScalarArgcArgv(argc, argv);
xiosim::libsim::init(ssargs.first, ssargs.second);
InitScheduler(num_cores);
// The following core/uncore power values correspond to 20% of total system
// power going to the uncore.
core_allocator = &(AllocatorParser::Get(knobs.allocator,
knobs.allocator_opt_target,
knobs.speedup_model,
1, // core_power
num_cores / (1 / 0.2 - 1), // uncore_power
num_cores));
SpawnSimulatorThreads(num_cores);
return 0;
}
void CheckIPCMessageQueue(bool isEarly, int caller_coreID) {
/* Grab a message from IPC queue in shared memory */
while (true) {
ipc_message_t ipcMessage;
MessageQueue* q = isEarly ? ipcEarlyMessageQueue : ipcMessageQueue;
lk_lock(lk_ipcMessageQueue, 1);
if (q->empty()) {
lk_unlock(lk_ipcMessageQueue);
break;
}
ipcMessage = q->front();
q->pop_front();
lk_unlock(lk_ipcMessageQueue);
#ifdef IPC_DEBUG
lk_lock(printing_lock, 1);
std::cerr << "IPC message, ID: " << ipcMessage.id << " early: " << isEarly << std::endl;
lk_unlock(printing_lock);
#endif
std::vector<int> ack_list;
bool ack_list_valid = false;
/* And execute the appropriate call based on the protocol
* defined in interface.h */
switch (ipcMessage.id) {
/* Sim control related */
case SLICE_START:
start_slice(ipcMessage.arg0);
break;
case SLICE_END:
end_slice(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
/* Shadow page table related */
case MMAP:
xiosim::memory::notify_mmap(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2, ipcMessage.arg3);
break;
case MUNMAP:
xiosim::memory::notify_munmap(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2, ipcMessage.arg3);
break;
case UPDATE_BRK:
xiosim::memory::update_brk(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
/* Warm caches */
case WARM_LLC:
xiosim::libsim::simulate_warmup(ipcMessage.arg0, ipcMessage.arg1, ipcMessage.arg2);
break;
case STOP_SIMULATION:
StopSimulation(ipcMessage.arg0, caller_coreID);
break;
case ACTIVATE_CORE:
xiosim::libsim::activate_core(ipcMessage.arg0);
break;
case DEACTIVATE_CORE:
xiosim::libsim::deactivate_core(ipcMessage.arg0);
break;
case SCHEDULE_NEW_THREAD:
ScheduleNewThread(ipcMessage.arg0);
break;
case SCHEDULE_PROCESS_THREADS: {
list<pid_t> threads;
for (unsigned int i = 0; i < ipcMessage.MAX_ARR_SIZE; i++) {
int32_t tid = (int32_t)ipcMessage.arg_array[i];
if (tid != -1)
threads.push_back(tid);
}
xiosim::ScheduleProcessThreads(ipcMessage.arg0, threads);
} break;
case ALLOCATE_THREAD:
xiosim::buffer_management::AllocateThreadConsumer(ipcMessage.arg0, ipcMessage.arg1);
break;
case THREAD_AFFINITY:
xiosim::SetThreadAffinity(ipcMessage.arg0, ipcMessage.arg1);
break;
case ALLOCATE_CORES: {
vector<double> scaling;
for (unsigned int i = 0; i < ipcMessage.MAX_ARR_SIZE; i++) {
double speedup = ipcMessage.arg_array[i];
if (speedup != -1)
scaling.push_back(speedup);
}
core_allocator->AllocateCoresForProcess(ipcMessage.arg0, scaling, ipcMessage.arg1);
ack_list = core_allocator->get_processes_to_unblock(ipcMessage.arg0);
ack_list_valid = true;
break;
}
case DEALLOCATE_CORES:
core_allocator->DeallocateCoresForProcess(ipcMessage.arg0);
break;
default:
abort();
break;
}
/* Handle blocking message acknowledgement. */
if (ipcMessage.blocking) {
/* Typically, a blocking message is ack-ed straight away and
* all is good with the world. */
if (!ack_list_valid) {
lk_lock(lk_ipcMessageQueue, 1);
assert(ackMessages->at(ipcMessage) == false);
ackMessages->at(ipcMessage) = true;
lk_unlock(lk_ipcMessageQueue);
} else {
/* Some messages are special. They want to ack a (possibly empty)
* list of messages of the same type (say, ack everyone after we are
* done with the last one). */
lk_lock(lk_ipcMessageQueue, 1);
for (int unblock_asid : ack_list) {
for (auto ack_it = ackMessages->begin(); ack_it != ackMessages->end();
++ack_it) {
if (ack_it->first.id == ipcMessage.id &&
ack_it->first.arg0 == unblock_asid) {
assert(ack_it->second == false);
ackMessages->at(ack_it->first) = true;
}
}
}
lk_unlock(lk_ipcMessageQueue);
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_PFHRGB_H_
#define PCL_FEATURES_IMPL_PFHRGB_H_
#include <pcl/features/pfhrgb.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computeRGBPairFeatures (
const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
int p_idx, int q_idx,
float &f1, float &f2, float &f3, float &f4, float &f5, float &f6, float &f7)
{
Eigen::Vector4i colors1 (cloud.points[p_idx].r, cloud.points[p_idx].g, cloud.points[p_idx].b, 0),
colors2 (cloud.points[q_idx].r, cloud.points[q_idx].g, cloud.points[q_idx].b, 0);
pcl::computeRGBPairFeatures (cloud.points[p_idx].getVector4fMap (), normals.points[p_idx].getNormalVector4fMap (),
colors1,
cloud.points[q_idx].getVector4fMap (), normals.points[q_idx].getNormalVector4fMap (),
colors2,
f1, f2, f3, f4, f5, f6, f7);
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computePointPFHRGBSignature (
const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
const std::vector<int> &indices, int nr_split, Eigen::VectorXf &pfhrgb_histogram)
{
int h_index, h_p;
// Clear the resultant point histogram
pfhrgb_histogram.setZero ();
// Factorization constant
float hist_incr = 100.0f / static_cast<float> (indices.size () * indices.size () - 1);
// Iterate over all the points in the neighborhood
for (size_t i_idx = 0; i_idx < indices.size (); ++i_idx)
{
for (size_t j_idx = 0; j_idx < indices.size (); ++j_idx)
{
// Avoid unnecessary returns
if (i_idx == j_idx)
continue;
// Compute the pair NNi to NNj
if (!computeRGBPairFeatures (cloud, normals, indices[i_idx], indices[j_idx],
pfhrgb_tuple_[0], pfhrgb_tuple_[1], pfhrgb_tuple_[2], pfhrgb_tuple_[3],
pfhrgb_tuple_[4], pfhrgb_tuple_[5], pfhrgb_tuple_[6]))
continue;
// Normalize the f1, f2, f3, f5, f6, f7 features and push them in the histogram
f_index_[0] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[0] + M_PI) * d_pi_)));
if (f_index_[0] < 0) f_index_[0] = 0;
if (f_index_[0] >= nr_split) f_index_[0] = nr_split - 1;
f_index_[1] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[1] + 1.0) * 0.5)));
if (f_index_[1] < 0) f_index_[1] = 0;
if (f_index_[1] >= nr_split) f_index_[1] = nr_split - 1;
f_index_[2] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[2] + 1.0) * 0.5)));
if (f_index_[2] < 0) f_index_[2] = 0;
if (f_index_[2] >= nr_split) f_index_[2] = nr_split - 1;
// color ratios are in [-1, 1]
f_index_[4] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[4] + 1.0) * 0.5)));
if (f_index_[4] < 0) f_index_[4] = 0;
if (f_index_[4] >= nr_split) f_index_[4] = nr_split - 1;
f_index_[5] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[5] + 1.0) * 0.5)));
if (f_index_[5] < 0) f_index_[5] = 0;
if (f_index_[5] >= nr_split) f_index_[5] = nr_split - 1;
f_index_[6] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[6] + 1.0) * 0.5)));
if (f_index_[6] < 0) f_index_[6] = 0;
if (f_index_[6] >= nr_split) f_index_[6] = nr_split - 1;
// Copy into the histogram
h_index = 0;
h_p = 1;
for (int d = 0; d < 3; ++d)
{
h_index += h_p * f_index_[d];
h_p *= nr_split;
}
pfhrgb_histogram[h_index] += hist_incr;
// and the colors
h_index = 125;
h_p = 1;
for (int d = 4; d < 7; ++d)
{
h_index += h_p * f_index_[d];
h_p *= nr_split;
}
pfhrgb_histogram[h_index] += hist_incr;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
/// nr_subdiv^3 for RGB and nr_subdiv^3 for the angular features
pfhrgb_histogram_.setZero (2 * nr_subdiv_ * nr_subdiv_ * nr_subdiv_);
pfhrgb_tuple_.setZero (7);
// Allocate enough space to hold the results
// \note This resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists);
// Estimate the PFH signature at each patch
computePointPFHRGBSignature (*surface_, *normals_, nn_indices, nr_subdiv_, pfhrgb_histogram_);
// Copy into the resultant cloud
for (int d = 0; d < pfhrgb_histogram_.size (); ++d) {
output.points[idx].histogram[d] = pfhrgb_histogram_[d];
// PCL_INFO ("%f ", pfhrgb_histogram_[d]);
}
// PCL_INFO ("\n");
}
}
#define PCL_INSTANTIATE_PFHRGBEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PFHRGBEstimation<T,NT,OutT>;
#endif /* PCL_FEATURES_IMPL_PFHRGB_H_ */
<commit_msg>Fix histogram computation: missing parenthesis<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_PFHRGB_H_
#define PCL_FEATURES_IMPL_PFHRGB_H_
#include <pcl/features/pfhrgb.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> bool
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computeRGBPairFeatures (
const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
int p_idx, int q_idx,
float &f1, float &f2, float &f3, float &f4, float &f5, float &f6, float &f7)
{
Eigen::Vector4i colors1 (cloud.points[p_idx].r, cloud.points[p_idx].g, cloud.points[p_idx].b, 0),
colors2 (cloud.points[q_idx].r, cloud.points[q_idx].g, cloud.points[q_idx].b, 0);
pcl::computeRGBPairFeatures (cloud.points[p_idx].getVector4fMap (), normals.points[p_idx].getNormalVector4fMap (),
colors1,
cloud.points[q_idx].getVector4fMap (), normals.points[q_idx].getNormalVector4fMap (),
colors2,
f1, f2, f3, f4, f5, f6, f7);
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computePointPFHRGBSignature (
const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
const std::vector<int> &indices, int nr_split, Eigen::VectorXf &pfhrgb_histogram)
{
int h_index, h_p;
// Clear the resultant point histogram
pfhrgb_histogram.setZero ();
// Factorization constant
float hist_incr = 100.0f / static_cast<float> (indices.size () * (indices.size () - 1) / 2);
// Iterate over all the points in the neighborhood
for (size_t i_idx = 0; i_idx < indices.size (); ++i_idx)
{
for (size_t j_idx = 0; j_idx < indices.size (); ++j_idx)
{
// Avoid unnecessary returns
if (i_idx == j_idx)
continue;
// Compute the pair NNi to NNj
if (!computeRGBPairFeatures (cloud, normals, indices[i_idx], indices[j_idx],
pfhrgb_tuple_[0], pfhrgb_tuple_[1], pfhrgb_tuple_[2], pfhrgb_tuple_[3],
pfhrgb_tuple_[4], pfhrgb_tuple_[5], pfhrgb_tuple_[6]))
continue;
// Normalize the f1, f2, f3, f5, f6, f7 features and push them in the histogram
f_index_[0] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[0] + M_PI) * d_pi_)));
if (f_index_[0] < 0) f_index_[0] = 0;
if (f_index_[0] >= nr_split) f_index_[0] = nr_split - 1;
f_index_[1] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[1] + 1.0) * 0.5)));
if (f_index_[1] < 0) f_index_[1] = 0;
if (f_index_[1] >= nr_split) f_index_[1] = nr_split - 1;
f_index_[2] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[2] + 1.0) * 0.5)));
if (f_index_[2] < 0) f_index_[2] = 0;
if (f_index_[2] >= nr_split) f_index_[2] = nr_split - 1;
// color ratios are in [-1, 1]
f_index_[4] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[4] + 1.0) * 0.5)));
if (f_index_[4] < 0) f_index_[4] = 0;
if (f_index_[4] >= nr_split) f_index_[4] = nr_split - 1;
f_index_[5] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[5] + 1.0) * 0.5)));
if (f_index_[5] < 0) f_index_[5] = 0;
if (f_index_[5] >= nr_split) f_index_[5] = nr_split - 1;
f_index_[6] = static_cast<int> (floor (nr_split * ((pfhrgb_tuple_[6] + 1.0) * 0.5)));
if (f_index_[6] < 0) f_index_[6] = 0;
if (f_index_[6] >= nr_split) f_index_[6] = nr_split - 1;
// Copy into the histogram
h_index = 0;
h_p = 1;
for (int d = 0; d < 3; ++d)
{
h_index += h_p * f_index_[d];
h_p *= nr_split;
}
pfhrgb_histogram[h_index] += hist_incr;
// and the colors
h_index = 125;
h_p = 1;
for (int d = 4; d < 7; ++d)
{
h_index += h_p * f_index_[d];
h_p *= nr_split;
}
pfhrgb_histogram[h_index] += hist_incr;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PFHRGBEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
/// nr_subdiv^3 for RGB and nr_subdiv^3 for the angular features
pfhrgb_histogram_.setZero (2 * nr_subdiv_ * nr_subdiv_ * nr_subdiv_);
pfhrgb_tuple_.setZero (7);
// Allocate enough space to hold the results
// \note This resize is irrelevant for a radiusSearch ().
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
// Iterating over the entire index vector
for (size_t idx = 0; idx < indices_->size (); ++idx)
{
this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists);
// Estimate the PFH signature at each patch
computePointPFHRGBSignature (*surface_, *normals_, nn_indices, nr_subdiv_, pfhrgb_histogram_);
// Copy into the resultant cloud
for (int d = 0; d < pfhrgb_histogram_.size (); ++d) {
output.points[idx].histogram[d] = pfhrgb_histogram_[d];
// PCL_INFO ("%f ", pfhrgb_histogram_[d]);
}
// PCL_INFO ("\n");
}
}
#define PCL_INSTANTIATE_PFHRGBEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PFHRGBEstimation<T,NT,OutT>;
#endif /* PCL_FEATURES_IMPL_PFHRGB_H_ */
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under 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)
//=======================================================================
/*
* This file contains the OS specific layer
*/
#include "acpica.hpp"
#include "kalloc.hpp"
#include "console.hpp"
#include "scheduler.hpp"
#include "virtual_allocator.hpp"
#include "paging.hpp"
extern "C" {
// Dynamic allocation
void* AcpiOsAllocate(ACPI_SIZE size){
return kalloc::k_malloc(size);
}
void AcpiOsFree(void* p){
kalloc::k_free(p);
}
// terminal
void AcpiOsPrintf(const char* format, ...){
va_list va;
va_start(va, format);
printf(format, va);
va_end(va);
}
void AcpiOsVprintf(const char* format, va_list va){
printf(format, va);
}
// Scheduling
ACPI_THREAD_ID AcpiOsGetThreadId(void){
return scheduler::get_pid();
}
// ACPI
ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(){
ACPI_PHYSICAL_ADDRESS root_pointer;
root_pointer = 0;
AcpiFindRootPointer(&root_pointer);
return root_pointer;
}
// Paging
void* AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS phys, ACPI_SIZE length){
size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1);
auto virt = virtual_allocator::allocate(pages);
auto phys_aligned = phys - (phys & ~(paging::PAGE_SIZE - 1));
paging::map_pages(virt, phys_aligned, pages);
return reinterpret_cast<void*>(virt + (phys & ~(paging::PAGE_SIZE - 1)));
}
void AcpiOsUnmapMemory(void* virt_aligned_raw, ACPI_SIZE length){
size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1);
auto virt_aligned = reinterpret_cast<size_t>(virt_aligned_raw);
auto virt = virt_aligned - (virt_aligned & ~(paging::PAGE_SIZE - 1));
paging::unmap_pages(virt, pages);
virtual_allocator::free(virt, pages);
}
} //end of extern "C"
<commit_msg>More ACPI OSL<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under 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)
//=======================================================================
/*
* This file contains the OS specific layer
*/
#include "acpica.hpp"
#include "kalloc.hpp"
#include "console.hpp"
#include "scheduler.hpp"
#include "virtual_allocator.hpp"
#include "paging.hpp"
#include "mutex.hpp"
#include "semaphore.hpp"
extern "C" {
// Initialization
ACPI_STATUS AcpiOsInitialize(){
//Nothing to initialize
return AE_OK;
}
ACPI_STATUS AcpiOsTerminate(){
//Nothing to terminate
return AE_OK;
}
// Overriding of ACPI
ACPI_STATUS AcpiOsPredefinedOverride(const ACPI_PREDEFINED_NAMES* /*PredefinedObject*/, ACPI_STRING* new_value){
*new_value = nullptr;
return AE_OK;
}
ACPI_STATUS AcpiOsTableOverride(ACPI_TABLE_HEADER* /*ExistingTable*/, ACPI_TABLE_HEADER** new_table){
*new_table = nullptr;
return AE_OK;
}
ACPI_STATUS AcpiOsPhysicalTableOverride(ACPI_TABLE_HEADER* /*ExistingTable*/, ACPI_PHYSICAL_ADDRESS* new_address, UINT32* new_table_length){
*new_address = 0;
*new_table_length = 0;
return AE_OK;
}
// Dynamic allocation
void* AcpiOsAllocate(ACPI_SIZE size){
return kalloc::k_malloc(size);
}
void AcpiOsFree(void* p){
kalloc::k_free(p);
}
// terminal
void AcpiOsPrintf(const char* format, ...){
va_list va;
va_start(va, format);
printf(format, va);
va_end(va);
}
void AcpiOsVprintf(const char* format, va_list va){
printf(format, va);
}
// Scheduling
ACPI_THREAD_ID AcpiOsGetThreadId(void){
return scheduler::get_pid();
}
// ACPI
ACPI_PHYSICAL_ADDRESS AcpiOsGetRootPointer(){
ACPI_PHYSICAL_ADDRESS root_pointer;
root_pointer = 0;
AcpiFindRootPointer(&root_pointer);
return root_pointer;
}
// Paging
void* AcpiOsMapMemory(ACPI_PHYSICAL_ADDRESS phys, ACPI_SIZE length){
size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1);
auto virt = virtual_allocator::allocate(pages);
auto phys_aligned = phys - (phys & ~(paging::PAGE_SIZE - 1));
paging::map_pages(virt, phys_aligned, pages);
return reinterpret_cast<void*>(virt + (phys & ~(paging::PAGE_SIZE - 1)));
}
void AcpiOsUnmapMemory(void* virt_aligned_raw, ACPI_SIZE length){
size_t pages = (length + paging::PAGE_SIZE - 1) & ~(paging::PAGE_SIZE - 1);
auto virt_aligned = reinterpret_cast<size_t>(virt_aligned_raw);
auto virt = virt_aligned - (virt_aligned & ~(paging::PAGE_SIZE - 1));
paging::unmap_pages(virt, pages);
virtual_allocator::free(virt, pages);
}
// Concurrency
#if (ACPI_MUTEX_TYPE != ACPI_BINARY_SEMAPHORE)
ACPI_STATUS AcpiOsCreateMutex(ACPI_MUTEX* handle){
auto* lock = new mutex<false>();
lock->init();
*handle = lock;
return AE_OK;
}
void AcpiOsDeleteMutex(ACPI_MUTEX handle){
auto* lock = static_cast<mutex<false>*>(handle);
delete lock;
}
ACPI_STATUS AcpiOsAcquireMutex(ACPI_MUTEX handle, UINT16 Timeout){
auto* lock = static_cast<mutex<false>*>(handle);
lock->acquire();
return AE_OK;
}
void AcpiOsReleaseMutex(ACPI_MUTEX handle){
auto* lock = static_cast<mutex<false>*>(handle);
lock->release();
}
#endif
ACPI_STATUS AcpiOsCreateSemaphore(UINT32 /*maxUnits*/, UINT32 initialUnits, ACPI_SEMAPHORE* handle){
auto* lock = new semaphore();
lock->init(initialUnits);
*handle = lock;
return AE_OK;
}
ACPI_STATUS AcpiOsDeleteSemaphore(ACPI_SEMAPHORE handle){
auto* lock = static_cast<semaphore*>(handle);
delete lock;
return AE_OK;
}
ACPI_STATUS AcpiOsWaitSemaphore(ACPI_SEMAPHORE handle, UINT32 units, UINT16 timeout){
auto* lock = static_cast<semaphore*>(handle);
lock->acquire();
return AE_OK;
}
ACPI_STATUS AcpiOsSignalSemaphore(ACPI_SEMAPHORE handle, UINT32 units){
auto* lock = static_cast<semaphore*>(handle);
lock->release();
return AE_OK;
}
} //end of extern "C"
<|endoftext|> |
<commit_before>
#include "LightApp_ShowHideOp.h"
#include "LightApp_Application.h"
#include "LightApp_DataOwner.h"
#include "LightApp_Module.h"
#include "LightApp_Study.h"
#include "LightApp_Displayer.h"
#include "CAM_Study.h"
#include "LightApp_SelectionMgr.h"
#include "LightApp_Selection.h"
#include <SALOME_ListIO.hxx>
#include <SALOME_ListIteratorOfListIO.hxx>
LightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )
: LightApp_Operation(),
myActionType( type )
{
}
LightApp_ShowHideOp::~LightApp_ShowHideOp()
{
}
LightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
LightApp_Module* m = dynamic_cast<LightApp_Module*>( app ? app->module( mod_name ) : 0 );
if( !m )
{
m = dynamic_cast<LightApp_Module*>( app->loadModule( mod_name ) );
if( m )
{
app->addModule( m );
m->connectToStudy( dynamic_cast<CAM_Study*>( app->activeStudy() ) );
m->setMenuShown( false );
m->setToolShown( false );
}
}
return m ? m->displayer() : 0;
}
void LightApp_ShowHideOp::startOperation()
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
LightApp_Study* study = app ? dynamic_cast<LightApp_Study*>( app->activeStudy() ) : 0;
if( !app || !study )
{
abort();
return;
}
LightApp_SelectionMgr* mgr = app->selectionMgr();
LightApp_Selection sel; sel.init( "", mgr );
if( sel.count()==0 && myActionType!=ERASE_ALL )
{
abort();
return;
}
QString aStr = sel.param( 0, "component" ).toString();
QString mod_name = app->moduleTitle( aStr );//sel.param( 0, "component" ).toString() );
LightApp_Displayer* d = displayer( mod_name );
if( !d )
{
abort();
return;
}
if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )
{
//ERASE ALL
QStringList comps;
study->components( comps );
QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();
for( ; anIt!=aLast; anIt++ )
{
LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );
if( disp )
disp->EraseAll( false, false, 0 );
}
if( myActionType==ERASE_ALL )
{
d->UpdateViewer();
commit();
return;
}
}
SALOME_ListIO selObjs;
mgr->selectedObjects( selObjs );
QStringList entries;
SALOME_ListIteratorOfListIO anIt( selObjs );
for( ; anIt.More(); anIt.Next() )
{
if( anIt.Value().IsNull() )
continue;
if( study->isComponent( anIt.Value()->getEntry() ) )
study->children( anIt.Value()->getEntry(), entries );
else
entries.append( anIt.Value()->getEntry() );
}
for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )
{
QString e = study->referencedToEntry( *it );
if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )
d->Display( e, false, 0 );
else if( myActionType==ERASE )
d->Erase( e, false, false, 0 );
}
d->UpdateViewer();
commit();
}
<commit_msg>PAL10479<commit_after>
#include "LightApp_ShowHideOp.h"
#include "LightApp_Application.h"
#include "LightApp_DataOwner.h"
#include "LightApp_Module.h"
#include "LightApp_Study.h"
#include "LightApp_Displayer.h"
#include "CAM_Study.h"
#include "LightApp_SelectionMgr.h"
#include "LightApp_Selection.h"
#include <SALOME_ListIO.hxx>
#include <SALOME_ListIteratorOfListIO.hxx>
LightApp_ShowHideOp::LightApp_ShowHideOp( ActionType type )
: LightApp_Operation(),
myActionType( type )
{
}
LightApp_ShowHideOp::~LightApp_ShowHideOp()
{
}
LightApp_Displayer* LightApp_ShowHideOp::displayer( const QString& mod_name ) const
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
LightApp_Module* m = dynamic_cast<LightApp_Module*>( app ? app->module( mod_name ) : 0 );
if( !m )
{
m = dynamic_cast<LightApp_Module*>( app->loadModule( mod_name ) );
if( m )
app->addModule( m );
}
if( m )
{
m->connectToStudy( dynamic_cast<CAM_Study*>( app->activeStudy() ) );
m->setMenuShown( false );
m->setToolShown( false );
}
return m ? m->displayer() : 0;
}
void LightApp_ShowHideOp::startOperation()
{
LightApp_Application* app = dynamic_cast<LightApp_Application*>( application() );
LightApp_Study* study = app ? dynamic_cast<LightApp_Study*>( app->activeStudy() ) : 0;
if( !app || !study )
{
abort();
return;
}
LightApp_SelectionMgr* mgr = app->selectionMgr();
LightApp_Selection sel; sel.init( "", mgr );
if( sel.count()==0 && myActionType!=ERASE_ALL )
{
abort();
return;
}
QString aStr = sel.param( 0, "component" ).toString();
QString mod_name = app->moduleTitle( aStr );//sel.param( 0, "component" ).toString() );
LightApp_Displayer* d = displayer( mod_name );
if( !d )
{
abort();
return;
}
if( myActionType==DISPLAY_ONLY || myActionType==ERASE_ALL )
{
//ERASE ALL
QStringList comps;
study->components( comps );
QStringList::const_iterator anIt = comps.begin(), aLast = comps.end();
for( ; anIt!=aLast; anIt++ )
{
LightApp_Displayer* disp = displayer( app->moduleTitle( *anIt ) );
if( disp )
disp->EraseAll( false, false, 0 );
}
if( myActionType==ERASE_ALL )
{
d->UpdateViewer();
commit();
return;
}
}
SALOME_ListIO selObjs;
mgr->selectedObjects( selObjs );
QStringList entries;
SALOME_ListIteratorOfListIO anIt( selObjs );
for( ; anIt.More(); anIt.Next() )
{
if( anIt.Value().IsNull() )
continue;
if( study->isComponent( anIt.Value()->getEntry() ) )
study->children( anIt.Value()->getEntry(), entries );
else
entries.append( anIt.Value()->getEntry() );
}
for( QStringList::const_iterator it = entries.begin(), last = entries.end(); it!=last; it++ )
{
QString e = study->referencedToEntry( *it );
if( myActionType==DISPLAY || myActionType==DISPLAY_ONLY )
d->Display( e, false, 0 );
else if( myActionType==ERASE )
d->Erase( e, false, false, 0 );
}
d->UpdateViewer();
commit();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRepAlgoAPI_Fuse.hxx>
#endif
#include "FeaturePartFuse.h"
#include <Base/Exception.h>
using namespace Part;
PROPERTY_SOURCE(Part::Fuse, Part::Boolean)
Fuse::Fuse(void)
{
}
TopoDS_Shape Fuse::runOperation(const TopoDS_Shape& base, const TopoDS_Shape& tool) const
{
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(base, tool);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
return mkFuse.Shape();
}
// ----------------------------------------------------
PROPERTY_SOURCE(Part::MultiFuse, Part::Feature)
MultiFuse::MultiFuse(void)
{
ADD_PROPERTY(Shapes,(0));
Shapes.setSize(0);
}
short MultiFuse::mustExecute() const
{
if (Shapes.isTouched())
return 1;
return 0;
}
App::DocumentObjectExecReturn *MultiFuse::execute(void)
{
std::vector<TopoDS_Shape> s;
std::vector<App::DocumentObject*> obj = Shapes.getValues();
std::vector<App::DocumentObject*>::iterator it;
for (it = obj.begin(); it != obj.end(); ++it) {
if ((*it)->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
s.push_back(static_cast<Part::Feature*>(*it)->Shape.getValue());
}
}
if (s.size() >= 2) {
TopoDS_Shape res = s.front();
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(res, *it);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
res = mkFuse.Shape();
}
if (res.IsNull())
throw Base::Exception("Resulting shape is invalid");
this->Shape.setValue(res);
}
else {
throw Base::Exception("Not enough shape objects linked");
}
return App::DocumentObject::StdReturn;
}
<commit_msg>0000570: App::Document::_RecomputeFeature(): Unknown exception in Feature "Fusion" thrown<commit_after>/***************************************************************************
* Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <BRepAlgoAPI_Fuse.hxx>
# include <Standard_Failure.hxx>
#endif
#include "FeaturePartFuse.h"
#include <Base/Exception.h>
using namespace Part;
PROPERTY_SOURCE(Part::Fuse, Part::Boolean)
Fuse::Fuse(void)
{
}
TopoDS_Shape Fuse::runOperation(const TopoDS_Shape& base, const TopoDS_Shape& tool) const
{
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(base, tool);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
return mkFuse.Shape();
}
// ----------------------------------------------------
PROPERTY_SOURCE(Part::MultiFuse, Part::Feature)
MultiFuse::MultiFuse(void)
{
ADD_PROPERTY(Shapes,(0));
Shapes.setSize(0);
}
short MultiFuse::mustExecute() const
{
if (Shapes.isTouched())
return 1;
return 0;
}
App::DocumentObjectExecReturn *MultiFuse::execute(void)
{
std::vector<TopoDS_Shape> s;
std::vector<App::DocumentObject*> obj = Shapes.getValues();
std::vector<App::DocumentObject*>::iterator it;
for (it = obj.begin(); it != obj.end(); ++it) {
if ((*it)->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
s.push_back(static_cast<Part::Feature*>(*it)->Shape.getValue());
}
}
if (s.size() >= 2) {
try {
TopoDS_Shape res = s.front();
for (std::vector<TopoDS_Shape>::iterator it = s.begin()+1; it != s.end(); ++it) {
// Let's call algorithm computing a fuse operation:
BRepAlgoAPI_Fuse mkFuse(res, *it);
// Let's check if the fusion has been successful
if (!mkFuse.IsDone())
throw Base::Exception("Fusion failed");
res = mkFuse.Shape();
}
if (res.IsNull())
throw Base::Exception("Resulting shape is invalid");
this->Shape.setValue(res);
}
catch (Standard_Failure) {
Handle_Standard_Failure e = Standard_Failure::Caught();
return new App::DocumentObjectExecReturn(e->GetMessageString());
}
}
else {
throw Base::Exception("Not enough shape objects linked");
}
return App::DocumentObject::StdReturn;
}
<|endoftext|> |
<commit_before>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmmimeparttree.h"
#include "kmreaderwin.h"
#include "partNode.h"
#include "kmmsgpart.h"
#include "kmkernel.h"
#include "objecttreeparser.h"
using KMail::ObjectTreeParser;
#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <qheader.h>
#include <qpopupmenu.h>
KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
QWidget* parent,
const char* name )
: KListView( parent, name ),
mReaderWin( readerWin )
{
addColumn( i18n("Description") );
addColumn( i18n("Type") );
addColumn( i18n("Encoding") );
addColumn( i18n("Size") );
setColumnAlignment( 3, Qt::AlignRight );
restoreLayoutIfPresent();
connect( this, SIGNAL( clicked( QListViewItem* ) ),
this, SLOT( itemClicked( QListViewItem* ) ) );
connect( this, SIGNAL( contextMenuRequested( QListViewItem*,
const QPoint&, int ) ),
this, SLOT( itemRightClicked( QListViewItem*, const QPoint& ) ) );
setSelectionMode( QListView::Extended );
setRootIsDecorated( false );
setAllColumnsShowFocus( true );
setShowToolTips( true );
setSorting(-1);
}
static const char configGroup[] = "MimePartTree";
KMMimePartTree::~KMMimePartTree() {
saveLayout( KMKernel::config(), configGroup );
}
void KMMimePartTree::restoreLayoutIfPresent() {
// first column: soaks up the rest of the space:
setColumnWidthMode( 0, Manual );
header()->setStretchEnabled( true, 0 );
// rest of the columns:
if ( KMKernel::config()->hasGroup( configGroup ) ) {
// there is a saved layout. use it...
restoreLayout( KMKernel::config(), configGroup );
// and disable Maximum mode:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Manual );
} else {
// columns grow with their contents:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Maximum );
}
}
void KMMimePartTree::itemClicked( QListViewItem* item )
{
KMMimePartTreeItem* i = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == i ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemClicked() **\n**" << endl;
if( mReaderWin->mRootNode == i->node() )
mReaderWin->update( true ); // Force update
else {
ObjectTreeParser otp( mReaderWin, 0, true );
otp.parseObjectTree( i->node() );
}
}
}
void KMMimePartTree::itemRightClicked( QListViewItem* item,
const QPoint& point )
{
// TODO: remove this member var?
mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == mCurrentContextMenuItem ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemRightClicked() **\n**" << endl;
/*
if( mReaderWin->mRootNode == i->node() )
mReaderWin->setMsg(mReaderWin->mMsg, true); // Force update
else
mReaderWin->parseObjectTree( i->node(), true );
// mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
*/
QPopupMenu* popup = new QPopupMenu;
popup->insertItem( i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) );
popup->insertItem( i18n( "Save as &Encoded..." ), this,
SLOT( slotSaveAsEncoded() ) );
popup->insertItem( i18n( "Save All Attachments..." ), this,
SLOT( slotSaveAll() ) );
popup->exec( point );
delete popup;
//mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
mCurrentContextMenuItem = 0;
}
}
void KMMimePartTree::slotSaveAs()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( !selected.isEmpty() );
if ( selected.isEmpty() )
return;
if ( selected.count() == 1 )
saveOneFile( selected.first(), false );
else
saveMultipleFiles( selected, false );
}
void KMMimePartTree::slotSaveAsEncoded()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( !selected.isEmpty() );
if ( selected.isEmpty() )
return;
if ( selected.count() == 1 )
saveOneFile( selected.first(), true );
else
saveMultipleFiles( selected, true );
}
void KMMimePartTree::slotSaveAll()
{
if( childCount() == 0)
return;
for ( QListViewItemIterator lit( firstChild() ); lit.current(); ++lit ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( lit.current() );
//Check if it has the Content-Disposition... filename: header
//to make sure it's an actual attachment
if( item->node()->msgPart().fileName().isNull() )
continue;
items.append( item.current() );
}
saveMultipleFiles( items, false );
}
void KMMimePartTree::saveOneFile( QListViewItem* item, bool encoded )
{
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
saveItem( static_cast<KMMimePartTreeItem *>(item), filename, encoded );
}
}
void KMMimePartTree::saveMultipleFiles( const QPtrList<QListViewItem>& selected, bool encoded )
{
QPtrListIterator<QListViewItem> it( selected );
// Let the user choose a *directory*.
// This is why this method is totally different from saveOneFile
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec()) return;
QString dir = fdlg.selectedURL().path();
while ( it.current() ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( it.current() );
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++it;
continue;
}
}
saveItem( item, filename, encoded );
}
++it;
}
}
void KMMimePartTree::saveItem( KMMimePartTreeItem* item, const QString& filename, bool encoded )
{
if ( item && !filename.isEmpty() ) {
bool bSaveEncrypted = false;
bool bEncryptedParts = item->node()->encryptionState() != KMMsgNotEncrypted;
if( bEncryptedParts )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is encrypted. Do you want to keep the encryption when saving?" ),
i18n( "KMail Question" ) ) ==
KMessageBox::Yes )
bSaveEncrypted = true;
bool bSaveWithSig = true;
if( item->node()->signatureState() != KMMsgNotSigned )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is signed. Do you want to keep the signature when saving?" ),
i18n( "KMail Question" ) ) !=
KMessageBox::Yes )
bSaveWithSig = false;
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
if ( encoded )
{
// Note: SaveAsEncoded *always* stores the ENCRYPTED content with SIGNATURES.
// reason: SaveAsEncoded does not decode the Message Content-Transfer-Encoding
// but saves the _original_ content of the message (or the message part, resp.)
QDataStream ds( &file );
QCString cstr( item->node()->msgPart().body() );
ds.writeRawBytes( cstr, cstr.length() );
}
else
{
QDataStream ds( &file );
if( (bSaveEncrypted || !bEncryptedParts) && bSaveWithSig ) {
QByteArray cstr = item->node()->msgPart().bodyDecodedBinary();
ds.writeRawBytes( cstr, cstr.size() );
} else {
ObjectTreeParser otp( mReaderWin, 0, true,
bSaveEncrypted, bSaveWithSig );
otp.parseObjectTree( item->node() );
}
}
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size,
bool revertOrder )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( revertOrder && nextSibling() ){
QListViewItem* sib = nextSibling();
while( sib->nextSibling() )
sib = sib->nextSibling();
moveItem( sib );
}
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
QString mimetype = mime.lower();
if ( mimetype.startsWith( "multipart/" ) ) {
setText( 1, mimetype );
setPixmap( 0, SmallIcon("folder") );
} else if ( mimetype == "application/octet-stream" ) {
setText( 1, i18n("Unspecified Binary Data") ); // don't show "Unknown"...
setPixmap( 0, SmallIcon("unknown") );
} else {
KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
setText( 1, mtp ? mtp->comment() : mimetype );
setPixmap( 0, mtp ? mtp->pixmap( KIcon::Small) : SmallIcon("unknown") );
}
}
#include "kmmimeparttree.moc"
<commit_msg>Now it compiles.<commit_after>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmmimeparttree.h"
#include "kmreaderwin.h"
#include "partNode.h"
#include "kmmsgpart.h"
#include "kmkernel.h"
#include "objecttreeparser.h"
using KMail::ObjectTreeParser;
#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <qheader.h>
#include <qpopupmenu.h>
KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
QWidget* parent,
const char* name )
: KListView( parent, name ),
mReaderWin( readerWin )
{
addColumn( i18n("Description") );
addColumn( i18n("Type") );
addColumn( i18n("Encoding") );
addColumn( i18n("Size") );
setColumnAlignment( 3, Qt::AlignRight );
restoreLayoutIfPresent();
connect( this, SIGNAL( clicked( QListViewItem* ) ),
this, SLOT( itemClicked( QListViewItem* ) ) );
connect( this, SIGNAL( contextMenuRequested( QListViewItem*,
const QPoint&, int ) ),
this, SLOT( itemRightClicked( QListViewItem*, const QPoint& ) ) );
setSelectionMode( QListView::Extended );
setRootIsDecorated( false );
setAllColumnsShowFocus( true );
setShowToolTips( true );
setSorting(-1);
}
static const char configGroup[] = "MimePartTree";
KMMimePartTree::~KMMimePartTree() {
saveLayout( KMKernel::config(), configGroup );
}
void KMMimePartTree::restoreLayoutIfPresent() {
// first column: soaks up the rest of the space:
setColumnWidthMode( 0, Manual );
header()->setStretchEnabled( true, 0 );
// rest of the columns:
if ( KMKernel::config()->hasGroup( configGroup ) ) {
// there is a saved layout. use it...
restoreLayout( KMKernel::config(), configGroup );
// and disable Maximum mode:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Manual );
} else {
// columns grow with their contents:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Maximum );
}
}
void KMMimePartTree::itemClicked( QListViewItem* item )
{
KMMimePartTreeItem* i = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == i ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemClicked() **\n**" << endl;
if( mReaderWin->mRootNode == i->node() )
mReaderWin->update( true ); // Force update
else {
ObjectTreeParser otp( mReaderWin, 0, true );
otp.parseObjectTree( i->node() );
}
}
}
void KMMimePartTree::itemRightClicked( QListViewItem* item,
const QPoint& point )
{
// TODO: remove this member var?
mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == mCurrentContextMenuItem ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemRightClicked() **\n**" << endl;
/*
if( mReaderWin->mRootNode == i->node() )
mReaderWin->setMsg(mReaderWin->mMsg, true); // Force update
else
mReaderWin->parseObjectTree( i->node(), true );
// mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
*/
QPopupMenu* popup = new QPopupMenu;
popup->insertItem( i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) );
popup->insertItem( i18n( "Save as &Encoded..." ), this,
SLOT( slotSaveAsEncoded() ) );
popup->insertItem( i18n( "Save All Attachments..." ), this,
SLOT( slotSaveAll() ) );
popup->exec( point );
delete popup;
//mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
mCurrentContextMenuItem = 0;
}
}
void KMMimePartTree::slotSaveAs()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( !selected.isEmpty() );
if ( selected.isEmpty() )
return;
if ( selected.count() == 1 )
saveOneFile( selected.first(), false );
else
saveMultipleFiles( selected, false );
}
void KMMimePartTree::slotSaveAsEncoded()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( !selected.isEmpty() );
if ( selected.isEmpty() )
return;
if ( selected.count() == 1 )
saveOneFile( selected.first(), true );
else
saveMultipleFiles( selected, true );
}
void KMMimePartTree::slotSaveAll()
{
if( childCount() == 0)
return;
QPtrList<QListViewItem> items;
for ( QListViewItemIterator lit( firstChild() ); lit.current(); ++lit ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( lit.current() );
//Check if it has the Content-Disposition... filename: header
//to make sure it's an actual attachment
if( item->node()->msgPart().fileName().isNull() )
continue;
items.append( item );
}
saveMultipleFiles( items, false );
}
void KMMimePartTree::saveOneFile( QListViewItem* item, bool encoded )
{
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
saveItem( static_cast<KMMimePartTreeItem *>(item), filename, encoded );
}
}
void KMMimePartTree::saveMultipleFiles( const QPtrList<QListViewItem>& selected, bool encoded )
{
QPtrListIterator<QListViewItem> it( selected );
// Let the user choose a *directory*.
// This is why this method is totally different from saveOneFile
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec()) return;
QString dir = fdlg.selectedURL().path();
while ( it.current() ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( it.current() );
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++it;
continue;
}
}
saveItem( item, filename, encoded );
}
++it;
}
}
void KMMimePartTree::saveItem( KMMimePartTreeItem* item, const QString& filename, bool encoded )
{
if ( item && !filename.isEmpty() ) {
bool bSaveEncrypted = false;
bool bEncryptedParts = item->node()->encryptionState() != KMMsgNotEncrypted;
if( bEncryptedParts )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is encrypted. Do you want to keep the encryption when saving?" ),
i18n( "KMail Question" ) ) ==
KMessageBox::Yes )
bSaveEncrypted = true;
bool bSaveWithSig = true;
if( item->node()->signatureState() != KMMsgNotSigned )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is signed. Do you want to keep the signature when saving?" ),
i18n( "KMail Question" ) ) !=
KMessageBox::Yes )
bSaveWithSig = false;
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
if ( encoded )
{
// Note: SaveAsEncoded *always* stores the ENCRYPTED content with SIGNATURES.
// reason: SaveAsEncoded does not decode the Message Content-Transfer-Encoding
// but saves the _original_ content of the message (or the message part, resp.)
QDataStream ds( &file );
QCString cstr( item->node()->msgPart().body() );
ds.writeRawBytes( cstr, cstr.length() );
}
else
{
QDataStream ds( &file );
if( (bSaveEncrypted || !bEncryptedParts) && bSaveWithSig ) {
QByteArray cstr = item->node()->msgPart().bodyDecodedBinary();
ds.writeRawBytes( cstr, cstr.size() );
} else {
ObjectTreeParser otp( mReaderWin, 0, true,
bSaveEncrypted, bSaveWithSig );
otp.parseObjectTree( item->node() );
}
}
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size,
bool revertOrder )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( revertOrder && nextSibling() ){
QListViewItem* sib = nextSibling();
while( sib->nextSibling() )
sib = sib->nextSibling();
moveItem( sib );
}
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
QString mimetype = mime.lower();
if ( mimetype.startsWith( "multipart/" ) ) {
setText( 1, mimetype );
setPixmap( 0, SmallIcon("folder") );
} else if ( mimetype == "application/octet-stream" ) {
setText( 1, i18n("Unspecified Binary Data") ); // don't show "Unknown"...
setPixmap( 0, SmallIcon("unknown") );
} else {
KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
setText( 1, mtp ? mtp->comment() : mimetype );
setPixmap( 0, mtp ? mtp->pixmap( KIcon::Small) : SmallIcon("unknown") );
}
}
#include "kmmimeparttree.moc"
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "log_writer.h"
namespace px4
{
namespace logger
{
LogWriter::LogWriter(Backend configured_backend, size_t file_buffer_size, unsigned int queue_size)
: _backend(configured_backend)
{
if (configured_backend & BackendFile) {
_log_writer_file_for_write = _log_writer_file = new LogWriterFile(file_buffer_size);
if (!_log_writer_file) {
PX4_ERR("LogWriterFile allocation failed");
}
}
if (configured_backend & BackendMavlink) {
_log_writer_mavlink_for_write = _log_writer_mavlink = new LogWriterMavlink(queue_size);
if (!_log_writer_mavlink) {
PX4_ERR("LogWriterMavlink allocation failed");
}
}
}
bool LogWriter::init()
{
if (_log_writer_file) {
if (!_log_writer_file->init()) {
PX4_ERR("alloc failed");
return false;
}
int ret = _log_writer_file->thread_start();
if (ret) {
PX4_ERR("failed to create writer thread (%i)", ret);
return false;
}
}
if (_log_writer_mavlink) {
if (!_log_writer_mavlink->init()) {
PX4_ERR("mavlink init failed");
return false;
}
}
return true;
}
LogWriter::~LogWriter()
{
if (_log_writer_file) {
delete(_log_writer_file);
}
if (_log_writer_mavlink) {
delete(_log_writer_mavlink);
}
}
bool LogWriter::is_started() const
{
bool ret = false;
if (_log_writer_file) {
ret = _log_writer_file->is_started();
}
if (_log_writer_mavlink) {
ret = ret || _log_writer_mavlink->is_started();
}
return ret;
}
bool LogWriter::is_started(Backend query_backend) const
{
if (query_backend == BackendFile && _log_writer_file) {
return _log_writer_file->is_started();
}
if (query_backend == BackendMavlink && _log_writer_mavlink) {
return _log_writer_mavlink->is_started();
}
return false;
}
void LogWriter::start_log_file(const char *filename)
{
if (_log_writer_file) {
_log_writer_file->start_log(filename);
}
}
void LogWriter::stop_log_file()
{
if (_log_writer_file) {
_log_writer_file->stop_log();
}
}
void LogWriter::start_log_mavlink()
{
if (_log_writer_mavlink) {
_log_writer_mavlink->start_log();
}
}
void LogWriter::stop_log_mavlink()
{
if (_log_writer_mavlink) {
_log_writer_mavlink->stop_log();
}
}
void LogWriter::thread_stop()
{
if (_log_writer_file) {
_log_writer_file->thread_stop();
}
}
int LogWriter::write_message(void *ptr, size_t size, uint64_t dropout_start)
{
int ret_file = 0, ret_mavlink = 0;
if (_log_writer_file_for_write) {
ret_file = _log_writer_file_for_write->write_message(ptr, size, dropout_start);
}
if (_log_writer_mavlink_for_write) {
ret_mavlink = _log_writer_mavlink_for_write->write_message(ptr, size);
}
// file backend errors takes precedence
if (ret_file != 0) {
return ret_file;
}
return ret_mavlink;
}
void LogWriter::select_write_backend(Backend sel_backend)
{
if (sel_backend & BackendFile) {
_log_writer_file_for_write = _log_writer_file;
} else {
_log_writer_file_for_write = nullptr;
}
if (sel_backend & BackendMavlink) {
_log_writer_mavlink_for_write = _log_writer_mavlink;
} else {
_log_writer_mavlink_for_write = nullptr;
}
}
}
}
<commit_msg>astyle src/modules/logger<commit_after>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "log_writer.h"
namespace px4
{
namespace logger
{
LogWriter::LogWriter(Backend configured_backend, size_t file_buffer_size, unsigned int queue_size)
: _backend(configured_backend)
{
if (configured_backend & BackendFile) {
_log_writer_file_for_write = _log_writer_file = new LogWriterFile(file_buffer_size);
if (!_log_writer_file) {
PX4_ERR("LogWriterFile allocation failed");
}
}
if (configured_backend & BackendMavlink) {
_log_writer_mavlink_for_write = _log_writer_mavlink = new LogWriterMavlink(queue_size);
if (!_log_writer_mavlink) {
PX4_ERR("LogWriterMavlink allocation failed");
}
}
}
bool LogWriter::init()
{
if (_log_writer_file) {
if (!_log_writer_file->init()) {
PX4_ERR("alloc failed");
return false;
}
int ret = _log_writer_file->thread_start();
if (ret) {
PX4_ERR("failed to create writer thread (%i)", ret);
return false;
}
}
if (_log_writer_mavlink) {
if (!_log_writer_mavlink->init()) {
PX4_ERR("mavlink init failed");
return false;
}
}
return true;
}
LogWriter::~LogWriter()
{
if (_log_writer_file) {
delete (_log_writer_file);
}
if (_log_writer_mavlink) {
delete (_log_writer_mavlink);
}
}
bool LogWriter::is_started() const
{
bool ret = false;
if (_log_writer_file) {
ret = _log_writer_file->is_started();
}
if (_log_writer_mavlink) {
ret = ret || _log_writer_mavlink->is_started();
}
return ret;
}
bool LogWriter::is_started(Backend query_backend) const
{
if (query_backend == BackendFile && _log_writer_file) {
return _log_writer_file->is_started();
}
if (query_backend == BackendMavlink && _log_writer_mavlink) {
return _log_writer_mavlink->is_started();
}
return false;
}
void LogWriter::start_log_file(const char *filename)
{
if (_log_writer_file) {
_log_writer_file->start_log(filename);
}
}
void LogWriter::stop_log_file()
{
if (_log_writer_file) {
_log_writer_file->stop_log();
}
}
void LogWriter::start_log_mavlink()
{
if (_log_writer_mavlink) {
_log_writer_mavlink->start_log();
}
}
void LogWriter::stop_log_mavlink()
{
if (_log_writer_mavlink) {
_log_writer_mavlink->stop_log();
}
}
void LogWriter::thread_stop()
{
if (_log_writer_file) {
_log_writer_file->thread_stop();
}
}
int LogWriter::write_message(void *ptr, size_t size, uint64_t dropout_start)
{
int ret_file = 0, ret_mavlink = 0;
if (_log_writer_file_for_write) {
ret_file = _log_writer_file_for_write->write_message(ptr, size, dropout_start);
}
if (_log_writer_mavlink_for_write) {
ret_mavlink = _log_writer_mavlink_for_write->write_message(ptr, size);
}
// file backend errors takes precedence
if (ret_file != 0) {
return ret_file;
}
return ret_mavlink;
}
void LogWriter::select_write_backend(Backend sel_backend)
{
if (sel_backend & BackendFile) {
_log_writer_file_for_write = _log_writer_file;
} else {
_log_writer_file_for_write = nullptr;
}
if (sel_backend & BackendMavlink) {
_log_writer_mavlink_for_write = _log_writer_mavlink;
} else {
_log_writer_mavlink_for_write = nullptr;
}
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include "app-template.hh"
#include "core/reactor.hh"
#include "core/scollectd.hh"
#include "core/metrics_api.hh"
#include <boost/program_options.hpp>
#include "core/print.hh"
#include <boost/program_options.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
#include <cstdlib>
namespace bpo = boost::program_options;
app_template::app_template()
: _opts("App options") {
_opts.add_options()
("help,h", "show help message")
;
_opts.add(reactor::get_options_description());
_opts.add(seastar::metrics::get_options_description());
_opts.add(smp::get_options_description());
_opts.add(scollectd::get_options_description());
}
boost::program_options::options_description_easy_init
app_template::add_options() {
return _opts.add_options();
}
void
app_template::add_positional_options(std::initializer_list<positional_option> options) {
for (auto&& o : options) {
_opts.add(boost::make_shared<bpo::option_description>(o.name, o.value_semantic, o.help));
_pos_opts.add(o.name, o.max_count);
}
}
bpo::variables_map&
app_template::configuration() {
return *_configuration;
}
int
app_template::run(int ac, char ** av, std::function<future<int> ()>&& func) {
return run_deprecated(ac, av, [func = std::move(func)] () mutable {
auto func_done = make_lw_shared<promise<>>();
engine().at_exit([func_done] { return func_done->get_future(); });
futurize_apply(func).finally([func_done] {
func_done->set_value();
}).then([] (int exit_code) {
return engine().exit(exit_code);
}).or_terminate();
});
}
int
app_template::run(int ac, char ** av, std::function<future<> ()>&& func) {
return run(ac, av, [func = std::move(func)] {
return func().then([] () {
return 0;
});
});
}
int
app_template::run_deprecated(int ac, char ** av, std::function<void ()>&& func) {
#ifdef DEBUG
print("WARNING: debug mode. Not for benchmarking or production\n");
#endif
bpo::variables_map configuration;
try {
bpo::store(bpo::command_line_parser(ac, av)
.options(_opts)
.positional(_pos_opts)
.run()
, configuration);
auto home = std::getenv("HOME");
if (home) {
std::ifstream ifs(std::string(home) + "/.config/seastar/seastar.conf");
if (ifs) {
bpo::store(bpo::parse_config_file(ifs, _opts), configuration);
}
std::ifstream ifs_io(std::string(home) + "/.config/seastar/io.conf");
if (ifs_io) {
bpo::store(bpo::parse_config_file(ifs_io, _opts), configuration);
}
}
} catch (bpo::error& e) {
print("error: %s\n\nTry --help.\n", e.what());
return 2;
}
bpo::notify(configuration);
if (configuration.count("help")) {
std::cout << _opts << "\n";
return 1;
}
configuration.emplace("argv0", boost::program_options::variable_value(std::string(av[0]), false));
smp::configure(configuration);
_configuration = {std::move(configuration)};
engine().when_started().then([this] {
seastar::metrics::configure(this->configuration()).then([this] {
// set scollectd use the metrics configuration, so the later
// need to be set first
scollectd::configure( this->configuration());
});
}).then(
std::move(func)
).then_wrapped([] (auto&& f) {
try {
f.get();
} catch (std::exception& ex) {
std::cout << "program failed with uncaught exception: " << ex.what() << "\n";
engine().exit(1);
}
});
auto exit_code = engine().run();
smp::cleanup();
return exit_code;
}
<commit_msg>app-template: make sure we can still get help with required options<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include "app-template.hh"
#include "core/reactor.hh"
#include "core/scollectd.hh"
#include "core/metrics_api.hh"
#include <boost/program_options.hpp>
#include "core/print.hh"
#include <boost/program_options.hpp>
#include <boost/make_shared.hpp>
#include <fstream>
#include <cstdlib>
namespace bpo = boost::program_options;
app_template::app_template()
: _opts("App options") {
_opts.add_options()
("help,h", "show help message")
;
_opts.add(reactor::get_options_description());
_opts.add(seastar::metrics::get_options_description());
_opts.add(smp::get_options_description());
_opts.add(scollectd::get_options_description());
}
boost::program_options::options_description_easy_init
app_template::add_options() {
return _opts.add_options();
}
void
app_template::add_positional_options(std::initializer_list<positional_option> options) {
for (auto&& o : options) {
_opts.add(boost::make_shared<bpo::option_description>(o.name, o.value_semantic, o.help));
_pos_opts.add(o.name, o.max_count);
}
}
bpo::variables_map&
app_template::configuration() {
return *_configuration;
}
int
app_template::run(int ac, char ** av, std::function<future<int> ()>&& func) {
return run_deprecated(ac, av, [func = std::move(func)] () mutable {
auto func_done = make_lw_shared<promise<>>();
engine().at_exit([func_done] { return func_done->get_future(); });
futurize_apply(func).finally([func_done] {
func_done->set_value();
}).then([] (int exit_code) {
return engine().exit(exit_code);
}).or_terminate();
});
}
int
app_template::run(int ac, char ** av, std::function<future<> ()>&& func) {
return run(ac, av, [func = std::move(func)] {
return func().then([] () {
return 0;
});
});
}
int
app_template::run_deprecated(int ac, char ** av, std::function<void ()>&& func) {
#ifdef DEBUG
print("WARNING: debug mode. Not for benchmarking or production\n");
#endif
bpo::variables_map configuration;
try {
bpo::store(bpo::command_line_parser(ac, av)
.options(_opts)
.positional(_pos_opts)
.run()
, configuration);
auto home = std::getenv("HOME");
if (home) {
std::ifstream ifs(std::string(home) + "/.config/seastar/seastar.conf");
if (ifs) {
bpo::store(bpo::parse_config_file(ifs, _opts), configuration);
}
std::ifstream ifs_io(std::string(home) + "/.config/seastar/io.conf");
if (ifs_io) {
bpo::store(bpo::parse_config_file(ifs_io, _opts), configuration);
}
}
} catch (bpo::error& e) {
print("error: %s\n\nTry --help.\n", e.what());
return 2;
}
if (configuration.count("help")) {
std::cout << _opts << "\n";
return 1;
}
bpo::notify(configuration);
configuration.emplace("argv0", boost::program_options::variable_value(std::string(av[0]), false));
smp::configure(configuration);
_configuration = {std::move(configuration)};
engine().when_started().then([this] {
seastar::metrics::configure(this->configuration()).then([this] {
// set scollectd use the metrics configuration, so the later
// need to be set first
scollectd::configure( this->configuration());
});
}).then(
std::move(func)
).then_wrapped([] (auto&& f) {
try {
f.get();
} catch (std::exception& ex) {
std::cout << "program failed with uncaught exception: " << ex.what() << "\n";
engine().exit(1);
}
});
auto exit_code = engine().run();
smp::cleanup();
return exit_code;
}
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/column.hpp>
#include <tightdb/utilities.hpp>
#include <tightdb/query_engine.hpp>
#include <assert.h>
#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
TIGHTDB_TABLE_3(ThreeColTable,
first, Int,
second, Float,
third, Double)
int main(int argc, char* argv[])
{
size_t match;
// Setup untyped table
Table untyped;
untyped.add_column(type_Int, "firs1");
untyped.add_column(type_Float, "second");
untyped.add_column(type_Double, "third");
untyped.add_empty_row(2);
untyped.set_int(0, 0, 20);
untyped.set_float(1, 0, 19.9f);
untyped.set_double(2, 0, 3.0);
untyped.set_int(0, 1, 20);
untyped.set_float(1, 1, 20.1f);
untyped.set_double(2, 1, 4.0);
// Setup typed table, same contents as untyped
ThreeColTable typed;
typed.add(20, 19.9f, 3.0);
typed.add(20, 20.1f, 4.0);
Query q4 = untyped.columns<float>(1) + untyped.columns<int64_t>(0) > 40;
Query q5 = 20 < untyped.columns<float>(1);
match = q4.expression( q5.get_expression() ).find_next();
assert(match == 1);
// Untyped, direct column addressing
Value<int64_t> uv1(1);
Columns<float> uc1 = untyped.columns<float>(1);
Query q2 = untyped.columns<float>(1) >= uv1;
match = q2.find_next();
assert(match == 0);
Query q3 = untyped.columns<float>(1) + untyped.columns<int64_t>(0) > 10 + untyped.columns<int64_t>(0);
match = q3.find_next();
match = q2.find_next();
assert(match == 0);
// Typed, direct column addressing
Query q1 = typed.column().second + typed.column().first > 40;
match = q1.find_next();
assert(match == 1);
match = (typed.column().first + typed.column().second > 40).find_next();
assert(match == 1);
Query tq1 = typed.column().first + typed.column().second >= typed.column().first + typed.column().second;
match = tq1.find_next();
assert(match == 0);
// Typed, column objects
Columns<int64_t> t0 = typed.column().first;
Columns<float> t1 = typed.column().second;
match = (t0 + t1 > 40).find_next();
assert(match == 1);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) > 40).find_next();
assert(match == 1);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) < 40).find_next();
assert(match == 0);
match = (untyped.columns<float>(1) <= untyped.columns<int64_t>(0)).find_next();
assert(match == 0);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) >= untyped.columns<int64_t>(0) + untyped.columns<float>(1)).find_next();
assert(match == 0);
// Untyped, column objects
Columns<int64_t> u0 = untyped.columns<int64_t>(0);
Columns<float> u1 = untyped.columns<float>(1);
match = (u0 + u1 > 40).find_next();
assert(match == 1);
// Flexible language binding style
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
// Bind table and do search
match = untyped.where().expression(e).find_next();
assert(match == 1);
// you MUST delete these in reversed order of creation
delete e;
delete plus;
delete constant;
delete third;
delete second;
delete first;
/*
ThreeColTable::Query q45 = typed.where().expression(static_cast<Expression*>(&e5));
match = q45.find_next();
assert(match == 1);
*/
// delete static_cast<Expression*>(e5);
// untyped table
// Columns<int64_t> c1 = untyped.columns<int64_t>(0);
// Columns<float> c2 = untyped.columns<float>(1);
// Compare<Greater, float> q2 = Compare<Greater, float>(c2, c1);
// match = untyped.where().expression(q2).find_next();
// assert(match == 1);
/*
// untyped table
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
*/
// match = untyped.where().expression(e).find_next();
/*
assert(match == 1);
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
*/
return 0;
}
// 638
// 545 568<commit_msg>just a short example more in main.. going to sleep now<commit_after>#include <cstring>
#include <iostream>
#include <UnitTest++.h>
#include <TestReporter.h> // Part of UnitTest++
#include <tightdb.hpp>
#include <tightdb/column.hpp>
#include <tightdb/utilities.hpp>
#include <tightdb/query_engine.hpp>
#include <assert.h>
#define USE_VLD
#if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD)
#include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h"
#endif
using namespace std;
using namespace UnitTest;
using namespace tightdb;
namespace {
struct CustomTestReporter: TestReporter {
void ReportTestStart(TestDetails const& test)
{
static_cast<void>(test);
// cerr << test.filename << ":" << test.lineNumber << ": Begin " << test.testName << "\n";
}
void ReportFailure(TestDetails const& test, char const* failure)
{
cerr << test.filename << ":" << test.lineNumber << ": error: "
"Failure in " << test.testName << ": " << failure << "\n";
}
void ReportTestFinish(TestDetails const& test, float seconds_elapsed)
{
static_cast<void>(test);
static_cast<void>(seconds_elapsed);
// cerr << test.filename << ":" << test.lineNumber << ": End\n";
}
void ReportSummary(int total_test_count, int failed_test_count, int failure_count, float seconds_elapsed)
{
if (0 < failure_count)
cerr << "FAILURE: " << failed_test_count << " "
"out of " << total_test_count << " tests failed "
"(" << failure_count << " failures).\n";
else
cerr << "Success: " << total_test_count << " tests passed.\n";
const streamsize orig_prec = cerr.precision();
cerr.precision(2);
cerr << "Test time: " << seconds_elapsed << " seconds.\n";
cerr.precision(orig_prec);
}
};
} // anonymous namespace
TIGHTDB_TABLE_3(ThreeColTable,
first, Int,
second, Float,
third, Double)
int main(int argc, char* argv[])
{
size_t match;
// Setup untyped table
Table untyped;
untyped.add_column(type_Int, "firs1");
untyped.add_column(type_Float, "second");
untyped.add_column(type_Double, "third");
untyped.add_empty_row(2);
untyped.set_int(0, 0, 20);
untyped.set_float(1, 0, 19.9f);
untyped.set_double(2, 0, 3.0);
untyped.set_int(0, 1, 20);
untyped.set_float(1, 1, 20.1f);
untyped.set_double(2, 1, 4.0);
// Setup typed table, same contents as untyped
ThreeColTable typed;
typed.add(20, 19.9f, 3.0);
typed.add(20, 20.1f, 4.0);
Query q4 = untyped.columns<float>(1) + untyped.columns<int64_t>(0) > 40;
Query q5 = 20 < untyped.columns<float>(1);
match = q4.expression( q5.get_expression() ).find_next();
assert(match == 1);
// Untyped, direct column addressing
Value<int64_t> uv1(1);
Columns<float> uc1 = untyped.columns<float>(1);
Query q2 = untyped.columns<float>(1) >= uv1;
match = q2.find_next();
assert(match == 0);
Query q3 = untyped.columns<float>(1) + untyped.columns<int64_t>(0) > 10 + untyped.columns<int64_t>(0);
match = q3.find_next();
match = q2.find_next();
assert(match == 0);
// Typed, direct column addressing
Query q1 = typed.column().second + typed.column().first > 40;
match = q1.find_next();
assert(match == 1);
match = (typed.column().first + typed.column().second > 40).find_next();
assert(match == 1);
Query tq1 = typed.column().first + typed.column().second >= typed.column().first + typed.column().second;
match = tq1.find_next();
assert(match == 0);
// Typed, column objects
Columns<int64_t> t0 = typed.column().first;
Columns<float> t1 = typed.column().second;
match = (t0 + t1 > 40).find_next();
assert(match == 1);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) > 40).find_next();
assert(match == 1);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) < 40).find_next();
assert(match == 0);
match = (untyped.columns<float>(1) <= untyped.columns<int64_t>(0)).find_next();
assert(match == 0);
match = (untyped.columns<int64_t>(0) + untyped.columns<float>(1) >= untyped.columns<int64_t>(0) + untyped.columns<float>(1)).find_next();
assert(match == 0);
// Untyped, column objects
Columns<int64_t> u0 = untyped.columns<int64_t>(0);
Columns<float> u1 = untyped.columns<float>(1);
match = (u0 + u1 > 40).find_next();
assert(match == 1);
// Flexible language binding style
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
// Bind table and do search
match = untyped.where().expression(e).find_next();
assert(match == 1);
Subexpr* first2 = new Columns<int64_t>(0);
Subexpr* second2 = new Columns<float>(1);
Subexpr* third2 = new Columns<double>(2);
Subexpr* constant2 = new Value<int64_t>(40);
Subexpr* plus2 = new Operator<Plus<float> >(*first, *second);
Expression *e2 = new Compare<Greater, float>(*plus, *constant);
match = untyped.where().expression(e).expression(e2).find_next();
assert(match == 1);
// you MUST delete these in reversed order of creation
delete e;
delete plus;
delete constant;
delete third;
delete second;
delete first;
/*
ThreeColTable::Query q45 = typed.where().expression(static_cast<Expression*>(&e5));
match = q45.find_next();
assert(match == 1);
*/
// delete static_cast<Expression*>(e5);
// untyped table
// Columns<int64_t> c1 = untyped.columns<int64_t>(0);
// Columns<float> c2 = untyped.columns<float>(1);
// Compare<Greater, float> q2 = Compare<Greater, float>(c2, c1);
// match = untyped.where().expression(q2).find_next();
// assert(match == 1);
/*
// untyped table
Subexpr* first = new Columns<int64_t>(0);
Subexpr* second = new Columns<float>(1);
Subexpr* third = new Columns<double>(2);
Subexpr* constant = new Value<int64_t>(40);
Subexpr* plus = new Operator<Plus<float> >(*first, *second);
Expression *e = new Compare<Greater, float>(*plus, *constant);
*/
// match = untyped.where().expression(e).find_next();
/*
assert(match == 1);
CustomTestReporter reporter;
TestRunner runner(reporter);
const int res = runner.RunTestsIf(Test::GetTestList(), 0, True(), 0);
*/
return 0;
}
// 638
// 545 568<|endoftext|> |
<commit_before>#include <algorithm>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include "producer.h"
std::string queue_path;
std::map<std::string, std::unique_ptr<Producer> > producers;
extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf);
/* Directive handlers */
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
/* Filter */
ngx_http_output_body_filter_pt ngx_http_next_body_filter;
static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r);
/* Directives */
static ngx_command_t ngx_http_lmdb_queue_commands[] = {
{ ngx_string("lmdb_queue"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
ngx_http_lmdb_queue,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_topic"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
ngx_http_lmdb_queue_topic,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_push"),
NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue_push,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
NULL, /* preconfiguration */
ngx_http_lmdb_queue_handler_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_lmdb_queue_create_loc_conf, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_lmdb_queue_module = {
NGX_MODULE_V1,
&ngx_http_lmdb_queue_module_ctx, /* module context */
ngx_http_lmdb_queue_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
struct ngx_http_lmdb_queue_loc_conf {
Producer* producer;
size_t data_format_len;
u_char data_format[1024 * 8];
size_t vars_count;
ngx_int_t* vars;
};
static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf) {
ngx_http_lmdb_queue_loc_conf *conf = (ngx_http_lmdb_queue_loc_conf*)ngx_pcalloc(cf->pool, sizeof(ngx_http_lmdb_queue_loc_conf));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(conf, sizeof(ngx_http_lmdb_queue_loc_conf));
return conf;
}
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *path = (const char*)args[1].data;
int res = mkdir(path, 0766);
if (res == 0 || errno == EEXIST) {
queue_path = path;
return NGX_CONF_OK;
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[1], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
}
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *name = (const char*)args[1].data;
const char *chunkSizeStr = (const char*)args[2].data;
size_t chunkSize = strtoull(chunkSizeStr, NULL, 10);
if (chunkSize == ULLONG_MAX) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[2], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
char unit = chunkSizeStr[args[2].len - 1];
switch (unit) {
case 'm':
case 'M':
chunkSize *= 1024 * 1024;
break;
case 'g':
case 'G':
chunkSize *= 1024 * 1024 * 1024;
break;
default:
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should be m|g).", &args[2]);
return (char*)NGX_CONF_ERROR;
}
if (chunkSize < 64 * 1024 * 1024 || chunkSize > size_t(64) * 1024 * 1024 * 1024) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should between 64MB and 64GB).", &args[2]);
return (char*)NGX_CONF_ERROR;
}
size_t chunksToKeep = strtoull((const char*)args[3].data, NULL, 10);
if (chunksToKeep == ULLONG_MAX) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: %s", &args[2], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
if (chunksToKeep < 4) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: You should keep at least 4 chunks.", &args[3]);
return (char*)NGX_CONF_ERROR;
}
//printf("Args: %s %zu %zu", name, chunkSize, chunksToKeep);
auto &ptr = producers[name];
if (ptr.get() == NULL) {
TopicOpt qopt = { chunkSize, chunksToKeep };
ptr.reset(new Producer(queue_path, name, &qopt));
}
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *topic = (const char*)args[1].data;
auto producerIter = producers.find(topic);
if (producerIter == producers.end()) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "Topic '%V' not exists.", &args[1]);
return (char*)NGX_CONF_ERROR;
}
ngx_http_lmdb_queue_loc_conf *locconf = (ngx_http_lmdb_queue_loc_conf*)conf;
std::vector<ngx_int_t> varIndexes;
u_char *end = args[2].data + args[2].len, *varCur = NULL, *outCur = locconf->data_format;
for (u_char *s = args[2].data; s < end;) {
if (*s == '$') {
varCur = ++s;
*outCur++ = '\1';
while (s < end && ((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '_')) {
++s;
}
ngx_str_t varName { size_t(s - varCur), varCur };
ngx_int_t idx = ngx_http_get_variable_index(cf, &varName);
if (idx == NGX_ERROR) {
return (char*)NGX_CONF_ERROR;
}
varIndexes.push_back(idx);
}
if (*s != '$' && s < end) {
*outCur++ = *s++;
}
}
locconf->data_format_len = size_t(outCur - locconf->data_format);
locconf->producer = producerIter->second.get();
locconf->vars_count = varIndexes.size();
locconf->vars = (ngx_int_t*)ngx_pcalloc(cf->pool, varIndexes.size() * sizeof(ngx_int_t));
std::copy(varIndexes.begin(), varIndexes.end(), locconf->vars);
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf) {
ngx_http_core_main_conf_t *cmcf = (ngx_http_core_main_conf_t*)ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
ngx_http_handler_pt *h = (ngx_http_handler_pt*)ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_lmdb_queue_handler;
return NGX_OK;
}
static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r) {
return NGX_OK;
}
}<commit_msg>queue write<commit_after>#include <algorithm>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include "producer.h"
std::string queue_path;
std::map<std::string, std::unique_ptr<Producer> > producers;
extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf);
/* Directive handlers */
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
/* Filter */
ngx_http_output_body_filter_pt ngx_http_next_body_filter;
static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r);
/* Directives */
static ngx_command_t ngx_http_lmdb_queue_commands[] = {
{ ngx_string("lmdb_queue"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
ngx_http_lmdb_queue,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_topic"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
ngx_http_lmdb_queue_topic,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_push"),
NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue_push,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
NULL, /* preconfiguration */
ngx_http_lmdb_queue_handler_init, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_http_lmdb_queue_create_loc_conf, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_lmdb_queue_module = {
NGX_MODULE_V1,
&ngx_http_lmdb_queue_module_ctx, /* module context */
ngx_http_lmdb_queue_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
struct ngx_http_lmdb_queue_loc_conf {
Producer* producer;
size_t data_format_len;
u_char data_format[1024 * 8];
size_t vars_count;
ngx_int_t* vars;
};
static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf) {
ngx_http_lmdb_queue_loc_conf *conf = (ngx_http_lmdb_queue_loc_conf*)ngx_pcalloc(cf->pool, sizeof(ngx_http_lmdb_queue_loc_conf));
if (conf == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(conf, sizeof(ngx_http_lmdb_queue_loc_conf));
return conf;
}
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *path = (const char*)args[1].data;
int res = mkdir(path, 0766);
if (res == 0 || errno == EEXIST) {
queue_path = path;
return NGX_CONF_OK;
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[1], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
}
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *name = (const char*)args[1].data;
const char *chunkSizeStr = (const char*)args[2].data;
size_t chunkSize = strtoull(chunkSizeStr, NULL, 10);
if (chunkSize == ULLONG_MAX) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[2], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
char unit = chunkSizeStr[args[2].len - 1];
switch (unit) {
case 'm':
case 'M':
chunkSize *= 1024 * 1024;
break;
case 'g':
case 'G':
chunkSize *= 1024 * 1024 * 1024;
break;
default:
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should be m|g).", &args[2]);
return (char*)NGX_CONF_ERROR;
}
if (chunkSize < 64 * 1024 * 1024 || chunkSize > size_t(64) * 1024 * 1024 * 1024) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should between 64MB and 64GB).", &args[2]);
return (char*)NGX_CONF_ERROR;
}
size_t chunksToKeep = strtoull((const char*)args[3].data, NULL, 10);
if (chunksToKeep == ULLONG_MAX) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: %s", &args[2], strerror(errno));
return (char*)NGX_CONF_ERROR;
}
if (chunksToKeep < 4) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: You should keep at least 4 chunks.", &args[3]);
return (char*)NGX_CONF_ERROR;
}
//printf("Args: %s %zu %zu", name, chunkSize, chunksToKeep);
auto &ptr = producers[name];
if (ptr.get() == NULL) {
TopicOpt qopt = { chunkSize, chunksToKeep };
ptr.reset(new Producer(queue_path, name, &qopt));
}
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
ngx_str_t *args = (ngx_str_t*)cf->args->elts;
const char *topic = (const char*)args[1].data;
auto producerIter = producers.find(topic);
if (producerIter == producers.end()) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "Topic '%V' not exists.", &args[1]);
return (char*)NGX_CONF_ERROR;
}
ngx_http_lmdb_queue_loc_conf *locconf = (ngx_http_lmdb_queue_loc_conf*)conf;
std::vector<ngx_int_t> varIndexes;
u_char *end = args[2].data + args[2].len, *varCur = NULL, *outCur = locconf->data_format;
for (u_char *s = args[2].data; s < end;) {
if (*s == '$') {
varCur = ++s;
*outCur++ = '\1';
while (s < end && ((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '_')) {
++s;
}
ngx_str_t varName { size_t(s - varCur), varCur };
ngx_int_t idx = ngx_http_get_variable_index(cf, &varName);
if (idx == NGX_ERROR) {
return (char*)NGX_CONF_ERROR;
}
varIndexes.push_back(idx);
}
if (*s != '$' && s < end) {
*outCur++ = *s++;
}
}
locconf->data_format_len = size_t(outCur - locconf->data_format);
locconf->producer = producerIter->second.get();
locconf->vars_count = varIndexes.size();
locconf->vars = (ngx_int_t*)ngx_pcalloc(cf->pool, varIndexes.size() * sizeof(ngx_int_t));
std::copy(varIndexes.begin(), varIndexes.end(), locconf->vars);
return NGX_CONF_OK;
}
static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf) {
ngx_http_core_main_conf_t *cmcf = (ngx_http_core_main_conf_t*)ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
ngx_http_handler_pt *h = (ngx_http_handler_pt*)ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_lmdb_queue_handler;
return NGX_OK;
}
static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r) {
ngx_http_lmdb_queue_loc_conf *lcf = (ngx_http_lmdb_queue_loc_conf*)ngx_http_get_module_loc_conf(r, ngx_http_accesskey_module);
if (lcf->producer == NULL) {
return NGX_OK;
}
std::vector<ngx_http_variable_value_t*> vals;
size_t resLen = lcf->data_format_len;
for (int i = 0; i < lcf->vars_count; ++i) {
ngx_http_variable_value_t *v = ngx_http_get_indexed_variable(r, lcf->vars[i]);
vals.push_back(v);
if (v && !v->not_found) {
resLen += (v->len - 1);
} else {
--resLen;
}
}
u_char *formatCur = lcf->data_format, *formatEnd = lcf->data_format + lcf->data_format_len;
u_char *buf = new u_char[resLen], *cur = buf;
auto valIter = vals.begin();
while (formatCur < formatEnd) {
if (*formatCur != '\1') {
*cur++ = *formatCur++;
} else {
++formatCur;
ngx_http_variable_value_t *v = *valIter++;
if (v && !v->not_found) {
for (u_char *src = v->data; src < v->data + v->len;) {
*cur++ = *src++;
}
}
}
}
Producer::BatchType bt;
bt.push_back(make_tuple((char*)buf, resLen));
lcf->producer.push(bt);
return NGX_OK;
}
}<|endoftext|> |
<commit_before>/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script. Only //
// add custom code in the designated areas or it will be overwritten during //
// the next update. //
//-----------------------------------NOTICE----------------------------------//
//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//
#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiVertexColorProperty.h"
using namespace Niflib;
//Definition of TYPE constant
const Type NiVertexColorProperty::TYPE("NiVertexColorProperty", &NiProperty::TYPE );
NiVertexColorProperty::NiVertexColorProperty() : flags((unsigned short)0) {
//--BEGIN CONSTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
NiVertexColorProperty::~NiVertexColorProperty() {
//--BEGIN DESTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
const Type & NiVertexColorProperty::GetType() const {
return TYPE;
}
NiObject * NiVertexColorProperty::Create() {
return new NiVertexColorProperty;
}
void NiVertexColorProperty::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
//--BEGIN PRE-READ CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::Read( in, link_stack, info );
NifStream( flags, in, info );
if ( info.version <= 0x14000005 ) {
NifStream( vertexMode, in, info );
NifStream( lightingMode, in, info );
};
//--BEGIN POST-READ CUSTOM CODE--//
//--END CUSTOM CODE--//
}
void NiVertexColorProperty::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, const NifInfo & info ) const {
//--BEGIN PRE-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::Write( out, link_map, info );
NifStream( flags, out, info );
if ( info.version <= 0x14000005 ) {
NifStream( vertexMode, out, info );
NifStream( lightingMode, out, info );
};
//--BEGIN POST-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::string NiVertexColorProperty::asString( bool verbose ) const {
//--BEGIN PRE-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
stringstream out;
unsigned int array_output_count = 0;
out << NiProperty::asString();
out << " Flags: " << flags << endl;
out << " Vertex Mode: " << vertexMode << endl;
out << " Lighting Mode: " << lightingMode << endl;
return out.str();
//--BEGIN POST-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
}
void NiVertexColorProperty::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, const NifInfo & info ) {
//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::FixLinks( objects, link_stack, info );
//--BEGIN POST-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::list<NiObjectRef> NiVertexColorProperty::GetRefs() const {
list<Ref<NiObject> > refs;
refs = NiProperty::GetRefs();
return refs;
}
//--BEGIN MISC CUSTOM CODE--//
unsigned short NiVertexColorProperty::GetFlags() const {
return flags;
}
void NiVertexColorProperty::SetFlags(unsigned short value) {
flags = value;
}
VertMode NiVertexColorProperty::GetVertexMode() const {
return vertexMode;
}
void NiVertexColorProperty::SetVertexMode(VertMode value) {
vertexMode = value;
}
LightMode NiVertexColorProperty::GetLightingMode() const {
return lightingMode;
}
void NiVertexColorProperty::SetLightingMode(LightMode value) {
lightingMode = value;
}
//--END CUSTOM CODE--//
<commit_msg>niflib: set src Mode and lighting flags when loading old files.<commit_after>/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved. Please see niflib.h for license. */
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script. Only //
// add custom code in the designated areas or it will be overwritten during //
// the next update. //
//-----------------------------------NOTICE----------------------------------//
//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//
#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiVertexColorProperty.h"
using namespace Niflib;
//Definition of TYPE constant
const Type NiVertexColorProperty::TYPE("NiVertexColorProperty", &NiProperty::TYPE );
NiVertexColorProperty::NiVertexColorProperty() : flags((unsigned short)0) {
//--BEGIN CONSTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
NiVertexColorProperty::~NiVertexColorProperty() {
//--BEGIN DESTRUCTOR CUSTOM CODE--//
//--END CUSTOM CODE--//
}
const Type & NiVertexColorProperty::GetType() const {
return TYPE;
}
NiObject * NiVertexColorProperty::Create() {
return new NiVertexColorProperty;
}
void NiVertexColorProperty::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
//--BEGIN PRE-READ CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::Read( in, link_stack, info );
NifStream( flags, in, info );
if ( info.version <= 0x14000005 ) {
NifStream( vertexMode, in, info );
NifStream( lightingMode, in, info );
};
//--BEGIN POST-READ CUSTOM CODE--//
if ( info.version > 0x14000005 ) {
lightingMode = (LightMode)UnpackField( flags, 3, 1);
vertexMode = (VertMode)UnpackField( flags, 4, 2);
}
//--END CUSTOM CODE--//
}
void NiVertexColorProperty::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, const NifInfo & info ) const {
//--BEGIN PRE-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::Write( out, link_map, info );
NifStream( flags, out, info );
if ( info.version <= 0x14000005 ) {
NifStream( vertexMode, out, info );
NifStream( lightingMode, out, info );
};
//--BEGIN POST-WRITE CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::string NiVertexColorProperty::asString( bool verbose ) const {
//--BEGIN PRE-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
stringstream out;
unsigned int array_output_count = 0;
out << NiProperty::asString();
out << " Flags: " << flags << endl;
out << " Vertex Mode: " << vertexMode << endl;
out << " Lighting Mode: " << lightingMode << endl;
return out.str();
//--BEGIN POST-STRING CUSTOM CODE--//
//--END CUSTOM CODE--//
}
void NiVertexColorProperty::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, const NifInfo & info ) {
//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
NiProperty::FixLinks( objects, link_stack, info );
//--BEGIN POST-FIXLINKS CUSTOM CODE--//
//--END CUSTOM CODE--//
}
std::list<NiObjectRef> NiVertexColorProperty::GetRefs() const {
list<Ref<NiObject> > refs;
refs = NiProperty::GetRefs();
return refs;
}
//--BEGIN MISC CUSTOM CODE--//
unsigned short NiVertexColorProperty::GetFlags() const {
return flags;
}
void NiVertexColorProperty::SetFlags(unsigned short value) {
flags = value;
}
VertMode NiVertexColorProperty::GetVertexMode() const {
return vertexMode;
}
void NiVertexColorProperty::SetVertexMode(VertMode value) {
vertexMode = value;
}
LightMode NiVertexColorProperty::GetLightingMode() const {
return lightingMode;
}
void NiVertexColorProperty::SetLightingMode(LightMode value) {
lightingMode = value;
}
//--END CUSTOM CODE--//
<|endoftext|> |
<commit_before>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include <QMediaPlayer>
MusicPlayer::MusicPlayer(QObject *parent)
: QObject(parent), m_audition(NULL)
{
m_playlist = NULL;
m_music = NULL;
m_state = StoppedState;
m_musicEnhanced = EnhancedOff;
m_music = CreateZPlay();
Q_ASSERT(m_music);
m_equalizer = new MusicEqualizer(m_music);
m_posOnCircle = 0;
m_currentVolumn = 100;
connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
M_Connection->setValue("MusicPlayer", this);
}
MusicPlayer::~MusicPlayer()
{
delete m_audition;
delete m_equalizer;
m_music->Close();
m_music->Release();
}
MusicPlayer::State MusicPlayer::state() const
{
return m_state;
}
MusicPlaylist *MusicPlayer::playlist() const
{
return m_playlist;
}
qint64 MusicPlayer::duration() const
{
TStreamInfo pInfo;
m_music->GetStreamInfo(&pInfo);
return pInfo.Length.hms.hour * 3600000 + pInfo.Length.hms.minute * 60000 +
pInfo.Length.hms.second * 1000 + pInfo.Length.hms.millisecond;
}
qint64 MusicPlayer::position() const
{
TStreamTime pos;
m_music->GetPosition(&pos);
return pos.hms.hour * 3600000 + pos.hms.minute * 60000 +
pos.hms.second * 1000 + pos.hms.millisecond;
}
int MusicPlayer::volume() const
{
uint vol;
m_music->GetMasterVolume(&vol, &vol);
return vol;
}
bool MusicPlayer::isMuted() const
{
return (volume() == 0) ? true : false;
}
void MusicPlayer::setMusicEnhanced(Enhanced type)
{
m_musicEnhanced = type;
m_music->EnableEcho(false);
m_music->EnableEqualizer(false);
if(m_musicEnhanced != Music3D &&
m_musicEnhanced != EnhancedOff)
{
m_music->EnableEqualizer(true);
setMusicEnhancedCase();
}
}
MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
return m_musicEnhanced;
}
void MusicPlayer::addAuditionUrl(const QString &url)
{
addAuditionUrl(QUrl(url));
}
void MusicPlayer::addAuditionUrl(const QUrl &url)
{
if(m_audition == NULL)
{
m_audition = new QMediaPlayer(this);
}
m_audition->setMedia(url);
}
void MusicPlayer::startAudition()
{
if(m_audition)
{
m_audition->play();
}
}
void MusicPlayer::stopAudition()
{
if(m_audition)
{
m_audition->stop();
}
}
QStringList MusicPlayer::supportFormatsString()
{
return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
<< "flac" << "ac3" << "aac" << "oga" << "pcm";
}
QStringList MusicPlayer::supportFormatsFilterString()
{
return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
<< "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
<< "*.oga" << "*.pcm";
}
QStringList MusicPlayer::supportFormatsFilterDialogString()
{
return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
<< "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
<< "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
<< "Pcm File(*.pcm)";
}
#ifdef Q_OS_WIN32
void MusicPlayer::setSpectrum(HWND wnd, int w, int h, int x, int y)
{
if(!m_music)
{
return;
}
/// set graph type to AREA, left channel on top
m_music->SetFFTGraphParam(gpGraphType, gtAreaLeftOnTop);
/// set linear scale
m_music->SetFFTGraphParam(gpHorizontalScale, gsLinear);
m_music->DrawFFTGraphOnHWND(wnd, x, y, w, h);
}
#endif
void MusicPlayer::play()
{
if(m_playlist->isEmpty())
{
return;
}
TStreamStatus status;
m_music->GetStatus(&status);///Get the current state of play
if(m_currentMedia == m_playlist->currentMediaString() &&
status.fPause)
{
m_music->Resume();///When the pause time for recovery
m_timer.start(1000);
return;
}
m_music->Close();///For the release of the last memory
m_currentMedia = m_playlist->currentMediaString();
///The current playback path
if(m_music->OpenFileW(m_currentMedia.toStdWString().c_str(), sfAutodetect) == 0)
{
M_LOOGER << "Error1." << m_music->GetError();
return;
}
m_timer.start(1000);
///Every second emits a signal change information
emit positionChanged(0);
emit durationChanged( duration() );
m_state = PlayingState;
if(m_music->Play() == 0)
{
M_LOOGER << "Error2." << m_music->GetError();
return;
}
////////////////////////////////////////////////
///Read the configuration settings for the sound
int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
if(volumn != -1)
{
setVolume(volumn);
}
////////////////////////////////////////////////
}
void MusicPlayer::playNext()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}
void MusicPlayer::playPrivious()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}
void MusicPlayer::pause()
{
m_music->Pause();
m_timer.stop();
m_state = PausedState;
}
void MusicPlayer::stop()
{
m_music->Stop();
m_timer.stop();
m_state = StoppedState;
}
void MusicPlayer::setPosition(qint64 position)
{
TStreamTime pTime;
pTime.ms = position;
m_music->Seek(tfMillisecond, &pTime, smFromBeginning);
}
void MusicPlayer::setVolume(int volume)
{
m_currentVolumn = volume;
m_music->SetMasterVolume(m_currentVolumn, m_currentVolumn);
}
void MusicPlayer::setMuted(bool muted)
{
muted ? m_music->SetMasterVolume(0, 0) :
m_music->SetMasterVolume(m_currentVolumn, m_currentVolumn);
}
void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
m_playlist = playlist;
connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}
void MusicPlayer::setTimeOut()
{
emit positionChanged( position() );
if(m_musicEnhanced == Music3D)
{ ///3D music settings
m_music->EnableEcho(true);
m_posOnCircle += 0.5f;
TEchoEffect effect;
effect.nLeftDelay = 450;
effect.nLeftEchoVolume = 20;
effect.nLeftSrcVolume = 100 * cosf(m_posOnCircle);
effect.nRightDelay = 500;
effect.nRightEchoVolume = 20;
effect.nRightSrcVolume = 100 * sinf(m_posOnCircle * 0.5f);
m_music->SetEchoParam(&effect, 1);
}
TStreamStatus status;
m_music->GetStatus(&status);
if(!status.fPlay && !status.fPause)
{
m_timer.stop();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
{
m_music->Stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
m_playlist->setCurrentIndex();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
m_playlist->currentIndex() == -1)
{
m_music->Stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
play();
}
}
void MusicPlayer::setMusicEnhancedCase()
{
switch(m_musicEnhanced)
{
case MusicVocal:
setEqEffect(MIntList()<<0<<6<<4<<1<<0<<0<<-3<<-4<<-4<<0<<0);
break;
case MusicNICAM:
setEqEffect(MIntList()<<0<<-12<<-12<<-9<<-6<<-3<<-12<<-9<<-6<<-3<<-12);
break;
case MusicSubwoofer:
setEqEffect(MIntList()<<0<<8<<1<<-5<<-1<<2<<-2<<-4<<-4<<0<<0);
break;
default:
break;
}
}
void MusicPlayer::removeCurrentMedia()
{
if(m_music)
{
m_timer.stop();
m_music->Close();
}
}
void MusicPlayer::setEqEffect(const MIntList &hz)
{
m_equalizer->setEqEffect(hz);
}
void MusicPlayer::setEnaleEffect(bool enable)
{
m_equalizer->setEnaleEffect(enable);
}
void MusicPlayer::setEqInformation()
{
m_equalizer->readEqInformation();
}
void MusicPlayer::resetEqEffect()
{
m_equalizer->resetEqEffect();
}
void MusicPlayer::setSpEqEffect(MusicObject::SpecialEQ eq)
{
if(m_state != PlayingState) return;
switch(eq)
{
case MusicObject::EQ_EchoEffect:
m_equalizer->setEchoEffect();break;
case MusicObject::EQ_MixChannelEffect:
m_equalizer->setMixChannelEffect();break;
case MusicObject::EQ_ReverseEffect:
m_equalizer->setReverseEffect();break;
case MusicObject::EQ_SideCutEffect:
m_equalizer->setSideCutEffect();break;
case MusicObject::EQ_CenterCutEffect:
m_equalizer->setCenterCutEffect();break;
case MusicObject::EQ_RateUpEffect:
m_equalizer->setRateUpEffect();break;
case MusicObject::EQ_RateDownEffect:
m_equalizer->setRateDownEffect();break;
case MusicObject::EQ_PitchUpEffect:
m_equalizer->setPitchUpEffect();break;
case MusicObject::EQ_PitchDownEffect:
m_equalizer->setPitchDownEffect();break;
case MusicObject::EQ_TempoUpEffect:
m_equalizer->setTempoUpEffect();break;
case MusicObject::EQ_TempoDownEffect:
m_equalizer->setTempoDownEffect();break;
case MusicObject::EQ_FadeOutEffect:
m_equalizer->setFadeOutEffect();break;
case MusicObject::EQ_FadeInEffect:
m_equalizer->setFadeInEffect();break;
}
}
<commit_msg>update music magic parameter[031065]<commit_after>#include "musicplayer.h"
#include "musicplaylist.h"
#include "musicsettingmanager.h"
#include "musicconnectionpool.h"
#include <QMediaPlayer>
MusicPlayer::MusicPlayer(QObject *parent)
: QObject(parent), m_audition(NULL)
{
m_playlist = NULL;
m_music = NULL;
m_state = StoppedState;
m_musicEnhanced = EnhancedOff;
m_music = CreateZPlay();
Q_ASSERT(m_music);
m_equalizer = new MusicEqualizer(m_music);
m_posOnCircle = 0;
m_currentVolumn = 100;
connect(&m_timer, SIGNAL(timeout()), SLOT(setTimeOut()));
M_Connection->setValue("MusicPlayer", this);
}
MusicPlayer::~MusicPlayer()
{
delete m_audition;
delete m_equalizer;
m_music->Close();
m_music->Release();
}
MusicPlayer::State MusicPlayer::state() const
{
return m_state;
}
MusicPlaylist *MusicPlayer::playlist() const
{
return m_playlist;
}
qint64 MusicPlayer::duration() const
{
TStreamInfo pInfo;
m_music->GetStreamInfo(&pInfo);
return pInfo.Length.hms.hour * 3600000 + pInfo.Length.hms.minute * 60000 +
pInfo.Length.hms.second * 1000 + pInfo.Length.hms.millisecond;
}
qint64 MusicPlayer::position() const
{
TStreamTime pos;
m_music->GetPosition(&pos);
return pos.hms.hour * 3600000 + pos.hms.minute * 60000 +
pos.hms.second * 1000 + pos.hms.millisecond;
}
int MusicPlayer::volume() const
{
uint vol;
m_music->GetMasterVolume(&vol, &vol);
return vol;
}
bool MusicPlayer::isMuted() const
{
return (volume() == 0) ? true : false;
}
void MusicPlayer::setMusicEnhanced(Enhanced type)
{
m_musicEnhanced = type;
m_music->EnableEcho(false);
m_music->EnableEqualizer(false);
if(m_musicEnhanced != Music3D &&
m_musicEnhanced != EnhancedOff)
{
m_music->EnableEqualizer(true);
setMusicEnhancedCase();
}
}
MusicPlayer::Enhanced MusicPlayer::getMusicEnhanced() const
{
return m_musicEnhanced;
}
void MusicPlayer::addAuditionUrl(const QString &url)
{
addAuditionUrl(QUrl(url));
}
void MusicPlayer::addAuditionUrl(const QUrl &url)
{
if(m_audition == NULL)
{
m_audition = new QMediaPlayer(this);
}
m_audition->setMedia(url);
}
void MusicPlayer::startAudition()
{
if(m_audition)
{
m_audition->play();
}
}
void MusicPlayer::stopAudition()
{
if(m_audition)
{
m_audition->stop();
}
}
QStringList MusicPlayer::supportFormatsString()
{
return QStringList()<< "mp3" << "mp2" << "mp1" << "wav" << "ogg"
<< "flac" << "ac3" << "aac" << "oga" << "pcm";
}
QStringList MusicPlayer::supportFormatsFilterString()
{
return QStringList()<< "*.mp3" << "*.mp2" << "*.mp1" << "*.wav"
<< "*.ogg" << "*.flac" << "*.ac3" << "*.aac"
<< "*.oga" << "*.pcm";
}
QStringList MusicPlayer::supportFormatsFilterDialogString()
{
return QStringList()<< "Mp3 File(*.mp3)" << "Mp2 File(*.mp2)" << "Mp1 File(*.mp1)"
<< "Wav File(*.wav)" << "Ogg File(*.ogg)" << "Flac File(*.flac)"
<< "Ac3 File(*.ac3)" << "Aac File(*.aac)" << "Oga File(*.oga)"
<< "Pcm File(*.pcm)";
}
#ifdef Q_OS_WIN32
void MusicPlayer::setSpectrum(HWND wnd, int w, int h, int x, int y)
{
if(!m_music)
{
return;
}
/// set graph type to AREA, left channel on top
m_music->SetFFTGraphParam(gpGraphType, gtAreaLeftOnTop);
/// set linear scale
m_music->SetFFTGraphParam(gpHorizontalScale, gsLinear);
m_music->DrawFFTGraphOnHWND(wnd, x, y, w, h);
}
#endif
void MusicPlayer::play()
{
if(m_playlist->isEmpty())
{
return;
}
TStreamStatus status;
m_music->GetStatus(&status);///Get the current state of play
if(m_currentMedia == m_playlist->currentMediaString() &&
status.fPause)
{
m_music->Resume();///When the pause time for recovery
m_timer.start(1000);
return;
}
m_music->Close();///For the release of the last memory
m_currentMedia = m_playlist->currentMediaString();
///The current playback path
if(m_music->OpenFileW(m_currentMedia.toStdWString().c_str(), sfAutodetect) == 0)
{
M_LOOGER << "Error1." << m_music->GetError();
return;
}
m_timer.start(1000);
///Every second emits a signal change information
emit positionChanged(0);
emit durationChanged( duration() );
m_state = PlayingState;
if(m_music->Play() == 0)
{
M_LOOGER << "Error2." << m_music->GetError();
return;
}
////////////////////////////////////////////////
///Read the configuration settings for the sound
int volumn = M_SETTING->value(MusicSettingManager::VolumeChoiced).toInt();
if(volumn != -1)
{
setVolume(volumn);
}
////////////////////////////////////////////////
}
void MusicPlayer::playNext()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((++index >= m_playlist->mediaCount()) ? 0 : index);
}
void MusicPlayer::playPrivious()
{
int index = m_playlist->currentIndex();
m_playlist->setCurrentIndex((--index < 0) ? 0 : index );
}
void MusicPlayer::pause()
{
m_music->Pause();
m_timer.stop();
m_state = PausedState;
}
void MusicPlayer::stop()
{
m_music->Stop();
m_timer.stop();
m_state = StoppedState;
}
void MusicPlayer::setPosition(qint64 position)
{
TStreamTime pTime;
pTime.ms = position;
m_music->Seek(tfMillisecond, &pTime, smFromBeginning);
}
void MusicPlayer::setVolume(int volume)
{
m_currentVolumn = volume;
m_music->SetMasterVolume(m_currentVolumn, m_currentVolumn);
}
void MusicPlayer::setMuted(bool muted)
{
muted ? m_music->SetMasterVolume(0, 0) :
m_music->SetMasterVolume(m_currentVolumn, m_currentVolumn);
}
void MusicPlayer::setPlaylist(MusicPlaylist *playlist)
{
m_playlist = playlist;
connect(m_playlist, SIGNAL(removeCurrentMedia()), SLOT(removeCurrentMedia()));
}
void MusicPlayer::setTimeOut()
{
emit positionChanged( position() );
if(m_musicEnhanced == Music3D)
{ ///3D music settings
m_music->EnableEcho(true);
m_posOnCircle += 0.5f;
TEchoEffect effect;
effect.nLeftDelay = 450;
effect.nLeftEchoVolume = 20;
effect.nLeftSrcVolume = 100 * cosf(m_posOnCircle);
effect.nRightDelay = 500;
effect.nRightEchoVolume = 20;
effect.nRightSrcVolume = 100 * sinf(m_posOnCircle * 0.5f);
m_music->SetEchoParam(&effect, 1);
}
TStreamStatus status;
m_music->GetStatus(&status);
if(!status.fPlay && !status.fPause)
{
m_timer.stop();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOnce)
{
m_music->Stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
m_playlist->setCurrentIndex();
if(m_playlist->playbackMode() == MusicObject::MC_PlayOrder &&
m_playlist->currentIndex() == -1)
{
m_music->Stop();
emit positionChanged(0);
emit stateChanged(StoppedState);
return;
}
play();
}
}
void MusicPlayer::setMusicEnhancedCase()
{
switch(m_musicEnhanced)
{
case MusicVocal:
setEqEffect(MIntList()<<0<<8<<1<<-5<<-1<<2<<-2<<-4<<-4<<0<<0);
break;
case MusicNICAM:
setEqEffect(MIntList()<<0<<-12<<-12<<-9<<-6<<-3<<-12<<-9<<-6<<-3<<-12);
break;
case MusicSubwoofer:
setEqEffect(MIntList()<<0<<6<<4<<1<<-2<<-3<<-5<<-7<<-9<<-11<<-13);
break;
default:
break;
}
}
void MusicPlayer::removeCurrentMedia()
{
if(m_music)
{
m_timer.stop();
m_music->Close();
}
}
void MusicPlayer::setEqEffect(const MIntList &hz)
{
m_equalizer->setEqEffect(hz);
}
void MusicPlayer::setEnaleEffect(bool enable)
{
m_equalizer->setEnaleEffect(enable);
}
void MusicPlayer::setEqInformation()
{
m_equalizer->readEqInformation();
}
void MusicPlayer::resetEqEffect()
{
m_equalizer->resetEqEffect();
}
void MusicPlayer::setSpEqEffect(MusicObject::SpecialEQ eq)
{
if(m_state != PlayingState) return;
switch(eq)
{
case MusicObject::EQ_EchoEffect:
m_equalizer->setEchoEffect();break;
case MusicObject::EQ_MixChannelEffect:
m_equalizer->setMixChannelEffect();break;
case MusicObject::EQ_ReverseEffect:
m_equalizer->setReverseEffect();break;
case MusicObject::EQ_SideCutEffect:
m_equalizer->setSideCutEffect();break;
case MusicObject::EQ_CenterCutEffect:
m_equalizer->setCenterCutEffect();break;
case MusicObject::EQ_RateUpEffect:
m_equalizer->setRateUpEffect();break;
case MusicObject::EQ_RateDownEffect:
m_equalizer->setRateDownEffect();break;
case MusicObject::EQ_PitchUpEffect:
m_equalizer->setPitchUpEffect();break;
case MusicObject::EQ_PitchDownEffect:
m_equalizer->setPitchDownEffect();break;
case MusicObject::EQ_TempoUpEffect:
m_equalizer->setTempoUpEffect();break;
case MusicObject::EQ_TempoDownEffect:
m_equalizer->setTempoDownEffect();break;
case MusicObject::EQ_FadeOutEffect:
m_equalizer->setFadeOutEffect();break;
case MusicObject::EQ_FadeInEffect:
m_equalizer->setFadeInEffect();break;
}
}
<|endoftext|> |
<commit_before>#include <cassert>
#include "../src/game.h"
void test1(void);
void test2(void);
int main(void)
{
test1();
test2();
return 0;
}
void test1(void)
{
int n = 10;
assert(10 == n);
std::cout << " ✔ : test1 complete" << std::endl;
}
void test2(void)
{
Game *game = new Game();
int const **mz = game->map->maze();
int wid = game->map->width();
int hei = game->map->height();
for ( int _i; _i < hei; _i++ ) {
assert(mz[_i][0] == 1);
assert(mz[_i][wid-1] == 1);
for ( int _j; _j < wid; _j++ ) {
assert(mz[0][_j] == 1);
assert(mz[hei-1][_j] == 1);
}
}
delete game;
std::cout << " ✔ : test2 complete" << std::endl;
}
<commit_msg>:currency_exchange: Change: test style<commit_after>#include "../src/game.h"
#define OK "\x1b[1m\x1b[32m✔\x1b[49m\x1b[0m"
#define NG "\x1b[1m\x1b[40m✘\x1b[49m\x1b[0m"
void test1(void);
void test2(void);
void testing(bool ope);
int flag = 0;
int main(void)
{
test1();
test2();
return flag;
}
void testing(bool ope)
{
if ( ope ) { return; }
throw false;
}
void test1(void)
{
int n = 10;
try {
testing(10 == n);
} catch(bool e) {
std::cout << "test1 : " << NG << std::endl;
flag = 1;
return;
}
std::cout << "test1 : " << OK << std::endl;
}
void test2(void)
{
bool flag = true;
Game *game = new Game();
int const **mz = game->map->maze();
int wid = game->map->width();
int hei = game->map->height();
try {
for ( int _i; _i < hei; _i++ ) {
testing(mz[_i][0] == 1);
testing(mz[_i][wid-1] == 1);
for ( int _j; _j < wid; _j++ ) {
testing(mz[0][_j] == 1);
testing(mz[hei-1][_j] == 1);
}
}
} catch(bool e) {
std::cout << "test2 : " << NG << std::endl;
delete game;
flag = 1;
return;
}
delete game;
std::cout << "test2 : " << OK << std::endl;
}
<|endoftext|> |
<commit_before>#include "Genes/Opponent_Pieces_Targeted_Gene.h"
#include <array>
#include <memory>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Moves/Move.h"
#include "Utility.h"
#include "Genes/Gene.h"
#include "Genes/Piece_Strength_Gene.h"
Opponent_Pieces_Targeted_Gene::Opponent_Pieces_Targeted_Gene(const Piece_Strength_Gene* piece_strength_gene) :
piece_strenth_source(piece_strength_gene)
{
}
double Opponent_Pieces_Targeted_Gene::score_board(const Board& board) const
{
double score = 0.0;
std::array<bool, 64> already_counted{};
for(const auto& move : board.legal_moves())
{
if( ! move->can_capture())
{
continue;
}
auto end_file = move->end_file();
auto end_rank = move->end_rank();
if(move->is_en_passant())
{
end_rank += (board.whose_turn() == WHITE ? -1 : 1);
}
auto target_piece = board.piece_on_square(end_file, end_rank);
auto target_index = Board::board_index(end_file, end_rank);
if(target_piece && ! already_counted[target_index])
{
score += piece_strenth_source->piece_value(target_piece);
already_counted[target_index] = true;
}
}
return score;
}
std::unique_ptr<Gene> Opponent_Pieces_Targeted_Gene::duplicate() const
{
return std::make_unique<Opponent_Pieces_Targeted_Gene>(*this);
}
std::string Opponent_Pieces_Targeted_Gene::name() const
{
return "Opponent Pieces Targeted Gene";
}
void Opponent_Pieces_Targeted_Gene::reset_piece_strength_gene(const Piece_Strength_Gene* psg)
{
piece_strenth_source = psg;
}
<commit_msg>Simpler en passant target modification<commit_after>#include "Genes/Opponent_Pieces_Targeted_Gene.h"
#include <array>
#include <memory>
#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Moves/Move.h"
#include "Utility.h"
#include "Genes/Gene.h"
#include "Genes/Piece_Strength_Gene.h"
Opponent_Pieces_Targeted_Gene::Opponent_Pieces_Targeted_Gene(const Piece_Strength_Gene* piece_strength_gene) :
piece_strenth_source(piece_strength_gene)
{
}
double Opponent_Pieces_Targeted_Gene::score_board(const Board& board) const
{
double score = 0.0;
std::array<bool, 64> already_counted{};
for(const auto& move : board.legal_moves())
{
if( ! move->can_capture())
{
continue;
}
auto end_file = move->end_file();
auto end_rank = move->end_rank();
if(move->is_en_passant())
{
end_rank -= move->rank_change();
}
auto target_piece = board.piece_on_square(end_file, end_rank);
auto target_index = Board::board_index(end_file, end_rank);
if(target_piece && ! already_counted[target_index])
{
score += piece_strenth_source->piece_value(target_piece);
already_counted[target_index] = true;
}
}
return score;
}
std::unique_ptr<Gene> Opponent_Pieces_Targeted_Gene::duplicate() const
{
return std::make_unique<Opponent_Pieces_Targeted_Gene>(*this);
}
std::string Opponent_Pieces_Targeted_Gene::name() const
{
return "Opponent Pieces Targeted Gene";
}
void Opponent_Pieces_Targeted_Gene::reset_piece_strength_gene(const Piece_Strength_Gene* psg)
{
piece_strenth_source = psg;
}
<|endoftext|> |
<commit_before>
#define BOOST_TEST_MODULE A429_test_module
#include <boost/test/included/unit_test.hpp>
#include <a429/a429base.hpp>
#include <a429/a429dis.hpp>
#include <a429/a429bcd.hpp>
#include <a429/a429bnr.hpp>
#include <a429/a429hyb.hpp>
BOOST_AUTO_TEST_SUITE( a429base_suite )
BOOST_AUTO_TEST_CASE( construct_default )
{
// Default construction, explicit cast
a429::a429base testword;
BOOST_TEST((a429::UINT)testword == 0);
}
BOOST_AUTO_TEST_CASE(construct_value_copy)
{
// Construct by value, implicit cast
a429::a429base testword(0xdeadbeef);
BOOST_TEST(testword == 0xdeadbeef);
// Construct by copy
a429::a429base testword2(testword);
BOOST_TEST(testword2 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(assign_operator)
{
a429::a429base testword(0xdeadbeef);
a429::a429base testword2;
testword2 = testword;
BOOST_TEST(testword2 == 0xdeadbeef);
testword2 = 0xa5a5a5a5;
BOOST_TEST(testword2 == 0xa5a5a5a5);
}
BOOST_AUTO_TEST_CASE(construct_ref)
{
// Construct by reference, GetWord
unsigned int reference = 0xdeadbeef;
a429::a429base testword(&reference);
BOOST_TEST(testword.GetWord() == 0xdeadbeef);
reference = 0xa5a5a5a5;
BOOST_TEST(testword.GetRevLbl() == 0xa5);
}
BOOST_AUTO_TEST_CASE(set_params)
{
a429::a429base testword;
testword.SetLbl(0271).SetSDI(01).SetSSM(3);
BOOST_TEST (testword.GetWord() == 0x6000019d);
}
BOOST_AUTO_TEST_CASE(get_params)
{
const a429::a429base testword(0x69a53cf0);
BOOST_TEST (testword.GetLbl() == 017);
BOOST_TEST (testword.GetRevLbl() == 0xf0);
BOOST_TEST (testword.GetSDI() == 0);
BOOST_TEST (testword.GetSSM() == 3);
BOOST_TEST (testword.GetWord() == 0x69a53cf0);
BOOST_TEST (testword.GetPar() == 0);
}
BOOST_AUTO_TEST_CASE(get_parity)
{
a429::a429base testword(0x600001ad);
BOOST_TEST (testword.GetPar() == 0);
BOOST_TEST (testword.CalcPar() == 1);
BOOST_TEST (testword.GetPar() == 0);
BOOST_TEST (testword.SetPar().GetPar() == 1);
BOOST_TEST (testword.SetPar(0).GetPar() == 0);
}
BOOST_AUTO_TEST_SUITE_END() // End a429base_suite
BOOST_AUTO_TEST_SUITE( a429dis_suite )
BOOST_AUTO_TEST_CASE( dis_copy_ctor )
{
a429::a429dis word1 = 0xa5a5a5a5;
a429::a429dis word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429dis word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(dis_bit)
{
a429::a429dis testword(0x00000200);
testword.SetBit(1, 9);
BOOST_TEST(testword.GetWord() == 0x00000300);
BOOST_TEST(testword.GetBit(9) == 1);
}
BOOST_AUTO_TEST_CASE(dis_bits)
{
a429::a429dis testword;
testword.SetBits(0xa, 16, 13);
BOOST_TEST(testword.GetWord() == 0x0000a000);
BOOST_TEST(testword.GetBits(16, 13) == 0xa);
}
BOOST_AUTO_TEST_CASE(dis_ssm)
{
a429::a429dis testword;
testword.SetSDI(a429::DIS_NCD);
BOOST_TEST(testword.GetSDI() == a429::DIS_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429dis_suite
BOOST_AUTO_TEST_SUITE( a429bcd_suite )
BOOST_AUTO_TEST_CASE( bcd_copy_ctor )
{
a429::a429bcd word1 = 0xa5a5a5a5;
a429::a429bcd word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429bcd word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(bcd_set_digit)
{
a429::a429bcd testword;
testword.SetDigit(0x7, 9, 11);
BOOST_TEST(testword.GetWord() == 0x00000700);
testword.SetDigit(0x0, 9, 10);
BOOST_TEST(testword.GetWord() == 0x00000400);
BOOST_TEST(testword.GetDigit(5, 12) == 0x40);
}
BOOST_AUTO_TEST_CASE(bcd_6_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(0.001, 6);
testword.SetBCD(123.456);
BOOST_TEST(testword.GetWord() == 0x12345600);
BOOST_TEST(testword.GetBCD() == 123.456); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE(bcd_5_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(1.0, 5);
testword.SetBCD(76543);
BOOST_TEST (testword.GetWord() == 0x1d950c00);
BOOST_TEST (testword.GetBCD() == 76543);
}
BOOST_AUTO_TEST_CASE(bcd_5_digit_inv)
{
a429::a429bcd testword(0xffffffff); // testing that we can also remove 1s
testword.SetBCDProperties(0.1, 5);
testword.SetBCD(32.1); // testing that leading zeros are cleared
BOOST_TEST (testword.GetWord() == 0x700c87ff);
BOOST_TEST (testword.GetBCD() == 32.1); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE(bcd_4_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(0.1, 4);
testword.SetBCD(432.1);
BOOST_TEST (testword.GetWord() == 0x10c84000);
BOOST_TEST (testword.GetBCD() == 432.1); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE(bcd_ssm)
{
a429::a429bcd testword;
testword.SetSDI(a429::BCD_NCD);
BOOST_TEST(testword.GetSDI() == a429::BCD_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429bcd_suite
BOOST_AUTO_TEST_SUITE( a429bnr_suite )
BOOST_AUTO_TEST_CASE( bnr_copy_ctor )
{
a429::a429bnr word1 = 0xa5a5a5a5;
a429::a429bnr word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429bnr word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE( bnr_pack )
{
a429::a429bnr testword;
testword.SetBNR(34.0, 1.0, 8);
BOOST_TEST (testword.GetWord() == 0x04400000);
testword.SetBNRPropertiesA(2.0, 12);
testword.SetBNR(-5108.0);
BOOST_TEST (testword.GetWord() == 0x19fa0000);
}
BOOST_AUTO_TEST_CASE( bnr_unpack )
{
a429::a429bnr testword(0x04400000);
testword.SetBNRPropertiesA(1.0, 8);
BOOST_TEST(testword.GetBNR() == 34.0); // Todo: add tolerance
testword = 0x19fa0000;
BOOST_TEST (testword.GetBNR(2.0, 12) == -5108.0); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE(bnr_ssm)
{
a429::a429bnr testword;
testword.SetSDI(a429::BNR_NCD);
BOOST_TEST(testword.GetSDI() == a429::BNR_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429bnr_suite
BOOST_AUTO_TEST_SUITE( a429hyb_suite )
BOOST_AUTO_TEST_CASE( hyb_copy_ctor )
{
a429::a429hyb word1 = 0xa5a5a5a5;
a429::a429hyb word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429hyb word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE( hyb_bnr )
{
a429::a429hyb testword;
testword.SetBNR(34.0, 1.0, 8);
BOOST_TEST (testword.GetWord() == 0x04400000);
testword.SetBNRPropertiesA(2.0, 12);
testword.SetBNR(-5108.0);
BOOST_TEST (testword.GetWord() == 0x19fa0000);
BOOST_TEST(testword.GetBNR() == 34.0); // Todo: add tolerance
testword = 0x19fa0000;
BOOST_TEST (testword.GetBNR(2.0, 12) == -5108.0); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE( hyb_bcd )
{
a429::a429hyb testword;
testword.SetBCDProperties(0.001, 6);
testword.SetBCD(123.456);
BOOST_TEST(testword.GetWord() == 0x12345600);
BOOST_TEST(testword.GetBCD() == 123.456); // Todo: add tolerance
}
BOOST_AUTO_TEST_CASE( hyb_dis )
{
a429::a429hyb testword(0x00000200);
testword.SetBit(1, 9);
BOOST_TEST(testword.GetWord() == 0x00000300);
BOOST_TEST(testword.GetBit(9) == 1);
testword.SetBits(0xa, 16, 13);
BOOST_TEST(testword.GetWord() == 0x0000a300);
BOOST_TEST(testword.GetBits(16, 13) == 0xa);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adding test tolerances to floating point numbers<commit_after>
#define BOOST_TEST_MODULE A429_test_module
#include <boost/test/included/unit_test.hpp>
#include <a429/a429base.hpp>
#include <a429/a429dis.hpp>
#include <a429/a429bcd.hpp>
#include <a429/a429bnr.hpp>
#include <a429/a429hyb.hpp>
namespace tt = boost::test_tools;
BOOST_AUTO_TEST_SUITE( a429base_suite )
BOOST_AUTO_TEST_CASE( construct_default )
{
// Default construction, explicit cast
a429::a429base testword;
BOOST_TEST((a429::UINT)testword == 0);
}
BOOST_AUTO_TEST_CASE(construct_value_copy)
{
// Construct by value, implicit cast
a429::a429base testword(0xdeadbeef);
BOOST_TEST(testword == 0xdeadbeef);
// Construct by copy
a429::a429base testword2(testword);
BOOST_TEST(testword2 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(assign_operator)
{
a429::a429base testword(0xdeadbeef);
a429::a429base testword2;
testword2 = testword;
BOOST_TEST(testword2 == 0xdeadbeef);
testword2 = 0xa5a5a5a5;
BOOST_TEST(testword2 == 0xa5a5a5a5);
}
BOOST_AUTO_TEST_CASE(construct_ref)
{
// Construct by reference, GetWord
unsigned int reference = 0xdeadbeef;
a429::a429base testword(&reference);
BOOST_TEST(testword.GetWord() == 0xdeadbeef);
reference = 0xa5a5a5a5;
BOOST_TEST(testword.GetRevLbl() == 0xa5);
}
BOOST_AUTO_TEST_CASE(set_params)
{
a429::a429base testword;
testword.SetLbl(0271).SetSDI(01).SetSSM(3);
BOOST_TEST (testword.GetWord() == 0x6000019d);
}
BOOST_AUTO_TEST_CASE(get_params)
{
const a429::a429base testword(0x69a53cf0);
BOOST_TEST (testword.GetLbl() == 017);
BOOST_TEST (testword.GetRevLbl() == 0xf0);
BOOST_TEST (testword.GetSDI() == 0);
BOOST_TEST (testword.GetSSM() == 3);
BOOST_TEST (testword.GetWord() == 0x69a53cf0);
BOOST_TEST (testword.GetPar() == 0);
}
BOOST_AUTO_TEST_CASE(get_parity)
{
a429::a429base testword(0x600003ad);
BOOST_TEST (testword.GetPar() == 0);
BOOST_TEST (testword.CalcPar() == 1);
BOOST_TEST (testword.GetPar() == 0);
BOOST_TEST (testword.SetPar().GetPar() == 1);
BOOST_TEST (testword.SetPar(0).GetPar() == 0);
}
BOOST_AUTO_TEST_SUITE_END() // End a429base_suite
BOOST_AUTO_TEST_SUITE( a429dis_suite )
BOOST_AUTO_TEST_CASE( dis_copy_ctor )
{
a429::a429dis word1 = 0xa5a5a5a5;
a429::a429dis word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429dis word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(dis_bit)
{
a429::a429dis testword(0x00000200);
testword.SetBit(1, 9);
BOOST_TEST(testword.GetWord() == 0x00000300);
BOOST_TEST(testword.GetBit(9) == 1);
}
BOOST_AUTO_TEST_CASE(dis_bits)
{
a429::a429dis testword;
testword.SetBits(0xa, 16, 13);
BOOST_TEST(testword.GetWord() == 0x0000a000);
BOOST_TEST(testword.GetBits(16, 13) == 0xa);
}
BOOST_AUTO_TEST_CASE(dis_ssm)
{
a429::a429dis testword;
testword.SetSDI(a429::DIS_NCD);
BOOST_TEST(testword.GetSDI() == a429::DIS_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429dis_suite
BOOST_AUTO_TEST_SUITE( a429bcd_suite )
BOOST_AUTO_TEST_CASE( bcd_copy_ctor )
{
a429::a429bcd word1 = 0xa5a5a5a5;
a429::a429bcd word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429bcd word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE(bcd_set_digit)
{
a429::a429bcd testword;
testword.SetDigit(0x7, 9, 11);
BOOST_TEST(testword.GetWord() == 0x00000700);
testword.SetDigit(0x0, 9, 10);
BOOST_TEST(testword.GetWord() == 0x00000400);
BOOST_TEST(testword.GetDigit(5, 12) == 0x40);
}
BOOST_AUTO_TEST_CASE(bcd_6_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(0.001, 6);
testword.SetBCD(123.456);
BOOST_TEST(testword.GetWord() == 0x12345600);
BOOST_TEST(testword.GetBCD() == 123.456, tt::tolerance(0.0000001));
}
BOOST_AUTO_TEST_CASE(bcd_5_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(1.0, 5);
testword.SetBCD(76543);
BOOST_TEST (testword.GetWord() == 0x1d950c00);
BOOST_TEST (testword.GetBCD() == 76543);
}
BOOST_AUTO_TEST_CASE(bcd_5_digit_inv)
{
a429::a429bcd testword( 0xffffffff ); // testing that we can also remove 1s
testword.SetBCDProperties(0.1, 5);
testword.SetBCD(32.1); // testing that leading zeros are cleared
BOOST_TEST (testword.GetWord() == 0x800c87ff); // Note SSM should represent BCD_POS.
BOOST_TEST (testword.GetBCD() == 32.1, tt::tolerance(0.0001) );
}
BOOST_AUTO_TEST_CASE(bcd_4_digit)
{
a429::a429bcd testword;
testword.SetBCDProperties(0.1, 4);
testword.SetBCD(432.1);
BOOST_TEST (testword.GetWord() == 0x10c84000);
BOOST_TEST (testword.GetBCD() == 432.1, tt::tolerance(0.00001) );
}
BOOST_AUTO_TEST_CASE(bcd_ssm)
{
a429::a429bcd testword;
testword.SetSDI(a429::BCD_NCD);
BOOST_TEST(testword.GetSDI() == a429::BCD_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429bcd_suite
BOOST_AUTO_TEST_SUITE( a429bnr_suite )
BOOST_AUTO_TEST_CASE( bnr_copy_ctor )
{
a429::a429bnr word1 = 0xa5a5a5a5;
a429::a429bnr word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429bnr word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE( bnr_pack )
{
a429::a429bnr testword;
testword.SetBNR(34.0, 1.0, 8);
BOOST_TEST (testword.GetWord() == 0x02200000);
testword.SetBNRPropertiesA(2.0, 12);
testword.SetBNR(-5108.0);
BOOST_TEST (testword.GetWord() == 0x19fa0000);
}
BOOST_AUTO_TEST_CASE( bnr_unpack )
{
a429::a429bnr testword(0x02200000);
testword.SetBNRPropertiesA(1.0, 8);
BOOST_TEST(testword.GetBNR() == 34.0, tt::tolerance(0.0001) );
testword = 0x19fa0000;
BOOST_TEST (testword.GetBNR(2.0, 12) == -5108.0, tt::tolerance(0.00001) );
}
BOOST_AUTO_TEST_CASE(bnr_ssm)
{
a429::a429bnr testword;
testword.SetSDI(a429::BNR_NCD);
BOOST_TEST(testword.GetSDI() == a429::BNR_NCD);
}
BOOST_AUTO_TEST_SUITE_END() // End a429bnr_suite
BOOST_AUTO_TEST_SUITE( a429hyb_suite )
BOOST_AUTO_TEST_CASE( hyb_copy_ctor )
{
a429::a429hyb word1 = 0xa5a5a5a5;
a429::a429hyb word2(word1);
BOOST_TEST (word2 == 0xa5a5a5a5);
a429::a429base word3 = 0xdeadbeef;
a429::a429hyb word4(word3);
BOOST_TEST (word4 == 0xdeadbeef);
}
BOOST_AUTO_TEST_CASE( hyb_bnr )
{
a429::a429hyb testword;
testword.SetBNR(34.0, 1.0, 8);
BOOST_TEST (testword.GetWord() == 0x02200000);
testword.SetBNRPropertiesA(2.0, 12);
testword.SetBNR(-5108.0);
BOOST_TEST (testword.GetWord() == 0x19fa0000);
BOOST_TEST(testword.GetBNR() == -5108.0, tt::tolerance(0.00001) );
testword = 0x19fa0000;
BOOST_TEST (testword.GetBNR(2.0, 12) == -5108.0, tt::tolerance(0.00001) );
}
BOOST_AUTO_TEST_CASE( hyb_bcd )
{
a429::a429hyb testword;
testword.SetBCDProperties(0.001, 6);
testword.SetBCD(123.456);
BOOST_TEST(testword.GetWord() == 0x12345600);
BOOST_TEST(testword.GetBCD() == 123.456, tt::tolerance(0.0000001) );
}
BOOST_AUTO_TEST_CASE( hyb_dis )
{
a429::a429hyb testword(0x00000200);
testword.SetBit(1, 9);
BOOST_TEST(testword.GetWord() == 0x00000300);
BOOST_TEST(testword.GetBit(9) == 1);
testword.SetBits(0xa, 16, 13);
BOOST_TEST(testword.GetWord() == 0x0000a300);
BOOST_TEST(testword.GetBits(16, 13) == 0xa);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "no_min_max.h"
#ifndef IUTEST_USE_MAIN
#define IUTEST_USE_MAIN
#endif
#include "../3rd_party/iutest/include/iutest.hpp"
#include "SigmoidTable.h"
#include "RSigmoidTable.h"
#include "analyzer.hpp"
#include "../SigColorFastAviUtl/SigmoidTable.hpp"
#include "../SigColorFastAviUtl/RSigmoidTable.hpp"
#include "../SigColorFastAviUtl/sigmoid.hpp"
#include "../SigColorFastAviUtl/inferior_iota_view.hpp"
#include "../SigColorFastAviUtl/analyzer.hpp"
#include "random.hpp"
#include <iostream>
#include <algorithm>
#include <execution>
thread_local auto engine = create_engine();
#if 0
IUTEST_TEST(SigmoidTableCompatibility, SigmoidTable_test) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
SigmoidTable new_table;
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::SigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
constexpr auto r = inferior::views::iota(0, 4097);
std::for_each(std::execution::par, r.begin(), r.end(), [&new_table, &old_table, s, m](int i) {
IUTEST_ASSERT(0 <= new_table.lookup(i) && new_table.lookup(i) <= 4096);
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
});
}
std::cerr << "\033[0;35mm=" << m + 1 << "/100\033[0;0m\r" << std::flush;
}
}
IUTEST_TEST(SigmoidTableCompatibility, RSigmoidTable_test) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
RSigmoidTable new_table;
new_table.change_param(1.0f, 30.0f);
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::RSigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
constexpr auto r = inferior::views::iota(0, 4097);
std::for_each(std::execution::par, r.begin(), r.end(), [&new_table, &old_table, s, m](int i) {
IUTEST_ASSERT(0 <= new_table.lookup(i) && new_table.lookup(i) <= 4096);
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
});
}
std::cerr << "\033[0;35mm=" << m + 1 << "/100\033[0;0m\r" << std::flush;
}
}
#endif
IUTEST_TEST(SigmoidTableCompatibility, SigmoidTable_test_out_of_range) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
SigmoidTable new_table;
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::SigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
for (int i : {-1, 4097}) {
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
//IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
}
}
}
}
IUTEST_TEST(SigmoidTableCompatibility, RSigmoidTable_test_out_of_range) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
RSigmoidTable new_table;
new_table.change_param(1.0f, 30.0f);
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::RSigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
for (int i : {-1, 4097}) {
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
//IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
}
}
}
}
IUTEST_TEST(SigmoidCompatibility, sigmod_test) {
static std::uniform_real_distribution<float> midtone(0.0, 1.0);
static std::uniform_real_distribution<float> strength(1.0, 30.0);
static std::uniform_int_distribution<std::uint16_t> u(0, 4096);
auto make_input = []() { return static_cast<float>(u(engine)) / 4096.0f; };
for (unsigned int i = 0; i < 100; ++i) {
const auto m = midtone(engine);
const auto s = strength(engine);
const auto u = make_input();
IUTEST_EXPECT(sigmoid(m, s, u) == sigmoid(m, s, u, sigmoid_pre(m, s)));
}
for (float m : {0.0f, 1.0f}) for (float s : {1.0f, 30.0f}) for (std::uint16_t u : {0, 4096}) {
IUTEST_EXPECT(sigmoid(m, s, static_cast<float>(u) / 4096.0f) == sigmoid(m, s, static_cast<float>(u) / 4096.0f, sigmoid_pre(m, s)));
}
}
IUTEST_TEST(Analyzer, calcAverage) {
using rep = std::chrono::nanoseconds::rep;
std::deque<rep> input;
input.resize(1000);
std::uniform_int_distribution<rep> d(1000, 7880500);
std::generate(input.begin(), input.end(), [d] { return d(engine); });
old_accumulate::analyzer old(input);
analyzer current(input);
IUTEST_EXPECT(old.average == current.average);
}
IUTEST_TEST(Analyzer, calcStdev) {
using rep = std::chrono::nanoseconds::rep;
std::deque<rep> input;
input.resize(1000);
std::uniform_int_distribution<rep> d(1000, 7880500);
std::generate(input.begin(), input.end(), [d] { return d(engine); });
old_accumulate::analyzer old(input);
analyzer current(input);
IUTEST_EXPECT(old.stdev == current.stdev);
}
<commit_msg>fix(test): use IUTEST_EXPECT_DOUBLE_EQ<commit_after>#include "no_min_max.h"
#ifndef IUTEST_USE_MAIN
#define IUTEST_USE_MAIN
#endif
#include "../3rd_party/iutest/include/iutest.hpp"
#include "SigmoidTable.h"
#include "RSigmoidTable.h"
#include "analyzer.hpp"
#include "../SigColorFastAviUtl/SigmoidTable.hpp"
#include "../SigColorFastAviUtl/RSigmoidTable.hpp"
#include "../SigColorFastAviUtl/sigmoid.hpp"
#include "../SigColorFastAviUtl/inferior_iota_view.hpp"
#include "../SigColorFastAviUtl/analyzer.hpp"
#include "random.hpp"
#include <iostream>
#include <algorithm>
#include <execution>
thread_local auto engine = create_engine();
#if 0
IUTEST_TEST(SigmoidTableCompatibility, SigmoidTable_test) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
SigmoidTable new_table;
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::SigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
constexpr auto r = inferior::views::iota(0, 4097);
std::for_each(std::execution::par, r.begin(), r.end(), [&new_table, &old_table, s, m](int i) {
IUTEST_ASSERT(0 <= new_table.lookup(i) && new_table.lookup(i) <= 4096);
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
});
}
std::cerr << "\033[0;35mm=" << m + 1 << "/100\033[0;0m\r" << std::flush;
}
}
IUTEST_TEST(SigmoidTableCompatibility, RSigmoidTable_test) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
RSigmoidTable new_table;
new_table.change_param(1.0f, 30.0f);
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::RSigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
constexpr auto r = inferior::views::iota(0, 4097);
std::for_each(std::execution::par, r.begin(), r.end(), [&new_table, &old_table, s, m](int i) {
IUTEST_ASSERT(0 <= new_table.lookup(i) && new_table.lookup(i) <= 4096);
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
});
}
std::cerr << "\033[0;35mm=" << m + 1 << "/100\033[0;0m\r" << std::flush;
}
}
#endif
IUTEST_TEST(SigmoidTableCompatibility, SigmoidTable_test_out_of_range) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
SigmoidTable new_table;
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::SigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
for (int i : {-1, 4097}) {
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
//IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
}
}
}
}
IUTEST_TEST(SigmoidTableCompatibility, RSigmoidTable_test_out_of_range) {
//0.0 <= midtone <= 1.0, 1.0 <= strength <= 30.0
RSigmoidTable new_table;
new_table.change_param(1.0f, 30.0f);
for (int m = 0; m <= 100; ++m) {
for (int s = 1; s <= 30; ++s) {
old::RSigmoidTable old_table(m / 100.0f, static_cast<float>(s), 4096, 4096.0);
new_table.change_param(m / 100.0f, static_cast<float>(s));
for (int i : {-1, 4097}) {
IUTEST_EXPECT(old_table.lookup(i) == new_table.lookup(i))
<< " (when i=" << i << " m=" << m << " s=" << s << ')';
//IUTEST_ASSERT_NEAR(static_cast<float>(old_table.lookup(i)), static_cast<float>(new_table.lookup(i)), 1.0f);
}
}
}
}
IUTEST_TEST(SigmoidCompatibility, sigmod_test) {
static std::uniform_real_distribution<float> midtone(0.0, 1.0);
static std::uniform_real_distribution<float> strength(1.0, 30.0);
static std::uniform_int_distribution<std::uint16_t> u(0, 4096);
auto make_input = []() { return static_cast<float>(u(engine)) / 4096.0f; };
for (unsigned int i = 0; i < 100; ++i) {
const auto m = midtone(engine);
const auto s = strength(engine);
const auto u = make_input();
IUTEST_EXPECT(sigmoid(m, s, u) == sigmoid(m, s, u, sigmoid_pre(m, s)));
}
for (float m : {0.0f, 1.0f}) for (float s : {1.0f, 30.0f}) for (std::uint16_t u : {0, 4096}) {
IUTEST_EXPECT(sigmoid(m, s, static_cast<float>(u) / 4096.0f) == sigmoid(m, s, static_cast<float>(u) / 4096.0f, sigmoid_pre(m, s)));
}
}
IUTEST_TEST(Analyzer, calcAverage) {
using rep = std::chrono::nanoseconds::rep;
std::deque<rep> input;
input.resize(1000);
std::uniform_int_distribution<rep> d(1000, 7880500);
std::generate(input.begin(), input.end(), [d] { return d(engine); });
old_accumulate::analyzer old(input);
analyzer current(input);
IUTEST_EXPECT_DOUBLE_EQ(old.average, current.average);
}
IUTEST_TEST(Analyzer, calcStdev) {
using rep = std::chrono::nanoseconds::rep;
std::deque<rep> input;
input.resize(1000);
std::uniform_int_distribution<rep> d(1000, 7880500);
std::generate(input.begin(), input.end(), [d] { return d(engine); });
old_accumulate::analyzer old(input);
analyzer current(input);
IUTEST_EXPECT_DOUBLE_EQ(old.stdev, current.stdev);
}
<|endoftext|> |
<commit_before>#include "medViewerConfigurationDiffusion.h"
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractViewFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewInteractor.h>
#include <medDataManager.h>
#include "medToolBoxDiffusionTensorView.h"
#include "medToolBoxDiffusion.h"
#include "medViewerToolBoxView.h"
#include "medToolBoxDiffusionFiberView.h"
#include "medToolBoxDiffusionFiberBundling.h"
#include <medViewContainer.h>
#include <medViewContainerSingle.h>
#include <medTabbedViewContainers.h>
class medViewerConfigurationDiffusionPrivate
{
public:
medViewerToolBoxView *viewToolBox;
medToolBoxDiffusionFiberView *fiberViewToolBox;
medToolBoxDiffusionFiberBundling *fiberBundlingToolBox;
medToolBoxDiffusion *diffusionToolBox;
medToolBoxDiffusionTensorView *tensorViewToolBox;
QList<dtkAbstractView *> views;
};
medViewerConfigurationDiffusion::medViewerConfigurationDiffusion(QWidget *parent) : medViewerConfiguration(parent), d(new medViewerConfigurationDiffusionPrivate)
{
// -- View toolbox --
d->viewToolBox = new medViewerToolBoxView(parent);
// -- Bundling toolbox --
d->fiberBundlingToolBox = new medToolBoxDiffusionFiberBundling(parent);
// -- Diffusion toolbox --
d->diffusionToolBox = new medToolBoxDiffusion(parent);
connect(d->diffusionToolBox, SIGNAL(addToolBox(medToolBox *)),
this, SLOT(addToolBox(medToolBox *)));
connect(d->diffusionToolBox, SIGNAL(removeToolBox(medToolBox *)),
this, SLOT(removeToolBox(medToolBox *)));
// -- Tensor tb --
d->tensorViewToolBox = new medToolBoxDiffusionTensorView(parent);
connect(d->tensorViewToolBox, SIGNAL(glyphShapeChanged(const QString&)), this, SLOT(onGlyphShapeChanged(const QString&)));
connect(d->tensorViewToolBox, SIGNAL(flipX(bool)), this, SLOT(onFlipXChanged(bool)));
connect(d->tensorViewToolBox, SIGNAL(flipY(bool)), this, SLOT(onFlipYChanged(bool)));
connect(d->tensorViewToolBox, SIGNAL(flipZ(bool)), this, SLOT(onFlipZChanged(bool)));
// -- Fiber view tb --
d->fiberViewToolBox = new medToolBoxDiffusionFiberView(parent);
connect(d->fiberViewToolBox, SIGNAL(fiberColorModeChanged(int)), this, SLOT(onFiberColorModeChanged(int)));
connect(d->fiberViewToolBox, SIGNAL(GPUActivated(bool)), this, SLOT(onGPUActivated(bool)));
connect(d->fiberViewToolBox, SIGNAL(lineModeSelected(bool)), this, SLOT(onLineModeSelected(bool)));
connect(d->fiberViewToolBox, SIGNAL(ribbonModeSelected(bool)), this, SLOT(onRibbonModeSelected(bool)));
connect(d->fiberViewToolBox, SIGNAL(tubeModeSelected(bool)), this, SLOT(onTubeModeSelected(bool)));
connect(d->fiberBundlingToolBox, SIGNAL(fiberSelectionValidated(const QString&, const QColor&)), this, SLOT(refreshInteractors()));
connect(d->diffusionToolBox, SIGNAL(success()), this, SLOT(onTBDiffusionSuccess()));
this->addToolBox( d->viewToolBox );
this->addToolBox( d->tensorViewToolBox );
this->addToolBox( d->fiberViewToolBox );
this->addToolBox( d->diffusionToolBox );
this->addToolBox( d->fiberBundlingToolBox );
}
medViewerConfigurationDiffusion::~medViewerConfigurationDiffusion(void)
{
delete d;
d = NULL;
}
QString medViewerConfigurationDiffusion::description(void) const
{
return "Diffusion";
}
void medViewerConfigurationDiffusion::setupViewContainerStack()
{
qDebug() << "ConfigurationDiffusionSetupViewContainerStack";
d->views.clear();
medViewContainer * diffusionContainer;
//the stack has been instantiated in constructor
if (!this->stackedViewContainers()->count())
{
medViewContainerSingle *single = new medViewContainerSingle ();
connect (single, SIGNAL (viewAdded (dtkAbstractView*)), this, SLOT (onViewAdded (dtkAbstractView*)));
connect (single, SIGNAL (viewRemoved (dtkAbstractView*)), this, SLOT (onViewRemoved (dtkAbstractView*)));
//ownership of single is transferred to the stackedWidget.
this->stackedViewContainers()->addContainer (description(), single);
diffusionContainer = single;
this->stackedViewContainers()->unlockTabs();
}
else
{
diffusionContainer = this->stackedViewContainers()->container(description());
//TODO: maybe clear views here too?
}
d->views << diffusionContainer->views();
//this->stackedViewContainers()->setContainer (description());
}
void medViewerConfigurationDiffusion::onViewAdded (dtkAbstractView *view)
{
if (!view)
return;
if (d->views.contains (view))
return;
d->views.append (view);
view->enableInteractor ("v3dViewFiberInteractor");
view->enableInteractor ("v3dViewTensorInteractor");
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor"))
connect(d->fiberViewToolBox, SIGNAL(fiberRadiusSet(int)), interactor, SLOT(onRadiusSet(int)));
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor"))
{
connect(d->tensorViewToolBox, SIGNAL(sampleRateChanged(int)), interactor, SLOT(onSampleRatePropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(eigenVectorChanged(int)), interactor, SLOT(onEigenVectorPropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(glyphResolutionChanged(int)), interactor, SLOT(onGlyphResolutionPropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(reverseBackgroundColor(bool)), interactor, SLOT(onReverseBackgroundColorPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(scalingChanged(double)), interactor, SLOT(onScalingPropertySet(double)));
connect(d->tensorViewToolBox, SIGNAL(hideShowAxial(bool)), interactor, SLOT(onHideShowAxialPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(hideShowCoronal(bool)), interactor, SLOT(onHideShowCoronalPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(hideShowSagittal(bool)), interactor, SLOT(onHideShowSagittalPropertySet(bool)));
// each change triggers and update of the view
// TODO we need to unify the view->update() as now some updates are done here and some
// are performed in the 'translate' function of the signal emitted by the toolbox
// (e.g. onFlipXChanged) ... maybe after dtk is extended to support QVariant properties
connect(d->tensorViewToolBox, SIGNAL(sampleRateChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(eigenVectorChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(glyphResolutionChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(reverseBackgroundColor(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(scalingChanged(double)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowAxial(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowCoronal(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowSagittal(bool)), view, SLOT(update(void)));
connect(view, SIGNAL(positionChanged(const QVector3D&,bool)), interactor, SLOT(onPositionChanged(const QVector3D&,bool)));
updateTensorInteractorWithToolboxValues(interactor, d->tensorViewToolBox);
}
}
void medViewerConfigurationDiffusion::updateTensorInteractorWithToolboxValues(dtkAbstractViewInteractor* interactor, medToolBoxDiffusionTensorView* tensorViewToolBox)
{
// we are temporary using Qt's reflection in this function to call the slots in the interactor
// without casting to a specific type (which is in a plugin)
// this code will be modified once a refactor in dtk property system is done
// (we might switch to QVariant instead of strings)
// TODO refactor this...
interactor->setProperty("GlyphShape", tensorViewToolBox->glyphShape());
int sampleRate = tensorViewToolBox->sampleRate();
QMetaObject::invokeMethod( interactor, "onSampleRatePropertySet", Qt::QueuedConnection, Q_ARG( int, sampleRate ) );
bool isFlipX = tensorViewToolBox->isFlipX();
interactor->setProperty("FlipX", isFlipX ? "true" : "false");
bool isFlipY = tensorViewToolBox->isFlipY();
interactor->setProperty("FlipY", isFlipY ? "true" : "false");
bool isFlipZ = tensorViewToolBox->isFlipZ();
interactor->setProperty("FlipZ", isFlipZ ? "true" : "false");
int eigenVector = tensorViewToolBox->eigenVector();
QMetaObject::invokeMethod( interactor, "onEigenVectorPropertySet", Qt::QueuedConnection, Q_ARG( int, eigenVector ) );
int glyphResolution = tensorViewToolBox->glyphResolution();
QMetaObject::invokeMethod( interactor, "onGlyphResolutionPropertySet", Qt::QueuedConnection, Q_ARG( int, glyphResolution ) );
double scale = tensorViewToolBox->scale();
QMetaObject::invokeMethod( interactor, "onScalingPropertySet", Qt::QueuedConnection, Q_ARG( double, scale ) );
bool isShowAxial = tensorViewToolBox->isShowAxial();
QMetaObject::invokeMethod( interactor, "onHideShowAxialPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowAxial ) );
bool isShowCoronal = tensorViewToolBox->isShowCoronal();
QMetaObject::invokeMethod( interactor, "onHideShowCoronalPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowCoronal ) );
bool isShowSagittal = tensorViewToolBox->isShowSagittal();
QMetaObject::invokeMethod( interactor, "onHideShowSagittalPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowSagittal ) );
}
void medViewerConfigurationDiffusion::onViewRemoved (dtkAbstractView *view)
{
if (!view)
return;
if (!d->views.contains (view))
return;
// view->disableInteractor ("v3dViewFiberInteractor");
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor"))
disconnect(d->fiberViewToolBox, SIGNAL(fiberRadiusSet(int)), interactor, SLOT(onRadiusSet(int)));
d->views.removeOne (view);
}
void medViewerConfigurationDiffusion::onFiberColorModeChanged(int index)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
if (index==0)
interactor->setProperty("ColorMode","local");
if (index==1)
interactor->setProperty("ColorMode","global");
if (index==2)
interactor->setProperty("ColorMode","fa");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onGPUActivated (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
if (value)
interactor->setProperty ("GPUMode", "true");
else
interactor->setProperty ("GPUMode", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onLineModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "lines");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onRibbonModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "ribbons");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onTubeModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "tubes");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onTBDiffusionSuccess(void)
{
foreach (dtkAbstractView *view, d->views) {
view->setData( d->diffusionToolBox->output(), 0 );
view->reset();
view->update();
}
if (d->diffusionToolBox->output()->description()=="v3dDataFibers")
d->fiberBundlingToolBox->setData( d->diffusionToolBox->output() );
medDataManager::instance()->importNonPersistent ( d->diffusionToolBox->output() );
}
// tensor interaction related methods
void medViewerConfigurationDiffusion::onGlyphShapeChanged(const QString& glyphShape)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
interactor->setProperty("GlyphShape", glyphShape);
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipXChanged(bool flipX)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipX)
interactor->setProperty("FlipX", "true");
else
interactor->setProperty("FlipX", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipYChanged(bool flipY)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipY)
interactor->setProperty("FlipY", "true");
else
interactor->setProperty("FlipY", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipZChanged(bool flipZ)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipZ)
interactor->setProperty("FlipZ", "true");
else
interactor->setProperty("FlipZ", "false");
view->update();
}
}
}
// end of tensor interaction related methods
void medViewerConfigurationDiffusion::refreshInteractors (void)
{
foreach (dtkAbstractView *view, d->views) {
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
// interactor->update(); // TO BE IMPLEMENTED
view->update();
}
}
}
void medViewerConfigurationDiffusion::onAddTabClicked()
{
QString name = this->description();
QString realName = name;
unsigned int suppTag = 0;
while (this->stackedViewContainers()->container(realName))
{
suppTag++;
realName = name + " ";
realName += QString::number(suppTag);
}
this->addSingleContainer(realName);
this->stackedViewContainers()->setContainer(realName);
}
medViewerConfiguration *createMedViewerConfigurationDiffusion(QWidget* parent)
{
return new medViewerConfigurationDiffusion(parent);
}
<commit_msg>Smart point what should be smart pointed<commit_after>#include "medViewerConfigurationDiffusion.h"
#include <dtkCore/dtkSmartPointer.h>
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractViewFactory.h>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkAbstractViewInteractor.h>
#include <medDataManager.h>
#include "medToolBoxDiffusionTensorView.h"
#include "medToolBoxDiffusion.h"
#include "medViewerToolBoxView.h"
#include "medToolBoxDiffusionFiberView.h"
#include "medToolBoxDiffusionFiberBundling.h"
#include <medViewContainer.h>
#include <medViewContainerSingle.h>
#include <medTabbedViewContainers.h>
class medViewerConfigurationDiffusionPrivate
{
public:
medViewerToolBoxView *viewToolBox;
medToolBoxDiffusionFiberView *fiberViewToolBox;
medToolBoxDiffusionFiberBundling *fiberBundlingToolBox;
medToolBoxDiffusion *diffusionToolBox;
medToolBoxDiffusionTensorView *tensorViewToolBox;
QList<dtkSmartPointer<dtkAbstractView> > views;
QString uuid;
};
medViewerConfigurationDiffusion::medViewerConfigurationDiffusion(QWidget *parent) : medViewerConfiguration(parent), d(new medViewerConfigurationDiffusionPrivate)
{
// -- View toolbox --
d->viewToolBox = new medViewerToolBoxView(parent);
// -- Bundling toolbox --
d->fiberBundlingToolBox = new medToolBoxDiffusionFiberBundling(parent);
// -- Diffusion toolbox --
d->diffusionToolBox = new medToolBoxDiffusion(parent);
connect(d->diffusionToolBox, SIGNAL(addToolBox(medToolBox *)),
this, SLOT(addToolBox(medToolBox *)));
connect(d->diffusionToolBox, SIGNAL(removeToolBox(medToolBox *)),
this, SLOT(removeToolBox(medToolBox *)));
// -- Tensor tb --
d->tensorViewToolBox = new medToolBoxDiffusionTensorView(parent);
connect(d->tensorViewToolBox, SIGNAL(glyphShapeChanged(const QString&)), this, SLOT(onGlyphShapeChanged(const QString&)));
connect(d->tensorViewToolBox, SIGNAL(flipX(bool)), this, SLOT(onFlipXChanged(bool)));
connect(d->tensorViewToolBox, SIGNAL(flipY(bool)), this, SLOT(onFlipYChanged(bool)));
connect(d->tensorViewToolBox, SIGNAL(flipZ(bool)), this, SLOT(onFlipZChanged(bool)));
// -- Fiber view tb --
d->fiberViewToolBox = new medToolBoxDiffusionFiberView(parent);
connect(d->fiberViewToolBox, SIGNAL(fiberColorModeChanged(int)), this, SLOT(onFiberColorModeChanged(int)));
connect(d->fiberViewToolBox, SIGNAL(GPUActivated(bool)), this, SLOT(onGPUActivated(bool)));
connect(d->fiberViewToolBox, SIGNAL(lineModeSelected(bool)), this, SLOT(onLineModeSelected(bool)));
connect(d->fiberViewToolBox, SIGNAL(ribbonModeSelected(bool)), this, SLOT(onRibbonModeSelected(bool)));
connect(d->fiberViewToolBox, SIGNAL(tubeModeSelected(bool)), this, SLOT(onTubeModeSelected(bool)));
connect(d->fiberBundlingToolBox, SIGNAL(fiberSelectionValidated(const QString&, const QColor&)), this, SLOT(refreshInteractors()));
connect(d->diffusionToolBox, SIGNAL(success()), this, SLOT(onTBDiffusionSuccess()));
this->addToolBox( d->viewToolBox );
this->addToolBox( d->tensorViewToolBox );
this->addToolBox( d->fiberViewToolBox );
this->addToolBox( d->diffusionToolBox );
this->addToolBox( d->fiberBundlingToolBox );
}
medViewerConfigurationDiffusion::~medViewerConfigurationDiffusion(void)
{
delete d;
d = NULL;
}
QString medViewerConfigurationDiffusion::description(void) const
{
return "Diffusion";
}
void medViewerConfigurationDiffusion::setupViewContainerStack()
{
d->views.clear();
medViewContainer * diffusionContainer = NULL;
//the stack has been instantiated in constructor
if (!this->stackedViewContainers()->count())
{
medViewContainerSingle *single = new medViewContainerSingle ();
connect (single, SIGNAL (viewAdded (dtkAbstractView*)), this, SLOT (onViewAdded (dtkAbstractView*)));
connect (single, SIGNAL (viewRemoved (dtkAbstractView*)), this, SLOT (onViewRemoved (dtkAbstractView*)));
//ownership of single is transferred to the stackedWidget.
this->stackedViewContainers()->addContainer (description(), single);
diffusionContainer = single;
this->stackedViewContainers()->lockTabs();
this->stackedViewContainers()->hideTabBar();
}
else
{
diffusionContainer = this->stackedViewContainers()->container(description());
//TODO: maybe clear views here too?
}
if (!diffusionContainer)
return;
foreach(dtkAbstractView *view, diffusionContainer->views())
d->views << view;
//this->stackedViewContainers()->setContainer (description());
}
void medViewerConfigurationDiffusion::onViewAdded (dtkAbstractView *view)
{
if (!view)
return;
if (d->views.contains (view))
return;
d->views.append (view);
view->enableInteractor ("v3dViewFiberInteractor");
view->enableInteractor ("v3dViewTensorInteractor");
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor"))
connect(d->fiberViewToolBox, SIGNAL(fiberRadiusSet(int)), interactor, SLOT(onRadiusSet(int)));
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor"))
{
connect(d->tensorViewToolBox, SIGNAL(sampleRateChanged(int)), interactor, SLOT(onSampleRatePropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(eigenVectorChanged(int)), interactor, SLOT(onEigenVectorPropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(glyphResolutionChanged(int)), interactor, SLOT(onGlyphResolutionPropertySet(int)));
connect(d->tensorViewToolBox, SIGNAL(reverseBackgroundColor(bool)), interactor, SLOT(onReverseBackgroundColorPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(scalingChanged(double)), interactor, SLOT(onScalingPropertySet(double)));
connect(d->tensorViewToolBox, SIGNAL(hideShowAxial(bool)), interactor, SLOT(onHideShowAxialPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(hideShowCoronal(bool)), interactor, SLOT(onHideShowCoronalPropertySet(bool)));
connect(d->tensorViewToolBox, SIGNAL(hideShowSagittal(bool)), interactor, SLOT(onHideShowSagittalPropertySet(bool)));
// each change triggers and update of the view
// TODO we need to unify the view->update() as now some updates are done here and some
// are performed in the 'translate' function of the signal emitted by the toolbox
// (e.g. onFlipXChanged) ... maybe after dtk is extended to support QVariant properties
connect(d->tensorViewToolBox, SIGNAL(sampleRateChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(eigenVectorChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(glyphResolutionChanged(int)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(reverseBackgroundColor(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(scalingChanged(double)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowAxial(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowCoronal(bool)), view, SLOT(update(void)));
connect(d->tensorViewToolBox, SIGNAL(hideShowSagittal(bool)), view, SLOT(update(void)));
connect(view, SIGNAL(positionChanged(const QVector3D&,bool)), interactor, SLOT(onPositionChanged(const QVector3D&,bool)));
updateTensorInteractorWithToolboxValues(interactor, d->tensorViewToolBox);
}
}
void medViewerConfigurationDiffusion::updateTensorInteractorWithToolboxValues(dtkAbstractViewInteractor* interactor, medToolBoxDiffusionTensorView* tensorViewToolBox)
{
// we are temporary using Qt's reflection in this function to call the slots in the interactor
// without casting to a specific type (which is in a plugin)
// this code will be modified once a refactor in dtk property system is done
// (we might switch to QVariant instead of strings)
// TODO refactor this...
interactor->setProperty("GlyphShape", tensorViewToolBox->glyphShape());
int sampleRate = tensorViewToolBox->sampleRate();
QMetaObject::invokeMethod( interactor, "onSampleRatePropertySet", Qt::QueuedConnection, Q_ARG( int, sampleRate ) );
bool isFlipX = tensorViewToolBox->isFlipX();
interactor->setProperty("FlipX", isFlipX ? "true" : "false");
bool isFlipY = tensorViewToolBox->isFlipY();
interactor->setProperty("FlipY", isFlipY ? "true" : "false");
bool isFlipZ = tensorViewToolBox->isFlipZ();
interactor->setProperty("FlipZ", isFlipZ ? "true" : "false");
int eigenVector = tensorViewToolBox->eigenVector();
QMetaObject::invokeMethod( interactor, "onEigenVectorPropertySet", Qt::QueuedConnection, Q_ARG( int, eigenVector ) );
int glyphResolution = tensorViewToolBox->glyphResolution();
QMetaObject::invokeMethod( interactor, "onGlyphResolutionPropertySet", Qt::QueuedConnection, Q_ARG( int, glyphResolution ) );
double scale = tensorViewToolBox->scale();
QMetaObject::invokeMethod( interactor, "onScalingPropertySet", Qt::QueuedConnection, Q_ARG( double, scale ) );
bool isShowAxial = tensorViewToolBox->isShowAxial();
QMetaObject::invokeMethod( interactor, "onHideShowAxialPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowAxial ) );
bool isShowCoronal = tensorViewToolBox->isShowCoronal();
QMetaObject::invokeMethod( interactor, "onHideShowCoronalPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowCoronal ) );
bool isShowSagittal = tensorViewToolBox->isShowSagittal();
QMetaObject::invokeMethod( interactor, "onHideShowSagittalPropertySet", Qt::QueuedConnection, Q_ARG( bool, isShowSagittal ) );
}
void medViewerConfigurationDiffusion::onViewRemoved (dtkAbstractView *view)
{
if (!view)
return;
if (!d->views.contains (view))
return;
// view->disableInteractor ("v3dViewFiberInteractor");
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor"))
disconnect(d->fiberViewToolBox, SIGNAL(fiberRadiusSet(int)), interactor, SLOT(onRadiusSet(int)));
d->views.removeOne (view);
}
void medViewerConfigurationDiffusion::onFiberColorModeChanged(int index)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
if (index==0)
interactor->setProperty("ColorMode","local");
if (index==1)
interactor->setProperty("ColorMode","global");
if (index==2)
interactor->setProperty("ColorMode","fa");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onGPUActivated (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
if (value)
interactor->setProperty ("GPUMode", "true");
else
interactor->setProperty ("GPUMode", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onLineModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "lines");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onRibbonModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "ribbons");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onTubeModeSelected (bool value)
{
foreach (dtkAbstractView *view, d->views) {
if (value)
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
interactor->setProperty ("RenderingMode", "tubes");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onTBDiffusionSuccess(void)
{
foreach (dtkAbstractView *view, d->views) {
view->setData( d->diffusionToolBox->output(), 0 );
view->reset();
view->update();
}
if (d->diffusionToolBox->output()->description()=="v3dDataFibers")
d->fiberBundlingToolBox->setData( d->diffusionToolBox->output() );
medDataManager::instance()->importNonPersistent ( d->diffusionToolBox->output() );
}
// tensor interaction related methods
void medViewerConfigurationDiffusion::onGlyphShapeChanged(const QString& glyphShape)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
interactor->setProperty("GlyphShape", glyphShape);
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipXChanged(bool flipX)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipX)
interactor->setProperty("FlipX", "true");
else
interactor->setProperty("FlipX", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipYChanged(bool flipY)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipY)
interactor->setProperty("FlipY", "true");
else
interactor->setProperty("FlipY", "false");
view->update();
}
}
}
void medViewerConfigurationDiffusion::onFlipZChanged(bool flipZ)
{
foreach (dtkAbstractView *view, d->views) {
if (dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewTensorInteractor")) {
if (flipZ)
interactor->setProperty("FlipZ", "true");
else
interactor->setProperty("FlipZ", "false");
view->update();
}
}
}
// end of tensor interaction related methods
void medViewerConfigurationDiffusion::refreshInteractors (void)
{
foreach (dtkAbstractView *view, d->views) {
if(dtkAbstractViewInteractor *interactor = view->interactor ("v3dViewFiberInteractor")) {
// interactor->update(); // TO BE IMPLEMENTED
view->update();
}
}
}
void medViewerConfigurationDiffusion::onAddTabClicked()
{
QString name = this->description();
QString realName = name;
unsigned int suppTag = 0;
while (this->stackedViewContainers()->container(realName))
{
suppTag++;
realName = name + " ";
realName += QString::number(suppTag);
}
this->addSingleContainer(realName);
this->stackedViewContainers()->setContainer(realName);
}
medViewerConfiguration *createMedViewerConfigurationDiffusion(QWidget* parent)
{
return new medViewerConfigurationDiffusion(parent);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include "Minesweeper.hpp"
int main() {
CErrorInfo errorInfo;
std::vector<char> errorMessage(100U, 0);
errorInfo.errorMessage = errorMessage.data();
GameHandle gameHandle{};
minesweeper_new_game(&gameHandle, GameLevel::Expert, &errorInfo);
std::cout << "Error message: \"" << std::string(errorInfo.errorMessage)
<< "\", error code: " << static_cast<uint32_t>(errorInfo.errorCode) << '\n';
FieldFlagResult result;
COpenInfo openInfo;
std::vector<CFieldInfo> fieldInfos(100U, CFieldInfo{});
openInfo.fieldInfos = fieldInfos.data();
openInfo.fieldInfosLength = 0U;
openInfo.fieldInfosMaxLength = fieldInfos.size();
minesweeper_game_open(gameHandle, 0U, 0U, &openInfo, &errorInfo);
std::cout << "Error message: \"" << std::string(errorInfo.errorMessage)
<< "\", error code: " << static_cast<uint32_t>(errorInfo.errorCode) << '\n';
std::cout << openInfo.fieldInfosLength << '\n';
return openInfo.fieldInfosLength;
minesweeper_destroy_game(gameHandle);
}<commit_msg>Fix CppCheck warnings<commit_after>#include <iostream>
#include <vector>
#include "Minesweeper.hpp"
int main() {
CErrorInfo errorInfo;
std::vector<char> errorMessage(100U, 0);
errorInfo.errorMessage = errorMessage.data();
GameHandle gameHandle{};
minesweeper_new_game(&gameHandle, GameLevel::Expert, &errorInfo);
std::cout << "Error message: \"" << std::string(errorInfo.errorMessage)
<< "\", error code: " << static_cast<uint32_t>(errorInfo.errorCode) << '\n';
COpenInfo openInfo;
std::vector<CFieldInfo> fieldInfos(100U, CFieldInfo{});
openInfo.fieldInfos = fieldInfos.data();
openInfo.fieldInfosLength = 0U;
openInfo.fieldInfosMaxLength = fieldInfos.size();
minesweeper_game_open(gameHandle, 0U, 0U, &openInfo, &errorInfo);
std::cout << "Error message: \"" << std::string(errorInfo.errorMessage)
<< "\", error code: " << static_cast<uint32_t>(errorInfo.errorCode) << '\n';
std::cout << openInfo.fieldInfosLength << '\n';
minesweeper_destroy_game(gameHandle);
return 0;
}<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "erpiko/cmp.h"
#include "erpiko/utils.h"
#include "erpiko/data-source.h"
#include "erpiko/rsakey.h"
#include "erpiko/certificate.h"
namespace Erpiko {
SCENARIO("CMP ir request") {
GIVEN("A ca cert, a key and a subject") {
DataSource* src = DataSource::fromFile("assets/cacert.pem");
auto v = src->readAll();
std::string pem(v.begin(),v.end());
Certificate* cacert = Certificate::fromPem(pem);
REQUIRE_FALSE(cacert == nullptr);
RsaKey* pair = RsaKey::create(4096);
REQUIRE(pair->bits() == 4096);
Identity* id = new Identity();
REQUIRE_FALSE(id == nullptr);
id->set("commonName", "testkk02");
id->set("UID", "omama");
auto cmp = new Cmp();
/*
We don't have mocking in place, so yeah...
cmp->subject(*id);
cmp->caCertificate(*cacert);
cmp->serverName("ejbca.sandbox");
cmp->serverPort(8181);
cmp->serverPath("/ejbca/publicweb/cmp/CMP");
cmp->referenceName("testkk02");
cmp->secret("omama");
cmp->privateKey(*pair);
ObjectId hash("2.16.840.1.101.3.4.2.1");
ObjectId siiType("1.2.3.4.5");
std::string sii("12345");
std::string password("abcde12345");
std::vector<unsigned char> r = {
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8 };
Sim sim(hash, siiType, sii, password, r);
cmp->insertSim(sim);
auto clCert = cmp->startInitRequest();
REQUIRE_FALSE(clCert == nullptr);
std::cout << Utils::hexString(clCert->toDer()) << "\n";
*/
}
}
} // namespace Erpiko
<commit_msg>Skip cmp test<commit_after>#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "erpiko/cmp.h"
#include "erpiko/utils.h"
#include "erpiko/data-source.h"
#include "erpiko/rsakey.h"
#include "erpiko/certificate.h"
namespace Erpiko {
SCENARIO("CMP ir request") {
GIVEN("A ca cert, a key and a subject") {
/*
DataSource* src = DataSource::fromFile("assets/cacert.pem");
auto v = src->readAll();
std::string pem(v.begin(),v.end());
Certificate* cacert = Certificate::fromPem(pem);
REQUIRE_FALSE(cacert == nullptr);
RsaKey* pair = RsaKey::create(4096);
REQUIRE(pair->bits() == 4096);
Identity* id = new Identity();
REQUIRE_FALSE(id == nullptr);
id->set("commonName", "testkk02");
id->set("UID", "omama");
auto cmp = new Cmp();
We don't have mocking in place, so yeah...
cmp->subject(*id);
cmp->caCertificate(*cacert);
cmp->serverName("ejbca.sandbox");
cmp->serverPort(8181);
cmp->serverPath("/ejbca/publicweb/cmp/CMP");
cmp->referenceName("testkk02");
cmp->secret("omama");
cmp->privateKey(*pair);
ObjectId hash("2.16.840.1.101.3.4.2.1");
ObjectId siiType("1.2.3.4.5");
std::string sii("12345");
std::string password("abcde12345");
std::vector<unsigned char> r = {
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8,
1, 2, 3, 4, 5, 6, 7, 8 };
Sim sim(hash, siiType, sii, password, r);
cmp->insertSim(sim);
auto clCert = cmp->startInitRequest();
REQUIRE_FALSE(clCert == nullptr);
std::cout << Utils::hexString(clCert->toDer()) << "\n";
*/
}
}
} // namespace Erpiko
<|endoftext|> |
<commit_before>#include "client/client.h"
#include <arpa/inet.h>
#include <glog/logging.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/socket.h>
#include <unistd.h>
#ifdef __MACH__
// does not exist on MacOS
#define MSG_NOSIGNAL 0
#endif
using std::string;
Client::Client(const string& server, const string& port)
: server_(server), port_(port), fd_(-1) {
}
Client::~Client() {
Disconnect();
}
bool Client::Connect() {
CHECK(!Connected());
static const addrinfo server_addr_hints = {
AI_ADDRCONFIG, /* ai_flags */
AF_UNSPEC, /* ai_family */
SOCK_STREAM, /* ai_socktype */
IPPROTO_TCP /* ai_protocol */
};
struct addrinfo* server_addr;
int ret = getaddrinfo(server_.c_str(), port_.c_str(), &server_addr_hints,
&server_addr);
CHECK_EQ(0, ret) << "Invalid server address '" << server_
<< "' and/or port '" << port_ << "': "
<< gai_strerror(ret);
bool is_connected = false;
while (!is_connected && server_addr != NULL) {
fd_ = socket(server_addr->ai_family,
server_addr->ai_socktype,
server_addr->ai_protocol);
PCHECK(fd_ >= 0) << "Socket creation failed";
if (connect(fd_, server_addr->ai_addr, server_addr->ai_addrlen) == 0) {
is_connected = true;
} else {
server_addr = server_addr->ai_next; // Try next address
}
}
freeaddrinfo(server_addr);
if (!is_connected) {
PLOG(ERROR) << "Connection to [" << server_ << "]:" << port_ << " failed";
Disconnect();
return false;
}
LOG(INFO) << "Connected to [" << server_ << "]:" << port_;
return true;
}
bool Client::Connected() const {
return fd_ > 0;
}
void Client::Disconnect() {
if (fd_ > 0) {
close(fd_);
LOG(INFO) << "Disconnected from [" << server_ << "]:" << port_;
fd_ = -1;
}
}
bool Client::Write(const string& data) {
CHECK(Connected());
int n = send(fd_, data.data(), data.length(), MSG_NOSIGNAL);
if (n <= 0) {
PCHECK(errno == EPIPE) << "Send failed";
LOG(ERROR) << "Remote server closed the connection.";
Disconnect();
return false;
}
CHECK_EQ(data.length(), (unsigned)n);
VLOG(1) << "wrote " << data.length() << " bytes";
return true;
}
bool Client::Read(size_t length, string* result) {
CHECK(Connected());
char* buf = new char[length];
for (size_t offset = 0; offset < length;) {
int n = recv(fd_, buf + offset, length - offset, MSG_NOSIGNAL);
if (n <= 0) {
PCHECK(errno == EPIPE) << "Read failed";
LOG(ERROR) << "Remote server closed the connection.";
Disconnect();
delete[] buf;
return false;
}
offset += n;
}
result->assign(string(buf, length));
delete[] buf;
VLOG(1) << "read " << length << " bytes";
return true;
}
<commit_msg>Makes value returned by getaddrinfo in client.cc const<commit_after>#include "client/client.h"
#include <arpa/inet.h>
#include <glog/logging.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/socket.h>
#include <unistd.h>
#ifdef __MACH__
// does not exist on MacOS
#define MSG_NOSIGNAL 0
#endif
using std::string;
Client::Client(const string& server, const string& port)
: server_(server), port_(port), fd_(-1) {
}
Client::~Client() {
Disconnect();
}
bool Client::Connect() {
CHECK(!Connected());
static const addrinfo server_addr_hints = {
AI_ADDRCONFIG, /* ai_flags */
AF_UNSPEC, /* ai_family */
SOCK_STREAM, /* ai_socktype */
IPPROTO_TCP /* ai_protocol */
};
struct addrinfo* server_addr;
const int ret = getaddrinfo(server_.c_str(), port_.c_str(),
&server_addr_hints, &server_addr);
CHECK_EQ(0, ret) << "Invalid server address '" << server_
<< "' and/or port '" << port_ << "': "
<< gai_strerror(ret);
bool is_connected = false;
while (!is_connected && server_addr != NULL) {
fd_ = socket(server_addr->ai_family,
server_addr->ai_socktype,
server_addr->ai_protocol);
PCHECK(fd_ >= 0) << "Socket creation failed";
if (connect(fd_, server_addr->ai_addr, server_addr->ai_addrlen) == 0) {
is_connected = true;
} else {
server_addr = server_addr->ai_next; // Try next address
}
}
freeaddrinfo(server_addr);
if (!is_connected) {
PLOG(ERROR) << "Connection to [" << server_ << "]:" << port_ << " failed";
Disconnect();
return false;
}
LOG(INFO) << "Connected to [" << server_ << "]:" << port_;
return true;
}
bool Client::Connected() const {
return fd_ > 0;
}
void Client::Disconnect() {
if (fd_ > 0) {
close(fd_);
LOG(INFO) << "Disconnected from [" << server_ << "]:" << port_;
fd_ = -1;
}
}
bool Client::Write(const string& data) {
CHECK(Connected());
int n = send(fd_, data.data(), data.length(), MSG_NOSIGNAL);
if (n <= 0) {
PCHECK(errno == EPIPE) << "Send failed";
LOG(ERROR) << "Remote server closed the connection.";
Disconnect();
return false;
}
CHECK_EQ(data.length(), (unsigned)n);
VLOG(1) << "wrote " << data.length() << " bytes";
return true;
}
bool Client::Read(size_t length, string* result) {
CHECK(Connected());
char* buf = new char[length];
for (size_t offset = 0; offset < length;) {
int n = recv(fd_, buf + offset, length - offset, MSG_NOSIGNAL);
if (n <= 0) {
PCHECK(errno == EPIPE) << "Read failed";
LOG(ERROR) << "Remote server closed the connection.";
Disconnect();
delete[] buf;
return false;
}
offset += n;
}
result->assign(string(buf, length));
delete[] buf;
VLOG(1) << "read " << length << " bytes";
return true;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <catch.hpp>
#include <proton/url.hpp>
namespace {
using proton::url;
#define CHECK_URL(U, SCHEME, USER, PWD, HOST, PORT, PATH, S) do { \
url u(U); \
CHECK((SCHEME) == u.scheme()); \
CHECK((USER) == u.user()); \
CHECK((PWD) == u.password()); \
CHECK((HOST) == u.host()); \
CHECK((PORT) == u.port()); \
CHECK((PATH) == u.path()); \
CHECK(std::string(S) == std::string(u)); \
} while(0)
TEST_CASE("parse URL","[url]") {
SECTION("full and defaulted") {
CHECK_URL(url("amqp://foo:xyz/path"),
"amqp", "", "", "foo", "xyz", "path",
"amqp://foo:xyz/path");
CHECK_URL(url("amqp://username:password@host:1234/path"),
"amqp", "username", "password", "host", "1234", "path",
"amqp://username:password@host:1234/path");
CHECK_URL(url("host:1234"),
"amqp", "", "", "host", "1234", "",
"amqp://host:1234");
CHECK_URL(url("host"),
"amqp", "", "", "host", "amqp", "",
"amqp://host:amqp");
CHECK_URL(url("host/path"),
"amqp", "", "", "host", "amqp", "path",
"amqp://host:amqp/path");
CHECK_URL(url("amqps://host"),
"amqps", "", "", "host", "amqps", "",
"amqps://host:amqps");
CHECK_URL(url("/path"),
"amqp", "", "", "localhost", "amqp", "path",
"amqp://localhost:amqp/path");
CHECK_URL(url(""),
"amqp", "", "", "localhost", "amqp", "",
"amqp://localhost:amqp");
CHECK_URL(url(":1234"),
"amqp", "", "", "localhost", "1234", "",
"amqp://localhost:1234");
}
SECTION("starting with //") {
CHECK_URL(url("//username:password@host:1234/path"),
"amqp", "username", "password", "host", "1234", "path",
"amqp://username:password@host:1234/path");
CHECK_URL(url("//host:port/path"),
"amqp", "", "", "host", "port", "path",
"amqp://host:port/path");
CHECK_URL(url("//host"),
"amqp", "", "", "host", "amqp", "",
"amqp://host:amqp");
CHECK_URL(url("//:port"),
"amqp", "", "", "localhost", "port", "",
"amqp://localhost:port");
CHECK_URL(url("//:0"),
"amqp", "", "", "localhost", "0", "",
"amqp://localhost:0");
}
SECTION("no defaults") {
CHECK_URL(url("", false),
"", "", "", "", "", "",
"");
CHECK_URL(url("//:", false),
"", "", "", "", "", "",
":");
CHECK_URL(url("//:0", false),
"", "", "", "", "0", "",
":0");
CHECK_URL(url("//h:", false),
"", "", "", "h", "", "",
"h:");
}
SECTION("urlencoding") {
CHECK_URL(url("amqps://%40user%2F%3A:%40pass%2F%3A@example.net/some_topic"),
"amqps", "@user/:", "@pass/:", "example.net", "amqps", "some_topic",
"amqps://%40user%2F%3A:%40pass%2F%3A@example.net:amqps/some_topic");
CHECK_URL(url("amqps://user%2F%3A=:pass%2F%3A=@example.net/some_topic"),
"amqps", "user/:=", "pass/:=", "example.net", "amqps", "some_topic",
"amqps://user%2F%3A=:pass%2F%3A=@example.net:amqps/some_topic");
}
}
} // namespace
<commit_msg>PROTON-2104 add test for IPv6 in proton::url (#280)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <catch.hpp>
#include <proton/url.hpp>
namespace {
using proton::url;
#define CHECK_URL(U, SCHEME, USER, PWD, HOST, PORT, PATH, S) do { \
url u(U); \
CHECK((SCHEME) == u.scheme()); \
CHECK((USER) == u.user()); \
CHECK((PWD) == u.password()); \
CHECK((HOST) == u.host()); \
CHECK((PORT) == u.port()); \
CHECK((PATH) == u.path()); \
CHECK(std::string(S) == std::string(u)); \
} while(0)
TEST_CASE("parse URL","[url]") {
SECTION("full and defaulted") {
CHECK_URL(url("amqp://foo:xyz/path"),
"amqp", "", "", "foo", "xyz", "path",
"amqp://foo:xyz/path");
CHECK_URL(url("amqp://username:password@host:1234/path"),
"amqp", "username", "password", "host", "1234", "path",
"amqp://username:password@host:1234/path");
CHECK_URL(url("host:1234"),
"amqp", "", "", "host", "1234", "",
"amqp://host:1234");
CHECK_URL(url("host"),
"amqp", "", "", "host", "amqp", "",
"amqp://host:amqp");
CHECK_URL(url("host/path"),
"amqp", "", "", "host", "amqp", "path",
"amqp://host:amqp/path");
CHECK_URL(url("amqps://host"),
"amqps", "", "", "host", "amqps", "",
"amqps://host:amqps");
CHECK_URL(url("/path"),
"amqp", "", "", "localhost", "amqp", "path",
"amqp://localhost:amqp/path");
CHECK_URL(url(""),
"amqp", "", "", "localhost", "amqp", "",
"amqp://localhost:amqp");
CHECK_URL(url(":1234"),
"amqp", "", "", "localhost", "1234", "",
"amqp://localhost:1234");
}
SECTION("starting with //") {
CHECK_URL(url("//username:password@host:1234/path"),
"amqp", "username", "password", "host", "1234", "path",
"amqp://username:password@host:1234/path");
CHECK_URL(url("//host:port/path"),
"amqp", "", "", "host", "port", "path",
"amqp://host:port/path");
CHECK_URL(url("//host"),
"amqp", "", "", "host", "amqp", "",
"amqp://host:amqp");
CHECK_URL(url("//:port"),
"amqp", "", "", "localhost", "port", "",
"amqp://localhost:port");
CHECK_URL(url("//:0"),
"amqp", "", "", "localhost", "0", "",
"amqp://localhost:0");
}
SECTION("no defaults") {
CHECK_URL(url("", false),
"", "", "", "", "", "",
"");
CHECK_URL(url("//:", false),
"", "", "", "", "", "",
":");
CHECK_URL(url("//:0", false),
"", "", "", "", "0", "",
":0");
CHECK_URL(url("//h:", false),
"", "", "", "h", "", "",
"h:");
}
SECTION("urlencoding") {
CHECK_URL(url("amqps://%40user%2F%3A:%40pass%2F%3A@example.net/some_topic"),
"amqps", "@user/:", "@pass/:", "example.net", "amqps", "some_topic",
"amqps://%40user%2F%3A:%40pass%2F%3A@example.net:amqps/some_topic");
CHECK_URL(url("amqps://user%2F%3A=:pass%2F%3A=@example.net/some_topic"),
"amqps", "user/:=", "pass/:=", "example.net", "amqps", "some_topic",
"amqps://user%2F%3A=:pass%2F%3A=@example.net:amqps/some_topic");
}
SECTION("ipv6") {
CHECK_URL(url("[fe80::c662:ab36:1ef1:1596]:5672/path"),
"amqp", "", "", "fe80::c662:ab36:1ef1:1596", "5672", "path",
"amqp://[fe80::c662:ab36:1ef1:1596]:5672/path");
CHECK_URL(url("amqp://user:pass@[::1]:1234/path"),
"amqp", "user", "pass", "::1", "1234", "path",
"amqp://user:pass@[::1]:1234/path");
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "deletabledetector.h"
#include "interfaces/isyncitem.h"
#include "interfaces/imod.h"
#include "afisync.h"
#include "afisynclogger.h"
QStringList AfiSync::activeModNames(const QList<IRepository*>& repositories)
{
QStringList retVal;
for (const IRepository* repository : repositories)
{
for (const QString& modName : activeModNames(repository))
{
if (!retVal.contains(modName))
{
retVal.append(modName);
}
}
}
return retVal;
}
QSet<QString> AfiSync::activeModNames(const IRepository* repository)
{
QSet<QString> retVal;
for (IMod* mod : repository->uiMods())
{
//FIXME: Incorrect?
if (mod->selected())
{
retVal.insert(mod->name());
}
}
return retVal;
}
void AfiSync::printDeletables(const DeletableDetector& deletableDetector)
{
QString modList;
for (const QString& modName : deletableDetector.deletableNames())
{
modList += " " + modName;
}
LOG << "Delete inactive mods (Space used: " + QString::number(deletableDetector.totalSize()/1000000000) + " GB ) rmdir" + modList;
}
<commit_msg>rmdir print refined<commit_after>#include "deletabledetector.h"
#include "interfaces/isyncitem.h"
#include "interfaces/imod.h"
#include "afisync.h"
#include "afisynclogger.h"
QStringList AfiSync::activeModNames(const QList<IRepository*>& repositories)
{
QStringList retVal;
for (const IRepository* repository : repositories)
{
for (const QString& modName : activeModNames(repository))
{
if (!retVal.contains(modName))
{
retVal.append(modName);
}
}
}
return retVal;
}
QSet<QString> AfiSync::activeModNames(const IRepository* repository)
{
QSet<QString> retVal;
for (IMod* mod : repository->uiMods())
{
//FIXME: Incorrect?
if (mod->selected())
{
retVal.insert(mod->name());
}
}
return retVal;
}
void AfiSync::printDeletables(const DeletableDetector& deletableDetector)
{
QString modList;
for (const QString& modName : deletableDetector.deletableNames())
{
modList += " " + modName;
}
LOG << "Delete inactive mods (Space used: " + QString::number(deletableDetector.totalSize()/1000000000) + " GB ) rmdir /s" + modList;
}
<|endoftext|> |
<commit_before>#include <Python.h>
#include "Quantuccia/ql/time/calendar.hpp"
#include "Quantuccia/ql/time/date.hpp"
#include "Quantuccia/ql/time/calendars/unitedkingdom.hpp"
static PyObject*
united_kingdom_is_business_day(PyObject *self, PyObject *args)
{
int year;
int month;
int day;
if (!PyArg_ParseTuple(args, "bbb|", &year, &month, &day))
return NULL;
QuantLib::Day d(day);
QuantLib::Month m(month);
QuantLib::Year y(year);
QuantLib::Date date(d, m, y);
QuantLib::Calendar calendar = new QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Market::Exchange);
return PyBool_FromLong(calendar.isBusinessDay(date));
}
static PyMethodDef QuantucciaMethods[] = {
{"united_kingdom_is_business_day", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef quantuccia_module_def = {
PyModuleDef_HEAD_INIT,
"quantuccia",
NULL,
-1,
QuantucciaMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_quantuccia(void){
PyObject *m;
m = PyModule_Create(&quantuccia_module_def);
return m;
}
<commit_msg>Cast an itneger to a Month enum.<commit_after>#include <Python.h>
#include "Quantuccia/ql/time/calendar.hpp"
#include "Quantuccia/ql/time/date.hpp"
#include "Quantuccia/ql/time/calendars/unitedkingdom.hpp"
static PyObject*
united_kingdom_is_business_day(PyObject *self, PyObject *args)
{
int year;
int month;
int day;
if (!PyArg_ParseTuple(args, "bbb|", &year, &month, &day))
return NULL;
QuantLib::Day d(day);
QuantLib::Month m = static_cast<QuantLib::Month>(month);
QuantLib::Year y(year);
QuantLib::Date date(d, m, y);
QuantLib::Calendar calendar = new QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Market::Exchange);
return PyBool_FromLong(calendar.isBusinessDay(date));
}
static PyMethodDef QuantucciaMethods[] = {
{"united_kingdom_is_business_day", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef quantuccia_module_def = {
PyModuleDef_HEAD_INIT,
"quantuccia",
NULL,
-1,
QuantucciaMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_quantuccia(void){
PyObject *m;
m = PyModule_Create(&quantuccia_module_def);
return m;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Debug/MemoryLeakTracker.hpp>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <stdexcept>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <windows.h>
#elif defined(NAZARA_PLATFORM_POSIX)
#include <pthread.h>
#endif
namespace
{
struct Block
{
std::size_t size;
const char* file;
Block* prev;
Block* next;
bool array;
unsigned int line;
unsigned int magic;
};
bool initialized = false;
const unsigned int magic = 0x51429EE;
const char* MLTFileName = "NazaraLeaks.log";
const char* nextFreeFile = "Internal error";
unsigned int nextFreeLine = 0;
Block ptrList =
{
0,
nullptr,
&ptrList,
&ptrList,
false,
0,
magic
};
#if defined(NAZARA_PLATFORM_WINDOWS)
CRITICAL_SECTION mutex;
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
}
NzMemoryManager::NzMemoryManager()
{
}
NzMemoryManager::~NzMemoryManager()
{
Uninitialize();
}
void* NzMemoryManager::Allocate(std::size_t size, bool multi, const char* file, unsigned int line)
{
if (!initialized)
Initialize();
#if defined(NAZARA_PLATFORM_WINDOWS)
EnterCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_lock(&mutex);
#endif
Block* ptr = reinterpret_cast<Block*>(std::malloc(size+sizeof(Block)));
if (!ptr)
{
// Pas d'information de temps (Car nécessitant une allocation)
FILE* log = std::fopen(MLTFileName, "a");
std::fprintf(log, "Failed to allocate memory (%d bytes)\n", size);
std::fclose(log);
return nullptr; // Impossible d'envoyer une exception car cela allouerait de la mémoire avec new (boucle infinie)
}
ptr->array = multi;
ptr->file = file;
ptr->line = line;
ptr->size = size;
ptr->magic = magic;
ptr->prev = ptrList.prev;
ptr->next = &ptrList;
ptrList.prev->next = ptr;
ptrList.prev = ptr;
#if defined(NAZARA_PLATFORM_WINDOWS)
LeaveCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_unlock(&mutex);
#endif
return reinterpret_cast<char*>(ptr)+sizeof(Block);
}
void NzMemoryManager::Free(void* pointer, bool multi)
{
if (!pointer)
return;
Block* ptr = reinterpret_cast<Block*>(reinterpret_cast<char*>(pointer)-sizeof(Block));
if (ptr->magic != magic)
return;
#if defined(NAZARA_PLATFORM_WINDOWS)
EnterCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_lock(&mutex);
#endif
if (ptr->array != multi)
{
char* time = TimeInfo();
FILE* log = std::fopen(MLTFileName, "a");
if (nextFreeFile)
{
if (multi)
std::fprintf(log, "%s Warning: delete[] after new at %s:%d\n", time, nextFreeFile, nextFreeLine);
else
std::fprintf(log, "%s Warning: delete after new[] at %s:%d\n", time, nextFreeFile, nextFreeLine);
}
else
{
if (multi)
std::fprintf(log, "%s Warning: delete[] after new at unknown position\n", time);
else
std::fprintf(log, "%s Warning: delete after new[] at unknown position\n", time);
}
std::fclose(log);
std::free(time);
}
ptr->magic = 0;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
std::free(ptr);
nextFreeFile = nullptr;
nextFreeLine = 0;
#if defined(NAZARA_PLATFORM_WINDOWS)
LeaveCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_unlock(&mutex);
#endif
}
void NzMemoryManager::NextFree(const char* file, unsigned int line)
{
nextFreeFile = file;
nextFreeLine = line;
}
void NzMemoryManager::Initialize()
{
char* time = TimeInfo();
FILE* file = std::fopen(MLTFileName, "w");
std::fprintf(file, "%s ==============================\n", time);
std::fprintf(file, "%s Nazara Memory Leak Tracker \n", time);
std::fprintf(file, "%s ==============================\n", time);
std::fclose(file);
std::free(time);
if (std::atexit(Uninitialize) != 0)
{
static NzMemoryManager manager;
}
#ifdef NAZARA_PLATFORM_WINDOWS
InitializeCriticalSection(&mutex);
#endif
initialized = true;
}
char* NzMemoryManager::TimeInfo()
{
char* buffer = reinterpret_cast<char*>(std::malloc(23*sizeof(char)));
time_t currentTime = std::time(nullptr);
std::strftime(buffer, 23, "%d/%m/%Y - %H:%M:%S:", std::localtime(¤tTime));
return buffer;
}
void NzMemoryManager::Uninitialize()
{
#ifdef NAZARA_PLATFORM_WINDOWS
DeleteCriticalSection(&mutex);
#endif
FILE* log = std::fopen(MLTFileName, "a");
char* time = TimeInfo();
std::fprintf(log, "%s Application finished, checking leaks...\n", time);
if (ptrList.next == &ptrList)
{
std::fprintf(log, "%s ==============================\n", time);
std::fprintf(log, "%s No leak detected \n", time);
std::fprintf(log, "%s ==============================", time);
}
else
{
std::fprintf(log, "%s ==============================\n", time);
std::fprintf(log, "%s Leaks have been detected \n", time);
std::fprintf(log, "%s ==============================\n\n", time);
std::fputs("Leak list:\n", log);
Block* ptr = ptrList.next;
unsigned int count = 0;
unsigned int totalSize = 0;
while (ptr != &ptrList)
{
count++;
totalSize += ptr->size;
if (ptr->file)
std::fprintf(log, "-0x%p -> %d bytes allocated at %s:%d\n", reinterpret_cast<char*>(ptr)+sizeof(Block), ptr->size, ptr->file, ptr->line);
else
std::fprintf(log, "-0x%p -> %d bytes allocated at unknown position\n", reinterpret_cast<char*>(ptr)+sizeof(Block), ptr->size);
void* pointer = ptr;
ptr = ptr->next;
std::free(pointer);
}
std::fprintf(log, "\n%d blocks leaked (%d bytes)", count, totalSize);
}
std::free(time);
std::fclose(log);
}
void* operator new(std::size_t size, const char* file, unsigned int line)
{
return NzMemoryManager::Allocate(size, false, file, line);
}
void* operator new[](std::size_t size, const char* file, unsigned int line)
{
return NzMemoryManager::Allocate(size, true, file, line);
}
void operator delete(void* ptr, const char* file, unsigned int line) throw()
{
NzMemoryManager::NextFree(file, line);
NzMemoryManager::Free(ptr, false);
}
void operator delete[](void* ptr, const char* file, unsigned int line) throw()
{
NzMemoryManager::NextFree(file, line);
NzMemoryManager::Free(ptr, true);
}
<commit_msg>Fixed fprintf specifiers<commit_after>// Copyright (C) 2012 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Debug/MemoryLeakTracker.hpp>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <stdexcept>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <windows.h>
#elif defined(NAZARA_PLATFORM_POSIX)
#include <pthread.h>
#endif
namespace
{
struct Block
{
std::size_t size;
const char* file;
Block* prev;
Block* next;
bool array;
unsigned int line;
unsigned int magic;
};
bool initialized = false;
const unsigned int magic = 0x51429EE;
const char* MLTFileName = "NazaraLeaks.log";
const char* nextFreeFile = "Internal error";
unsigned int nextFreeLine = 0;
Block ptrList =
{
0,
nullptr,
&ptrList,
&ptrList,
false,
0,
magic
};
#if defined(NAZARA_PLATFORM_WINDOWS)
CRITICAL_SECTION mutex;
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
}
NzMemoryManager::NzMemoryManager()
{
}
NzMemoryManager::~NzMemoryManager()
{
Uninitialize();
}
void* NzMemoryManager::Allocate(std::size_t size, bool multi, const char* file, unsigned int line)
{
if (!initialized)
Initialize();
#if defined(NAZARA_PLATFORM_WINDOWS)
EnterCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_lock(&mutex);
#endif
Block* ptr = reinterpret_cast<Block*>(std::malloc(size+sizeof(Block)));
if (!ptr)
{
// Pas d'information de temps (Car nécessitant une allocation)
FILE* log = std::fopen(MLTFileName, "a");
std::fprintf(log, "Failed to allocate memory (%zu bytes)\n", size);
std::fclose(log);
return nullptr; // Impossible d'envoyer une exception car cela allouerait de la mémoire avec new (boucle infinie)
}
ptr->array = multi;
ptr->file = file;
ptr->line = line;
ptr->size = size;
ptr->magic = magic;
ptr->prev = ptrList.prev;
ptr->next = &ptrList;
ptrList.prev->next = ptr;
ptrList.prev = ptr;
#if defined(NAZARA_PLATFORM_WINDOWS)
LeaveCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_unlock(&mutex);
#endif
return reinterpret_cast<char*>(ptr)+sizeof(Block);
}
void NzMemoryManager::Free(void* pointer, bool multi)
{
if (!pointer)
return;
Block* ptr = reinterpret_cast<Block*>(reinterpret_cast<char*>(pointer)-sizeof(Block));
if (ptr->magic != magic)
return;
#if defined(NAZARA_PLATFORM_WINDOWS)
EnterCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_lock(&mutex);
#endif
if (ptr->array != multi)
{
char* time = TimeInfo();
FILE* log = std::fopen(MLTFileName, "a");
if (nextFreeFile)
{
if (multi)
std::fprintf(log, "%s Warning: delete[] after new at %s:%u\n", time, nextFreeFile, nextFreeLine);
else
std::fprintf(log, "%s Warning: delete after new[] at %s:%u\n", time, nextFreeFile, nextFreeLine);
}
else
{
if (multi)
std::fprintf(log, "%s Warning: delete[] after new at unknown position\n", time);
else
std::fprintf(log, "%s Warning: delete after new[] at unknown position\n", time);
}
std::fclose(log);
std::free(time);
}
ptr->magic = 0;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
std::free(ptr);
nextFreeFile = nullptr;
nextFreeLine = 0;
#if defined(NAZARA_PLATFORM_WINDOWS)
LeaveCriticalSection(&mutex);
#elif defined(NAZARA_PLATFORM_POSIX)
pthread_mutex_unlock(&mutex);
#endif
}
void NzMemoryManager::NextFree(const char* file, unsigned int line)
{
nextFreeFile = file;
nextFreeLine = line;
}
void NzMemoryManager::Initialize()
{
char* time = TimeInfo();
FILE* file = std::fopen(MLTFileName, "w");
std::fprintf(file, "%s ==============================\n", time);
std::fprintf(file, "%s Nazara Memory Leak Tracker \n", time);
std::fprintf(file, "%s ==============================\n", time);
std::fclose(file);
std::free(time);
if (std::atexit(Uninitialize) != 0)
{
static NzMemoryManager manager;
}
#ifdef NAZARA_PLATFORM_WINDOWS
InitializeCriticalSection(&mutex);
#endif
initialized = true;
}
char* NzMemoryManager::TimeInfo()
{
char* buffer = reinterpret_cast<char*>(std::malloc(23*sizeof(char)));
time_t currentTime = std::time(nullptr);
std::strftime(buffer, 23, "%d/%m/%Y - %H:%M:%S:", std::localtime(¤tTime));
return buffer;
}
void NzMemoryManager::Uninitialize()
{
#ifdef NAZARA_PLATFORM_WINDOWS
DeleteCriticalSection(&mutex);
#endif
FILE* log = std::fopen(MLTFileName, "a");
char* time = TimeInfo();
std::fprintf(log, "%s Application finished, checking leaks...\n", time);
if (ptrList.next == &ptrList)
{
std::fprintf(log, "%s ==============================\n", time);
std::fprintf(log, "%s No leak detected \n", time);
std::fprintf(log, "%s ==============================", time);
}
else
{
std::fprintf(log, "%s ==============================\n", time);
std::fprintf(log, "%s Leaks have been detected \n", time);
std::fprintf(log, "%s ==============================\n\n", time);
std::fputs("Leak list:\n", log);
Block* ptr = ptrList.next;
unsigned int count = 0;
unsigned int totalSize = 0;
while (ptr != &ptrList)
{
count++;
totalSize += ptr->size;
if (ptr->file)
std::fprintf(log, "-0x%p -> %zu bytes allocated at %s:%u\n", reinterpret_cast<char*>(ptr)+sizeof(Block), ptr->size, ptr->file, ptr->line);
else
std::fprintf(log, "-0x%p -> %zu bytes allocated at unknown position\n", reinterpret_cast<char*>(ptr)+sizeof(Block), ptr->size);
void* pointer = ptr;
ptr = ptr->next;
std::free(pointer);
}
std::fprintf(log, "\n%u blocks leaked (%u bytes)", count, totalSize);
}
std::free(time);
std::fclose(log);
}
void* operator new(std::size_t size, const char* file, unsigned int line)
{
return NzMemoryManager::Allocate(size, false, file, line);
}
void* operator new[](std::size_t size, const char* file, unsigned int line)
{
return NzMemoryManager::Allocate(size, true, file, line);
}
void operator delete(void* ptr, const char* file, unsigned int line) throw()
{
NzMemoryManager::NextFree(file, line);
NzMemoryManager::Free(ptr, false);
}
void operator delete[](void* ptr, const char* file, unsigned int line) throw()
{
NzMemoryManager::NextFree(file, line);
NzMemoryManager::Free(ptr, true);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Matthias Fuchs
*
* 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 <stromx/runtime/Version.h>
#include <boost/python.hpp>
using namespace boost::python;
using namespace stromx::runtime;
void exportVersion()
{
class_<Version>("Version", no_init)
.def("major", &Version::major)
.def("minor", &Version::minor)
.def("revision", &Version::revision)
;
}<commit_msg>Undefine major, minor in python wrappers<commit_after>/*
* Copyright 2011 Matthias Fuchs
*
* 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 <boost/python.hpp>
#undef major
#undef minor
#include <stromx/runtime/Version.h>
using namespace boost::python;
using namespace stromx::runtime;
void exportVersion()
{
class_<Version>("Version", no_init)
.def("major", &Version::major)
.def("minor", &Version::minor)
.def("revision", &Version::revision)
;
}<|endoftext|> |
<commit_before>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "VTKViewer_FramedTextActor.h"
#include <vtkCellArray.h>
#include <vtkObjectFactory.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkProperty2D.h>
#include <vtkRenderer.h>
#include <vtkTextActor.h>
#include <vtkTextMapper.h>
#include <vtkTextProperty.h>
#include <vtkTimeStamp.h>
#include <vtkViewport.h>
#include <vtkWindow.h>
#include <QStringList>
#define TEXT_MARGIN 4
#define OFFSET_SPACING 2
//VSR: uncomment below macro to support unicode text properly in SALOME
// current commented out due to regressions
//#define PAL22528_UNICODE
namespace
{
QString fromUtf8( const char* txt )
{
#ifdef PAL22528_UNICODE
return QString::fromUtf8( txt );
#else
return QString( txt );
#endif
}
const char* toUtf8( const QString& txt )
{
#ifdef PAL22528_UNICODE
return txt.toUtf8().constData();
#else
return txt.toLatin1().constData();
#endif
}
}
//==================================================================
vtkStandardNewMacro(VTKViewer_FramedTextActor);
//==================================================================
// function : VTKViewer_FramedTextActor
// purpose :
//==================================================================
VTKViewer_FramedTextActor::VTKViewer_FramedTextActor()
{
PositionCoordinate->SetCoordinateSystemToNormalizedViewport();
myTransparency=0.;
myBar = vtkPolyData::New();
myBarMapper = vtkPolyDataMapper2D::New();
myBarMapper->SetInputData(myBar);
myBarActor = vtkActor2D::New();
myBarActor->SetMapper(myBarMapper);
myBarActor->GetProperty()->SetOpacity(1.-myTransparency);
myBarActor->GetProperty()->SetColor(.5, .5, .5);
myTextProperty = vtkTextProperty::New();
myTextProperty->SetFontSize(12);
myTextProperty->SetBold(0);
myTextProperty->SetItalic(0);
myTextProperty->SetShadow(1);
myTextProperty->SetFontFamilyToArial();
myTextActor=vtkTextActor::New();
myTextActor->SetTextProperty(myTextProperty);
myBarActor->SetVisibility(1);
myTextActor->SetVisibility(1);
myBarActor->SetPickable(0);
myTextActor->SetPickable(0);
myModePosition = BelowPoint;
myLayoutType = Vertical;
for(int i=0; i<4; i++) {
myWorldPoint[i] = 0.;
}
myDistance=10.;
myTextMargin = TEXT_MARGIN;
myHorizontalOffset = 0;
myVerticalOffset = 0;
myMoveFrameFlag = 0;
}
//==================================================================
// function : ~
// purpose :
//==================================================================
VTKViewer_FramedTextActor::~VTKViewer_FramedTextActor()
{
myTextActor->Delete();
myTextProperty->Delete();
myBarActor->Delete();
myBarMapper->Delete();
myBar->Delete();
}
//==================================================================
// function : SetVisibility
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetVisibility (int theVisibility)
{
myBarActor->SetVisibility(theVisibility);
myTextActor->SetVisibility(theVisibility);
}
//==================================================================
// function : GetVisibility
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetVisibility()
{
return myBarActor->GetVisibility();
}
//==================================================================
// function : SetPickable
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetPickable (int thePickability)
{
myBarActor->SetPickable(thePickability);
myTextActor->SetPickable(thePickability);
}
//==================================================================
// function : GetPickable
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetPickable()
{
return myBarActor->GetPickable();
}
//==================================================================
// function : GetSize
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetSize(vtkRenderer* vport, double theSize[2]) const
{
myTextActor->GetSize(vport, theSize);
theSize[0] = theSize[0] + 2 * GetTextMargin() + OFFSET_SPACING;
theSize[1] = theSize[1] + 2 * GetTextMargin() + OFFSET_SPACING;
}
//==================================================================
// function : SetForegroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetForegroundColor(const double r,
const double g,
const double b)
{
myTextProperty->SetColor(r, g, b);
myTextActor->GetTextProperty()->ShallowCopy(myTextProperty);
Modified();
}
//==================================================================
// function : GetForegroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetForegroundColor(double& r,
double& g,
double& b)
{
double aColor[3];
myTextProperty->GetColor(aColor);
r = aColor[0];
g = aColor[1];
b = aColor[2];
}
//==================================================================
// function : SetBackgroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetBackgroundColor(const double r,
const double g,
const double b)
{
myBarActor->GetProperty()->SetColor(r, g, b);
Modified();
}
//==================================================================
// function : GetBackgroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetBackgroundColor(double& r,
double& g,
double& b)
{
double aColor[3];
myBarActor->GetProperty()->GetColor(aColor);
r = aColor[0];
g = aColor[1];
b = aColor[2];
}
//==================================================================
// function : SetTransparency
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetTransparency(const double theTransparency)
{
if (theTransparency>=0. && theTransparency<=1.){
myTransparency=theTransparency;
myBarActor->GetProperty()->SetOpacity(1.-myTransparency);
Modified();
}
}
//==================================================================
// function : GetTransparency
// purpose :
//==================================================================
double VTKViewer_FramedTextActor::GetTransparency()const
{
return myTransparency;
}
//==================================================================
// function : SetTextMargin
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetTextMargin(const int theMargin)
{
if( theMargin >= 0 ) {
myTextMargin = theMargin;
Modified();
}
}
//==================================================================
// function : GetTextMargin
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetTextMargin() const
{
return myTextMargin;
}
//==================================================================
// function : SetOffset
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetOffset(const double theOffset[2])
{
myHorizontalOffset = theOffset[0];
myVerticalOffset = theOffset[1];
Modified();
}
//==================================================================
// function : SetText
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetText(const char* theText)
{
// remove whitespaces from from the start and the end
// additionally, consider a case of multi-string text
QString aString(fromUtf8(theText));
QStringList aTrimmedStringList;
QStringList aStringList = aString.split("\n");
QStringListIterator anIter(aStringList);
while(anIter.hasNext())
aTrimmedStringList.append(anIter.next().trimmed());
myTextActor->SetInput(toUtf8(aTrimmedStringList.join("\n")));
Modified();
}
//==================================================================
// function : GetText
// purpose :
//==================================================================
char* VTKViewer_FramedTextActor::GetText()
{
return myTextActor->GetInput();
}
//==================================================================
// function : SetModePosition
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetModePosition(const int theMode)
{
myModePosition = theMode;
Modified();
}
//==================================================================
// function : GetModePosition
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetModePosition()const
{
return myModePosition;
}
//==================================================================
// function : SetLayoutType
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetLayoutType(const int theType)
{
myLayoutType = theType;
Modified();
}
//==================================================================
// function : GetLayoutType
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetLayoutType() const
{
return myLayoutType;
}
//==================================================================
// function : SetWorldPoint
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetWorldPoint(const double theWorldPoint[4])
{
for(int i = 0; i<4; ++i) {
myWorldPoint[i] = theWorldPoint[i];
}
Modified();
}
//==================================================================
// function : GetWorldPoint
// purpose :
//==================================================================
const double* VTKViewer_FramedTextActor::GetWorldPoint()const
{
return myWorldPoint;
}
//==================================================================
// function : SetDistance
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetDistance(const double theDistance)
{
myDistance=theDistance;
}
//==================================================================
// function : GetDistance
// purpose :
//==================================================================
double VTKViewer_FramedTextActor::GetDistance()const
{
return myDistance;
}
//==================================================================
// function : SetMoveFrameFlag
// purpose : If moveFrameFlag is true, then frame with text is moved
// under world point
//==================================================================
void VTKViewer_FramedTextActor::SetMoveFrameFlag(const int theMoveFrameFlag)
{
if(myMoveFrameFlag != theMoveFrameFlag) {
myMoveFrameFlag = theMoveFrameFlag;
Modified();
}
}
//==================================================================
// function : GetDistance
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetMoveFrameFlag() const
{
return myMoveFrameFlag;
}
//==================================================================
// function : ReleaseGraphicsResources
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::ReleaseGraphicsResources(vtkWindow *win)
{
myTextActor->ReleaseGraphicsResources(win);
myBarActor->ReleaseGraphicsResources(win);
}
//==================================================================
// function : RenderOverlay
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::RenderOverlay(vtkViewport *viewport)
{
int renderedSomething = 0;
renderedSomething +=myTextActor->RenderOverlay(viewport);
renderedSomething +=myBarActor->RenderOverlay(viewport);
return renderedSomething;
}
//==================================================================
// function : RenderOpaqueGeometry
// purpose :
//==================================================================
int
VTKViewer_FramedTextActor
::RenderOpaqueGeometry(vtkViewport *theViewport)
{
int anIsRenderedSomething = 0;
int* aViewportSize = theViewport->GetSize();
int aViewPortWidth = aViewportSize[0];
int aViewPortHeight = aViewportSize[1];
if(aViewPortWidth == 1 || aViewPortHeight == 1)
return anIsRenderedSomething;
if(!myTextActor->GetInput())
return anIsRenderedSomething;
myBar->Initialize();
int aNbPoints = 4;
vtkPoints *aPoints = vtkPoints::New();
aPoints->SetNumberOfPoints(aNbPoints);
myBar->SetPoints(aPoints);
aPoints->Delete();
vtkCellArray *aPolys = vtkCellArray::New();
aPolys->Allocate(aPolys->EstimateSize(1,4));
vtkIdType aPointsIds[4] = {0, 1, 3, 2};
aPolys->InsertNextCell(4,aPointsIds);
myBar->SetPolys(aPolys);
aPolys->Delete();
double aTextSize[2];
myTextActor->GetSize(theViewport, aTextSize);
int aBarWidth = aTextSize[0];
int aBarHeight = aTextSize[1];
int aTextMargin = GetTextMargin();
double xMin = 0.0;
double xMax = 0.0;
double yMin = -aBarHeight/2 - aTextMargin;
double yMax = aBarHeight/2 + aTextMargin;
int aHorizontalOffset = GetLayoutType() == Horizontal ? myHorizontalOffset : 0;
int aVerticalOffset = GetLayoutType() == Vertical ? myVerticalOffset : 0;
if( myModePosition == BelowPoint )
{
theViewport->SetWorldPoint(myWorldPoint);
theViewport->WorldToDisplay();
double aSelectionPoint[3];
theViewport->GetDisplayPoint(aSelectionPoint);
double u = aSelectionPoint[0];
double v = aSelectionPoint[1] - myDistance;
if(myMoveFrameFlag)
v -= aBarHeight/2.;
theViewport->ViewportToNormalizedViewport(u, v);
PositionCoordinate->SetValue(u, v);
myTextProperty->SetJustificationToCentered();
xMin = -aBarWidth/2 - aTextMargin;
xMax = aBarWidth/2 + aTextMargin;
}
else // except BelowPoint, only TopLeft and TopRight modes are supported at this moment
{
double x = 0, xOffset = aHorizontalOffset + aTextMargin + OFFSET_SPACING;
double y = 0, yOffset = aVerticalOffset + aTextMargin + OFFSET_SPACING;
if( myModePosition == TopLeft )
{
x = xOffset;
y = aViewPortHeight - yOffset - aBarHeight/2;
myTextProperty->SetJustificationToLeft();
xMin = - aTextMargin;
xMax = aBarWidth + aTextMargin;
}
else if( myModePosition == TopRight )
{
x = aViewPortWidth - xOffset;
y = aViewPortHeight - yOffset - aBarHeight/2;
myTextProperty->SetJustificationToRight();
xMin = -aBarWidth - aTextMargin;
xMax = aTextMargin;
}
PositionCoordinate->SetValue(x / (double)aViewPortWidth,
y / (double)aViewPortHeight);
}
aPoints->SetPoint(0, xMin, yMax, 0.0);
aPoints->SetPoint(1, xMin, yMin, 0.0);
aPoints->SetPoint(2, xMax, yMax, 0.0);
aPoints->SetPoint(3, xMax, yMin, 0.0);
myTextProperty->SetVerticalJustificationToCentered();
myBarActor ->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate);
myTextActor->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate);
myBuildTime.Modified();
return anIsRenderedSomething;
}
<commit_msg>Fix bug: function toUtf8() returns pointer to the temporarily allocated data<commit_after>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "VTKViewer_FramedTextActor.h"
#include <vtkCellArray.h>
#include <vtkObjectFactory.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkProperty2D.h>
#include <vtkRenderer.h>
#include <vtkTextActor.h>
#include <vtkTextMapper.h>
#include <vtkTextProperty.h>
#include <vtkTimeStamp.h>
#include <vtkViewport.h>
#include <vtkWindow.h>
#include <QStringList>
#define TEXT_MARGIN 4
#define OFFSET_SPACING 2
//VSR: uncomment below macro to support unicode text properly in SALOME
// current commented out due to regressions
//#define PAL22528_UNICODE
namespace
{
QString fromUtf8( const char* txt )
{
#ifdef PAL22528_UNICODE
return QString::fromUtf8( txt );
#else
return QString( txt );
#endif
}
std::string toUtf8( const QString& txt )
{
#ifdef PAL22528_UNICODE
return txt.toUtf8().constData();
#else
return txt.toLatin1().constData();
#endif
}
}
//==================================================================
vtkStandardNewMacro(VTKViewer_FramedTextActor);
//==================================================================
// function : VTKViewer_FramedTextActor
// purpose :
//==================================================================
VTKViewer_FramedTextActor::VTKViewer_FramedTextActor()
{
PositionCoordinate->SetCoordinateSystemToNormalizedViewport();
myTransparency=0.;
myBar = vtkPolyData::New();
myBarMapper = vtkPolyDataMapper2D::New();
myBarMapper->SetInputData(myBar);
myBarActor = vtkActor2D::New();
myBarActor->SetMapper(myBarMapper);
myBarActor->GetProperty()->SetOpacity(1.-myTransparency);
myBarActor->GetProperty()->SetColor(.5, .5, .5);
myTextProperty = vtkTextProperty::New();
myTextProperty->SetFontSize(12);
myTextProperty->SetBold(0);
myTextProperty->SetItalic(0);
myTextProperty->SetShadow(1);
myTextProperty->SetFontFamilyToArial();
myTextActor=vtkTextActor::New();
myTextActor->SetTextProperty(myTextProperty);
myBarActor->SetVisibility(1);
myTextActor->SetVisibility(1);
myBarActor->SetPickable(0);
myTextActor->SetPickable(0);
myModePosition = BelowPoint;
myLayoutType = Vertical;
for(int i=0; i<4; i++) {
myWorldPoint[i] = 0.;
}
myDistance=10.;
myTextMargin = TEXT_MARGIN;
myHorizontalOffset = 0;
myVerticalOffset = 0;
myMoveFrameFlag = 0;
}
//==================================================================
// function : ~
// purpose :
//==================================================================
VTKViewer_FramedTextActor::~VTKViewer_FramedTextActor()
{
myTextActor->Delete();
myTextProperty->Delete();
myBarActor->Delete();
myBarMapper->Delete();
myBar->Delete();
}
//==================================================================
// function : SetVisibility
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetVisibility (int theVisibility)
{
myBarActor->SetVisibility(theVisibility);
myTextActor->SetVisibility(theVisibility);
}
//==================================================================
// function : GetVisibility
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetVisibility()
{
return myBarActor->GetVisibility();
}
//==================================================================
// function : SetPickable
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetPickable (int thePickability)
{
myBarActor->SetPickable(thePickability);
myTextActor->SetPickable(thePickability);
}
//==================================================================
// function : GetPickable
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetPickable()
{
return myBarActor->GetPickable();
}
//==================================================================
// function : GetSize
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetSize(vtkRenderer* vport, double theSize[2]) const
{
myTextActor->GetSize(vport, theSize);
theSize[0] = theSize[0] + 2 * GetTextMargin() + OFFSET_SPACING;
theSize[1] = theSize[1] + 2 * GetTextMargin() + OFFSET_SPACING;
}
//==================================================================
// function : SetForegroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetForegroundColor(const double r,
const double g,
const double b)
{
myTextProperty->SetColor(r, g, b);
myTextActor->GetTextProperty()->ShallowCopy(myTextProperty);
Modified();
}
//==================================================================
// function : GetForegroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetForegroundColor(double& r,
double& g,
double& b)
{
double aColor[3];
myTextProperty->GetColor(aColor);
r = aColor[0];
g = aColor[1];
b = aColor[2];
}
//==================================================================
// function : SetBackgroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetBackgroundColor(const double r,
const double g,
const double b)
{
myBarActor->GetProperty()->SetColor(r, g, b);
Modified();
}
//==================================================================
// function : GetBackgroundColor
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::GetBackgroundColor(double& r,
double& g,
double& b)
{
double aColor[3];
myBarActor->GetProperty()->GetColor(aColor);
r = aColor[0];
g = aColor[1];
b = aColor[2];
}
//==================================================================
// function : SetTransparency
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetTransparency(const double theTransparency)
{
if (theTransparency>=0. && theTransparency<=1.){
myTransparency=theTransparency;
myBarActor->GetProperty()->SetOpacity(1.-myTransparency);
Modified();
}
}
//==================================================================
// function : GetTransparency
// purpose :
//==================================================================
double VTKViewer_FramedTextActor::GetTransparency()const
{
return myTransparency;
}
//==================================================================
// function : SetTextMargin
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetTextMargin(const int theMargin)
{
if( theMargin >= 0 ) {
myTextMargin = theMargin;
Modified();
}
}
//==================================================================
// function : GetTextMargin
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetTextMargin() const
{
return myTextMargin;
}
//==================================================================
// function : SetOffset
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetOffset(const double theOffset[2])
{
myHorizontalOffset = theOffset[0];
myVerticalOffset = theOffset[1];
Modified();
}
//==================================================================
// function : SetText
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetText(const char* theText)
{
// remove whitespaces from from the start and the end
// additionally, consider a case of multi-string text
QString aString(fromUtf8(theText));
QStringList aTrimmedStringList;
QStringList aStringList = aString.split("\n");
QStringListIterator anIter(aStringList);
while(anIter.hasNext())
aTrimmedStringList.append(anIter.next().trimmed());
myTextActor->SetInput(toUtf8(aTrimmedStringList.join("\n")).c_str());
Modified();
}
//==================================================================
// function : GetText
// purpose :
//==================================================================
char* VTKViewer_FramedTextActor::GetText()
{
return myTextActor->GetInput();
}
//==================================================================
// function : SetModePosition
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetModePosition(const int theMode)
{
myModePosition = theMode;
Modified();
}
//==================================================================
// function : GetModePosition
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetModePosition()const
{
return myModePosition;
}
//==================================================================
// function : SetLayoutType
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetLayoutType(const int theType)
{
myLayoutType = theType;
Modified();
}
//==================================================================
// function : GetLayoutType
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetLayoutType() const
{
return myLayoutType;
}
//==================================================================
// function : SetWorldPoint
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetWorldPoint(const double theWorldPoint[4])
{
for(int i = 0; i<4; ++i) {
myWorldPoint[i] = theWorldPoint[i];
}
Modified();
}
//==================================================================
// function : GetWorldPoint
// purpose :
//==================================================================
const double* VTKViewer_FramedTextActor::GetWorldPoint()const
{
return myWorldPoint;
}
//==================================================================
// function : SetDistance
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::SetDistance(const double theDistance)
{
myDistance=theDistance;
}
//==================================================================
// function : GetDistance
// purpose :
//==================================================================
double VTKViewer_FramedTextActor::GetDistance()const
{
return myDistance;
}
//==================================================================
// function : SetMoveFrameFlag
// purpose : If moveFrameFlag is true, then frame with text is moved
// under world point
//==================================================================
void VTKViewer_FramedTextActor::SetMoveFrameFlag(const int theMoveFrameFlag)
{
if(myMoveFrameFlag != theMoveFrameFlag) {
myMoveFrameFlag = theMoveFrameFlag;
Modified();
}
}
//==================================================================
// function : GetDistance
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::GetMoveFrameFlag() const
{
return myMoveFrameFlag;
}
//==================================================================
// function : ReleaseGraphicsResources
// purpose :
//==================================================================
void VTKViewer_FramedTextActor::ReleaseGraphicsResources(vtkWindow *win)
{
myTextActor->ReleaseGraphicsResources(win);
myBarActor->ReleaseGraphicsResources(win);
}
//==================================================================
// function : RenderOverlay
// purpose :
//==================================================================
int VTKViewer_FramedTextActor::RenderOverlay(vtkViewport *viewport)
{
int renderedSomething = 0;
renderedSomething +=myTextActor->RenderOverlay(viewport);
renderedSomething +=myBarActor->RenderOverlay(viewport);
return renderedSomething;
}
//==================================================================
// function : RenderOpaqueGeometry
// purpose :
//==================================================================
int
VTKViewer_FramedTextActor
::RenderOpaqueGeometry(vtkViewport *theViewport)
{
int anIsRenderedSomething = 0;
int* aViewportSize = theViewport->GetSize();
int aViewPortWidth = aViewportSize[0];
int aViewPortHeight = aViewportSize[1];
if(aViewPortWidth == 1 || aViewPortHeight == 1)
return anIsRenderedSomething;
if(!myTextActor->GetInput())
return anIsRenderedSomething;
myBar->Initialize();
int aNbPoints = 4;
vtkPoints *aPoints = vtkPoints::New();
aPoints->SetNumberOfPoints(aNbPoints);
myBar->SetPoints(aPoints);
aPoints->Delete();
vtkCellArray *aPolys = vtkCellArray::New();
aPolys->Allocate(aPolys->EstimateSize(1,4));
vtkIdType aPointsIds[4] = {0, 1, 3, 2};
aPolys->InsertNextCell(4,aPointsIds);
myBar->SetPolys(aPolys);
aPolys->Delete();
double aTextSize[2];
myTextActor->GetSize(theViewport, aTextSize);
int aBarWidth = aTextSize[0];
int aBarHeight = aTextSize[1];
int aTextMargin = GetTextMargin();
double xMin = 0.0;
double xMax = 0.0;
double yMin = -aBarHeight/2 - aTextMargin;
double yMax = aBarHeight/2 + aTextMargin;
int aHorizontalOffset = GetLayoutType() == Horizontal ? myHorizontalOffset : 0;
int aVerticalOffset = GetLayoutType() == Vertical ? myVerticalOffset : 0;
if( myModePosition == BelowPoint )
{
theViewport->SetWorldPoint(myWorldPoint);
theViewport->WorldToDisplay();
double aSelectionPoint[3];
theViewport->GetDisplayPoint(aSelectionPoint);
double u = aSelectionPoint[0];
double v = aSelectionPoint[1] - myDistance;
if(myMoveFrameFlag)
v -= aBarHeight/2.;
theViewport->ViewportToNormalizedViewport(u, v);
PositionCoordinate->SetValue(u, v);
myTextProperty->SetJustificationToCentered();
xMin = -aBarWidth/2 - aTextMargin;
xMax = aBarWidth/2 + aTextMargin;
}
else // except BelowPoint, only TopLeft and TopRight modes are supported at this moment
{
double x = 0, xOffset = aHorizontalOffset + aTextMargin + OFFSET_SPACING;
double y = 0, yOffset = aVerticalOffset + aTextMargin + OFFSET_SPACING;
if( myModePosition == TopLeft )
{
x = xOffset;
y = aViewPortHeight - yOffset - aBarHeight/2;
myTextProperty->SetJustificationToLeft();
xMin = - aTextMargin;
xMax = aBarWidth + aTextMargin;
}
else if( myModePosition == TopRight )
{
x = aViewPortWidth - xOffset;
y = aViewPortHeight - yOffset - aBarHeight/2;
myTextProperty->SetJustificationToRight();
xMin = -aBarWidth - aTextMargin;
xMax = aTextMargin;
}
PositionCoordinate->SetValue(x / (double)aViewPortWidth,
y / (double)aViewPortHeight);
}
aPoints->SetPoint(0, xMin, yMax, 0.0);
aPoints->SetPoint(1, xMin, yMin, 0.0);
aPoints->SetPoint(2, xMax, yMax, 0.0);
aPoints->SetPoint(3, xMax, yMin, 0.0);
myTextProperty->SetVerticalJustificationToCentered();
myBarActor ->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate);
myTextActor->GetPositionCoordinate()->SetReferenceCoordinate(PositionCoordinate);
myBuildTime.Modified();
return anIsRenderedSomething;
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <kernel/sort_by_key.hpp>
#include <kernel/sort_helper.hpp>
#include <Array.hpp>
#include <math.hpp>
#include <algorithm>
#include <numeric>
#include <queue>
#include <err_cpu.hpp>
#include <functional>
namespace cpu
{
namespace kernel
{
template<typename Tk, typename Tv, bool isAscending>
void sort0ByKeyIterative(Array<Tk> okey, Array<Tv> oval)
{
// Get pointers and initialize original index locations
Tk *okey_ptr = okey.get();
Tv *oval_ptr = oval.get();
std::vector<IndexPair<Tk, Tv> > pairKeyVal(okey.dims()[0]);
for(dim_t w = 0; w < okey.dims()[3]; w++) {
dim_t okeyW = w * okey.strides()[3];
dim_t ovalW = w * oval.strides()[3];
for(dim_t z = 0; z < okey.dims()[2]; z++) {
dim_t okeyWZ = okeyW + z * okey.strides()[2];
dim_t ovalWZ = ovalW + z * oval.strides()[2];
for(dim_t y = 0; y < okey.dims()[1]; y++) {
dim_t okeyOffset = okeyWZ + y * okey.strides()[1];
dim_t ovalOffset = ovalWZ + y * oval.strides()[1];
Tk *okey_col_ptr = okey_ptr + okeyOffset;
Tv *oval_col_ptr = oval_ptr + ovalOffset;
for(dim_t x = 0; x < (dim_t)pairKeyVal.size(); x++) {
pairKeyVal[x] = std::make_tuple(okey_col_ptr[x], oval_col_ptr[x]);
}
std::stable_sort(std::begin(pairKeyVal), std::end(pairKeyVal), IPCompare<Tk, Tv, isAscending>());
for(unsigned x = 0; x < pairKeyVal.size(); x++) {
okey_ptr[okeyOffset + x] = std::get<0>(pairKeyVal[x]);
oval_ptr[ovalOffset + x] = std::get<1>(pairKeyVal[x]);
}
}
}
}
return;
}
template<typename Tk, typename Tv, bool isAscending, int dim>
void sortByKeyBatched(Array<Tk> okey, Array<Tv> oval)
{
af::dim4 inDims = okey.dims();
af::dim4 tileDims(1);
af::dim4 seqDims = inDims;
tileDims[dim] = inDims[dim];
seqDims[dim] = 1;
uint* key = memAlloc<uint>(inDims.elements());
// IOTA
{
af::dim4 dims = inDims;
uint* out = key;
af::dim4 strides(1);
for(int i = 1; i < 4; i++)
strides[i] = strides[i-1] * dims[i-1];
for(dim_t w = 0; w < dims[3]; w++) {
dim_t offW = w * strides[3];
uint okeyW = (w % seqDims[3]) * seqDims[0] * seqDims[1] * seqDims[2];
for(dim_t z = 0; z < dims[2]; z++) {
dim_t offWZ = offW + z * strides[2];
uint okeyZ = okeyW + (z % seqDims[2]) * seqDims[0] * seqDims[1];
for(dim_t y = 0; y < dims[1]; y++) {
dim_t offWZY = offWZ + y * strides[1];
uint okeyY = okeyZ + (y % seqDims[1]) * seqDims[0];
for(dim_t x = 0; x < dims[0]; x++) {
dim_t id = offWZY + x;
out[id] = okeyY + (x % seqDims[0]);
}
}
}
}
}
// initialize original index locations
Tk *okey_ptr = okey.get();
Tv *oval_ptr = oval.get();
std::vector<KeyIndexPair<Tk, Tv> > pairKeyVal(okey.elements());
for(unsigned i = 0; i < okey.elements(); i++) {
pairKeyVal[i] = std::make_tuple(okey_ptr[i], oval_ptr[i], key[i]);
}
memFree(key); // key is no longer required
std::stable_sort(pairKeyVal.begin(), pairKeyVal.end(), KIPCompareV<Tk, Tv, isAscending>());
std::stable_sort(pairKeyVal.begin(), pairKeyVal.end(), KIPCompareK<Tk, Tv, true>());
for(unsigned x = 0; x < okey.elements(); x++) {
okey_ptr[x] = std::get<0>(pairKeyVal[x]);
oval_ptr[x] = std::get<1>(pairKeyVal[x]);
}
return;
}
template<typename Tk, typename Tv, bool isAscending>
void sort0ByKey(Array<Tk> okey, Array<Tv> oval)
{
int higherDims = okey.dims()[1] * okey.dims()[2] * okey.dims()[3];
// TODO Make a better heurisitic
if(higherDims > 4)
kernel::sortByKeyBatched<Tk, Tv, isAscending, 0>(okey, oval);
else
kernel::sort0ByKeyIterative<Tk, Tv, isAscending>(okey, oval);
}
#define INSTANTIATE(Tk, Tv, dr) \
template void sort0ByKey<Tk, Tv, dr>(Array<Tk> okey, Array<Tv> oval); \
template void sort0ByKeyIterative<Tk, Tv, dr>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 0>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 1>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 2>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 3>(Array<Tk> okey, Array<Tv> oval); \
#define INSTANTIATE1(Tk , dr) \
INSTANTIATE(Tk, float , dr) \
INSTANTIATE(Tk, double , dr) \
INSTANTIATE(Tk, cfloat , dr) \
INSTANTIATE(Tk, cdouble, dr) \
INSTANTIATE(Tk, int , dr) \
INSTANTIATE(Tk, uint , dr) \
INSTANTIATE(Tk, short , dr) \
INSTANTIATE(Tk, ushort , dr) \
INSTANTIATE(Tk, char , dr) \
INSTANTIATE(Tk, uchar , dr) \
INSTANTIATE(Tk, intl , dr) \
INSTANTIATE(Tk, uintl , dr)
}
}
<commit_msg>Use memAlloc and memFree instead of std::vector internally<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <kernel/sort_by_key.hpp>
#include <kernel/sort_helper.hpp>
#include <Array.hpp>
#include <math.hpp>
#include <algorithm>
#include <numeric>
#include <queue>
#include <err_cpu.hpp>
#include <functional>
namespace cpu
{
namespace kernel
{
template<typename Tk, typename Tv, bool isAscending>
void sort0ByKeyIterative(Array<Tk> okey, Array<Tv> oval)
{
// Get pointers and initialize original index locations
Tk *okey_ptr = okey.get();
Tv *oval_ptr = oval.get();
typedef IndexPair<Tk, Tv> CurrentPair;
dim_t size = okey.dims()[0];
size_t bytes = size * sizeof(CurrentPair);
CurrentPair *pairKeyVal = (CurrentPair *)memAlloc<char>(bytes);
for(dim_t w = 0; w < okey.dims()[3]; w++) {
dim_t okeyW = w * okey.strides()[3];
dim_t ovalW = w * oval.strides()[3];
for(dim_t z = 0; z < okey.dims()[2]; z++) {
dim_t okeyWZ = okeyW + z * okey.strides()[2];
dim_t ovalWZ = ovalW + z * oval.strides()[2];
for(dim_t y = 0; y < okey.dims()[1]; y++) {
dim_t okeyOffset = okeyWZ + y * okey.strides()[1];
dim_t ovalOffset = ovalWZ + y * oval.strides()[1];
Tk *okey_col_ptr = okey_ptr + okeyOffset;
Tv *oval_col_ptr = oval_ptr + ovalOffset;
for(dim_t x = 0; x < size; x++) {
pairKeyVal[x] = std::make_tuple(okey_col_ptr[x], oval_col_ptr[x]);
}
std::stable_sort(pairKeyVal, pairKeyVal + size, IPCompare<Tk, Tv, isAscending>());
for(unsigned x = 0; x < size; x++) {
okey_ptr[okeyOffset + x] = std::get<0>(pairKeyVal[x]);
oval_ptr[ovalOffset + x] = std::get<1>(pairKeyVal[x]);
}
}
}
}
memFree((char *)pairKeyVal);
return;
}
template<typename Tk, typename Tv, bool isAscending, int dim>
void sortByKeyBatched(Array<Tk> okey, Array<Tv> oval)
{
af::dim4 inDims = okey.dims();
af::dim4 tileDims(1);
af::dim4 seqDims = inDims;
tileDims[dim] = inDims[dim];
seqDims[dim] = 1;
uint* key = memAlloc<uint>(inDims.elements());
// IOTA
{
af::dim4 dims = inDims;
uint* out = key;
af::dim4 strides(1);
for(int i = 1; i < 4; i++)
strides[i] = strides[i-1] * dims[i-1];
for(dim_t w = 0; w < dims[3]; w++) {
dim_t offW = w * strides[3];
uint okeyW = (w % seqDims[3]) * seqDims[0] * seqDims[1] * seqDims[2];
for(dim_t z = 0; z < dims[2]; z++) {
dim_t offWZ = offW + z * strides[2];
uint okeyZ = okeyW + (z % seqDims[2]) * seqDims[0] * seqDims[1];
for(dim_t y = 0; y < dims[1]; y++) {
dim_t offWZY = offWZ + y * strides[1];
uint okeyY = okeyZ + (y % seqDims[1]) * seqDims[0];
for(dim_t x = 0; x < dims[0]; x++) {
dim_t id = offWZY + x;
out[id] = okeyY + (x % seqDims[0]);
}
}
}
}
}
// initialize original index locations
Tk *okey_ptr = okey.get();
Tv *oval_ptr = oval.get();
typedef KeyIndexPair<Tk, Tv> CurrentTuple;
size_t size = okey.elements();
size_t bytes = okey.elements() * sizeof(CurrentTuple);
CurrentTuple *tupleKeyValIdx = (CurrentTuple *)memAlloc<char>(bytes);
for(unsigned i = 0; i < size; i++) {
tupleKeyValIdx[i] = std::make_tuple(okey_ptr[i], oval_ptr[i], key[i]);
}
memFree(key); // key is no longer required
std::stable_sort(tupleKeyValIdx, tupleKeyValIdx + size, KIPCompareV<Tk, Tv, isAscending>());
std::stable_sort(tupleKeyValIdx, tupleKeyValIdx + size, KIPCompareK<Tk, Tv, true>());
for(unsigned x = 0; x < okey.elements(); x++) {
okey_ptr[x] = std::get<0>(tupleKeyValIdx[x]);
oval_ptr[x] = std::get<1>(tupleKeyValIdx[x]);
}
memFree((char *)tupleKeyValIdx);
return;
}
template<typename Tk, typename Tv, bool isAscending>
void sort0ByKey(Array<Tk> okey, Array<Tv> oval)
{
int higherDims = okey.dims()[1] * okey.dims()[2] * okey.dims()[3];
// TODO Make a better heurisitic
if(higherDims > 4)
kernel::sortByKeyBatched<Tk, Tv, isAscending, 0>(okey, oval);
else
kernel::sort0ByKeyIterative<Tk, Tv, isAscending>(okey, oval);
}
#define INSTANTIATE(Tk, Tv, dr) \
template void sort0ByKey<Tk, Tv, dr>(Array<Tk> okey, Array<Tv> oval); \
template void sort0ByKeyIterative<Tk, Tv, dr>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 0>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 1>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 2>(Array<Tk> okey, Array<Tv> oval); \
template void sortByKeyBatched<Tk, Tv, dr, 3>(Array<Tk> okey, Array<Tv> oval); \
#define INSTANTIATE1(Tk , dr) \
INSTANTIATE(Tk, float , dr) \
INSTANTIATE(Tk, double , dr) \
INSTANTIATE(Tk, cfloat , dr) \
INSTANTIATE(Tk, cdouble, dr) \
INSTANTIATE(Tk, int , dr) \
INSTANTIATE(Tk, uint , dr) \
INSTANTIATE(Tk, short , dr) \
INSTANTIATE(Tk, ushort , dr) \
INSTANTIATE(Tk, char , dr) \
INSTANTIATE(Tk, uchar , dr) \
INSTANTIATE(Tk, intl , dr) \
INSTANTIATE(Tk, uintl , dr)
}
}
<|endoftext|> |
<commit_before>#include "rapid_pbd/action_executor.h"
#include <string>
#include "actionlib/client/simple_action_client.h"
#include "actionlib/server/simple_action_server.h"
#include "control_msgs/GripperCommandAction.h"
#include "control_msgs/FollowJointTrajectoryAction.h"
#include "ros/ros.h"
#include "rapid_pbd/action_names.h"
using actionlib::SimpleActionClient;
using actionlib::SimpleClientGoalState;
using control_msgs::FollowJointTrajectoryAction;
using rapid_pbd_msgs::Action;
namespace rapid {
namespace pbd {
ActionExecutor::ActionExecutor(const Action& action,
ActionClients* action_clients)
: action_(action), clients_(action_clients) {}
bool ActionExecutor::IsValid(const Action& action) {
if (action.type == Action::ACTUATE_GRIPPER) {
if (action.actuator_group == Action::GRIPPER ||
action.actuator_group == Action::LEFT_GRIPPER ||
action.actuator_group == Action::RIGHT_GRIPPER) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_JOINT_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_CARTESIAN_GOAL) {
} else if (action.type == Action::DETECT_TABLETOP_OBJECTS) {
} else if (action.type == Action::FIND_CUSTOM_LANDMARK) {
} else {
ROS_ERROR("Invalid action type: \"%s\"", action.type.c_str());
return false;
}
return true;
}
void ActionExecutor::Start() {
if (action_.type == Action::ACTUATE_GRIPPER) {
ActuateGripper();
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
MoveToJointGoal();
}
}
bool ActionExecutor::IsDone() const {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
return clients_->gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
return clients_->l_gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
return clients_->r_gripper_client.getState().isDone();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::ARM) {
return clients_->arm_joint_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_ARM) {
return clients_->l_arm_joint_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_ARM) {
return clients_->r_arm_joint_client.getState().isDone();
}
}
return true;
}
void ActionExecutor::Cancel() {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
clients_->gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
clients_->l_gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
clients_->r_gripper_client.cancelAllGoals();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::ARM) {
clients_->arm_joint_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_ARM) {
clients_->l_arm_joint_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_ARM) {
clients_->r_arm_joint_client.cancelAllGoals();
}
}
}
void ActionExecutor::ActuateGripper() {
control_msgs::GripperCommandGoal gripper_goal;
gripper_goal.command = action_.gripper_command;
SimpleActionClient<control_msgs::GripperCommandAction>* client;
if (action_.actuator_group == Action::GRIPPER) {
client = &clients_->gripper_client;
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
client = &clients_->l_gripper_client;
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
client = &clients_->r_gripper_client;
} else {
return;
}
client->sendGoal(gripper_goal);
}
void ActionExecutor::MoveToJointGoal() {
control_msgs::FollowJointTrajectoryGoal joint_goal;
joint_goal.trajectory = action_.joint_trajectory;
double delay;
ros::param::param("arm_delay", delay, 1.5);
joint_goal.trajectory.header.stamp = ros::Time::now() + ros::Duration(delay);
SimpleActionClient<FollowJointTrajectoryAction>* client;
if (action_.actuator_group == Action::ARM) {
client = &clients_->arm_joint_client;
} else if (action_.actuator_group == Action::LEFT_ARM) {
client = &clients_->l_arm_joint_client;
} else if (action_.actuator_group == Action::RIGHT_ARM) {
client = &clients_->r_arm_joint_client;
} else {
return;
}
client->sendGoal(joint_goal);
}
void ActionExecutor::PublishInvalidGroupError(const Action& action) {
ROS_ERROR("Invalid actuator_group \"%s\" for action type \"%s\".",
action.actuator_group.c_str(), action.type.c_str());
}
} // namespace pbd
} // namespace rapid
<commit_msg>Alphabetize.<commit_after>#include "rapid_pbd/action_executor.h"
#include <string>
#include "actionlib/client/simple_action_client.h"
#include "actionlib/server/simple_action_server.h"
#include "control_msgs/FollowJointTrajectoryAction.h"
#include "control_msgs/GripperCommandAction.h"
#include "ros/ros.h"
#include "rapid_pbd/action_names.h"
using actionlib::SimpleActionClient;
using actionlib::SimpleClientGoalState;
using control_msgs::FollowJointTrajectoryAction;
using rapid_pbd_msgs::Action;
namespace rapid {
namespace pbd {
ActionExecutor::ActionExecutor(const Action& action,
ActionClients* action_clients)
: action_(action), clients_(action_clients) {}
bool ActionExecutor::IsValid(const Action& action) {
if (action.type == Action::ACTUATE_GRIPPER) {
if (action.actuator_group == Action::GRIPPER ||
action.actuator_group == Action::LEFT_GRIPPER ||
action.actuator_group == Action::RIGHT_GRIPPER) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_JOINT_GOAL) {
if (action.actuator_group == Action::ARM ||
action.actuator_group == Action::LEFT_ARM ||
action.actuator_group == Action::RIGHT_ARM) {
} else {
PublishInvalidGroupError(action);
return false;
}
} else if (action.type == Action::MOVE_TO_CARTESIAN_GOAL) {
} else if (action.type == Action::DETECT_TABLETOP_OBJECTS) {
} else if (action.type == Action::FIND_CUSTOM_LANDMARK) {
} else {
ROS_ERROR("Invalid action type: \"%s\"", action.type.c_str());
return false;
}
return true;
}
void ActionExecutor::Start() {
if (action_.type == Action::ACTUATE_GRIPPER) {
ActuateGripper();
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
MoveToJointGoal();
}
}
bool ActionExecutor::IsDone() const {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
return clients_->gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
return clients_->l_gripper_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
return clients_->r_gripper_client.getState().isDone();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::ARM) {
return clients_->arm_joint_client.getState().isDone();
} else if (action_.actuator_group == Action::LEFT_ARM) {
return clients_->l_arm_joint_client.getState().isDone();
} else if (action_.actuator_group == Action::RIGHT_ARM) {
return clients_->r_arm_joint_client.getState().isDone();
}
}
return true;
}
void ActionExecutor::Cancel() {
if (action_.type == Action::ACTUATE_GRIPPER) {
if (action_.actuator_group == Action::GRIPPER) {
clients_->gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
clients_->l_gripper_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
clients_->r_gripper_client.cancelAllGoals();
}
} else if (action_.type == Action::MOVE_TO_JOINT_GOAL) {
if (action_.actuator_group == Action::ARM) {
clients_->arm_joint_client.cancelAllGoals();
} else if (action_.actuator_group == Action::LEFT_ARM) {
clients_->l_arm_joint_client.cancelAllGoals();
} else if (action_.actuator_group == Action::RIGHT_ARM) {
clients_->r_arm_joint_client.cancelAllGoals();
}
}
}
void ActionExecutor::ActuateGripper() {
control_msgs::GripperCommandGoal gripper_goal;
gripper_goal.command = action_.gripper_command;
SimpleActionClient<control_msgs::GripperCommandAction>* client;
if (action_.actuator_group == Action::GRIPPER) {
client = &clients_->gripper_client;
} else if (action_.actuator_group == Action::LEFT_GRIPPER) {
client = &clients_->l_gripper_client;
} else if (action_.actuator_group == Action::RIGHT_GRIPPER) {
client = &clients_->r_gripper_client;
} else {
return;
}
client->sendGoal(gripper_goal);
}
void ActionExecutor::MoveToJointGoal() {
control_msgs::FollowJointTrajectoryGoal joint_goal;
joint_goal.trajectory = action_.joint_trajectory;
double delay;
ros::param::param("arm_delay", delay, 1.5);
joint_goal.trajectory.header.stamp = ros::Time::now() + ros::Duration(delay);
SimpleActionClient<FollowJointTrajectoryAction>* client;
if (action_.actuator_group == Action::ARM) {
client = &clients_->arm_joint_client;
} else if (action_.actuator_group == Action::LEFT_ARM) {
client = &clients_->l_arm_joint_client;
} else if (action_.actuator_group == Action::RIGHT_ARM) {
client = &clients_->r_arm_joint_client;
} else {
return;
}
client->sendGoal(joint_goal);
}
void ActionExecutor::PublishInvalidGroupError(const Action& action) {
ROS_ERROR("Invalid actuator_group \"%s\" for action type \"%s\".",
action.actuator_group.c_str(), action.type.c_str());
}
} // namespace pbd
} // namespace rapid
<|endoftext|> |
<commit_before>/*
BSD 3-Clause License
Copyright (c) 2016, Bluecadet
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 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 "AnalyticsClient.h"
#include "cinder/Log.h"
#include "GAEvent.hpp"
#include "GAScreenView.hpp"
using namespace ci;
using namespace ci::app;
using namespace std;
namespace bluecadet {
namespace analytics {
AnalyticsClient::AnalyticsClient() :
mThreadManager(make_shared<utils::ThreadManager>()),
mCacheBusterEnabled(true),
mAutoSessionsEnabled(true),
mMaxHitsPerSession(400), // stay below 500 events per session limit
mHitsInCurrentSession(0),
mGaApiVersion("1")
{
}
AnalyticsClient::~AnalyticsClient() {
}
void AnalyticsClient::setup(string clientId, string gaId, string appName, string appVersion, int numThreads, double maxBatchAge, int maxBatchesPerCycle) {
destroy();
mAppName = appName;
mAppVersion = appVersion;
mGaId = gaId;
mClientId = clientId;
mMaxBatchAge = maxBatchAge;
mMaxBatchesPerCycle = maxBatchesPerCycle;
mThreadManager->setup(numThreads);
CI_LOG_I("Client set up with GA ID '" << mGaId << "' and client ID '" << mClientId << "'");
mUpdateConnection = AppBase::get()->getSignalUpdate().connect([=] {
// process batches regularly on sub thread
mThreadManager->addTask([this] {
processBatches();
});
});
}
void AnalyticsClient::destroy() {
mThreadManager->destroy();
if (mUpdateConnection.isConnected()) {
mUpdateConnection.disconnect();
}
lock_guard<mutex> lock(mBatchMutex);
mBatchQueue.clear();
mCurrentBatch = nullptr;
}
void AnalyticsClient::trackEvent(const string & category, const string & action, const string & label, const int value, const std::string & customQuery) {
GAEventRef event = make_shared<GAEvent>(mAppName, mGaId, mClientId, mGaApiVersion, category, action, label, value, customQuery);
trackHit(event);
}
void AnalyticsClient::trackScreenView(const string & screenName, const std::string & customQuery) {
GAScreenViewRef screenView = make_shared<GAScreenView>(mAppName, mGaId, mClientId, mGaApiVersion, screenName, customQuery);
trackHit(screenView);
}
void AnalyticsClient::trackHit(GAHitRef hit) {
// optional hit parameters
hit->mAppVersion = mAppVersion;
hit->mCacheBuster = mCacheBusterEnabled;
// handle session control to stay within quotas
if (mAutoSessionsEnabled) {
if (mHitsInCurrentSession <= 0) {
hit->mSessionControl = GAHit::SessionControl::Start;
CI_LOG_V("Starting a new session");
}
mHitsInCurrentSession++;
if (mHitsInCurrentSession >= mMaxHitsPerSession) {
hit->mSessionControl = GAHit::SessionControl::End;
CI_LOG_V("Ended session after " << to_string(mHitsInCurrentSession) << " hits");
mHitsInCurrentSession = 0;
}
}
mThreadManager->addTask([=] {
lock_guard<mutex> lock(mBatchMutex);
// ensure we have a batch that can fit our hit
if (!mCurrentBatch || !mCurrentBatch->canAddHit(hit)) {
if (mCurrentBatch) {
// buffer current batch for sending
mBatchQueue.push_back(mCurrentBatch);
}
// new batch
mCurrentBatch = make_shared<GABatch>();
}
mCurrentBatch->addHit(hit);
});
}
void AnalyticsClient::processBatches() {
lock_guard<mutex> lock(mBatchMutex);
// check if we should send the current batch
if (mCurrentBatch && (mCurrentBatch->isFull() || mCurrentBatch->getAge() >= mMaxBatchAge)) {
mBatchQueue.push_back(mCurrentBatch);
mCurrentBatch = nullptr;
}
const double currentTime = getElapsedSeconds();
const int maxBatchesToSend = min((int)mBatchQueue.size(), mMaxBatchesPerCycle);
int numHitsSent = 0;
int numBatchesSent = 0;
// process batch queue and send as many as we can
for (int i = 0; i < maxBatchesToSend; ++i) {
auto batch = mBatchQueue.front();
const double timeSinceLastAttempt = currentTime - batch->getTimeOfLastSendAttempt();
if (timeSinceLastAttempt < batch->getDelayUntilNextSendAttempt()) {
continue; // wait until we can try again
}
// send batch
sendBatch(batch);
numBatchesSent++;
numHitsSent += (int)batch->numHits();
// remove batch
mBatchQueue.pop_front();
}
if (numBatchesSent > 0) {
CI_LOG_V("Sending " << to_string(numBatchesSent) << " batches with a total of " <<
to_string(numHitsSent) << " hits (" << to_string(mBatchQueue.size()) << " batches remaining)");
}
}
void AnalyticsClient::sendBatch(GABatchRef batch) {
mThreadManager->addTask([=] {
const string body = batch->getPayloadString();
utils::UrlRequest::Options options;
options.method = utils::UrlRequest::Method::POST;
options.setBodyText(body);
utils::UrlRequestRef request = utils::UrlRequest::create(mGaBaseUrl, mGaBatchUri, options);
// save and send request
lock_guard<mutex> lock(mRequestMutex);
mPendingRequests.insert(request);
CI_LOG_D(body);
request->connect([=] (utils::UrlRequestRef request) {
handleBatchRequestCompleted(batch, request);
});
});
}
void AnalyticsClient::handleBatchRequestCompleted(GABatchRef batch, utils::UrlRequestRef request) {
if (!request || !request->wasSuccessful()) {
// increase delay until next attempt
batch->setTimeOfLastSendAttempt(getElapsedSeconds());
batch->increaseDelayUntilNextSendAttempt();
const string reason = request ? request->getHttpResponse().getReason() : "(unknown reason)";
CI_LOG_W("Batch failed to send: " << reason <<
" - attempting again in " << to_string(batch->getDelayUntilNextSendAttempt()) << " seconds");
// push batch back onto queue to retry
lock_guard<mutex> lock(mBatchMutex);
mBatchQueue.push_front(batch);
}
AppBase::get()->dispatchAsync([=] {
// discard request asynchronously (can't remove it directly from our callback)
lock_guard<mutex> lock(mRequestMutex);
auto it = mPendingRequests.find(request);
if (it != mPendingRequests.end()) {
mPendingRequests.erase(it);
}
});
}
} // analytics namespace
} // bluecadet namespace
<commit_msg>Removed debug log<commit_after>/*
BSD 3-Clause License
Copyright (c) 2016, Bluecadet
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 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 "AnalyticsClient.h"
#include "cinder/Log.h"
#include "GAEvent.hpp"
#include "GAScreenView.hpp"
using namespace ci;
using namespace ci::app;
using namespace std;
namespace bluecadet {
namespace analytics {
AnalyticsClient::AnalyticsClient() :
mThreadManager(make_shared<utils::ThreadManager>()),
mCacheBusterEnabled(true),
mAutoSessionsEnabled(true),
mMaxHitsPerSession(400), // stay below 500 events per session limit
mHitsInCurrentSession(0),
mGaApiVersion("1")
{
}
AnalyticsClient::~AnalyticsClient() {
}
void AnalyticsClient::setup(string clientId, string gaId, string appName, string appVersion, int numThreads, double maxBatchAge, int maxBatchesPerCycle) {
destroy();
mAppName = appName;
mAppVersion = appVersion;
mGaId = gaId;
mClientId = clientId;
mMaxBatchAge = maxBatchAge;
mMaxBatchesPerCycle = maxBatchesPerCycle;
mThreadManager->setup(numThreads);
CI_LOG_I("Client set up with GA ID '" << mGaId << "' and client ID '" << mClientId << "'");
mUpdateConnection = AppBase::get()->getSignalUpdate().connect([=] {
// process batches regularly on sub thread
mThreadManager->addTask([this] {
processBatches();
});
});
}
void AnalyticsClient::destroy() {
mThreadManager->destroy();
if (mUpdateConnection.isConnected()) {
mUpdateConnection.disconnect();
}
lock_guard<mutex> lock(mBatchMutex);
mBatchQueue.clear();
mCurrentBatch = nullptr;
}
void AnalyticsClient::trackEvent(const string & category, const string & action, const string & label, const int value, const std::string & customQuery) {
GAEventRef event = make_shared<GAEvent>(mAppName, mGaId, mClientId, mGaApiVersion, category, action, label, value, customQuery);
trackHit(event);
}
void AnalyticsClient::trackScreenView(const string & screenName, const std::string & customQuery) {
GAScreenViewRef screenView = make_shared<GAScreenView>(mAppName, mGaId, mClientId, mGaApiVersion, screenName, customQuery);
trackHit(screenView);
}
void AnalyticsClient::trackHit(GAHitRef hit) {
// optional hit parameters
hit->mAppVersion = mAppVersion;
hit->mCacheBuster = mCacheBusterEnabled;
// handle session control to stay within quotas
if (mAutoSessionsEnabled) {
if (mHitsInCurrentSession <= 0) {
hit->mSessionControl = GAHit::SessionControl::Start;
CI_LOG_V("Starting a new session");
}
mHitsInCurrentSession++;
if (mHitsInCurrentSession >= mMaxHitsPerSession) {
hit->mSessionControl = GAHit::SessionControl::End;
CI_LOG_V("Ended session after " << to_string(mHitsInCurrentSession) << " hits");
mHitsInCurrentSession = 0;
}
}
mThreadManager->addTask([=] {
lock_guard<mutex> lock(mBatchMutex);
// ensure we have a batch that can fit our hit
if (!mCurrentBatch || !mCurrentBatch->canAddHit(hit)) {
if (mCurrentBatch) {
// buffer current batch for sending
mBatchQueue.push_back(mCurrentBatch);
}
// new batch
mCurrentBatch = make_shared<GABatch>();
}
mCurrentBatch->addHit(hit);
});
}
void AnalyticsClient::processBatches() {
lock_guard<mutex> lock(mBatchMutex);
// check if we should send the current batch
if (mCurrentBatch && (mCurrentBatch->isFull() || mCurrentBatch->getAge() >= mMaxBatchAge)) {
mBatchQueue.push_back(mCurrentBatch);
mCurrentBatch = nullptr;
}
const double currentTime = getElapsedSeconds();
const int maxBatchesToSend = min((int)mBatchQueue.size(), mMaxBatchesPerCycle);
int numHitsSent = 0;
int numBatchesSent = 0;
// process batch queue and send as many as we can
for (int i = 0; i < maxBatchesToSend; ++i) {
auto batch = mBatchQueue.front();
const double timeSinceLastAttempt = currentTime - batch->getTimeOfLastSendAttempt();
if (timeSinceLastAttempt < batch->getDelayUntilNextSendAttempt()) {
continue; // wait until we can try again
}
// send batch
sendBatch(batch);
numBatchesSent++;
numHitsSent += (int)batch->numHits();
// remove batch
mBatchQueue.pop_front();
}
if (numBatchesSent > 0) {
CI_LOG_V("Sending " << to_string(numBatchesSent) << " batches with a total of " <<
to_string(numHitsSent) << " hits (" << to_string(mBatchQueue.size()) << " batches remaining)");
}
}
void AnalyticsClient::sendBatch(GABatchRef batch) {
mThreadManager->addTask([=] {
const string body = batch->getPayloadString();
utils::UrlRequest::Options options;
options.method = utils::UrlRequest::Method::POST;
options.setBodyText(body);
utils::UrlRequestRef request = utils::UrlRequest::create(mGaBaseUrl, mGaBatchUri, options);
// save and send request
lock_guard<mutex> lock(mRequestMutex);
mPendingRequests.insert(request);
request->connect([=] (utils::UrlRequestRef request) {
handleBatchRequestCompleted(batch, request);
});
});
}
void AnalyticsClient::handleBatchRequestCompleted(GABatchRef batch, utils::UrlRequestRef request) {
if (!request || !request->wasSuccessful()) {
// increase delay until next attempt
batch->setTimeOfLastSendAttempt(getElapsedSeconds());
batch->increaseDelayUntilNextSendAttempt();
const string reason = request ? request->getHttpResponse().getReason() : "(unknown reason)";
CI_LOG_W("Batch failed to send: " << reason <<
" - attempting again in " << to_string(batch->getDelayUntilNextSendAttempt()) << " seconds");
// push batch back onto queue to retry
lock_guard<mutex> lock(mBatchMutex);
mBatchQueue.push_front(batch);
}
AppBase::get()->dispatchAsync([=] {
// discard request asynchronously (can't remove it directly from our callback)
lock_guard<mutex> lock(mRequestMutex);
auto it = mPendingRequests.find(request);
if (it != mPendingRequests.end()) {
mPendingRequests.erase(it);
}
});
}
} // analytics namespace
} // bluecadet namespace
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_crash_reporter_client.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
#if defined(OS_WIN)
#include <windows.h>
#include "base/file_version_info.h"
#include "base/win/registry.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/util_constants.h"
//#include "policy/policy_constants.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
#include "chrome/browser/crash_upload_list.h"
#include "chrome/common/chrome_version_info_values.h"
#endif
#if defined(OS_POSIX)
#include "base/debug/dump_without_crashing.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/common/descriptors_android.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/common/chrome_version_info.h"
#include "chromeos/chromeos_switches.h"
#endif
namespace chrome {
namespace {
#if defined(OS_WIN)
// This is the minimum version of google update that is required for deferred
// crash uploads to work.
const char kMinUpdateVersion[] = "1.3.21.115";
// The value name prefix will be of the form {chrome-version}-{pid}-{timestamp}
// (i.e., "#####.#####.#####.#####-########-########") which easily fits into a
// 63 character buffer.
const char kBrowserCrashDumpPrefixTemplate[] = "%s-%08x-%08x";
const size_t kBrowserCrashDumpPrefixLength = 63;
char g_browser_crash_dump_prefix[kBrowserCrashDumpPrefixLength + 1] = {};
// These registry key to which we'll write a value for each crash dump attempt.
HKEY g_browser_crash_dump_regkey = NULL;
// A atomic counter to make each crash dump value name unique.
base::subtle::Atomic32 g_browser_crash_dump_count = 0;
#endif
} // namespace
ChromeCrashReporterClient::ChromeCrashReporterClient() {}
ChromeCrashReporterClient::~ChromeCrashReporterClient() {}
void ChromeCrashReporterClient::SetCrashReporterClientIdFromGUID(
const std::string& client_guid) {
crash_keys::SetCrashClientIdFromGUID(client_guid);
}
#if defined(OS_WIN)
bool ChromeCrashReporterClient::GetAlternativeCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
*crash_dir = base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
return true;
}
return false;
}
void ChromeCrashReporterClient::GetProductNameAndVersion(
const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
DCHECK(product_name);
DCHECK(version);
DCHECK(special_build);
DCHECK(channel_name);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(exe_path));
if (version_info.get()) {
// Get the information from the file.
*version = version_info->product_version();
if (!version_info->is_official_build())
version->append(base::ASCIIToUTF16("-devel"));
*product_name = version_info->product_short_name();
*special_build = version_info->special_build();
} else {
// No version info found. Make up the values.
*product_name = base::ASCIIToUTF16("Chrome");
*version = base::ASCIIToUTF16("0.0.0.0-devel");
}
#if 0
GoogleUpdateSettings::GetChromeChannelAndModifiers(
!GetIsPerUserInstall(exe_path), channel_name);
#endif
}
bool ChromeCrashReporterClient::ShouldShowRestartDialog(base::string16* title,
base::string16* message,
bool* is_rtl_locale) {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kShowRestart) ||
!env->HasVar(env_vars::kRestartInfo) ||
env->HasVar(env_vars::kMetroConnected)) {
return false;
}
std::string restart_info;
env->GetVar(env_vars::kRestartInfo, &restart_info);
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment()
// for details.
std::vector<std::string> dlg_strings;
base::SplitString(restart_info, '|', &dlg_strings);
if (dlg_strings.size() < 3)
return false;
*title = base::UTF8ToUTF16(dlg_strings[0]);
*message = base::UTF8ToUTF16(dlg_strings[1]);
*is_rtl_locale = dlg_strings[2] == env_vars::kRtlLocale;
return true;
}
bool ChromeCrashReporterClient::AboutToRestart() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kRestartInfo))
return false;
env->SetVar(env_vars::kShowRestart, "1");
return true;
}
bool ChromeCrashReporterClient::GetDeferredUploadsSupported(
bool is_per_user_install) {
#if 0
Version update_version = GoogleUpdateSettings::GetGoogleUpdateVersion(
!is_per_user_install);
if (!update_version.IsValid() ||
update_version.IsOlderThan(std::string(kMinUpdateVersion)))
return false;
#endif
return true;
}
bool ChromeCrashReporterClient::GetIsPerUserInstall(
const base::FilePath& exe_path) {
return true;
}
bool ChromeCrashReporterClient::GetShouldDumpLargerDumps(
bool is_per_user_install) {
return true;
#if 0
base::string16 channel_name =
GoogleUpdateSettings::GetChromeChannel(!is_per_user_install);
// Capture more detail in crash dumps for beta and dev channel builds.
return (channel_name == installer::kChromeChannelDev ||
channel_name == installer::kChromeChannelBeta ||
channel_name == GoogleChromeSxSDistribution::ChannelName());
#endif
}
int ChromeCrashReporterClient::GetResultCodeRespawnFailed() {
return chrome::RESULT_CODE_RESPAWN_FAILED;
}
void ChromeCrashReporterClient::InitBrowserCrashDumpsRegKey() {
DCHECK(g_browser_crash_dump_regkey == NULL);
base::win::RegKey regkey;
if (regkey.Create(HKEY_CURRENT_USER,
chrome::kBrowserCrashDumpAttemptsRegistryPath,
KEY_ALL_ACCESS) != ERROR_SUCCESS) {
return;
}
// We use the current process id and the current tick count as a (hopefully)
// unique combination for the crash dump value. There's a small chance that
// across a reboot we might have a crash dump signal written, and the next
// browser process might have the same process id and tick count, but crash
// before consuming the signal (overwriting the signal with an identical one).
// For now, we're willing to live with that risk.
if (base::strings::SafeSPrintf(g_browser_crash_dump_prefix,
kBrowserCrashDumpPrefixTemplate,
"version",
::GetCurrentProcessId(),
::GetTickCount()) <= 0) {
NOTREACHED();
g_browser_crash_dump_prefix[0] = '\0';
return;
}
// Hold the registry key in a global for update on crash dump.
g_browser_crash_dump_regkey = regkey.Take();
}
void ChromeCrashReporterClient::RecordCrashDumpAttempt(bool is_real_crash) {
// If we're not a browser (or the registry is unavailable to us for some
// reason) then there's nothing to do.
if (g_browser_crash_dump_regkey == NULL)
return;
// Generate the final value name we'll use (appends the crash number to the
// base value name).
const size_t kMaxValueSize = 2 * kBrowserCrashDumpPrefixLength;
char value_name[kMaxValueSize + 1] = {};
if (base::strings::SafeSPrintf(
value_name, "%s-%x", g_browser_crash_dump_prefix,
base::subtle::NoBarrier_AtomicIncrement(&g_browser_crash_dump_count,
1)) > 0) {
DWORD value_dword = is_real_crash ? 1 : 0;
::RegSetValueExA(g_browser_crash_dump_regkey, value_name, 0, REG_DWORD,
reinterpret_cast<BYTE*>(&value_dword),
sizeof(value_dword));
}
}
bool ChromeCrashReporterClient::ReportingIsEnforcedByPolicy(
bool* breakpad_enabled) {
// Determine whether configuration management allows loading the crash reporter.
// Since the configuration management infrastructure is not initialized at this
// point, we read the corresponding registry key directly. The return status
// indicates whether policy data was successfully read. If it is true,
// |breakpad_enabled| contains the value set by policy.
#if 0
base::string16 key_name =
base::UTF8ToUTF16(policy::key::kMetricsReportingEnabled);
DWORD value = 0;
base::win::RegKey hklm_policy_key(HKEY_LOCAL_MACHINE,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hklm_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
base::win::RegKey hkcu_policy_key(HKEY_CURRENT_USER,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hkcu_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
#endif
return false;
}
#endif // defined(OS_WIN)
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
void ChromeCrashReporterClient::GetProductNameAndVersion(
const char** product_name,
const char** version) {
DCHECK(product_name);
DCHECK(version);
#if defined(OS_ANDROID)
*product_name = "Chrome_Android";
#elif defined(OS_CHROMEOS)
*product_name = "Chrome_ChromeOS";
#else // OS_LINUX
#if !defined(ADDRESS_SANITIZER)
*product_name = "Chrome_Linux";
#else
*product_name = "Chrome_Linux_ASan";
#endif
#endif
*version = PRODUCT_VERSION;
}
base::FilePath ChromeCrashReporterClient::GetReporterLogFilename() {
return base::FilePath(CrashUploadList::kReporterLogFilename);
}
#endif
bool ChromeCrashReporterClient::GetCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
base::FilePath crash_dumps_dir_path =
base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
PathService::Override(chrome::DIR_CRASH_DUMPS, crash_dumps_dir_path);
}
return PathService::Get(chrome::DIR_CRASH_DUMPS, crash_dir);
}
size_t ChromeCrashReporterClient::RegisterCrashKeys() {
// Note: This is not called on Windows because Breakpad is initialized in the
// EXE module, but code that uses crash keys is in the DLL module.
// RegisterChromeCrashKeys() will be called after the DLL is loaded.
return crash_keys::RegisterChromeCrashKeys();
}
bool ChromeCrashReporterClient::IsRunningUnattended() {
scoped_ptr<base::Environment> env(base::Environment::Create());
return env->HasVar(env_vars::kHeadless);
}
bool ChromeCrashReporterClient::GetCollectStatsConsent() {
#if defined(GOOGLE_CHROME_BUILD)
bool is_official_chrome_build = true;
#else
// bool is_official_chrome_build = false;
#endif
#if defined(OS_CHROMEOS)
bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kGuestSession);
bool is_stable_channel =
chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;
if (is_guest_session && is_stable_channel)
return false;
#endif // defined(OS_CHROMEOS)
#if defined(OS_ANDROID)
// TODO(jcivelli): we should not initialize the crash-reporter when it was not
// enabled. Right now if it is disabled we still generate the minidumps but we
// do not upload them.
return is_official_chrome_build;
#else // !defined(OS_ANDROID)
return false;
#endif // defined(OS_ANDROID)
}
#if defined(OS_ANDROID)
int ChromeCrashReporterClient::GetAndroidMinidumpDescriptor() {
return kAndroidMinidumpDescriptor;
}
#endif
bool ChromeCrashReporterClient::EnableBreakpadForProcess(
const std::string& process_type) {
return process_type == switches::kRendererProcess ||
process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kZygoteProcess ||
process_type == switches::kGpuProcess;
}
} // namespace chrome
<commit_msg>fix ChromeCrashReporterClient<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_crash_reporter_client.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/safe_sprintf.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_settings.h"
#include "content/nw/src/nw_version.h"
#if defined(OS_WIN)
#include <windows.h>
#include "base/file_version_info.h"
#include "base/win/registry.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/util_constants.h"
//#include "policy/policy_constants.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
#include "chrome/browser/crash_upload_list.h"
//#include "chrome/common/chrome_version_info_values.h"
#endif
#if defined(OS_POSIX)
#include "base/debug/dump_without_crashing.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/common/descriptors_android.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/common/chrome_version_info.h"
#include "chromeos/chromeos_switches.h"
#endif
namespace chrome {
namespace {
#if defined(OS_WIN)
// This is the minimum version of google update that is required for deferred
// crash uploads to work.
const char kMinUpdateVersion[] = "1.3.21.115";
// The value name prefix will be of the form {chrome-version}-{pid}-{timestamp}
// (i.e., "#####.#####.#####.#####-########-########") which easily fits into a
// 63 character buffer.
const char kBrowserCrashDumpPrefixTemplate[] = "%s-%08x-%08x";
const size_t kBrowserCrashDumpPrefixLength = 63;
char g_browser_crash_dump_prefix[kBrowserCrashDumpPrefixLength + 1] = {};
// These registry key to which we'll write a value for each crash dump attempt.
HKEY g_browser_crash_dump_regkey = NULL;
// A atomic counter to make each crash dump value name unique.
base::subtle::Atomic32 g_browser_crash_dump_count = 0;
#endif
} // namespace
ChromeCrashReporterClient::ChromeCrashReporterClient() {}
ChromeCrashReporterClient::~ChromeCrashReporterClient() {}
void ChromeCrashReporterClient::SetCrashReporterClientIdFromGUID(
const std::string& client_guid) {
crash_keys::SetCrashClientIdFromGUID(client_guid);
}
#if defined(OS_WIN)
bool ChromeCrashReporterClient::GetAlternativeCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
*crash_dir = base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
return true;
}
return false;
}
void ChromeCrashReporterClient::GetProductNameAndVersion(
const base::FilePath& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
DCHECK(product_name);
DCHECK(version);
DCHECK(special_build);
DCHECK(channel_name);
scoped_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(exe_path));
if (version_info.get()) {
// Get the information from the file.
*version = version_info->product_version();
if (!version_info->is_official_build())
version->append(base::ASCIIToUTF16("-devel"));
*product_name = version_info->product_short_name();
*special_build = version_info->special_build();
} else {
// No version info found. Make up the values.
*product_name = base::ASCIIToUTF16("Chrome");
*version = base::ASCIIToUTF16("0.0.0.0-devel");
}
#if 0
GoogleUpdateSettings::GetChromeChannelAndModifiers(
!GetIsPerUserInstall(exe_path), channel_name);
#endif
}
bool ChromeCrashReporterClient::ShouldShowRestartDialog(base::string16* title,
base::string16* message,
bool* is_rtl_locale) {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kShowRestart) ||
!env->HasVar(env_vars::kRestartInfo) ||
env->HasVar(env_vars::kMetroConnected)) {
return false;
}
std::string restart_info;
env->GetVar(env_vars::kRestartInfo, &restart_info);
// The CHROME_RESTART var contains the dialog strings separated by '|'.
// See ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment()
// for details.
std::vector<std::string> dlg_strings;
base::SplitString(restart_info, '|', &dlg_strings);
if (dlg_strings.size() < 3)
return false;
*title = base::UTF8ToUTF16(dlg_strings[0]);
*message = base::UTF8ToUTF16(dlg_strings[1]);
*is_rtl_locale = dlg_strings[2] == env_vars::kRtlLocale;
return true;
}
bool ChromeCrashReporterClient::AboutToRestart() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (!env->HasVar(env_vars::kRestartInfo))
return false;
env->SetVar(env_vars::kShowRestart, "1");
return true;
}
bool ChromeCrashReporterClient::GetDeferredUploadsSupported(
bool is_per_user_install) {
#if 0
Version update_version = GoogleUpdateSettings::GetGoogleUpdateVersion(
!is_per_user_install);
if (!update_version.IsValid() ||
update_version.IsOlderThan(std::string(kMinUpdateVersion)))
return false;
#endif
return true;
}
bool ChromeCrashReporterClient::GetIsPerUserInstall(
const base::FilePath& exe_path) {
return true;
}
bool ChromeCrashReporterClient::GetShouldDumpLargerDumps(
bool is_per_user_install) {
return true;
#if 0
base::string16 channel_name =
GoogleUpdateSettings::GetChromeChannel(!is_per_user_install);
// Capture more detail in crash dumps for beta and dev channel builds.
return (channel_name == installer::kChromeChannelDev ||
channel_name == installer::kChromeChannelBeta ||
channel_name == GoogleChromeSxSDistribution::ChannelName());
#endif
}
int ChromeCrashReporterClient::GetResultCodeRespawnFailed() {
return chrome::RESULT_CODE_RESPAWN_FAILED;
}
void ChromeCrashReporterClient::InitBrowserCrashDumpsRegKey() {
DCHECK(g_browser_crash_dump_regkey == NULL);
base::win::RegKey regkey;
if (regkey.Create(HKEY_CURRENT_USER,
chrome::kBrowserCrashDumpAttemptsRegistryPath,
KEY_ALL_ACCESS) != ERROR_SUCCESS) {
return;
}
// We use the current process id and the current tick count as a (hopefully)
// unique combination for the crash dump value. There's a small chance that
// across a reboot we might have a crash dump signal written, and the next
// browser process might have the same process id and tick count, but crash
// before consuming the signal (overwriting the signal with an identical one).
// For now, we're willing to live with that risk.
if (base::strings::SafeSPrintf(g_browser_crash_dump_prefix,
kBrowserCrashDumpPrefixTemplate,
"version",
::GetCurrentProcessId(),
::GetTickCount()) <= 0) {
NOTREACHED();
g_browser_crash_dump_prefix[0] = '\0';
return;
}
// Hold the registry key in a global for update on crash dump.
g_browser_crash_dump_regkey = regkey.Take();
}
void ChromeCrashReporterClient::RecordCrashDumpAttempt(bool is_real_crash) {
// If we're not a browser (or the registry is unavailable to us for some
// reason) then there's nothing to do.
if (g_browser_crash_dump_regkey == NULL)
return;
// Generate the final value name we'll use (appends the crash number to the
// base value name).
const size_t kMaxValueSize = 2 * kBrowserCrashDumpPrefixLength;
char value_name[kMaxValueSize + 1] = {};
if (base::strings::SafeSPrintf(
value_name, "%s-%x", g_browser_crash_dump_prefix,
base::subtle::NoBarrier_AtomicIncrement(&g_browser_crash_dump_count,
1)) > 0) {
DWORD value_dword = is_real_crash ? 1 : 0;
::RegSetValueExA(g_browser_crash_dump_regkey, value_name, 0, REG_DWORD,
reinterpret_cast<BYTE*>(&value_dword),
sizeof(value_dword));
}
}
bool ChromeCrashReporterClient::ReportingIsEnforcedByPolicy(
bool* breakpad_enabled) {
// Determine whether configuration management allows loading the crash reporter.
// Since the configuration management infrastructure is not initialized at this
// point, we read the corresponding registry key directly. The return status
// indicates whether policy data was successfully read. If it is true,
// |breakpad_enabled| contains the value set by policy.
#if 0
base::string16 key_name =
base::UTF8ToUTF16(policy::key::kMetricsReportingEnabled);
DWORD value = 0;
base::win::RegKey hklm_policy_key(HKEY_LOCAL_MACHINE,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hklm_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
base::win::RegKey hkcu_policy_key(HKEY_CURRENT_USER,
policy::kRegistryChromePolicyKey, KEY_READ);
if (hkcu_policy_key.ReadValueDW(key_name.c_str(), &value) == ERROR_SUCCESS) {
*breakpad_enabled = value != 0;
return true;
}
#endif
return false;
}
#endif // defined(OS_WIN)
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS)
void ChromeCrashReporterClient::GetProductNameAndVersion(
const char** product_name,
const char** version) {
DCHECK(product_name);
DCHECK(version);
*product_name = "NW.JS";
*version = NW_VERSION_STRING;
}
base::FilePath ChromeCrashReporterClient::GetReporterLogFilename() {
return base::FilePath(CrashUploadList::kReporterLogFilename);
}
#endif
bool ChromeCrashReporterClient::GetCrashDumpLocation(
base::FilePath* crash_dir) {
// By setting the BREAKPAD_DUMP_LOCATION environment variable, an alternate
// location to write breakpad crash dumps can be set.
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string alternate_crash_dump_location;
if (env->GetVar("BREAKPAD_DUMP_LOCATION", &alternate_crash_dump_location)) {
base::FilePath crash_dumps_dir_path =
base::FilePath::FromUTF8Unsafe(alternate_crash_dump_location);
PathService::Override(chrome::DIR_CRASH_DUMPS, crash_dumps_dir_path);
}
return PathService::Get(chrome::DIR_CRASH_DUMPS, crash_dir);
}
size_t ChromeCrashReporterClient::RegisterCrashKeys() {
// Note: This is not called on Windows because Breakpad is initialized in the
// EXE module, but code that uses crash keys is in the DLL module.
// RegisterChromeCrashKeys() will be called after the DLL is loaded.
return crash_keys::RegisterChromeCrashKeys();
}
bool ChromeCrashReporterClient::IsRunningUnattended() {
scoped_ptr<base::Environment> env(base::Environment::Create());
return env->HasVar(env_vars::kHeadless);
}
bool ChromeCrashReporterClient::GetCollectStatsConsent() {
#if defined(GOOGLE_CHROME_BUILD)
bool is_official_chrome_build = true;
#else
// bool is_official_chrome_build = false;
#endif
#if defined(OS_CHROMEOS)
bool is_guest_session = CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kGuestSession);
bool is_stable_channel =
chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE;
if (is_guest_session && is_stable_channel)
return false;
#endif // defined(OS_CHROMEOS)
#if defined(OS_ANDROID)
// TODO(jcivelli): we should not initialize the crash-reporter when it was not
// enabled. Right now if it is disabled we still generate the minidumps but we
// do not upload them.
return is_official_chrome_build;
#else // !defined(OS_ANDROID)
return false;
#endif // defined(OS_ANDROID)
}
#if defined(OS_ANDROID)
int ChromeCrashReporterClient::GetAndroidMinidumpDescriptor() {
return kAndroidMinidumpDescriptor;
}
#endif
bool ChromeCrashReporterClient::EnableBreakpadForProcess(
const std::string& process_type) {
return process_type == switches::kRendererProcess ||
process_type == switches::kPluginProcess ||
process_type == switches::kPpapiPluginProcess ||
process_type == switches::kZygoteProcess ||
process_type == switches::kGpuProcess;
}
} // namespace chrome
<|endoftext|> |
<commit_before>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "constants.hpp"
#include "event_manipulator.hpp"
#include "human_interface_device.hpp"
#include "iokit_utility.hpp"
#include "iopm_client.hpp"
#include "logger.hpp"
#include "manipulator.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <fstream>
#include <json/json.hpp>
#include <thread>
#include <time.h>
class device_grabber final {
public:
device_grabber(const device_grabber&) = delete;
device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator),
queue_(dispatch_queue_create(nullptr, nullptr)),
grab_timer_(0),
mode_(mode::observing),
grabbed_(false),
suspended_(false) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
iopm_client_ = std::make_unique<iopm_client>(logger::get_logger(),
std::bind(&device_grabber::iopm_client_callback, this, std::placeholders::_1));
}
~device_grabber(void) {
iopm_client_ = nullptr;
ungrab_devices();
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
dispatch_release(queue_);
}
void grab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::grabbing;
}
auto __block last_warning_message_time = ::time(nullptr) - 1;
cancel_grab_timer();
// ----------------------------------------
// setup grab_timer_
grab_timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_);
dispatch_source_set_timer(grab_timer_, dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), 0.1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(grab_timer_, ^{
std::lock_guard<std::mutex> grab_guard(grab_mutex_);
if (grabbed_) {
return;
}
std::string warning_message;
if (!event_manipulator_.is_ready()) {
warning_message = "event_manipulator_ is not ready. Please wait for a while.";
}
if (warning_message.empty()) {
std::string is_grabbable_warning_message;
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (const auto& it : hids_) {
if (!(it.second)->is_grabbable(is_grabbable_warning_message)) {
warning_message = is_grabbable_warning_message.empty() ? "Some devices are not grabbable." : is_grabbable_warning_message;
break;
}
}
}
if (!warning_message.empty()) {
auto time = ::time(nullptr);
if (last_warning_message_time != time) {
last_warning_message_time = time;
logger::get_logger().warn(warning_message);
}
return;
}
// ----------------------------------------
// grab devices
grabbed_ = true;
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
unobserve(*(it.second));
grab(*(it.second));
}
}
event_manipulator_.reset();
event_manipulator_.grab_mouse_events();
logger::get_logger().info("Connected devices are grabbed");
cancel_grab_timer();
});
dispatch_resume(grab_timer_);
}
void ungrab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::observing;
}
if (!grabbed_) {
return;
}
grabbed_ = false;
cancel_grab_timer();
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
ungrab(*(it.second));
observe(*(it.second));
}
}
event_manipulator_.ungrab_mouse_events();
event_manipulator_.reset();
logger::get_logger().info("Connected devices are ungrabbed");
}
void suspend(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (!suspended_) {
logger::get_logger().info("device_grabber::suspend");
suspended_ = true;
if (mode_ == mode::grabbing) {
ungrab_devices(false);
}
}
}
void resume(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (suspended_) {
logger::get_logger().info("device_grabber::resume");
suspended_ = false;
if (mode_ == mode::grabbing) {
grab_devices(false);
}
}
}
void set_caps_lock_led_state(krbn::led_state state) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
(it.second)->set_caps_lock_led_state(state);
}
}
private:
enum class mode {
observing,
grabbing,
};
void iopm_client_callback(uint32_t message_type) {
switch (message_type) {
case kIOMessageSystemWillSleep:
suspend();
break;
case kIOMessageSystemWillPowerOn:
resume();
break;
default:
break;
}
}
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_matching_device(logger::get_logger(), device);
auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device);
// ----------------------------------------
if (grabbed_) {
grab(*dev);
} else {
observe(*dev);
}
{
std::lock_guard<std::mutex> guard(hids_mutex_);
hids_[device] = std::move(dev);
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(logger::get_logger(), device);
{
std::lock_guard<std::mutex> guard(hids_mutex_);
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
hids_.erase(it);
}
}
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
event_manipulator_.stop_key_repeat();
}
void observe(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
human_interface_device::value_callback callback;
hid.observe(callback);
}
void unobserve(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
hid.unobserve();
}
void grab(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
// seize device
hid.grab(std::bind(&device_grabber::value_callback,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4,
std::placeholders::_5,
std::placeholders::_6));
// set keyboard led
event_manipulator_.refresh_caps_lock_led();
}
void ungrab(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
hid.ungrab();
}
void value_callback(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
if (!grabbed_) {
return;
}
auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id());
if (auto key_code = krbn::types::get_key_code(usage_page, usage)) {
bool pressed = integer_value;
event_manipulator_.handle_keyboard_event(device_registry_entry_id, *key_code, pressed);
} else if (auto pointing_button = krbn::types::get_pointing_button(usage_page, usage)) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::button,
*pointing_button,
integer_value);
} else {
switch (usage_page) {
case kHIDPage_GenericDesktop:
if (usage == kHIDUsage_GD_X) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::x,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Y) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::y,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Wheel) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::vertical_wheel,
boost::none,
integer_value);
}
break;
case kHIDPage_Consumer:
if (usage == kHIDUsage_Csmr_ACPan) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::horizontal_wheel,
boost::none,
integer_value);
}
break;
default:
break;
}
}
// reset modifier_flags state if all keys are released.
if (get_all_devices_pressed_keys_count() == 0) {
event_manipulator_.reset_modifier_flag_state();
event_manipulator_.reset_pointing_button_state();
}
}
size_t get_all_devices_pressed_keys_count(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
size_t total = 0;
for (const auto& it : hids_) {
total += (it.second)->get_pressed_keys_count();
}
return total;
}
bool is_keyboard_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_keyboard()) {
return true;
}
}
return false;
}
bool is_pointing_device_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_pointing_device()) {
return true;
}
}
return false;
}
void output_devices_json(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
nlohmann::json json;
json["devices"] = nlohmann::json::array();
for (const auto& it : hids_) {
nlohmann::json j({});
if (auto vendor_id = (it.second)->get_vendor_id()) {
j["vendor_id"] = *vendor_id;
}
if (auto product_id = (it.second)->get_product_id()) {
j["product_id"] = *product_id;
}
if (auto manufacturer = (it.second)->get_manufacturer()) {
j["manipulator"] = *manufacturer;
}
if (auto product = (it.second)->get_product()) {
j["product"] = *product;
}
if (!j.empty()) {
json["devices"].push_back(j);
}
}
std::ofstream stream(constants::get_devices_json_file_path());
if (stream) {
stream << std::setw(4) << json << std::endl;
chmod(constants::get_devices_json_file_path(), 0644);
}
}
void cancel_grab_timer(void) {
if (grab_timer_) {
dispatch_source_cancel(grab_timer_);
dispatch_release(grab_timer_);
grab_timer_ = 0;
}
}
manipulator::event_manipulator& event_manipulator_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<iopm_client> iopm_client_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
std::mutex hids_mutex_;
dispatch_queue_t _Nonnull queue_;
dispatch_source_t _Nullable grab_timer_;
std::mutex grab_mutex_;
std::atomic<mode> mode_;
std::atomic<bool> grabbed_;
std::mutex suspend_mutex_;
bool suspended_;
};
<commit_msg>update devices.json<commit_after>#pragma once
#include "apple_hid_usage_tables.hpp"
#include "constants.hpp"
#include "event_manipulator.hpp"
#include "human_interface_device.hpp"
#include "iokit_utility.hpp"
#include "iopm_client.hpp"
#include "logger.hpp"
#include "manipulator.hpp"
#include "types.hpp"
#include <IOKit/hid/IOHIDManager.h>
#include <fstream>
#include <json/json.hpp>
#include <thread>
#include <time.h>
class device_grabber final {
public:
device_grabber(const device_grabber&) = delete;
device_grabber(manipulator::event_manipulator& event_manipulator) : event_manipulator_(event_manipulator),
queue_(dispatch_queue_create(nullptr, nullptr)),
grab_timer_(0),
mode_(mode::observing),
grabbed_(false),
suspended_(false) {
manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (!manager_) {
logger::get_logger().error("{0}: failed to IOHIDManagerCreate", __PRETTY_FUNCTION__);
return;
}
auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({
std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),
// std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),
// std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),
});
if (device_matching_dictionaries) {
IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);
CFRelease(device_matching_dictionaries);
IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);
IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);
IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
iopm_client_ = std::make_unique<iopm_client>(logger::get_logger(),
std::bind(&device_grabber::iopm_client_callback, this, std::placeholders::_1));
}
~device_grabber(void) {
iopm_client_ = nullptr;
ungrab_devices();
if (manager_) {
IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
CFRelease(manager_);
manager_ = nullptr;
}
dispatch_release(queue_);
}
void grab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::grabbing;
}
auto __block last_warning_message_time = ::time(nullptr) - 1;
cancel_grab_timer();
// ----------------------------------------
// setup grab_timer_
grab_timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue_);
dispatch_source_set_timer(grab_timer_, dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), 0.1 * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(grab_timer_, ^{
std::lock_guard<std::mutex> grab_guard(grab_mutex_);
if (grabbed_) {
return;
}
std::string warning_message;
if (!event_manipulator_.is_ready()) {
warning_message = "event_manipulator_ is not ready. Please wait for a while.";
}
if (warning_message.empty()) {
std::string is_grabbable_warning_message;
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (const auto& it : hids_) {
if (!(it.second)->is_grabbable(is_grabbable_warning_message)) {
warning_message = is_grabbable_warning_message.empty() ? "Some devices are not grabbable." : is_grabbable_warning_message;
break;
}
}
}
if (!warning_message.empty()) {
auto time = ::time(nullptr);
if (last_warning_message_time != time) {
last_warning_message_time = time;
logger::get_logger().warn(warning_message);
}
return;
}
// ----------------------------------------
// grab devices
grabbed_ = true;
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
unobserve(*(it.second));
grab(*(it.second));
}
}
event_manipulator_.reset();
event_manipulator_.grab_mouse_events();
logger::get_logger().info("Connected devices are grabbed");
cancel_grab_timer();
});
dispatch_resume(grab_timer_);
}
void ungrab_devices(bool change_mode = true) {
std::lock_guard<std::mutex> guard(grab_mutex_);
if (change_mode) {
mode_ = mode::observing;
}
if (!grabbed_) {
return;
}
grabbed_ = false;
cancel_grab_timer();
{
std::lock_guard<std::mutex> hids_guard(hids_mutex_);
for (auto&& it : hids_) {
ungrab(*(it.second));
observe(*(it.second));
}
}
event_manipulator_.ungrab_mouse_events();
event_manipulator_.reset();
logger::get_logger().info("Connected devices are ungrabbed");
}
void suspend(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (!suspended_) {
logger::get_logger().info("device_grabber::suspend");
suspended_ = true;
if (mode_ == mode::grabbing) {
ungrab_devices(false);
}
}
}
void resume(void) {
std::lock_guard<std::mutex> guard(suspend_mutex_);
if (suspended_) {
logger::get_logger().info("device_grabber::resume");
suspended_ = false;
if (mode_ == mode::grabbing) {
grab_devices(false);
}
}
}
void set_caps_lock_led_state(krbn::led_state state) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
(it.second)->set_caps_lock_led_state(state);
}
}
private:
enum class mode {
observing,
grabbing,
};
void iopm_client_callback(uint32_t message_type) {
switch (message_type) {
case kIOMessageSystemWillSleep:
suspend();
break;
case kIOMessageSystemWillPowerOn:
resume();
break;
default:
break;
}
}
static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_matching_callback(device);
}
void device_matching_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_matching_device(logger::get_logger(), device);
auto dev = std::make_unique<human_interface_device>(logger::get_logger(), device);
// ----------------------------------------
if (grabbed_) {
grab(*dev);
} else {
observe(*dev);
}
{
std::lock_guard<std::mutex> guard(hids_mutex_);
hids_[device] = std::move(dev);
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
}
static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<device_grabber*>(context);
if (!self) {
return;
}
self->device_removal_callback(device);
}
void device_removal_callback(IOHIDDeviceRef _Nonnull device) {
if (!device) {
return;
}
iokit_utility::log_removal_device(logger::get_logger(), device);
{
std::lock_guard<std::mutex> guard(hids_mutex_);
auto it = hids_.find(device);
if (it != hids_.end()) {
auto& dev = it->second;
if (dev) {
hids_.erase(it);
}
}
}
output_devices_json();
if (is_pointing_device_connected()) {
event_manipulator_.create_virtual_hid_manager_client();
} else {
event_manipulator_.release_virtual_hid_manager_client();
}
event_manipulator_.stop_key_repeat();
}
void observe(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
human_interface_device::value_callback callback;
hid.observe(callback);
}
void unobserve(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
hid.unobserve();
}
void grab(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
// seize device
hid.grab(std::bind(&device_grabber::value_callback,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3,
std::placeholders::_4,
std::placeholders::_5,
std::placeholders::_6));
// set keyboard led
event_manipulator_.refresh_caps_lock_led();
}
void ungrab(human_interface_device& hid) {
auto manufacturer = hid.get_manufacturer();
if (manufacturer && *manufacturer == "pqrs.org") {
return;
}
hid.ungrab();
}
void value_callback(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value) {
if (!grabbed_) {
return;
}
auto device_registry_entry_id = manipulator::device_registry_entry_id(device.get_registry_entry_id());
if (auto key_code = krbn::types::get_key_code(usage_page, usage)) {
bool pressed = integer_value;
event_manipulator_.handle_keyboard_event(device_registry_entry_id, *key_code, pressed);
} else if (auto pointing_button = krbn::types::get_pointing_button(usage_page, usage)) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::button,
*pointing_button,
integer_value);
} else {
switch (usage_page) {
case kHIDPage_GenericDesktop:
if (usage == kHIDUsage_GD_X) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::x,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Y) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::y,
boost::none,
integer_value);
}
if (usage == kHIDUsage_GD_Wheel) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::vertical_wheel,
boost::none,
integer_value);
}
break;
case kHIDPage_Consumer:
if (usage == kHIDUsage_Csmr_ACPan) {
event_manipulator_.handle_pointing_event(device_registry_entry_id,
krbn::pointing_event::horizontal_wheel,
boost::none,
integer_value);
}
break;
default:
break;
}
}
// reset modifier_flags state if all keys are released.
if (get_all_devices_pressed_keys_count() == 0) {
event_manipulator_.reset_modifier_flag_state();
event_manipulator_.reset_pointing_button_state();
}
}
size_t get_all_devices_pressed_keys_count(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
size_t total = 0;
for (const auto& it : hids_) {
total += (it.second)->get_pressed_keys_count();
}
return total;
}
bool is_keyboard_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_keyboard()) {
return true;
}
}
return false;
}
bool is_pointing_device_connected(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
for (const auto& it : hids_) {
if ((it.second)->is_pointing_device()) {
return true;
}
}
return false;
}
void output_devices_json(void) {
std::lock_guard<std::mutex> guard(hids_mutex_);
nlohmann::json json;
json = nlohmann::json::array();
for (const auto& it : hids_) {
nlohmann::json j({});
if (auto vendor_id = (it.second)->get_vendor_id()) {
j["vendor_id"] = *vendor_id;
}
if (auto product_id = (it.second)->get_product_id()) {
j["product_id"] = *product_id;
}
if (auto manufacturer = (it.second)->get_manufacturer()) {
j["manipulator"] = *manufacturer;
}
if (auto product = (it.second)->get_product()) {
j["product"] = *product;
}
if (!j.empty()) {
json.push_back(j);
}
}
std::ofstream stream(constants::get_devices_json_file_path());
if (stream) {
stream << std::setw(4) << json << std::endl;
chmod(constants::get_devices_json_file_path(), 0644);
}
}
void cancel_grab_timer(void) {
if (grab_timer_) {
dispatch_source_cancel(grab_timer_);
dispatch_release(grab_timer_);
grab_timer_ = 0;
}
}
manipulator::event_manipulator& event_manipulator_;
IOHIDManagerRef _Nullable manager_;
std::unique_ptr<iopm_client> iopm_client_;
std::unordered_map<IOHIDDeviceRef, std::unique_ptr<human_interface_device>> hids_;
std::mutex hids_mutex_;
dispatch_queue_t _Nonnull queue_;
dispatch_source_t _Nullable grab_timer_;
std::mutex grab_mutex_;
std::atomic<mode> mode_;
std::atomic<bool> grabbed_;
std::mutex suspend_mutex_;
bool suspended_;
};
<|endoftext|> |
<commit_before>#include "FlipScrollWheel.hpp"
#include "EventOutputQueue.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
FlipScrollWheel::FlipScrollWheel(void) : flipHorizontalScroll_(false), flipVerticalScroll_(false)
{}
FlipScrollWheel::~FlipScrollWheel(void)
{}
void
FlipScrollWheel::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_OPTION:
{
/* */ if (Option::FLIPSCROLLWHEEL_HORIZONTAL == newval) {
flipHorizontalScroll_ = true;
} else if (Option::FLIPSCROLLWHEEL_VERTICAL == newval) {
flipVerticalScroll_ = true;
} else {
IOLOG_ERROR("FlipScrollWheel::add unknown option:%d\n", newval);
}
break;
}
default:
IOLOG_ERROR("FlipScrollWheel::add invalid datatype:%d\n", datatype);
break;
}
}
bool
FlipScrollWheel::remap(RemapPointingParams_scroll& remapParams)
{
remapParams.isremapped = true;
short da1 = remapParams.params.deltaAxis1;
short da2 = remapParams.params.deltaAxis2;
short da3 = remapParams.params.deltaAxis3;
IOFixed fd1 = remapParams.params.fixedDelta1;
IOFixed fd2 = remapParams.params.fixedDelta2;
IOFixed fd3 = remapParams.params.fixedDelta3;
SInt32 pd1 = remapParams.params.pointDelta1;
SInt32 pd2 = remapParams.params.pointDelta2;
SInt32 pd3 = remapParams.params.pointDelta3;
if (flipHorizontalScroll_) {
da1 = -da1;
fd1 = -fd1;
pd1 = -pd1;
}
if (flipVerticalScroll_) {
da2 = -da2;
fd2 = -fd2;
pd2 = -pd2;
}
Params_ScrollWheelEventCallback::auto_ptr ptr(Params_ScrollWheelEventCallback::alloc(da1, da2, da3,
fd1, fd2, fd3,
pd1, pd2, pd3,
remapParams.params.options));
if (ptr) {
EventOutputQueue::FireScrollWheel::fire(*ptr);
}
return true;
}
}
}
<commit_msg>fixed flip direction<commit_after>#include "FlipScrollWheel.hpp"
#include "EventOutputQueue.hpp"
namespace org_pqrs_KeyRemap4MacBook {
namespace RemapFunc {
FlipScrollWheel::FlipScrollWheel(void) : flipHorizontalScroll_(false), flipVerticalScroll_(false)
{}
FlipScrollWheel::~FlipScrollWheel(void)
{}
void
FlipScrollWheel::add(unsigned int datatype, unsigned int newval)
{
switch (datatype) {
case BRIDGE_DATATYPE_OPTION:
{
/* */ if (Option::FLIPSCROLLWHEEL_HORIZONTAL == newval) {
flipHorizontalScroll_ = true;
} else if (Option::FLIPSCROLLWHEEL_VERTICAL == newval) {
flipVerticalScroll_ = true;
} else {
IOLOG_ERROR("FlipScrollWheel::add unknown option:%d\n", newval);
}
break;
}
default:
IOLOG_ERROR("FlipScrollWheel::add invalid datatype:%d\n", datatype);
break;
}
}
bool
FlipScrollWheel::remap(RemapPointingParams_scroll& remapParams)
{
if (remapParams.isremapped) return false;
remapParams.isremapped = true;
short da1 = remapParams.params.deltaAxis1;
short da2 = remapParams.params.deltaAxis2;
short da3 = remapParams.params.deltaAxis3;
IOFixed fd1 = remapParams.params.fixedDelta1;
IOFixed fd2 = remapParams.params.fixedDelta2;
IOFixed fd3 = remapParams.params.fixedDelta3;
SInt32 pd1 = remapParams.params.pointDelta1;
SInt32 pd2 = remapParams.params.pointDelta2;
SInt32 pd3 = remapParams.params.pointDelta3;
if (flipHorizontalScroll_) {
da2 = -da2;
fd2 = -fd2;
pd2 = -pd2;
}
if (flipVerticalScroll_) {
da1 = -da1;
fd1 = -fd1;
pd1 = -pd1;
}
Params_ScrollWheelEventCallback::auto_ptr ptr(Params_ScrollWheelEventCallback::alloc(da1, da2, da3,
fd1, fd2, fd3,
pd1, pd2, pd3,
remapParams.params.options));
if (ptr) {
EventOutputQueue::FireScrollWheel::fire(*ptr);
}
return true;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2013 DNAnexus, Inc.
//
// This file is part of dx-toolkit (DNAnexus platform client libraries).
//
// 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 "SimpleHttpHeaders.h"
namespace dx {
void HttpHeaders::appendHeaderString(const std::string &s) {
using namespace std;
using namespace HttpHelperUtils;
// See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
pair<string, std::string> h = splitOnFirstColon(s);
h.second = stripWhitespaces(h.second);
// If header field-name is already present, append the content with ","
if (isPresent(h.first))
header[h.first] += "," + h.second;
else
header[h.first] = h.second;
}
std::vector<std::string> HttpHeaders::getAllHeadersAsVector() const {
using namespace std;
vector<string> out;
for (map<string,string>::const_iterator it = header.begin(); it != header.end(); ++it)
out.push_back(it->first + ": " + it->second);
return out;
}
}
<commit_msg>Adding a missing file from the commit: 08fb11<commit_after>// Copyright (C) 2013 DNAnexus, Inc.
//
// This file is part of dx-toolkit (DNAnexus platform client libraries).
//
// 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 "SimpleHttpHeaders.h"
#include <boost/algorithm/string/predicate.hpp> // for case-insensitive string comparison
namespace dx {
using namespace std;
void HttpHeaders::appendHeaderString(const string &s) {
using namespace std;
using namespace HttpHelperUtils;
// See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
pair<string, string> h = splitOnFirstColon(s);
h.second = stripWhitespaces(h.second);
// If header field-name is already present, append the content with ","
if (isPresent(h.first))
header[h.first] += "," + h.second;
else
header[h.first] = h.second;
}
vector<string> HttpHeaders::getAllHeadersAsVector() const {
using namespace std;
vector<string> out;
for (map<string,string>::const_iterator it = header.begin(); it != header.end(); ++it)
out.push_back(it->first + ": " + it->second);
return out;
}
// get value of a header (case-insensitive match)
bool HttpHeaders::getHeaderString(const string &key, string &val) {
for (map<string,string>::const_iterator it = header.begin(); it != header.end(); ++it) {
if (boost::iequals(it->first, key)) {
val = it->second;
return true;
}
}
return false;
}
}
<|endoftext|> |
<commit_before>///
/// @file pi_deleglise_rivat3.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting
/// algorithm with the improvements of Deleglise and Rivat.
/// This version uses compression (see FactorTable & PiTable)
/// to reduce the memory usage.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Calculate the contribution of the special leaves.
/// @see ../docs/computing-special-leaves.md
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t pi_y,
int64_t c,
vector<int32_t>& primes)
{
int64_t limit = x / y + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
int64_t S2_result = 0;
BitSieve sieve(segment_size);
FactorTable factors(y);
PiTable pi(y);
vector<int32_t> counters(segment_size);
vector<int64_t> next(primes.begin(), primes.end());
vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 2;
sieve.memset(low);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime * 2)
sieve.unset(k - low);
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b < pi_y
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b < pi_sqrty; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
factors.to_index(&min_m);
factors.to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_result -= factors.mu(m) * phi_xn;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b < pi_y; b++)
{
int64_t prime = primes[b];
int64_t l = pi(min(x / (prime * low), y));
if (prime >= primes[l])
goto next_segment;
int64_t min_m = max(x / (prime * high), y / prime);
min_m = in_between(prime, min_m, y);
int64_t min_trivial_leaf = pi(min(x / (prime * prime), y));
int64_t min_clustered_easy_leaf = pi(min(isqrt(x / prime), y));
int64_t min_sparse_easy_leaf = pi(min(z / prime, y));
int64_t min_hard_leaf = pi(min_m);
min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);
// For max(x / primes[b]^2, primes[b]) < primes[l] <= y
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (l > min_trivial_leaf)
{
S2_result += l - min_trivial_leaf;
l = min_trivial_leaf;
}
// For max(sqrt(x / primes[b]), primes[b]) < primes[l] <= x / primes[b]^2
// Find all clustered easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi(x / n) - b + 2
// And phi(x / n, b - 1) == phi(x / m, b - 1)
while (l > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t phi_xn = pi(x / n) - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t l2 = pi(x / m);
l2 = max(l2, min_clustered_easy_leaf);
S2_result += phi_xn * (l - l2);
l = l2;
}
// For max(z / primes[b], primes[b]) < primes[l] <= sqrt(x / primes[b])
// Find all sparse easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi(x / n) - b + 2
for (; l > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
S2_result += pi(xn) - b + 2;
}
// For max(x / (primes[b] * high), primes[b]) < primes[l] <= z / primes[b]
// Find all hard leaves which satisfy:
// low <= (x / n) < high
for (; l > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_result += phi_xn;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_result;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log log x) space.
///
int64_t pi_deleglise_rivat3(int64_t x)
{
if (x < 2)
return 0;
// alpha is a tuning factor
double d = (double) x;
double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
int64_t x13 = iroot<3>(x);
int64_t y = (int64_t) (x13 * alpha);
int64_t z = x / (int64_t) (x13 * sqrt(alpha));
vector<int32_t> mu = make_moebius(y);
vector<int32_t> lpf = make_least_prime_factor(y);
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
int64_t pi_y = primes.size() - 1;
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, lpf , mu);
int64_t s2 = S2(x, y, z, pi_y, c, primes);
int64_t p2 = P2(x, y, 1);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<commit_msg>Use FactorTable instead of lpf and mu<commit_after>///
/// @file pi_deleglise_rivat3.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting
/// algorithm with the improvements of Deleglise and Rivat.
/// This version uses compression (see FactorTable & PiTable)
/// to reduce the memory usage.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <PiTable.hpp>
#include <FactorTable.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>
#include <stdint.h>
#include <algorithm>
#include <vector>
using namespace std;
using namespace primecount;
namespace {
/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
int64_t segment_size = sieve.size();
int64_t k = next_multiple;
for (; k < high; k += prime * 2)
{
if (sieve[k - low])
{
sieve.unset(k - low);
cnt_update(counters, k - low, segment_size);
}
}
next_multiple = k;
}
/// Calculate the contribution of the special leaves.
/// @see ../docs/computing-special-leaves.md
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
int64_t y,
int64_t z,
int64_t pi_y,
int64_t c,
vector<int32_t>& primes,
FactorTable& factors)
{
int64_t limit = x / y + 1;
int64_t segment_size = next_power_of_2(isqrt(limit));
int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
int64_t S2_result = 0;
BitSieve sieve(segment_size);
PiTable pi(y);
vector<int32_t> counters(segment_size);
vector<int64_t> next(primes.begin(), primes.end());
vector<int64_t> phi(primes.size(), 0);
// Segmented sieve of Eratosthenes
for (int64_t low = 1; low < limit; low += segment_size)
{
// Current segment = interval [low, high[
int64_t high = min(low + segment_size, limit);
int64_t b = 2;
sieve.memset(low);
// phi(y, b) nodes with b <= c do not contribute to S2, so we
// simply sieve out the multiples of the first c primes
for (; b <= c; b++)
{
int64_t k = next[b];
for (int64_t prime = primes[b]; k < high; k += prime * 2)
sieve.unset(k - low);
next[b] = k;
}
// Initialize special tree data structure from sieve
cnt_finit(sieve, counters, segment_size);
// For c + 1 <= b < pi_y
// Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
// which satisfy: low <= (x / n) < high
for (; b < pi_sqrty; b++)
{
int64_t prime = primes[b];
int64_t min_m = max(x / (prime * high), y / prime);
int64_t max_m = min(x / (prime * low), y);
if (prime >= max_m)
goto next_segment;
FactorTable::to_index(&min_m);
FactorTable::to_index(&max_m);
for (int64_t m = max_m; m > min_m; m--)
{
if (prime < factors.lpf(m))
{
int64_t n = prime * factors.get_number(m);
int64_t count = cnt_query(counters, (x / n) - low);
int64_t phi_xn = phi[b] + count;
S2_result -= factors.mu(m) * phi_xn;
}
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
// For pi_sqrty <= b < pi_y
// Find all special leaves: n = primes[b] * primes[l]
// which satisfy: low <= (x / n) < high
for (; b < pi_y; b++)
{
int64_t prime = primes[b];
int64_t l = pi(min(x / (prime * low), y));
if (prime >= primes[l])
goto next_segment;
int64_t min_m = max(x / (prime * high), y / prime);
min_m = in_between(prime, min_m, y);
int64_t min_trivial_leaf = pi(min(x / (prime * prime), y));
int64_t min_clustered_easy_leaf = pi(min(isqrt(x / prime), y));
int64_t min_sparse_easy_leaf = pi(min(z / prime, y));
int64_t min_hard_leaf = pi(min_m);
min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf);
min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf);
// For max(x / primes[b]^2, primes[b]) < primes[l] <= y
// Find all trivial leaves which satisfy:
// phi(x / (primes[b] * primes[l]), b - 1) = 1
if (l > min_trivial_leaf)
{
S2_result += l - min_trivial_leaf;
l = min_trivial_leaf;
}
// For max(sqrt(x / primes[b]), primes[b]) < primes[l] <= x / primes[b]^2
// Find all clustered easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi(x / n) - b + 2
// And phi(x / n, b - 1) == phi(x / m, b - 1)
while (l > min_clustered_easy_leaf)
{
int64_t n = prime * primes[l];
int64_t phi_xn = pi(x / n) - b + 2;
int64_t m = prime * primes[b + phi_xn - 1];
int64_t l2 = pi(x / m);
l2 = max(l2, min_clustered_easy_leaf);
S2_result += phi_xn * (l - l2);
l = l2;
}
// For max(z / primes[b], primes[b]) < primes[l] <= sqrt(x / primes[b])
// Find all sparse easy leaves which satisfy:
// x / n <= y such that phi(x / n, b - 1) = pi(x / n) - b + 2
for (; l > min_sparse_easy_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
S2_result += pi(xn) - b + 2;
}
// For max(x / (primes[b] * high), primes[b]) < primes[l] <= z / primes[b]
// Find all hard leaves which satisfy:
// low <= (x / n) < high
for (; l > min_hard_leaf; l--)
{
int64_t n = prime * primes[l];
int64_t xn = x / n;
int64_t count = cnt_query(counters, xn - low);
int64_t phi_xn = phi[b] + count;
S2_result += phi_xn;
}
phi[b] += cnt_query(counters, (high - 1) - low);
cross_off(prime, low, high, next[b], sieve, counters);
}
next_segment:;
}
return S2_result;
}
} // namespace
namespace primecount {
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log log x) space.
///
int64_t pi_deleglise_rivat3(int64_t x)
{
if (x < 2)
return 0;
// alpha is a tuning factor
double d = (double) x;
double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
int64_t x13 = iroot<3>(x);
int64_t y = (int64_t) (x13 * alpha);
int64_t z = (int64_t) (x / x13 * sqrt(alpha));
vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_primes(y, &primes);
FactorTable factors(y);
int64_t pi_y = primes.size() - 1;
int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
int64_t s1 = S1(x, y, c, primes, factors);
int64_t s2 = S2(x, y, z, pi_y, c, primes, factors);
int64_t p2 = P2(x, y, 1);
int64_t phi = s1 + s2;
int64_t sum = phi + pi_y - 1 - p2;
return sum;
}
} // namespace primecount
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// The AliDAQ class is responsible for handling all the information about //
// Data Acquisition configuration. It defines the detector indexing, //
// the number of DDLs and LDCs per detector. //
// The number of LDCs per detector is used only in the simulation in order //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the //
// rest of the aliroot code. //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as: //
// Equipment ID = (detectorID << 8) + DDLIndex //
// where the detectorID is given by fgkDetectorName array and DDLIndex is //
// the index of the corresponding DDL inside the detector partition. //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or //
// at least without big gaps in between. //
// The sub-detector code use only this class in the simulation and reading //
// of the raw data. //
// //
// cvetan.cheshkov@cern.ch 2006/06/09 //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TString.h>
#include "AliDAQ.h"
#include "AliLog.h"
ClassImp(AliDAQ)
const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
"ITSSPD",
"ITSSDD",
"ITSSSD",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUONTRK",
"MUONTRG",
"FMD",
"T0",
"VZERO", // Name to be changed to V0 ?
"ZDC",
"ACORDE",
"TRG",
"EMCAL",
"DAQ_TEST",
"HLT"
};
Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
20,
24,
16,
216,
18,
72,
20,
20,
10,
6,
20,
2,
3,
1,
1,
1,
1,
1,
24,
1,
10
};
Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
4,
4,
4,
36,
3,
12,
4,
4,
2,
1,
4,
1,
1,
0.5,
0.5,
1,
1,
1,
4,
1,
5
};
const char* AliDAQ::fgkOfflineModuleName[AliDAQ::kNDetectors] = {
"ITS",
"ITS",
"ITS",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUON",
"MUON",
"FMD",
"T0",
"VZERO",
"ZDC",
"ACORDE",
"CTP",
"EMCAL",
"",
"HLT"
};
const char* AliDAQ::fgkOnlineName[AliDAQ::kNDetectors] = {
"SPD",
"SDD",
"SSD",
"TPC",
"TRD",
"TOF",
"HMP",
"PHS",
"CPV",
"PMD",
"MCH",
"MTR",
"FMD",
"T00",
"V00",
"ZDC",
"ACO",
"TRI",
"EMC",
"TST",
"HLT"
};
AliDAQ::AliDAQ(const AliDAQ& source) :
TObject(source)
{
// Copy constructor
// Nothing to be done
}
AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
// Assignment operator
// Nothing to be done
return *this;
}
Int_t AliDAQ::DetectorID(const char *detectorName)
{
// Return the detector index
// corresponding to a given
// detector name
TString detStr = detectorName;
Int_t iDet;
for(iDet = 0; iDet < kNDetectors; iDet++) {
if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
break;
}
if (iDet == kNDetectors) {
AliErrorClass(Form("Invalid detector name: %s !",detectorName));
return -1;
}
return iDet;
}
const char *AliDAQ::DetectorName(Int_t detectorID)
{
// Returns the name of particular
// detector identified by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkDetectorName[detectorID];
}
Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
// Returns the DDL ID offset
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlIDOffset(detectorID);
}
Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
// Returns the DDL ID offset
// for a given detector identified
// by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
// HLT has a DDL offset = 30
if (detectorID == (kNDetectors-1)) return (kHLTId << 8);
return (detectorID << 8);
}
const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector name for
// a given DDL ID
ddlIndex = -1;
Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
if (detectorID < 0)
return "";
return DetectorName(detectorID);
}
Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector ID and
// the ddl index within the
// detector range for
// a given input DDL ID
Int_t detectorID = ddlID >> 8;
// HLT
if (detectorID == kHLTId) detectorID = kNDetectors-1;
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
ddlIndex = ddlID & 0xFF;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
ddlIndex = -1;
return -1;
}
return detectorID;
}
Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlID(detectorID,ddlIndex);
}
Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return -1;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return -1;
}
ddlID += ddlIndex;
return ddlID;
}
const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return DdlFileName(detectorID,ddlIndex);
}
const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return "";
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return "";
}
ddlID += ddlIndex;
static TString fileName;
fileName = DetectorName(detectorID);
fileName += "_";
fileName += ddlID;
fileName += ".ddl";
return fileName.Data();
}
Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfDdls(detectorID);
}
Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfDdls[detectorID];
}
Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfLdcs(detectorID);
}
Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfLdcs[detectorID];
}
void AliDAQ::PrintConfig()
{
// Print the DAQ configuration
// for all the detectors
printf("===================================================================================================\n"
"| ALICE Data Acquisition Configuration |\n"
"===================================================================================================\n"
"| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs | Online Name | AliRoot Module |\n"
"===================================================================================================\n");
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
printf("|%11d |%13s |%10d |%9d |%9.1f |%11s |%14s |\n",
iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet),
OnlineName(iDet),OfflineModuleName(iDet));
}
printf("===================================================================================================\n");
}
const char *AliDAQ::ListOfTriggeredDetectors(UInt_t detectorPattern)
{
// Returns a string with the list of
// active detectors. The input is the
// trigger pattern word contained in
// the raw-data event header.
static TString detList;
detList = "";
for(Int_t iDet = 0; iDet < (kNDetectors-1); iDet++) {
if ((detectorPattern >> iDet) & 0x1) {
detList += fgkDetectorName[iDet];
detList += " ";
}
}
// Always remember HLT
if ((detectorPattern >> kHLTId) & 0x1) detList += fgkDetectorName[kNDetectors-1];
return detList.Data();
}
UInt_t AliDAQ::DetectorPattern(const char *detectorList)
{
// Returns a 32-bit word containing the
// the detector pattern corresponding to a given
// list of detectors
UInt_t pattern = 0;
TString detList = detectorList;
for(Int_t iDet = 0; iDet < (kNDetectors-1); iDet++) {
TString det = fgkDetectorName[iDet];
if((detList.CompareTo(det) == 0) ||
detList.BeginsWith(det) ||
detList.EndsWith(det) ||
detList.Contains( " "+det+" " )) pattern |= (1 << iDet) ;
}
// HLT
TString hltDet = fgkDetectorName[kNDetectors-1];
if((detList.CompareTo(hltDet) == 0) ||
detList.BeginsWith(hltDet) ||
detList.EndsWith(hltDet) ||
detList.Contains( " "+hltDet+" " )) pattern |= (1 << kHLTId) ;
return pattern;
}
const char *AliDAQ::OfflineModuleName(const char *detectorName)
{
// Returns the name of the offline module
// for a given detector (online naming convention)
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return OfflineModuleName(detectorID);
}
const char *AliDAQ::OfflineModuleName(Int_t detectorID)
{
// Returns the name of the offline module
// for a given detector (online naming convention)
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkOfflineModuleName[detectorID];
}
const char *AliDAQ::OnlineName(const char *detectorName)
{
// Returns the name of the online detector name (3 characters)
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return OnlineName(detectorID);
}
const char *AliDAQ::OnlineName(Int_t detectorID)
{
// Returns the name of the online detector name (3 characters)
// for a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkOnlineName[detectorID];
}
<commit_msg>Bug #55851: Inclusion of J-Cal DDLs + EMCAL and J-Cal STU DDLs. This makes a total of 48 DDLs for EMCAL (was 24). And we put the number of LDCs (not really used offline) to 8 (was 4).<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// The AliDAQ class is responsible for handling all the information about //
// Data Acquisition configuration. It defines the detector indexing, //
// the number of DDLs and LDCs per detector. //
// The number of LDCs per detector is used only in the simulation in order //
// to define the configuration of the dateStream application. Therefore the //
// numbers in the corresponding array can be changed without affecting the //
// rest of the aliroot code. //
// The equipment ID (DDL ID) is an integer (32-bit) number defined as: //
// Equipment ID = (detectorID << 8) + DDLIndex //
// where the detectorID is given by fgkDetectorName array and DDLIndex is //
// the index of the corresponding DDL inside the detector partition. //
// Due to DAQ/HLT limitations, the ddl indexes should be consequtive, or //
// at least without big gaps in between. //
// The sub-detector code use only this class in the simulation and reading //
// of the raw data. //
// //
// cvetan.cheshkov@cern.ch 2006/06/09 //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TClass.h>
#include <TString.h>
#include "AliDAQ.h"
#include "AliLog.h"
ClassImp(AliDAQ)
const char* AliDAQ::fgkDetectorName[AliDAQ::kNDetectors] = {
"ITSSPD",
"ITSSDD",
"ITSSSD",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUONTRK",
"MUONTRG",
"FMD",
"T0",
"VZERO", // Name to be changed to V0 ?
"ZDC",
"ACORDE",
"TRG",
"EMCAL",
"DAQ_TEST",
"HLT"
};
Int_t AliDAQ::fgkNumberOfDdls[AliDAQ::kNDetectors] = {
20,
24,
16,
216,
18,
72,
20,
20,
10,
6,
20,
2,
3,
1,
1,
1,
1,
1,
46,
1,
10
};
Float_t AliDAQ::fgkNumberOfLdcs[AliDAQ::kNDetectors] = {
4,
4,
4,
36,
3,
12,
4,
4,
2,
1,
4,
1,
1,
0.5,
0.5,
1,
1,
1,
8,
1,
5
};
const char* AliDAQ::fgkOfflineModuleName[AliDAQ::kNDetectors] = {
"ITS",
"ITS",
"ITS",
"TPC",
"TRD",
"TOF",
"HMPID",
"PHOS",
"CPV",
"PMD",
"MUON",
"MUON",
"FMD",
"T0",
"VZERO",
"ZDC",
"ACORDE",
"CTP",
"EMCAL",
"",
"HLT"
};
const char* AliDAQ::fgkOnlineName[AliDAQ::kNDetectors] = {
"SPD",
"SDD",
"SSD",
"TPC",
"TRD",
"TOF",
"HMP",
"PHS",
"CPV",
"PMD",
"MCH",
"MTR",
"FMD",
"T00",
"V00",
"ZDC",
"ACO",
"TRI",
"EMC",
"TST",
"HLT"
};
AliDAQ::AliDAQ(const AliDAQ& source) :
TObject(source)
{
// Copy constructor
// Nothing to be done
}
AliDAQ& AliDAQ::operator = (const AliDAQ& /* source */)
{
// Assignment operator
// Nothing to be done
return *this;
}
Int_t AliDAQ::DetectorID(const char *detectorName)
{
// Return the detector index
// corresponding to a given
// detector name
TString detStr = detectorName;
Int_t iDet;
for(iDet = 0; iDet < kNDetectors; iDet++) {
if (detStr.CompareTo(fgkDetectorName[iDet],TString::kIgnoreCase) == 0)
break;
}
if (iDet == kNDetectors) {
AliErrorClass(Form("Invalid detector name: %s !",detectorName));
return -1;
}
return iDet;
}
const char *AliDAQ::DetectorName(Int_t detectorID)
{
// Returns the name of particular
// detector identified by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkDetectorName[detectorID];
}
Int_t AliDAQ::DdlIDOffset(const char *detectorName)
{
// Returns the DDL ID offset
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlIDOffset(detectorID);
}
Int_t AliDAQ::DdlIDOffset(Int_t detectorID)
{
// Returns the DDL ID offset
// for a given detector identified
// by its index
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
// HLT has a DDL offset = 30
if (detectorID == (kNDetectors-1)) return (kHLTId << 8);
return (detectorID << 8);
}
const char *AliDAQ::DetectorNameFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector name for
// a given DDL ID
ddlIndex = -1;
Int_t detectorID = DetectorIDFromDdlID(ddlID,ddlIndex);
if (detectorID < 0)
return "";
return DetectorName(detectorID);
}
Int_t AliDAQ::DetectorIDFromDdlID(Int_t ddlID,Int_t &ddlIndex)
{
// Returns the detector ID and
// the ddl index within the
// detector range for
// a given input DDL ID
Int_t detectorID = ddlID >> 8;
// HLT
if (detectorID == kHLTId) detectorID = kNDetectors-1;
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
ddlIndex = ddlID & 0xFF;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
ddlIndex = -1;
return -1;
}
return detectorID;
}
Int_t AliDAQ::DdlID(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return DdlID(detectorID,ddlIndex);
}
Int_t AliDAQ::DdlID(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL ID starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return -1;
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return -1;
}
ddlID += ddlIndex;
return ddlID;
}
const char *AliDAQ::DdlFileName(const char *detectorName, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector name and the DDL
// index inside the detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return DdlFileName(detectorID,ddlIndex);
}
const char *AliDAQ::DdlFileName(Int_t detectorID, Int_t ddlIndex)
{
// Returns the DDL file name
// (used in the simulation) starting from
// the detector ID and the DDL
// index inside the detector
Int_t ddlID = DdlIDOffset(detectorID);
if (ddlID < 0)
return "";
if (ddlIndex >= fgkNumberOfDdls[detectorID]) {
AliErrorClass(Form("Invalid DDL index %d (%d -> %d) for detector %d",
ddlIndex,0,fgkNumberOfDdls[detectorID],detectorID));
return "";
}
ddlID += ddlIndex;
static TString fileName;
fileName = DetectorName(detectorID);
fileName += "_";
fileName += ddlID;
fileName += ".ddl";
return fileName.Data();
}
Int_t AliDAQ::NumberOfDdls(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfDdls(detectorID);
}
Int_t AliDAQ::NumberOfDdls(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfDdls[detectorID];
}
Float_t AliDAQ::NumberOfLdcs(const char *detectorName)
{
// Returns the number of DDLs for
// a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return -1;
return NumberOfLdcs(detectorID);
}
Float_t AliDAQ::NumberOfLdcs(Int_t detectorID)
{
// Returns the number of DDLs for
// a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return -1;
}
return fgkNumberOfLdcs[detectorID];
}
void AliDAQ::PrintConfig()
{
// Print the DAQ configuration
// for all the detectors
printf("===================================================================================================\n"
"| ALICE Data Acquisition Configuration |\n"
"===================================================================================================\n"
"| Detector ID | Detector Name | DDL Offset | # of DDLs | # of LDCs | Online Name | AliRoot Module |\n"
"===================================================================================================\n");
for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
printf("|%11d |%13s |%10d |%9d |%9.1f |%11s |%14s |\n",
iDet,DetectorName(iDet),DdlIDOffset(iDet),NumberOfDdls(iDet),NumberOfLdcs(iDet),
OnlineName(iDet),OfflineModuleName(iDet));
}
printf("===================================================================================================\n");
}
const char *AliDAQ::ListOfTriggeredDetectors(UInt_t detectorPattern)
{
// Returns a string with the list of
// active detectors. The input is the
// trigger pattern word contained in
// the raw-data event header.
static TString detList;
detList = "";
for(Int_t iDet = 0; iDet < (kNDetectors-1); iDet++) {
if ((detectorPattern >> iDet) & 0x1) {
detList += fgkDetectorName[iDet];
detList += " ";
}
}
// Always remember HLT
if ((detectorPattern >> kHLTId) & 0x1) detList += fgkDetectorName[kNDetectors-1];
return detList.Data();
}
UInt_t AliDAQ::DetectorPattern(const char *detectorList)
{
// Returns a 32-bit word containing the
// the detector pattern corresponding to a given
// list of detectors
UInt_t pattern = 0;
TString detList = detectorList;
for(Int_t iDet = 0; iDet < (kNDetectors-1); iDet++) {
TString det = fgkDetectorName[iDet];
if((detList.CompareTo(det) == 0) ||
detList.BeginsWith(det) ||
detList.EndsWith(det) ||
detList.Contains( " "+det+" " )) pattern |= (1 << iDet) ;
}
// HLT
TString hltDet = fgkDetectorName[kNDetectors-1];
if((detList.CompareTo(hltDet) == 0) ||
detList.BeginsWith(hltDet) ||
detList.EndsWith(hltDet) ||
detList.Contains( " "+hltDet+" " )) pattern |= (1 << kHLTId) ;
return pattern;
}
const char *AliDAQ::OfflineModuleName(const char *detectorName)
{
// Returns the name of the offline module
// for a given detector (online naming convention)
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return OfflineModuleName(detectorID);
}
const char *AliDAQ::OfflineModuleName(Int_t detectorID)
{
// Returns the name of the offline module
// for a given detector (online naming convention)
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkOfflineModuleName[detectorID];
}
const char *AliDAQ::OnlineName(const char *detectorName)
{
// Returns the name of the online detector name (3 characters)
// for a given detector
Int_t detectorID = DetectorID(detectorName);
if (detectorID < 0)
return "";
return OnlineName(detectorID);
}
const char *AliDAQ::OnlineName(Int_t detectorID)
{
// Returns the name of the online detector name (3 characters)
// for a given detector
if (detectorID < 0 || detectorID >= kNDetectors) {
AliErrorClass(Form("Invalid detector index: %d (%d -> %d) !",detectorID,0,kNDetectors-1));
return "";
}
return fgkOnlineName[detectorID];
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnord {
namespace util {
using fnordmetric::util::RuntimeException;
CatchAndPrintExceptionHandler::CatchAndPrintExceptionHandler(
Logger* logger) :
logger_(logger) {}
void CatchAndPrintExceptionHandler::onException(
const std::exception& error) const {
logger_->exception("ERROR", "Uncaught exception", error);
}
CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler(
const std::string& message) :
message_(message) {}
void CatchAndAbortExceptionHandler::onException(
const std::exception& error) const {
fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL
try {
auto rte = dynamic_cast<const RuntimeException&>(error);
rte.debugPrint();
} catch (const std::exception& e) {
fprintf(stderr, "Aborting...\n");
}
abort(); // core dump if enabled
}
static std::string globalEHandlerMessage;
static void globalEHandler() {
fprintf(stderr, "%s\n", globalEHandlerMessage.c_str());
try {
throw;
} catch (const std::exception& e) {
try {
auto rte = dynamic_cast<const RuntimeException&>(e);
rte.debugPrint();
exit(1);
} catch (...) {
/* fallthrough */
}
} catch (...) {
/* fallthrough */
}
abort();
}
void CatchAndAbortExceptionHandler::installGlobalHandlers() {
globalEHandlerMessage = message_;
std::set_terminate(&globalEHandler);
std::set_unexpected(&globalEHandler);
}
}
}
<commit_msg>handle all std::exceptions in CatchAndAbortExceptionHandler<commit_after>/**
* This file is part of the "FnordMetric" project
* Copyright (c) 2011-2014 Paul Asmuth, Google Inc.
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <fnordmetric/util/exceptionhandler.h>
#include <fnordmetric/util/runtimeexception.h>
namespace fnord {
namespace util {
using fnordmetric::util::RuntimeException;
CatchAndPrintExceptionHandler::CatchAndPrintExceptionHandler(
Logger* logger) :
logger_(logger) {}
void CatchAndPrintExceptionHandler::onException(
const std::exception& error) const {
logger_->exception("ERROR", "Uncaught exception", error);
}
CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler(
const std::string& message) :
message_(message) {}
void CatchAndAbortExceptionHandler::onException(
const std::exception& error) const {
fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL
try {
auto rte = dynamic_cast<const RuntimeException&>(error);
rte.debugPrint();
} catch (const std::exception& cast_error) {
fprintf(stderr, "foreign exception: %s\n", error.what());
}
fprintf(stderr, "Aborting...\n");
abort(); // core dump if enabled
}
static std::string globalEHandlerMessage;
static void globalEHandler() {
fprintf(stderr, "%s\n", globalEHandlerMessage.c_str());
try {
throw;
} catch (const std::exception& e) {
try {
auto rte = dynamic_cast<const RuntimeException&>(e);
rte.debugPrint();
exit(1);
} catch (...) {
/* fallthrough */
}
} catch (...) {
/* fallthrough */
}
abort();
}
void CatchAndAbortExceptionHandler::installGlobalHandlers() {
globalEHandlerMessage = message_;
std::set_terminate(&globalEHandler);
std::set_unexpected(&globalEHandler);
}
}
}
<|endoftext|> |
<commit_before>#include <cstdio>
#define ELEMENT_COUNT 100000
using namespace std;
int n, d[ELEMENT_COUNT];
int pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
void radix_sort()
{
static int c[10], t[11], _d[ELEMENT_COUNT];
for (int k = 0; k < 8; k++)
{
for (int i = 0; i < 10; i++)
{
c[i] = t[i] = 0;
}
for (int i = 0; i < n; i++)
{
c[d[i] / pow10[k] % 10 + 1]++;
}
for (int i = 1; i < 10; i++)
{
c[i] += c[i - 1];
}
for (int i = 0; i < n; i++)
{
int w = d[i] / pow10[k] % 10;
_d[c[w] + t[w]] = d[i];
t[w]++;
}
for (int i = 0; i < n; i++)
{
d[i] = _d[i];
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &d[i]);
}
radix_sort();
for (int i = 0; i < n; i++)
{
printf("%d\n", d[i]);
}
return 0;
}
<commit_msg>简化代码,提升运行效率<commit_after>#include <cstdio>
#define ELEMENT_COUNT 100000
using namespace std;
int n, d[ELEMENT_COUNT];
int pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
void radix_sort()
{
static int c[10], _d[ELEMENT_COUNT];
for (int k = 0; k < 8; k++)
{
for (int i = 0; i < 10; i++)
{
c[i] = 0;
}
for (int i = 0; i < n; i++)
{
c[d[i] / pow10[k] % 10]++;
}
for (int i = 1; i < 10; i++)
{
c[i] += c[i - 1];
}
for (int i = n - 1; i >= 0; i--)
{
_d[--c[d[i] / pow10[k] % 10]] = d[i];
}
for (int i = 0; i < n; i++)
{
d[i] = _d[i];
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &d[i]);
}
radix_sort();
for (int i = 0; i < n; i++)
{
printf("%d ", d[i]);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
large prime sample for 64-bit arch
make CFLAGS_USER="-DMCL_MAX_OP_BIT_SIZE=768"
*/
#include <mcl/fp.hpp>
#include <cybozu/benchmark.hpp>
typedef mcl::FpT<> Fp;
void test(mcl::fp::Mode mode)
{
printf("test %s\n", mcl::fp::ModeToStr(mode));
std::string pStr = "776259046150354467574489744231251277628443008558348305569526019013025476343188443165439204414323238975243865348565536603085790022057407195722143637520590569602227488010424952775132642815799222412631499596858234375446423426908029627";
Fp::init(pStr, mode);
mpz_class p(pStr);
Fp x = 123456;
Fp::pow(x, x, p);
std::cout << x << std::endl;
CYBOZU_BENCH("mul", Fp::mul, x, x, x);
}
int main()
try
{
test(mcl::fp::FP_GMP);
test(mcl::fp::FP_GMP_MONT);
#ifdef MCL_USE_LLVM
test(mcl::fp::FP_LLVM);
test(mcl::fp::FP_LLVM_MONT);
#endif
} catch (std::exception& e) {
printf("err %s\n", e.what());
puts("make clean");
puts("make CFLAGS_USER=\"-DMCL_MAX_OP_BIT_SIZE=768\"");
return 1;
}
<commit_msg>benchmark of large<commit_after>/*
large prime sample for 64-bit arch
make USE_LLVM=1 CFLAGS_USER="-DMCL_MAX_OP_BIT_SIZE=768"
*/
#include <mcl/fp.hpp>
#include <cybozu/benchmark.hpp>
typedef mcl::FpT<> Fp;
typedef mcl::fp::Unit Unit;
void test(const std::string& pStr, mcl::fp::Mode mode)
{
printf("test %s\n", mcl::fp::ModeToStr(mode));
Fp::init(pStr, mode);
const mcl::fp::Op& op = Fp::getOp();
printf("bitSize=%d\n", (int)Fp::getBitSize());
mpz_class p(pStr);
Fp x = 123456;
Fp::pow(x, x, p);
std::cout << x << std::endl;
const size_t N = 24;
mcl::fp::Unit ux[N], uy[N];
for (size_t i = 0; i < N; i++) {
ux[i] = -i * i + 5;
uy[i] = -i * i + 9;
}
CYBOZU_BENCH("mulPre", op.fpDbl_mulPre, ux, ux, uy);
CYBOZU_BENCH("sqrPre", op.fpDbl_sqrPre, ux, ux);
CYBOZU_BENCH("mont", op.fpDbl_mod, ux, ux);
CYBOZU_BENCH("mul", Fp::mul, x, x, x);
}
void testAll(const std::string& pStr)
{
test(pStr, mcl::fp::FP_GMP);
test(pStr, mcl::fp::FP_GMP_MONT);
#ifdef MCL_USE_LLVM
test(pStr, mcl::fp::FP_LLVM);
test(pStr, mcl::fp::FP_LLVM_MONT);
#endif
}
int main()
try
{
const char *pTbl[] = {
"40347654345107946713373737062547060536401653012956617387979052445947619094013143666088208645002153616185987062074179207",
"776259046150354467574489744231251277628443008558348305569526019013025476343188443165439204414323238975243865348565536603085790022057407195722143637520590569602227488010424952775132642815799222412631499596858234375446423426908029627",
};
testAll(pTbl[0]);
testAll(pTbl[1]);
} catch (std::exception& e) {
printf("err %s\n", e.what());
puts("make clean");
puts("make CFLAGS_USER=\"-DMCL_MAX_OP_BIT_SIZE=768\"");
return 1;
}
<|endoftext|> |
<commit_before>/* The MIT License (MIT)
Copyright (c) 2013 QuantumCD
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 "stdafx.h"
#include <windows.h>
#include <string>
#include <vector>
#include <fstream>
// This little bit simply gets rid of the console window
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
int main(int argc, char* argv[])
{
std::vector<std::wstring> parameters;
std::wstring paramString;
std::wstring applicationExecutable;
// We start at argv[1] as that is the second parameter passed, etc.
// The first is always the program itself (possibly a path instead).
for (int i = 1; i < argc; i++)
{
// Convert to wide string
std::string standardString(argv[i]);
std::wstring wideString;
// This is a handy way you can convert strings to wide strings ;)
wideString.assign(standardString.begin(), standardString.end());
parameters.push_back(wideString);
}
// C++11 ;)
for (auto &str : parameters)
paramString += L" " + str;
std::ifstream configFileStream;
configFileStream.open("RunAsAdmin.cfg", std::ifstream::in);
// Make sure the file is open for reading.
if (configFileStream.is_open())
{
std::string applicationNameFromConfig;
std::getline(configFileStream, applicationNameFromConfig);
std::wstring wApplicationNameFromConfig;
wApplicationNameFromConfig.assign(applicationNameFromConfig.begin(), applicationNameFromConfig.end());
applicationExecutable = wApplicationNameFromConfig;
std::string commandLineParametersFromConfig;
std::getline(configFileStream, commandLineParametersFromConfig);
// This is just a fallback. Use the provided parameters before anything else,
// i.e. the ones passed to this application (argv)
if (!commandLineParametersFromConfig.empty() && paramString.empty())
{
paramString.assign(commandLineParametersFromConfig.begin(), commandLineParametersFromConfig.end());
}
configFileStream.close();
}
else if (applicationExecutable.empty()) // This triggers if a) the file can't be opened and
// b) there is no default file name provided in the source.
{
MessageBox(NULL, L"Unable to open configuration file.\n(Have you created a configuration file?)",
L"Run As Admin - Error", MB_OK | MB_ICONERROR);
return -2;
}
// This launches the application with the UAC prompt, and administrator rights are requested.
HINSTANCE shellResult = ShellExecute(NULL, _T("RUNAS"), (LPCWSTR)applicationExecutable.c_str(),
(LPCWSTR)paramString.c_str(), NULL, SW_SHOWNORMAL);
int returnCode = (int)shellResult;
// ShellExecute returns a value less than 32 if it fails
if (returnCode < 32)
{
switch (returnCode)
{
case ERROR_FILE_NOT_FOUND:
MessageBox(NULL, L"Could not find executable.", L"Run As Admin - Error", MB_OK | MB_ICONERROR);
break;
case ERROR_BAD_FORMAT:
MessageBox(NULL, L"Provided file isn't an executable and/or an invalid executable.",
L"Run as Admin - Error", MB_OK | MB_ICONERROR);
break;
default:
MessageBox(NULL, L"An unknown critical error has occurred. Unable to launch executable.",
L"Run as Admin - Error", MB_OK | MB_ICONERROR);
break;
}
}
return 0;
}
<commit_msg>New system automatically checks for the configuration file, and creates a default one if there isn't a pre-existent one.<commit_after>/* The MIT License (MIT)
Copyright (c) 2013 QuantumCD
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 "stdafx.h"
#include <windows.h>
#include <string>
#include <vector>
#include <fstream>
// This little bit simply gets rid of the console window
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
int main(int argc, char* argv[])
{
std::vector<std::wstring> parameters;
std::wstring paramString;
std::wstring applicationExecutable;
// We start at argv[1] as that is the second parameter passed, etc.
// The first is always the program itself (possibly a path instead).
for (int i = 1; i < argc; i++)
{
// Convert to wide string
std::string standardString(argv[i]);
std::wstring wideString;
// This is a handy way you can convert strings to wide strings ;)
wideString.assign(standardString.begin(), standardString.end());
parameters.push_back(wideString);
}
// C++11 ;)
for (auto &str : parameters)
paramString += L" " + str;
std::ifstream configFileStream("RunAsAdmin.cfg");
if (!configFileStream)
{
std::ofstream createConfigFile("RunAsAdmin.cfg");
createConfigFile << "MyApplication.exe" << std::endl;
createConfigFile << "--my-command-line-argument --another-argument" << std::endl;
MessageBox(NULL, L"Configuration file didn't exist before... now it's there.\n"
L"Be sure you change the properties so that it works!", L"Run As Admin - Error",
MB_OK | MB_ICONINFORMATION);
createConfigFile.close();
return -2;
}
// Make sure the file is open for reading.
if (configFileStream.is_open())
{
std::string applicationNameFromConfig;
std::getline(configFileStream, applicationNameFromConfig);
std::wstring wApplicationNameFromConfig;
wApplicationNameFromConfig.assign(applicationNameFromConfig.begin(), applicationNameFromConfig.end());
applicationExecutable = wApplicationNameFromConfig;
std::string commandLineParametersFromConfig;
std::getline(configFileStream, commandLineParametersFromConfig);
// This is just a fallback. Use the provided parameters before anything else,
// i.e. the ones passed to this application (argv)
if (!commandLineParametersFromConfig.empty() && paramString.empty())
{
paramString.assign(commandLineParametersFromConfig.begin(), commandLineParametersFromConfig.end());
}
configFileStream.close();
}
else if (applicationExecutable.empty()) // This triggers if a) the file can't be opened and
// b) there is no default file name provided in the source.
{
MessageBox(NULL, L"Unable to open configuration file.\n(Have you created a configuration file?)",
L"Run As Admin - Error", MB_OK | MB_ICONERROR);
return -2;
}
// This launches the application with the UAC prompt, and administrator rights are requested.
HINSTANCE shellResult = ShellExecute(NULL, _T("RUNAS"), (LPCWSTR)applicationExecutable.c_str(),
(LPCWSTR)paramString.c_str(), NULL, SW_SHOWNORMAL);
int returnCode = (int)shellResult;
// ShellExecute returns a value less than 32 if it fails
if (returnCode < 32)
{
switch (returnCode)
{
case ERROR_FILE_NOT_FOUND:
MessageBox(NULL, L"Could not find executable.", L"Run As Admin - Error", MB_OK | MB_ICONERROR);
break;
case ERROR_BAD_FORMAT:
MessageBox(NULL, L"Provided file isn't an executable and/or an invalid executable.",
L"Run as Admin - Error", MB_OK | MB_ICONERROR);
break;
default:
MessageBox(NULL, L"An unknown critical error has occurred. Unable to launch executable.",
L"Run as Admin - Error", MB_OK | MB_ICONERROR);
break;
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "sample_dynamic.h"
#include "simconf.h"
#include "element.h"
#include <iostream>
#include <cmath>
using namespace MyTRIM_NS;
sampleDynamic::sampleDynamic(simconfType * simconf_, double x, double y, double z):
sampleLayers(x, y, z),
simconf(simconf_)
{
bc[0] = CUT;
bc[1] = PBC;
bc[2] = PBC;
};
void sampleDynamic::averages( const ionBase *_pka )
{
// remember pka, we do not calculate averages right now, but on demand!
pka = _pka;
// reset update status, to trigger on-demand updates
int i = material.size();
while( i > 0 ) material[--i]->dirty = true;
}
materialBase* sampleDynamic::lookupMaterial( double* pos )
{
//std::cout << "lookuplayer" << std::endl;
materialBase* m = material[lookupLayer(pos)];
//std::cout << m << ' ' << m->arho << ' ' << m->am << ' ' << m->az << ' ' << m->mu << std::endl;
// on-demand update
if( m->dirty )
{
//std::cout << "on demand aver" << std::endl;
m->average( pka );
//std::cout << m << ' ' << m->arho << ' ' << m->am << ' ' << m->az << ' ' << m->mu << std::endl;
}
return m;
}
void sampleDynamic::addAtomsToLayer( int layer, int n, int Z )
{
unsigned int i, ne = material[layer]->element.size();
double rnorm = 0.0; // volume of one atom with the fractional composition of the layer at natural density
// look which element in the layer we are modifying and take weighted average of 1/rho of elements
for (i = 0; i < material[layer]->element.size(); ++i)
{
if (material[layer]->element[i]->z == Z) ne = i;
rnorm += material[layer]->element[i]->t / simconf->scoef[material[layer]->element[i]->z-1].atrho;
}
// element not yet contained in layer
if (ne == material[layer]->element.size())
{
elementBase* element = new elementBase;
element->z = Z;
element->m = simconf->scoef[Z-1].m1;
element->t = 0.0;
material[layer]->element.push_back(element);
}
// mass of layer (g/cm^3 * Ang^3 = 10^-24 g)
//double ml = material[layer]->rho * w[1] * w[2] * layerThickness[layer];
// number of atoms in layer
int nl = material[layer]->arho * w[1] * w[2] * layerThickness[layer];
// mass change of layer ( g/mole = g/(0.6022*10^24))
double ma = 0.6022 * material[layer]->element[ne]->m * double(n);
// keep density consistent...
layerThickness[layer] += ma / ( material[layer]->rho * w[1] * w[2] );
// change stoichiometry (arho 1/ang^3 * ang^3 )
if (material[layer]->element[ne]->t*nl + double(n) < 0.0)
{
std::cout << "Crap, t*nl=" << material[layer]->element[ne]->t*nl << ", but n=" << n << std::endl;
material[layer]->element[ne]->t = 0.0;
}
else
material[layer]->element[ne]->t += double(n)/nl; // sum t will be scaled to 1.0 in material->prepare()
// mark as dirty, just in case, and re-prepare to update averages
material[layer]->dirty = true;
material[layer]->prepare();
}
<commit_msg>Fix compile warning<commit_after>#include "sample_dynamic.h"
#include "simconf.h"
#include "element.h"
#include <iostream>
#include <cmath>
using namespace MyTRIM_NS;
sampleDynamic::sampleDynamic(simconfType * simconf_, double x, double y, double z):
sampleLayers(x, y, z),
simconf(simconf_)
{
bc[0] = CUT;
bc[1] = PBC;
bc[2] = PBC;
}
void sampleDynamic::averages( const ionBase *_pka )
{
// remember pka, we do not calculate averages right now, but on demand!
pka = _pka;
// reset update status, to trigger on-demand updates
int i = material.size();
while( i > 0 ) material[--i]->dirty = true;
}
materialBase* sampleDynamic::lookupMaterial( double* pos )
{
//std::cout << "lookuplayer" << std::endl;
materialBase* m = material[lookupLayer(pos)];
//std::cout << m << ' ' << m->arho << ' ' << m->am << ' ' << m->az << ' ' << m->mu << std::endl;
// on-demand update
if( m->dirty )
{
//std::cout << "on demand aver" << std::endl;
m->average( pka );
//std::cout << m << ' ' << m->arho << ' ' << m->am << ' ' << m->az << ' ' << m->mu << std::endl;
}
return m;
}
void sampleDynamic::addAtomsToLayer( int layer, int n, int Z )
{
unsigned int i, ne = material[layer]->element.size();
double rnorm = 0.0; // volume of one atom with the fractional composition of the layer at natural density
// look which element in the layer we are modifying and take weighted average of 1/rho of elements
for (i = 0; i < material[layer]->element.size(); ++i)
{
if (material[layer]->element[i]->z == Z) ne = i;
rnorm += material[layer]->element[i]->t / simconf->scoef[material[layer]->element[i]->z-1].atrho;
}
// element not yet contained in layer
if (ne == material[layer]->element.size())
{
elementBase* element = new elementBase;
element->z = Z;
element->m = simconf->scoef[Z-1].m1;
element->t = 0.0;
material[layer]->element.push_back(element);
}
// mass of layer (g/cm^3 * Ang^3 = 10^-24 g)
//double ml = material[layer]->rho * w[1] * w[2] * layerThickness[layer];
// number of atoms in layer
int nl = material[layer]->arho * w[1] * w[2] * layerThickness[layer];
// mass change of layer ( g/mole = g/(0.6022*10^24))
double ma = 0.6022 * material[layer]->element[ne]->m * double(n);
// keep density consistent...
layerThickness[layer] += ma / ( material[layer]->rho * w[1] * w[2] );
// change stoichiometry (arho 1/ang^3 * ang^3 )
if (material[layer]->element[ne]->t*nl + double(n) < 0.0)
{
std::cout << "Crap, t*nl=" << material[layer]->element[ne]->t*nl << ", but n=" << n << std::endl;
material[layer]->element[ne]->t = 0.0;
}
else
material[layer]->element[ne]->t += double(n)/nl; // sum t will be scaled to 1.0 in material->prepare()
// mark as dirty, just in case, and re-prepare to update averages
material[layer]->dirty = true;
material[layer]->prepare();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartWindow.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:05:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ChartWindow.hxx"
#include "ChartController.hxx"
#include "HelpIds.hrc"
#include <vcl/help.hxx>
using namespace ::com::sun::star;
namespace
{
::Rectangle lcl_AWTRectToVCLRect( const ::com::sun::star::awt::Rectangle & rAWTRect )
{
::Rectangle aResult;
aResult.setX( rAWTRect.X );
aResult.setY( rAWTRect.Y );
aResult.setWidth( rAWTRect.Width );
aResult.setHeight( rAWTRect.Height );
return aResult;
}
} // anonymous namespace
//.............................................................................
namespace chart
{
//.............................................................................
ChartWindow::ChartWindow( WindowController* pWindowController, Window* pParent, WinBits nStyle )
: Window(pParent, nStyle)
, m_pWindowController( pWindowController )
{
this->SetSmartHelpId( SmartId( HID_SCH_WIN_DOCUMENT ) );
this->SetMapMode( MapMode(MAP_100TH_MM) );
adjustHighContrastMode();
}
ChartWindow::~ChartWindow()
{
}
void ChartWindow::clear()
{
m_pWindowController=0;
this->ReleaseMouse();
}
void ChartWindow::Paint( const Rectangle& rRect )
{
if( m_pWindowController )
m_pWindowController->execute_Paint( rRect );
else
Window::Paint( rRect );
}
void ChartWindow::MouseButtonDown(const MouseEvent& rMEvt)
{
if( m_pWindowController )
m_pWindowController->execute_MouseButtonDown(rMEvt);
else
Window::MouseButtonDown(rMEvt);
}
void ChartWindow::MouseMove( const MouseEvent& rMEvt )
{
if( m_pWindowController )
m_pWindowController->execute_MouseMove( rMEvt );
else
Window::MouseMove( rMEvt );
}
void ChartWindow::Tracking( const TrackingEvent& rTEvt )
{
if( m_pWindowController )
m_pWindowController->execute_Tracking( rTEvt );
else
Window::Tracking( rTEvt );
}
void ChartWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
if( m_pWindowController )
m_pWindowController->execute_MouseButtonUp( rMEvt );
else
Window::MouseButtonUp( rMEvt );
}
void ChartWindow::Resize()
{
if( m_pWindowController )
m_pWindowController->execute_Resize();
else
Window::Resize();
}
void ChartWindow::Activate()
{
if( m_pWindowController )
m_pWindowController->execute_Activate();
else
Window::Activate();
}
void ChartWindow::Deactivate()
{
if( m_pWindowController )
m_pWindowController->execute_Deactivate();
else
Window::Deactivate();
}
void ChartWindow::GetFocus()
{
if( m_pWindowController )
m_pWindowController->execute_GetFocus();
else
Window::GetFocus();
}
void ChartWindow::LoseFocus()
{
if( m_pWindowController )
m_pWindowController->execute_LoseFocus();
else
Window::LoseFocus();
}
void ChartWindow::Command( const CommandEvent& rCEvt )
{
if( m_pWindowController )
m_pWindowController->execute_Command( rCEvt );
else
Window::Command( rCEvt );
}
void ChartWindow::KeyInput( const KeyEvent& rKEvt )
{
if( m_pWindowController )
{
if( !m_pWindowController->execute_KeyInput(rKEvt) )
Window::KeyInput(rKEvt);
}
else
Window::KeyInput( rKEvt );
}
uno::Reference< accessibility::XAccessible > ChartWindow::CreateAccessible()
{
if( m_pWindowController )
return m_pWindowController->CreateAccessible();
else
return Window::CreateAccessible();
}
void ChartWindow::DataChanged( const DataChangedEvent& rDCEvt )
{
::Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
adjustHighContrastMode();
}
}
void ChartWindow::RequestHelp( const HelpEvent& rHEvt )
{
bool bHelpHandled = false;
if( ( rHEvt.GetMode() & HELPMODE_QUICK ) &&
m_pWindowController )
{
// Point aLogicHitPos = PixelToLogic( rHEvt.GetMousePosPixel()); // old chart: GetPointerPosPixel()
Point aLogicHitPos = PixelToLogic( GetPointerPosPixel());
::rtl::OUString aQuickHelpText;
awt::Rectangle aHelpRect;
bool bIsBalloonHelp( Help::IsBalloonHelpEnabled() );
bHelpHandled = m_pWindowController->requestQuickHelp( aLogicHitPos, bIsBalloonHelp, aQuickHelpText, aHelpRect );
if( bHelpHandled )
{
if( bIsBalloonHelp )
Help::ShowBalloon(
this, rHEvt.GetMousePosPixel(), lcl_AWTRectToVCLRect( aHelpRect ), String( aQuickHelpText ));
else
Help::ShowQuickHelp(
this, lcl_AWTRectToVCLRect( aHelpRect ), String( aQuickHelpText ));
}
}
if( !bHelpHandled )
::Window::RequestHelp( rHEvt );
}
void ChartWindow::adjustHighContrastMode()
{
static const sal_Int32 nContrastMode =
DRAWMODE_SETTINGSLINE | DRAWMODE_SETTINGSFILL |
DRAWMODE_SETTINGSTEXT | DRAWMODE_SETTINGSGRADIENT;
bool bUseContrast = GetSettings().GetStyleSettings().GetHighContrastMode();
SetDrawMode( bUseContrast ? nContrastMode : DRAWMODE_DEFAULT );
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.5.126); FILE MERGED 2008/03/28 16:43:49 rt 1.5.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartWindow.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ChartWindow.hxx"
#include "ChartController.hxx"
#include "HelpIds.hrc"
#include <vcl/help.hxx>
using namespace ::com::sun::star;
namespace
{
::Rectangle lcl_AWTRectToVCLRect( const ::com::sun::star::awt::Rectangle & rAWTRect )
{
::Rectangle aResult;
aResult.setX( rAWTRect.X );
aResult.setY( rAWTRect.Y );
aResult.setWidth( rAWTRect.Width );
aResult.setHeight( rAWTRect.Height );
return aResult;
}
} // anonymous namespace
//.............................................................................
namespace chart
{
//.............................................................................
ChartWindow::ChartWindow( WindowController* pWindowController, Window* pParent, WinBits nStyle )
: Window(pParent, nStyle)
, m_pWindowController( pWindowController )
{
this->SetSmartHelpId( SmartId( HID_SCH_WIN_DOCUMENT ) );
this->SetMapMode( MapMode(MAP_100TH_MM) );
adjustHighContrastMode();
}
ChartWindow::~ChartWindow()
{
}
void ChartWindow::clear()
{
m_pWindowController=0;
this->ReleaseMouse();
}
void ChartWindow::Paint( const Rectangle& rRect )
{
if( m_pWindowController )
m_pWindowController->execute_Paint( rRect );
else
Window::Paint( rRect );
}
void ChartWindow::MouseButtonDown(const MouseEvent& rMEvt)
{
if( m_pWindowController )
m_pWindowController->execute_MouseButtonDown(rMEvt);
else
Window::MouseButtonDown(rMEvt);
}
void ChartWindow::MouseMove( const MouseEvent& rMEvt )
{
if( m_pWindowController )
m_pWindowController->execute_MouseMove( rMEvt );
else
Window::MouseMove( rMEvt );
}
void ChartWindow::Tracking( const TrackingEvent& rTEvt )
{
if( m_pWindowController )
m_pWindowController->execute_Tracking( rTEvt );
else
Window::Tracking( rTEvt );
}
void ChartWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
if( m_pWindowController )
m_pWindowController->execute_MouseButtonUp( rMEvt );
else
Window::MouseButtonUp( rMEvt );
}
void ChartWindow::Resize()
{
if( m_pWindowController )
m_pWindowController->execute_Resize();
else
Window::Resize();
}
void ChartWindow::Activate()
{
if( m_pWindowController )
m_pWindowController->execute_Activate();
else
Window::Activate();
}
void ChartWindow::Deactivate()
{
if( m_pWindowController )
m_pWindowController->execute_Deactivate();
else
Window::Deactivate();
}
void ChartWindow::GetFocus()
{
if( m_pWindowController )
m_pWindowController->execute_GetFocus();
else
Window::GetFocus();
}
void ChartWindow::LoseFocus()
{
if( m_pWindowController )
m_pWindowController->execute_LoseFocus();
else
Window::LoseFocus();
}
void ChartWindow::Command( const CommandEvent& rCEvt )
{
if( m_pWindowController )
m_pWindowController->execute_Command( rCEvt );
else
Window::Command( rCEvt );
}
void ChartWindow::KeyInput( const KeyEvent& rKEvt )
{
if( m_pWindowController )
{
if( !m_pWindowController->execute_KeyInput(rKEvt) )
Window::KeyInput(rKEvt);
}
else
Window::KeyInput( rKEvt );
}
uno::Reference< accessibility::XAccessible > ChartWindow::CreateAccessible()
{
if( m_pWindowController )
return m_pWindowController->CreateAccessible();
else
return Window::CreateAccessible();
}
void ChartWindow::DataChanged( const DataChangedEvent& rDCEvt )
{
::Window::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
(rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
adjustHighContrastMode();
}
}
void ChartWindow::RequestHelp( const HelpEvent& rHEvt )
{
bool bHelpHandled = false;
if( ( rHEvt.GetMode() & HELPMODE_QUICK ) &&
m_pWindowController )
{
// Point aLogicHitPos = PixelToLogic( rHEvt.GetMousePosPixel()); // old chart: GetPointerPosPixel()
Point aLogicHitPos = PixelToLogic( GetPointerPosPixel());
::rtl::OUString aQuickHelpText;
awt::Rectangle aHelpRect;
bool bIsBalloonHelp( Help::IsBalloonHelpEnabled() );
bHelpHandled = m_pWindowController->requestQuickHelp( aLogicHitPos, bIsBalloonHelp, aQuickHelpText, aHelpRect );
if( bHelpHandled )
{
if( bIsBalloonHelp )
Help::ShowBalloon(
this, rHEvt.GetMousePosPixel(), lcl_AWTRectToVCLRect( aHelpRect ), String( aQuickHelpText ));
else
Help::ShowQuickHelp(
this, lcl_AWTRectToVCLRect( aHelpRect ), String( aQuickHelpText ));
}
}
if( !bHelpHandled )
::Window::RequestHelp( rHEvt );
}
void ChartWindow::adjustHighContrastMode()
{
static const sal_Int32 nContrastMode =
DRAWMODE_SETTINGSLINE | DRAWMODE_SETTINGSFILL |
DRAWMODE_SETTINGSTEXT | DRAWMODE_SETTINGSGRADIENT;
bool bUseContrast = GetSettings().GetStyleSettings().GetHighContrastMode();
SetDrawMode( bUseContrast ? nContrastMode : DRAWMODE_DEFAULT );
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_BRIDGES_SOURCE_CPP_UNO_GCC3_IOS_ARM_SHARE_HXX
#define INCLUDED_BRIDGES_SOURCE_CPP_UNO_GCC3_IOS_ARM_SHARE_HXX
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
// from opensource.apple.com: libcppabi-24.4/include/rtti.h
#include "rtti.h"
// from opensource.apple.com: libcppabi-24.4/include/unwind-cxx.h
#include "unwind-cxx.h"
// Import the __cxxabiv1 a.k.a. "abi" namespace
using namespace abi;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}
namespace arm
{
#if defined(__arm)
enum armlimits {
MAX_GPR_REGS = 4,
MAX_FPR_REGS = 8
};
bool return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef );
#elif defined(__arm64)
enum armlimits {
MAX_GPR_REGS = 8,
MAX_FPR_REGS = 8
};
bool return_in_x8( typelib_TypeDescriptionReference *pTypeRef );
#else
#error wtf
#endif
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>No need for that #else #error, breaks compilation for the simulator<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_BRIDGES_SOURCE_CPP_UNO_GCC3_IOS_ARM_SHARE_HXX
#define INCLUDED_BRIDGES_SOURCE_CPP_UNO_GCC3_IOS_ARM_SHARE_HXX
#include "uno/mapping.h"
#include <typeinfo>
#include <exception>
#include <cstddef>
// from opensource.apple.com: libcppabi-24.4/include/rtti.h
#include "rtti.h"
// from opensource.apple.com: libcppabi-24.4/include/unwind-cxx.h
#include "unwind-cxx.h"
// Import the __cxxabiv1 a.k.a. "abi" namespace
using namespace abi;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * );
void raiseException(
uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );
void fillUnoException(
__cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );
bool isSimpleReturnType(typelib_TypeDescription * pTD, bool recursive = false);
}
namespace arm
{
#if defined(__arm)
enum armlimits {
MAX_GPR_REGS = 4,
MAX_FPR_REGS = 8
};
bool return_in_hidden_param( typelib_TypeDescriptionReference *pTypeRef );
#elif defined(__arm64)
enum armlimits {
MAX_GPR_REGS = 8,
MAX_FPR_REGS = 8
};
bool return_in_x8( typelib_TypeDescriptionReference *pTypeRef );
#endif
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) {
auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
// Work around http://crbug.com/279472.
contents->GetView()->SetAllowOverlappingViews(true);
#endif
return Create(contents);
}
InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
}
<commit_msg>Fix cpplint errors in inspectable_web_contents.cc<commit_after>#include "browser/inspectable_web_contents.h"
#include "browser/inspectable_web_contents_impl.h"
#include "content/public/browser/web_contents_view.h"
namespace brightray {
InspectableWebContents* InspectableWebContents::Create(
const content::WebContents::CreateParams& create_params) {
auto contents = content::WebContents::Create(create_params);
#if defined(OS_MACOSX)
// Work around http://crbug.com/279472.
contents->GetView()->SetAllowOverlappingViews(true);
#endif
return Create(contents);
}
InspectableWebContents* InspectableWebContents::Create(
content::WebContents* web_contents) {
return new InspectableWebContentsImpl(web_contents);
}
} // namespace brightray
<|endoftext|> |
<commit_before>#include "RosalilaSound.h"
Sound::Sound()
{
music=NULL;
writeLogLine("Initializing SLD sound engine.");
int channels=10;
if( Mix_OpenAudio( 44100, AUDIO_S16SYS/*MIX_DEFAULT_FORMAT*/, 2, 4096 ) == -1 )
{
writeLogLine("Failed initializing sound engine. :(");
return;
}
Mix_AllocateChannels(100);
writeLogLine("Success!");
current_music="";
}
void Sound::drop()
{
//TODO for each chunk
//Mix_FreeChunk( chunk );
Mix_FreeMusic(music);
Mix_CloseAudio();
}
void Sound::addSound(std::string variable,std::string value)
{
//if(sounds.find(variable)==sounds.end())
sounds[variable]=Mix_LoadWAV(value.c_str());
}
void Sound::playSound(std::string variable)
{
if(!soundExists(variable))
{
writeLogLine("Error: "+variable+" sound does not exists.");
}
if(sounds[variable]!=NULL)
{
Mix_PlayChannel( 1, sounds[variable], 0 );
}
}
int Sound::playSound(std::string variable, int channel, int loops)
{
if(!soundExists(variable))
{
writeLogLine("Error: "+variable+" sound does not exists.");
return -1;
}
if(sounds[variable]!=NULL)
{
//Mix_HaltChannel(channel);
return Mix_PlayChannel( channel, sounds[variable], 1);
//Mix_PlayChannel( -1, sounds[variable], 0 );
}
}
void Sound::playMusic(std::string path)
{
stopMusic();
writeLogLine("Playing music: "+path);
music = Mix_LoadMUS(path.c_str());
Mix_PlayMusic(music,-1);
current_music=path;
}
void Sound::playMusic(std::string path,int loops)
{
stopMusic();
writeLogLine("Playing music: "+path);
music = Mix_LoadMUS(path.c_str());
Mix_PlayMusic(music,loops);
}
void Sound::stopMusic()
{
if(music!=NULL)
{
Mix_HaltMusic();
Mix_FreeMusic(music);
music=NULL;
}
}
bool Sound::soundExists(std::string variable)
{
map<std::string,Mix_Chunk*>::iterator it = sounds.find(variable);
return it!=sounds.end();
return false;
}
string Sound::getCurrentMusic()
{
return current_music;
}
<commit_msg>sfx sfx<commit_after>#include "RosalilaSound.h"
Sound::Sound()
{
music=NULL;
writeLogLine("Initializing SLD sound engine.");
int channels=10;
if( Mix_OpenAudio( 44100, AUDIO_S16SYS/*MIX_DEFAULT_FORMAT*/, 2, 4096 ) == -1 )
{
writeLogLine("Failed initializing sound engine. :(");
return;
}
Mix_AllocateChannels(100);
writeLogLine("Success!");
current_music="";
}
void Sound::drop()
{
//TODO for each chunk
//Mix_FreeChunk( chunk );
Mix_FreeMusic(music);
Mix_CloseAudio();
}
void Sound::addSound(std::string variable,std::string value)
{
//if(sounds.find(variable)==sounds.end())
sounds[variable]=Mix_LoadWAV(value.c_str());
}
void Sound::playSound(std::string variable)
{
if(!soundExists(variable))
{
writeLogLine("Error: "+variable+" sound does not exists.");
}
if(sounds[variable]!=NULL)
{
Mix_PlayChannel( 1, sounds[variable], 0 );
}
}
int Sound::playSound(std::string variable, int channel, int loops)
{
if(!soundExists(variable))
{
writeLogLine("Error: "+variable+" sound does not exists.");
return -1;
}
if(sounds[variable]!=NULL)
{
//Mix_HaltChannel(channel);
return Mix_PlayChannel( channel, sounds[variable], loops);
//Mix_PlayChannel( -1, sounds[variable], 0 );
}
}
void Sound::playMusic(std::string path)
{
stopMusic();
writeLogLine("Playing music: "+path);
music = Mix_LoadMUS(path.c_str());
Mix_PlayMusic(music,-1);
current_music=path;
}
void Sound::playMusic(std::string path,int loops)
{
stopMusic();
writeLogLine("Playing music: "+path);
music = Mix_LoadMUS(path.c_str());
Mix_PlayMusic(music,loops);
}
void Sound::stopMusic()
{
if(music!=NULL)
{
Mix_HaltMusic();
Mix_FreeMusic(music);
music=NULL;
}
}
bool Sound::soundExists(std::string variable)
{
map<std::string,Mix_Chunk*>::iterator it = sounds.find(variable);
return it!=sounds.end();
return false;
}
string Sound::getCurrentMusic()
{
return current_music;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Cloudflare, Inc. and contributors
// Licensed under the MIT License:
//
// 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.
#if _WIN32
#define WIN32_LEAN_AND_MEAN 1 // lolz
#endif
#include "time.h"
#include "debug.h"
#include <kj/test.h>
#include <time.h>
#if _WIN32
#include <windows.h>
#include "windows-sanity.h"
#else
#include <unistd.h>
#endif
namespace kj {
namespace {
KJ_TEST("stringify times") {
KJ_EXPECT(kj::str(50 * kj::SECONDS) == "50s");
KJ_EXPECT(kj::str(5 * kj::SECONDS + 2 * kj::MILLISECONDS) == "5.002s");
KJ_EXPECT(kj::str(256 * kj::MILLISECONDS) == "256ms");
KJ_EXPECT(kj::str(5 * kj::MILLISECONDS + 2 * kj::NANOSECONDS) == "5.000002ms");
KJ_EXPECT(kj::str(50 * kj::MICROSECONDS) == "50μs");
KJ_EXPECT(kj::str(5 * kj::MICROSECONDS + 300 * kj::NANOSECONDS) == "5.3μs");
KJ_EXPECT(kj::str(50 * kj::NANOSECONDS) == "50ns");
}
#if _WIN32
void delay(kj::Duration d) {
Sleep(d / kj::MILLISECONDS);
}
#else
void delay(kj::Duration d) {
usleep(d / kj::MICROSECONDS);
}
#endif
KJ_TEST("calendar clocks matches unix time") {
// Check that the times returned by the calendar clock are within 1s of what time() returns.
auto& coarse = systemCoarseCalendarClock();
auto& precise = systemPreciseCalendarClock();
Date p = precise.now();
Date c = coarse.now();
time_t t = time(nullptr);
int64_t pi = (p - UNIX_EPOCH) / kj::SECONDS;
int64_t ci = (c - UNIX_EPOCH) / kj::SECONDS;
KJ_EXPECT(pi >= t - 1);
KJ_EXPECT(pi <= t + 1);
KJ_EXPECT(ci >= t - 1);
KJ_EXPECT(ci <= t + 1);
}
KJ_TEST("monotonic clocks match each other") {
// Check that the monotonic clocks return comparable times.
auto& coarse = systemCoarseMonotonicClock();
auto& precise = systemPreciseMonotonicClock();
TimePoint p = precise.now();
TimePoint c = coarse.now();
// 20ms tolerance due to Windows timeslices being quite long.
KJ_EXPECT(p < c + 20 * kj::MILLISECONDS, p - c);
KJ_EXPECT(p > c - 20 * kj::MILLISECONDS, c - p);
}
KJ_TEST("all clocks advance in real time") {
Duration coarseCalDiff;
Duration preciseCalDiff;
Duration coarseMonoDiff;
Duration preciseMonoDiff;
for (uint retryCount KJ_UNUSED: kj::zeroTo(20)) {
auto& coarseCal = systemCoarseCalendarClock();
auto& preciseCal = systemPreciseCalendarClock();
auto& coarseMono = systemCoarseMonotonicClock();
auto& preciseMono = systemPreciseMonotonicClock();
Date coarseCalBefore = coarseCal.now();
Date preciseCalBefore = preciseCal.now();
TimePoint coarseMonoBefore = coarseMono.now();
TimePoint preciseMonoBefore = preciseMono.now();
Duration delayTime = 150 * kj::MILLISECONDS;
delay(delayTime);
Date coarseCalAfter = coarseCal.now();
Date preciseCalAfter = preciseCal.now();
TimePoint coarseMonoAfter = coarseMono.now();
TimePoint preciseMonoAfter = preciseMono.now();
coarseCalDiff = coarseCalAfter - coarseCalBefore;
preciseCalDiff = preciseCalAfter - preciseCalBefore;
coarseMonoDiff = coarseMonoAfter - coarseMonoBefore;
preciseMonoDiff = preciseMonoAfter - preciseMonoBefore;
// 20ms tolerance due to Windows timeslices being quite long (and Windows sleeps being only
// accurate to the timeslice).
if (coarseCalDiff > delayTime - 20 * kj::MILLISECONDS &&
coarseCalDiff < delayTime + 20 * kj::MILLISECONDS &&
preciseCalDiff > delayTime - 20 * kj::MILLISECONDS &&
preciseCalDiff < delayTime + 20 * kj::MILLISECONDS &&
coarseMonoDiff > delayTime - 20 * kj::MILLISECONDS &&
coarseMonoDiff < delayTime + 20 * kj::MILLISECONDS &&
preciseMonoDiff > delayTime - 20 * kj::MILLISECONDS &&
preciseMonoDiff < delayTime + 20 * kj::MILLISECONDS) {
// success
return;
}
}
KJ_FAIL_EXPECT("clocks seem inaccurate even after 20 tries",
coarseCalDiff / kj::MICROSECONDS, preciseCalDiff / kj::MICROSECONDS,
coarseMonoDiff / kj::MICROSECONDS, preciseMonoDiff / kj::MICROSECONDS);
}
} // namespace
} // namespace kj
<commit_msg>Fudge time-test.c++ even more for Windows.<commit_after>// Copyright (c) 2019 Cloudflare, Inc. and contributors
// Licensed under the MIT License:
//
// 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.
#if _WIN32
#define WIN32_LEAN_AND_MEAN 1 // lolz
#endif
#include "time.h"
#include "debug.h"
#include <kj/test.h>
#include <time.h>
#if _WIN32
#include <windows.h>
#include "windows-sanity.h"
#else
#include <unistd.h>
#endif
namespace kj {
namespace {
KJ_TEST("stringify times") {
KJ_EXPECT(kj::str(50 * kj::SECONDS) == "50s");
KJ_EXPECT(kj::str(5 * kj::SECONDS + 2 * kj::MILLISECONDS) == "5.002s");
KJ_EXPECT(kj::str(256 * kj::MILLISECONDS) == "256ms");
KJ_EXPECT(kj::str(5 * kj::MILLISECONDS + 2 * kj::NANOSECONDS) == "5.000002ms");
KJ_EXPECT(kj::str(50 * kj::MICROSECONDS) == "50μs");
KJ_EXPECT(kj::str(5 * kj::MICROSECONDS + 300 * kj::NANOSECONDS) == "5.3μs");
KJ_EXPECT(kj::str(50 * kj::NANOSECONDS) == "50ns");
}
#if _WIN32
void delay(kj::Duration d) {
Sleep(d / kj::MILLISECONDS);
}
#else
void delay(kj::Duration d) {
usleep(d / kj::MICROSECONDS);
}
#endif
KJ_TEST("calendar clocks matches unix time") {
// Check that the times returned by the calendar clock are within 1s of what time() returns.
auto& coarse = systemCoarseCalendarClock();
auto& precise = systemPreciseCalendarClock();
Date p = precise.now();
Date c = coarse.now();
time_t t = time(nullptr);
int64_t pi = (p - UNIX_EPOCH) / kj::SECONDS;
int64_t ci = (c - UNIX_EPOCH) / kj::SECONDS;
KJ_EXPECT(pi >= t - 1);
KJ_EXPECT(pi <= t + 1);
KJ_EXPECT(ci >= t - 1);
KJ_EXPECT(ci <= t + 1);
}
KJ_TEST("monotonic clocks match each other") {
// Check that the monotonic clocks return comparable times.
auto& coarse = systemCoarseMonotonicClock();
auto& precise = systemPreciseMonotonicClock();
TimePoint p = precise.now();
TimePoint c = coarse.now();
// 40ms tolerance due to Windows timeslices being quite long, especially on GitHub Actions where
// Windows is drunk and has completely lost track of time.
KJ_EXPECT(p < c + 40 * kj::MILLISECONDS, p - c);
KJ_EXPECT(p > c - 40 * kj::MILLISECONDS, c - p);
}
KJ_TEST("all clocks advance in real time") {
Duration coarseCalDiff;
Duration preciseCalDiff;
Duration coarseMonoDiff;
Duration preciseMonoDiff;
for (uint retryCount KJ_UNUSED: kj::zeroTo(20)) {
auto& coarseCal = systemCoarseCalendarClock();
auto& preciseCal = systemPreciseCalendarClock();
auto& coarseMono = systemCoarseMonotonicClock();
auto& preciseMono = systemPreciseMonotonicClock();
Date coarseCalBefore = coarseCal.now();
Date preciseCalBefore = preciseCal.now();
TimePoint coarseMonoBefore = coarseMono.now();
TimePoint preciseMonoBefore = preciseMono.now();
Duration delayTime = 150 * kj::MILLISECONDS;
delay(delayTime);
Date coarseCalAfter = coarseCal.now();
Date preciseCalAfter = preciseCal.now();
TimePoint coarseMonoAfter = coarseMono.now();
TimePoint preciseMonoAfter = preciseMono.now();
coarseCalDiff = coarseCalAfter - coarseCalBefore;
preciseCalDiff = preciseCalAfter - preciseCalBefore;
coarseMonoDiff = coarseMonoAfter - coarseMonoBefore;
preciseMonoDiff = preciseMonoAfter - preciseMonoBefore;
// 20ms tolerance due to Windows timeslices being quite long (and Windows sleeps being only
// accurate to the timeslice).
if (coarseCalDiff > delayTime - 20 * kj::MILLISECONDS &&
coarseCalDiff < delayTime + 20 * kj::MILLISECONDS &&
preciseCalDiff > delayTime - 20 * kj::MILLISECONDS &&
preciseCalDiff < delayTime + 20 * kj::MILLISECONDS &&
coarseMonoDiff > delayTime - 20 * kj::MILLISECONDS &&
coarseMonoDiff < delayTime + 20 * kj::MILLISECONDS &&
preciseMonoDiff > delayTime - 20 * kj::MILLISECONDS &&
preciseMonoDiff < delayTime + 20 * kj::MILLISECONDS) {
// success
return;
}
}
KJ_FAIL_EXPECT("clocks seem inaccurate even after 20 tries",
coarseCalDiff / kj::MICROSECONDS, preciseCalDiff / kj::MICROSECONDS,
coarseMonoDiff / kj::MICROSECONDS, preciseMonoDiff / kj::MICROSECONDS);
}
} // namespace
} // namespace kj
<|endoftext|> |
<commit_before>#include "test.h"
#include <RobustWiFiServer.h>
void prepareState(ServerState state, RobustWiFiServer& rs) {
WiFiClient& c = rs._getClient();
WiFiServer& s = rs._getServer();
switch(state){
case DISCONNECTED:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case ERR_SSID_NOT_AVAIL:
WiFi.setStatus(WL_NO_SSID_AVAIL);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case SERVER_LISTENING:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(true);
c.setAvailable(false);
c.setConnected(false);
break;
case CLIENT_CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(false);
c.setConnected(true);
break;
case DATA_AVAILABLE:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(true);
c.setConnected(true);
break;
default:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
}
printf("test");
rs._printInternalState();
}
void client_connect(RobustWiFiServer& rs) {
printf("test> client connects.\n");
prepareState(CLIENT_CONNECTED, rs);
}
void client_disconnects(RobustWiFiServer& rs) {
printf("test> client disconnects.\n");
prepareState(SERVER_LISTENING, rs);
}
void client_send_data(RobustWiFiServer& rs) {
printf("test> client sends data.\n");
prepareState(DATA_AVAILABLE, rs);
}
void wifi_disconnects(RobustWiFiServer& rs) {
printf("test> wifi disconnects.\n");
prepareState(ERR_SSID_NOT_AVAIL, rs);
}
const String ssid = "MY_SSID";
const String password = "my_password";
IPAddress myIP(192,168,1,127);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
uint16_t port = 1110;
TEST(StaticHandler, runthruWithWifiDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=15; i++){
printf("%d\n", i);
wifiServer.loop();
ServerCondition cond = wifiServer.getCondition();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
client_send_data(wifiServer);
break;
case 4:
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
client_disconnects(wifiServer);
break;
case 5:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
wifi_disconnects(wifiServer);
break;
case 6:
case 7:
case 8:
case 9:
// will not allow that connect succeeds
wifi_disconnects(wifiServer);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
break;
// needs 3 iterations back to disconnected
case 10:
case 11:
EXPECT_EQ(state, ERR_SSID_NOT_AVAIL);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
WiFi.setNumSSIDs(0);
break;
case 12:
WiFi.setNumSSIDs(1);
break;
case 13:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 14:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
}
}
}
TEST(StaticHandler, runthruWithWifiDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=15; i++){
printf("%d\n", i);
wifiServer.loop();
ServerCondition cond = wifiServer.getCondition();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
client_send_data(wifiServer);
break;
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
wifiServer.connect();
break;
}
}
}
TEST(StaticHandler, runWithTimeout){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
WiFi.setNumSSIDs(0);
for (int i=0; i<=7; i++){
printf("%d\n", i);
mock_increaseTime(1000);
wifiServer.loop();
// dont succeed server start
prepareState(DISCONNECTED, wifiServer);
ServerCondition cond = wifiServer.getCondition();
switch(i){
case 0:
case 1:
case 2:
case 3:
EXPECT_EQ(cond.error, NO_ERROR);
EXPECT_EQ(cond.numberOfTimeouts, 0);
break;
case 4:
// timeout occured
EXPECT_EQ(cond.error, TRANSITION_TIMEOUT_REACHED);
EXPECT_EQ(cond.numberOfTimeouts, 1);
break;
}
}
} <commit_msg>add disconnect test<commit_after>#include "test.h"
#include <RobustWiFiServer.h>
void prepareState(ServerState state, RobustWiFiServer& rs) {
WiFiClient& c = rs._getClient();
WiFiServer& s = rs._getServer();
switch(state){
case DISCONNECTED:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case ERR_SSID_NOT_AVAIL:
WiFi.setStatus(WL_NO_SSID_AVAIL);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case SERVER_LISTENING:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(true);
c.setAvailable(false);
c.setConnected(false);
break;
case CLIENT_CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(false);
c.setConnected(true);
break;
case DATA_AVAILABLE:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(true);
c.setConnected(true);
break;
default:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
}
printf("test");
rs._printInternalState();
}
void client_connect(RobustWiFiServer& rs) {
printf("test> client connects.\n");
prepareState(CLIENT_CONNECTED, rs);
}
void client_disconnects(RobustWiFiServer& rs) {
printf("test> client disconnects.\n");
prepareState(SERVER_LISTENING, rs);
}
void client_send_data(RobustWiFiServer& rs) {
printf("test> client sends data.\n");
prepareState(DATA_AVAILABLE, rs);
}
void wifi_disconnects(RobustWiFiServer& rs) {
printf("test> wifi disconnects.\n");
prepareState(ERR_SSID_NOT_AVAIL, rs);
}
const String ssid = "MY_SSID";
const String password = "my_password";
IPAddress myIP(192,168,1,127);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
uint16_t port = 1110;
TEST(StaticHandler, runthruWithWifiDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=15; i++){
printf("%d\n", i);
wifiServer.loop();
ServerCondition cond = wifiServer.getCondition();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
client_send_data(wifiServer);
break;
case 4:
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
client_disconnects(wifiServer);
break;
case 5:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
wifi_disconnects(wifiServer);
break;
case 6:
case 7:
case 8:
case 9:
// will not allow that connect succeeds
wifi_disconnects(wifiServer);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
break;
// needs 3 iterations back to disconnected
case 10:
case 11:
EXPECT_EQ(state, ERR_SSID_NOT_AVAIL);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
WiFi.setNumSSIDs(0);
break;
case 12:
WiFi.setNumSSIDs(1);
break;
case 13:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 14:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
}
}
}
TEST(StaticHandler, runthruWithConnectDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=10; i++){
printf("%d\n", i);
wifiServer.loop();
ServerCondition cond = wifiServer.getCondition();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
client_send_data(wifiServer);
break;
case 4:
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
wifiServer.disconnect();
break;
case 5:
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 6:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 7:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 8:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 9:
EXPECT_EQ(state,DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 10:
EXPECT_EQ(state,DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
}
}
}
TEST(StaticHandler, runWithTimeout){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
WiFi.setNumSSIDs(0);
for (int i=0; i<=7; i++){
printf("%d\n", i);
mock_increaseTime(1000);
wifiServer.loop();
// dont succeed server start
prepareState(DISCONNECTED, wifiServer);
ServerCondition cond = wifiServer.getCondition();
switch(i){
case 0:
case 1:
case 2:
case 3:
EXPECT_EQ(cond.error, NO_ERROR);
EXPECT_EQ(cond.numberOfTimeouts, 0);
break;
case 4:
// timeout occured
EXPECT_EQ(cond.error, TRANSITION_TIMEOUT_REACHED);
EXPECT_EQ(cond.numberOfTimeouts, 1);
break;
}
}
} <|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "impl/external_commit_helper.hpp"
#include "impl/realm_coordinator.hpp"
#include <algorithm>
using namespace realm;
using namespace realm::_impl;
using namespace realm::util;
static std::string normalize_realm_path_for_windows_kernel_object_name(std::string realm_path) {
// windows named objects names should not contain backslash
std::replace(realm_path.begin(), realm_path.end(), '\\', '/');
// always use lowercase for the drive letter as a win32 named objects name
auto position = realm_path.find(':');
if (position != std::string::npos && position > 0) {
realm_path[position - 1] = tolower(realm_path[position - 1]);
}
return realm_path;
}
static std::string create_condvar_sharedmemory_name(std::string realm_path) {
realm_path = normalize_realm_path_for_windows_kernel_object_name(realm_path);
std::string name("Local\\Realm_ObjectStore_ExternalCommitHelper_SharedCondVar_");
name.append(realm_path);
return name;
}
ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
: m_parent(parent)
, m_condvar_shared(create_condvar_sharedmemory_name(parent.get_path()))
{
m_mutex.set_shared_part(InterprocessMutex::SharedPart(),
normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_ControlMutex");
m_commit_available.set_shared_part(m_condvar_shared.get(),
normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_CommitCondVar",
std::filesystem::temp_directory_path().u8string());
m_thread = std::async(std::launch::async, [this]() { listen(); });
}
ExternalCommitHelper::~ExternalCommitHelper()
{
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_keep_listening = false;
m_commit_available.notify_all();
}
m_thread.wait();
m_commit_available.release_shared_part();
}
void ExternalCommitHelper::notify_others()
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_commit_available.notify_all();
}
void ExternalCommitHelper::listen()
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
while (m_keep_listening) {
m_commit_available.wait(m_mutex, nullptr);
if (m_keep_listening) {
m_parent.on_change();
}
}
}
<commit_msg>release the lock while calling on_change<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "impl/external_commit_helper.hpp"
#include "impl/realm_coordinator.hpp"
#include <algorithm>
using namespace realm;
using namespace realm::_impl;
using namespace realm::util;
static std::string normalize_realm_path_for_windows_kernel_object_name(std::string realm_path) {
// windows named objects names should not contain backslash
std::replace(realm_path.begin(), realm_path.end(), '\\', '/');
// always use lowercase for the drive letter as a win32 named objects name
auto position = realm_path.find(':');
if (position != std::string::npos && position > 0) {
realm_path[position - 1] = tolower(realm_path[position - 1]);
}
return realm_path;
}
static std::string create_condvar_sharedmemory_name(std::string realm_path) {
realm_path = normalize_realm_path_for_windows_kernel_object_name(realm_path);
std::string name("Local\\Realm_ObjectStore_ExternalCommitHelper_SharedCondVar_");
name.append(realm_path);
return name;
}
ExternalCommitHelper::ExternalCommitHelper(RealmCoordinator& parent)
: m_parent(parent)
, m_condvar_shared(create_condvar_sharedmemory_name(parent.get_path()))
{
m_mutex.set_shared_part(InterprocessMutex::SharedPart(),
normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_ControlMutex");
m_commit_available.set_shared_part(m_condvar_shared.get(),
normalize_realm_path_for_windows_kernel_object_name(parent.get_path()),
"ExternalCommitHelper_CommitCondVar",
std::filesystem::temp_directory_path().u8string());
m_thread = std::async(std::launch::async, [this]() { listen(); });
}
ExternalCommitHelper::~ExternalCommitHelper()
{
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_keep_listening = false;
m_commit_available.notify_all();
}
m_thread.wait();
m_commit_available.release_shared_part();
}
void ExternalCommitHelper::notify_others()
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
m_commit_available.notify_all();
}
void ExternalCommitHelper::listen()
{
std::lock_guard<InterprocessMutex> lock(m_mutex);
while (m_keep_listening) {
m_commit_available.wait(m_mutex, nullptr);
if (m_keep_listening) {
m_mutex.unlock();
m_parent.on_change();
m_mutex.lock();
}
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickbehavior_p.h"
#include "qquickanimation_p.h"
#include <qqmlcontext.h>
#include <qqmlinfo.h>
#include <private/qqmlproperty_p.h>
#include <private/qqmlengine_p.h>
#include <private/qabstractanimationjob_p.h>
#include <private/qquicktransition_p.h>
#include <private/qquickanimatorjob_p.h>
#include <private/qobject_p.h>
QT_BEGIN_NAMESPACE
class QQuickBehaviorPrivate : public QObjectPrivate, public QAnimationJobChangeListener
{
Q_DECLARE_PUBLIC(QQuickBehavior)
public:
QQuickBehaviorPrivate() : animation(0), animationInstance(0), enabled(true), finalized(false)
, blockRunningChanged(false) {}
virtual void animationStateChanged(QAbstractAnimationJob *, QAbstractAnimationJob::State newState, QAbstractAnimationJob::State oldState);
QQmlProperty property;
QVariant targetValue;
QPointer<QQuickAbstractAnimation> animation;
QAbstractAnimationJob *animationInstance;
bool enabled;
bool finalized;
bool blockRunningChanged;
};
/*!
\qmltype Behavior
\instantiates QQuickBehavior
\inqmlmodule QtQuick
\ingroup qtquick-transitions-animations
\ingroup qtquick-interceptors
\brief Defines a default animation for a property change
A Behavior defines the default animation to be applied whenever a
particular property value changes.
For example, the following Behavior defines a NumberAnimation to be run
whenever the \l Rectangle's \c width value changes. When the MouseArea
is clicked, the \c width is changed, triggering the behavior's animation:
\snippet qml/behavior.qml 0
Note that a property cannot have more than one assigned Behavior. To provide
multiple animations within a Behavior, use ParallelAnimation or
SequentialAnimation.
If a \l{Qt Quick States}{state change} has a \l Transition that matches the same property as a
Behavior, the \l Transition animation overrides the Behavior for that
state change. For general advice on using Behaviors to animate state changes, see
\l{Using Qt Quick Behaviors with States}.
\sa {Animation and Transitions in Qt Quick}, {declarative/animation/behaviors}{Behavior example}, {Qt QML}
*/
QQuickBehavior::QQuickBehavior(QObject *parent)
: QObject(*(new QQuickBehaviorPrivate), parent)
{
}
QQuickBehavior::~QQuickBehavior()
{
Q_D(QQuickBehavior);
delete d->animationInstance;
}
/*!
\qmlproperty Animation QtQuick::Behavior::animation
\default
This property holds the animation to run when the behavior is triggered.
*/
QQuickAbstractAnimation *QQuickBehavior::animation()
{
Q_D(QQuickBehavior);
return d->animation;
}
void QQuickBehavior::setAnimation(QQuickAbstractAnimation *animation)
{
Q_D(QQuickBehavior);
if (d->animation) {
qmlInfo(this) << tr("Cannot change the animation assigned to a Behavior.");
return;
}
d->animation = animation;
if (d->animation) {
d->animation->setDefaultTarget(d->property);
d->animation->setDisableUserControl();
}
}
void QQuickBehaviorPrivate::animationStateChanged(QAbstractAnimationJob *, QAbstractAnimationJob::State newState,QAbstractAnimationJob::State)
{
if (!blockRunningChanged)
animation->notifyRunningChanged(newState == QAbstractAnimationJob::Running);
}
/*!
\qmlproperty bool QtQuick::Behavior::enabled
This property holds whether the behavior will be triggered when the tracked
property changes value.
By default a Behavior is enabled.
*/
bool QQuickBehavior::enabled() const
{
Q_D(const QQuickBehavior);
return d->enabled;
}
void QQuickBehavior::setEnabled(bool enabled)
{
Q_D(QQuickBehavior);
if (d->enabled == enabled)
return;
d->enabled = enabled;
emit enabledChanged();
}
void QQuickBehavior::write(const QVariant &value)
{
Q_D(QQuickBehavior);
bool bypass = !d->enabled || !d->finalized || QQmlEnginePrivate::designerMode();
if (!bypass)
qmlExecuteDeferred(this);
if (!d->animation || bypass) {
if (d->animationInstance)
d->animationInstance->stop();
QQmlPropertyPrivate::write(d->property, value, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
d->targetValue = value;
return;
}
if (d->animation->isRunning() && value == d->targetValue)
return;
d->targetValue = value;
if (d->animationInstance
&& (d->animationInstance->duration() != -1
|| d->animationInstance->isRenderThreadProxy())
&& !d->animationInstance->isStopped()) {
d->blockRunningChanged = true;
d->animationInstance->stop();
}
// Render thread animations use "stop" to synchronize the property back
// to the item, so we need to read the value after.
const QVariant ¤tValue = d->property.read();
QQuickStateOperation::ActionList actions;
QQuickStateAction action;
action.property = d->property;
action.fromValue = currentValue;
action.toValue = value;
actions << action;
QList<QQmlProperty> after;
QAbstractAnimationJob *prev = d->animationInstance;
d->animationInstance = d->animation->transition(actions, after, QQuickAbstractAnimation::Forward);
if (d->animationInstance && d->animation->threadingModel() == QQuickAbstractAnimation::RenderThread)
d->animationInstance = new QQuickAnimatorProxyJob(d->animationInstance, d->animation);
if (prev && prev != d->animationInstance)
delete prev;
if (d->animationInstance) {
if (d->animationInstance != prev)
d->animationInstance->addAnimationChangeListener(d, QAbstractAnimationJob::StateChange);
d->animationInstance->start();
d->blockRunningChanged = false;
}
if (!after.contains(d->property))
QQmlPropertyPrivate::write(d->property, value, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
}
void QQuickBehavior::setTarget(const QQmlProperty &property)
{
Q_D(QQuickBehavior);
d->property = property;
if (d->animation)
d->animation->setDefaultTarget(property);
QQmlEnginePrivate *engPriv = QQmlEnginePrivate::get(qmlEngine(this));
static int finalizedIdx = -1;
if (finalizedIdx < 0)
finalizedIdx = metaObject()->indexOfSlot("componentFinalized()");
engPriv->registerFinalizeCallback(this, finalizedIdx);
}
void QQuickBehavior::componentFinalized()
{
Q_D(QQuickBehavior);
d->finalized = true;
}
QT_END_NAMESPACE
<commit_msg>Behavior should not trigger when the tracked value has not changed.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickbehavior_p.h"
#include "qquickanimation_p.h"
#include <qqmlcontext.h>
#include <qqmlinfo.h>
#include <private/qqmlproperty_p.h>
#include <private/qqmlengine_p.h>
#include <private/qabstractanimationjob_p.h>
#include <private/qquicktransition_p.h>
#include <private/qquickanimatorjob_p.h>
#include <private/qobject_p.h>
QT_BEGIN_NAMESPACE
class QQuickBehaviorPrivate : public QObjectPrivate, public QAnimationJobChangeListener
{
Q_DECLARE_PUBLIC(QQuickBehavior)
public:
QQuickBehaviorPrivate() : animation(0), animationInstance(0), enabled(true), finalized(false)
, blockRunningChanged(false) {}
virtual void animationStateChanged(QAbstractAnimationJob *, QAbstractAnimationJob::State newState, QAbstractAnimationJob::State oldState);
QQmlProperty property;
QVariant targetValue;
QPointer<QQuickAbstractAnimation> animation;
QAbstractAnimationJob *animationInstance;
bool enabled;
bool finalized;
bool blockRunningChanged;
};
/*!
\qmltype Behavior
\instantiates QQuickBehavior
\inqmlmodule QtQuick
\ingroup qtquick-transitions-animations
\ingroup qtquick-interceptors
\brief Defines a default animation for a property change
A Behavior defines the default animation to be applied whenever a
particular property value changes.
For example, the following Behavior defines a NumberAnimation to be run
whenever the \l Rectangle's \c width value changes. When the MouseArea
is clicked, the \c width is changed, triggering the behavior's animation:
\snippet qml/behavior.qml 0
Note that a property cannot have more than one assigned Behavior. To provide
multiple animations within a Behavior, use ParallelAnimation or
SequentialAnimation.
If a \l{Qt Quick States}{state change} has a \l Transition that matches the same property as a
Behavior, the \l Transition animation overrides the Behavior for that
state change. For general advice on using Behaviors to animate state changes, see
\l{Using Qt Quick Behaviors with States}.
\sa {Animation and Transitions in Qt Quick}, {declarative/animation/behaviors}{Behavior example}, {Qt QML}
*/
QQuickBehavior::QQuickBehavior(QObject *parent)
: QObject(*(new QQuickBehaviorPrivate), parent)
{
}
QQuickBehavior::~QQuickBehavior()
{
Q_D(QQuickBehavior);
delete d->animationInstance;
}
/*!
\qmlproperty Animation QtQuick::Behavior::animation
\default
This property holds the animation to run when the behavior is triggered.
*/
QQuickAbstractAnimation *QQuickBehavior::animation()
{
Q_D(QQuickBehavior);
return d->animation;
}
void QQuickBehavior::setAnimation(QQuickAbstractAnimation *animation)
{
Q_D(QQuickBehavior);
if (d->animation) {
qmlInfo(this) << tr("Cannot change the animation assigned to a Behavior.");
return;
}
d->animation = animation;
if (d->animation) {
d->animation->setDefaultTarget(d->property);
d->animation->setDisableUserControl();
}
}
void QQuickBehaviorPrivate::animationStateChanged(QAbstractAnimationJob *, QAbstractAnimationJob::State newState,QAbstractAnimationJob::State)
{
if (!blockRunningChanged)
animation->notifyRunningChanged(newState == QAbstractAnimationJob::Running);
}
/*!
\qmlproperty bool QtQuick::Behavior::enabled
This property holds whether the behavior will be triggered when the tracked
property changes value.
By default a Behavior is enabled.
*/
bool QQuickBehavior::enabled() const
{
Q_D(const QQuickBehavior);
return d->enabled;
}
void QQuickBehavior::setEnabled(bool enabled)
{
Q_D(QQuickBehavior);
if (d->enabled == enabled)
return;
d->enabled = enabled;
emit enabledChanged();
}
void QQuickBehavior::write(const QVariant &value)
{
Q_D(QQuickBehavior);
bool bypass = !d->enabled || !d->finalized || QQmlEnginePrivate::designerMode();
if (!bypass)
qmlExecuteDeferred(this);
if (!d->animation || bypass) {
if (d->animationInstance)
d->animationInstance->stop();
QQmlPropertyPrivate::write(d->property, value, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
d->targetValue = value;
return;
}
if (d->animation->isRunning() && value == d->targetValue)
return;
d->targetValue = value;
if (d->animationInstance
&& (d->animationInstance->duration() != -1
|| d->animationInstance->isRenderThreadProxy())
&& !d->animationInstance->isStopped()) {
d->blockRunningChanged = true;
d->animationInstance->stop();
}
// Render thread animations use "stop" to synchronize the property back
// to the item, so we need to read the value after.
const QVariant ¤tValue = d->property.read();
if (d->targetValue == currentValue) {
QQmlPropertyPrivate::write(d->property, value, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
return;
}
QQuickStateOperation::ActionList actions;
QQuickStateAction action;
action.property = d->property;
action.fromValue = currentValue;
action.toValue = value;
actions << action;
QList<QQmlProperty> after;
QAbstractAnimationJob *prev = d->animationInstance;
d->animationInstance = d->animation->transition(actions, after, QQuickAbstractAnimation::Forward);
if (d->animationInstance && d->animation->threadingModel() == QQuickAbstractAnimation::RenderThread)
d->animationInstance = new QQuickAnimatorProxyJob(d->animationInstance, d->animation);
if (prev && prev != d->animationInstance)
delete prev;
if (d->animationInstance) {
if (d->animationInstance != prev)
d->animationInstance->addAnimationChangeListener(d, QAbstractAnimationJob::StateChange);
d->animationInstance->start();
d->blockRunningChanged = false;
}
if (!after.contains(d->property))
QQmlPropertyPrivate::write(d->property, value, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
}
void QQuickBehavior::setTarget(const QQmlProperty &property)
{
Q_D(QQuickBehavior);
d->property = property;
if (d->animation)
d->animation->setDefaultTarget(property);
QQmlEnginePrivate *engPriv = QQmlEnginePrivate::get(qmlEngine(this));
static int finalizedIdx = -1;
if (finalizedIdx < 0)
finalizedIdx = metaObject()->indexOfSlot("componentFinalized()");
engPriv->registerFinalizeCallback(this, finalizedIdx);
}
void QQuickBehavior::componentFinalized()
{
Q_D(QQuickBehavior);
d->finalized = true;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// This file is part of BlueSky
//
// BlueSky is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// BlueSky 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 BlueSky; if not, see <http://www.gnu.org/licenses/>.
#include "bs_npvec_shared.h"
#include "bs_array.h"
#include "py_bs_exports.h"
#include "py_smart_ptr.h"
using namespace std;
namespace blue_sky {
// usefull typedefs
typedef bs_array< int , bs_npvec_shared > bs_npvec_shared_i;
typedef bs_array< unsigned int , bs_npvec_shared > bs_npvec_shared_ui;
typedef bs_array< long , bs_npvec_shared > bs_npvec_shared_l;
typedef bs_array< long long , bs_npvec_shared > bs_npvec_shared_ll;
typedef bs_array< unsigned long , bs_npvec_shared > bs_npvec_shared_ul;
typedef bs_array< unsigned long long , bs_npvec_shared > bs_npvec_shared_ull;
typedef bs_array< float , bs_npvec_shared > bs_npvec_shared_f;
typedef bs_array< double , bs_npvec_shared > bs_npvec_shared_d;
typedef bs_array< std::string , bs_npvec_shared > bs_npvec_shared_s;
typedef bs_array< std::wstring , bs_npvec_shared > bs_npvec_shared_ws;
// bs_array< T, bs_nparray > instantiations
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned int, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (long long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned long long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::wstring, bs_npvec_shared));
kernel::types_enum register_npvec_shared() {
kernel::types_enum te;
te.push_back(bs_npvec_shared_i::bs_type());
te.push_back(bs_npvec_shared_ui::bs_type());
te.push_back(bs_npvec_shared_l::bs_type());
te.push_back(bs_npvec_shared_ll::bs_type());
te.push_back(bs_npvec_shared_ul::bs_type());
te.push_back(bs_npvec_shared_ull::bs_type());
te.push_back(bs_npvec_shared_f::bs_type());
te.push_back(bs_npvec_shared_d::bs_type());
te.push_back(bs_npvec_shared_s::bs_type());
te.push_back(bs_npvec_shared_ws::bs_type());
return te;
}
}
<commit_msg>bs_array: add explicit bs_npvec_impl instantiations for bs_npvec_shared<commit_after>// This file is part of BlueSky
//
// BlueSky is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// BlueSky 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 BlueSky; if not, see <http://www.gnu.org/licenses/>.
#include "bs_npvec_shared.h"
#include "bs_array.h"
#include "py_bs_exports.h"
#include "py_smart_ptr.h"
using namespace std;
namespace blue_sky {
// usefull typedefs
typedef bs_array< int , bs_npvec_shared > bs_npvec_shared_i;
typedef bs_array< unsigned int , bs_npvec_shared > bs_npvec_shared_ui;
typedef bs_array< long , bs_npvec_shared > bs_npvec_shared_l;
typedef bs_array< long long , bs_npvec_shared > bs_npvec_shared_ll;
typedef bs_array< unsigned long , bs_npvec_shared > bs_npvec_shared_ul;
typedef bs_array< unsigned long long , bs_npvec_shared > bs_npvec_shared_ull;
typedef bs_array< float , bs_npvec_shared > bs_npvec_shared_f;
typedef bs_array< double , bs_npvec_shared > bs_npvec_shared_d;
typedef bs_array< std::string , bs_npvec_shared > bs_npvec_shared_s;
typedef bs_array< std::wstring , bs_npvec_shared > bs_npvec_shared_ws;
// bs_array< T, bs_nparray > instantiations
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (int, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned int, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (long long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (unsigned long long, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (float, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (double, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::string, bs_npvec_shared));
BS_TYPE_IMPL_T_EXT_MEM(bs_array, 2, (std::wstring, bs_npvec_shared));
// explicit instantiations needed by VS when linking with clients
// I think this is just to overcome compiler strange behaviour (bugs?)
template class detail::bs_npvec_impl< bs_array_shared< int > >;
template class detail::bs_npvec_impl< bs_array_shared< unsigned int > >;
template class detail::bs_npvec_impl< bs_array_shared< long > >;
template class detail::bs_npvec_impl< bs_array_shared< unsigned long > >;
template class detail::bs_npvec_impl< bs_array_shared< long long > >;
template class detail::bs_npvec_impl< bs_array_shared< unsigned long long > >;
template class detail::bs_npvec_impl< bs_array_shared< float > >;
template class detail::bs_npvec_impl< bs_array_shared< double > >;
template class detail::bs_npvec_impl< bs_array_shared< std::string > >;
template class detail::bs_npvec_impl< bs_array_shared< std::wstring > >;
kernel::types_enum register_npvec_shared() {
kernel::types_enum te;
te.push_back(bs_npvec_shared_i::bs_type());
te.push_back(bs_npvec_shared_ui::bs_type());
te.push_back(bs_npvec_shared_l::bs_type());
te.push_back(bs_npvec_shared_ll::bs_type());
te.push_back(bs_npvec_shared_ul::bs_type());
te.push_back(bs_npvec_shared_ull::bs_type());
te.push_back(bs_npvec_shared_f::bs_type());
te.push_back(bs_npvec_shared_d::bs_type());
te.push_back(bs_npvec_shared_s::bs_type());
te.push_back(bs_npvec_shared_ws::bs_type());
return te;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include "TranslateKernel.hpp"
#include <pdal/KernelSupport.hpp>
#include <pdal/BufferReader.hpp>
#include <pdal/StageFactory.hpp>
#include <reprojection/ReprojectionFilter.hpp>
namespace pdal
{
TranslateKernel::TranslateKernel() :
Kernel(), m_bCompress(false),
m_input_srs(pdal::SpatialReference()),
m_output_srs(pdal::SpatialReference()), m_bForwardMetadata(false),
m_decimation_step(1), m_decimation_offset(0), m_decimation_leaf_size(1), m_decimation_limit(0)
{}
void TranslateKernel::validateSwitches()
{
if (m_inputFile == "")
throw app_usage_error("--input/-i required");
if (m_outputFile == "")
throw app_usage_error("--output/-o required");
//
// auto options = getExtraOptions();
//
// for (const auto& o : options)
// {
//
// typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
//
// // if we don't have --, we're not an option we
// // even care about
// if (!boost::algorithm::find_first(o, "--")) continue;
//
// // Find the dimensions listed and put them on the id list.
// boost::char_separator<char> equal("=");
// boost::char_separator<char> dot(".");
// // boost::erase_all(o, " "); // Wipe off spaces
// tokenizer option_tokens(o, equal);
// std::vector<std::string> option_split;
// for (auto ti = option_tokens.begin(); ti != option_tokens.end(); ++ti)
// option_split.push_back(boost::lexical_cast<std::string>(*ti));
// if (! (option_split.size() == 2))
// {
// std::ostringstream oss;
// oss << "option '" << o << "' did not split correctly. Is it in the form --readers.las.option=foo?";
// throw app_usage_error(oss.str());
// }
//
// std::string option_value(option_split[1]);
// std::string stage_value(option_split[0]);
// boost::algorithm::erase_all(stage_value, "--");
//
// tokenizer name_tokens(stage_value, dot);
// std::vector<std::string> stage_values;
// for (auto ti = name_tokens.begin(); ti != name_tokens.end(); ++ti)
// {
// stage_values.push_back(*ti);
// }
//
// std::string option_name = *stage_values.rbegin();
// std::ostringstream stage_name_ostr;
// bool bFirst(true);
// for (auto s = stage_values.begin(); s != stage_values.end()-1; ++s)
// {
// auto s2 = boost::algorithm::erase_all_copy(*s, " ");
//
// if (bFirst)
// {
// bFirst = false;
// } else
// stage_name_ostr <<".";
// stage_name_ostr << s2;
// }
// std::string stage_name(stage_name_ostr.str());
// std::cout << "stage name: '" << stage_name << "' option_name: '" << option_name << "' option value: '" << option_value <<"'"<<std::endl;
//
// auto found = m_stage_options.find(stage_name);
// if (found == m_stage_options.end())
// m_stage_options.insert(std::make_pair(stage_name, Option(option_name, option_value, "")));
// else
// found->second.add(Option(option_name, option_value, ""));
// }
}
void TranslateKernel::addSwitches()
{
po::options_description* file_options =
new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""),
"input file name")
("output,o", po::value<std::string>(&m_outputFile)->default_value(""),
"output file name")
("a_srs", po::value<pdal::SpatialReference>(&m_input_srs),
"Assign input coordinate system (if supported by output format)")
("t_srs", po::value<pdal::SpatialReference>(&m_output_srs),
"Transform to output coordinate system (if supported by "
"output format)")
("compress,z",
po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),
"Compress output data (if supported by output format)")
("bounds", po::value<BOX3D >(&m_bounds),
"Extent (in XYZ to clip output to)")
("polygon", po::value<std::string >(&m_wkt),
"POLYGON WKT to use for precise crop of data (2d or 3d)")
("metadata,m",
po::value< bool >(&m_bForwardMetadata)->implicit_value(true),
"Forward metadata (VLRs, header entries, etc) from previous stages")
("d_step",
po::value<uint32_t>(&m_decimation_step)->default_value(1),
"Decimation filter step")
("d_offset",
po::value<uint32_t>(&m_decimation_offset)->default_value(0),
"Decimation filter offset")
("d_leaf_size",
po::value<double>(&m_decimation_leaf_size)->default_value(1),
"Decimation filter leaf size")
("d_method",
po::value<std::string>(&m_decimation_method)->default_value("RankOrder"),
"Decimation filter method (RankOrder, VoxelGrid)")
("d_limit",
po::value<point_count_t>(&m_decimation_limit)->default_value(0),
"Decimation limit")
;
addSwitchSet(file_options);
addPositionalSwitch("input", 1);
addPositionalSwitch("output", 1);
}
std::unique_ptr<Stage> TranslateKernel::makeReader(Options readerOptions)
{
if (isDebug())
{
readerOptions.add("debug", true);
uint32_t verbosity(getVerboseLevel());
if (!verbosity)
verbosity = 1;
readerOptions.add("verbose", verbosity);
readerOptions.add("log", "STDERR");
}
Stage* stage = KernelSupport::makeReader(m_inputFile);
stage->setOptions(readerOptions);
std::unique_ptr<Stage> reader_stage(stage);
return reader_stage;
}
Stage* TranslateKernel::makeTranslate(Options translateOptions, Stage* reader_stage)
{
Stage* final_stage = reader_stage;
Options readerOptions = reader_stage->getOptions();
std::map<std::string, Options> extra_opts = getExtraStageOptions();
if (!m_bounds.empty() || !m_wkt.empty() || !m_output_srs.empty() || extra_opts.size() > 0)
{
Stage* next_stage = reader_stage;
Stage* crop_stage(0);
Stage* reprojection_stage(0);
bool bHaveReprojection = extra_opts.find("filters.reprojection") != extra_opts.end();
bool bHaveCrop = extra_opts.find("filters.crop") != extra_opts.end();
if (!m_output_srs.empty())
{
translateOptions.add("out_srs", m_output_srs.getWKT());
reprojection_stage =
new ReprojectionFilter();
reprojection_stage->setInput(next_stage);
reprojection_stage->setOptions(readerOptions);
next_stage = reprojection_stage;
} else if (bHaveReprojection)
{
reprojection_stage =
new ReprojectionFilter();
reprojection_stage->setInput(next_stage);
reprojection_stage->setOptions(extra_opts.find("filters.reprojection")->second);
next_stage = reprojection_stage;
}
if ((!m_bounds.empty() && m_wkt.empty()))
{
readerOptions.add("bounds", m_bounds);
crop_stage->setInput(next_stage);
crop_stage->setOptions(readerOptions);
next_stage = crop_stage;
}
else if (m_bounds.empty() && !m_wkt.empty())
{
std::istream* wkt_stream;
try
{
wkt_stream = FileUtils::openFile(m_wkt);
std::stringstream buffer;
buffer << wkt_stream->rdbuf();
m_wkt = buffer.str();
FileUtils::closeFile(wkt_stream);
}
catch (pdal::pdal_error const&)
{
// If we couldn't open the file given in m_wkt because it
// was likely actually wkt, leave it alone
}
readerOptions.add("polygon", m_wkt);
crop_stage->setInput(next_stage);
crop_stage->setOptions(readerOptions);
next_stage = crop_stage;
} else if (bHaveCrop)
{
crop_stage->setInput(next_stage);
crop_stage->setOptions(extra_opts.find("filters.crop")->second);
next_stage = crop_stage;
}
final_stage = next_stage;
}
if (boost::iequals(m_decimation_method, "VoxelGrid"))
{
StageFactory f;
Stage* decimation_stage(f.createFilter("filters.pclblock"));
Options decimationOptions;
std::ostringstream ss;
ss << "{";
ss << " \"pipeline\": {";
ss << " \"filters\": [{";
ss << " \"name\": \"VoxelGrid\",";
ss << " \"setLeafSize\": {";
ss << " \"x\": " << m_decimation_leaf_size << ",";
ss << " \"y\": " << m_decimation_leaf_size << ",";
ss << " \"z\": " << m_decimation_leaf_size;
ss << " }";
ss << " }]";
ss << " }";
ss << "}";
std::string json = ss.str();
decimationOptions.add<std::string>("json", json);
decimationOptions.add<bool>("debug", isDebug());
decimationOptions.add<uint32_t>("verbose", getVerboseLevel());
decimation_stage->setOptions(decimationOptions);
decimation_stage->setInput(final_stage);
final_stage = decimation_stage;
}
else if (m_decimation_step > 1 || m_decimation_limit > 0)
{
Options decimationOptions;
decimationOptions.add("debug", isDebug());
decimationOptions.add("verbose", getVerboseLevel());
decimationOptions.add("step", m_decimation_step);
decimationOptions.add("offset", m_decimation_offset);
decimationOptions.add("limit", m_decimation_limit);
StageFactory f;
Stage* decimation_stage(f.createFilter("filters.decimation"));
decimation_stage->setInput(final_stage);
decimation_stage->setOptions(decimationOptions);
final_stage = decimation_stage;
}
return final_stage;
}
int TranslateKernel::execute()
{
PointContext ctx;
Options readerOptions;
readerOptions.add("filename", m_inputFile);
readerOptions.add("debug", isDebug());
readerOptions.add("verbose", getVerboseLevel());
if (!m_input_srs.empty())
readerOptions.add("spatialreference", m_input_srs.getWKT());
std::unique_ptr<Stage> readerStage = makeReader(readerOptions);
// go ahead and prepare/execute on reader stage only to grab input
// PointBufferSet, this makes the input PointBuffer available to both the
// processing pipeline and the visualizer
readerStage->prepare(ctx);
PointBufferSet pbSetIn = readerStage->execute(ctx);
// the input PointBufferSet will be used to populate a BufferReader that is
// consumed by the processing pipeline
PointBufferPtr input_buffer = *pbSetIn.begin();
BufferReader bufferReader;
bufferReader.setOptions(readerOptions);
bufferReader.addBuffer(input_buffer);
// the translation consumes the BufferReader rather than the readerStage
Stage* finalStage = makeTranslate(readerOptions, &bufferReader);
Options writerOptions;
writerOptions.add("filename", m_outputFile);
setCommonOptions(writerOptions);
if (!m_input_srs.empty())
writerOptions.add("spatialreference", m_input_srs.getWKT());
if (m_bCompress)
writerOptions.add("compression", true);
if (m_bForwardMetadata)
writerOptions.add("forward_metadata", true);
std::vector<std::string> cmd = getProgressShellCommand();
UserCallback *callback =
cmd.size() ? (UserCallback *)new ShellScriptCallback(cmd) :
(UserCallback *)new HeartbeatCallback();
WriterPtr writer( KernelSupport::makeWriter(m_outputFile, finalStage));
if (!m_output_srs.empty())
writer->setSpatialReference(m_output_srs);
// Some options are inferred by makeWriter based on filename
// (compression, driver type, etc).
writer->setOptions(writerOptions+writer->getOptions());
// writer->setUserCallback(callback);
for (const auto& pi : getExtraStageOptions())
{
std::string name = pi.first;
Options options = pi.second;
std::vector<Stage*> stages = writer->findStage(name);
for (const auto& s : stages)
{
Options opts = s->getOptions();
for (const auto& o : options.getOptions())
opts.add(o);
s->setOptions(opts);
}
}
writer->prepare(ctx);
// process the data, grabbing the PointBufferSet for visualization of the
PointBufferSet pbSetOut = writer->execute(ctx);
if (isVisualize())
visualize(*pbSetOut.begin());
//visualize(*pbSetIn.begin(), *pbSetOut.begin());
return 0;
}
} // namespace pdal
<commit_msg>Fix NULL pointer in `pdal translate --polygon`<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include "TranslateKernel.hpp"
#include <pdal/KernelSupport.hpp>
#include <pdal/BufferReader.hpp>
#include <pdal/StageFactory.hpp>
#include <reprojection/ReprojectionFilter.hpp>
namespace pdal
{
TranslateKernel::TranslateKernel() :
Kernel(), m_bCompress(false),
m_input_srs(pdal::SpatialReference()),
m_output_srs(pdal::SpatialReference()), m_bForwardMetadata(false),
m_decimation_step(1), m_decimation_offset(0), m_decimation_leaf_size(1), m_decimation_limit(0)
{}
void TranslateKernel::validateSwitches()
{
if (m_inputFile == "")
throw app_usage_error("--input/-i required");
if (m_outputFile == "")
throw app_usage_error("--output/-o required");
//
// auto options = getExtraOptions();
//
// for (const auto& o : options)
// {
//
// typedef boost::tokenizer<boost::char_separator<char>> tokenizer;
//
// // if we don't have --, we're not an option we
// // even care about
// if (!boost::algorithm::find_first(o, "--")) continue;
//
// // Find the dimensions listed and put them on the id list.
// boost::char_separator<char> equal("=");
// boost::char_separator<char> dot(".");
// // boost::erase_all(o, " "); // Wipe off spaces
// tokenizer option_tokens(o, equal);
// std::vector<std::string> option_split;
// for (auto ti = option_tokens.begin(); ti != option_tokens.end(); ++ti)
// option_split.push_back(boost::lexical_cast<std::string>(*ti));
// if (! (option_split.size() == 2))
// {
// std::ostringstream oss;
// oss << "option '" << o << "' did not split correctly. Is it in the form --readers.las.option=foo?";
// throw app_usage_error(oss.str());
// }
//
// std::string option_value(option_split[1]);
// std::string stage_value(option_split[0]);
// boost::algorithm::erase_all(stage_value, "--");
//
// tokenizer name_tokens(stage_value, dot);
// std::vector<std::string> stage_values;
// for (auto ti = name_tokens.begin(); ti != name_tokens.end(); ++ti)
// {
// stage_values.push_back(*ti);
// }
//
// std::string option_name = *stage_values.rbegin();
// std::ostringstream stage_name_ostr;
// bool bFirst(true);
// for (auto s = stage_values.begin(); s != stage_values.end()-1; ++s)
// {
// auto s2 = boost::algorithm::erase_all_copy(*s, " ");
//
// if (bFirst)
// {
// bFirst = false;
// } else
// stage_name_ostr <<".";
// stage_name_ostr << s2;
// }
// std::string stage_name(stage_name_ostr.str());
// std::cout << "stage name: '" << stage_name << "' option_name: '" << option_name << "' option value: '" << option_value <<"'"<<std::endl;
//
// auto found = m_stage_options.find(stage_name);
// if (found == m_stage_options.end())
// m_stage_options.insert(std::make_pair(stage_name, Option(option_name, option_value, "")));
// else
// found->second.add(Option(option_name, option_value, ""));
// }
}
void TranslateKernel::addSwitches()
{
po::options_description* file_options =
new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile)->default_value(""),
"input file name")
("output,o", po::value<std::string>(&m_outputFile)->default_value(""),
"output file name")
("a_srs", po::value<pdal::SpatialReference>(&m_input_srs),
"Assign input coordinate system (if supported by output format)")
("t_srs", po::value<pdal::SpatialReference>(&m_output_srs),
"Transform to output coordinate system (if supported by "
"output format)")
("compress,z",
po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),
"Compress output data (if supported by output format)")
("bounds", po::value<BOX3D >(&m_bounds),
"Extent (in XYZ to clip output to)")
("polygon", po::value<std::string >(&m_wkt),
"POLYGON WKT to use for precise crop of data (2d or 3d)")
("metadata,m",
po::value< bool >(&m_bForwardMetadata)->implicit_value(true),
"Forward metadata (VLRs, header entries, etc) from previous stages")
("d_step",
po::value<uint32_t>(&m_decimation_step)->default_value(1),
"Decimation filter step")
("d_offset",
po::value<uint32_t>(&m_decimation_offset)->default_value(0),
"Decimation filter offset")
("d_leaf_size",
po::value<double>(&m_decimation_leaf_size)->default_value(1),
"Decimation filter leaf size")
("d_method",
po::value<std::string>(&m_decimation_method)->default_value("RankOrder"),
"Decimation filter method (RankOrder, VoxelGrid)")
("d_limit",
po::value<point_count_t>(&m_decimation_limit)->default_value(0),
"Decimation limit")
;
addSwitchSet(file_options);
addPositionalSwitch("input", 1);
addPositionalSwitch("output", 1);
}
std::unique_ptr<Stage> TranslateKernel::makeReader(Options readerOptions)
{
if (isDebug())
{
readerOptions.add("debug", true);
uint32_t verbosity(getVerboseLevel());
if (!verbosity)
verbosity = 1;
readerOptions.add("verbose", verbosity);
readerOptions.add("log", "STDERR");
}
Stage* stage = KernelSupport::makeReader(m_inputFile);
stage->setOptions(readerOptions);
std::unique_ptr<Stage> reader_stage(stage);
return reader_stage;
}
Stage* TranslateKernel::makeTranslate(Options translateOptions, Stage* reader_stage)
{
StageFactory f;
Stage* final_stage = reader_stage;
Options readerOptions = reader_stage->getOptions();
std::map<std::string, Options> extra_opts = getExtraStageOptions();
if (!m_bounds.empty() || !m_wkt.empty() || !m_output_srs.empty() || extra_opts.size() > 0)
{
Stage* next_stage = reader_stage;
Stage* crop_stage = f.createFilter("filters.crop");
Stage* reprojection_stage = f.createFilter("filters.reprojection");
bool bHaveReprojection = extra_opts.find("filters.reprojection") != extra_opts.end();
bool bHaveCrop = extra_opts.find("filters.crop") != extra_opts.end();
if (!m_output_srs.empty())
{
translateOptions.add("out_srs", m_output_srs.getWKT());
reprojection_stage =
new ReprojectionFilter();
reprojection_stage->setInput(next_stage);
reprojection_stage->setOptions(readerOptions);
next_stage = reprojection_stage;
} else if (bHaveReprojection)
{
reprojection_stage =
new ReprojectionFilter();
reprojection_stage->setInput(next_stage);
reprojection_stage->setOptions(extra_opts.find("filters.reprojection")->second);
next_stage = reprojection_stage;
}
if ((!m_bounds.empty() && m_wkt.empty()))
{
readerOptions.add("bounds", m_bounds);
crop_stage->setInput(next_stage);
crop_stage->setOptions(readerOptions);
next_stage = crop_stage;
}
else if (m_bounds.empty() && !m_wkt.empty())
{
std::istream* wkt_stream;
try
{
wkt_stream = FileUtils::openFile(m_wkt);
std::stringstream buffer;
buffer << wkt_stream->rdbuf();
m_wkt = buffer.str();
FileUtils::closeFile(wkt_stream);
}
catch (pdal::pdal_error const&)
{
// If we couldn't open the file given in m_wkt because it
// was likely actually wkt, leave it alone
}
readerOptions.add("polygon", m_wkt);
crop_stage->setInput(next_stage);
crop_stage->setOptions(readerOptions);
next_stage = crop_stage;
} else if (bHaveCrop)
{
crop_stage->setInput(next_stage);
crop_stage->setOptions(extra_opts.find("filters.crop")->second);
next_stage = crop_stage;
}
final_stage = next_stage;
}
if (boost::iequals(m_decimation_method, "VoxelGrid"))
{
Stage* decimation_stage(f.createFilter("filters.pclblock"));
Options decimationOptions;
std::ostringstream ss;
ss << "{";
ss << " \"pipeline\": {";
ss << " \"filters\": [{";
ss << " \"name\": \"VoxelGrid\",";
ss << " \"setLeafSize\": {";
ss << " \"x\": " << m_decimation_leaf_size << ",";
ss << " \"y\": " << m_decimation_leaf_size << ",";
ss << " \"z\": " << m_decimation_leaf_size;
ss << " }";
ss << " }]";
ss << " }";
ss << "}";
std::string json = ss.str();
decimationOptions.add<std::string>("json", json);
decimationOptions.add<bool>("debug", isDebug());
decimationOptions.add<uint32_t>("verbose", getVerboseLevel());
decimation_stage->setOptions(decimationOptions);
decimation_stage->setInput(final_stage);
final_stage = decimation_stage;
}
else if (m_decimation_step > 1 || m_decimation_limit > 0)
{
Options decimationOptions;
decimationOptions.add("debug", isDebug());
decimationOptions.add("verbose", getVerboseLevel());
decimationOptions.add("step", m_decimation_step);
decimationOptions.add("offset", m_decimation_offset);
decimationOptions.add("limit", m_decimation_limit);
Stage* decimation_stage(f.createFilter("filters.decimation"));
decimation_stage->setInput(final_stage);
decimation_stage->setOptions(decimationOptions);
final_stage = decimation_stage;
}
return final_stage;
}
int TranslateKernel::execute()
{
PointContext ctx;
Options readerOptions;
readerOptions.add("filename", m_inputFile);
readerOptions.add("debug", isDebug());
readerOptions.add("verbose", getVerboseLevel());
if (!m_input_srs.empty())
readerOptions.add("spatialreference", m_input_srs.getWKT());
std::unique_ptr<Stage> readerStage = makeReader(readerOptions);
// go ahead and prepare/execute on reader stage only to grab input
// PointBufferSet, this makes the input PointBuffer available to both the
// processing pipeline and the visualizer
readerStage->prepare(ctx);
PointBufferSet pbSetIn = readerStage->execute(ctx);
// the input PointBufferSet will be used to populate a BufferReader that is
// consumed by the processing pipeline
PointBufferPtr input_buffer = *pbSetIn.begin();
BufferReader bufferReader;
bufferReader.setOptions(readerOptions);
bufferReader.addBuffer(input_buffer);
// the translation consumes the BufferReader rather than the readerStage
Stage* finalStage = makeTranslate(readerOptions, &bufferReader);
Options writerOptions;
writerOptions.add("filename", m_outputFile);
setCommonOptions(writerOptions);
if (!m_input_srs.empty())
writerOptions.add("spatialreference", m_input_srs.getWKT());
if (m_bCompress)
writerOptions.add("compression", true);
if (m_bForwardMetadata)
writerOptions.add("forward_metadata", true);
std::vector<std::string> cmd = getProgressShellCommand();
UserCallback *callback =
cmd.size() ? (UserCallback *)new ShellScriptCallback(cmd) :
(UserCallback *)new HeartbeatCallback();
WriterPtr writer( KernelSupport::makeWriter(m_outputFile, finalStage));
if (!m_output_srs.empty())
writer->setSpatialReference(m_output_srs);
// Some options are inferred by makeWriter based on filename
// (compression, driver type, etc).
writer->setOptions(writerOptions+writer->getOptions());
// writer->setUserCallback(callback);
for (const auto& pi : getExtraStageOptions())
{
std::string name = pi.first;
Options options = pi.second;
std::vector<Stage*> stages = writer->findStage(name);
for (const auto& s : stages)
{
Options opts = s->getOptions();
for (const auto& o : options.getOptions())
opts.add(o);
s->setOptions(opts);
}
}
writer->prepare(ctx);
// process the data, grabbing the PointBufferSet for visualization of the
PointBufferSet pbSetOut = writer->execute(ctx);
if (isVisualize())
visualize(*pbSetOut.begin());
//visualize(*pbSetIn.begin(), *pbSetOut.begin());
return 0;
}
} // namespace pdal
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kdebug.h>
#include <klocale.h>
#include "koglobals.h"
#include "navigatorbar.h"
#include "kdatenavigator.h"
#include <kcalendarsystem.h>
#include <kdialog.h>
#include "datenavigatorcontainer.h"
#include <QTimer>
#include <QFrame>
#include <QResizeEvent>
DateNavigatorContainer::DateNavigatorContainer( QWidget *parent )
: QFrame( parent ), mCalendar( 0 ),
mHorizontalCount( 1 ), mVerticalCount( 1 )
{
setFrameStyle( QFrame::Sunken | QFrame::StyledPanel );
mNavigatorView = new KDateNavigator( this );
mNavigatorView->setWhatsThis(
i18n( "<qt><p>Select the dates you want to "
"display in KOrganizer's main view here. Hold the "
"mouse button to select more than one day.</p>"
"<p>Press the top buttons to browse to the next "
"/ previous months or years.</p>"
"<p>Each line shows a week. The number in the left "
"column is the number of the week in the year. "
"Press it to select the whole week.</p>"
"</qt>" ) );
connectNavigatorView( mNavigatorView );
}
DateNavigatorContainer::~DateNavigatorContainer()
{
qDeleteAll( mExtraViews );
}
void DateNavigatorContainer::connectNavigatorView( KDateNavigator *v )
{
connect( v, SIGNAL( datesSelected( const KCal::DateList & ) ),
SIGNAL( datesSelected( const KCal::DateList & ) ) );
connect( v, SIGNAL( incidenceDropped( Incidence *, const QDate & ) ),
SIGNAL( incidenceDropped( Incidence *, const QDate & ) ) );
connect( v, SIGNAL( incidenceDroppedMove( Incidence *, const QDate & ) ),
SIGNAL( incidenceDroppedMove( Incidence *, const QDate & ) ) );
connect( v, SIGNAL( weekClicked( const QDate & ) ),
SIGNAL( weekClicked( const QDate & ) ) );
connect( v, SIGNAL( goPrevious() ), SIGNAL( goPrevious() ) );
connect( v, SIGNAL( goNext() ), SIGNAL( goNext() ) );
connect( v, SIGNAL( goNextMonth() ), SIGNAL( goNextMonth() ) );
connect( v, SIGNAL( goPrevMonth() ), SIGNAL( goPrevMonth() ) );
connect( v, SIGNAL( goNextYear() ), SIGNAL( goNextYear() ) );
connect( v, SIGNAL( goPrevYear() ), SIGNAL( goPrevYear() ) );
connect( v, SIGNAL( goMonth( int ) ), SIGNAL( goMonth( int ) ) );
}
void DateNavigatorContainer::setCalendar( Calendar *cal )
{
mCalendar = cal;
mNavigatorView->setCalendar( cal );
foreach( KDateNavigator *n, mExtraViews ) { if (n) n->setCalendar( cal ); }
}
// TODO_Recurrence: let the navigators update just once, and tell them that
// if data has changed or just the selection (because then the list of dayss
// with events doesn't have to be updated if the month stayed the same
void DateNavigatorContainer::updateDayMatrix()
{
mNavigatorView->updateDayMatrix();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateDayMatrix(); }
}
void DateNavigatorContainer::updateToday()
{
mNavigatorView->updateToday();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateToday(); }
}
void DateNavigatorContainer::updateView()
{
mNavigatorView->updateView();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateView(); }
}
void DateNavigatorContainer::updateConfig()
{
mNavigatorView->updateConfig();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateConfig(); }
}
void DateNavigatorContainer::selectDates( const DateList &dateList )
{
if ( !dateList.isEmpty() ) {
QDate start( dateList.first() );
QDate end( dateList.last() );
QDate navfirst( mNavigatorView->startDate() );
QDate navsecond; // start of the second shown month if existant
QDate navlast;
if ( !mExtraViews.isEmpty() ) {
navlast = mExtraViews.last()->endDate();
navsecond = mExtraViews.first()->startDate();
} else {
navlast = mNavigatorView->endDate();
navsecond = navfirst;
}
if ( start < navfirst // <- start should always be visible
// end is not visible and we have a spare month at the beginning:
|| ( end > navlast && start >= navsecond ) ) {
// Change the shown months so that the beginning of the date list is visible
setBaseDates( start );
}
mNavigatorView->selectDates( dateList );
foreach ( KDateNavigator *n, mExtraViews ) {
if (n) n->selectDates( dateList );
}
}
}
void DateNavigatorContainer::setBaseDates( const QDate &start )
{
QDate baseDate = start;
mNavigatorView->setBaseDate( baseDate );
foreach ( KDateNavigator *n, mExtraViews ) {
baseDate = KOGlobals::self()->calendarSystem()->addMonths( baseDate, 1 );
n->setBaseDate( baseDate );
}
}
void DateNavigatorContainer::resizeEvent( QResizeEvent * )
{
#if 0
kDebug(5850) << "DateNavigatorContainer::resizeEvent()" << endl;
kDebug(5850) << " CURRENT SIZE: " << size() << endl;
kDebug(5850) << " MINIMUM SIZEHINT: " << minimumSizeHint() << endl;
kDebug(5850) << " SIZEHINT: " << sizeHint() << endl;
kDebug(5850) << " MINIMUM SIZE: " << minimumSize() << endl;
#endif
QTimer::singleShot( 0, this, SLOT( resizeAllContents() ) );
}
void DateNavigatorContainer::resizeAllContents()
{
QSize minSize = mNavigatorView->minimumSizeHint();
// kDebug(5850) << " NAVIGATORVIEW minimumSizeHint: " << minSize << endl;
int margin = KDialog::spacingHint();
int verticalCount = ( size().height() - margin*2 ) / minSize.height();
int horizontalCount = ( size().width() - margin*2 ) / minSize.width();
if ( horizontalCount != mHorizontalCount ||
verticalCount != mVerticalCount ) {
int count = horizontalCount * verticalCount;
if ( count == 0 ) return;
while ( count > ( mExtraViews.count() + 1 ) ) {
KDateNavigator *n = new KDateNavigator( this );
mExtraViews.append( n );
n->setCalendar( mCalendar );
connectNavigatorView( n );
}
while ( count < ( mExtraViews.count() + 1 ) ) {
delete ( mExtraViews.last() );
mExtraViews.removeLast();
}
mHorizontalCount = horizontalCount;
mVerticalCount = verticalCount;
selectDates( mNavigatorView->selectedDates() );
foreach( KDateNavigator *n, mExtraViews ) { if ( n ) n->show(); }
}
int height = (size().height() - margin*2) / verticalCount;
int width = (size().width() - margin*2) / horizontalCount;
NavigatorBar *bar = mNavigatorView->navigatorBar();
if ( horizontalCount > 1 ) bar->showButtons( true, false );
else bar->showButtons( true, true );
mNavigatorView->setGeometry(
( ( (KOGlobals::self()->reverseLayout())?(horizontalCount-1):0) * width ) + margin,
margin, width, height );
for( int i = 0; i < mExtraViews.count(); ++i ) {
int x = ( i + 1 ) % horizontalCount;
int y = ( i + 1 ) / horizontalCount;
KDateNavigator *view = mExtraViews.at( i );
bar = view->navigatorBar();
if ( y > 0 ) bar->showButtons( false, false );
else {
if ( x + 1 == horizontalCount ) bar->showButtons( false, true );
else bar->showButtons( false, false );
}
view->setGeometry(
( ( (KOGlobals::self()->reverseLayout())?(horizontalCount-1-x):x) * width ) + margin,
( y * height ) + margin, width, height );
}
}
QSize DateNavigatorContainer::minimumSizeHint() const
{
int margin = KDialog::spacingHint() * 2;
return mNavigatorView->minimumSizeHint() + QSize( margin, margin );
}
QSize DateNavigatorContainer::sizeHint() const
{
int margin = KDialog::spacingHint() * 2;
return mNavigatorView->sizeHint() + QSize( margin, margin );
}
#include "datenavigatorcontainer.moc"
<commit_msg>forward port SVN commit 540317 by bram:<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2001,2002,2003 Cornelius Schumacher <schumacher@kde.org>
Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kdebug.h>
#include <klocale.h>
#include "koglobals.h"
#include "navigatorbar.h"
#include "kdatenavigator.h"
#include <kcalendarsystem.h>
#include <kdialog.h>
#include "datenavigatorcontainer.h"
#include <QTimer>
#include <QFrame>
#include <QResizeEvent>
DateNavigatorContainer::DateNavigatorContainer( QWidget *parent )
: QFrame( parent ), mCalendar( 0 ),
mHorizontalCount( 1 ), mVerticalCount( 1 )
{
setFrameStyle( QFrame::Sunken | QFrame::StyledPanel );
mNavigatorView = new KDateNavigator( this );
mNavigatorView->setWhatsThis(
i18n( "<qt><p>Select the dates you want to "
"display in KOrganizer's main view here. Hold the "
"mouse button to select more than one day.</p>"
"<p>Press the top buttons to browse to the next "
"/ previous months or years.</p>"
"<p>Each line shows a week. The number in the left "
"column is the number of the week in the year. "
"Press it to select the whole week.</p>"
"</qt>" ) );
connectNavigatorView( mNavigatorView );
}
DateNavigatorContainer::~DateNavigatorContainer()
{
qDeleteAll( mExtraViews );
}
void DateNavigatorContainer::connectNavigatorView( KDateNavigator *v )
{
connect( v, SIGNAL( datesSelected( const KCal::DateList & ) ),
SIGNAL( datesSelected( const KCal::DateList & ) ) );
connect( v, SIGNAL( incidenceDropped( Incidence *, const QDate & ) ),
SIGNAL( incidenceDropped( Incidence *, const QDate & ) ) );
connect( v, SIGNAL( incidenceDroppedMove( Incidence *, const QDate & ) ),
SIGNAL( incidenceDroppedMove( Incidence *, const QDate & ) ) );
connect( v, SIGNAL( weekClicked( const QDate & ) ),
SIGNAL( weekClicked( const QDate & ) ) );
connect( v, SIGNAL( goPrevious() ), SIGNAL( goPrevious() ) );
connect( v, SIGNAL( goNext() ), SIGNAL( goNext() ) );
connect( v, SIGNAL( goNextMonth() ), SIGNAL( goNextMonth() ) );
connect( v, SIGNAL( goPrevMonth() ), SIGNAL( goPrevMonth() ) );
connect( v, SIGNAL( goNextYear() ), SIGNAL( goNextYear() ) );
connect( v, SIGNAL( goPrevYear() ), SIGNAL( goPrevYear() ) );
connect( v, SIGNAL( goMonth( int ) ), SIGNAL( goMonth( int ) ) );
}
void DateNavigatorContainer::setCalendar( Calendar *cal )
{
mCalendar = cal;
mNavigatorView->setCalendar( cal );
foreach( KDateNavigator *n, mExtraViews ) { if (n) n->setCalendar( cal ); }
}
// TODO_Recurrence: let the navigators update just once, and tell them that
// if data has changed or just the selection (because then the list of dayss
// with events doesn't have to be updated if the month stayed the same
void DateNavigatorContainer::updateDayMatrix()
{
mNavigatorView->updateDayMatrix();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateDayMatrix(); }
}
void DateNavigatorContainer::updateToday()
{
mNavigatorView->updateToday();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateToday(); }
}
void DateNavigatorContainer::updateView()
{
mNavigatorView->updateView();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateView(); }
}
void DateNavigatorContainer::updateConfig()
{
mNavigatorView->updateConfig();
foreach ( KDateNavigator *n, mExtraViews ) { if (n) n->updateConfig(); }
}
void DateNavigatorContainer::selectDates( const DateList &dateList )
{
if ( !dateList.isEmpty() ) {
QDate start( dateList.first() );
QDate end( dateList.last() );
QDate navfirst( mNavigatorView->startDate() );
QDate navsecond; // start of the second shown month if existant
QDate navlast;
if ( !mExtraViews.isEmpty() ) {
navlast = mExtraViews.last()->endDate();
navsecond = mExtraViews.first()->startDate();
} else {
navlast = mNavigatorView->endDate();
navsecond = navfirst;
}
if ( start < navfirst // <- start should always be visible
// end is not visible and we have a spare month at the beginning:
|| ( end > navlast && start >= navsecond ) ) {
// Change the shown months so that the beginning of the date list is visible
setBaseDates( start );
}
mNavigatorView->selectDates( dateList );
foreach ( KDateNavigator *n, mExtraViews ) {
if (n) n->selectDates( dateList );
}
}
}
void DateNavigatorContainer::setBaseDates( const QDate &start )
{
QDate baseDate = start;
mNavigatorView->setBaseDate( baseDate );
foreach ( KDateNavigator *n, mExtraViews ) {
baseDate = KOGlobals::self()->calendarSystem()->addMonths( baseDate, 1 );
n->setBaseDate( baseDate );
}
}
void DateNavigatorContainer::resizeEvent( QResizeEvent * )
{
#if 0
kDebug(5850) << "DateNavigatorContainer::resizeEvent()" << endl;
kDebug(5850) << " CURRENT SIZE: " << size() << endl;
kDebug(5850) << " MINIMUM SIZEHINT: " << minimumSizeHint() << endl;
kDebug(5850) << " SIZEHINT: " << sizeHint() << endl;
kDebug(5850) << " MINIMUM SIZE: " << minimumSize() << endl;
#endif
QTimer::singleShot( 0, this, SLOT( resizeAllContents() ) );
}
void DateNavigatorContainer::resizeAllContents()
{
QSize minSize = mNavigatorView->minimumSizeHint();
// kDebug(5850) << " NAVIGATORVIEW minimumSizeHint: " << minSize << endl;
int margin = KDialog::spacingHint();
int verticalCount = ( size().height() - margin*2 ) / minSize.height();
int horizontalCount = ( size().width() - margin*2 ) / minSize.width();
if ( horizontalCount != mHorizontalCount ||
verticalCount != mVerticalCount ) {
int count = horizontalCount * verticalCount;
if ( count == 0 ) return;
while ( count > ( mExtraViews.count() + 1 ) ) {
KDateNavigator *n = new KDateNavigator( this );
mExtraViews.append( n );
n->setCalendar( mCalendar );
connectNavigatorView( n );
}
while ( count < ( mExtraViews.count() + 1 ) ) {
delete ( mExtraViews.last() );
mExtraViews.removeLast();
}
mHorizontalCount = horizontalCount;
mVerticalCount = verticalCount;
setBaseDates( mNavigatorView->selectedDates().first() );
selectDates( mNavigatorView->selectedDates() );
foreach( KDateNavigator *n, mExtraViews ) { if ( n ) n->show(); }
}
int height = (size().height() - margin*2) / verticalCount;
int width = (size().width() - margin*2) / horizontalCount;
NavigatorBar *bar = mNavigatorView->navigatorBar();
if ( horizontalCount > 1 ) bar->showButtons( true, false );
else bar->showButtons( true, true );
mNavigatorView->setGeometry(
( ( (KOGlobals::self()->reverseLayout())?(horizontalCount-1):0) * width ) + margin,
margin, width, height );
for( int i = 0; i < mExtraViews.count(); ++i ) {
int x = ( i + 1 ) % horizontalCount;
int y = ( i + 1 ) / horizontalCount;
KDateNavigator *view = mExtraViews.at( i );
bar = view->navigatorBar();
if ( y > 0 ) bar->showButtons( false, false );
else {
if ( x + 1 == horizontalCount ) bar->showButtons( false, true );
else bar->showButtons( false, false );
}
view->setGeometry(
( ( (KOGlobals::self()->reverseLayout())?(horizontalCount-1-x):x) * width ) + margin,
( y * height ) + margin, width, height );
}
}
QSize DateNavigatorContainer::minimumSizeHint() const
{
int margin = KDialog::spacingHint() * 2;
return mNavigatorView->minimumSizeHint() + QSize( margin, margin );
}
QSize DateNavigatorContainer::sizeHint() const
{
int margin = KDialog::spacingHint() * 2;
return mNavigatorView->sizeHint() + QSize( margin, margin );
}
#include "datenavigatorcontainer.moc"
<|endoftext|> |
<commit_before>#include "glyph_object_creation.hpp"
#include "vector_font.hpp"
#include "text3D.hpp"
#include "object.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
namespace ontology
{
void create_glyph_objects(const std::string& text_string, ontology::Text3D* text3D)
{
const char* text_pointer = text_string.c_str();
while (*text_pointer != '\0')
{
int32_t unicode_value = string::extract_unicode_value_from_string(text_pointer);
ontology::Glyph* glyph_pointer = text3D->parent->get_glyph_pointer(unicode_value);
if (glyph_pointer == nullptr)
{
// nullptr, so skip this character.
std::cerr << "Error: no matching Glyph found for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
continue;
}
std::cout << "Creating the glyph Object for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
ObjectStruct object_struct;
object_struct.glyph_parent = glyph_pointer;
object_struct.text3D_parent = text3D;
object_struct.original_scale_vector = text3D->original_scale_vector;
object_struct.rotate_angle = text3D->rotate_angle;
object_struct.is_character = true;
object_struct.cartesian_coordinates = text3D->cartesian_coordinates; // TODO: adjust this as needed.
object_struct.rotate_vector = text3D->rotate_vector;
ontology::Object* object = new ontology::Object(text3D->universe, object_struct);
}
// TODO: Add support for Unicode strings.
// TODO: go through `text_string`.
// TODO: extract Unicode.
//
// TODO: If the Unicode exists in the hash map, create the corresponding glyph `Object`.
// If not, continue from the next Unicode of `text_string`.
}
}
<commit_msg>Bugfix: added missing forward declaration.<commit_after>#include "glyph_object_creation.hpp"
#include "vector_font.hpp"
#include "text3D.hpp"
#include "object.hpp"
// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
namespace ontology
{
class Glyph;
void create_glyph_objects(const std::string& text_string, ontology::Text3D* text3D)
{
const char* text_pointer = text_string.c_str();
while (*text_pointer != '\0')
{
int32_t unicode_value = string::extract_unicode_value_from_string(text_pointer);
ontology::Glyph* glyph_pointer = text3D->parent->get_glyph_pointer(unicode_value);
if (glyph_pointer == nullptr)
{
// nullptr, so skip this character.
std::cerr << "Error: no matching Glyph found for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
continue;
}
std::cout << "Creating the glyph Object for unicode_value 0x" << std::hex << unicode_value << std::dec << "\n";
ObjectStruct object_struct;
object_struct.glyph_parent = glyph_pointer;
object_struct.text3D_parent = text3D;
object_struct.original_scale_vector = text3D->original_scale_vector;
object_struct.rotate_angle = text3D->rotate_angle;
object_struct.is_character = true;
object_struct.cartesian_coordinates = text3D->cartesian_coordinates; // TODO: adjust this as needed.
object_struct.rotate_vector = text3D->rotate_vector;
ontology::Object* object = new ontology::Object(text3D->universe, object_struct);
}
// TODO: Add support for Unicode strings.
// TODO: go through `text_string`.
// TODO: extract Unicode.
//
// TODO: If the Unicode exists in the hash map, create the corresponding glyph `Object`.
// If not, continue from the next Unicode of `text_string`.
}
}
<|endoftext|> |
<commit_before>#include <common/buffer.h>
#include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>
#include <event/event_callback.h>
#include <event/event_system.h>
#include <io/socket/socket_types.h>
#include "proxy_listener.h"
#include "ssh_proxy_listener.h"
#include "wanproxy_config_class_codec.h"
#include "wanproxy_config_class_interface.h"
#include "wanproxy_config_class_peer.h"
#include "wanproxy_config_class_proxy.h"
WANProxyConfigClassProxy wanproxy_config_class_proxy;
bool
WANProxyConfigClassProxy::activate(ConfigObject *co)
{
if (object_listener_map_.find(co) != object_listener_map_.end())
return (false);
/* Extract type. */
WANProxyConfigTypeProxyType *typect;
ConfigValue *typecv = co->get("type", &typect);
if (typecv == NULL)
return (false);
WANProxyConfigProxyType type;
if (!typect->get(typecv, &type))
return (false);
/* Extract interface. */
ConfigTypePointer *interfacect;
ConfigValue *interfacecv = co->get("interface", &interfacect);
if (interfacecv == NULL)
return (false);
WANProxyConfigClassInterface *interfacecc;
ConfigObject *interfaceco;
if (!interfacect->get(interfacecv, &interfaceco, &interfacecc))
return (false);
ConfigTypeAddressFamily *interface_familyct;
ConfigValue *interface_familycv = interfaceco->get("family", &interface_familyct);
if (interface_familycv == NULL)
return (false);
SocketAddressFamily interface_family;
if (!interface_familyct->get(interface_familycv, &interface_family))
return (false);
ConfigTypeString *interface_hostct;
ConfigValue *interface_hostcv = interfaceco->get("host", &interface_hostct);
if (interface_hostcv == NULL)
return (false);
std::string interface_hoststr;
if (!interface_hostct->get(interface_hostcv, &interface_hoststr))
return (false);
ConfigTypeString *interface_portct;
ConfigValue *interface_portcv = interfaceco->get("port", &interface_portct);
if (interface_portcv == NULL)
return (false);
std::string interface_portstr;
if (!interface_portct->get(interface_portcv, &interface_portstr))
return (false);
/* Extract interface_codec. */
ConfigTypePointer *interface_codecct;
ConfigValue *interface_codeccv = co->get("interface_codec", &interface_codecct);
if (interface_codeccv == NULL)
return (false);
WANProxyConfigClassCodec *interface_codeccc;
ConfigObject *interface_codecco;
if (!interface_codecct->get(interface_codeccv, &interface_codecco, &interface_codeccc))
return (false);
WANProxyCodec *interface_codeccodec;
if (interface_codecco != NULL) {
interface_codeccodec = interface_codeccc->get(interface_codecco);
} else {
interface_codeccodec = NULL;
}
/* Extract peer. */
ConfigTypePointer *peerct;
ConfigValue *peercv = co->get("peer", &peerct);
if (peercv == NULL)
return (false);
WANProxyConfigClassPeer *peercc;
ConfigObject *peerco;
if (!peerct->get(peercv, &peerco, &peercc))
return (false);
ConfigTypeAddressFamily *peer_familyct;
ConfigValue *peer_familycv = peerco->get("family", &peer_familyct);
if (peer_familycv == NULL)
return (false);
SocketAddressFamily peer_family;
if (!peer_familyct->get(peer_familycv, &peer_family))
return (false);
ConfigTypeString *peer_hostct;
ConfigValue *peer_hostcv = peerco->get("host", &peer_hostct);
if (peer_hostcv == NULL)
return (false);
std::string peer_hoststr;
if (!peer_hostct->get(peer_hostcv, &peer_hoststr))
return (false);
ConfigTypeString *peer_portct;
ConfigValue *peer_portcv = peerco->get("port", &peer_portct);
if (peer_portcv == NULL)
return (false);
std::string peer_portstr;
if (!peer_portct->get(peer_portcv, &peer_portstr))
return (false);
/* Extract peer_codec. */
ConfigTypePointer *peer_codecct;
ConfigValue *peer_codeccv = co->get("peer_codec", &peer_codecct);
if (peer_codeccv == NULL)
return (false);
WANProxyConfigClassCodec *peer_codeccc;
ConfigObject *peer_codecco;
if (!peer_codecct->get(peer_codeccv, &peer_codecco, &peer_codeccc))
return (false);
WANProxyCodec *peer_codeccodec;
if (peer_codecco != NULL) {
peer_codeccodec = peer_codeccc->get(peer_codecco);
} else {
peer_codeccodec = NULL;
}
std::string interface_address = '[' + interface_hoststr + ']' + ':' + interface_portstr;
std::string peer_address = '[' + peer_hoststr + ']' + ':' + peer_portstr;
if (type == WANProxyConfigProxyTypeTCPTCP) {
ProxyListener *listener = new ProxyListener(co->name(), interface_codeccodec, peer_codeccodec, interface_family, interface_address, peer_family, peer_address);
object_listener_map_[co] = listener;
} else {
SSHProxyListener *listener = new SSHProxyListener(co->name(), interface_codeccodec, peer_codeccodec, interface_family, interface_address, peer_family, peer_address);
(void)listener;
}
return (true);
}
<commit_msg>Default to TCP if no type is specified.<commit_after>#include <common/buffer.h>
#include <config/config_class.h>
#include <config/config_object.h>
#include <config/config_value.h>
#include <event/event_callback.h>
#include <event/event_system.h>
#include <io/socket/socket_types.h>
#include "proxy_listener.h"
#include "ssh_proxy_listener.h"
#include "wanproxy_config_class_codec.h"
#include "wanproxy_config_class_interface.h"
#include "wanproxy_config_class_peer.h"
#include "wanproxy_config_class_proxy.h"
WANProxyConfigClassProxy wanproxy_config_class_proxy;
bool
WANProxyConfigClassProxy::activate(ConfigObject *co)
{
if (object_listener_map_.find(co) != object_listener_map_.end())
return (false);
/* Extract type. Defaults to TCP. */
WANProxyConfigProxyType type = WANProxyConfigProxyTypeTCPTCP;
WANProxyConfigTypeProxyType *typect;
ConfigValue *typecv = co->get("type", &typect);
if (typecv != NULL) {
if (!typect->get(typecv, &type)) {
DEBUG("/wanproxy/config/proxy") << "Could not get proxy type.";
}
}
/* Extract interface. */
ConfigTypePointer *interfacect;
ConfigValue *interfacecv = co->get("interface", &interfacect);
if (interfacecv == NULL)
return (false);
WANProxyConfigClassInterface *interfacecc;
ConfigObject *interfaceco;
if (!interfacect->get(interfacecv, &interfaceco, &interfacecc))
return (false);
ConfigTypeAddressFamily *interface_familyct;
ConfigValue *interface_familycv = interfaceco->get("family", &interface_familyct);
if (interface_familycv == NULL)
return (false);
SocketAddressFamily interface_family;
if (!interface_familyct->get(interface_familycv, &interface_family))
return (false);
ConfigTypeString *interface_hostct;
ConfigValue *interface_hostcv = interfaceco->get("host", &interface_hostct);
if (interface_hostcv == NULL)
return (false);
std::string interface_hoststr;
if (!interface_hostct->get(interface_hostcv, &interface_hoststr))
return (false);
ConfigTypeString *interface_portct;
ConfigValue *interface_portcv = interfaceco->get("port", &interface_portct);
if (interface_portcv == NULL)
return (false);
std::string interface_portstr;
if (!interface_portct->get(interface_portcv, &interface_portstr))
return (false);
/* Extract interface_codec. */
ConfigTypePointer *interface_codecct;
ConfigValue *interface_codeccv = co->get("interface_codec", &interface_codecct);
if (interface_codeccv == NULL)
return (false);
WANProxyConfigClassCodec *interface_codeccc;
ConfigObject *interface_codecco;
if (!interface_codecct->get(interface_codeccv, &interface_codecco, &interface_codeccc))
return (false);
WANProxyCodec *interface_codeccodec;
if (interface_codecco != NULL) {
interface_codeccodec = interface_codeccc->get(interface_codecco);
} else {
interface_codeccodec = NULL;
}
/* Extract peer. */
ConfigTypePointer *peerct;
ConfigValue *peercv = co->get("peer", &peerct);
if (peercv == NULL)
return (false);
WANProxyConfigClassPeer *peercc;
ConfigObject *peerco;
if (!peerct->get(peercv, &peerco, &peercc))
return (false);
ConfigTypeAddressFamily *peer_familyct;
ConfigValue *peer_familycv = peerco->get("family", &peer_familyct);
if (peer_familycv == NULL)
return (false);
SocketAddressFamily peer_family;
if (!peer_familyct->get(peer_familycv, &peer_family))
return (false);
ConfigTypeString *peer_hostct;
ConfigValue *peer_hostcv = peerco->get("host", &peer_hostct);
if (peer_hostcv == NULL)
return (false);
std::string peer_hoststr;
if (!peer_hostct->get(peer_hostcv, &peer_hoststr))
return (false);
ConfigTypeString *peer_portct;
ConfigValue *peer_portcv = peerco->get("port", &peer_portct);
if (peer_portcv == NULL)
return (false);
std::string peer_portstr;
if (!peer_portct->get(peer_portcv, &peer_portstr))
return (false);
/* Extract peer_codec. */
ConfigTypePointer *peer_codecct;
ConfigValue *peer_codeccv = co->get("peer_codec", &peer_codecct);
if (peer_codeccv == NULL)
return (false);
WANProxyConfigClassCodec *peer_codeccc;
ConfigObject *peer_codecco;
if (!peer_codecct->get(peer_codeccv, &peer_codecco, &peer_codeccc))
return (false);
WANProxyCodec *peer_codeccodec;
if (peer_codecco != NULL) {
peer_codeccodec = peer_codeccc->get(peer_codecco);
} else {
peer_codeccodec = NULL;
}
std::string interface_address = '[' + interface_hoststr + ']' + ':' + interface_portstr;
std::string peer_address = '[' + peer_hoststr + ']' + ':' + peer_portstr;
if (type == WANProxyConfigProxyTypeTCPTCP) {
ProxyListener *listener = new ProxyListener(co->name(), interface_codeccodec, peer_codeccodec, interface_family, interface_address, peer_family, peer_address);
object_listener_map_[co] = listener;
} else {
SSHProxyListener *listener = new SSHProxyListener(co->name(), interface_codeccodec, peer_codeccodec, interface_family, interface_address, peer_family, peer_address);
(void)listener;
}
return (true);
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/async.h"
#include "spdlog/spdlog.h"
#include <iostream>
#include <memory>
void async_example();
void syslog_example();
void android_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
// Console logger with color
auto console = spdlog::console<spd::stdout_color_mt>("console");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging is very fast..
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
async_example();
// syslog example. linux/osx only
syslog_example();
// android example. compile with NDK
android_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i);
}
// optional change thread pool settings *before* creating the logger:
// spdlog::init_thread_pool(8192, 1);
// if not called a defaults are: 8192 queue size and 1 worker thread.
}
// syslog example (linux/osx/freebsd)
void syslog_example()
{
#ifdef SPDLOG_ENABLE_SYSLOG
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
#endif
}
// Android example
void android_example()
{
#if defined(__ANDROID__)
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
#endif
}
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<commit_msg>fix example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/spdlog.h"
#include <iostream>
#include <memory>
void async_example();
void syslog_example();
void android_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
// Console logger with color
auto console = spdlog::console<spd::stdout_color_mt>("console");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging is very fast..
// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
async_example();
// syslog example. linux/osx only
syslog_example();
// android example. compile with NDK
android_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
// must be included to use async logger
#include "spdlog/async.h"
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i);
}
// optional change thread pool settings *before* creating the logger:
// spdlog::init_thread_pool(8192, 1);
// if not called a defaults are: 8192 queue size and 1 worker thread.
}
// syslog example (linux/osx/freebsd)
void syslog_example()
{
#ifdef SPDLOG_ENABLE_SYSLOG
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
#endif
}
// Android example
void android_example()
{
#if defined(__ANDROID__)
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
#endif
}
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { std::cerr << "my err handler: " << msg << std::endl; });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "session.h"
#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <LuminaUtils.h>
void LSession::stopall(){
stopping = true;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
}
QCoreApplication::processEvents();
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
}
//QCoreApplication::exit(0);
}
void LSession::procFinished(){
//Go through and check the status on all the procs to determine which one finished
int stopped = 0;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()==QProcess::NotRunning){
stopped++;
if(!stopping){
//See if this process is the main desktop binary
if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall(); } //start closing down everything
//else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
break;
}
}
}
if(stopping && stopped==PROCS.length()){
QCoreApplication::exit(0);
}
}
void LSession::startProcess(QString ID, QString command){
QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
QString logfile = dir+"/"+ID+".log";
if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }
QProcess *proc = new QProcess();
proc->setProcessChannelMode(QProcess::MergedChannels);
proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
proc->setStandardOutputFile(logfile);
proc->start(command, QIODevice::ReadOnly);
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
PROCS << proc;
}
void LSession::start(){
//First check for a valid installation
if( !LUtils::isValidBinary("fluxbox") || !LUtils::isValidBinary("lumina-desktop") ){
exit(1);
}
//Window Manager First
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
//if(!QFile::exists(QDir::homePath()+"/.fluxbox")){ QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox"); }
//startProcess("wm", "fluxbox -rc "+QDir::homePath()+"/.lumina/fluxbox-init -no-slit -no-toolbar");
//Compositing manager
if(LUtils::isValidBinary("xcompmgr")){ startProcess("compositing","xcompmgr"); }
//Desktop Next
startProcess("runtime","lumina-desktop");
//ScreenSaver
if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }
}
<commit_msg>Setup Lumina to use "compton" for the compositing manager instead of xcompmgr (if it is installed)<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2016, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "session.h"
#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <LuminaUtils.h>
void LSession::stopall(){
stopping = true;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
}
QCoreApplication::processEvents();
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
}
//QCoreApplication::exit(0);
}
void LSession::procFinished(){
//Go through and check the status on all the procs to determine which one finished
int stopped = 0;
for(int i=0; i<PROCS.length(); i++){
if(PROCS[i]->state()==QProcess::NotRunning){
stopped++;
if(!stopping){
//See if this process is the main desktop binary
if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall(); } //start closing down everything
//else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
break;
}
}
}
if(stopping && stopped==PROCS.length()){
QCoreApplication::exit(0);
}
}
void LSession::startProcess(QString ID, QString command){
QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
QString logfile = dir+"/"+ID+".log";
if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }
QProcess *proc = new QProcess();
proc->setProcessChannelMode(QProcess::MergedChannels);
proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
proc->setStandardOutputFile(logfile);
proc->start(command, QIODevice::ReadOnly);
connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
PROCS << proc;
}
void LSession::start(){
//First check for a valid installation
if( !LUtils::isValidBinary("fluxbox") || !LUtils::isValidBinary("lumina-desktop") ){
exit(1);
}
//Window Manager First
// FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
//if(!QFile::exists(QDir::homePath()+"/.fluxbox")){ QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox"); }
//startProcess("wm", "fluxbox -rc "+QDir::homePath()+"/.lumina/fluxbox-init -no-slit -no-toolbar");
//Compositing manager
if(LUtils::isValidBinary("compton")){ startProcess("compositing","compton"); }
else if(LUtils::isValidBinary("xcompmgr")){ startProcess("compositing","xcompmgr"); }
//Desktop Next
startProcess("runtime","lumina-desktop");
//ScreenSaver
if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }
}
<|endoftext|> |
<commit_before>/** @file palettetoolbox.cpp
* @brief Класс палитры элементов
* */
#include <QtGui>
#include "palettetoolbox.h"
#include "realrepoinfo.h"
#include <QMessageBox>
PaletteToolbox::DraggableElement::DraggableElement(TypeIdType const &classid, QWidget *parent)
: QWidget(parent)
{
RealRepoInfo info;
m_id = classid;
m_text = info.objectDesc(classid);
m_icon = info.objectIcon(classid);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(4, 4, 4, 4);
QLabel *icon = new QLabel(this);
icon->setFixedSize(16, 16);
icon->setPixmap(m_icon.pixmap(16, 16));
layout->addWidget(icon);
QLabel *text = new QLabel(this);
text->setText(m_text);
layout->addWidget(text);
setLayout(layout);
}
PaletteToolbox::PaletteToolbox(QWidget *parent)
: QWidget(parent)
{
RealRepoInfo info;
mLayout = new QVBoxLayout;
mLayout->setSpacing(6);
mLayout->setMargin(0);
mComboBox = new QComboBox;
mLayout->addWidget(mComboBox);
mScrollArea = new QScrollArea;
mLayout->addWidget(mScrollArea);
setLayout(mLayout);
QStringList categories = info.getObjectCategories();
mTabs.resize(categories.size());
mTabNames.resize(categories.size());
mShownTabs.resize(categories.size());
QSettings settings("Tercom", "QReal");
unsigned i = 0;
foreach (QString category, categories) {
QWidget *tab = new QWidget;
QVBoxLayout *layout = new QVBoxLayout(tab);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
foreach(TypeIdType classid, info.getObjects(category)) {
DraggableElement *element = new DraggableElement(classid);
layout->addWidget(element);
}
tab->setLayout(layout);
Q_ASSERT(!category.isEmpty());
mTabs[i] = tab;
mTabNames[i] = category;
mShownTabs[i] = !settings.contains(category)
|| settings.value(category).toString() == "Show";
++i;
}
setEditors(mShownTabs);
connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
mComboBox->setCurrentIndex(-1);
}
PaletteToolbox::~PaletteToolbox()
{
QSettings settings("Tercom", "QReal");
for (int i = 0; i < mTabNames.count(); ++i)
if (mShownTabs[i])
settings.setValue(mTabNames[i], "Show");
else
settings.setValue(mTabNames[i], "Hide");
mScrollArea->takeWidget();
delete mScrollArea;
delete mComboBox;
delete mLayout;
}
void PaletteToolbox::setActiveEditor(int comboIndex)
{
mScrollArea->takeWidget(); // Save current editor from extermination.
if (comboIndex == -1) return;
if (mComboToRepo[comboIndex] == -1) return;
mScrollArea->setWidget(mTabs[mComboToRepo[comboIndex]]);
}
void PaletteToolbox::setEditors(QVector<bool> const &editors)
{
int oldComboIndex, oldIndex, curComboIndex = -1;
int newComboIndex = -1;
oldComboIndex = mComboBox->currentIndex();
oldIndex = (oldComboIndex==-1)?-1:mComboToRepo[oldComboIndex];
mComboBox->clear();
mComboToRepo.clear();
mRepoToCombo.clear();
// Rebuld vectors
for (int i = 0; i < editors.size(); ++i)
{
if (editors[i])
{
curComboIndex++;
mComboToRepo << i;
mRepoToCombo << curComboIndex;
}
else
mRepoToCombo << -1;
mShownTabs[i] = editors[i];
}
// Fill Combobox
for (int i = 0; i < editors.size(); ++i)
if (editors[i])
mComboBox->addItem(mTabNames[i]);
if (oldIndex != -1)
newComboIndex = mRepoToCombo[oldIndex];
mComboBox->setCurrentIndex(newComboIndex);
}
QVector<bool> PaletteToolbox::getSelectedTabs() const
{
return mShownTabs;
}
void PaletteToolbox::dragEnterEvent(QDragEnterEvent * /*event*/)
{
}
void PaletteToolbox::dropEvent(QDropEvent * /*event*/)
{
}
void PaletteToolbox::mousePressEvent(QMouseEvent *event)
{
QWidget *atMouse = childAt(event->pos());
if ( ! atMouse || atMouse == this )
return;
DraggableElement *child = dynamic_cast<DraggableElement *>(atMouse->parent());
if (!child)
child = dynamic_cast<DraggableElement *>(atMouse);
if (!child)
return;
QByteArray itemData;
QDataStream stream(&itemData, QIODevice::WriteOnly);
stream << -1; // uuid
stream << child->id(); // type
stream << -1; // old parent
stream << QString("(anon element)");
stream << QPointF(0,0);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-real-uml-data", itemData);
// mimeData->setText(child->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
QPixmap p = child->icon().pixmap(96,96);
if ( ! p.isNull() )
drag->setPixmap(child->icon().pixmap(96,96));
if (drag->start(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)
child->close();
else
child->show();
}
<commit_msg>Do not set an empty editor, this reduces usability.<commit_after>/** @file palettetoolbox.cpp
* @brief Класс палитры элементов
* */
#include <QtGui>
#include "palettetoolbox.h"
#include "realrepoinfo.h"
#include <QMessageBox>
PaletteToolbox::DraggableElement::DraggableElement(TypeIdType const &classid, QWidget *parent)
: QWidget(parent)
{
RealRepoInfo info;
m_id = classid;
m_text = info.objectDesc(classid);
m_icon = info.objectIcon(classid);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->setContentsMargins(4, 4, 4, 4);
QLabel *icon = new QLabel(this);
icon->setFixedSize(16, 16);
icon->setPixmap(m_icon.pixmap(16, 16));
layout->addWidget(icon);
QLabel *text = new QLabel(this);
text->setText(m_text);
layout->addWidget(text);
setLayout(layout);
}
PaletteToolbox::PaletteToolbox(QWidget *parent)
: QWidget(parent)
{
RealRepoInfo info;
mLayout = new QVBoxLayout;
mLayout->setSpacing(6);
mLayout->setMargin(0);
mComboBox = new QComboBox;
mLayout->addWidget(mComboBox);
mScrollArea = new QScrollArea;
mLayout->addWidget(mScrollArea);
setLayout(mLayout);
QStringList categories = info.getObjectCategories();
mTabs.resize(categories.size());
mTabNames.resize(categories.size());
mShownTabs.resize(categories.size());
QSettings settings("Tercom", "QReal");
unsigned i = 0;
foreach (QString category, categories) {
QWidget *tab = new QWidget;
QVBoxLayout *layout = new QVBoxLayout(tab);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
foreach(TypeIdType classid, info.getObjects(category)) {
DraggableElement *element = new DraggableElement(classid);
layout->addWidget(element);
}
tab->setLayout(layout);
Q_ASSERT(!category.isEmpty());
mTabs[i] = tab;
mTabNames[i] = category;
mShownTabs[i] = !settings.contains(category)
|| settings.value(category).toString() == "Show";
++i;
}
mComboBox->setUpdatesEnabled(false);
setEditors(mShownTabs);
connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
// This sequence changes current editor, so mComboBox will issue signal
mComboBox->setCurrentIndex(-1);
mComboBox->setCurrentIndex(0);
mComboBox->setUpdatesEnabled(true);
}
PaletteToolbox::~PaletteToolbox()
{
QSettings settings("Tercom", "QReal");
for (int i = 0; i < mTabNames.count(); ++i)
if (mShownTabs[i])
settings.setValue(mTabNames[i], "Show");
else
settings.setValue(mTabNames[i], "Hide");
mScrollArea->takeWidget();
delete mScrollArea;
delete mComboBox;
delete mLayout;
}
void PaletteToolbox::setActiveEditor(int comboIndex)
{
mScrollArea->takeWidget(); // Save current editor from extermination.
if (comboIndex == -1) return;
mScrollArea->setWidget(mTabs[mComboToRepo[comboIndex]]);
}
void PaletteToolbox::setEditors(QVector<bool> const &editors)
{
int oldComboIndex, oldIndex, curComboIndex = -1;
int newComboIndex = -1;
bool old_updatesEnabled;
old_updatesEnabled = mComboBox->updatesEnabled();
mComboBox->setUpdatesEnabled(false);
oldComboIndex = mComboBox->currentIndex();
oldIndex = (oldComboIndex==-1)?-1:mComboToRepo[oldComboIndex];
mComboBox->clear();
mComboToRepo.clear();
mRepoToCombo.clear();
// Rebuld vectors
for (int i = 0; i < editors.size(); ++i)
{
if (editors[i])
{
curComboIndex++;
mComboToRepo << i;
mRepoToCombo << curComboIndex;
}
else
mRepoToCombo << -1;
mShownTabs[i] = editors[i];
}
// Fill Combobox
for (int i = 0; i < editors.size(); ++i)
if (editors[i])
mComboBox->addItem(mTabNames[i]);
if (oldIndex != -1)
newComboIndex = mRepoToCombo[oldIndex];
// Setting empty editor reduces usability, so avoid it
if (newComboIndex == -1)
newComboIndex = 0;
mComboBox->setCurrentIndex(newComboIndex);
mComboBox->setUpdatesEnabled(old_updatesEnabled);
}
QVector<bool> PaletteToolbox::getSelectedTabs() const
{
return mShownTabs;
}
void PaletteToolbox::dragEnterEvent(QDragEnterEvent * /*event*/)
{
}
void PaletteToolbox::dropEvent(QDropEvent * /*event*/)
{
}
void PaletteToolbox::mousePressEvent(QMouseEvent *event)
{
QWidget *atMouse = childAt(event->pos());
if ( ! atMouse || atMouse == this )
return;
DraggableElement *child = dynamic_cast<DraggableElement *>(atMouse->parent());
if (!child)
child = dynamic_cast<DraggableElement *>(atMouse);
if (!child)
return;
QByteArray itemData;
QDataStream stream(&itemData, QIODevice::WriteOnly);
stream << -1; // uuid
stream << child->id(); // type
stream << -1; // old parent
stream << QString("(anon element)");
stream << QPointF(0,0);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-real-uml-data", itemData);
// mimeData->setText(child->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
QPixmap p = child->icon().pixmap(96,96);
if ( ! p.isNull() )
drag->setPixmap(child->icon().pixmap(96,96));
if (drag->start(Qt::CopyAction | Qt::MoveAction) == Qt::MoveAction)
child->close();
else
child->show();
}
<|endoftext|> |
<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/simple_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>
#include <memory>
void async_example();
void user_defined_example();
void err_handler_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
auto console = spdlog::stdout_color_st("console");
console->info("Welcome to spdlog!");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
err_handler_example();
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Change format back to to default
spd::set_pattern("%+");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging example
async_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
// must be included to use async logger
#include "spdlog/async.h"
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
// thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 4); // queue with max 32k items 4 backing threads.
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i + 1);
}
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spd::get("console")->error("*******my err handler: {}", msg); });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
// spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<commit_msg>updated example<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
//
// spdlog usage example
//
//
#define SPDLOG_TRACE_ON
#define SPDLOG_DEBUG_ON
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/simple_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <iostream>
#include <memory>
void async_example();
void user_defined_example();
void err_handler_example();
void syslog_example();
namespace spd = spdlog;
int main(int, char *[])
{
try
{
syslog_example();
auto console = spdlog::stdout_color_st("console");
console->info("Welcome to spdlog!");
console->info("Welcome to spdlog!");
console->error("Some error message with arg: {}", 1);
err_handler_example();
// Formatting examples
console->warn("Easy padding in numbers like {:08d}", 12);
console->critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
console->info("Support for floats {:03.2f}", 1.23456);
console->info("Positional args are {1} {0}..", "too", "supported");
console->info("{:<30}", "left aligned");
spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");
// Create basic file logger (not rotated)
auto my_logger = spd::basic_logger_mt("basic_logger", "logs/basic-log.txt");
my_logger->info("Some log message");
// Create a file rotating logger with 5mb size max and 3 rotated files
auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "logs/rotating.txt", 1048576 * 5, 3);
for (int i = 0; i < 10; ++i)
{
rotating_logger->info("{} * {} equals {:>10}", i, i, i * i);
}
// Create a daily logger - a new file is created every day on 2:30am
auto daily_logger = spd::daily_logger_mt("daily_logger", "logs/daily.txt", 2, 30);
// trigger flush if the log severity is error or higher
daily_logger->flush_on(spd::level::err);
daily_logger->info(123.44);
// Customize msg format for all messages
spd::set_pattern("[%^+++%$] [%H:%M:%S %z] [thread %t] %v");
console->info("This an info message with custom format");
console->error("This an error message with custom format");
// Change format back to to default
spd::set_pattern("%+");
// Runtime log levels
spd::set_level(spd::level::info); // Set global log level to info
console->debug("This message should not be displayed!");
console->set_level(spd::level::debug); // Set specific logger's log level
console->debug("This message should be displayed..");
// Compile time log levels
// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
// Asynchronous logging example
async_example();
// Log user-defined types example
user_defined_example();
// Change default log error handler
err_handler_example();
// Apply a function on all registered loggers
spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });
// Release and close all loggers
spdlog::drop_all();
}
// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
catch (const spd::spdlog_ex &ex)
{
std::cout << "Log init failed: " << ex.what() << std::endl;
return 1;
}
}
// must be included to use async logger
#include "spdlog/async.h"
void async_example()
{
auto async_file = spd::basic_logger_mt<spdlog::create_async>("async_file_logger", "logs/async_log.txt");
// thread pool settings can be modified *before* creating the async logger:
// spdlog::init_thread_pool(32768, 4); // queue with max 32k items 4 backing threads.
for (int i = 0; i < 100; ++i)
{
async_file->info("Async message #{}", i + 1);
}
}
// syslog example (linux/osx/freebsd)
#ifndef _WIN32
#include "spdlog/sinks/syslog_sink.h"
void syslog_example()
{
std::string ident = "spdlog-example";
auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
syslog_logger->warn("This is warning that will end up in syslog.");
}
#endif
// Android example
#if defined(__ANDROID__)
#incude "spdlog/sinks/android_sink.h"
void android_example()
{
std::string tag = "spdlog-android";
auto android_logger = spd::android_logger("android", tag);
android_logger->critical("Use \"adb shell logcat\" to view this message.");
}
#endif
// user defined types logging by implementing operator<<
struct my_type
{
int i;
template<typename OStream>
friend OStream &operator<<(OStream &os, const my_type &c)
{
return os << "[my_type i=" << c.i << "]";
}
};
#include "spdlog/fmt/ostr.h" // must be included
void user_defined_example()
{
spd::get("console")->info("user defined type: {}", my_type{14});
}
//
// custom error handler
//
void err_handler_example()
{
// can be set globaly or per logger(logger->set_error_handler(..))
spdlog::set_error_handler([](const std::string &msg) { spd::get("console")->error("*******my err handler: {}", msg); });
spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
// spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
}
<|endoftext|> |
<commit_before>#include "ScriptRepo.hpp"
#include "ClientRepo.hpp"
#include "RemoteRepo.hpp"
#include "EntityManager.hpp"
#include "Action.hpp"
#include "../inanity/script/np/State.hpp"
#include "../inanity/script/np/Any.hpp"
#include "../inanity/FileInputStream.hpp"
#include "../inanity/MemoryStream.hpp"
#include "../inanity/StreamReader.hpp"
#include "../inanity/StreamWriter.hpp"
#include "../inanity/File.hpp"
#include <sstream>
BEGIN_INANITY_OIL
//*** class ScriptRepo::InitHandler
class ScriptRepo::InitHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
InitHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> data)
{
try
{
scriptRepo->clientRepo->ReadServerManifest(&StreamReader(NEW(FileInputStream(data))));
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewString("OK"));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo::PullHandler
class ScriptRepo::PullHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
PullHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> data)
{
try
{
bool changedSomething = scriptRepo->clientRepo->Pull(&StreamReader(NEW(FileInputStream(data))));
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewBoolean(changedSomething));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo::WatchHandler
class ScriptRepo::WatchHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
WatchHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> file)
{
try
{
StreamReader reader(NEW(FileInputStream(file)));
bool needSync = scriptRepo->clientRepo->ReadWatchResponse(&reader);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewBoolean(needSync));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo
ScriptRepo::ScriptRepo(ptr<ClientRepo> clientRepo, ptr<RemoteRepo> remoteRepo, ptr<EntityManager> entityManager)
: clientRepo(clientRepo), remoteRepo(remoteRepo), entityManager(entityManager) {}
ptr<EntityManager> ScriptRepo::GetEntityManager() const
{
return entityManager;
}
void ScriptRepo::Init(ptr<Script::Any> callback)
{
remoteRepo->GetManifest(NEW(InitHandler(this, callback.FastCast<Script::Np::Any>())));
}
void ScriptRepo::Sync(ptr<Script::Any> callback)
{
try
{
ptr<MemoryStream> stream = NEW(MemoryStream());
StreamWriter writer(stream);
writer.Write('\n');
clientRepo->Push(&writer);
remoteRepo->Sync(stream->ToFile(), NEW(PullHandler(this, callback.FastCast<Script::Np::Any>())));
}
catch(Exception* exception)
{
try
{
clientRepo->Cleanup();
}
catch(Exception* exception)
{
MakePointer(exception);
}
std::ostringstream ss;
MakePointer(exception)->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback.FastCast<Script::Np::Any>()->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
}
void ScriptRepo::Watch(ptr<Script::Any> callback)
{
ptr<MemoryStream> stream = NEW(MemoryStream());
StreamWriter writer(stream);
writer.Write('\n');
clientRepo->WriteWatchRequest(&writer);
remoteRepo->Watch(stream->ToFile(), NEW(WatchHandler(this, callback.FastCast<Script::Np::Any>())));
}
void ScriptRepo::ProcessEvents()
{
class EventHandler : public ClientRepo::EventHandler
{
private:
ScriptRepo* repo;
public:
EventHandler(ScriptRepo* repo) : repo(repo) {}
void OnEvent(ptr<File> key, ptr<File> value)
{
repo->OnChange(key, value);
}
};
clientRepo->ProcessEvents(&EventHandler(this));
}
void ScriptRepo::ApplyAction(ptr<Action> action)
{
const Action::Changes& changes = action->GetChanges();
for(size_t i = 0; i < changes.size(); ++i)
{
const Action::Change& change = changes[i];
clientRepo->Change(change.first, change.second);
}
}
ptr<Action> ScriptRepo::ReverseAction(ptr<Action> action)
{
ptr<Action> reverseAction = NEW(Action(action->GetDescription()));
const Action::Changes& changes = action->GetChanges();
for(size_t i = 0; i < changes.size(); ++i)
{
const Action::Change& change = changes[i];
ptr<File> key = change.first;
ptr<File> initialValue = clientRepo->GetValue(key);
reverseAction->AddChange(key, initialValue);
}
return reverseAction;
}
void ScriptRepo::FireUndoRedoChangedCallback()
{
ptr<Action> undoAction = undoActions.empty() ? nullptr : undoActions.back();
ptr<Action> redoAction = redoActions.empty() ? nullptr : redoActions.back();
if(undoRedoChangedCallback)
{
ptr<Script::Np::State> scriptState = undoRedoChangedCallback->GetState();
undoRedoChangedCallback->Call(
scriptState->WrapObject(undoAction),
scriptState->WrapObject(redoAction));
}
}
void ScriptRepo::OnChange(ptr<File> key, ptr<File> value)
{
entityManager->OnChange(key, value);
}
void ScriptRepo::MakeAction(ptr<Action> action)
{
ptr<Action> undoAction = ReverseAction(action);
undoActions.push_back(undoAction);
redoActions.clear();
ApplyAction(action);
FireUndoRedoChangedCallback();
}
bool ScriptRepo::Undo()
{
if(undoActions.empty())
return false;
ptr<Action> undoAction = undoActions.back();
undoActions.pop_back();
ApplyAction(undoAction);
ptr<Action> redoAction = ReverseAction(undoAction);
redoActions.push_back(redoAction);
FireUndoRedoChangedCallback();
return true;
}
bool ScriptRepo::Redo()
{
if(redoActions.empty())
return false;
ptr<Action> redoAction = redoActions.back();
redoActions.pop_back();
ApplyAction(redoAction);
ptr<Action> undoAction = ReverseAction(redoAction);
undoActions.push_back(undoAction);
FireUndoRedoChangedCallback();
return true;
}
void ScriptRepo::SetUndoRedoChangedCallback(ptr<Script::Any> callback)
{
this->undoRedoChangedCallback = callback.FastCast<Script::Np::Any>();
}
END_INANITY_OIL
<commit_msg>fix creation of undo-redo actions<commit_after>#include "ScriptRepo.hpp"
#include "ClientRepo.hpp"
#include "RemoteRepo.hpp"
#include "EntityManager.hpp"
#include "Action.hpp"
#include "../inanity/script/np/State.hpp"
#include "../inanity/script/np/Any.hpp"
#include "../inanity/FileInputStream.hpp"
#include "../inanity/MemoryStream.hpp"
#include "../inanity/StreamReader.hpp"
#include "../inanity/StreamWriter.hpp"
#include "../inanity/File.hpp"
#include <sstream>
BEGIN_INANITY_OIL
//*** class ScriptRepo::InitHandler
class ScriptRepo::InitHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
InitHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> data)
{
try
{
scriptRepo->clientRepo->ReadServerManifest(&StreamReader(NEW(FileInputStream(data))));
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewString("OK"));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo::PullHandler
class ScriptRepo::PullHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
PullHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> data)
{
try
{
bool changedSomething = scriptRepo->clientRepo->Pull(&StreamReader(NEW(FileInputStream(data))));
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewBoolean(changedSomething));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo::WatchHandler
class ScriptRepo::WatchHandler : public DataHandler<ptr<File> >
{
private:
ptr<ScriptRepo> scriptRepo;
ptr<Script::Np::Any> callback;
public:
WatchHandler(ptr<ScriptRepo> scriptRepo, ptr<Script::Np::Any> callback)
: scriptRepo(scriptRepo), callback(callback) {}
void OnData(ptr<File> file)
{
try
{
StreamReader reader(NEW(FileInputStream(file)));
bool needSync = scriptRepo->clientRepo->ReadWatchResponse(&reader);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(true),
scriptState->NewBoolean(needSync));
}
catch(Exception* exception)
{
OnError(exception);
}
}
void OnError(ptr<Exception> exception)
{
std::ostringstream ss;
exception->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
};
//*** class ScriptRepo
ScriptRepo::ScriptRepo(ptr<ClientRepo> clientRepo, ptr<RemoteRepo> remoteRepo, ptr<EntityManager> entityManager)
: clientRepo(clientRepo), remoteRepo(remoteRepo), entityManager(entityManager) {}
ptr<EntityManager> ScriptRepo::GetEntityManager() const
{
return entityManager;
}
void ScriptRepo::Init(ptr<Script::Any> callback)
{
remoteRepo->GetManifest(NEW(InitHandler(this, callback.FastCast<Script::Np::Any>())));
}
void ScriptRepo::Sync(ptr<Script::Any> callback)
{
try
{
ptr<MemoryStream> stream = NEW(MemoryStream());
StreamWriter writer(stream);
writer.Write('\n');
clientRepo->Push(&writer);
remoteRepo->Sync(stream->ToFile(), NEW(PullHandler(this, callback.FastCast<Script::Np::Any>())));
}
catch(Exception* exception)
{
try
{
clientRepo->Cleanup();
}
catch(Exception* exception)
{
MakePointer(exception);
}
std::ostringstream ss;
MakePointer(exception)->PrintStack(ss);
ptr<Script::Np::State> scriptState = callback.FastCast<Script::Np::Any>()->GetState();
callback->Call(
scriptState->NewBoolean(false),
scriptState->NewString(ss.str()));
}
}
void ScriptRepo::Watch(ptr<Script::Any> callback)
{
ptr<MemoryStream> stream = NEW(MemoryStream());
StreamWriter writer(stream);
writer.Write('\n');
clientRepo->WriteWatchRequest(&writer);
remoteRepo->Watch(stream->ToFile(), NEW(WatchHandler(this, callback.FastCast<Script::Np::Any>())));
}
void ScriptRepo::ProcessEvents()
{
class EventHandler : public ClientRepo::EventHandler
{
private:
ScriptRepo* repo;
public:
EventHandler(ScriptRepo* repo) : repo(repo) {}
void OnEvent(ptr<File> key, ptr<File> value)
{
repo->OnChange(key, value);
}
};
clientRepo->ProcessEvents(&EventHandler(this));
}
void ScriptRepo::ApplyAction(ptr<Action> action)
{
const Action::Changes& changes = action->GetChanges();
for(size_t i = 0; i < changes.size(); ++i)
{
const Action::Change& change = changes[i];
clientRepo->Change(change.first, change.second);
}
}
ptr<Action> ScriptRepo::ReverseAction(ptr<Action> action)
{
ptr<Action> reverseAction = NEW(Action(action->GetDescription()));
const Action::Changes& changes = action->GetChanges();
for(size_t i = 0; i < changes.size(); ++i)
{
const Action::Change& change = changes[i];
ptr<File> key = change.first;
ptr<File> initialValue = clientRepo->GetValue(key);
reverseAction->AddChange(key, initialValue);
}
return reverseAction;
}
void ScriptRepo::FireUndoRedoChangedCallback()
{
ptr<Action> undoAction = undoActions.empty() ? nullptr : undoActions.back();
ptr<Action> redoAction = redoActions.empty() ? nullptr : redoActions.back();
if(undoRedoChangedCallback)
{
ptr<Script::Np::State> scriptState = undoRedoChangedCallback->GetState();
undoRedoChangedCallback->Call(
scriptState->WrapObject(undoAction),
scriptState->WrapObject(redoAction));
}
}
void ScriptRepo::OnChange(ptr<File> key, ptr<File> value)
{
entityManager->OnChange(key, value);
}
void ScriptRepo::MakeAction(ptr<Action> action)
{
ptr<Action> undoAction = ReverseAction(action);
undoActions.push_back(undoAction);
redoActions.clear();
ApplyAction(action);
FireUndoRedoChangedCallback();
}
bool ScriptRepo::Undo()
{
if(undoActions.empty())
return false;
// get undo action
ptr<Action> undoAction = undoActions.back();
undoActions.pop_back();
// create redo action
ptr<Action> redoAction = ReverseAction(undoAction);
// apply undo action
ApplyAction(undoAction);
// add redo action into redo stack
redoActions.push_back(redoAction);
FireUndoRedoChangedCallback();
return true;
}
bool ScriptRepo::Redo()
{
if(redoActions.empty())
return false;
// get redo action
ptr<Action> redoAction = redoActions.back();
redoActions.pop_back();
// create undo action
ptr<Action> undoAction = ReverseAction(redoAction);
// apply redo action
ApplyAction(redoAction);
// add undo action into undo stack
undoActions.push_back(undoAction);
FireUndoRedoChangedCallback();
return true;
}
void ScriptRepo::SetUndoRedoChangedCallback(ptr<Script::Any> callback)
{
this->undoRedoChangedCallback = callback.FastCast<Script::Np::Any>();
}
END_INANITY_OIL
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MApplication>
#include <MWindow>
#include "homewindowmonitor.h"
#include "x11wrapper.h"
HomeWindowMonitor::HomeWindowMonitor() :
nonFullscreenApplicationWindowTypes(QSet<Atom>() << WindowInfo::NotificationAtom <<
WindowInfo::DialogAtom <<
WindowInfo::MenuAtom),
netClientListStacking(X11Wrapper::XInternAtom(QX11Info::display(), "_NET_CLIENT_LIST_STACKING", False))
{
}
HomeWindowMonitor::~HomeWindowMonitor()
{
}
bool HomeWindowMonitor::isOwnWindow(WId wid) const
{
foreach (MWindow *window, MApplication::windows()) {
if (window->winId() == wid) {
return true;
}
}
return false;
}
bool HomeWindowMonitor::handleXEvent(const XEvent& event)
{
bool eventHandled = false;
if (event.type == PropertyNotify && event.xproperty.atom == netClientListStacking && event.xproperty.window == DefaultRootWindow(QX11Info::display())) {
int numWindowStackingOrderReceivers = receivers(SIGNAL(windowStackingOrderChanged(QList<WindowInfo>)));
int numFullscreenWindowReceivers = receivers(SIGNAL(fullscreenWindowOnTopOfOwnWindow()));
if (numWindowStackingOrderReceivers + numFullscreenWindowReceivers > 0) {
QList<Window> windowOrder = windowStackingOrder();
if (numWindowStackingOrderReceivers > 0) {
QList<WindowInfo> windowStackingList;
foreach (Window window, windowOrder) {
windowStackingList.append(WindowInfo(window));
}
emit windowStackingOrderChanged(windowStackingList);
}
if (numFullscreenWindowReceivers > 0) {
if (!windowOrder.isEmpty()) {
QList<Window>::iterator iter;
for (iter = windowOrder.end(); iter != windowOrder.begin(); iter--) {
WindowInfo windowInfo(*iter);
if (windowInfo.types().toSet().intersect(nonFullscreenApplicationWindowTypes).isEmpty()) {
if (!isOwnWindow(windowInfo.window())) {
emit fullscreenWindowOnTopOfOwnWindow();
}
break;
}
}
}
}
}
eventHandled = true;
}
return eventHandled;
}
QList<Window> HomeWindowMonitor::windowStackingOrder()
{
Display *display = QX11Info::display();
Atom actualType;
int actualFormat;
unsigned long numWindowItems, bytesLeft;
unsigned char *windowData = NULL;
Status result = X11Wrapper::XGetWindowProperty(display, DefaultRootWindow(display), netClientListStacking,
0, 0x7fffffff, False, XA_WINDOW,
&actualType, &actualFormat, &numWindowItems, &bytesLeft, &windowData);
QList<Window> stackingWindowList;
if (result == Success && windowData != None) {
Window *windows = (Window *)windowData;
for (unsigned int i = 0; i < numWindowItems; i++) {
stackingWindowList.append(windows[i]);
}
}
return stackingWindowList;
}
<commit_msg>Changes: Not closing the launcher when a non-fullscreen window came on top of it didn't work because the code iterated beyond the bounds of the window list<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <MApplication>
#include <MWindow>
#include "homewindowmonitor.h"
#include "x11wrapper.h"
HomeWindowMonitor::HomeWindowMonitor() :
nonFullscreenApplicationWindowTypes(QSet<Atom>() << WindowInfo::NotificationAtom <<
WindowInfo::DialogAtom <<
WindowInfo::MenuAtom),
netClientListStacking(X11Wrapper::XInternAtom(QX11Info::display(), "_NET_CLIENT_LIST_STACKING", False))
{
}
HomeWindowMonitor::~HomeWindowMonitor()
{
}
bool HomeWindowMonitor::isOwnWindow(WId wid) const
{
foreach (MWindow *window, MApplication::windows()) {
if (window->winId() == wid) {
return true;
}
}
return false;
}
bool HomeWindowMonitor::handleXEvent(const XEvent& event)
{
bool eventHandled = false;
if (event.type == PropertyNotify && event.xproperty.atom == netClientListStacking && event.xproperty.window == DefaultRootWindow(QX11Info::display())) {
int numWindowStackingOrderReceivers = receivers(SIGNAL(windowStackingOrderChanged(QList<WindowInfo>)));
int numFullscreenWindowReceivers = receivers(SIGNAL(fullscreenWindowOnTopOfOwnWindow()));
if (numWindowStackingOrderReceivers + numFullscreenWindowReceivers > 0) {
QList<Window> windowOrder = windowStackingOrder();
if (numWindowStackingOrderReceivers > 0) {
QList<WindowInfo> windowStackingList;
foreach (Window window, windowOrder) {
windowStackingList.append(WindowInfo(window));
}
emit windowStackingOrderChanged(windowStackingList);
}
if (numFullscreenWindowReceivers > 0) {
if (!windowOrder.isEmpty()) {
QListIterator<Window> iter(windowOrder);
iter.toBack();
while (iter.hasPrevious()) {
WindowInfo windowInfo(iter.previous());
if (windowInfo.types().toSet().intersect(nonFullscreenApplicationWindowTypes).isEmpty()) {
if (!isOwnWindow(windowInfo.window())) {
emit fullscreenWindowOnTopOfOwnWindow();
}
break;
}
}
}
}
}
eventHandled = true;
}
return eventHandled;
}
QList<Window> HomeWindowMonitor::windowStackingOrder()
{
Display *display = QX11Info::display();
Atom actualType;
int actualFormat;
unsigned long numWindowItems, bytesLeft;
unsigned char *windowData = NULL;
Status result = X11Wrapper::XGetWindowProperty(display, DefaultRootWindow(display), netClientListStacking,
0, 0x7fffffff, False, XA_WINDOW,
&actualType, &actualFormat, &numWindowItems, &bytesLeft, &windowData);
QList<Window> stackingWindowList;
if (result == Success && windowData != None) {
Window *windows = (Window *)windowData;
for (unsigned int i = 0; i < numWindowItems; i++) {
stackingWindowList.append(windows[i]);
}
}
return stackingWindowList;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/eventhandler.h"
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/event.h>
#include <sys/time.h>
#include <unistd.h>
#include "bin/dartutils.h"
#include "bin/fdutils.h"
#include "bin/hashmap.h"
#include "platform/utils.h"
int64_t GetCurrentTimeMilliseconds() {
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0) {
UNREACHABLE();
return 0;
}
return ((static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec) / 1000;
}
static const int kInterruptMessageSize = sizeof(InterruptMessage);
static const int kInfinityTimeout = -1;
static const int kTimerId = -1;
bool SocketData::HasReadEvent() {
return !IsClosedRead() && ((mask_ & (1 << kInEvent)) != 0);
}
bool SocketData::HasWriteEvent() {
return !IsClosedWrite() && ((mask_ & (1 << kOutEvent)) != 0);
}
// Unregister the file descriptor for a SocketData structure with kqueue.
static void RemoveFromKqueue(intptr_t kqueue_fd_, SocketData* sd) {
static const intptr_t kMaxChanges = 2;
intptr_t changes = 0;
struct kevent events[kMaxChanges];
if (sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_read_tracked_by_kqueue(false);
}
if (sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, sd);
++changes;
sd->set_write_tracked_by_kqueue(false);
}
if (changes > 0) {
ASSERT(changes < kMaxChanges);
int status =
TEMP_FAILURE_RETRY(kevent(kqueue_fd_, events, changes, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed deleting events from kqueue");
}
}
}
// Update the kqueue registration for SocketData structure to reflect
// the events currently of interest.
static void UpdateKqueue(intptr_t kqueue_fd_, SocketData* sd) {
static const intptr_t kMaxChanges = 2;
intptr_t changes = 0;
struct kevent events[kMaxChanges];
if (sd->port() != 0) {
// Register or unregister READ filter if needed.
if (sd->HasReadEvent()) {
if (!sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_ADD, 0, 0, sd);
++changes;
sd->set_read_tracked_by_kqueue(true);
}
} else if (sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_read_tracked_by_kqueue(false);
}
// Register or unregister WRITE filter if needed.
if (sd->HasWriteEvent()) {
if (!sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_ADD, 0, 0, sd);
++changes;
sd->set_write_tracked_by_kqueue(true);
}
} else if (sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_write_tracked_by_kqueue(false);
}
}
if (changes > 0) {
ASSERT(changes < kMaxChanges);
int status =
TEMP_FAILURE_RETRY(kevent(kqueue_fd_, events, changes, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed updating kqueue");
}
}
}
EventHandlerImplementation::EventHandlerImplementation()
: socket_map_(&HashMap::SamePointerValue, 16) {
intptr_t result;
result = TEMP_FAILURE_RETRY(pipe(interrupt_fds_));
if (result != 0) {
FATAL("Pipe creation failed");
}
FDUtils::SetNonBlocking(interrupt_fds_[0]);
timeout_ = kInfinityTimeout;
timeout_port_ = 0;
kqueue_fd_ = TEMP_FAILURE_RETRY(kqueue());
if (kqueue_fd_ == -1) {
FATAL("Failed creating kqueue");
}
// Register the interrupt_fd with the kqueue.
struct kevent event;
EV_SET(&event, interrupt_fds_[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
int status = TEMP_FAILURE_RETRY(kevent(kqueue_fd_, &event, 1, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed adding interrupt fd to kqueue");
}
}
EventHandlerImplementation::~EventHandlerImplementation() {
TEMP_FAILURE_RETRY(close(interrupt_fds_[0]));
TEMP_FAILURE_RETRY(close(interrupt_fds_[1]));
}
SocketData* EventHandlerImplementation::GetSocketData(intptr_t fd) {
ASSERT(fd >= 0);
HashMap::Entry* entry = socket_map_.Lookup(
GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd), true);
ASSERT(entry != NULL);
SocketData* sd = reinterpret_cast<SocketData*>(entry->value);
if (sd == NULL) {
// If there is no data in the hash map for this file descriptor a
// new SocketData for the file descriptor is inserted.
sd = new SocketData(fd);
entry->value = sd;
}
ASSERT(fd == sd->fd());
return sd;
}
void EventHandlerImplementation::WakeupHandler(intptr_t id,
Dart_Port dart_port,
int64_t data) {
InterruptMessage msg;
msg.id = id;
msg.dart_port = dart_port;
msg.data = data;
intptr_t result =
FDUtils::WriteToBlocking(interrupt_fds_[1], &msg, kInterruptMessageSize);
if (result != kInterruptMessageSize) {
if (result == -1) {
perror("Interrupt message failure:");
}
FATAL1("Interrupt message failure. Wrote %d bytes.", result);
}
}
bool EventHandlerImplementation::GetInterruptMessage(InterruptMessage* msg) {
int total_read = 0;
int bytes_read =
TEMP_FAILURE_RETRY(read(interrupt_fds_[0], msg, kInterruptMessageSize));
if (bytes_read < 0) {
return false;
}
total_read = bytes_read;
while (total_read < kInterruptMessageSize) {
bytes_read = TEMP_FAILURE_RETRY(read(interrupt_fds_[0],
msg + total_read,
kInterruptMessageSize - total_read));
if (bytes_read > 0) {
total_read = total_read + bytes_read;
}
}
return (total_read == kInterruptMessageSize) ? true : false;
}
void EventHandlerImplementation::HandleInterruptFd() {
InterruptMessage msg;
while (GetInterruptMessage(&msg)) {
if (msg.id == kTimerId) {
timeout_ = msg.data;
timeout_port_ = msg.dart_port;
} else {
SocketData* sd = GetSocketData(msg.id);
if ((msg.data & (1 << kShutdownReadCommand)) != 0) {
ASSERT(msg.data == (1 << kShutdownReadCommand));
// Close the socket for reading.
sd->ShutdownRead();
UpdateKqueue(kqueue_fd_, sd);
} else if ((msg.data & (1 << kShutdownWriteCommand)) != 0) {
ASSERT(msg.data == (1 << kShutdownWriteCommand));
// Close the socket for writing.
sd->ShutdownWrite();
UpdateKqueue(kqueue_fd_, sd);
} else if ((msg.data & (1 << kCloseCommand)) != 0) {
ASSERT(msg.data == (1 << kCloseCommand));
// Close the socket and free system resources.
RemoveFromKqueue(kqueue_fd_, sd);
intptr_t fd = sd->fd();
sd->Close();
socket_map_.Remove(GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
delete sd;
} else {
// Setup events to wait for.
sd->SetPortAndMask(msg.dart_port, msg.data);
UpdateKqueue(kqueue_fd_, sd);
}
}
}
}
#ifdef DEBUG_KQUEUE
static void PrintEventMask(intptr_t fd, struct kevent* event) {
printf("%d ", fd);
if (event->filter == EVFILT_READ) printf("EVFILT_READ ");
if (event->filter == EVFILT_WRITE) printf("EVFILT_WRITE ");
printf("flags: %x: ", event->flags);
if ((event->flags & EV_EOF) != 0) printf("EV_EOF ");
if ((event->flags & EV_ERROR) != 0) printf("EV_ERROR ");
printf("(available %d) ", FDUtils::AvailableBytes(fd));
printf("\n");
}
#endif
intptr_t EventHandlerImplementation::GetEvents(struct kevent* event,
SocketData* sd) {
#ifdef DEBUG_KQUEUE
PrintEventMask(sd->fd(), event);
#endif
intptr_t event_mask = 0;
if (sd->IsListeningSocket()) {
// On a listening socket the READ event means that there are
// connections ready to be accepted.
if (event->filter == EVFILT_READ) {
if ((event->flags & EV_EOF) != 0) event_mask |= (1 << kCloseEvent);
if ((event->flags & EV_ERROR) != 0) event_mask |= (1 << kErrorEvent);
if (event_mask == 0) event_mask |= (1 << kInEvent);
}
} else {
// Prioritize data events over close and error events.
if (event->filter == EVFILT_READ) {
if (FDUtils::AvailableBytes(sd->fd()) != 0) {
event_mask = (1 << kInEvent);
} else if ((event->flags & EV_EOF) != 0) {
event_mask = (1 << kCloseEvent);
sd->MarkClosedRead();
} else if ((event->flags & EV_ERROR) != 0) {
event_mask = (1 << kErrorEvent);
}
}
if (event->filter == EVFILT_WRITE) {
if ((event->flags & EV_ERROR) != 0) {
event_mask = (1 << kErrorEvent);
sd->MarkClosedWrite();
} else if ((event->flags & EV_EOF) != 0) {
// If the receiver closed for reading, close for writing,
// update the registration with kqueue, and do not report a
// write event.
sd->MarkClosedWrite();
UpdateKqueue(kqueue_fd_, sd);
} else {
event_mask |= (1 << kOutEvent);
}
}
}
return event_mask;
}
void EventHandlerImplementation::HandleEvents(struct kevent* events,
int size) {
for (int i = 0; i < size; i++) {
if (events[i].udata != NULL) {
SocketData* sd = reinterpret_cast<SocketData*>(events[i].udata);
intptr_t event_mask = GetEvents(events + i, sd);
if (event_mask != 0) {
// Unregister events for the file descriptor. Events will be
// registered again when the current event has been handled in
// Dart code.
RemoveFromKqueue(kqueue_fd_, sd);
Dart_Port port = sd->port();
ASSERT(port != 0);
DartUtils::PostInt32(port, event_mask);
}
}
}
HandleInterruptFd();
}
intptr_t EventHandlerImplementation::GetTimeout() {
if (timeout_ == kInfinityTimeout) {
return kInfinityTimeout;
}
intptr_t millis = timeout_ - GetCurrentTimeMilliseconds();
return (millis < 0) ? 0 : millis;
}
void EventHandlerImplementation::HandleTimeout() {
if (timeout_ != kInfinityTimeout) {
intptr_t millis = timeout_ - GetCurrentTimeMilliseconds();
if (millis <= 0) {
DartUtils::PostNull(timeout_port_);
timeout_ = kInfinityTimeout;
timeout_port_ = 0;
}
}
}
void EventHandlerImplementation::EventHandlerEntry(uword args) {
static const intptr_t kMaxEvents = 16;
struct kevent events[kMaxEvents];
EventHandlerImplementation* handler =
reinterpret_cast<EventHandlerImplementation*>(args);
ASSERT(handler != NULL);
while (1) {
intptr_t millis = handler->GetTimeout();
struct timespec ts;
int64_t secs = 0;
int64_t nanos = 0;
if (millis > 0) {
secs = millis / 1000;
nanos = (millis - (secs * 1000)) * 1000000;
}
ts.tv_sec = secs;
ts.tv_nsec = nanos;
intptr_t result = TEMP_FAILURE_RETRY(kevent(handler->kqueue_fd_,
NULL,
0,
events,
kMaxEvents,
&ts));
if (result == -1) {
perror("kevent failed");
FATAL("kevent failed\n");
} else {
handler->HandleTimeout();
handler->HandleEvents(events, result);
}
}
}
void EventHandlerImplementation::StartEventHandler() {
int result =
dart::Thread::Start(&EventHandlerImplementation::EventHandlerEntry,
reinterpret_cast<uword>(this));
if (result != 0) {
FATAL1("Failed to start event handler thread %d", result);
}
}
void EventHandlerImplementation::SendData(intptr_t id,
Dart_Port dart_port,
intptr_t data) {
WakeupHandler(id, dart_port, data);
}
void* EventHandlerImplementation::GetHashmapKeyFromFd(intptr_t fd) {
// The hashmap does not support keys with value 0.
return reinterpret_cast<void*>(fd + 1);
}
uint32_t EventHandlerImplementation::GetHashmapHashFromFd(intptr_t fd) {
// The hashmap does not support keys with value 0.
return dart::Utils::WordHash(fd + 1);
}
<commit_msg>Fix event handler assert stupidity. :-)<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/eventhandler.h"
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/event.h>
#include <sys/time.h>
#include <unistd.h>
#include "bin/dartutils.h"
#include "bin/fdutils.h"
#include "bin/hashmap.h"
#include "platform/utils.h"
int64_t GetCurrentTimeMilliseconds() {
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0) {
UNREACHABLE();
return 0;
}
return ((static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec) / 1000;
}
static const int kInterruptMessageSize = sizeof(InterruptMessage);
static const int kInfinityTimeout = -1;
static const int kTimerId = -1;
bool SocketData::HasReadEvent() {
return !IsClosedRead() && ((mask_ & (1 << kInEvent)) != 0);
}
bool SocketData::HasWriteEvent() {
return !IsClosedWrite() && ((mask_ & (1 << kOutEvent)) != 0);
}
// Unregister the file descriptor for a SocketData structure with kqueue.
static void RemoveFromKqueue(intptr_t kqueue_fd_, SocketData* sd) {
static const intptr_t kMaxChanges = 2;
intptr_t changes = 0;
struct kevent events[kMaxChanges];
if (sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_read_tracked_by_kqueue(false);
}
if (sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, sd);
++changes;
sd->set_write_tracked_by_kqueue(false);
}
if (changes > 0) {
ASSERT(changes <= kMaxChanges);
int status =
TEMP_FAILURE_RETRY(kevent(kqueue_fd_, events, changes, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed deleting events from kqueue");
}
}
}
// Update the kqueue registration for SocketData structure to reflect
// the events currently of interest.
static void UpdateKqueue(intptr_t kqueue_fd_, SocketData* sd) {
static const intptr_t kMaxChanges = 2;
intptr_t changes = 0;
struct kevent events[kMaxChanges];
if (sd->port() != 0) {
// Register or unregister READ filter if needed.
if (sd->HasReadEvent()) {
if (!sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_ADD, 0, 0, sd);
++changes;
sd->set_read_tracked_by_kqueue(true);
}
} else if (sd->read_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_READ, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_read_tracked_by_kqueue(false);
}
// Register or unregister WRITE filter if needed.
if (sd->HasWriteEvent()) {
if (!sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_ADD, 0, 0, sd);
++changes;
sd->set_write_tracked_by_kqueue(true);
}
} else if (sd->write_tracked_by_kqueue()) {
EV_SET(events + changes, sd->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
++changes;
sd->set_write_tracked_by_kqueue(false);
}
}
if (changes > 0) {
ASSERT(changes <= kMaxChanges);
int status =
TEMP_FAILURE_RETRY(kevent(kqueue_fd_, events, changes, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed updating kqueue");
}
}
}
EventHandlerImplementation::EventHandlerImplementation()
: socket_map_(&HashMap::SamePointerValue, 16) {
intptr_t result;
result = TEMP_FAILURE_RETRY(pipe(interrupt_fds_));
if (result != 0) {
FATAL("Pipe creation failed");
}
FDUtils::SetNonBlocking(interrupt_fds_[0]);
timeout_ = kInfinityTimeout;
timeout_port_ = 0;
kqueue_fd_ = TEMP_FAILURE_RETRY(kqueue());
if (kqueue_fd_ == -1) {
FATAL("Failed creating kqueue");
}
// Register the interrupt_fd with the kqueue.
struct kevent event;
EV_SET(&event, interrupt_fds_[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
int status = TEMP_FAILURE_RETRY(kevent(kqueue_fd_, &event, 1, NULL, 0, NULL));
if (status == -1) {
FATAL("Failed adding interrupt fd to kqueue");
}
}
EventHandlerImplementation::~EventHandlerImplementation() {
TEMP_FAILURE_RETRY(close(interrupt_fds_[0]));
TEMP_FAILURE_RETRY(close(interrupt_fds_[1]));
}
SocketData* EventHandlerImplementation::GetSocketData(intptr_t fd) {
ASSERT(fd >= 0);
HashMap::Entry* entry = socket_map_.Lookup(
GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd), true);
ASSERT(entry != NULL);
SocketData* sd = reinterpret_cast<SocketData*>(entry->value);
if (sd == NULL) {
// If there is no data in the hash map for this file descriptor a
// new SocketData for the file descriptor is inserted.
sd = new SocketData(fd);
entry->value = sd;
}
ASSERT(fd == sd->fd());
return sd;
}
void EventHandlerImplementation::WakeupHandler(intptr_t id,
Dart_Port dart_port,
int64_t data) {
InterruptMessage msg;
msg.id = id;
msg.dart_port = dart_port;
msg.data = data;
intptr_t result =
FDUtils::WriteToBlocking(interrupt_fds_[1], &msg, kInterruptMessageSize);
if (result != kInterruptMessageSize) {
if (result == -1) {
perror("Interrupt message failure:");
}
FATAL1("Interrupt message failure. Wrote %d bytes.", result);
}
}
bool EventHandlerImplementation::GetInterruptMessage(InterruptMessage* msg) {
int total_read = 0;
int bytes_read =
TEMP_FAILURE_RETRY(read(interrupt_fds_[0], msg, kInterruptMessageSize));
if (bytes_read < 0) {
return false;
}
total_read = bytes_read;
while (total_read < kInterruptMessageSize) {
bytes_read = TEMP_FAILURE_RETRY(read(interrupt_fds_[0],
msg + total_read,
kInterruptMessageSize - total_read));
if (bytes_read > 0) {
total_read = total_read + bytes_read;
}
}
return (total_read == kInterruptMessageSize) ? true : false;
}
void EventHandlerImplementation::HandleInterruptFd() {
InterruptMessage msg;
while (GetInterruptMessage(&msg)) {
if (msg.id == kTimerId) {
timeout_ = msg.data;
timeout_port_ = msg.dart_port;
} else {
SocketData* sd = GetSocketData(msg.id);
if ((msg.data & (1 << kShutdownReadCommand)) != 0) {
ASSERT(msg.data == (1 << kShutdownReadCommand));
// Close the socket for reading.
sd->ShutdownRead();
UpdateKqueue(kqueue_fd_, sd);
} else if ((msg.data & (1 << kShutdownWriteCommand)) != 0) {
ASSERT(msg.data == (1 << kShutdownWriteCommand));
// Close the socket for writing.
sd->ShutdownWrite();
UpdateKqueue(kqueue_fd_, sd);
} else if ((msg.data & (1 << kCloseCommand)) != 0) {
ASSERT(msg.data == (1 << kCloseCommand));
// Close the socket and free system resources.
RemoveFromKqueue(kqueue_fd_, sd);
intptr_t fd = sd->fd();
sd->Close();
socket_map_.Remove(GetHashmapKeyFromFd(fd), GetHashmapHashFromFd(fd));
delete sd;
} else {
// Setup events to wait for.
sd->SetPortAndMask(msg.dart_port, msg.data);
UpdateKqueue(kqueue_fd_, sd);
}
}
}
}
#ifdef DEBUG_KQUEUE
static void PrintEventMask(intptr_t fd, struct kevent* event) {
printf("%d ", fd);
if (event->filter == EVFILT_READ) printf("EVFILT_READ ");
if (event->filter == EVFILT_WRITE) printf("EVFILT_WRITE ");
printf("flags: %x: ", event->flags);
if ((event->flags & EV_EOF) != 0) printf("EV_EOF ");
if ((event->flags & EV_ERROR) != 0) printf("EV_ERROR ");
printf("(available %d) ", FDUtils::AvailableBytes(fd));
printf("\n");
}
#endif
intptr_t EventHandlerImplementation::GetEvents(struct kevent* event,
SocketData* sd) {
#ifdef DEBUG_KQUEUE
PrintEventMask(sd->fd(), event);
#endif
intptr_t event_mask = 0;
if (sd->IsListeningSocket()) {
// On a listening socket the READ event means that there are
// connections ready to be accepted.
if (event->filter == EVFILT_READ) {
if ((event->flags & EV_EOF) != 0) event_mask |= (1 << kCloseEvent);
if ((event->flags & EV_ERROR) != 0) event_mask |= (1 << kErrorEvent);
if (event_mask == 0) event_mask |= (1 << kInEvent);
}
} else {
// Prioritize data events over close and error events.
if (event->filter == EVFILT_READ) {
if (FDUtils::AvailableBytes(sd->fd()) != 0) {
event_mask = (1 << kInEvent);
} else if ((event->flags & EV_EOF) != 0) {
event_mask = (1 << kCloseEvent);
sd->MarkClosedRead();
} else if ((event->flags & EV_ERROR) != 0) {
event_mask = (1 << kErrorEvent);
}
}
if (event->filter == EVFILT_WRITE) {
if ((event->flags & EV_ERROR) != 0) {
event_mask = (1 << kErrorEvent);
sd->MarkClosedWrite();
} else if ((event->flags & EV_EOF) != 0) {
// If the receiver closed for reading, close for writing,
// update the registration with kqueue, and do not report a
// write event.
sd->MarkClosedWrite();
UpdateKqueue(kqueue_fd_, sd);
} else {
event_mask |= (1 << kOutEvent);
}
}
}
return event_mask;
}
void EventHandlerImplementation::HandleEvents(struct kevent* events,
int size) {
for (int i = 0; i < size; i++) {
if (events[i].udata != NULL) {
SocketData* sd = reinterpret_cast<SocketData*>(events[i].udata);
intptr_t event_mask = GetEvents(events + i, sd);
if (event_mask != 0) {
// Unregister events for the file descriptor. Events will be
// registered again when the current event has been handled in
// Dart code.
RemoveFromKqueue(kqueue_fd_, sd);
Dart_Port port = sd->port();
ASSERT(port != 0);
DartUtils::PostInt32(port, event_mask);
}
}
}
HandleInterruptFd();
}
intptr_t EventHandlerImplementation::GetTimeout() {
if (timeout_ == kInfinityTimeout) {
return kInfinityTimeout;
}
intptr_t millis = timeout_ - GetCurrentTimeMilliseconds();
return (millis < 0) ? 0 : millis;
}
void EventHandlerImplementation::HandleTimeout() {
if (timeout_ != kInfinityTimeout) {
intptr_t millis = timeout_ - GetCurrentTimeMilliseconds();
if (millis <= 0) {
DartUtils::PostNull(timeout_port_);
timeout_ = kInfinityTimeout;
timeout_port_ = 0;
}
}
}
void EventHandlerImplementation::EventHandlerEntry(uword args) {
static const intptr_t kMaxEvents = 16;
struct kevent events[kMaxEvents];
EventHandlerImplementation* handler =
reinterpret_cast<EventHandlerImplementation*>(args);
ASSERT(handler != NULL);
while (1) {
intptr_t millis = handler->GetTimeout();
struct timespec ts;
int64_t secs = 0;
int64_t nanos = 0;
if (millis > 0) {
secs = millis / 1000;
nanos = (millis - (secs * 1000)) * 1000000;
}
ts.tv_sec = secs;
ts.tv_nsec = nanos;
intptr_t result = TEMP_FAILURE_RETRY(kevent(handler->kqueue_fd_,
NULL,
0,
events,
kMaxEvents,
&ts));
if (result == -1) {
perror("kevent failed");
FATAL("kevent failed\n");
} else {
handler->HandleTimeout();
handler->HandleEvents(events, result);
}
}
}
void EventHandlerImplementation::StartEventHandler() {
int result =
dart::Thread::Start(&EventHandlerImplementation::EventHandlerEntry,
reinterpret_cast<uword>(this));
if (result != 0) {
FATAL1("Failed to start event handler thread %d", result);
}
}
void EventHandlerImplementation::SendData(intptr_t id,
Dart_Port dart_port,
intptr_t data) {
WakeupHandler(id, dart_port, data);
}
void* EventHandlerImplementation::GetHashmapKeyFromFd(intptr_t fd) {
// The hashmap does not support keys with value 0.
return reinterpret_cast<void*>(fd + 1);
}
uint32_t EventHandlerImplementation::GetHashmapHashFromFd(intptr_t fd) {
// The hashmap does not support keys with value 0.
return dart::Utils::WordHash(fd + 1);
}
<|endoftext|> |
<commit_before>#ifndef SEGMENTATOR_HH
#define SEGMENTATOR_HH
/** Structure for representing states and their probabilities */
struct StateProbPair {
int state_num;
double prob;
};
/** Virtual base class for generating or reading segmentations of
* training utterances.
*/
class Segmentator {
public:
/** Precomputes necessary statistics for generating the segmentation
* for an utterance. */
void init_utterance_segmentation(void) = 0;
/** Returns the current frame number, as referenced for
* \ref FeatureGenerator. */
int current_frame(void) = 0;
/** Computes the state probability statistics for the next frame. */
void next_frame(void) = 0;
/** Returns a reference to a vector of possible states and their
* probabilities */
const std::vector<StateProbPair>& state_probs(void) = 0;
};
#endif // SEGMENTATOR_HH
<commit_msg>Added eof()<commit_after>#ifndef SEGMENTATOR_HH
#define SEGMENTATOR_HH
/** Structure for representing states and their probabilities */
struct StateProbPair {
int state_num;
double prob;
};
/** Virtual base class for generating or reading segmentations of
* training utterances.
*/
class Segmentator {
public:
/** Precomputes necessary statistics for generating the segmentation
* for an utterance. */
void init_utterance_segmentation(void) = 0;
/** Returns the current frame number, as referenced for
* \ref FeatureGenerator. */
int current_frame(void) = 0;
/** Computes the state probability statistics for the next frame. */
void next_frame(void) = 0;
/** Returns true if the previous frame read was the last one. After
* that, \ref next_frame() should not be called */
bool eof(void) = 0;
/** Returns a reference to a vector of possible states and their
* probabilities */
const std::vector<StateProbPair>& state_probs(void) = 0;
};
#endif // SEGMENTATOR_HH
<|endoftext|> |
<commit_before>/**
* @doc Vector NIF module - provides a C++ implementation of the `vector` Erlang module
*
* @copyright 2012-2013 David H. Bronke and Christopher S. Case
* Licensed under the MIT license; see the LICENSE file for details.
*/
#include <string.h>
#include "nif_helpers.h"
#include "vector_nif.h"
// --------------------------------------------------------------------------------------------------------------------
// NIFs
// dot/2
static ERL_NIF_TERM dot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end dot
// cross/2
static ERL_NIF_TERM cross(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
Vec vec0, vec1;
if(termToVec(env, argv[0], vec0) && termToVec(env, argv[1], vec1))
{
return vecToTerm(env, vec0.cross(vec1));
}
else
{
FAIL;
} // end if
} // end cross
// multiply/2
static ERL_NIF_TERM multiply(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end multiply
// divide/2
static ERL_NIF_TERM divide(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end divide
// squared_norm/1
static ERL_NIF_TERM squared_norm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end squared_norm
// norm/1
static ERL_NIF_TERM norm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end norm
// length/1
static ERL_NIF_TERM length(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end length
// unit/1
static ERL_NIF_TERM unit(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end unit
// hpr_to/1
static ERL_NIF_TERM hpr_to(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end hpr_to
// add/2, add/3
static ERL_NIF_TERM add(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC_RANGE(2, 3)
FAIL;
} // end add
// subtract/2
static ERL_NIF_TERM subtract(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end subtract
// is_zero/1
static ERL_NIF_TERM is_zero(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end is_zero
// --------------------------------------------------------------------------------------------------------------------
// Helpers
static bool termToVec(ErlNifEnv* env, const ERL_NIF_TERM term, Vec& targetVec)
{
int arity;
const ERL_NIF_TERM* array;
if(!enif_get_tuple(env, term, &arity, &array))
{
return false;
} // end if
if(arity != 4)
{
return false;
} // end if
if(!enif_get_double(env, array[0], &targetVec.x)
|| !enif_get_double(env, array[1], &targetVec.y)
|| !enif_get_double(env, array[2], &targetVec.z))
{
return false;
} // end if
return true;
} // termToVec
static inline ERL_NIF_TERM vecToTerm(ErlNifEnv* env, const Vec& vec)
{
return enif_make_tuple3(env,
enif_make_double(env, vec.x),
enif_make_double(env, vec.y),
enif_make_double(env, vec.z)
);
} // end vecToTerm
/// Multiply this Vec by whatever's stored in the given Erlang term, if possible.
static Vec multiply(const Vec& vec, ErlNifEnv* env, const ERL_NIF_TERM other)
{
//FIXME Implement this!
return vec;
} // end multiply
<commit_msg>Corrected vector_nif's termToVec() to use getNIFDouble instead of enif_get_double, so we can handle ints and other such things.<commit_after>/**
* @doc Vector NIF module - provides a C++ implementation of the `vector` Erlang module
*
* @copyright 2012-2013 David H. Bronke and Christopher S. Case
* Licensed under the MIT license; see the LICENSE file for details.
*/
#include <string>
#include "nif_helpers.h"
#include "vector_nif.h"
// --------------------------------------------------------------------------------------------------------------------
// NIFs
// dot/2
static ERL_NIF_TERM dot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end dot
// cross/2
static ERL_NIF_TERM cross(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
Vec vec0, vec1;
if(termToVec(env, argv[0], vec0) && termToVec(env, argv[1], vec1))
{
return vecToTerm(env, vec0.cross(vec1));
}
else
{
FAIL;
} // end if
} // end cross
// multiply/2
static ERL_NIF_TERM multiply(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end multiply
// divide/2
static ERL_NIF_TERM divide(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end divide
// squared_norm/1
static ERL_NIF_TERM squared_norm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end squared_norm
// norm/1
static ERL_NIF_TERM norm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end norm
// length/1
static ERL_NIF_TERM length(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end length
// unit/1
static ERL_NIF_TERM unit(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end unit
// hpr_to/1
static ERL_NIF_TERM hpr_to(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end hpr_to
// add/2, add/3
static ERL_NIF_TERM add(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC_RANGE(2, 3)
FAIL;
} // end add
// subtract/2
static ERL_NIF_TERM subtract(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(2);
FAIL;
} // end subtract
// is_zero/1
static ERL_NIF_TERM is_zero(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
CHECK_ARGC(1);
FAIL;
} // end is_zero
// --------------------------------------------------------------------------------------------------------------------
// Helpers
static bool termToVec(ErlNifEnv* env, const ERL_NIF_TERM term, Vec& targetVec)
{
int arity;
const ERL_NIF_TERM* array;
if(!enif_get_tuple(env, term, &arity, &array))
{
return false;
} // end if
if(arity != 3)
{
return false;
} // end if
if(!getNIFDouble(env, array[0], &targetVec.x)
|| !getNIFDouble(env, array[1], &targetVec.y)
|| !getNIFDouble(env, array[2], &targetVec.z))
{
return false;
} // end if
return true;
} // termToVec
static inline ERL_NIF_TERM vecToTerm(ErlNifEnv* env, const Vec& vec)
{
return enif_make_tuple3(env,
enif_make_double(env, vec.x),
enif_make_double(env, vec.y),
enif_make_double(env, vec.z)
);
} // end vecToTerm
/// Multiply this Vec by whatever's stored in the given Erlang term, if possible.
static Vec multiply(const Vec& vec, ErlNifEnv* env, const ERL_NIF_TERM other)
{
//FIXME Implement this!
return vec;
} // end multiply
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/chrome_pref_service_factory.h"
#include "chrome/browser/prefs/pref_hash_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
#include "chromeos/chromeos_switches.h"
#endif
namespace {
// An observer that returns back to test code after a new profile is
// initialized.
void OnUnblockOnProfileCreation(const base::Closure& callback,
Profile* profile,
Profile::CreateStatus status) {
switch (status) {
case Profile::CREATE_STATUS_CREATED:
// Wait for CREATE_STATUS_INITIALIZED.
break;
case Profile::CREATE_STATUS_INITIALIZED:
callback.Run();
break;
default:
ADD_FAILURE() << "Unexpected Profile::CreateStatus: " << status;
callback.Run();
break;
}
}
// Finds a profile path corresponding to a profile that has not been loaded yet.
base::FilePath GetUnloadedProfilePath() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
const ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
const std::vector<Profile*> loaded_profiles =
profile_manager->GetLoadedProfiles();
std::set<base::FilePath> profile_paths;
for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i)
profile_paths.insert(cache.GetPathOfProfileAtIndex(i));
for (size_t i = 0; i < loaded_profiles.size(); ++i)
EXPECT_EQ(1U, profile_paths.erase(loaded_profiles[i]->GetPath()));
if (profile_paths.size())
return *profile_paths.begin();
return base::FilePath();
}
// Returns the number of times |histogram_name| was reported so far; adding the
// results of the first 100 buckets (there are only ~14 reporting IDs as of this
// writting; varies depending on the platform). If |expect_zero| is true, this
// method will explicitly report IDs that are non-zero for ease of diagnosis.
int GetTrackedPrefHistogramCount(const char* histogram_name, bool expect_zero) {
const base::HistogramBase* histogram =
base::StatisticsRecorder::FindHistogram(histogram_name);
if (!histogram)
return 0;
scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
int sum = 0;
for (int i = 0; i < 100; ++i) {
int count_for_id = samples->GetCount(i);
sum += count_for_id;
if (expect_zero)
EXPECT_EQ(0, count_for_id) << "Faulty reporting_id: " << i;
}
return sum;
}
} // namespace
class PrefHashBrowserTest : public InProcessBrowserTest,
public testing::WithParamInterface<std::string> {
public:
PrefHashBrowserTest()
: is_unloaded_profile_seeding_allowed_(
IsUnloadedProfileSeedingAllowed()) {}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kForceFieldTrials,
std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
"/" + GetParam() + "/");
#if defined(OS_CHROMEOS)
command_line->AppendSwitch(
chromeos::switches::kIgnoreUserProfileMappingForTests);
#endif
}
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
// Force the delayed PrefHashStore update task to happen immediately with
// no domain check (bots are on a domain).
chrome_prefs::DisableDelaysAndDomainCheckForTesting();
}
virtual void SetUpOnMainThread() OVERRIDE {
// content::RunAllPendingInMessageLoop() is already called before
// SetUpOnMainThread() in in_process_browser_test.cc which guarantees that
// UpdateAllPrefHashStoresIfRequired() has already been called.
// Now flush the blocking pool to force any pending JsonPrefStore async read
// requests.
content::BrowserThread::GetBlockingPool()->FlushForTesting();
// And finally run tasks on this message loop again to process the OnRead()
// callbacks resulting from the file reads above.
content::RunAllPendingInMessageLoop();
}
protected:
const bool is_unloaded_profile_seeding_allowed_;
private:
bool IsUnloadedProfileSeedingAllowed() const {
#if defined(OFFICIAL_BUILD)
// SettingsEnforcement can't be forced via --force-fieldtrials in official
// builds. Explicitly return whether the default in
// chrome_pref_service_factory.cc allows unloaded profile seeding on this
// platform.
return true;
#endif // defined(OFFICIAL_BUILD)
return GetParam() == chrome_prefs::internals::
kSettingsEnforcementGroupNoEnforcement ||
GetParam() == chrome_prefs::internals::
kSettingsEnforcementGroupEnforceOnload;
}
};
#if defined(OS_CHROMEOS)
// PrefHash service has been disabled on ChromeOS: crbug.com/343261
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles DISABLED_PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles DISABLED_PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles DISABLED_InitializeUnloadedProfiles
#else
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles InitializeUnloadedProfiles
#endif
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_PRE_InitializeUnloadedProfiles) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create an additional profile.
const base::FilePath new_path =
profile_manager->GenerateNextProfileDirectoryPath();
const scoped_refptr<content::MessageLoopRunner> runner(
new content::MessageLoopRunner);
profile_manager->CreateProfileAsync(
new_path,
base::Bind(&OnUnblockOnProfileCreation, runner->QuitClosure()),
base::string16(),
base::string16(),
std::string());
// Spin to allow profile creation to take place, loop is terminated
// by OnUnblockOnProfileCreation when the profile is created.
runner->Run();
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles should have been loaded normally.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_InitializeUnloadedProfiles) {
// Creating the profile would have initialized its hash store. Also, we don't
// know whether the newly created or original profile will be launched (does
// creating a profile cause it to be the most recently used?).
// So we will find the profile that isn't loaded, reset its hash store, and
// then verify in the _next_ launch that it is, indeed, restored despite not
// having been loaded.
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// 4 is for hash_of_hashes, versions_dict, default profile, and new profile.
EXPECT_EQ(4U, hashes->size());
// One of the two profiles should not have been loaded. Reset its hash store.
const base::FilePath unloaded_profile_path = GetUnloadedProfilePath();
chrome_prefs::ResetPrefHashStore(unloaded_profile_path);
// One of the profile hash collections should be gone.
EXPECT_EQ(3U, hashes->size());
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles were already initialized at the beginning of
// this phase (resetting the unloaded profile's PrefHashStore should only
// force initialization in the next phase's startup).
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_InitializeUnloadedProfiles) {
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// The deleted hash collection should be restored only if the current
// SettingsEnforcement group allows it.
if (is_unloaded_profile_seeding_allowed_) {
EXPECT_EQ(4U, hashes->size());
// Verify that the initialization truly did occur in this phase's startup;
// rather than in the previous phase's shutdown.
EXPECT_EQ(
1, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
false));
} else {
EXPECT_EQ(3U, hashes->size());
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Verify that only one profile was loaded. We assume that the unloaded
// profile is the same one that wasn't loaded in the last launch (i.e., it's
// the one whose hash store we reset, and the fact that it is now restored is
// evidence that we restored the hashes of an unloaded profile.).
ASSERT_EQ(1U, profile_manager->GetLoadedProfiles().size());
// Loading the first profile should only have produced unchanged reports.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
int initial_unchanged_count =
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false);
EXPECT_GT(initial_unchanged_count, 0);
if (is_unloaded_profile_seeding_allowed_) {
// Explicitly load the unloaded profile.
profile_manager->GetProfile(GetUnloadedProfilePath());
ASSERT_EQ(2U, profile_manager->GetLoadedProfiles().size());
// Loading the unloaded profile should only generate unchanged pings; and
// should have produced as many of them as loading the first profile.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
EXPECT_EQ(
initial_unchanged_count * 2,
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false));
}
}
INSTANTIATE_TEST_CASE_P(
PrefHashBrowserTestInstance,
PrefHashBrowserTest,
testing::Values(
chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceOnload,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways,
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensions,
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE));
<commit_msg>Add an #else to #ifdef OFFICIAL_BUILD<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/chrome_pref_service_factory.h"
#include "chrome/browser/prefs/pref_hash_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_CHROMEOS)
#include "chromeos/chromeos_switches.h"
#endif
namespace {
// An observer that returns back to test code after a new profile is
// initialized.
void OnUnblockOnProfileCreation(const base::Closure& callback,
Profile* profile,
Profile::CreateStatus status) {
switch (status) {
case Profile::CREATE_STATUS_CREATED:
// Wait for CREATE_STATUS_INITIALIZED.
break;
case Profile::CREATE_STATUS_INITIALIZED:
callback.Run();
break;
default:
ADD_FAILURE() << "Unexpected Profile::CreateStatus: " << status;
callback.Run();
break;
}
}
// Finds a profile path corresponding to a profile that has not been loaded yet.
base::FilePath GetUnloadedProfilePath() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
const ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
const std::vector<Profile*> loaded_profiles =
profile_manager->GetLoadedProfiles();
std::set<base::FilePath> profile_paths;
for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i)
profile_paths.insert(cache.GetPathOfProfileAtIndex(i));
for (size_t i = 0; i < loaded_profiles.size(); ++i)
EXPECT_EQ(1U, profile_paths.erase(loaded_profiles[i]->GetPath()));
if (profile_paths.size())
return *profile_paths.begin();
return base::FilePath();
}
// Returns the number of times |histogram_name| was reported so far; adding the
// results of the first 100 buckets (there are only ~14 reporting IDs as of this
// writting; varies depending on the platform). If |expect_zero| is true, this
// method will explicitly report IDs that are non-zero for ease of diagnosis.
int GetTrackedPrefHistogramCount(const char* histogram_name, bool expect_zero) {
const base::HistogramBase* histogram =
base::StatisticsRecorder::FindHistogram(histogram_name);
if (!histogram)
return 0;
scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
int sum = 0;
for (int i = 0; i < 100; ++i) {
int count_for_id = samples->GetCount(i);
sum += count_for_id;
if (expect_zero)
EXPECT_EQ(0, count_for_id) << "Faulty reporting_id: " << i;
}
return sum;
}
} // namespace
class PrefHashBrowserTest : public InProcessBrowserTest,
public testing::WithParamInterface<std::string> {
public:
PrefHashBrowserTest()
: is_unloaded_profile_seeding_allowed_(
IsUnloadedProfileSeedingAllowed()) {}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kForceFieldTrials,
std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
"/" + GetParam() + "/");
#if defined(OS_CHROMEOS)
command_line->AppendSwitch(
chromeos::switches::kIgnoreUserProfileMappingForTests);
#endif
}
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
// Force the delayed PrefHashStore update task to happen immediately with
// no domain check (bots are on a domain).
chrome_prefs::DisableDelaysAndDomainCheckForTesting();
}
virtual void SetUpOnMainThread() OVERRIDE {
// content::RunAllPendingInMessageLoop() is already called before
// SetUpOnMainThread() in in_process_browser_test.cc which guarantees that
// UpdateAllPrefHashStoresIfRequired() has already been called.
// Now flush the blocking pool to force any pending JsonPrefStore async read
// requests.
content::BrowserThread::GetBlockingPool()->FlushForTesting();
// And finally run tasks on this message loop again to process the OnRead()
// callbacks resulting from the file reads above.
content::RunAllPendingInMessageLoop();
}
protected:
const bool is_unloaded_profile_seeding_allowed_;
private:
bool IsUnloadedProfileSeedingAllowed() const {
#if defined(OFFICIAL_BUILD)
// SettingsEnforcement can't be forced via --force-fieldtrials in official
// builds. Explicitly return whether the default in
// chrome_pref_service_factory.cc allows unloaded profile seeding on this
// platform.
return true;
#else
return GetParam() == chrome_prefs::internals::
kSettingsEnforcementGroupNoEnforcement ||
GetParam() == chrome_prefs::internals::
kSettingsEnforcementGroupEnforceOnload;
#endif // defined(OFFICIAL_BUILD)
}
};
#if defined(OS_CHROMEOS)
// PrefHash service has been disabled on ChromeOS: crbug.com/343261
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles DISABLED_PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles DISABLED_PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles DISABLED_InitializeUnloadedProfiles
#else
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles InitializeUnloadedProfiles
#endif
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_PRE_InitializeUnloadedProfiles) {
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create an additional profile.
const base::FilePath new_path =
profile_manager->GenerateNextProfileDirectoryPath();
const scoped_refptr<content::MessageLoopRunner> runner(
new content::MessageLoopRunner);
profile_manager->CreateProfileAsync(
new_path,
base::Bind(&OnUnblockOnProfileCreation, runner->QuitClosure()),
base::string16(),
base::string16(),
std::string());
// Spin to allow profile creation to take place, loop is terminated
// by OnUnblockOnProfileCreation when the profile is created.
runner->Run();
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles should have been loaded normally.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_InitializeUnloadedProfiles) {
// Creating the profile would have initialized its hash store. Also, we don't
// know whether the newly created or original profile will be launched (does
// creating a profile cause it to be the most recently used?).
// So we will find the profile that isn't loaded, reset its hash store, and
// then verify in the _next_ launch that it is, indeed, restored despite not
// having been loaded.
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// 4 is for hash_of_hashes, versions_dict, default profile, and new profile.
EXPECT_EQ(4U, hashes->size());
// One of the two profiles should not have been loaded. Reset its hash store.
const base::FilePath unloaded_profile_path = GetUnloadedProfilePath();
chrome_prefs::ResetPrefHashStore(unloaded_profile_path);
// One of the profile hash collections should be gone.
EXPECT_EQ(3U, hashes->size());
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles were already initialized at the beginning of
// this phase (resetting the unloaded profile's PrefHashStore should only
// force initialization in the next phase's startup).
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_InitializeUnloadedProfiles) {
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// The deleted hash collection should be restored only if the current
// SettingsEnforcement group allows it.
if (is_unloaded_profile_seeding_allowed_) {
EXPECT_EQ(4U, hashes->size());
// Verify that the initialization truly did occur in this phase's startup;
// rather than in the previous phase's shutdown.
EXPECT_EQ(
1, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
false));
} else {
EXPECT_EQ(3U, hashes->size());
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Verify that only one profile was loaded. We assume that the unloaded
// profile is the same one that wasn't loaded in the last launch (i.e., it's
// the one whose hash store we reset, and the fact that it is now restored is
// evidence that we restored the hashes of an unloaded profile.).
ASSERT_EQ(1U, profile_manager->GetLoadedProfiles().size());
// Loading the first profile should only have produced unchanged reports.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
int initial_unchanged_count =
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false);
EXPECT_GT(initial_unchanged_count, 0);
if (is_unloaded_profile_seeding_allowed_) {
// Explicitly load the unloaded profile.
profile_manager->GetProfile(GetUnloadedProfilePath());
ASSERT_EQ(2U, profile_manager->GetLoadedProfiles().size());
// Loading the unloaded profile should only generate unchanged pings; and
// should have produced as many of them as loading the first profile.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
EXPECT_EQ(
initial_unchanged_count * 2,
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false));
}
}
INSTANTIATE_TEST_CASE_P(
PrefHashBrowserTestInstance,
PrefHashBrowserTest,
testing::Values(
chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceOnload,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways,
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensions,
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensionsAndDSE));
<|endoftext|> |
<commit_before>/* Copyright 2017 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "numa_module.h"
#include "numasysif.h"
#include "logging.h"
#include "cmdline.h"
#include "proc_impl.h"
#include "threads.h"
#include "runtime_impl.h"
#include "utils.h"
namespace Realm {
Logger log_numa("numa");
////////////////////////////////////////////////////////////////////////
//
// class LocalNumaProcessor
// this is nearly identical to a LocalCPUProcessor, but it asks for its thread(s)
// to run on the specified numa domain
class LocalNumaProcessor : public LocalTaskProcessor {
public:
LocalNumaProcessor(Processor _me, int _numa_node,
CoreReservationSet& crs, size_t _stack_size);
virtual ~LocalNumaProcessor(void);
protected:
int numa_node;
CoreReservation *core_rsrv;
};
LocalNumaProcessor::LocalNumaProcessor(Processor _me, int _numa_node,
CoreReservationSet& crs,
size_t _stack_size)
: LocalTaskProcessor(_me, Processor::LOC_PROC)
, numa_node(_numa_node)
{
CoreReservationParameters params;
params.set_num_cores(1);
params.set_numa_domain(numa_node);
params.set_alu_usage(params.CORE_USAGE_EXCLUSIVE);
params.set_fpu_usage(params.CORE_USAGE_EXCLUSIVE);
params.set_ldst_usage(params.CORE_USAGE_SHARED);
params.set_max_stack_size(_stack_size);
std::string name = stringbuilder() << "NUMA" << numa_node << " proc " << _me;
core_rsrv = new CoreReservation(name, crs, params);
#ifdef REALM_USE_USER_THREADS
UserThreadTaskScheduler *sched = new UserThreadTaskScheduler(me, *core_rsrv);
// no config settings we want to tweak yet
#else
KernelThreadTaskScheduler *sched = new KernelThreadTaskScheduler(me, *core_rsrv);
sched->cfg_max_idle_workers = 3; // keep a few idle threads around
#endif
set_scheduler(sched);
}
LocalNumaProcessor::~LocalNumaProcessor(void)
{
delete core_rsrv;
}
namespace Numa {
////////////////////////////////////////////////////////////////////////
//
// class NumaModule
NumaModule::NumaModule(void)
: Module("numa")
, cfg_numa_mem_size_in_mb(0)
, cfg_numa_nocpu_mem_size_in_mb(-1)
, cfg_num_numa_cpus(0)
, cfg_pin_memory(false)
, cfg_stack_size_in_mb(2)
{
}
NumaModule::~NumaModule(void)
{}
/*static*/ Module *NumaModule::create_module(RuntimeImpl *runtime,
std::vector<std::string>& cmdline)
{
// create a module to fill in with stuff - we'll delete it if numa is
// disabled
NumaModule *m = new NumaModule;
// first order of business - read command line parameters
{
CommandLineParser cp;
cp.add_option_int("-ll:nsize", m->cfg_numa_mem_size_in_mb)
.add_option_int("-ll:ncsize", m->cfg_numa_nocpu_mem_size_in_mb)
.add_option_int("-ll:ncpu", m->cfg_num_numa_cpus)
.add_option_bool("-numa:pin", m->cfg_pin_memory);
bool ok = cp.parse_command_line(cmdline);
if(!ok) {
log_numa.fatal() << "error reading NUMA command line parameters";
assert(false);
}
}
// if neither NUMA memory nor cpus was requested, there's no point
if((m->cfg_numa_mem_size_in_mb == 0) && (m->cfg_num_numa_cpus == 0)) {
log_numa.debug() << "no NUMA memory or cpus requested";
delete m;
return 0;
}
// next step - see if the system supports NUMA allocation/binding
if(!numasysif_numa_available()) {
// TODO: warning or fatal error here?
log_numa.warning() << "numa support not available in system";
delete m;
return 0;
}
// get number/sizes of NUMA nodes
std::map<int, NumaNodeMemInfo> meminfo;
std::map<int, NumaNodeCpuInfo> cpuinfo;
if(!numasysif_get_mem_info(meminfo) ||
!numasysif_get_cpu_info(cpuinfo)) {
log_numa.fatal() << "failed to get mem/cpu info from system";
assert(false);
}
// some sanity-checks
for(std::map<int, NumaNodeMemInfo>::const_iterator it = meminfo.begin();
it != meminfo.end();
++it) {
const NumaNodeMemInfo& mi = it->second;
log_numa.info() << "NUMA memory node " << mi.node_id << ": " << (mi.bytes_available >> 20) << " MB";
size_t mem_size = (m->cfg_numa_mem_size_in_mb << 20);
if(m->cfg_numa_nocpu_mem_size_in_mb >= 0) {
// use this value instead if there are no cpus in this domain
if(cpuinfo.count(mi.node_id) == 0)
mem_size = (m->cfg_numa_nocpu_mem_size_in_mb << 20);
}
// skip domain silently if no memory is requested
if(mem_size == 0)
continue;
if(mi.bytes_available >= mem_size) {
m->numa_mem_bases[mi.node_id] = 0;
m->numa_mem_sizes[mi.node_id] = mem_size;
} else {
// TODO: fatal error?
log_numa.warning() << "insufficient memory in NUMA node " << mi.node_id << " (" << mem_size << " > " << mi.bytes_available << " bytes) - skipping allocation";
}
}
for(std::map<int, NumaNodeCpuInfo>::const_iterator it = cpuinfo.begin();
it != cpuinfo.end();
++it) {
const NumaNodeCpuInfo& ci = it->second;
log_numa.info() << "NUMA cpu node " << ci.node_id << ": " << ci.cores_available << " cores";
if(ci.cores_available >= m->cfg_num_numa_cpus) {
m->numa_cpu_counts[ci.node_id] = m->cfg_num_numa_cpus;
} else {
// TODO: fatal error?
log_numa.warning() << "insufficient cores in NUMA node " << ci.node_id << " - core assignment will fail";
m->numa_cpu_counts[ci.node_id] = m->cfg_num_numa_cpus;
}
}
return m;
}
// do any general initialization - this is called after all configuration is
// complete
void NumaModule::initialize(RuntimeImpl *runtime)
{
Module::initialize(runtime);
// memory allocations are performed here
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
void *base = numasysif_alloc_mem(it->first,
mem_size,
cfg_pin_memory);
if(!base) {
log_numa.fatal() << "allocation of " << mem_size << " bytes in NUMA node " << it->first << " failed!";
assert(false);
}
it->second = base;
}
}
// create any memories provided by this module (default == do nothing)
// (each new MemoryImpl should use a Memory from RuntimeImpl::next_local_memory_id)
void NumaModule::create_memories(RuntimeImpl *runtime)
{
Module::create_memories(runtime);
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
int mem_node = it->first;
void *base_ptr = it->second;
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
Memory m = runtime->next_local_memory_id();
LocalCPUMemory *numamem = new LocalCPUMemory(m,
mem_size,
base_ptr,
false /*!registered*/);
runtime->add_memory(numamem);
memories[mem_node] = numamem;
}
}
// create any processors provided by the module (default == do nothing)
// (each new ProcessorImpl should use a Processor from
// RuntimeImpl::next_local_processor_id)
void NumaModule::create_processors(RuntimeImpl *runtime)
{
Module::create_processors(runtime);
for(std::map<int, int>::const_iterator it = numa_cpu_counts.begin();
it != numa_cpu_counts.end();
++it) {
int cpu_node = it->first;
for(int i = 0; i < it->second; i++) {
Processor p = runtime->next_local_processor_id();
ProcessorImpl *pi = new LocalNumaProcessor(p, it->first,
runtime->core_reservation_set(),
cfg_stack_size_in_mb << 20);
runtime->add_processor(pi);
// create affinities between this processor and system/reg memories
// if the memory is one we created, use the kernel-reported distance
// to adjust the answer
std::vector<MemoryImpl *>& local_mems = runtime->nodes[gasnet_mynode()].memories;
for(std::vector<MemoryImpl *>::iterator it2 = local_mems.begin();
it2 != local_mems.end();
++it2) {
Memory::Kind kind = (*it2)->get_kind();
if((kind != Memory::SYSTEM_MEM) && (kind != Memory::REGDMA_MEM))
continue;
Machine::ProcessorMemoryAffinity pma;
pma.p = p;
pma.m = (*it2)->me;
int mem_node = -1;
for(std::map<int, MemoryImpl *>::const_iterator it3 = memories.begin();
it3 != memories.end();
++it3)
if(it3->second == *it2) {
mem_node = it3->first;
break;
}
if(mem_node == -1) {
// not one of our memories - use the same made-up numbers as in
// runtime_impl.cc
if(kind == Memory::SYSTEM_MEM) {
pma.bandwidth = 100; // "large"
pma.latency = 5; // "small"
} else {
pma.bandwidth = 80; // "large"
pma.latency = 10; // "small"
}
} else {
int d = numasysif_get_distance(cpu_node, mem_node);
if(d >= 0) {
pma.bandwidth = 150 - d;
pma.latency = d / 10; // Linux uses a cost of ~10/hop
} else {
// same as random sysmem
pma.bandwidth = 100;
pma.latency = 5;
}
}
runtime->add_proc_mem_affinity(pma);
}
}
}
}
// create any DMA channels provided by the module (default == do nothing)
void NumaModule::create_dma_channels(RuntimeImpl *runtime)
{
Module::create_dma_channels(runtime);
}
// create any code translators provided by the module (default == do nothing)
void NumaModule::create_code_translators(RuntimeImpl *runtime)
{
Module::create_code_translators(runtime);
}
// clean up any common resources created by the module - this will be called
// after all memories/processors/etc. have been shut down and destroyed
void NumaModule::cleanup(void)
{
Module::cleanup();
// free our allocations here
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
bool ok = numasysif_free_mem(it->first, it->second, mem_size);
if(!ok)
log_numa.error() << "failed to free memory in NUMA node " << it->first << ": ptr=" << it->second;
}
}
}; // namespace Numa
}; // namespace Realm
<commit_msg>numa: avoid duplicate affinities for now<commit_after>/* Copyright 2017 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "numa_module.h"
#include "numasysif.h"
#include "logging.h"
#include "cmdline.h"
#include "proc_impl.h"
#include "threads.h"
#include "runtime_impl.h"
#include "utils.h"
namespace Realm {
Logger log_numa("numa");
////////////////////////////////////////////////////////////////////////
//
// class LocalNumaProcessor
// this is nearly identical to a LocalCPUProcessor, but it asks for its thread(s)
// to run on the specified numa domain
class LocalNumaProcessor : public LocalTaskProcessor {
public:
LocalNumaProcessor(Processor _me, int _numa_node,
CoreReservationSet& crs, size_t _stack_size);
virtual ~LocalNumaProcessor(void);
protected:
int numa_node;
CoreReservation *core_rsrv;
};
LocalNumaProcessor::LocalNumaProcessor(Processor _me, int _numa_node,
CoreReservationSet& crs,
size_t _stack_size)
: LocalTaskProcessor(_me, Processor::LOC_PROC)
, numa_node(_numa_node)
{
CoreReservationParameters params;
params.set_num_cores(1);
params.set_numa_domain(numa_node);
params.set_alu_usage(params.CORE_USAGE_EXCLUSIVE);
params.set_fpu_usage(params.CORE_USAGE_EXCLUSIVE);
params.set_ldst_usage(params.CORE_USAGE_SHARED);
params.set_max_stack_size(_stack_size);
std::string name = stringbuilder() << "NUMA" << numa_node << " proc " << _me;
core_rsrv = new CoreReservation(name, crs, params);
#ifdef REALM_USE_USER_THREADS
UserThreadTaskScheduler *sched = new UserThreadTaskScheduler(me, *core_rsrv);
// no config settings we want to tweak yet
#else
KernelThreadTaskScheduler *sched = new KernelThreadTaskScheduler(me, *core_rsrv);
sched->cfg_max_idle_workers = 3; // keep a few idle threads around
#endif
set_scheduler(sched);
}
LocalNumaProcessor::~LocalNumaProcessor(void)
{
delete core_rsrv;
}
namespace Numa {
////////////////////////////////////////////////////////////////////////
//
// class NumaModule
NumaModule::NumaModule(void)
: Module("numa")
, cfg_numa_mem_size_in_mb(0)
, cfg_numa_nocpu_mem_size_in_mb(-1)
, cfg_num_numa_cpus(0)
, cfg_pin_memory(false)
, cfg_stack_size_in_mb(2)
{
}
NumaModule::~NumaModule(void)
{}
/*static*/ Module *NumaModule::create_module(RuntimeImpl *runtime,
std::vector<std::string>& cmdline)
{
// create a module to fill in with stuff - we'll delete it if numa is
// disabled
NumaModule *m = new NumaModule;
// first order of business - read command line parameters
{
CommandLineParser cp;
cp.add_option_int("-ll:nsize", m->cfg_numa_mem_size_in_mb)
.add_option_int("-ll:ncsize", m->cfg_numa_nocpu_mem_size_in_mb)
.add_option_int("-ll:ncpu", m->cfg_num_numa_cpus)
.add_option_bool("-numa:pin", m->cfg_pin_memory);
bool ok = cp.parse_command_line(cmdline);
if(!ok) {
log_numa.fatal() << "error reading NUMA command line parameters";
assert(false);
}
}
// if neither NUMA memory nor cpus was requested, there's no point
if((m->cfg_numa_mem_size_in_mb == 0) && (m->cfg_num_numa_cpus == 0)) {
log_numa.debug() << "no NUMA memory or cpus requested";
delete m;
return 0;
}
// next step - see if the system supports NUMA allocation/binding
if(!numasysif_numa_available()) {
// TODO: warning or fatal error here?
log_numa.warning() << "numa support not available in system";
delete m;
return 0;
}
// get number/sizes of NUMA nodes
std::map<int, NumaNodeMemInfo> meminfo;
std::map<int, NumaNodeCpuInfo> cpuinfo;
if(!numasysif_get_mem_info(meminfo) ||
!numasysif_get_cpu_info(cpuinfo)) {
log_numa.fatal() << "failed to get mem/cpu info from system";
assert(false);
}
// some sanity-checks
for(std::map<int, NumaNodeMemInfo>::const_iterator it = meminfo.begin();
it != meminfo.end();
++it) {
const NumaNodeMemInfo& mi = it->second;
log_numa.info() << "NUMA memory node " << mi.node_id << ": " << (mi.bytes_available >> 20) << " MB";
size_t mem_size = (m->cfg_numa_mem_size_in_mb << 20);
if(m->cfg_numa_nocpu_mem_size_in_mb >= 0) {
// use this value instead if there are no cpus in this domain
if(cpuinfo.count(mi.node_id) == 0)
mem_size = (m->cfg_numa_nocpu_mem_size_in_mb << 20);
}
// skip domain silently if no memory is requested
if(mem_size == 0)
continue;
if(mi.bytes_available >= mem_size) {
m->numa_mem_bases[mi.node_id] = 0;
m->numa_mem_sizes[mi.node_id] = mem_size;
} else {
// TODO: fatal error?
log_numa.warning() << "insufficient memory in NUMA node " << mi.node_id << " (" << mem_size << " > " << mi.bytes_available << " bytes) - skipping allocation";
}
}
for(std::map<int, NumaNodeCpuInfo>::const_iterator it = cpuinfo.begin();
it != cpuinfo.end();
++it) {
const NumaNodeCpuInfo& ci = it->second;
log_numa.info() << "NUMA cpu node " << ci.node_id << ": " << ci.cores_available << " cores";
if(ci.cores_available >= m->cfg_num_numa_cpus) {
m->numa_cpu_counts[ci.node_id] = m->cfg_num_numa_cpus;
} else {
// TODO: fatal error?
log_numa.warning() << "insufficient cores in NUMA node " << ci.node_id << " - core assignment will fail";
m->numa_cpu_counts[ci.node_id] = m->cfg_num_numa_cpus;
}
}
return m;
}
// do any general initialization - this is called after all configuration is
// complete
void NumaModule::initialize(RuntimeImpl *runtime)
{
Module::initialize(runtime);
// memory allocations are performed here
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
void *base = numasysif_alloc_mem(it->first,
mem_size,
cfg_pin_memory);
if(!base) {
log_numa.fatal() << "allocation of " << mem_size << " bytes in NUMA node " << it->first << " failed!";
assert(false);
}
it->second = base;
}
}
// create any memories provided by this module (default == do nothing)
// (each new MemoryImpl should use a Memory from RuntimeImpl::next_local_memory_id)
void NumaModule::create_memories(RuntimeImpl *runtime)
{
Module::create_memories(runtime);
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
int mem_node = it->first;
void *base_ptr = it->second;
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
Memory m = runtime->next_local_memory_id();
LocalCPUMemory *numamem = new LocalCPUMemory(m,
mem_size,
base_ptr,
false /*!registered*/);
runtime->add_memory(numamem);
memories[mem_node] = numamem;
}
}
// create any processors provided by the module (default == do nothing)
// (each new ProcessorImpl should use a Processor from
// RuntimeImpl::next_local_processor_id)
void NumaModule::create_processors(RuntimeImpl *runtime)
{
Module::create_processors(runtime);
for(std::map<int, int>::const_iterator it = numa_cpu_counts.begin();
it != numa_cpu_counts.end();
++it) {
int cpu_node = it->first;
for(int i = 0; i < it->second; i++) {
Processor p = runtime->next_local_processor_id();
ProcessorImpl *pi = new LocalNumaProcessor(p, it->first,
runtime->core_reservation_set(),
cfg_stack_size_in_mb << 20);
runtime->add_processor(pi);
// create affinities between this processor and system/reg memories
// if the memory is one we created, use the kernel-reported distance
// to adjust the answer
std::vector<MemoryImpl *>& local_mems = runtime->nodes[gasnet_mynode()].memories;
for(std::vector<MemoryImpl *>::iterator it2 = local_mems.begin();
it2 != local_mems.end();
++it2) {
Memory::Kind kind = (*it2)->get_kind();
if((kind != Memory::SYSTEM_MEM) && (kind != Memory::REGDMA_MEM))
continue;
Machine::ProcessorMemoryAffinity pma;
pma.p = p;
pma.m = (*it2)->me;
int mem_node = -1;
for(std::map<int, MemoryImpl *>::const_iterator it3 = memories.begin();
it3 != memories.end();
++it3)
if(it3->second == *it2) {
mem_node = it3->first;
break;
}
if(mem_node == -1) {
// not one of our memories - use the same made-up numbers as in
// runtime_impl.cc
if(kind == Memory::SYSTEM_MEM) {
pma.bandwidth = 100; // "large"
pma.latency = 5; // "small"
} else {
pma.bandwidth = 80; // "large"
pma.latency = 10; // "small"
}
// FIXME: once the stuff in runtime_impl.cc is removed, remove
// this 'continue' so that we create affinities here
continue;
} else {
int d = numasysif_get_distance(cpu_node, mem_node);
if(d >= 0) {
pma.bandwidth = 150 - d;
pma.latency = d / 10; // Linux uses a cost of ~10/hop
} else {
// same as random sysmem
pma.bandwidth = 100;
pma.latency = 5;
}
}
runtime->add_proc_mem_affinity(pma);
}
}
}
}
// create any DMA channels provided by the module (default == do nothing)
void NumaModule::create_dma_channels(RuntimeImpl *runtime)
{
Module::create_dma_channels(runtime);
}
// create any code translators provided by the module (default == do nothing)
void NumaModule::create_code_translators(RuntimeImpl *runtime)
{
Module::create_code_translators(runtime);
}
// clean up any common resources created by the module - this will be called
// after all memories/processors/etc. have been shut down and destroyed
void NumaModule::cleanup(void)
{
Module::cleanup();
// free our allocations here
for(std::map<int, void *>::iterator it = numa_mem_bases.begin();
it != numa_mem_bases.end();
++it) {
size_t mem_size = numa_mem_sizes[it->first];
assert(mem_size > 0);
bool ok = numasysif_free_mem(it->first, it->second, mem_size);
if(!ok)
log_numa.error() << "failed to free memory in NUMA node " << it->first << ": ptr=" << it->second;
}
}
}; // namespace Numa
}; // namespace Realm
<|endoftext|> |
<commit_before>//===-- llvm/Target/TargetSchedule.cpp - Sched Machine Model ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a wrapper around MCSchedModel that allows the interface
// to benefit from information currently only available in TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
static cl::opt<bool> EnableSchedModel("schedmodel", cl::Hidden, cl::init(true),
cl::desc("Use TargetSchedModel for latency lookup"));
static cl::opt<bool> EnableSchedItins("scheditins", cl::Hidden, cl::init(true),
cl::desc("Use InstrItineraryData for latency lookup"));
bool TargetSchedModel::hasInstrSchedModel() const {
return EnableSchedModel && SchedModel.hasInstrSchedModel();
}
bool TargetSchedModel::hasInstrItineraries() const {
return EnableSchedItins && !InstrItins.isEmpty();
}
static unsigned gcd(unsigned Dividend, unsigned Divisor) {
// Dividend and Divisor will be naturally swapped as needed.
while(Divisor) {
unsigned Rem = Dividend % Divisor;
Dividend = Divisor;
Divisor = Rem;
};
return Dividend;
}
static unsigned lcm(unsigned A, unsigned B) {
unsigned LCM = (uint64_t(A) * B) / gcd(A, B);
assert((LCM >= A && LCM >= B) && "LCM overflow");
return LCM;
}
void TargetSchedModel::init(const MCSchedModel &sm,
const TargetSubtargetInfo *sti,
const TargetInstrInfo *tii) {
SchedModel = sm;
STI = sti;
TII = tii;
STI->initInstrItins(InstrItins);
unsigned NumRes = SchedModel.getNumProcResourceKinds();
ResourceFactors.resize(NumRes);
ResourceLCM = SchedModel.IssueWidth;
for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
if (NumUnits > 0)
ResourceLCM = lcm(ResourceLCM, NumUnits);
}
MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
}
}
unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI,
const MCSchedClassDesc *SC) const {
if (hasInstrItineraries()) {
int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, MI);
}
if (hasInstrSchedModel()) {
if (!SC)
SC = resolveSchedClass(MI);
if (SC->isValid())
return SC->NumMicroOps;
}
return MI->isTransient() ? 0 : 1;
}
// The machine model may explicitly specify an invalid latency, which
// effectively means infinite latency. Since users of the TargetSchedule API
// don't know how to handle this, we convert it to a very large latency that is
// easy to distinguish when debugging the DAG but won't induce overflow.
static unsigned convertLatency(int Cycles) {
return Cycles >= 0 ? Cycles : 1000;
}
/// If we can determine the operand latency from the def only, without machine
/// model or itinerary lookup, do so. Otherwise return -1.
int TargetSchedModel::getDefLatency(const MachineInstr *DefMI,
bool FindMin) const {
// Return a latency based on the itinerary properties and defining instruction
// if possible. Some common subtargets don't require per-operand latency,
// especially for minimum latencies.
if (FindMin) {
// If MinLatency is invalid, then use the itinerary for MinLatency. If no
// itinerary exists either, then use single cycle latency.
if (SchedModel.MinLatency < 0 && !hasInstrItineraries()) {
return 1;
}
return SchedModel.MinLatency;
}
else if (!hasInstrSchedModel() && !hasInstrItineraries()) {
return TII->defaultDefLatency(&SchedModel, DefMI);
}
// ...operand lookup required
return -1;
}
/// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
/// evaluation of predicates that depend on instruction operands or flags.
const MCSchedClassDesc *TargetSchedModel::
resolveSchedClass(const MachineInstr *MI) const {
// Get the definition's scheduling class descriptor from this machine model.
unsigned SchedClass = MI->getDesc().getSchedClass();
const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
#ifndef NDEBUG
unsigned NIter = 0;
#endif
while (SCDesc->isVariant()) {
assert(++NIter < 6 && "Variants are nested deeper than the magic number");
SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
SCDesc = SchedModel.getSchedClassDesc(SchedClass);
}
return SCDesc;
}
/// Find the def index of this operand. This index maps to the machine model and
/// is independent of use operands. Def operands may be reordered with uses or
/// merged with uses without affecting the def index (e.g. before/after
/// regalloc). However, an instruction's def operands must never be reordered
/// with respect to each other.
static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
unsigned DefIdx = 0;
for (unsigned i = 0; i != DefOperIdx; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef())
++DefIdx;
}
return DefIdx;
}
/// Find the use index of this operand. This is independent of the instruction's
/// def operands.
///
/// Note that uses are not determined by the operand's isUse property, which
/// is simply the inverse of isDef. Here we consider any readsReg operand to be
/// a "use". The machine model allows an operand to be both a Def and Use.
static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
unsigned UseIdx = 0;
for (unsigned i = 0; i != UseOperIdx; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.readsReg())
++UseIdx;
}
return UseIdx;
}
// Top-level API for clients that know the operand indices.
unsigned TargetSchedModel::computeOperandLatency(
const MachineInstr *DefMI, unsigned DefOperIdx,
const MachineInstr *UseMI, unsigned UseOperIdx,
bool FindMin) const {
int DefLatency = getDefLatency(DefMI, FindMin);
if (DefLatency >= 0)
return DefLatency;
if (hasInstrItineraries()) {
int OperLatency = 0;
if (UseMI) {
OperLatency =
TII->getOperandLatency(&InstrItins, DefMI, DefOperIdx, UseMI, UseOperIdx);
}
else {
unsigned DefClass = DefMI->getDesc().getSchedClass();
OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
}
if (OperLatency >= 0)
return OperLatency;
// No operand latency was found.
unsigned InstrLatency = TII->getInstrLatency(&InstrItins, DefMI);
// Expected latency is the max of the stage latency and itinerary props.
// Rather than directly querying InstrItins stage latency, we call a TII
// hook to allow subtargets to specialize latency. This hook is only
// applicable to the InstrItins model. InstrSchedModel should model all
// special cases without TII hooks.
if (!FindMin)
InstrLatency = std::max(InstrLatency,
TII->defaultDefLatency(&SchedModel, DefMI));
return InstrLatency;
}
assert(!FindMin && hasInstrSchedModel() &&
"Expected a SchedModel for this cpu");
const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
if (DefIdx < SCDesc->NumWriteLatencyEntries) {
// Lookup the definition's write latency in SubtargetInfo.
const MCWriteLatencyEntry *WLEntry =
STI->getWriteLatencyEntry(SCDesc, DefIdx);
unsigned WriteID = WLEntry->WriteResourceID;
unsigned Latency = convertLatency(WLEntry->Cycles);
if (!UseMI)
return Latency;
// Lookup the use's latency adjustment in SubtargetInfo.
const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
if (UseDesc->NumReadAdvanceEntries == 0)
return Latency;
unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
return Latency - STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
}
// If DefIdx does not exist in the model (e.g. implicit defs), then return
// unit latency (defaultDefLatency may be too conservative).
#ifndef NDEBUG
if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
&& !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()) {
std::string Err;
raw_string_ostream ss(Err);
ss << "DefIdx " << DefIdx << " exceeds machine model writes for "
<< *DefMI;
report_fatal_error(ss.str());
}
#endif
return DefMI->isTransient() ? 0 : 1;
}
unsigned TargetSchedModel::computeInstrLatency(const MachineInstr *MI) const {
// For the itinerary model, fall back to the old subtarget hook.
// Allow subtargets to compute Bundle latencies outside the machine model.
if (hasInstrItineraries() || MI->isBundle())
return TII->getInstrLatency(&InstrItins, MI);
if (hasInstrSchedModel()) {
const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
if (SCDesc->isValid()) {
unsigned Latency = 0;
for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
DefIdx != DefEnd; ++DefIdx) {
// Lookup the definition's write latency in SubtargetInfo.
const MCWriteLatencyEntry *WLEntry =
STI->getWriteLatencyEntry(SCDesc, DefIdx);
Latency = std::max(Latency, convertLatency(WLEntry->Cycles));
}
return Latency;
}
}
return TII->defaultDefLatency(&SchedModel, MI);
}
unsigned TargetSchedModel::
computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
const MachineInstr *DepMI) const {
// MinLatency == -1 is for in-order processors that always have unit
// MinLatency. MinLatency > 0 is for in-order processors with varying min
// latencies, but since this is not a RAW dep, we always use unit latency.
if (SchedModel.MinLatency != 0)
return 1;
// MinLatency == 0 indicates an out-of-order processor that can dispatch
// WAW dependencies in the same cycle.
// Treat predication as a data dependency for out-of-order cpus. In-order
// cpus do not need to treat predicated writes specially.
//
// TODO: The following hack exists because predication passes do not
// correctly append imp-use operands, and readsReg() strangely returns false
// for predicated defs.
unsigned Reg = DefMI->getOperand(DefOperIdx).getReg();
const MachineFunction &MF = *DefMI->getParent()->getParent();
const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(DepMI))
return computeInstrLatency(DefMI);
// If we have a per operand scheduling model, check if this def is writing
// an unbuffered resource. If so, it treated like an in-order cpu.
if (hasInstrSchedModel()) {
const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
if (SCDesc->isValid()) {
for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
*PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->IsBuffered)
return 1;
}
}
}
return 0;
}
<commit_msg>Change the default latency for implicit defs.<commit_after>//===-- llvm/Target/TargetSchedule.cpp - Sched Machine Model ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a wrapper around MCSchedModel that allows the interface
// to benefit from information currently only available in TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
static cl::opt<bool> EnableSchedModel("schedmodel", cl::Hidden, cl::init(true),
cl::desc("Use TargetSchedModel for latency lookup"));
static cl::opt<bool> EnableSchedItins("scheditins", cl::Hidden, cl::init(true),
cl::desc("Use InstrItineraryData for latency lookup"));
bool TargetSchedModel::hasInstrSchedModel() const {
return EnableSchedModel && SchedModel.hasInstrSchedModel();
}
bool TargetSchedModel::hasInstrItineraries() const {
return EnableSchedItins && !InstrItins.isEmpty();
}
static unsigned gcd(unsigned Dividend, unsigned Divisor) {
// Dividend and Divisor will be naturally swapped as needed.
while(Divisor) {
unsigned Rem = Dividend % Divisor;
Dividend = Divisor;
Divisor = Rem;
};
return Dividend;
}
static unsigned lcm(unsigned A, unsigned B) {
unsigned LCM = (uint64_t(A) * B) / gcd(A, B);
assert((LCM >= A && LCM >= B) && "LCM overflow");
return LCM;
}
void TargetSchedModel::init(const MCSchedModel &sm,
const TargetSubtargetInfo *sti,
const TargetInstrInfo *tii) {
SchedModel = sm;
STI = sti;
TII = tii;
STI->initInstrItins(InstrItins);
unsigned NumRes = SchedModel.getNumProcResourceKinds();
ResourceFactors.resize(NumRes);
ResourceLCM = SchedModel.IssueWidth;
for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
if (NumUnits > 0)
ResourceLCM = lcm(ResourceLCM, NumUnits);
}
MicroOpFactor = ResourceLCM / SchedModel.IssueWidth;
for (unsigned Idx = 0; Idx < NumRes; ++Idx) {
unsigned NumUnits = SchedModel.getProcResource(Idx)->NumUnits;
ResourceFactors[Idx] = NumUnits ? (ResourceLCM / NumUnits) : 0;
}
}
unsigned TargetSchedModel::getNumMicroOps(const MachineInstr *MI,
const MCSchedClassDesc *SC) const {
if (hasInstrItineraries()) {
int UOps = InstrItins.getNumMicroOps(MI->getDesc().getSchedClass());
return (UOps >= 0) ? UOps : TII->getNumMicroOps(&InstrItins, MI);
}
if (hasInstrSchedModel()) {
if (!SC)
SC = resolveSchedClass(MI);
if (SC->isValid())
return SC->NumMicroOps;
}
return MI->isTransient() ? 0 : 1;
}
// The machine model may explicitly specify an invalid latency, which
// effectively means infinite latency. Since users of the TargetSchedule API
// don't know how to handle this, we convert it to a very large latency that is
// easy to distinguish when debugging the DAG but won't induce overflow.
static unsigned convertLatency(int Cycles) {
return Cycles >= 0 ? Cycles : 1000;
}
/// If we can determine the operand latency from the def only, without machine
/// model or itinerary lookup, do so. Otherwise return -1.
int TargetSchedModel::getDefLatency(const MachineInstr *DefMI,
bool FindMin) const {
// Return a latency based on the itinerary properties and defining instruction
// if possible. Some common subtargets don't require per-operand latency,
// especially for minimum latencies.
if (FindMin) {
// If MinLatency is invalid, then use the itinerary for MinLatency. If no
// itinerary exists either, then use single cycle latency.
if (SchedModel.MinLatency < 0 && !hasInstrItineraries()) {
return 1;
}
return SchedModel.MinLatency;
}
else if (!hasInstrSchedModel() && !hasInstrItineraries()) {
return TII->defaultDefLatency(&SchedModel, DefMI);
}
// ...operand lookup required
return -1;
}
/// Return the MCSchedClassDesc for this instruction. Some SchedClasses require
/// evaluation of predicates that depend on instruction operands or flags.
const MCSchedClassDesc *TargetSchedModel::
resolveSchedClass(const MachineInstr *MI) const {
// Get the definition's scheduling class descriptor from this machine model.
unsigned SchedClass = MI->getDesc().getSchedClass();
const MCSchedClassDesc *SCDesc = SchedModel.getSchedClassDesc(SchedClass);
#ifndef NDEBUG
unsigned NIter = 0;
#endif
while (SCDesc->isVariant()) {
assert(++NIter < 6 && "Variants are nested deeper than the magic number");
SchedClass = STI->resolveSchedClass(SchedClass, MI, this);
SCDesc = SchedModel.getSchedClassDesc(SchedClass);
}
return SCDesc;
}
/// Find the def index of this operand. This index maps to the machine model and
/// is independent of use operands. Def operands may be reordered with uses or
/// merged with uses without affecting the def index (e.g. before/after
/// regalloc). However, an instruction's def operands must never be reordered
/// with respect to each other.
static unsigned findDefIdx(const MachineInstr *MI, unsigned DefOperIdx) {
unsigned DefIdx = 0;
for (unsigned i = 0; i != DefOperIdx; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.isDef())
++DefIdx;
}
return DefIdx;
}
/// Find the use index of this operand. This is independent of the instruction's
/// def operands.
///
/// Note that uses are not determined by the operand's isUse property, which
/// is simply the inverse of isDef. Here we consider any readsReg operand to be
/// a "use". The machine model allows an operand to be both a Def and Use.
static unsigned findUseIdx(const MachineInstr *MI, unsigned UseOperIdx) {
unsigned UseIdx = 0;
for (unsigned i = 0; i != UseOperIdx; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isReg() && MO.readsReg())
++UseIdx;
}
return UseIdx;
}
// Top-level API for clients that know the operand indices.
unsigned TargetSchedModel::computeOperandLatency(
const MachineInstr *DefMI, unsigned DefOperIdx,
const MachineInstr *UseMI, unsigned UseOperIdx,
bool FindMin) const {
int DefLatency = getDefLatency(DefMI, FindMin);
if (DefLatency >= 0)
return DefLatency;
if (hasInstrItineraries()) {
int OperLatency = 0;
if (UseMI) {
OperLatency =
TII->getOperandLatency(&InstrItins, DefMI, DefOperIdx, UseMI, UseOperIdx);
}
else {
unsigned DefClass = DefMI->getDesc().getSchedClass();
OperLatency = InstrItins.getOperandCycle(DefClass, DefOperIdx);
}
if (OperLatency >= 0)
return OperLatency;
// No operand latency was found.
unsigned InstrLatency = TII->getInstrLatency(&InstrItins, DefMI);
// Expected latency is the max of the stage latency and itinerary props.
// Rather than directly querying InstrItins stage latency, we call a TII
// hook to allow subtargets to specialize latency. This hook is only
// applicable to the InstrItins model. InstrSchedModel should model all
// special cases without TII hooks.
if (!FindMin)
InstrLatency = std::max(InstrLatency,
TII->defaultDefLatency(&SchedModel, DefMI));
return InstrLatency;
}
assert(!FindMin && hasInstrSchedModel() &&
"Expected a SchedModel for this cpu");
const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
unsigned DefIdx = findDefIdx(DefMI, DefOperIdx);
if (DefIdx < SCDesc->NumWriteLatencyEntries) {
// Lookup the definition's write latency in SubtargetInfo.
const MCWriteLatencyEntry *WLEntry =
STI->getWriteLatencyEntry(SCDesc, DefIdx);
unsigned WriteID = WLEntry->WriteResourceID;
unsigned Latency = convertLatency(WLEntry->Cycles);
if (!UseMI)
return Latency;
// Lookup the use's latency adjustment in SubtargetInfo.
const MCSchedClassDesc *UseDesc = resolveSchedClass(UseMI);
if (UseDesc->NumReadAdvanceEntries == 0)
return Latency;
unsigned UseIdx = findUseIdx(UseMI, UseOperIdx);
return Latency - STI->getReadAdvanceCycles(UseDesc, UseIdx, WriteID);
}
// If DefIdx does not exist in the model (e.g. implicit defs), then return
// unit latency (defaultDefLatency may be too conservative).
#ifndef NDEBUG
if (SCDesc->isValid() && !DefMI->getOperand(DefOperIdx).isImplicit()
&& !DefMI->getDesc().OpInfo[DefOperIdx].isOptionalDef()) {
std::string Err;
raw_string_ostream ss(Err);
ss << "DefIdx " << DefIdx << " exceeds machine model writes for "
<< *DefMI;
report_fatal_error(ss.str());
}
#endif
// FIXME: Automatically giving all implicit defs defaultDefLatency is
// undesirable. We should only do it for defs that are known to the MC
// desc like flags. Truly implicit defs should get 1 cycle latency.
return DefMI->isTransient() ? 0 : TII->defaultDefLatency(&SchedModel, DefMI);
}
unsigned TargetSchedModel::computeInstrLatency(const MachineInstr *MI) const {
// For the itinerary model, fall back to the old subtarget hook.
// Allow subtargets to compute Bundle latencies outside the machine model.
if (hasInstrItineraries() || MI->isBundle())
return TII->getInstrLatency(&InstrItins, MI);
if (hasInstrSchedModel()) {
const MCSchedClassDesc *SCDesc = resolveSchedClass(MI);
if (SCDesc->isValid()) {
unsigned Latency = 0;
for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
DefIdx != DefEnd; ++DefIdx) {
// Lookup the definition's write latency in SubtargetInfo.
const MCWriteLatencyEntry *WLEntry =
STI->getWriteLatencyEntry(SCDesc, DefIdx);
Latency = std::max(Latency, convertLatency(WLEntry->Cycles));
}
return Latency;
}
}
return TII->defaultDefLatency(&SchedModel, MI);
}
unsigned TargetSchedModel::
computeOutputLatency(const MachineInstr *DefMI, unsigned DefOperIdx,
const MachineInstr *DepMI) const {
// MinLatency == -1 is for in-order processors that always have unit
// MinLatency. MinLatency > 0 is for in-order processors with varying min
// latencies, but since this is not a RAW dep, we always use unit latency.
if (SchedModel.MinLatency != 0)
return 1;
// MinLatency == 0 indicates an out-of-order processor that can dispatch
// WAW dependencies in the same cycle.
// Treat predication as a data dependency for out-of-order cpus. In-order
// cpus do not need to treat predicated writes specially.
//
// TODO: The following hack exists because predication passes do not
// correctly append imp-use operands, and readsReg() strangely returns false
// for predicated defs.
unsigned Reg = DefMI->getOperand(DefOperIdx).getReg();
const MachineFunction &MF = *DefMI->getParent()->getParent();
const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
if (!DepMI->readsRegister(Reg, TRI) && TII->isPredicated(DepMI))
return computeInstrLatency(DefMI);
// If we have a per operand scheduling model, check if this def is writing
// an unbuffered resource. If so, it treated like an in-order cpu.
if (hasInstrSchedModel()) {
const MCSchedClassDesc *SCDesc = resolveSchedClass(DefMI);
if (SCDesc->isValid()) {
for (const MCWriteProcResEntry *PRI = STI->getWriteProcResBegin(SCDesc),
*PRE = STI->getWriteProcResEnd(SCDesc); PRI != PRE; ++PRI) {
if (!SchedModel.getProcResource(PRI->ProcResourceIdx)->IsBuffered)
return 1;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* <x0/plugins/status.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpHeader.h>
#include <x0/io/BufferSource.h>
#include <x0/TimeSpan.h>
#include <x0/strutils.h>
#include <x0/Types.h>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <cstring>
#include <cerrno>
#include <cstddef>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#define TRACE(msg...) DEBUG("status: " msg)
/**
* \ingroup plugins
* \brief example content generator plugin
*/
class StatusPlugin :
public x0::HttpPlugin
{
private:
std::list<x0::HttpConnection*> connections_;
public:
StatusPlugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
registerHandler<StatusPlugin, &StatusPlugin::handleRequest>("status");
}
private:
virtual bool handleRequest(x0::HttpRequest *r, const x0::FlowParams& args)
{
// set response status code
r->status = x0::HttpError::Ok;
r->responseHeaders.push_back("Content-Type", "text/html; charset=utf-8");
bool debug = true;
r->write<x0::BufferSource>(createResponseBody(debug));
r->finish();
return true;
}
// TODO let this method return a movable instead of a full copy
x0::Buffer createResponseBody(bool debug)
{
/*
* process uptime
* number of threads (total / active)
* cpu load (process / per worker)
* # requests
* # connections
* # requests since start
*/
x0::TimeSpan uptime(server().uptime());
std::size_t nconns = 0;
unsigned long long numTotalRequests = 0;
unsigned long long numTotalConns = 0;
double p1 = 0, p5 = 0, p15 = 0;
for (std::size_t i = 0, e = server().workers().size(); i != e; ++i) {
const x0::HttpWorker *w = server().workers()[i];
nconns += w->connectionLoad();
numTotalRequests += w->requestCount();
numTotalConns += w->connectionCount();
w->fetchPerformanceCounts(&p1, &p5, &p15);
}
x0::Buffer buf;
buf << "<html>";
buf << "<head><title>x0 status page</title>\n";
buf <<
"<style>"
"#conn-table {"
"border: 1px solid #ccc;"
"font-size: 11px;"
"}"
"#conn-table th {"
"border: 1px solid #ccc;"
"padding-left: 4px;"
"padding-right: 4px;"
"}"
"#conn-table td {"
"border: 1px solid #ccc;"
"padding-left: 4px;"
"padding-right: 4px;"
"white-space: nowrap;"
"}"
"td { vertical-align: top; }"
".cid { text-align: right; }"
".wid { text-align: right; }"
".ip { text-align: center; }"
".state { text-align: center; }"
".age { text-align: right; }"
".idle { text-align: right; }"
".read { text-align: right; }"
".written { text-align: right; }"
".host { text-align: left; }"
".method { text-align: center; }"
".uri { text-align: left; }"
".status { text-align: center; }"
".debug { text-align: left; }"
"</style>";
buf << "</head>";
buf << "<body>";
buf << "<h1>x0 status page</h1>\n";
buf << "<small><pre>" << server().tag() << "</pre></small>\n";
buf << "<pre>\n";
buf << "process uptime: " << uptime << "\n";
buf << "process generation: " << server().generation() << "\n";
buf << "average requests per second: ";
char tmp[80];
snprintf(tmp, sizeof(tmp), "%.2f, %.2f, %.2f", p1, p5, p15);
buf << ((char*)tmp) << "\n";
buf << "# workers: " << server().workers().size() << "\n";
buf << "# connections: " << nconns << "\n";
buf << "# total requests: " << numTotalRequests << "\n";
buf << "# total connections: " << numTotalConns << "\n";
buf << "</pre>\n";
buf << "<table border='0' cellspacing='0' cellpadding='0' id='conn-table'>\n";
buf << "<th>" << "cid" << "</th>";
buf << "<th>" << "wid" << "</th>";
buf << "<th>" << "IP" << "</th>";
buf << "<th>" << "state" << "</th>";
buf << "<th>" << "age" << "</th>";
buf << "<th>" << "idle" << "</th>";
buf << "<th>" << "read" << "</th>";
buf << "<th>" << "written" << "</th>";
buf << "<th>" << "host" << "</th>";
buf << "<th>" << "method" << "</th>";
buf << "<th>" << "uri" << "</th>";
buf << "<th>" << "status" << "</th>";
if (debug)
buf << "<th>" << "debug" << "</th>";
for (auto w: server().workers())
for (auto c: w->connections())
dump(buf, c, debug);
buf << "</table>\n";
buf << "</body></html>\n";
return buf;
}
void dump(x0::Buffer& out, x0::HttpConnection* c, bool debug)
{
out << "<tr>";
out << "<td class='cid'>" << c->id() << "</td>";
out << "<td class='wid'>" << c->worker().id() << "</td>";
out << "<td class='ip'>" << c->remoteIP() << "</td>";
out << "<td class='state'>" << c->status_str();
if (c->status() == x0::HttpConnection::ReadingRequest)
out << " (" << c->state_str() << ")";
out << "</td>";
out << "<td class='age'>" << (c->worker().now() - c->socket()->startedAt()).str() << "</td>";
out << "<td class='idle'>" << (c->worker().now() - c->socket()->lastActivityAt()).str() << "</td>";
out << "<td class='read'>" << c->inputOffset() << "/" << c->inputSize() << "</td>";
const x0::HttpRequest* r = c->request();
if (r && c->status() != x0::HttpConnection::KeepAliveRead) {
out << "<td class='written'>" << r->bytesTransmitted() << "</td>";
out << "<td class='host'>" << sanitize(r->hostname) << "</td>";
out << "<td class='method'>" << sanitize(r->method) << "</td>";
out << "<td class='uri'>" << sanitize(r->uri) << "</td>";
out << "<td class='status'>" << x0::make_error_code(r->status).message() << "</td>";
} else {
out << "<td colspan='5'>" << "</td>";
}
if (debug) {
static const char *outputStateStr[] = {
"unhandled",
"populating",
"finished",
};
out << "<td class='debug'>";
out << "refcount:" << c->refCount() << ", ";
out << "outputState:" << outputStateStr[c->request()->outputState()] << ", ";
c->socket()->inspect(out);
out << "</td>";
}
out << "</tr>\n";
}
template<typename T>
std::string sanitize(const T& value)
{
std::string out;
char buf[32];
for (auto i: value) {
switch (i) {
case '<':
case '>':
case '&':
snprintf(buf, sizeof(buf), "&#%d;", static_cast<unsigned>(i) & 0xFF);
out += buf;
break;
default:
out += i;
break;
}
}
return !out.empty() ? out : "(null)";
}
};
X0_EXPORT_PLUGIN_CLASS(StatusPlugin)
<commit_msg>[plugins] status: show request-custom inspect data<commit_after>/* <x0/plugins/status.cpp>
*
* This file is part of the x0 web server project and is released under LGPL-3.
* http://www.xzero.ws/
*
* (c) 2009-2010 Christian Parpart <trapni@gentoo.org>
*/
#include <x0/http/HttpPlugin.h>
#include <x0/http/HttpServer.h>
#include <x0/http/HttpRequest.h>
#include <x0/http/HttpConnection.h>
#include <x0/http/HttpHeader.h>
#include <x0/io/BufferSource.h>
#include <x0/TimeSpan.h>
#include <x0/strutils.h>
#include <x0/Types.h>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <cstring>
#include <cerrno>
#include <cstddef>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#define TRACE(msg...) DEBUG("status: " msg)
/**
* \ingroup plugins
* \brief example content generator plugin
*/
class StatusPlugin :
public x0::HttpPlugin
{
private:
std::list<x0::HttpConnection*> connections_;
public:
StatusPlugin(x0::HttpServer& srv, const std::string& name) :
x0::HttpPlugin(srv, name)
{
registerHandler<StatusPlugin, &StatusPlugin::handleRequest>("status");
}
private:
virtual bool handleRequest(x0::HttpRequest *r, const x0::FlowParams& args)
{
// set response status code
r->status = x0::HttpError::Ok;
r->responseHeaders.push_back("Content-Type", "text/html; charset=utf-8");
bool debug = true;
r->write<x0::BufferSource>(createResponseBody(debug));
r->finish();
return true;
}
// TODO let this method return a movable instead of a full copy
x0::Buffer createResponseBody(bool debug)
{
/*
* process uptime
* number of threads (total / active)
* cpu load (process / per worker)
* # requests
* # connections
* # requests since start
*/
x0::TimeSpan uptime(server().uptime());
std::size_t nconns = 0;
unsigned long long numTotalRequests = 0;
unsigned long long numTotalConns = 0;
double p1 = 0, p5 = 0, p15 = 0;
for (std::size_t i = 0, e = server().workers().size(); i != e; ++i) {
const x0::HttpWorker *w = server().workers()[i];
nconns += w->connectionLoad();
numTotalRequests += w->requestCount();
numTotalConns += w->connectionCount();
w->fetchPerformanceCounts(&p1, &p5, &p15);
}
x0::Buffer buf;
buf << "<html>";
buf << "<head><title>x0 status page</title>\n";
buf <<
"<style>"
"#conn-table {"
"border: 1px solid #ccc;"
"font-size: 11px;"
"}"
"#conn-table th {"
"border: 1px solid #ccc;"
"padding-left: 4px;"
"padding-right: 4px;"
"}"
"#conn-table td {"
"border: 1px solid #ccc;"
"padding-left: 4px;"
"padding-right: 4px;"
"white-space: nowrap;"
"}"
"td { vertical-align: top; }"
".cid { text-align: right; }"
".wid { text-align: right; }"
".ip { text-align: center; }"
".state { text-align: center; }"
".age { text-align: right; }"
".idle { text-align: right; }"
".read { text-align: right; }"
".written { text-align: right; }"
".host { text-align: left; }"
".method { text-align: center; }"
".uri { text-align: left; }"
".status { text-align: center; }"
".debug { text-align: left; }"
"</style>";
buf << "</head>";
buf << "<body>";
buf << "<h1>x0 status page</h1>\n";
buf << "<small><pre>" << server().tag() << "</pre></small>\n";
buf << "<pre>\n";
buf << "process uptime: " << uptime << "\n";
buf << "process generation: " << server().generation() << "\n";
buf << "average requests per second: ";
char tmp[80];
snprintf(tmp, sizeof(tmp), "%.2f, %.2f, %.2f", p1, p5, p15);
buf << ((char*)tmp) << "\n";
buf << "# workers: " << server().workers().size() << "\n";
buf << "# connections: " << nconns << "\n";
buf << "# total requests: " << numTotalRequests << "\n";
buf << "# total connections: " << numTotalConns << "\n";
buf << "</pre>\n";
buf << "<table border='0' cellspacing='0' cellpadding='0' id='conn-table'>\n";
buf << "<th>" << "cid" << "</th>";
buf << "<th>" << "wid" << "</th>";
buf << "<th>" << "IP" << "</th>";
buf << "<th>" << "state" << "</th>";
buf << "<th>" << "age" << "</th>";
buf << "<th>" << "idle" << "</th>";
buf << "<th>" << "read" << "</th>";
buf << "<th>" << "written" << "</th>";
buf << "<th>" << "host" << "</th>";
buf << "<th>" << "method" << "</th>";
buf << "<th>" << "uri" << "</th>";
buf << "<th>" << "status" << "</th>";
if (debug)
buf << "<th>" << "debug" << "</th>";
for (auto w: server().workers())
for (auto c: w->connections())
dump(buf, c, debug);
buf << "</table>\n";
buf << "</body></html>\n";
return buf;
}
void dump(x0::Buffer& out, x0::HttpConnection* c, bool debug)
{
out << "<tr>";
out << "<td class='cid'>" << c->id() << "</td>";
out << "<td class='wid'>" << c->worker().id() << "</td>";
out << "<td class='ip'>" << c->remoteIP() << "</td>";
out << "<td class='state'>" << c->status_str();
if (c->status() == x0::HttpConnection::ReadingRequest)
out << " (" << c->state_str() << ")";
out << "</td>";
out << "<td class='age'>" << (c->worker().now() - c->socket()->startedAt()).str() << "</td>";
out << "<td class='idle'>" << (c->worker().now() - c->socket()->lastActivityAt()).str() << "</td>";
out << "<td class='read'>" << c->inputOffset() << "/" << c->inputSize() << "</td>";
const x0::HttpRequest* r = c->request();
if (r && c->status() != x0::HttpConnection::KeepAliveRead) {
out << "<td class='written'>" << r->bytesTransmitted() << "</td>";
out << "<td class='host'>" << sanitize(r->hostname) << "</td>";
out << "<td class='method'>" << sanitize(r->method) << "</td>";
out << "<td class='uri'>" << sanitize(r->uri) << "</td>";
out << "<td class='status'>" << x0::make_error_code(r->status).message() << "</td>";
} else {
out << "<td colspan='5'>" << "</td>";
}
if (debug) {
static const char *outputStateStr[] = {
"unhandled",
"populating",
"finished",
};
out << "<td class='debug'>";
out << "refcount:" << c->refCount() << ", ";
out << "outputState:" << outputStateStr[c->request()->outputState()] << ", ";
c->socket()->inspect(out);
if (c->request()) {
c->request()->inspect(out);
}
out << "</td>";
}
out << "</tr>\n";
}
template<typename T>
std::string sanitize(const T& value)
{
std::string out;
char buf[32];
for (auto i: value) {
switch (i) {
case '<':
case '>':
case '&':
snprintf(buf, sizeof(buf), "&#%d;", static_cast<unsigned>(i) & 0xFF);
out += buf;
break;
default:
out += i;
break;
}
}
return !out.empty() ? out : "(null)";
}
};
X0_EXPORT_PLUGIN_CLASS(StatusPlugin)
<|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/views/controls/button/native_button.h"
#include "base/logging.h"
#include "chrome/common/l10n_util.h"
namespace views {
static int kButtonBorderHWidth = 8;
// static
const char NativeButton::kViewClassName[] = "chrome/views/NativeButton";
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:
NativeButton::NativeButton(ButtonListener* listener)
: Button(listener),
native_wrapper_(NULL),
is_default_(false),
ignore_minimum_size_(false),
minimum_size_(50, 14) {
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
InitBorder();
SetFocusable(true);
}
NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
: Button(listener),
native_wrapper_(NULL),
label_(label),
is_default_(false),
ignore_minimum_size_(false),
minimum_size_(50, 14) {
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
InitBorder();
SetFocusable(true);
}
NativeButton::~NativeButton() {
}
void NativeButton::SetLabel(const std::wstring& label) {
label_ = label;
// Even though we create a flipped HWND for a native button when the locale
// is right-to-left, Windows does not render text for the button using a
// right-to-left context (perhaps because the parent HWND is not flipped).
// The result is that RTL strings containing punctuation marks are not
// displayed properly. For example, the string "...ABC" (where A, B and C are
// Hebrew characters) is displayed as "ABC..." which is incorrect.
//
// In order to overcome this problem, we mark the localized Hebrew strings as
// RTL strings explicitly (using the appropriate Unicode formatting) so that
// Windows displays the text correctly regardless of the HWND hierarchy.
std::wstring localized_label;
if (l10n_util::AdjustStringForLocaleDirection(label_, &localized_label))
label_ = localized_label;
if (native_wrapper_)
native_wrapper_->UpdateLabel();
}
void NativeButton::SetIsDefault(bool is_default) {
if (is_default == is_default_)
return;
is_default_ = is_default;
if (native_wrapper_)
native_wrapper_->UpdateDefault();
}
void NativeButton::ButtonPressed() {
RequestFocus();
// TODO(beng): obtain mouse event flags for native buttons someday.
NotifyClick(mouse_event_flags());
}
////////////////////////////////////////////////////////////////////////////////
// NativeButton, View overrides:
gfx::Size NativeButton::GetPreferredSize() {
gfx::Size sz = native_wrapper_->GetView()->GetPreferredSize();
// Add in the border size. (Do this before clamping the minimum size in case
// that clamping causes an increase in size that would include the borders.
gfx::Insets border = GetInsets();
sz.set_width(sz.width() + border.left() + border.right());
sz.set_height(sz.height() + border.top() + border.bottom());
// Clamp the size returned to at least the minimum size.
if (!ignore_minimum_size_) {
if (minimum_size_.width()) {
int min_width = font_.horizontal_dlus_to_pixels(minimum_size_.width());
sz.set_width(std::max(static_cast<int>(sz.width()), min_width));
}
if (minimum_size_.height()) {
int min_height = font_.vertical_dlus_to_pixels(minimum_size_.height());
sz.set_height(std::max(static_cast<int>(sz.height()), min_height));
}
}
return sz;
}
void NativeButton::Layout() {
if (native_wrapper_) {
native_wrapper_->GetView()->SetBounds(0, 0, width(), height());
native_wrapper_->GetView()->Layout();
}
}
void NativeButton::ViewHierarchyChanged(bool is_add, View* parent,
View* child) {
if (is_add && !native_wrapper_ && GetWidget()) {
CreateWrapper();
AddChildView(native_wrapper_->GetView());
}
}
std::string NativeButton::GetClassName() const {
return kViewClassName;
}
bool NativeButton::AcceleratorPressed(const Accelerator& accelerator) {
if (IsEnabled()) {
NotifyClick(mouse_event_flags());
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NativeButton, protected:
void NativeButton::CreateWrapper() {
native_wrapper_ = NativeButtonWrapper::CreateNativeButtonWrapper(this);
native_wrapper_->UpdateLabel();
}
void NativeButton::InitBorder() {
set_border(Border::CreateEmptyBorder(0, kButtonBorderHWidth, 0,
kButtonBorderHWidth));
}
} // namespace views
<commit_msg>Fix UI test: NULL check the wrapper since this can be called when we're not in a view hierarchy.<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/views/controls/button/native_button.h"
#include "base/logging.h"
#include "chrome/common/l10n_util.h"
namespace views {
static int kButtonBorderHWidth = 8;
// static
const char NativeButton::kViewClassName[] = "chrome/views/NativeButton";
////////////////////////////////////////////////////////////////////////////////
// NativeButton, public:
NativeButton::NativeButton(ButtonListener* listener)
: Button(listener),
native_wrapper_(NULL),
is_default_(false),
ignore_minimum_size_(false),
minimum_size_(50, 14) {
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
InitBorder();
SetFocusable(true);
}
NativeButton::NativeButton(ButtonListener* listener, const std::wstring& label)
: Button(listener),
native_wrapper_(NULL),
label_(label),
is_default_(false),
ignore_minimum_size_(false),
minimum_size_(50, 14) {
// The min size in DLUs comes from
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwue/html/ch14e.asp
InitBorder();
SetFocusable(true);
}
NativeButton::~NativeButton() {
}
void NativeButton::SetLabel(const std::wstring& label) {
label_ = label;
// Even though we create a flipped HWND for a native button when the locale
// is right-to-left, Windows does not render text for the button using a
// right-to-left context (perhaps because the parent HWND is not flipped).
// The result is that RTL strings containing punctuation marks are not
// displayed properly. For example, the string "...ABC" (where A, B and C are
// Hebrew characters) is displayed as "ABC..." which is incorrect.
//
// In order to overcome this problem, we mark the localized Hebrew strings as
// RTL strings explicitly (using the appropriate Unicode formatting) so that
// Windows displays the text correctly regardless of the HWND hierarchy.
std::wstring localized_label;
if (l10n_util::AdjustStringForLocaleDirection(label_, &localized_label))
label_ = localized_label;
if (native_wrapper_)
native_wrapper_->UpdateLabel();
}
void NativeButton::SetIsDefault(bool is_default) {
if (is_default == is_default_)
return;
is_default_ = is_default;
if (native_wrapper_)
native_wrapper_->UpdateDefault();
}
void NativeButton::ButtonPressed() {
RequestFocus();
// TODO(beng): obtain mouse event flags for native buttons someday.
NotifyClick(mouse_event_flags());
}
////////////////////////////////////////////////////////////////////////////////
// NativeButton, View overrides:
gfx::Size NativeButton::GetPreferredSize() {
if (!native_wrapper_)
return gfx::Size();
gfx::Size sz = native_wrapper_->GetView()->GetPreferredSize();
// Add in the border size. (Do this before clamping the minimum size in case
// that clamping causes an increase in size that would include the borders.
gfx::Insets border = GetInsets();
sz.set_width(sz.width() + border.left() + border.right());
sz.set_height(sz.height() + border.top() + border.bottom());
// Clamp the size returned to at least the minimum size.
if (!ignore_minimum_size_) {
if (minimum_size_.width()) {
int min_width = font_.horizontal_dlus_to_pixels(minimum_size_.width());
sz.set_width(std::max(static_cast<int>(sz.width()), min_width));
}
if (minimum_size_.height()) {
int min_height = font_.vertical_dlus_to_pixels(minimum_size_.height());
sz.set_height(std::max(static_cast<int>(sz.height()), min_height));
}
}
return sz;
}
void NativeButton::Layout() {
if (native_wrapper_) {
native_wrapper_->GetView()->SetBounds(0, 0, width(), height());
native_wrapper_->GetView()->Layout();
}
}
void NativeButton::ViewHierarchyChanged(bool is_add, View* parent,
View* child) {
if (is_add && !native_wrapper_ && GetWidget()) {
CreateWrapper();
AddChildView(native_wrapper_->GetView());
}
}
std::string NativeButton::GetClassName() const {
return kViewClassName;
}
bool NativeButton::AcceleratorPressed(const Accelerator& accelerator) {
if (IsEnabled()) {
NotifyClick(mouse_event_flags());
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// NativeButton, protected:
void NativeButton::CreateWrapper() {
native_wrapper_ = NativeButtonWrapper::CreateNativeButtonWrapper(this);
native_wrapper_->UpdateLabel();
}
void NativeButton::InitBorder() {
set_border(Border::CreateEmptyBorder(0, kButtonBorderHWidth, 0,
kButtonBorderHWidth));
}
} // namespace views
<|endoftext|> |
<commit_before>#define DEBUG_TYPE "dyn-aa"
#include <cstdio>
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "rcs/IDAssigner.h"
#include "dyn-aa/DynamicAliasAnalysis.h"
#include "dyn-aa/Utils.h"
using namespace std;
using namespace llvm;
using namespace rcs;
using namespace neongoby;
static RegisterPass<DynamicAliasAnalysis> X("dyn-aa",
"Accurate alias analysis "
"according to the point-to log",
false, // Is CFG Only?
true); // Is Analysis?
// Don't register to AliasAnalysis group. It would confuse CallGraphChecker
// to use DynamicAliasAnalysis as the underlying AA to generate the call
// graph.
// static RegisterAnalysisGroup<AliasAnalysis> Y(X);
static cl::opt<string> OutputDynamicAliases(
"output-ng",
cl::desc("Dump all dynamic aliases"));
STATISTIC(NumRemoveOps, "Number of remove operations");
STATISTIC(NumInsertOps, "Number of insert operations");
STATISTIC(MaxNumPointersToSameLocation,
"Maximum number of pointers to the same location. "
"Used for analyzing time complexity");
char DynamicAliasAnalysis::ID = 0;
const unsigned DynamicAliasAnalysis::UnknownVersion = (unsigned)-1;
bool DynamicAliasAnalysis::runOnModule(Module &M) {
// We needn't chain DynamicAliasAnalysis to the AA chain
// InitializeAliasAnalysis(this);
IDAssigner &IDA = getAnalysis<IDAssigner>();
processLog();
errs() << "# of aliases = " << Aliases.size() << "\n";
if (OutputDynamicAliases != "") {
string ErrorInfo;
raw_fd_ostream OutputFile(OutputDynamicAliases.c_str(), ErrorInfo);
for (auto &Alias : Aliases) {
Value *V1 = Alias.first, *V2 = Alias.second;
OutputFile << IDA.getValueID(V1) << " " << IDA.getValueID(V2) << "\n";
}
}
#if 0
errs() << PointersVersionUnknown.size()
<< " pointers whose version is unknown:\n";
for (auto &Pointer : PointersVersionUnknown) {
IDA.printValue(errs(), Pointer);
errs() << "\n";
}
#endif
return false;
}
void DynamicAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
// TODO: Do we need this? since DynamicAliasAnalysis is not in the AA chain
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll();
AU.addRequired<IDAssigner>();
}
void DynamicAliasAnalysis::updateVersion(void *Start,
unsigned long Bound,
unsigned Version) {
Interval I((unsigned long)Start, (unsigned long)Start + Bound);
auto ER = AddressVersion.equal_range(I);
AddressVersion.erase(ER.first, ER.second);
AddressVersion.insert(make_pair(I, Version));
assert(lookupAddress(Start) == Version);
}
void DynamicAliasAnalysis::initialize() {
AddressVersion.clear();
CurrentVersion = 0;
PointedBy.clear();
PointsTo.clear();
// Do not clear Aliases, PointersVersionUnknown, and AddressVersionUnknown.
NumInvocations = 0;
// std::stack doesn't have clear().
while (!CallStack.empty())
CallStack.pop();
ActivePointers.clear();
OutdatedContexts.clear();
}
void DynamicAliasAnalysis::processMemAlloc(const MemAllocRecord &Record) {
updateVersion(Record.Address, Record.Bound, CurrentVersion);
++CurrentVersion;
// Check for numeric overflow.
assert(CurrentVersion != UnknownVersion);
}
void DynamicAliasAnalysis::processEnter(const EnterRecord &Record) {
auto I = OutdatedContexts.find(Record.FunctionID);
if (I != OutdatedContexts.end()) {
for (auto &OutdatedContext : I->second)
removePointsTo(OutdatedContext);
OutdatedContexts.erase(I);
}
++NumInvocations;
CallStack.push(NumInvocations);
}
void DynamicAliasAnalysis::processReturn(const ReturnRecord &Record) {
assert(!CallStack.empty());
OutdatedContexts[Record.FunctionID].insert(CallStack.top());
CallStack.pop();
}
void DynamicAliasAnalysis::processTopLevel(const TopLevelRecord &Record) {
unsigned PointerVID = Record.PointerValueID;
void *PointeeAddress = Record.PointeeAddress;
// We don't consider NULLs as aliases.
if (PointeeAddress != NULL) {
unsigned Version = lookupAddress(PointeeAddress);
// Report the pointers pointing to unversioned address.
if (Version == UnknownVersion) {
if (!AddressesVersionUnknown.count(PointeeAddress)) {
AddressesVersionUnknown.insert(PointeeAddress);
#if 0
errs() << "Unknown version: " << PointerVID << " => "
<< PointeeAddress << "\n";
#endif
IDAssigner &IDA = getAnalysis<IDAssigner>();
PointersVersionUnknown.insert(IDA.getValue(PointerVID));
}
}
// Global variables are processed before any invocation.
Definition Ptr(PointerVID, CallStack.empty() ? 0 : CallStack.top());
Location Loc(PointeeAddress, Version);
addPointsTo(Ptr, Loc);
// Report aliases.
auto I = PointedBy.find(Loc);
assert(I != PointedBy.end()); // We just added a point-to in.
if (Version != UnknownVersion &&
I->second.size() > MaxNumPointersToSameLocation) {
MaxNumPointersToSameLocation = I->second.size();
}
addAliasPairs(Ptr, I->second);
} // if (PointerAddress != NULL)
}
void DynamicAliasAnalysis::removePointedBy(Definition Ptr, Location Loc) {
auto J = PointedBy.find(Loc);
assert(J != PointedBy.end());
J->second.erase(Ptr);
}
void DynamicAliasAnalysis::removePointsTo(Definition Ptr) {
auto I = PointsTo.find(Ptr);
if (I != PointsTo.end()) {
++NumRemoveOps;
removePointedBy(I->first, I->second);
PointsTo.erase(I);
}
}
void DynamicAliasAnalysis::removePointsTo(unsigned InvocationID) {
auto I = ActivePointers.find(InvocationID);
if (I != ActivePointers.end()) {
for (auto &PointerID : I->second)
removePointsTo(Definition(PointerID, InvocationID));
ActivePointers.erase(I);
}
}
void DynamicAliasAnalysis::addPointsTo(Definition Ptr, Location Loc) {
++NumInsertOps;
removePointsTo(Ptr);
PointsTo[Ptr] = Loc;
PointedBy[Loc].insert(Ptr);
ActivePointers[Ptr.second].push_back(Ptr.first);
}
unsigned DynamicAliasAnalysis::lookupAddress(void *Addr) const {
Interval I((unsigned long)Addr, (unsigned long)Addr + 1);
auto Pos = AddressVersion.find(I);
if (Pos == AddressVersion.end())
return UnknownVersion;
return Pos->second;
}
void *DynamicAliasAnalysis::getAdjustedAnalysisPointer(AnalysisID PI) {
if (PI == &AliasAnalysis::ID)
return (AliasAnalysis *)this;
return this;
}
AliasAnalysis::AliasResult DynamicAliasAnalysis::alias(
const AliasAnalysis::Location &L1,
const AliasAnalysis::Location &L2) {
Value *V1 = const_cast<Value *>(L1.Ptr);
Value *V2 = const_cast<Value *>(L2.Ptr);
if (V1 > V2)
swap(V1, V2);
if (Aliases.count(make_pair(V1, V2)))
return MayAlias;
return NoAlias;
}
void DynamicAliasAnalysis::addAliasPair(Value *V1, Value *V2) {
assert(V1 && V2);
if (V1 > V2)
swap(V1, V2);
Aliases.insert(make_pair(V1, V2));
}
void DynamicAliasAnalysis::addAliasPair(Definition P, Definition Q) {
assert(P.first != IDAssigner::InvalidID &&
Q.first != IDAssigner::InvalidID);
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *U = IDA.getValue(P.first), *V = IDA.getValue(Q.first);
const Function *F = DynAAUtils::GetContainingFunction(U);
const Function *G = DynAAUtils::GetContainingFunction(V);
if (F == G && P.second != Q.second)
return;
addAliasPair(U, V);
}
void DynamicAliasAnalysis::addAliasPairs(Definition P,
const DenseSet<Definition> &Qs) {
for (auto &Q : Qs)
addAliasPair(P, Q);
}
<commit_msg>Update DynamicAliasAnalysis.cpp<commit_after>#define DEBUG_TYPE "dyn-aa"
#include <cstdio>
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "rcs/IDAssigner.h"
#include "dyn-aa/DynamicAliasAnalysis.h"
#include "dyn-aa/Utils.h"
using namespace std;
using namespace llvm;
using namespace rcs;
using namespace neongoby;
static RegisterPass<DynamicAliasAnalysis> X("dyn-aa",
"Accurate alias analysis "
"according to the point-to log",
false, // Is CFG Only?
true); // Is Analysis?
// Don't register to AliasAnalysis group. It would confuse CallGraphChecker
// to use DynamicAliasAnalysis as the underlying AA to generate the call
// graph.
// static RegisterAnalysisGroup<AliasAnalysis> Y(X);
static cl::opt<string> OutputDynamicAliases(
"output-ng",
cl::desc("Dump all dynamic aliases"));
STATISTIC(NumRemoveOps, "Number of remove operations");
STATISTIC(NumInsertOps, "Number of insert operations");
STATISTIC(MaxNumPointersToSameLocation,
"Maximum number of pointers to the same location. "
"Used for analyzing time complexity");
char DynamicAliasAnalysis::ID = 0;
const unsigned DynamicAliasAnalysis::UnknownVersion = (unsigned)-1;
bool DynamicAliasAnalysis::runOnModule(Module &M) {
// We needn't chain DynamicAliasAnalysis to the AA chain
// InitializeAliasAnalysis(this);
IDAssigner &IDA = getAnalysis<IDAssigner>();
processLog();
errs() << "# of aliases = " << Aliases.size() << "\n";
if (OutputDynamicAliases != "") {
string ErrorInfo;
raw_fd_ostream OutputFile(OutputDynamicAliases.c_str(), ErrorInfo);
for (auto &Alias : Aliases) {
Value *V1 = Alias.first, *V2 = Alias.second;
OutputFile << IDA.getValueID(V1) << " " << IDA.getValueID(V2) << "\n";
}
}
#if 0
errs() << PointersVersionUnknown.size()
<< " pointers whose version is unknown:\n";
for (auto &Pointer : PointersVersionUnknown) {
IDA.printValue(errs(), Pointer);
errs() << "\n";
}
#endif
return false;
}
void DynamicAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
// TODO: Do we need this? since DynamicAliasAnalysis is not in the AA chain
AliasAnalysis::getAnalysisUsage(AU);
AU.setPreservesAll();
AU.addRequired<IDAssigner>();
}
void DynamicAliasAnalysis::updateVersion(void *Start,
unsigned long Bound,
unsigned Version) {
Interval I((unsigned long)Start, (unsigned long)Start + Bound);
auto ER = AddressVersion.equal_range(I);
AddressVersion.erase(ER.first, ER.second);
AddressVersion.insert(make_pair(I, Version));
assert(lookupAddress(Start) == Version);
}
void DynamicAliasAnalysis::initialize() {
AddressVersion.clear();
CurrentVersion = 0;
PointedBy.clear();
PointsTo.clear();
// Do not clear Aliases, PointersVersionUnknown, and AddressVersionUnknown.
NumInvocations = 0;
// std::stack doesn't have clear().
while (!CallStack.empty())
CallStack.pop();
ActivePointers.clear();
OutdatedContexts.clear();
}
void DynamicAliasAnalysis::processMemAlloc(const MemAllocRecord &Record) {
updateVersion(Record.Address, Record.Bound, CurrentVersion);
++CurrentVersion;
// Check for numeric overflow.
assert(CurrentVersion != UnknownVersion);
}
void DynamicAliasAnalysis::processEnter(const EnterRecord &Record) {
auto I = OutdatedContexts.find(Record.FunctionID);
if (I != OutdatedContexts.end()) {
for (auto &OutdatedContext : I->second)
removePointsTo(OutdatedContext);
OutdatedContexts.erase(I);
}
++NumInvocations;
CallStack.push(NumInvocations);
}
void DynamicAliasAnalysis::processReturn(const ReturnRecord &Record) {
assert(!CallStack.empty());
OutdatedContexts[Record.FunctionID].insert(CallStack.top());
CallStack.pop();
}
void DynamicAliasAnalysis::processTopLevel(const TopLevelRecord &Record) {
unsigned PointerVID = Record.PointerValueID;
void *PointeeAddress = Record.PointeeAddress;
// We don't consider NULLs as aliases.
if (PointeeAddress != NULL) {
unsigned Version = lookupAddress(PointeeAddress);
// Report the pointers pointing to unversioned address.
if (Version == UnknownVersion) {
if (!AddressesVersionUnknown.count(PointeeAddress)) {
AddressesVersionUnknown.insert(PointeeAddress);
#if 0
errs() << "Unknown version: " << PointerVID << " => "
<< PointeeAddress << "\n";
#endif
IDAssigner &IDA = getAnalysis<IDAssigner>();
PointersVersionUnknown.insert(IDA.getValue(PointerVID));
}
}
// Global variables are processed before any invocation.
Definition Ptr(PointerVID, CallStack.empty() ? 0 : CallStack.top());
Location Loc(PointeeAddress, Version);
addPointsTo(Ptr, Loc);
// Report aliases.
auto I = PointedBy.find(Loc);
assert(I != PointedBy.end()); // We just added a point-to in.
if (Version != UnknownVersion &&
I->second.size() > MaxNumPointersToSameLocation) {
MaxNumPointersToSameLocation = I->second.size();
}
addAliasPairs(Ptr, I->second);
} // if (PointerAddress != NULL)
}
void DynamicAliasAnalysis::removePointedBy(Definition Ptr, Location Loc) {
auto J = PointedBy.find(Loc);
assert(J != PointedBy.end());
J->second.erase(Ptr);
/*Do not keep those Location entry which does not map to any Defintion set*/
if(0 == J->second.size()) {
PointedBy.erase(J);
}
}
void DynamicAliasAnalysis::removePointsTo(Definition Ptr) {
auto I = PointsTo.find(Ptr);
if (I != PointsTo.end()) {
++NumRemoveOps;
removePointedBy(I->first, I->second);
PointsTo.erase(I);
}
}
void DynamicAliasAnalysis::removePointsTo(unsigned InvocationID) {
auto I = ActivePointers.find(InvocationID);
if (I != ActivePointers.end()) {
for (auto &PointerID : I->second)
removePointsTo(Definition(PointerID, InvocationID));
ActivePointers.erase(I);
}
}
void DynamicAliasAnalysis::addPointsTo(Definition Ptr, Location Loc) {
++NumInsertOps;
removePointsTo(Ptr);
PointsTo[Ptr] = Loc;
PointedBy[Loc].insert(Ptr);
ActivePointers[Ptr.second].push_back(Ptr.first);
}
unsigned DynamicAliasAnalysis::lookupAddress(void *Addr) const {
Interval I((unsigned long)Addr, (unsigned long)Addr + 1);
auto Pos = AddressVersion.find(I);
if (Pos == AddressVersion.end())
return UnknownVersion;
return Pos->second;
}
void *DynamicAliasAnalysis::getAdjustedAnalysisPointer(AnalysisID PI) {
if (PI == &AliasAnalysis::ID)
return (AliasAnalysis *)this;
return this;
}
AliasAnalysis::AliasResult DynamicAliasAnalysis::alias(
const AliasAnalysis::Location &L1,
const AliasAnalysis::Location &L2) {
Value *V1 = const_cast<Value *>(L1.Ptr);
Value *V2 = const_cast<Value *>(L2.Ptr);
if (V1 > V2)
swap(V1, V2);
if (Aliases.count(make_pair(V1, V2)))
return MayAlias;
return NoAlias;
}
void DynamicAliasAnalysis::addAliasPair(Value *V1, Value *V2) {
assert(V1 && V2);
if (V1 > V2)
swap(V1, V2);
Aliases.insert(make_pair(V1, V2));
}
void DynamicAliasAnalysis::addAliasPair(Definition P, Definition Q) {
assert(P.first != IDAssigner::InvalidID &&
Q.first != IDAssigner::InvalidID);
IDAssigner &IDA = getAnalysis<IDAssigner>();
Value *U = IDA.getValue(P.first), *V = IDA.getValue(Q.first);
const Function *F = DynAAUtils::GetContainingFunction(U);
const Function *G = DynAAUtils::GetContainingFunction(V);
if (F == G && P.second != Q.second)
return;
addAliasPair(U, V);
}
void DynamicAliasAnalysis::addAliasPairs(Definition P,
const DenseSet<Definition> &Qs) {
for (auto &Q : Qs)
addAliasPair(P, Q);
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOgreRenderer.cpp
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "CEGUIOgreRenderer.h"
#include "CEGUIOgreGeometryBuffer.h"
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include "CEGUIOgreWindowTarget.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIOgreResourceProvider.h"
#include "CEGUIOgreImageCodec.h"
#include <OgreRoot.h>
#include <OgreRenderSystem.h>
#include <OgreRenderWindow.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal Ogre::FrameListener based class. This is how we noew hook into the
// rendering process (as opposed to render queues previously)
static class OgreGUIFrameListener : public Ogre::FrameListener
{
public:
OgreGUIFrameListener();
void setCEGUIRenderEnabled(bool enabled);
bool isCEGUIRenderEnabled() const;
bool frameRenderingQueued(const Ogre::FrameEvent& evt);
private:
bool d_enabled;
} S_frameListener;
//----------------------------------------------------------------------------//
String OgreRenderer::d_rendererID(
"CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module.");
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem()
{
if (System::getSingletonPtr())
throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
"CEGUI::System object is already initialised.");
OgreRenderer& renderer = create();
OgreResourceProvider& rp = createOgreResourceProvider();
OgreImageCodec& ic = createOgreImageCodec();
System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);
return renderer;
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target)
{
if (System::getSingletonPtr())
throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
"CEGUI::System object is already initialised.");
OgreRenderer& renderer = OgreRenderer::create(target);
OgreResourceProvider& rp = createOgreResourceProvider();
OgreImageCodec& ic = createOgreImageCodec();
System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);
return renderer;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroySystem()
{
System* sys;
if (!(sys = System::getSingletonPtr()))
throw InvalidRequestException("OgreRenderer::destroySystem: "
"CEGUI::System object is not created or was already destroyed.");
OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer());
OgreResourceProvider* rp =
static_cast<OgreResourceProvider*>(sys->getResourceProvider());
OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec());
System::destroy();
destroyOgreImageCodec(*ic);
destroyOgreResourceProvider(*rp);
destroy(*renderer);
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create()
{
return *new OgreRenderer;
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target)
{
return *new OgreRenderer(target);
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroy(OgreRenderer& renderer)
{
delete &renderer;
}
//----------------------------------------------------------------------------//
OgreResourceProvider& OgreRenderer::createOgreResourceProvider()
{
return *new OgreResourceProvider;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp)
{
delete &rp;
}
//----------------------------------------------------------------------------//
OgreImageCodec& OgreRenderer::createOgreImageCodec()
{
return *new OgreImageCodec;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic)
{
delete ⁣
}
//----------------------------------------------------------------------------//
void OgreRenderer::setRenderingEnabled(const bool enabled)
{
S_frameListener.setCEGUIRenderEnabled(enabled);
}
//----------------------------------------------------------------------------//
bool OgreRenderer::isRenderingEnabled() const
{
return S_frameListener.isCEGUIRenderEnabled();
}
//----------------------------------------------------------------------------//
RenderingRoot& OgreRenderer::getDefaultRenderingRoot()
{
return *d_defaultRoot;
}
//----------------------------------------------------------------------------//
GeometryBuffer& OgreRenderer::createGeometryBuffer()
{
OgreGeometryBuffer* gb =
new OgreGeometryBuffer(*this, *d_renderSystem);
d_geometryBuffers.push_back(gb);
return *gb;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
d_geometryBuffers.end(),
&buffer);
if (d_geometryBuffers.end() != i)
{
d_geometryBuffers.erase(i);
delete &buffer;
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllGeometryBuffers()
{
while (!d_geometryBuffers.empty())
destroyGeometryBuffer(**d_geometryBuffers.begin());
}
//----------------------------------------------------------------------------//
TextureTarget* OgreRenderer::createTextureTarget()
{
TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem);
d_textureTargets.push_back(tt);
return tt;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyTextureTarget(TextureTarget* target)
{
TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
d_textureTargets.end(),
target);
if (d_textureTargets.end() != i)
{
d_textureTargets.erase(i);
delete target;
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextureTargets()
{
while (!d_textureTargets.empty())
destroyTextureTarget(*d_textureTargets.begin());
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture()
{
OgreTexture* t = new OgreTexture;
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const String& filename,
const String& resourceGroup)
{
OgreTexture* t = new OgreTexture(filename, resourceGroup);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const Size& size)
{
OgreTexture* t = new OgreTexture(size);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership)
{
OgreTexture* t = new OgreTexture(tex, take_ownership);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyTexture(Texture& texture)
{
TextureList::iterator i = std::find(d_textures.begin(),
d_textures.end(),
&texture);
if (d_textures.end() != i)
{
d_textures.erase(i);
delete &static_cast<OgreTexture&>(texture);
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextures()
{
while (!d_textures.empty())
destroyTexture(**d_textures.begin());
}
//----------------------------------------------------------------------------//
void OgreRenderer::beginRendering()
{
initialiseRenderStateSettings();
if (d_makeFrameControlCalls)
d_renderSystem->_beginFrame();
}
//----------------------------------------------------------------------------//
void OgreRenderer::endRendering()
{
if (d_makeFrameControlCalls)
d_renderSystem->_endFrame();
}
//----------------------------------------------------------------------------//
const Size& OgreRenderer::getDisplaySize() const
{
return d_displaySize;
}
//----------------------------------------------------------------------------//
const Vector2& OgreRenderer::getDisplayDPI() const
{
return d_displayDPI;
}
//----------------------------------------------------------------------------//
uint OgreRenderer::getMaxTextureSize() const
{
return d_maxTextureSize;
}
//----------------------------------------------------------------------------//
const String& OgreRenderer::getIdentifierString() const
{
return d_rendererID;
}
//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer() :
d_displayDPI(96, 96),
// TODO: should be set to correct value
d_maxTextureSize(2048),
d_ogreRoot(Ogre::Root::getSingletonPtr()),
d_activeBlendMode(BM_INVALID)
{
checkOgreInitialised();
// get auto created window
Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow();
if (!rwnd)
throw RendererException("Ogre was not initialised to automatically "
"create a window, you should therefore be "
"explicitly specifying a Ogre::RenderTarget in "
"the OgreRenderer::create function.");
constructor_impl(*rwnd);
}
//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) :
d_displayDPI(96, 96),
// TODO: should be set to correct value
d_maxTextureSize(2048),
d_ogreRoot(Ogre::Root::getSingletonPtr()),
d_activeBlendMode(BM_INVALID),
d_makeFrameControlCalls(true)
{
checkOgreInitialised();
constructor_impl(target);
}
//----------------------------------------------------------------------------//
OgreRenderer::~OgreRenderer()
{
d_ogreRoot->removeFrameListener(&S_frameListener);
destroyAllGeometryBuffers();
destroyAllTextureTargets();
destroyAllTextures();
delete d_defaultRoot;
delete d_defaultTarget;
}
//----------------------------------------------------------------------------//
void OgreRenderer::checkOgreInitialised()
{
if (!d_ogreRoot)
throw RendererException("The Ogre::Root object has not been created. "
"You must initialise Ogre first!");
if (!d_ogreRoot->isInitialised())
throw RendererException("Ogre has not been initialised. You must "
"initialise Ogre first!");
}
//----------------------------------------------------------------------------//
void OgreRenderer::constructor_impl(Ogre::RenderTarget& target)
{
d_renderSystem = d_ogreRoot->getRenderSystem();
d_displaySize.d_width = target.getWidth();
d_displaySize.d_height = target.getHeight();
// create default target & rendering root (surface) that uses it
d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target);
d_defaultRoot = new RenderingRoot(*d_defaultTarget);
// hook into the rendering process
d_ogreRoot->addFrameListener(&S_frameListener);
}
//----------------------------------------------------------------------------//
void OgreRenderer::setDisplaySize(const Size& sz)
{
if (sz != d_displaySize)
{
d_displaySize = sz;
// FIXME: This is probably not the right thing to do in all cases.
Rect area(d_defaultTarget->getArea());
area.setSize(sz);
d_defaultTarget->setArea(area);
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::setupRenderingBlendMode(const BlendMode mode,
const bool force)
{
using namespace Ogre;
// do nothing if mode appears current (and is not forced)
if ((d_activeBlendMode == mode) && !force)
return;
d_activeBlendMode = mode;
if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)
d_renderSystem->_setSceneBlending(SBF_ONE, SBF_ONE_MINUS_SOURCE_ALPHA);
else
d_renderSystem->_setSeparateSceneBlending(SBF_SOURCE_ALPHA,
SBF_ONE_MINUS_SOURCE_ALPHA,
SBF_ONE_MINUS_DEST_ALPHA,
SBF_ONE);
}
//----------------------------------------------------------------------------//
void OgreRenderer::setFrameControlExecutionEnabled(const bool enabled)
{
d_makeFrameControlCalls = enabled;
// default rendering requires _beginFrame and _endFrame calls be made,
// so if we're disabling those we must also disable default rendering.
if (!d_makeFrameControlCalls)
setRenderingEnabled(false);
}
//----------------------------------------------------------------------------//
bool OgreRenderer::isFrameControlExecutionEnabled() const
{
return d_makeFrameControlCalls;
}
//----------------------------------------------------------------------------//
void OgreRenderer::initialiseRenderStateSettings()
{
using namespace Ogre;
// initialise render settings
d_renderSystem->setLightingEnabled(false);
d_renderSystem->_setDepthBufferParams(false, false);
d_renderSystem->_setDepthBias(0, 0);
d_renderSystem->_setCullingMode(CULL_NONE);
d_renderSystem->_setFog(FOG_NONE);
d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true);
d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
d_renderSystem->setShadingType(SO_GOURAUD);
d_renderSystem->_setPolygonMode(PM_SOLID);
// set alpha blending to known state
setupRenderingBlendMode(BM_NORMAL, true);
}
//----------------------------------------------------------------------------//
OgreGUIFrameListener::OgreGUIFrameListener() :
d_enabled(true)
{
}
//----------------------------------------------------------------------------//
void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled)
{
d_enabled = enabled;
}
//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::isCEGUIRenderEnabled() const
{
return d_enabled;
}
//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&)
{
if (d_enabled)
System::getSingleton().renderGUI();
return true;
}
} // End of CEGUI namespace section
<commit_msg>The default constructor for CEGUI::OgreRenderer was not initialising member d_makeFrameControlCalls. See: http://www.cegui.org.uk/mantis/view.php?id=343<commit_after>/***********************************************************************
filename: CEGUIOgreRenderer.cpp
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "CEGUIOgreRenderer.h"
#include "CEGUIOgreGeometryBuffer.h"
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include "CEGUIOgreWindowTarget.h"
#include "CEGUIRenderingRoot.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIOgreResourceProvider.h"
#include "CEGUIOgreImageCodec.h"
#include <OgreRoot.h>
#include <OgreRenderSystem.h>
#include <OgreRenderWindow.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal Ogre::FrameListener based class. This is how we noew hook into the
// rendering process (as opposed to render queues previously)
static class OgreGUIFrameListener : public Ogre::FrameListener
{
public:
OgreGUIFrameListener();
void setCEGUIRenderEnabled(bool enabled);
bool isCEGUIRenderEnabled() const;
bool frameRenderingQueued(const Ogre::FrameEvent& evt);
private:
bool d_enabled;
} S_frameListener;
//----------------------------------------------------------------------------//
String OgreRenderer::d_rendererID(
"CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module.");
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem()
{
if (System::getSingletonPtr())
throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
"CEGUI::System object is already initialised.");
OgreRenderer& renderer = create();
OgreResourceProvider& rp = createOgreResourceProvider();
OgreImageCodec& ic = createOgreImageCodec();
System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);
return renderer;
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target)
{
if (System::getSingletonPtr())
throw InvalidRequestException("OgreRenderer::bootstrapSystem: "
"CEGUI::System object is already initialised.");
OgreRenderer& renderer = OgreRenderer::create(target);
OgreResourceProvider& rp = createOgreResourceProvider();
OgreImageCodec& ic = createOgreImageCodec();
System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic);
return renderer;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroySystem()
{
System* sys;
if (!(sys = System::getSingletonPtr()))
throw InvalidRequestException("OgreRenderer::destroySystem: "
"CEGUI::System object is not created or was already destroyed.");
OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer());
OgreResourceProvider* rp =
static_cast<OgreResourceProvider*>(sys->getResourceProvider());
OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec());
System::destroy();
destroyOgreImageCodec(*ic);
destroyOgreResourceProvider(*rp);
destroy(*renderer);
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create()
{
return *new OgreRenderer;
}
//----------------------------------------------------------------------------//
OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target)
{
return *new OgreRenderer(target);
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroy(OgreRenderer& renderer)
{
delete &renderer;
}
//----------------------------------------------------------------------------//
OgreResourceProvider& OgreRenderer::createOgreResourceProvider()
{
return *new OgreResourceProvider;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp)
{
delete &rp;
}
//----------------------------------------------------------------------------//
OgreImageCodec& OgreRenderer::createOgreImageCodec()
{
return *new OgreImageCodec;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic)
{
delete ⁣
}
//----------------------------------------------------------------------------//
void OgreRenderer::setRenderingEnabled(const bool enabled)
{
S_frameListener.setCEGUIRenderEnabled(enabled);
}
//----------------------------------------------------------------------------//
bool OgreRenderer::isRenderingEnabled() const
{
return S_frameListener.isCEGUIRenderEnabled();
}
//----------------------------------------------------------------------------//
RenderingRoot& OgreRenderer::getDefaultRenderingRoot()
{
return *d_defaultRoot;
}
//----------------------------------------------------------------------------//
GeometryBuffer& OgreRenderer::createGeometryBuffer()
{
OgreGeometryBuffer* gb =
new OgreGeometryBuffer(*this, *d_renderSystem);
d_geometryBuffers.push_back(gb);
return *gb;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer)
{
GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(),
d_geometryBuffers.end(),
&buffer);
if (d_geometryBuffers.end() != i)
{
d_geometryBuffers.erase(i);
delete &buffer;
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllGeometryBuffers()
{
while (!d_geometryBuffers.empty())
destroyGeometryBuffer(**d_geometryBuffers.begin());
}
//----------------------------------------------------------------------------//
TextureTarget* OgreRenderer::createTextureTarget()
{
TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem);
d_textureTargets.push_back(tt);
return tt;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyTextureTarget(TextureTarget* target)
{
TextureTargetList::iterator i = std::find(d_textureTargets.begin(),
d_textureTargets.end(),
target);
if (d_textureTargets.end() != i)
{
d_textureTargets.erase(i);
delete target;
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextureTargets()
{
while (!d_textureTargets.empty())
destroyTextureTarget(*d_textureTargets.begin());
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture()
{
OgreTexture* t = new OgreTexture;
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const String& filename,
const String& resourceGroup)
{
OgreTexture* t = new OgreTexture(filename, resourceGroup);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(const Size& size)
{
OgreTexture* t = new OgreTexture(size);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership)
{
OgreTexture* t = new OgreTexture(tex, take_ownership);
d_textures.push_back(t);
return *t;
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyTexture(Texture& texture)
{
TextureList::iterator i = std::find(d_textures.begin(),
d_textures.end(),
&texture);
if (d_textures.end() != i)
{
d_textures.erase(i);
delete &static_cast<OgreTexture&>(texture);
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::destroyAllTextures()
{
while (!d_textures.empty())
destroyTexture(**d_textures.begin());
}
//----------------------------------------------------------------------------//
void OgreRenderer::beginRendering()
{
initialiseRenderStateSettings();
if (d_makeFrameControlCalls)
d_renderSystem->_beginFrame();
}
//----------------------------------------------------------------------------//
void OgreRenderer::endRendering()
{
if (d_makeFrameControlCalls)
d_renderSystem->_endFrame();
}
//----------------------------------------------------------------------------//
const Size& OgreRenderer::getDisplaySize() const
{
return d_displaySize;
}
//----------------------------------------------------------------------------//
const Vector2& OgreRenderer::getDisplayDPI() const
{
return d_displayDPI;
}
//----------------------------------------------------------------------------//
uint OgreRenderer::getMaxTextureSize() const
{
return d_maxTextureSize;
}
//----------------------------------------------------------------------------//
const String& OgreRenderer::getIdentifierString() const
{
return d_rendererID;
}
//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer() :
d_displayDPI(96, 96),
// TODO: should be set to correct value
d_maxTextureSize(2048),
d_ogreRoot(Ogre::Root::getSingletonPtr()),
d_activeBlendMode(BM_INVALID),
d_makeFrameControlCalls(true)
{
checkOgreInitialised();
// get auto created window
Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow();
if (!rwnd)
throw RendererException("Ogre was not initialised to automatically "
"create a window, you should therefore be "
"explicitly specifying a Ogre::RenderTarget in "
"the OgreRenderer::create function.");
constructor_impl(*rwnd);
}
//----------------------------------------------------------------------------//
OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) :
d_displayDPI(96, 96),
// TODO: should be set to correct value
d_maxTextureSize(2048),
d_ogreRoot(Ogre::Root::getSingletonPtr()),
d_activeBlendMode(BM_INVALID),
d_makeFrameControlCalls(true)
{
checkOgreInitialised();
constructor_impl(target);
}
//----------------------------------------------------------------------------//
OgreRenderer::~OgreRenderer()
{
d_ogreRoot->removeFrameListener(&S_frameListener);
destroyAllGeometryBuffers();
destroyAllTextureTargets();
destroyAllTextures();
delete d_defaultRoot;
delete d_defaultTarget;
}
//----------------------------------------------------------------------------//
void OgreRenderer::checkOgreInitialised()
{
if (!d_ogreRoot)
throw RendererException("The Ogre::Root object has not been created. "
"You must initialise Ogre first!");
if (!d_ogreRoot->isInitialised())
throw RendererException("Ogre has not been initialised. You must "
"initialise Ogre first!");
}
//----------------------------------------------------------------------------//
void OgreRenderer::constructor_impl(Ogre::RenderTarget& target)
{
d_renderSystem = d_ogreRoot->getRenderSystem();
d_displaySize.d_width = target.getWidth();
d_displaySize.d_height = target.getHeight();
// create default target & rendering root (surface) that uses it
d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target);
d_defaultRoot = new RenderingRoot(*d_defaultTarget);
// hook into the rendering process
d_ogreRoot->addFrameListener(&S_frameListener);
}
//----------------------------------------------------------------------------//
void OgreRenderer::setDisplaySize(const Size& sz)
{
if (sz != d_displaySize)
{
d_displaySize = sz;
// FIXME: This is probably not the right thing to do in all cases.
Rect area(d_defaultTarget->getArea());
area.setSize(sz);
d_defaultTarget->setArea(area);
}
}
//----------------------------------------------------------------------------//
void OgreRenderer::setupRenderingBlendMode(const BlendMode mode,
const bool force)
{
using namespace Ogre;
// do nothing if mode appears current (and is not forced)
if ((d_activeBlendMode == mode) && !force)
return;
d_activeBlendMode = mode;
if (d_activeBlendMode == BM_RTT_PREMULTIPLIED)
d_renderSystem->_setSceneBlending(SBF_ONE, SBF_ONE_MINUS_SOURCE_ALPHA);
else
d_renderSystem->_setSeparateSceneBlending(SBF_SOURCE_ALPHA,
SBF_ONE_MINUS_SOURCE_ALPHA,
SBF_ONE_MINUS_DEST_ALPHA,
SBF_ONE);
}
//----------------------------------------------------------------------------//
void OgreRenderer::setFrameControlExecutionEnabled(const bool enabled)
{
d_makeFrameControlCalls = enabled;
// default rendering requires _beginFrame and _endFrame calls be made,
// so if we're disabling those we must also disable default rendering.
if (!d_makeFrameControlCalls)
setRenderingEnabled(false);
}
//----------------------------------------------------------------------------//
bool OgreRenderer::isFrameControlExecutionEnabled() const
{
return d_makeFrameControlCalls;
}
//----------------------------------------------------------------------------//
void OgreRenderer::initialiseRenderStateSettings()
{
using namespace Ogre;
// initialise render settings
d_renderSystem->setLightingEnabled(false);
d_renderSystem->_setDepthBufferParams(false, false);
d_renderSystem->_setDepthBias(0, 0);
d_renderSystem->_setCullingMode(CULL_NONE);
d_renderSystem->_setFog(FOG_NONE);
d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true);
d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM);
d_renderSystem->setShadingType(SO_GOURAUD);
d_renderSystem->_setPolygonMode(PM_SOLID);
// set alpha blending to known state
setupRenderingBlendMode(BM_NORMAL, true);
}
//----------------------------------------------------------------------------//
OgreGUIFrameListener::OgreGUIFrameListener() :
d_enabled(true)
{
}
//----------------------------------------------------------------------------//
void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled)
{
d_enabled = enabled;
}
//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::isCEGUIRenderEnabled() const
{
return d_enabled;
}
//----------------------------------------------------------------------------//
bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&)
{
if (d_enabled)
System::getSingleton().renderGUI();
return true;
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>/* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "common/EtchArrayValue.h"
#include "common/EtchTypes.h"
const EtchObjectType* EtchArrayValue::TYPE() {
static const EtchObjectType TYPE(EOTID_ARRAY_VALUE, NULL);
return &TYPE;
}
EtchArrayValue::EtchArrayValue(capu::SmartPointer<EtchNativeArrayBase> array, capu::int32_t size, capu::int8_t typeCode, EtchType* customStructType, capu::int32_t dim)
: mArray(array), mTypeCode(typeCode),
mCustomStructType(customStructType), mDim(dim), mAddIndex(size), mSize(size) {
addObjectType(TYPE());
}
EtchArrayValue::EtchArrayValue(capu::SmartPointer<EtchNativeArrayBase> array, capu::int32_t size)
: mArray(array), mTypeCode(0),
mCustomStructType(NULL), mDim(1), mAddIndex(size), mSize(size) {
addObjectType(TYPE());
}
EtchArrayValue::EtchArrayValue(const EtchArrayValue& other)
: EtchObject(other), mArray(other.mArray), mTypeCode(other.mTypeCode), mCustomStructType(other.mCustomStructType),
mDim(other.mDim), mAddIndex(other.mAddIndex), mSize(other.mSize) {
}
EtchArrayValue::~EtchArrayValue() {
}
capu::int32_t EtchArrayValue::getDim() {
return mDim;
}
capu::uint32_t EtchArrayValue::getSize() {
return mSize;
}
capu::int8_t EtchArrayValue::getTypeCode() {
return mTypeCode;
}
capu::SmartPointer<EtchNativeArrayBase> EtchArrayValue::getArray() {
return mArray;
}
capu::int32_t EtchArrayValue::getIndex() {
return mAddIndex;
}
void EtchArrayValue::setIndex(capu::int32_t val) {
mAddIndex = val;
}
EtchType * EtchArrayValue::getCustomStructType() {
return mCustomStructType;
}
capu::bool_t EtchArrayValue::equals(const EtchObject* other) const {
if(other == NULL)
return false;
if(!other->isInstanceOf(TYPE()))
return false;
EtchArrayValue* value = (EtchArrayValue*) other;
capu::bool_t customTypeTest = false;
if(mCustomStructType == NULL)
customTypeTest = mCustomStructType == value->mCustomStructType;
else
customTypeTest = this->mCustomStructType->equals(value->mCustomStructType);
if(customTypeTest && this->mArray->isInstanceOf(value->mArray->TYPE())
&& this->mSize == value->mSize && this->mDim == value->mDim && this->mAddIndex == value->mAddIndex)
return true;
return false;
}
status_t EtchArrayValue::get(capu::uint32_t index, capu::SmartPointer<EtchObject> &result) {
if ((index >= getSize()) || (mArray.get() == NULL)) {
return ETCH_EINVAL;
}
return mArray->getBase(index, result);
}
status_t EtchArrayValue::add(capu::SmartPointer<EtchObject> value) {
if (value.get() == NULL) {
return ETCH_EINVAL;
}
//check if we have to resize the array
capu::int32_t n = mSize;
if (mAddIndex >= n) {
if (n == 0) {
n = 8;
} else {
n *= 2;
}
mArray->resize(n);
mSize = n;
}
return mArray->setBase(mAddIndex++, value);
}
<commit_msg>ETCH-246 Fixed multidimensional array serialization<commit_after>/* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "common/EtchArrayValue.h"
#include "common/EtchTypes.h"
const EtchObjectType* EtchArrayValue::TYPE() {
static const EtchObjectType TYPE(EOTID_ARRAY_VALUE, NULL);
return &TYPE;
}
EtchArrayValue::EtchArrayValue(capu::SmartPointer<EtchNativeArrayBase> array, capu::int32_t size, capu::int8_t typeCode, EtchType* customStructType, capu::int32_t dim)
: mArray(array), mTypeCode(typeCode),
mCustomStructType(customStructType), mDim(dim), mAddIndex(size), mSize(size) {
addObjectType(TYPE());
}
EtchArrayValue::EtchArrayValue(capu::SmartPointer<EtchNativeArrayBase> array, capu::int32_t size)
: mArray(array), mTypeCode(0),
mCustomStructType(NULL), mDim(1), mAddIndex(size), mSize(size) {
addObjectType(TYPE());
}
EtchArrayValue::EtchArrayValue(const EtchArrayValue& other)
: EtchObject(other), mArray(other.mArray), mTypeCode(other.mTypeCode), mCustomStructType(other.mCustomStructType),
mDim(other.mDim), mAddIndex(other.mAddIndex), mSize(other.mSize) {
}
EtchArrayValue::~EtchArrayValue() {
}
capu::int32_t EtchArrayValue::getDim() {
return mDim;
}
capu::uint32_t EtchArrayValue::getSize() {
return mSize;
}
capu::int8_t EtchArrayValue::getTypeCode() {
return mTypeCode;
}
capu::SmartPointer<EtchNativeArrayBase> EtchArrayValue::getArray() {
return mArray;
}
capu::int32_t EtchArrayValue::getIndex() {
return mAddIndex;
}
void EtchArrayValue::setIndex(capu::int32_t val) {
mAddIndex = val;
}
EtchType * EtchArrayValue::getCustomStructType() {
return mCustomStructType;
}
capu::bool_t EtchArrayValue::equals(const EtchObject* other) const {
if(other == NULL)
return false;
if(!other->isInstanceOf(TYPE()))
return false;
EtchArrayValue* value = (EtchArrayValue*) other;
capu::bool_t customTypeTest = false;
if(mCustomStructType == NULL)
customTypeTest = mCustomStructType == value->mCustomStructType;
else
customTypeTest = this->mCustomStructType->equals(value->mCustomStructType);
if(customTypeTest && this->mArray->isInstanceOf(value->mArray->TYPE())
&& this->mSize == value->mSize && this->mDim == value->mDim && this->mAddIndex == value->mAddIndex)
return true;
return false;
}
status_t EtchArrayValue::get(capu::uint32_t index, capu::SmartPointer<EtchObject> &result) {
if ((index >= getSize()) || (mArray.get() == NULL)) {
return ETCH_EINVAL;
}
return mArray->getBase(index, result);
}
status_t EtchArrayValue::add(capu::SmartPointer<EtchObject> value) {
//check if we have to resize the array
capu::int32_t n = mSize;
if (mAddIndex >= n) {
if (n == 0) {
n = 8;
} else {
n *= 2;
}
mArray->resize(n);
mSize = n;
}
return mArray->setBase(mAddIndex++, value);
}
<|endoftext|> |
<commit_before>//===- DivRemPairs.cpp - Hoist/[dr]ecompose division and remainder --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass hoists and/or decomposes/recomposes integer division and remainder
// instructions to enable CFG improvements and better codegen.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/DivRemPairs.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Pass.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BypassSlowDivision.h"
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "div-rem-pairs"
STATISTIC(NumPairs, "Number of div/rem pairs");
STATISTIC(NumRecomposed, "Number of instructions recomposed");
STATISTIC(NumHoisted, "Number of instructions hoisted");
STATISTIC(NumDecomposed, "Number of instructions decomposed");
DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform",
"Controls transformations in div-rem-pairs pass");
namespace {
struct ExpandedMatch {
DivRemMapKey Key;
Instruction *Value;
};
} // namespace
/// See if we can match: (which is the form we expand into)
/// X - ((X ?/ Y) * Y)
/// which is equivalent to:
/// X ?% Y
static llvm::Optional<ExpandedMatch> matchExpandedRem(Instruction &I) {
Value *Dividend, *XroundedDownToMultipleOfY;
if (!match(&I, m_Sub(m_Value(Dividend), m_Value(XroundedDownToMultipleOfY))))
return llvm::None;
Value *Divisor;
Instruction *Div;
// Look for ((X / Y) * Y)
if (!match(
XroundedDownToMultipleOfY,
m_c_Mul(m_CombineAnd(m_IDiv(m_Specific(Dividend), m_Value(Divisor)),
m_Instruction(Div)),
m_Deferred(Divisor))))
return llvm::None;
ExpandedMatch M;
M.Key.SignedOp = Div->getOpcode() == Instruction::SDiv;
M.Key.Dividend = Dividend;
M.Key.Divisor = Divisor;
M.Value = &I;
return M;
}
/// A thin wrapper to store two values that we matched as div-rem pair.
/// We want this extra indirection to avoid dealing with RAUW'ing the map keys.
struct DivRemPairWorklistEntry {
/// The actual udiv/sdiv instruction. Source of truth.
AssertingVH<Instruction> DivInst;
/// The instruction that we have matched as a remainder instruction.
/// Should only be used as Value, don't introspect it.
AssertingVH<Instruction> RemInst;
DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_)
: DivInst(DivInst_), RemInst(RemInst_) {
assert((DivInst->getOpcode() == Instruction::UDiv ||
DivInst->getOpcode() == Instruction::SDiv) &&
"Not a division.");
assert(DivInst->getType() == RemInst->getType() && "Types should match.");
// We can't check anything else about remainder instruction,
// it's not strictly required to be a urem/srem.
}
/// The type for this pair, identical for both the div and rem.
Type *getType() const { return DivInst->getType(); }
/// Is this pair signed or unsigned?
bool isSigned() const { return DivInst->getOpcode() == Instruction::SDiv; }
/// In this pair, what are the divident and divisor?
Value *getDividend() const { return DivInst->getOperand(0); }
Value *getDivisor() const { return DivInst->getOperand(1); }
bool isRemExpanded() const {
switch (RemInst->getOpcode()) {
case Instruction::SRem:
case Instruction::URem:
return false; // single 'rem' instruction - unexpanded form.
default:
return true; // anything else means we have remainder in expanded form.
}
}
};
using DivRemWorklistTy = SmallVector<DivRemPairWorklistEntry, 4>;
/// Find matching pairs of integer div/rem ops (they have the same numerator,
/// denominator, and signedness). Place those pairs into a worklist for further
/// processing. This indirection is needed because we have to use TrackingVH<>
/// because we will be doing RAUW, and if one of the rem instructions we change
/// happens to be an input to another div/rem in the maps, we'd have problems.
static DivRemWorklistTy getWorklist(Function &F) {
// Insert all divide and remainder instructions into maps keyed by their
// operands and opcode (signed or unsigned).
DenseMap<DivRemMapKey, Instruction *> DivMap;
// Use a MapVector for RemMap so that instructions are moved/inserted in a
// deterministic order.
MapVector<DivRemMapKey, Instruction *> RemMap;
for (auto &BB : F) {
for (auto &I : BB) {
if (I.getOpcode() == Instruction::SDiv)
DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::UDiv)
DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::SRem)
RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::URem)
RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
else if (auto Match = matchExpandedRem(I))
RemMap[Match->Key] = Match->Value;
}
}
// We'll accumulate the matching pairs of div-rem instructions here.
DivRemWorklistTy Worklist;
// We can iterate over either map because we are only looking for matched
// pairs. Choose remainders for efficiency because they are usually even more
// rare than division.
for (auto &RemPair : RemMap) {
// Find the matching division instruction from the division map.
Instruction *DivInst = DivMap[RemPair.first];
if (!DivInst)
continue;
// We have a matching pair of div/rem instructions.
NumPairs++;
Instruction *RemInst = RemPair.second;
// Place it in the worklist.
Worklist.emplace_back(DivInst, RemInst);
}
return Worklist;
}
/// Find matching pairs of integer div/rem ops (they have the same numerator,
/// denominator, and signedness). If they exist in different basic blocks, bring
/// them together by hoisting or replace the common division operation that is
/// implicit in the remainder:
/// X % Y <--> X - ((X / Y) * Y).
///
/// We can largely ignore the normal safety and cost constraints on speculation
/// of these ops when we find a matching pair. This is because we are already
/// guaranteed that any exceptions and most cost are already incurred by the
/// first member of the pair.
///
/// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or
/// SimplifyCFG, but it's split off on its own because it's different enough
/// that it doesn't quite match the stated objectives of those passes.
static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI,
const DominatorTree &DT) {
bool Changed = false;
// Get the matching pairs of div-rem instructions. We want this extra
// indirection to avoid dealing with having to RAUW the keys of the maps.
DivRemWorklistTy Worklist = getWorklist(F);
// Process each entry in the worklist.
for (DivRemPairWorklistEntry &E : Worklist) {
if (!DebugCounter::shouldExecute(DRPCounter))
continue;
bool HasDivRemOp = TTI.hasDivRemOp(E.getType(), E.isSigned());
auto &DivInst = E.DivInst;
auto &RemInst = E.RemInst;
const bool RemOriginallyWasInExpandedForm = E.isRemExpanded();
if (HasDivRemOp && E.isRemExpanded()) {
// The target supports div+rem but the rem is expanded.
// We should recompose it first.
Value *X = E.getDividend();
Value *Y = E.getDivisor();
Instruction *RealRem = E.isSigned() ? BinaryOperator::CreateSRem(X, Y)
: BinaryOperator::CreateURem(X, Y);
// Note that we place it right next to the original expanded instruction,
// and letting further handling to move it if needed.
RealRem->setName(RemInst->getName() + ".recomposed");
RealRem->insertAfter(RemInst);
Instruction *OrigRemInst = RemInst;
// Update AssertingVH<> with new instruction so it doesn't assert.
RemInst = RealRem;
// And replace the original instruction with the new one.
OrigRemInst->replaceAllUsesWith(RealRem);
OrigRemInst->eraseFromParent();
NumRecomposed++;
// Note that we have left ((X / Y) * Y) around.
// If it had other uses we could rewrite it as X - X % Y
}
assert((!E.isRemExpanded() || !HasDivRemOp) &&
"*If* the target supports div-rem, then by now the RemInst *is* "
"Instruction::[US]Rem.");
// If the target supports div+rem and the instructions are in the same block
// already, there's nothing to do. The backend should handle this. If the
// target does not support div+rem, then we will decompose the rem.
if (HasDivRemOp && RemInst->getParent() == DivInst->getParent())
continue;
bool DivDominates = DT.dominates(DivInst, RemInst);
if (!DivDominates && !DT.dominates(RemInst, DivInst)) {
// We have matching div-rem pair, but they are in two different blocks,
// neither of which dominates one another.
assert(!RemOriginallyWasInExpandedForm &&
"Won't happen for expanded-form rem.");
// FIXME: We could hoist both ops to the common predecessor block?
continue;
}
// The target does not have a single div/rem operation,
// and the rem is already in expanded form. Nothing to do.
if (!HasDivRemOp && E.isRemExpanded())
continue;
if (HasDivRemOp) {
// The target has a single div/rem operation. Hoist the lower instruction
// to make the matched pair visible to the backend.
if (DivDominates)
RemInst->moveAfter(DivInst);
else
DivInst->moveAfter(RemInst);
NumHoisted++;
} else {
// The target does not have a single div/rem operation,
// and the rem is *not* in a already-expanded form.
// Decompose the remainder calculation as:
// X % Y --> X - ((X / Y) * Y).
assert(!RemOriginallyWasInExpandedForm &&
"We should not be expanding if the rem was in expanded form to "
"begin with.");
Value *X = E.getDividend();
Value *Y = E.getDivisor();
Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y);
Instruction *Sub = BinaryOperator::CreateSub(X, Mul);
// If the remainder dominates, then hoist the division up to that block:
//
// bb1:
// %rem = srem %x, %y
// bb2:
// %div = sdiv %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// %mul = mul %div, %y
// %rem = sub %x, %mul
//
// If the division dominates, it's already in the right place. The mul+sub
// will be in a different block because we don't assume that they are
// cheap to speculatively execute:
//
// bb1:
// %div = sdiv %x, %y
// bb2:
// %rem = srem %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// bb2:
// %mul = mul %div, %y
// %rem = sub %x, %mul
//
// If the div and rem are in the same block, we do the same transform,
// but any code movement would be within the same block.
if (!DivDominates)
DivInst->moveBefore(RemInst);
Mul->insertAfter(RemInst);
Sub->insertAfter(Mul);
// Now kill the explicit remainder. We have replaced it with:
// (sub X, (mul (div X, Y), Y)
Sub->setName(RemInst->getName() + ".decomposed");
Instruction *OrigRemInst = RemInst;
// Update AssertingVH<> with new instruction so it doesn't assert.
RemInst = Sub;
// And replace the original instruction with the new one.
OrigRemInst->replaceAllUsesWith(Sub);
OrigRemInst->eraseFromParent();
NumDecomposed++;
}
Changed = true;
}
return Changed;
}
// Pass manager boilerplate below here.
namespace {
struct DivRemPairsLegacyPass : public FunctionPass {
static char ID;
DivRemPairsLegacyPass() : FunctionPass(ID) {
initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.setPreservesCFG();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return optimizeDivRem(F, TTI, DT);
}
};
} // namespace
char DivRemPairsLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs",
"Hoist/decompose integer division and remainder", false,
false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs",
"Hoist/decompose integer division and remainder", false,
false)
FunctionPass *llvm::createDivRemPairsPass() {
return new DivRemPairsLegacyPass();
}
PreservedAnalyses DivRemPairsPass::run(Function &F,
FunctionAnalysisManager &FAM) {
TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
if (!optimizeDivRem(F, TTI, DT))
return PreservedAnalyses::all();
// TODO: This pass just hoists/replaces math ops - all analyses are preserved?
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
PA.preserve<GlobalsAA>();
return PA;
}
<commit_msg>[DivRemPairs] Fixup DNDEBUG build - variable is only used in assertion<commit_after>//===- DivRemPairs.cpp - Hoist/[dr]ecompose division and remainder --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass hoists and/or decomposes/recomposes integer division and remainder
// instructions to enable CFG improvements and better codegen.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/DivRemPairs.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Pass.h"
#include "llvm/Support/DebugCounter.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BypassSlowDivision.h"
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "div-rem-pairs"
STATISTIC(NumPairs, "Number of div/rem pairs");
STATISTIC(NumRecomposed, "Number of instructions recomposed");
STATISTIC(NumHoisted, "Number of instructions hoisted");
STATISTIC(NumDecomposed, "Number of instructions decomposed");
DEBUG_COUNTER(DRPCounter, "div-rem-pairs-transform",
"Controls transformations in div-rem-pairs pass");
namespace {
struct ExpandedMatch {
DivRemMapKey Key;
Instruction *Value;
};
} // namespace
/// See if we can match: (which is the form we expand into)
/// X - ((X ?/ Y) * Y)
/// which is equivalent to:
/// X ?% Y
static llvm::Optional<ExpandedMatch> matchExpandedRem(Instruction &I) {
Value *Dividend, *XroundedDownToMultipleOfY;
if (!match(&I, m_Sub(m_Value(Dividend), m_Value(XroundedDownToMultipleOfY))))
return llvm::None;
Value *Divisor;
Instruction *Div;
// Look for ((X / Y) * Y)
if (!match(
XroundedDownToMultipleOfY,
m_c_Mul(m_CombineAnd(m_IDiv(m_Specific(Dividend), m_Value(Divisor)),
m_Instruction(Div)),
m_Deferred(Divisor))))
return llvm::None;
ExpandedMatch M;
M.Key.SignedOp = Div->getOpcode() == Instruction::SDiv;
M.Key.Dividend = Dividend;
M.Key.Divisor = Divisor;
M.Value = &I;
return M;
}
/// A thin wrapper to store two values that we matched as div-rem pair.
/// We want this extra indirection to avoid dealing with RAUW'ing the map keys.
struct DivRemPairWorklistEntry {
/// The actual udiv/sdiv instruction. Source of truth.
AssertingVH<Instruction> DivInst;
/// The instruction that we have matched as a remainder instruction.
/// Should only be used as Value, don't introspect it.
AssertingVH<Instruction> RemInst;
DivRemPairWorklistEntry(Instruction *DivInst_, Instruction *RemInst_)
: DivInst(DivInst_), RemInst(RemInst_) {
assert((DivInst->getOpcode() == Instruction::UDiv ||
DivInst->getOpcode() == Instruction::SDiv) &&
"Not a division.");
assert(DivInst->getType() == RemInst->getType() && "Types should match.");
// We can't check anything else about remainder instruction,
// it's not strictly required to be a urem/srem.
}
/// The type for this pair, identical for both the div and rem.
Type *getType() const { return DivInst->getType(); }
/// Is this pair signed or unsigned?
bool isSigned() const { return DivInst->getOpcode() == Instruction::SDiv; }
/// In this pair, what are the divident and divisor?
Value *getDividend() const { return DivInst->getOperand(0); }
Value *getDivisor() const { return DivInst->getOperand(1); }
bool isRemExpanded() const {
switch (RemInst->getOpcode()) {
case Instruction::SRem:
case Instruction::URem:
return false; // single 'rem' instruction - unexpanded form.
default:
return true; // anything else means we have remainder in expanded form.
}
}
};
using DivRemWorklistTy = SmallVector<DivRemPairWorklistEntry, 4>;
/// Find matching pairs of integer div/rem ops (they have the same numerator,
/// denominator, and signedness). Place those pairs into a worklist for further
/// processing. This indirection is needed because we have to use TrackingVH<>
/// because we will be doing RAUW, and if one of the rem instructions we change
/// happens to be an input to another div/rem in the maps, we'd have problems.
static DivRemWorklistTy getWorklist(Function &F) {
// Insert all divide and remainder instructions into maps keyed by their
// operands and opcode (signed or unsigned).
DenseMap<DivRemMapKey, Instruction *> DivMap;
// Use a MapVector for RemMap so that instructions are moved/inserted in a
// deterministic order.
MapVector<DivRemMapKey, Instruction *> RemMap;
for (auto &BB : F) {
for (auto &I : BB) {
if (I.getOpcode() == Instruction::SDiv)
DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::UDiv)
DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::SRem)
RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I;
else if (I.getOpcode() == Instruction::URem)
RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I;
else if (auto Match = matchExpandedRem(I))
RemMap[Match->Key] = Match->Value;
}
}
// We'll accumulate the matching pairs of div-rem instructions here.
DivRemWorklistTy Worklist;
// We can iterate over either map because we are only looking for matched
// pairs. Choose remainders for efficiency because they are usually even more
// rare than division.
for (auto &RemPair : RemMap) {
// Find the matching division instruction from the division map.
Instruction *DivInst = DivMap[RemPair.first];
if (!DivInst)
continue;
// We have a matching pair of div/rem instructions.
NumPairs++;
Instruction *RemInst = RemPair.second;
// Place it in the worklist.
Worklist.emplace_back(DivInst, RemInst);
}
return Worklist;
}
/// Find matching pairs of integer div/rem ops (they have the same numerator,
/// denominator, and signedness). If they exist in different basic blocks, bring
/// them together by hoisting or replace the common division operation that is
/// implicit in the remainder:
/// X % Y <--> X - ((X / Y) * Y).
///
/// We can largely ignore the normal safety and cost constraints on speculation
/// of these ops when we find a matching pair. This is because we are already
/// guaranteed that any exceptions and most cost are already incurred by the
/// first member of the pair.
///
/// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or
/// SimplifyCFG, but it's split off on its own because it's different enough
/// that it doesn't quite match the stated objectives of those passes.
static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI,
const DominatorTree &DT) {
bool Changed = false;
// Get the matching pairs of div-rem instructions. We want this extra
// indirection to avoid dealing with having to RAUW the keys of the maps.
DivRemWorklistTy Worklist = getWorklist(F);
// Process each entry in the worklist.
for (DivRemPairWorklistEntry &E : Worklist) {
if (!DebugCounter::shouldExecute(DRPCounter))
continue;
bool HasDivRemOp = TTI.hasDivRemOp(E.getType(), E.isSigned());
auto &DivInst = E.DivInst;
auto &RemInst = E.RemInst;
const bool RemOriginallyWasInExpandedForm = E.isRemExpanded();
(void)RemOriginallyWasInExpandedForm; // suppress unused variable warning
if (HasDivRemOp && E.isRemExpanded()) {
// The target supports div+rem but the rem is expanded.
// We should recompose it first.
Value *X = E.getDividend();
Value *Y = E.getDivisor();
Instruction *RealRem = E.isSigned() ? BinaryOperator::CreateSRem(X, Y)
: BinaryOperator::CreateURem(X, Y);
// Note that we place it right next to the original expanded instruction,
// and letting further handling to move it if needed.
RealRem->setName(RemInst->getName() + ".recomposed");
RealRem->insertAfter(RemInst);
Instruction *OrigRemInst = RemInst;
// Update AssertingVH<> with new instruction so it doesn't assert.
RemInst = RealRem;
// And replace the original instruction with the new one.
OrigRemInst->replaceAllUsesWith(RealRem);
OrigRemInst->eraseFromParent();
NumRecomposed++;
// Note that we have left ((X / Y) * Y) around.
// If it had other uses we could rewrite it as X - X % Y
}
assert((!E.isRemExpanded() || !HasDivRemOp) &&
"*If* the target supports div-rem, then by now the RemInst *is* "
"Instruction::[US]Rem.");
// If the target supports div+rem and the instructions are in the same block
// already, there's nothing to do. The backend should handle this. If the
// target does not support div+rem, then we will decompose the rem.
if (HasDivRemOp && RemInst->getParent() == DivInst->getParent())
continue;
bool DivDominates = DT.dominates(DivInst, RemInst);
if (!DivDominates && !DT.dominates(RemInst, DivInst)) {
// We have matching div-rem pair, but they are in two different blocks,
// neither of which dominates one another.
assert(!RemOriginallyWasInExpandedForm &&
"Won't happen for expanded-form rem.");
// FIXME: We could hoist both ops to the common predecessor block?
continue;
}
// The target does not have a single div/rem operation,
// and the rem is already in expanded form. Nothing to do.
if (!HasDivRemOp && E.isRemExpanded())
continue;
if (HasDivRemOp) {
// The target has a single div/rem operation. Hoist the lower instruction
// to make the matched pair visible to the backend.
if (DivDominates)
RemInst->moveAfter(DivInst);
else
DivInst->moveAfter(RemInst);
NumHoisted++;
} else {
// The target does not have a single div/rem operation,
// and the rem is *not* in a already-expanded form.
// Decompose the remainder calculation as:
// X % Y --> X - ((X / Y) * Y).
assert(!RemOriginallyWasInExpandedForm &&
"We should not be expanding if the rem was in expanded form to "
"begin with.");
Value *X = E.getDividend();
Value *Y = E.getDivisor();
Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y);
Instruction *Sub = BinaryOperator::CreateSub(X, Mul);
// If the remainder dominates, then hoist the division up to that block:
//
// bb1:
// %rem = srem %x, %y
// bb2:
// %div = sdiv %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// %mul = mul %div, %y
// %rem = sub %x, %mul
//
// If the division dominates, it's already in the right place. The mul+sub
// will be in a different block because we don't assume that they are
// cheap to speculatively execute:
//
// bb1:
// %div = sdiv %x, %y
// bb2:
// %rem = srem %x, %y
// -->
// bb1:
// %div = sdiv %x, %y
// bb2:
// %mul = mul %div, %y
// %rem = sub %x, %mul
//
// If the div and rem are in the same block, we do the same transform,
// but any code movement would be within the same block.
if (!DivDominates)
DivInst->moveBefore(RemInst);
Mul->insertAfter(RemInst);
Sub->insertAfter(Mul);
// Now kill the explicit remainder. We have replaced it with:
// (sub X, (mul (div X, Y), Y)
Sub->setName(RemInst->getName() + ".decomposed");
Instruction *OrigRemInst = RemInst;
// Update AssertingVH<> with new instruction so it doesn't assert.
RemInst = Sub;
// And replace the original instruction with the new one.
OrigRemInst->replaceAllUsesWith(Sub);
OrigRemInst->eraseFromParent();
NumDecomposed++;
}
Changed = true;
}
return Changed;
}
// Pass manager boilerplate below here.
namespace {
struct DivRemPairsLegacyPass : public FunctionPass {
static char ID;
DivRemPairsLegacyPass() : FunctionPass(ID) {
initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<TargetTransformInfoWrapperPass>();
AU.setPreservesCFG();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<GlobalsAAWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
bool runOnFunction(Function &F) override {
if (skipFunction(F))
return false;
auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return optimizeDivRem(F, TTI, DT);
}
};
} // namespace
char DivRemPairsLegacyPass::ID = 0;
INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs",
"Hoist/decompose integer division and remainder", false,
false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs",
"Hoist/decompose integer division and remainder", false,
false)
FunctionPass *llvm::createDivRemPairsPass() {
return new DivRemPairsLegacyPass();
}
PreservedAnalyses DivRemPairsPass::run(Function &F,
FunctionAnalysisManager &FAM) {
TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F);
DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
if (!optimizeDivRem(F, TTI, DT))
return PreservedAnalyses::all();
// TODO: This pass just hoists/replaces math ops - all analyses are preserved?
PreservedAnalyses PA;
PA.preserveSet<CFGAnalyses>();
PA.preserve<GlobalsAA>();
return PA;
}
<|endoftext|> |
<commit_before>#include "Core/Context.h"
#include "Core/Engine.h"
#include "Core/Logger.h"
#include "GameFramework/World.h"
#include "GameFramework/Entity.h"
#include "Component/CameraComponent.h"
#include "Component/MeshRenderComponent.h"
#include "Component/LightComponent.h"
#include "Resource/ResourceManager.h"
#include "Resource/Model.h"
#include "Resource/ModelLoader.h"
#include "Resource/Material.h"
#include "Resource/Texture2D.h"
#include "Rendering/Cube.h"
#include "Rendering/Quad.h"
#include "Rendering/RendererDX11.h"
#include "Math/Vector3.h"
#include "MT/ThreadPool.h"
#include "RotateComponent.h"
using namespace Mile;
int main( )
{
auto context = new Context();
auto engine = new Engine(context);
int execute = 1;
if (engine->Init())
{
auto world = Engine::GetWorld();
auto resMng = Engine::GetResourceManager();
auto renderer = Engine::GetRenderer();
Entity* cameraParent = world->CreateEntity(TEXT("CameraParent"));
Transform* camParentTransform = cameraParent->GetTransform();
RotateComponent* cameraParentRotation = cameraParent->AddComponent<RotateComponent>();
Entity* camera = world->CreateEntity(TEXT("Camera"));
CameraComponent* camComponent = camera->AddComponent<CameraComponent>();
Transform* camTransform = camera->GetTransform();
camComponent->SetNearPlane(0.1f);
camComponent->SetFarPlane(100.0f);
camComponent->SetFov(45.0f);
camTransform->SetPosition(Vector3(0.0f, 2.0f, -7.0f));
camTransform->SetRotation(Quaternion(-20.0f, Vector3(1.0f, 0.0f, 0.0f)));
cameraParent->AttachChild(camera);
Entity* mainLight = world->CreateEntity(TEXT("Main Light"));
LightComponent* mainLightComponent = mainLight->AddComponent<LightComponent>();
Transform* mainLightTransform = mainLight->GetTransform();
mainLightComponent->SetLightType(ELightType::Point);
mainLightComponent->SetRadiance(Vector3(200.0f, 200.0f, 200.0f));
mainLightTransform->SetPosition(Vector3(-9.0f, 0.0f, -3.0f));
Model* lanternModel = resMng->Load<Model>(TEXT("Contents/Models/Lantern/Lantern.gltf"));
Entity* lantern = Model::Instantiate(lanternModel, world, TEXT("Lantern"));
Entity* lanternMesh = lantern->GetChildren()[0];
//RotateComponent* lanternRotateComponent = lantern->AddComponent<RotateComponent>();
MeshRenderComponent* lanternRenderComponent = lanternMesh->GetComponent<MeshRenderComponent>();
Material* lanternMaterial = lanternRenderComponent->GetMaterial();
lanternMaterial->Save();
Transform* lanternTransform = lantern->GetTransform();
lanternTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
lanternTransform->SetPosition(Vector3(-2.5f, -0.9f, 0.0f));
Model* damagedHelmetModel = resMng->Load<Model>(TEXT("Contents/Models/DamagedHelmet/DamagedHelmet.gltf"));
Entity* damagedHelmet = Model::Instantiate(damagedHelmetModel, world, TEXT("DamagedHelmet"));
Entity* damagedHelmetMesh = damagedHelmet->GetChildren()[0];
MeshRenderComponent* helmetRenderComponent = damagedHelmetMesh->GetComponent<MeshRenderComponent>();
Material* damagedHelmetMaterial = helmetRenderComponent->GetMaterial();
Transform* helmetTransform = damagedHelmet->GetTransform();
helmetTransform->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
damagedHelmetMaterial->Save();
Cube* cubeMesh = new Cube(renderer);
cubeMesh->Init(Vector3(-1.0f, -1.0f, -1.0f), Vector3(1.0f, 1.0f, 1.0f));
Entity* cube = world->CreateEntity(TEXT("Cube"));
Transform* cubeTransform = cube->GetTransform();
MeshRenderComponent* cubeRenderComponent = cube->AddComponent<MeshRenderComponent>();
Material* cubeMaterial = resMng->Load<Material>(TEXT("Contents/Materials/Default.material"));
cubeMaterial->SetScalarFactor(MaterialFactorProperty::Metallic, 0.0f);
cubeMaterial->SetScalarFactor(MaterialFactorProperty::Roughness, 1.0f);
cubeRenderComponent->SetMesh(cubeMesh);
cubeRenderComponent->SetMaterial(cubeMaterial);
cubeTransform->SetPosition(Vector3(3.5f, 0.0f, 0.0f));
cubeTransform->SetScale(Vector3(1.0f, 1.0f, 1.0f));
Quad* quadMesh = new Quad(renderer);
quadMesh->Init(-1.0f, -1.0f, 1.0f, 1.0f);
Entity* plane = world->CreateEntity(TEXT("Plane"));
Transform* planeTransform = plane->GetTransform();
MeshRenderComponent* planeRenderComponent = plane->AddComponent<MeshRenderComponent>();
planeRenderComponent->SetMesh(quadMesh);
planeRenderComponent->SetMaterial(cubeMaterial);
planeTransform->SetPosition(Vector3(0.0f, -1.0f, 0.0f));
planeTransform->SetRotation(Quaternion(-90.0f, Vector3(1.0f, 0.0f, 0.0f)));
Model* metalRoughSpheresModel = resMng->Load<Model>(TEXT("Contents/Models/MetalRoughSpheres/MetalRoughSpheres.gltf"));
Entity* spheresEntity = Model::Instantiate(metalRoughSpheresModel, world, TEXT("Spheres"));
Entity* spheresMesh = spheresEntity->GetChildren()[0];
MeshRenderComponent* spheresRenderComponent = spheresMesh->GetComponent<MeshRenderComponent>();
Material* spheresMaterial = spheresRenderComponent->GetMaterial();
spheresMaterial->Save();
Transform* spheresTransform = spheresEntity->GetTransform();
spheresTransform->SetPosition(Vector3(0.0f, 0.0f, 4.0f));
//world->GetComponentsFromEntities<Transform>(); // Transform Component ʱ ϵ ʴ´.
Texture2D* iceLakeHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Ice_Lake/Ice_Lake_Ref.hdr"));
renderer->SetEquirectangularMap(iceLakeHDR);
//Texture2D* helipadGoldenHourHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Helipad_GoldenHour/LA_Downtown_Helipad_GoldenHour_3k.hdr"));
//renderer->SetEquirectangularMap(helipadGoldenHourHDR);
//Texture2D* newPortHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Newport_Loft/Newport_Loft_Ref.hdr"));
//renderer->SetEquirectangularMap(newPortHDR);
//Texture2D* walkOfFameHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Walk_Of_Fame/Mans_Outside_2k.hdr"));
//renderer->SetEquirectangularMap(walkOfFameHDR);
//Texture2D* winterForestHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Winter_Forest/WinterForest_Ref.hdr"));
//renderer->SetEquirectangularMap(winterForestHDR);
//Texture2D* barcelonaRooftopsHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Barcelona_Rooftops/Barce_Rooftop_C_3k.hdr"));
//renderer->SetEquirectangularMap(barcelonaRooftopsHDR);
//Texture2D* snowMachineHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/snow_machine/test8_Ref.hdr"));
//renderer->SetEquirectangularMap(snowMachineHDR);
renderer->SetComputeIBLAsRealtime(false);
renderer->SetAmbientOcclusionFactor(1.0f);
renderer->SetGammaFactor(DEFAULT_GAMMA_FACTOR);
renderer->SetExposure(1.0f);
renderer->SetBloomType(EBloomType::Gaussian);
renderer->SetGaussianBloomAmount(16);
renderer->SetGaussianBloomIntensity(1.5f);
renderer->SetGaussianBloomThreshold(0.8f);
execute = engine->Execute();
}
SafeDelete(context);
return execute;
}<commit_msg>Modify plane of test scene<commit_after>#include "Core/Context.h"
#include "Core/Engine.h"
#include "Core/Logger.h"
#include "GameFramework/World.h"
#include "GameFramework/Entity.h"
#include "Component/CameraComponent.h"
#include "Component/MeshRenderComponent.h"
#include "Component/LightComponent.h"
#include "Resource/ResourceManager.h"
#include "Resource/Model.h"
#include "Resource/ModelLoader.h"
#include "Resource/Material.h"
#include "Resource/Texture2D.h"
#include "Rendering/Cube.h"
#include "Rendering/Quad.h"
#include "Rendering/RendererDX11.h"
#include "Math/Vector3.h"
#include "MT/ThreadPool.h"
#include "RotateComponent.h"
using namespace Mile;
int main( )
{
auto context = new Context();
auto engine = new Engine(context);
int execute = 1;
if (engine->Init())
{
auto world = Engine::GetWorld();
auto resMng = Engine::GetResourceManager();
auto renderer = Engine::GetRenderer();
Entity* cameraParent = world->CreateEntity(TEXT("CameraParent"));
Transform* camParentTransform = cameraParent->GetTransform();
RotateComponent* cameraParentRotation = cameraParent->AddComponent<RotateComponent>();
Entity* camera = world->CreateEntity(TEXT("Camera"));
CameraComponent* camComponent = camera->AddComponent<CameraComponent>();
Transform* camTransform = camera->GetTransform();
camComponent->SetNearPlane(0.1f);
camComponent->SetFarPlane(100.0f);
camComponent->SetFov(45.0f);
camTransform->SetPosition(Vector3(0.0f, 2.0f, -7.0f));
camTransform->SetRotation(Quaternion(-20.0f, Vector3(1.0f, 0.0f, 0.0f)));
cameraParent->AttachChild(camera);
Entity* mainLight = world->CreateEntity(TEXT("Main Light"));
LightComponent* mainLightComponent = mainLight->AddComponent<LightComponent>();
Transform* mainLightTransform = mainLight->GetTransform();
mainLightComponent->SetLightType(ELightType::Point);
mainLightComponent->SetRadiance(Vector3(200.0f, 200.0f, 200.0f));
mainLightTransform->SetPosition(Vector3(-9.0f, 0.0f, -3.0f));
Model* lanternModel = resMng->Load<Model>(TEXT("Contents/Models/Lantern/Lantern.gltf"));
Entity* lantern = Model::Instantiate(lanternModel, world, TEXT("Lantern"));
Entity* lanternMesh = lantern->GetChildren()[0];
//RotateComponent* lanternRotateComponent = lantern->AddComponent<RotateComponent>();
MeshRenderComponent* lanternRenderComponent = lanternMesh->GetComponent<MeshRenderComponent>();
Material* lanternMaterial = lanternRenderComponent->GetMaterial();
lanternMaterial->Save();
Transform* lanternTransform = lantern->GetTransform();
lanternTransform->SetScale(Vector3(0.1f, 0.1f, 0.1f));
lanternTransform->SetPosition(Vector3(-2.5f, -0.9f, 0.0f));
Model* damagedHelmetModel = resMng->Load<Model>(TEXT("Contents/Models/DamagedHelmet/DamagedHelmet.gltf"));
Entity* damagedHelmet = Model::Instantiate(damagedHelmetModel, world, TEXT("DamagedHelmet"));
Entity* damagedHelmetMesh = damagedHelmet->GetChildren()[0];
MeshRenderComponent* helmetRenderComponent = damagedHelmetMesh->GetComponent<MeshRenderComponent>();
Material* damagedHelmetMaterial = helmetRenderComponent->GetMaterial();
Transform* helmetTransform = damagedHelmet->GetTransform();
helmetTransform->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
damagedHelmetMaterial->Save();
Cube* cubeMesh = new Cube(renderer);
cubeMesh->Init(Vector3(-1.0f, -1.0f, -1.0f), Vector3(1.0f, 1.0f, 1.0f));
Entity* cube = world->CreateEntity(TEXT("Cube"));
Transform* cubeTransform = cube->GetTransform();
MeshRenderComponent* cubeRenderComponent = cube->AddComponent<MeshRenderComponent>();
Material* cubeMaterial = resMng->Load<Material>(TEXT("Contents/Materials/Default.material"));
cubeMaterial->SetScalarFactor(MaterialFactorProperty::Metallic, 0.0f);
cubeMaterial->SetScalarFactor(MaterialFactorProperty::Roughness, 1.0f);
cubeRenderComponent->SetMesh(cubeMesh);
cubeRenderComponent->SetMaterial(cubeMaterial);
cubeTransform->SetPosition(Vector3(3.5f, 0.0f, 0.0f));
cubeTransform->SetScale(Vector3(1.0f, 1.0f, 1.0f));
Quad* quadMesh = new Quad(renderer);
quadMesh->Init(-1.0f, -1.0f, 1.0f, 1.0f);
Entity* plane = world->CreateEntity(TEXT("Plane"));
Transform* planeTransform = plane->GetTransform();
MeshRenderComponent* planeRenderComponent = plane->AddComponent<MeshRenderComponent>();
planeRenderComponent->SetMesh(quadMesh);
planeRenderComponent->SetMaterial(cubeMaterial);
planeTransform->SetPosition(Vector3(0.0f, -6.0f, 0.0f));
planeTransform->SetRotation(Quaternion(-90.0f, Vector3(1.0f, 0.0f, 0.0f)));
planeTransform->SetScale(Vector3(30.0f, 30.0f, 30.0f));
Model* metalRoughSpheresModel = resMng->Load<Model>(TEXT("Contents/Models/MetalRoughSpheres/MetalRoughSpheres.gltf"));
Entity* spheresEntity = Model::Instantiate(metalRoughSpheresModel, world, TEXT("Spheres"));
Entity* spheresMesh = spheresEntity->GetChildren()[0];
MeshRenderComponent* spheresRenderComponent = spheresMesh->GetComponent<MeshRenderComponent>();
Material* spheresMaterial = spheresRenderComponent->GetMaterial();
spheresMaterial->Save();
Transform* spheresTransform = spheresEntity->GetTransform();
spheresTransform->SetPosition(Vector3(0.0f, 0.0f, 4.0f));
//world->GetComponentsFromEntities<Transform>(); // Transform Component ʱ ϵ ʴ´.
Texture2D* iceLakeHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Ice_Lake/Ice_Lake_Ref.hdr"));
renderer->SetEquirectangularMap(iceLakeHDR);
//Texture2D* helipadGoldenHourHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Helipad_GoldenHour/LA_Downtown_Helipad_GoldenHour_3k.hdr"));
//renderer->SetEquirectangularMap(helipadGoldenHourHDR);
//Texture2D* newPortHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Newport_Loft/Newport_Loft_Ref.hdr"));
//renderer->SetEquirectangularMap(newPortHDR);
//Texture2D* walkOfFameHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Walk_Of_Fame/Mans_Outside_2k.hdr"));
//renderer->SetEquirectangularMap(walkOfFameHDR);
//Texture2D* winterForestHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Winter_Forest/WinterForest_Ref.hdr"));
//renderer->SetEquirectangularMap(winterForestHDR);
//Texture2D* barcelonaRooftopsHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/Barcelona_Rooftops/Barce_Rooftop_C_3k.hdr"));
//renderer->SetEquirectangularMap(barcelonaRooftopsHDR);
//Texture2D* snowMachineHDR = resMng->Load<Texture2D>(TEXT("Contents/Textures/snow_machine/test8_Ref.hdr"));
//renderer->SetEquirectangularMap(snowMachineHDR);
renderer->SetComputeIBLAsRealtime(false);
renderer->SetAmbientOcclusionFactor(1.0f);
renderer->SetGammaFactor(DEFAULT_GAMMA_FACTOR);
renderer->SetExposure(1.0f);
renderer->SetBloomType(EBloomType::Gaussian);
renderer->SetGaussianBloomAmount(16);
renderer->SetGaussianBloomIntensity(1.5f);
renderer->SetGaussianBloomThreshold(0.8f);
execute = engine->Execute();
}
SafeDelete(context);
return execute;
}<|endoftext|> |
<commit_before>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void WriteLock()
{
mutex.lock();
}
void WriteUnlock()
{
mutex.unlock();
}
void ReadLock()
{
mutex.lock_shared();
}
void ReadUnlock()
{
mutex.unlock_shared();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
static const int upgradableBit = 0x00010000;
static const int readerBits = 0x0000ffff;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!val.compare_exchange_weak(expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeLockBit);
}
void ReadUnlock()
{
val.fetch_sub(1);
}
void ReadLockUpgradable()
{
LockInternal(upgradableBit, writeLockBit | upgradableBit);
}
void ReadUnlockUpgradable()
{
val.fetch_sub(upgradableBit);
}
void Upgrade()
{
LockInternal(writeLockBit - upgradableBit, readerBits | writeLockBit);
}
void WriteLock()
{
LockInternal(writeLockBit, readerBits | writeLockBit | upgradableBit);
}
void WriteUnlock()
{
val.fetch_sub(writeLockBit);
}
};
//static AsmLock lock;
static SharedMutex lock;
//static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
for (int i = 0; i < 1000000; i++) {
int r = rand() % 10000;
if (i % 10 == 0) {
lock.ReadLock();
auto it = c.find(r);
if (it != c.end()) {
lock.ReadUnlock();
} else {
lock.ReadUnlock();
lock.WriteLock();
auto it = c.find(r);
if (it == c.end()) {
c.insert(r);
}
lock.WriteUnlock();
}
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d\n", id, readFound, readNotFound);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<commit_msg>TryUpgrade<commit_after>// ThreadTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <set>
#include <vector>
#include <shared_mutex>
#include <atomic>
int egis = 0;
class AsmLock {
public:
void Lock()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jnz retry;
}
}
void Lock2()
{
__asm {
mov eax, 1;
retry:
xchg eax, [egis];
test eax, eax;
jz done;
retry_mov:
mov ebx, [egis];
test ebx, ebx;
jnz retry_mov;
jmp retry;
done:
}
}
void Unlock()
{
__asm {
mov eax, 0;
xchg eax, [egis];
}
}
void Unlock2()
{
__asm {
mov[egis], 0;
}
}
};
class SharedMutex {
std::shared_timed_mutex mutex;
public:
void WriteLock()
{
mutex.lock();
}
void WriteUnlock()
{
mutex.unlock();
}
void ReadLock()
{
mutex.lock_shared();
}
void ReadUnlock()
{
mutex.unlock_shared();
}
};
class Atomic {
std::atomic<int> val = 0;
static const int writeLockBit = 0x40000000;
static const int upgradingBit = 0x20000000;
static const int readerBits = 0x0000ffff;
void LockInternal(int delta, int testBits)
{
int expected;
do {
do {
expected = val;
} while (expected & testBits);
} while (!val.compare_exchange_weak(expected, expected + delta));
}
public:
void ReadLock()
{
LockInternal(1, writeLockBit | upgradingBit);
}
void ReadUnlock()
{
val.fetch_sub(1);
}
void WriteLock()
{
LockInternal(writeLockBit, 0xffffffff);
}
void WriteUnlock()
{
val.fetch_sub(writeLockBit);
}
bool TryUpgrade()
{
int expected;
do {
expected = val;
if (expected & upgradingBit) {
return false;
}
} while (!val.compare_exchange_weak(expected, expected | upgradingBit));
LockInternal(writeLockBit - upgradingBit - 1, writeLockBit | (readerBits & ~1));
return true;
}
};
//static AsmLock lock;
//static SharedMutex lock;
static Atomic lock;
void IncDecThreadMain()
{
static int a = 0;
for (int i = 0; i < 1000000; i++) {
lock.WriteLock();
a++;
if (a != 1)
{
printf("%d ", a);
}
a--;
lock.WriteUnlock();
printf("");
}
}
void StlContainerThreadMain(int id)
{
static std::set<int> c;
int readFound = 0;
int readNotFound = 0;
int upgradeFail = 0;
srand(id);
for (int i = 0; i < 1000000; i++) {
int r = rand() % 10000000;
if (i % 10 == 0) {
lock.ReadLock();
auto it = c.find(r);
if (it != c.end()) {
lock.ReadUnlock();
} else {
if (lock.TryUpgrade()) {
c.insert(r);
lock.WriteUnlock();
} else {
upgradeFail++;
lock.ReadUnlock();
}
}
} else {
lock.ReadLock();
auto it = c.find(r);
if (it == c.end()) {
readNotFound++;
} else {
readFound++;
}
lock.ReadUnlock();
}
printf("");
}
printf("threadId=%d readFound=%d readNotFound=%d upgradeFail=%d\n", id, readFound, readNotFound, upgradeFail);
}
double GetTime()
{
static auto start = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count();
}
void IncDecTest()
{
printf("IncDecTest\n");
double begin = GetTime();
std::thread t1(IncDecThreadMain);
std::thread t2(IncDecThreadMain);
std::thread t3(IncDecThreadMain);
t1.join();
t2.join();
t3.join();
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
void StlContainerTest()
{
printf("StlContainerTest\n");
double begin = GetTime();
std::vector<std::thread> t;
for (int i = 0; i < 10; i++) {
t.emplace_back(std::thread(StlContainerThreadMain, i));
}
for (int i = 0; i < 10; i++) {
t[i].join();
}
double end = GetTime();
printf("elapsed: %f\n", end - begin);
}
int main()
{
IncDecTest();
StlContainerTest();
return 0;
}
<|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/chromeos/compact_location_bar_view.h"
#include <gtk/gtk.h>
#include <algorithm>
#include "app/l10n_util.h"
#include "app/drag_drop_types.h"
#include "app/resource_bundle.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/chromeos/compact_location_bar_host.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/event_utils.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_star_toggle.h"
#include "gfx/canvas.h"
#include "gfx/point.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/controls/button/image_button.h"
#include "views/controls/native/native_view_host.h"
#include "views/drag_utils.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace chromeos {
const int kAutocompletePopupWidth = 700;
const int kDefaultLocationEntryWidth = 250;
const int kCompactLocationLeftMargin = 5;
const int kCompactLocationRightMargin = 10;
const int kEntryLeftMargin = 2;
// TODO(oshima): ToolbarView gets this from background image's height;
// Find out the right way, value for compact location bar.
const int kDefaultLocationBarHeight = 34;
const int kWidgetsSeparatorWidth = 2;
CompactLocationBarView::CompactLocationBarView(CompactLocationBarHost* host)
: DropdownBarView(host),
reload_(NULL),
browser_actions_(NULL),
star_(NULL) {
SetFocusable(true);
}
CompactLocationBarView::~CompactLocationBarView() {
}
////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarView public:
void CompactLocationBarView::SetFocusAndSelection() {
location_entry_->SetFocus();
location_entry_->SelectAll(true);
}
void CompactLocationBarView::Update(const TabContents* contents) {
location_entry_->Update(contents);
browser_actions_->RefreshBrowserActionViews();
}
////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarView private:
Browser* CompactLocationBarView::browser() const {
return host()->browser_view()->browser();
}
void CompactLocationBarView::Init() {
ThemeProvider* tp = browser()->profile()->GetThemeProvider();
SkColor color = tp->GetColor(BrowserThemeProvider::COLOR_BUTTON_BACKGROUND);
SkBitmap* background = tp->GetBitmapNamed(IDR_THEME_BUTTON_BACKGROUND);
// Reload button.
reload_ = new views::ImageButton(this);
reload_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
reload_->set_tag(IDC_RELOAD);
reload_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_RELOAD));
reload_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_RELOAD));
reload_->SetID(VIEW_ID_RELOAD_BUTTON);
reload_->SetImage(views::CustomButton::BS_NORMAL,
tp->GetBitmapNamed(IDR_RELOAD));
reload_->SetImage(views::CustomButton::BS_HOT,
tp->GetBitmapNamed(IDR_RELOAD_H));
reload_->SetImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_RELOAD_P));
reload_->SetBackground(color, background,
tp->GetBitmapNamed(IDR_BUTTON_MASK));
AddChildView(reload_);
// Location bar.
location_entry_.reset(new AutocompleteEditViewGtk(
this, browser()->toolbar_model(), browser()->profile(),
browser()->command_updater(), false, this));
location_entry_->Init();
location_entry_->Update(browser()->GetSelectedTabContents());
gtk_widget_show_all(location_entry_->GetNativeView());
gtk_widget_hide(location_entry_->GetNativeView());
location_entry_view_ = new views::NativeViewHost;
AddChildView(location_entry_view_);
location_entry_view_->set_focus_view(this);
location_entry_view_->Attach(location_entry_->GetNativeView());
star_ = new ToolbarStarToggle(this);
star_->SetDragController(this);
star_->set_profile(browser()->profile());
star_->set_host_view(this);
star_->set_bubble_positioner(this);
star_->Init();
AddChildView(star_);
location_entry_->Update(browser()->GetSelectedTabContents());
// Note: we tell the BrowserActionsContainer not to save its size because
// the main container is part of the ToolbarView, and we don't want them
// fighting. See http://code.google.com/p/chromium/issues/detail?id=38992
browser_actions_ = new BrowserActionsContainer(browser(), this, false);
AddChildView(browser_actions_);
}
////////////////////////////////////////////////////////////////////////////////
// views::View overrides:
gfx::Size CompactLocationBarView::GetPreferredSize() {
if (!reload_)
return gfx::Size(); // Not initialized yet, do nothing.
gfx::Size reload_size = reload_->GetPreferredSize();
gfx::Size star_size = star_->GetPreferredSize();
gfx::Size location_size = location_entry_view_->GetPreferredSize();
gfx::Size ba_size = browser_actions_->GetPreferredSize();
int width =
reload_size.width() + kEntryLeftMargin + star_size.width() +
std::max(kDefaultLocationEntryWidth,
location_entry_view_->GetPreferredSize().width()) +
ba_size.width() +
kCompactLocationLeftMargin +
kCompactLocationRightMargin;
return gfx::Size(width, kDefaultLocationBarHeight);
}
void CompactLocationBarView::Layout() {
if (!reload_)
return; // Not initialized yet, do nothing.
int cur_x = kCompactLocationLeftMargin;
gfx::Size reload_size = reload_->GetPreferredSize();
int reload_y = (height() - reload_size.height()) / 2;
reload_->SetBounds(cur_x, reload_y,
reload_size.width(), reload_size.height());
cur_x += reload_size.width() + kEntryLeftMargin;
gfx::Size star_size = star_->GetPreferredSize();
int star_y = (height() - star_size.height()) / 2;
star_->SetBounds(cur_x, star_y, star_size.width(), star_size.height());
cur_x += star_size.width();
gfx::Size ba_size = browser_actions_->GetPreferredSize();
int ba_y = (height() - ba_size.height()) / 2;
browser_actions_->SetBounds(
width() - ba_size.width(), ba_y, ba_size.width(), ba_size.height());
int location_entry_width = browser_actions_->x() - cur_x;
if (ba_size.IsEmpty()) {
// BrowserActionsContainer has its own margin on right.
// Use the our margin when if the browser action is empty.
location_entry_width -= kCompactLocationRightMargin;
}
// The location bar gets the rest of the space in the middle.
location_entry_view_->SetBounds(cur_x, 0, location_entry_width, height());
}
void CompactLocationBarView::Paint(gfx::Canvas* canvas) {
gfx::Rect lb = GetLocalBounds(true);
ThemeProvider* tp = GetThemeProvider();
gfx::Rect bounds;
host()->GetThemePosition(&bounds);
canvas->TileImageInt(*tp->GetBitmapNamed(IDR_THEME_TOOLBAR),
bounds.x(), bounds.y(), 0, 0, lb.width(), lb.height());
View::Paint(canvas);
}
void CompactLocationBarView::ViewHierarchyChanged(bool is_add, View* parent,
View* child) {
if (is_add && child == this)
Init();
}
void CompactLocationBarView::Focus() {
location_entry_->SetFocus();
}
////////////////////////////////////////////////////////////////////////////////
// views::ButtonListener overrides:
void CompactLocationBarView::ButtonPressed(views::Button* sender,
const views::Event& event) {
int id = sender->tag();
// Shift-clicking or Ctrl-clicking the reload button means we should
// ignore any cached content.
// TODO(avayvod): eliminate duplication of this logic in
// CompactLocationBarView.
if (id == IDC_RELOAD && (event.IsShiftDown() || event.IsControlDown()))
id = IDC_RELOAD_IGNORING_CACHE;
browser()->ExecuteCommandWithDisposition(
id, event_utils::DispositionFromEventFlags(sender->mouse_event_flags()));
}
////////////////////////////////////////////////////////////////////////////////
// AutocompleteEditController overrides:
void CompactLocationBarView::OnAutocompleteAccept(
const GURL& url,
WindowOpenDisposition disposition,
PageTransition::Type transition,
const GURL& alternate_nav_url) {
browser()->OpenURL(url, GURL(), disposition, transition);
clb_host()->StartAutoHideTimer();
}
void CompactLocationBarView::OnChanged() {
// Other one does "DoLayout" here.
}
void CompactLocationBarView::OnKillFocus() {
host()->UnregisterEscAccelerator();
}
void CompactLocationBarView::OnSetFocus() {
views::FocusManager* focus_manager = GetFocusManager();
if (!focus_manager) {
NOTREACHED();
return;
}
focus_manager->SetFocusedView(this);
host()->RegisterEscAccelerator();
}
void CompactLocationBarView::OnInputInProgress(bool in_progress) {
}
SkBitmap CompactLocationBarView::GetFavIcon() const {
return SkBitmap();
}
std::wstring CompactLocationBarView::GetTitle() const {
return std::wstring();
}
////////////////////////////////////////////////////////////////////////////////
// BubblePositioner overrides:
gfx::Rect CompactLocationBarView::GetLocationStackBounds() const {
gfx::Point lower_left(0, height());
ConvertPointToScreen(this, &lower_left);
gfx::Rect popup = gfx::Rect(lower_left.x(), lower_left.y(),
kAutocompletePopupWidth, 0);
return popup.AdjustToFit(GetWidget()->GetWindow()->GetBounds());
}
////////////////////////////////////////////////////////////////////////////////
// views::DragController overrides:
void CompactLocationBarView::WriteDragData(views::View* sender,
const gfx::Point& press_pt,
OSExchangeData* data) {
DCHECK(GetDragOperations(sender, press_pt) != DragDropTypes::DRAG_NONE);
UserMetrics::RecordAction(UserMetricsAction("CompactLocationBar_DragStar"),
browser()->profile());
// If there is a bookmark for the URL, add the bookmark drag data for it. We
// do this to ensure the bookmark is moved, rather than creating an new
// bookmark.
TabContents* tab = browser()->GetSelectedTabContents();
if (tab) {
Profile* profile = browser()->profile();
if (profile && profile->GetBookmarkModel()) {
const BookmarkNode* node = profile->GetBookmarkModel()->
GetMostRecentlyAddedNodeForURL(tab->GetURL());
if (node) {
BookmarkDragData bookmark_data(node);
bookmark_data.Write(profile, data);
}
}
drag_utils::SetURLAndDragImage(tab->GetURL(),
UTF16ToWideHack(tab->GetTitle()),
tab->GetFavIcon(),
data);
}
}
int CompactLocationBarView::GetDragOperations(views::View* sender,
const gfx::Point& p) {
DCHECK(sender == star_);
TabContents* tab = browser()->GetSelectedTabContents();
if (!tab || !tab->ShouldDisplayURL() || !tab->GetURL().is_valid()) {
return DragDropTypes::DRAG_NONE;
}
Profile* profile = browser()->profile();
if (profile && profile->GetBookmarkModel() &&
profile->GetBookmarkModel()->IsBookmarked(tab->GetURL())) {
return DragDropTypes::DRAG_MOVE | DragDropTypes::DRAG_COPY |
DragDropTypes::DRAG_LINK;
}
return DragDropTypes::DRAG_COPY | DragDropTypes::DRAG_LINK;
}
} // namespace chromeos
<commit_msg>Fix ChromeOS build (function was renamed)<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/chromeos/compact_location_bar_view.h"
#include <gtk/gtk.h>
#include <algorithm>
#include "app/l10n_util.h"
#include "app/drag_drop_types.h"
#include "app/resource_bundle.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_theme_provider.h"
#include "chrome/browser/chromeos/compact_location_bar_host.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/event_utils.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_star_toggle.h"
#include "gfx/canvas.h"
#include "gfx/point.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/controls/button/image_button.h"
#include "views/controls/native/native_view_host.h"
#include "views/drag_utils.h"
#include "views/widget/widget.h"
#include "views/window/window.h"
namespace chromeos {
const int kAutocompletePopupWidth = 700;
const int kDefaultLocationEntryWidth = 250;
const int kCompactLocationLeftMargin = 5;
const int kCompactLocationRightMargin = 10;
const int kEntryLeftMargin = 2;
// TODO(oshima): ToolbarView gets this from background image's height;
// Find out the right way, value for compact location bar.
const int kDefaultLocationBarHeight = 34;
const int kWidgetsSeparatorWidth = 2;
CompactLocationBarView::CompactLocationBarView(CompactLocationBarHost* host)
: DropdownBarView(host),
reload_(NULL),
browser_actions_(NULL),
star_(NULL) {
SetFocusable(true);
}
CompactLocationBarView::~CompactLocationBarView() {
}
////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarView public:
void CompactLocationBarView::SetFocusAndSelection() {
location_entry_->SetFocus();
location_entry_->SelectAll(true);
}
void CompactLocationBarView::Update(const TabContents* contents) {
location_entry_->Update(contents);
browser_actions_->RefreshBrowserActionViews();
}
////////////////////////////////////////////////////////////////////////////////
// CompactLocationBarView private:
Browser* CompactLocationBarView::browser() const {
return host()->browser_view()->browser();
}
void CompactLocationBarView::Init() {
ThemeProvider* tp = browser()->profile()->GetThemeProvider();
SkColor color = tp->GetColor(BrowserThemeProvider::COLOR_BUTTON_BACKGROUND);
SkBitmap* background = tp->GetBitmapNamed(IDR_THEME_BUTTON_BACKGROUND);
// Reload button.
reload_ = new views::ImageButton(this);
reload_->SetImageAlignment(views::ImageButton::ALIGN_CENTER,
views::ImageButton::ALIGN_MIDDLE);
reload_->set_tag(IDC_RELOAD);
reload_->SetTooltipText(l10n_util::GetString(IDS_TOOLTIP_RELOAD));
reload_->SetAccessibleName(l10n_util::GetString(IDS_ACCNAME_RELOAD));
reload_->SetID(VIEW_ID_RELOAD_BUTTON);
reload_->SetImage(views::CustomButton::BS_NORMAL,
tp->GetBitmapNamed(IDR_RELOAD));
reload_->SetImage(views::CustomButton::BS_HOT,
tp->GetBitmapNamed(IDR_RELOAD_H));
reload_->SetImage(views::CustomButton::BS_PUSHED,
tp->GetBitmapNamed(IDR_RELOAD_P));
reload_->SetBackground(color, background,
tp->GetBitmapNamed(IDR_BUTTON_MASK));
AddChildView(reload_);
// Location bar.
location_entry_.reset(new AutocompleteEditViewGtk(
this, browser()->toolbar_model(), browser()->profile(),
browser()->command_updater(), false, this));
location_entry_->Init();
location_entry_->Update(browser()->GetSelectedTabContents());
gtk_widget_show_all(location_entry_->GetNativeView());
gtk_widget_hide(location_entry_->GetNativeView());
location_entry_view_ = new views::NativeViewHost;
AddChildView(location_entry_view_);
location_entry_view_->set_focus_view(this);
location_entry_view_->Attach(location_entry_->GetNativeView());
star_ = new ToolbarStarToggle(this);
star_->SetDragController(this);
star_->set_profile(browser()->profile());
star_->set_host_view(this);
star_->set_bubble_positioner(this);
star_->Init();
AddChildView(star_);
location_entry_->Update(browser()->GetSelectedTabContents());
// Note: we tell the BrowserActionsContainer not to save its size because
// the main container is part of the ToolbarView, and we don't want them
// fighting. See http://code.google.com/p/chromium/issues/detail?id=38992
browser_actions_ = new BrowserActionsContainer(browser(), this, false);
AddChildView(browser_actions_);
}
////////////////////////////////////////////////////////////////////////////////
// views::View overrides:
gfx::Size CompactLocationBarView::GetPreferredSize() {
if (!reload_)
return gfx::Size(); // Not initialized yet, do nothing.
gfx::Size reload_size = reload_->GetPreferredSize();
gfx::Size star_size = star_->GetPreferredSize();
gfx::Size location_size = location_entry_view_->GetPreferredSize();
gfx::Size ba_size = browser_actions_->GetPreferredSize();
int width =
reload_size.width() + kEntryLeftMargin + star_size.width() +
std::max(kDefaultLocationEntryWidth,
location_entry_view_->GetPreferredSize().width()) +
ba_size.width() +
kCompactLocationLeftMargin +
kCompactLocationRightMargin;
return gfx::Size(width, kDefaultLocationBarHeight);
}
void CompactLocationBarView::Layout() {
if (!reload_)
return; // Not initialized yet, do nothing.
int cur_x = kCompactLocationLeftMargin;
gfx::Size reload_size = reload_->GetPreferredSize();
int reload_y = (height() - reload_size.height()) / 2;
reload_->SetBounds(cur_x, reload_y,
reload_size.width(), reload_size.height());
cur_x += reload_size.width() + kEntryLeftMargin;
gfx::Size star_size = star_->GetPreferredSize();
int star_y = (height() - star_size.height()) / 2;
star_->SetBounds(cur_x, star_y, star_size.width(), star_size.height());
cur_x += star_size.width();
gfx::Size ba_size = browser_actions_->GetPreferredSize();
int ba_y = (height() - ba_size.height()) / 2;
browser_actions_->SetBounds(
width() - ba_size.width(), ba_y, ba_size.width(), ba_size.height());
int location_entry_width = browser_actions_->x() - cur_x;
if (ba_size.IsEmpty()) {
// BrowserActionsContainer has its own margin on right.
// Use the our margin when if the browser action is empty.
location_entry_width -= kCompactLocationRightMargin;
}
// The location bar gets the rest of the space in the middle.
location_entry_view_->SetBounds(cur_x, 0, location_entry_width, height());
}
void CompactLocationBarView::Paint(gfx::Canvas* canvas) {
gfx::Rect lb = GetLocalBounds(true);
ThemeProvider* tp = GetThemeProvider();
gfx::Rect bounds;
host()->GetThemePosition(&bounds);
canvas->TileImageInt(*tp->GetBitmapNamed(IDR_THEME_TOOLBAR),
bounds.x(), bounds.y(), 0, 0, lb.width(), lb.height());
View::Paint(canvas);
}
void CompactLocationBarView::ViewHierarchyChanged(bool is_add, View* parent,
View* child) {
if (is_add && child == this)
Init();
}
void CompactLocationBarView::Focus() {
location_entry_->SetFocus();
}
////////////////////////////////////////////////////////////////////////////////
// views::ButtonListener overrides:
void CompactLocationBarView::ButtonPressed(views::Button* sender,
const views::Event& event) {
int id = sender->tag();
// Shift-clicking or Ctrl-clicking the reload button means we should
// ignore any cached content.
// TODO(avayvod): eliminate duplication of this logic in
// CompactLocationBarView.
if (id == IDC_RELOAD && (event.IsShiftDown() || event.IsControlDown()))
id = IDC_RELOAD_IGNORING_CACHE;
browser()->ExecuteCommandWithDisposition(
id, event_utils::DispositionFromEventFlags(sender->mouse_event_flags()));
}
////////////////////////////////////////////////////////////////////////////////
// AutocompleteEditController overrides:
void CompactLocationBarView::OnAutocompleteAccept(
const GURL& url,
WindowOpenDisposition disposition,
PageTransition::Type transition,
const GURL& alternate_nav_url) {
browser()->OpenURL(url, GURL(), disposition, transition);
clb_host()->StartAutoHideTimer();
}
void CompactLocationBarView::OnChanged() {
// Other one does "DoLayout" here.
}
void CompactLocationBarView::OnKillFocus() {
host()->UnregisterAccelerators();
}
void CompactLocationBarView::OnSetFocus() {
views::FocusManager* focus_manager = GetFocusManager();
if (!focus_manager) {
NOTREACHED();
return;
}
focus_manager->SetFocusedView(this);
host()->RegisterAccelerators();
}
void CompactLocationBarView::OnInputInProgress(bool in_progress) {
}
SkBitmap CompactLocationBarView::GetFavIcon() const {
return SkBitmap();
}
std::wstring CompactLocationBarView::GetTitle() const {
return std::wstring();
}
////////////////////////////////////////////////////////////////////////////////
// BubblePositioner overrides:
gfx::Rect CompactLocationBarView::GetLocationStackBounds() const {
gfx::Point lower_left(0, height());
ConvertPointToScreen(this, &lower_left);
gfx::Rect popup = gfx::Rect(lower_left.x(), lower_left.y(),
kAutocompletePopupWidth, 0);
return popup.AdjustToFit(GetWidget()->GetWindow()->GetBounds());
}
////////////////////////////////////////////////////////////////////////////////
// views::DragController overrides:
void CompactLocationBarView::WriteDragData(views::View* sender,
const gfx::Point& press_pt,
OSExchangeData* data) {
DCHECK(GetDragOperations(sender, press_pt) != DragDropTypes::DRAG_NONE);
UserMetrics::RecordAction(UserMetricsAction("CompactLocationBar_DragStar"),
browser()->profile());
// If there is a bookmark for the URL, add the bookmark drag data for it. We
// do this to ensure the bookmark is moved, rather than creating an new
// bookmark.
TabContents* tab = browser()->GetSelectedTabContents();
if (tab) {
Profile* profile = browser()->profile();
if (profile && profile->GetBookmarkModel()) {
const BookmarkNode* node = profile->GetBookmarkModel()->
GetMostRecentlyAddedNodeForURL(tab->GetURL());
if (node) {
BookmarkDragData bookmark_data(node);
bookmark_data.Write(profile, data);
}
}
drag_utils::SetURLAndDragImage(tab->GetURL(),
UTF16ToWideHack(tab->GetTitle()),
tab->GetFavIcon(),
data);
}
}
int CompactLocationBarView::GetDragOperations(views::View* sender,
const gfx::Point& p) {
DCHECK(sender == star_);
TabContents* tab = browser()->GetSelectedTabContents();
if (!tab || !tab->ShouldDisplayURL() || !tab->GetURL().is_valid()) {
return DragDropTypes::DRAG_NONE;
}
Profile* profile = browser()->profile();
if (profile && profile->GetBookmarkModel() &&
profile->GetBookmarkModel()->IsBookmarked(tab->GetURL())) {
return DragDropTypes::DRAG_MOVE | DragDropTypes::DRAG_COPY |
DragDropTypes::DRAG_LINK;
}
return DragDropTypes::DRAG_COPY | DragDropTypes::DRAG_LINK;
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/download/download_file_manager.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_file.h"
#include "content/browser/download/download_create_info.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/download/download_manager_delegate.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
namespace {
// Throttle updates to the UI thread so that a fast moving download doesn't
// cause it to become unresponsive (in milliseconds).
const int kUpdatePeriodMs = 500;
} // namespace
DownloadFileManager::DownloadFileManager(ResourceDispatcherHost* rdh)
: resource_dispatcher_host_(rdh) {
}
DownloadFileManager::~DownloadFileManager() {
DCHECK(downloads_.empty());
}
void DownloadFileManager::Shutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &DownloadFileManager::OnShutdown));
}
void DownloadFileManager::OnShutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
StopUpdateTimer();
STLDeleteValues(&downloads_);
}
void DownloadFileManager::CreateDownloadFile(DownloadCreateInfo* info,
DownloadManager* download_manager,
bool get_hash) {
DCHECK(info);
VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
// Life of |info| ends here. No more references to it after this method.
scoped_ptr<DownloadCreateInfo> infop(info);
scoped_ptr<DownloadFile>
download_file(new DownloadFile(info, download_manager));
if (net::OK != download_file->Initialize(get_hash)) {
info->request_handle.CancelRequest();
return;
}
DownloadId global_id(download_manager, info->download_id);
DCHECK(GetDownloadFile(global_id) == NULL);
downloads_[global_id] = download_file.release();
// The file is now ready, we can un-pause the request and start saving data.
info->request_handle.ResumeRequest();
StartUpdateTimer();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(download_manager,
&DownloadManager::StartDownload, info->download_id));
}
DownloadFile* DownloadFileManager::GetDownloadFile(DownloadId global_id) {
DownloadFileMap::iterator it = downloads_.find(global_id);
return it == downloads_.end() ? NULL : it->second;
}
void DownloadFileManager::StartUpdateTimer() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!update_timer_.IsRunning()) {
update_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kUpdatePeriodMs),
this, &DownloadFileManager::UpdateInProgressDownloads);
}
}
void DownloadFileManager::StopUpdateTimer() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
update_timer_.Stop();
}
void DownloadFileManager::UpdateInProgressDownloads() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
for (DownloadFileMap::iterator i = downloads_.begin();
i != downloads_.end(); ++i) {
DownloadId global_id = i->first;
DownloadFile* download_file = i->second;
DownloadManager* manager = download_file->GetDownloadManager();
if (manager) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(manager, &DownloadManager::UpdateDownload,
global_id.local(), download_file->bytes_so_far()));
}
}
}
void DownloadFileManager::StartDownload(DownloadCreateInfo* info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(info);
DownloadManager* manager = info->request_handle.GetDownloadManager();
if (!manager) {
info->request_handle.CancelRequest();
delete info;
return;
}
// TODO(phajdan.jr): fix the duplication of path info below.
info->path = info->save_info.file_path;
manager->CreateDownloadItem(info);
bool hash_needed = manager->delegate()->GenerateFileHash();
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &DownloadFileManager::CreateDownloadFile,
info, make_scoped_refptr(manager), hash_needed));
}
// We don't forward an update to the UI thread here, since we want to throttle
// the UI update rate via a periodic timer. If the user has cancelled the
// download (in the UI thread), we may receive a few more updates before the IO
// thread gets the cancel message: we just delete the data since the
// DownloadFile has been deleted.
void DownloadFileManager::UpdateDownload(
DownloadId global_id, DownloadBuffer* buffer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
std::vector<DownloadBuffer::Contents> contents;
{
base::AutoLock auto_lock(buffer->lock);
contents.swap(buffer->contents);
}
DownloadFile* download_file = GetDownloadFile(global_id);
bool had_error = false;
for (size_t i = 0; i < contents.size(); ++i) {
net::IOBuffer* data = contents[i].first;
const int data_len = contents[i].second;
if (!had_error && download_file) {
net::Error write_result =
download_file->AppendDataToFile(data->data(), data_len);
if (write_result != net::OK) {
// Write failed: interrupt the download.
DownloadManager* download_manager = download_file->GetDownloadManager();
had_error = true;
int64 bytes_downloaded = download_file->bytes_so_far();
// Calling this here in case we get more data, to avoid
// processing data after an error. That could lead to
// files that are corrupted if the later processing succeeded.
CancelDownload(global_id);
download_file = NULL; // Was deleted in |CancelDownload|.
if (download_manager) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
bytes_downloaded,
write_result));
}
}
}
data->Release();
}
}
void DownloadFileManager::OnResponseCompleted(
DownloadId global_id,
DownloadBuffer* buffer,
net::Error net_error,
const std::string& security_info) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " net_error = " << net_error
<< " security_info = \"" << security_info << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
delete buffer;
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
download_file->Finish();
DownloadManager* download_manager = download_file->GetDownloadManager();
if (!download_manager) {
CancelDownload(global_id);
return;
}
std::string hash;
if (!download_file->GetSha256Hash(&hash))
hash.clear();
// ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
// advertise a larger Content-Length than the amount of bytes in the message
// body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
// and Safari 5.0.4 - treat the download as complete in this case, so we
// follow their lead.
if (net_error == net::OK || net_error == net::ERR_CONNECTION_CLOSED) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnResponseCompleted,
global_id.local(),
download_file->bytes_so_far(),
hash));
} else {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
download_file->bytes_so_far(),
net_error));
}
// We need to keep the download around until the UI thread has finalized
// the name.
}
// This method will be sent via a user action, or shutdown on the UI thread, and
// run on the download thread. Since this message has been sent from the UI
// thread, the download may have already completed and won't exist in our map.
void DownloadFileManager::CancelDownload(DownloadId global_id) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id;
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFileMap::iterator it = downloads_.find(global_id);
if (it == downloads_.end())
return;
DownloadFile* download_file = it->second;
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
download_file->Cancel();
EraseDownload(global_id);
}
void DownloadFileManager::CompleteDownload(DownloadId global_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
download_file->Detach();
EraseDownload(global_id);
}
void DownloadFileManager::OnDownloadManagerShutdown(DownloadManager* manager) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(manager);
std::set<DownloadFile*> to_remove;
for (DownloadFileMap::iterator i = downloads_.begin();
i != downloads_.end(); ++i) {
DownloadFile* download_file = i->second;
if (download_file->GetDownloadManager() == manager) {
download_file->CancelDownloadRequest();
to_remove.insert(download_file);
}
}
for (std::set<DownloadFile*>::iterator i = to_remove.begin();
i != to_remove.end(); ++i) {
downloads_.erase(DownloadId((*i)->GetDownloadManager(), (*i)->id()));
delete *i;
}
}
// Actions from the UI thread and run on the download thread
// The DownloadManager in the UI thread has provided an intermediate .crdownload
// name for the download specified by 'id'. Rename the in progress download.
//
// There are 2 possible rename cases where this method can be called:
// 1. tmp -> foo.crdownload (not final, safe)
// 2. tmp-> Unconfirmed.xxx.crdownload (not final, dangerous)
void DownloadFileManager::RenameInProgressDownloadFile(
DownloadId global_id, const FilePath& full_path) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " full_path = \"" << full_path.value() << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
net::Error rename_error = download_file->Rename(full_path);
if (net::OK != rename_error) {
// Error. Between the time the UI thread generated 'full_path' to the time
// this code runs, something happened that prevents us from renaming.
CancelDownloadOnRename(global_id, rename_error);
}
}
// The DownloadManager in the UI thread has provided a final name for the
// download specified by 'id'. Rename the download that's in the process
// of completing.
//
// There are 2 possible rename cases where this method can be called:
// 1. foo.crdownload -> foo (final, safe)
// 2. Unconfirmed.xxx.crdownload -> xxx (final, validated)
void DownloadFileManager::RenameCompletingDownloadFile(
DownloadId global_id,
const FilePath& full_path,
bool overwrite_existing_file) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " overwrite_existing_file = " << overwrite_existing_file
<< " full_path = \"" << full_path.value() << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
DCHECK(download_file->GetDownloadManager());
DownloadManager* download_manager = download_file->GetDownloadManager();
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
int uniquifier = 0;
FilePath new_path = full_path;
if (!overwrite_existing_file) {
// Make our name unique at this point, as if a dangerous file is
// downloading and a 2nd download is started for a file with the same
// name, they would have the same path. This is because we uniquify
// the name on download start, and at that time the first file does
// not exists yet, so the second file gets the same name.
// This should not happen in the SAFE case, and we check for that in the UI
// thread.
uniquifier = DownloadFile::GetUniquePathNumber(new_path);
if (uniquifier > 0) {
DownloadFile::AppendNumberToPath(&new_path, uniquifier);
}
}
// Rename the file, overwriting if necessary.
net::Error rename_error = download_file->Rename(full_path);
if (net::OK != rename_error) {
// Error. Between the time the UI thread generated 'full_path' to the time
// this code runs, something happened that prevents us from renaming.
CancelDownloadOnRename(global_id, rename_error);
return;
}
#if defined(OS_MACOSX)
// Done here because we only want to do this once; see
// http://crbug.com/13120 for details.
download_file->AnnotateWithSourceInformation();
#endif
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(
download_manager, &DownloadManager::OnDownloadRenamedToFinalName,
global_id.local(), new_path, uniquifier));
}
// Called only from RenameInProgressDownloadFile and
// RenameCompletingDownloadFile on the FILE thread.
void DownloadFileManager::CancelDownloadOnRename(
DownloadId global_id, net::Error rename_error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
DownloadManager* download_manager = download_file->GetDownloadManager();
if (!download_manager) {
// Without a download manager, we can't cancel the request normally, so we
// need to do it here. The normal path will also update the download
// history before canceling the request.
download_file->CancelDownloadRequest();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
download_file->bytes_so_far(),
rename_error));
}
void DownloadFileManager::EraseDownload(DownloadId global_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
downloads_.erase(global_id);
delete download_file;
if (downloads_.empty())
StopUpdateTimer();
}
<commit_msg>Uniquified path needs to be used to rename the file for dangerous types.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/download/download_file_manager.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_file.h"
#include "content/browser/download/download_create_info.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/download/download_manager_delegate.h"
#include "content/browser/renderer_host/resource_dispatcher_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "googleurl/src/gurl.h"
#include "net/base/io_buffer.h"
namespace {
// Throttle updates to the UI thread so that a fast moving download doesn't
// cause it to become unresponsive (in milliseconds).
const int kUpdatePeriodMs = 500;
} // namespace
DownloadFileManager::DownloadFileManager(ResourceDispatcherHost* rdh)
: resource_dispatcher_host_(rdh) {
}
DownloadFileManager::~DownloadFileManager() {
DCHECK(downloads_.empty());
}
void DownloadFileManager::Shutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &DownloadFileManager::OnShutdown));
}
void DownloadFileManager::OnShutdown() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
StopUpdateTimer();
STLDeleteValues(&downloads_);
}
void DownloadFileManager::CreateDownloadFile(DownloadCreateInfo* info,
DownloadManager* download_manager,
bool get_hash) {
DCHECK(info);
VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
// Life of |info| ends here. No more references to it after this method.
scoped_ptr<DownloadCreateInfo> infop(info);
scoped_ptr<DownloadFile>
download_file(new DownloadFile(info, download_manager));
if (net::OK != download_file->Initialize(get_hash)) {
info->request_handle.CancelRequest();
return;
}
DownloadId global_id(download_manager, info->download_id);
DCHECK(GetDownloadFile(global_id) == NULL);
downloads_[global_id] = download_file.release();
// The file is now ready, we can un-pause the request and start saving data.
info->request_handle.ResumeRequest();
StartUpdateTimer();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(download_manager,
&DownloadManager::StartDownload, info->download_id));
}
DownloadFile* DownloadFileManager::GetDownloadFile(DownloadId global_id) {
DownloadFileMap::iterator it = downloads_.find(global_id);
return it == downloads_.end() ? NULL : it->second;
}
void DownloadFileManager::StartUpdateTimer() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!update_timer_.IsRunning()) {
update_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(kUpdatePeriodMs),
this, &DownloadFileManager::UpdateInProgressDownloads);
}
}
void DownloadFileManager::StopUpdateTimer() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
update_timer_.Stop();
}
void DownloadFileManager::UpdateInProgressDownloads() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
for (DownloadFileMap::iterator i = downloads_.begin();
i != downloads_.end(); ++i) {
DownloadId global_id = i->first;
DownloadFile* download_file = i->second;
DownloadManager* manager = download_file->GetDownloadManager();
if (manager) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(manager, &DownloadManager::UpdateDownload,
global_id.local(), download_file->bytes_so_far()));
}
}
}
void DownloadFileManager::StartDownload(DownloadCreateInfo* info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(info);
DownloadManager* manager = info->request_handle.GetDownloadManager();
if (!manager) {
info->request_handle.CancelRequest();
delete info;
return;
}
// TODO(phajdan.jr): fix the duplication of path info below.
info->path = info->save_info.file_path;
manager->CreateDownloadItem(info);
bool hash_needed = manager->delegate()->GenerateFileHash();
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(this, &DownloadFileManager::CreateDownloadFile,
info, make_scoped_refptr(manager), hash_needed));
}
// We don't forward an update to the UI thread here, since we want to throttle
// the UI update rate via a periodic timer. If the user has cancelled the
// download (in the UI thread), we may receive a few more updates before the IO
// thread gets the cancel message: we just delete the data since the
// DownloadFile has been deleted.
void DownloadFileManager::UpdateDownload(
DownloadId global_id, DownloadBuffer* buffer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
std::vector<DownloadBuffer::Contents> contents;
{
base::AutoLock auto_lock(buffer->lock);
contents.swap(buffer->contents);
}
DownloadFile* download_file = GetDownloadFile(global_id);
bool had_error = false;
for (size_t i = 0; i < contents.size(); ++i) {
net::IOBuffer* data = contents[i].first;
const int data_len = contents[i].second;
if (!had_error && download_file) {
net::Error write_result =
download_file->AppendDataToFile(data->data(), data_len);
if (write_result != net::OK) {
// Write failed: interrupt the download.
DownloadManager* download_manager = download_file->GetDownloadManager();
had_error = true;
int64 bytes_downloaded = download_file->bytes_so_far();
// Calling this here in case we get more data, to avoid
// processing data after an error. That could lead to
// files that are corrupted if the later processing succeeded.
CancelDownload(global_id);
download_file = NULL; // Was deleted in |CancelDownload|.
if (download_manager) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
bytes_downloaded,
write_result));
}
}
}
data->Release();
}
}
void DownloadFileManager::OnResponseCompleted(
DownloadId global_id,
DownloadBuffer* buffer,
net::Error net_error,
const std::string& security_info) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " net_error = " << net_error
<< " security_info = \"" << security_info << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
delete buffer;
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
download_file->Finish();
DownloadManager* download_manager = download_file->GetDownloadManager();
if (!download_manager) {
CancelDownload(global_id);
return;
}
std::string hash;
if (!download_file->GetSha256Hash(&hash))
hash.clear();
// ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
// advertise a larger Content-Length than the amount of bytes in the message
// body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
// and Safari 5.0.4 - treat the download as complete in this case, so we
// follow their lead.
if (net_error == net::OK || net_error == net::ERR_CONNECTION_CLOSED) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnResponseCompleted,
global_id.local(),
download_file->bytes_so_far(),
hash));
} else {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
NewRunnableMethod(
download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
download_file->bytes_so_far(),
net_error));
}
// We need to keep the download around until the UI thread has finalized
// the name.
}
// This method will be sent via a user action, or shutdown on the UI thread, and
// run on the download thread. Since this message has been sent from the UI
// thread, the download may have already completed and won't exist in our map.
void DownloadFileManager::CancelDownload(DownloadId global_id) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id;
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFileMap::iterator it = downloads_.find(global_id);
if (it == downloads_.end())
return;
DownloadFile* download_file = it->second;
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
download_file->Cancel();
EraseDownload(global_id);
}
void DownloadFileManager::CompleteDownload(DownloadId global_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
download_file->Detach();
EraseDownload(global_id);
}
void DownloadFileManager::OnDownloadManagerShutdown(DownloadManager* manager) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DCHECK(manager);
std::set<DownloadFile*> to_remove;
for (DownloadFileMap::iterator i = downloads_.begin();
i != downloads_.end(); ++i) {
DownloadFile* download_file = i->second;
if (download_file->GetDownloadManager() == manager) {
download_file->CancelDownloadRequest();
to_remove.insert(download_file);
}
}
for (std::set<DownloadFile*>::iterator i = to_remove.begin();
i != to_remove.end(); ++i) {
downloads_.erase(DownloadId((*i)->GetDownloadManager(), (*i)->id()));
delete *i;
}
}
// Actions from the UI thread and run on the download thread
// The DownloadManager in the UI thread has provided an intermediate .crdownload
// name for the download specified by 'id'. Rename the in progress download.
//
// There are 2 possible rename cases where this method can be called:
// 1. tmp -> foo.crdownload (not final, safe)
// 2. tmp-> Unconfirmed.xxx.crdownload (not final, dangerous)
void DownloadFileManager::RenameInProgressDownloadFile(
DownloadId global_id, const FilePath& full_path) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " full_path = \"" << full_path.value() << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
net::Error rename_error = download_file->Rename(full_path);
if (net::OK != rename_error) {
// Error. Between the time the UI thread generated 'full_path' to the time
// this code runs, something happened that prevents us from renaming.
CancelDownloadOnRename(global_id, rename_error);
}
}
// The DownloadManager in the UI thread has provided a final name for the
// download specified by 'id'. Rename the download that's in the process
// of completing.
//
// There are 2 possible rename cases where this method can be called:
// 1. foo.crdownload -> foo (final, safe)
// 2. Unconfirmed.xxx.crdownload -> xxx (final, validated)
void DownloadFileManager::RenameCompletingDownloadFile(
DownloadId global_id,
const FilePath& full_path,
bool overwrite_existing_file) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " overwrite_existing_file = " << overwrite_existing_file
<< " full_path = \"" << full_path.value() << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
DCHECK(download_file->GetDownloadManager());
DownloadManager* download_manager = download_file->GetDownloadManager();
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
int uniquifier = 0;
FilePath new_path = full_path;
if (!overwrite_existing_file) {
// Make our name unique at this point, as if a dangerous file is
// downloading and a 2nd download is started for a file with the same
// name, they would have the same path. This is because we uniquify
// the name on download start, and at that time the first file does
// not exists yet, so the second file gets the same name.
// This should not happen in the SAFE case, and we check for that in the UI
// thread.
uniquifier = DownloadFile::GetUniquePathNumber(new_path);
if (uniquifier > 0) {
DownloadFile::AppendNumberToPath(&new_path, uniquifier);
}
}
// Rename the file, overwriting if necessary.
net::Error rename_error = download_file->Rename(new_path);
if (net::OK != rename_error) {
// Error. Between the time the UI thread generated 'full_path' to the time
// this code runs, something happened that prevents us from renaming.
CancelDownloadOnRename(global_id, rename_error);
return;
}
#if defined(OS_MACOSX)
// Done here because we only want to do this once; see
// http://crbug.com/13120 for details.
download_file->AnnotateWithSourceInformation();
#endif
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(
download_manager, &DownloadManager::OnDownloadRenamedToFinalName,
global_id.local(), new_path, uniquifier));
}
// Called only from RenameInProgressDownloadFile and
// RenameCompletingDownloadFile on the FILE thread.
void DownloadFileManager::CancelDownloadOnRename(
DownloadId global_id, net::Error rename_error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
DownloadManager* download_manager = download_file->GetDownloadManager();
if (!download_manager) {
// Without a download manager, we can't cancel the request normally, so we
// need to do it here. The normal path will also update the download
// history before canceling the request.
download_file->CancelDownloadRequest();
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
NewRunnableMethod(download_manager,
&DownloadManager::OnDownloadError,
global_id.local(),
download_file->bytes_so_far(),
rename_error));
}
void DownloadFileManager::EraseDownload(DownloadId global_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!ContainsKey(downloads_, global_id))
return;
DownloadFile* download_file = downloads_[global_id];
VLOG(20) << " " << __FUNCTION__ << "()"
<< " id = " << global_id
<< " download_file = " << download_file->DebugString();
downloads_.erase(global_id);
delete download_file;
if (downloads_.empty())
StopUpdateTimer();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/system_key_event_listener.h"
// TODO(saintlou): should we handle this define in gyp even if only used once?
#define XK_MISCELLANY 1
#include <X11/keysymdef.h>
#include <X11/XF86keysym.h>
#include <X11/XKBlib.h>
#include "chrome/browser/accessibility_events.h"
#include "chrome/browser/chromeos/audio_handler.h"
#include "chrome/browser/chromeos/brightness_bubble.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/power_manager_client.h"
#include "chrome/browser/chromeos/input_method/hotkey_manager.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/volume_bubble.h"
#include "content/browser/user_metrics.h"
#include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h"
#include "ui/base/x/x11_util.h"
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
#include "base/message_pump_x.h"
#endif
namespace chromeos {
namespace {
// Percent by which the volume should be changed when a volume key is pressed.
const double kStepPercentage = 4.0;
// Percent to which the volume should be set when the "volume up" key is pressed
// while we're muted and have the volume set to 0. See
// http://crosbug.com/13618.
const double kVolumePercentOnVolumeUpWhileMuted = 25.0;
static SystemKeyEventListener* g_system_key_event_listener = NULL;
} // namespace
// static
void SystemKeyEventListener::Initialize() {
CHECK(!g_system_key_event_listener);
g_system_key_event_listener = new SystemKeyEventListener();
}
// static
void SystemKeyEventListener::Shutdown() {
// We may call Shutdown without calling Initialize, e.g. if we exit early.
if (g_system_key_event_listener) {
delete g_system_key_event_listener;
g_system_key_event_listener = NULL;
}
}
// static
SystemKeyEventListener* SystemKeyEventListener::GetInstance() {
VLOG_IF(1, !g_system_key_event_listener)
<< "SystemKeyEventListener::GetInstance() with NULL global instance.";
return g_system_key_event_listener;
}
SystemKeyEventListener::SystemKeyEventListener()
: stopped_(false),
caps_lock_is_on_(input_method::XKeyboard::CapsLockIsEnabled()),
xkb_event_base_(0) {
Display* display = ui::GetXDisplay();
key_brightness_down_ = XKeysymToKeycode(display,
XF86XK_MonBrightnessDown);
key_brightness_up_ = XKeysymToKeycode(display, XF86XK_MonBrightnessUp);
key_volume_mute_ = XKeysymToKeycode(display, XF86XK_AudioMute);
key_volume_down_ = XKeysymToKeycode(display, XF86XK_AudioLowerVolume);
key_volume_up_ = XKeysymToKeycode(display, XF86XK_AudioRaiseVolume);
key_f6_ = XKeysymToKeycode(display, XK_F6);
key_f7_ = XKeysymToKeycode(display, XK_F7);
key_f8_ = XKeysymToKeycode(display, XK_F8);
key_f9_ = XKeysymToKeycode(display, XK_F9);
key_f10_ = XKeysymToKeycode(display, XK_F10);
key_left_shift_ = XKeysymToKeycode(display, XK_Shift_L);
key_right_shift_ = XKeysymToKeycode(display, XK_Shift_R);
if (key_brightness_down_)
GrabKey(key_brightness_down_, 0);
if (key_brightness_up_)
GrabKey(key_brightness_up_, 0);
if (key_volume_mute_)
GrabKey(key_volume_mute_, 0);
if (key_volume_down_)
GrabKey(key_volume_down_, 0);
if (key_volume_up_)
GrabKey(key_volume_up_, 0);
GrabKey(key_f6_, 0);
GrabKey(key_f7_, 0);
GrabKey(key_f8_, 0);
GrabKey(key_f9_, 0);
GrabKey(key_f10_, 0);
int xkb_major_version = XkbMajorVersion;
int xkb_minor_version = XkbMinorVersion;
if (!XkbQueryExtension(display,
NULL, // opcode_return
&xkb_event_base_,
NULL, // error_return
&xkb_major_version,
&xkb_minor_version)) {
LOG(WARNING) << "Could not query Xkb extension";
}
if (!XkbSelectEvents(display, XkbUseCoreKbd,
XkbStateNotifyMask,
XkbStateNotifyMask)) {
LOG(WARNING) << "Could not install Xkb Indicator observer";
}
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
MessageLoopForUI::current()->AddObserver(this);
#else
gdk_window_add_filter(NULL, GdkEventFilter, this);
#endif
}
SystemKeyEventListener::~SystemKeyEventListener() {
Stop();
}
void SystemKeyEventListener::Stop() {
if (stopped_)
return;
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
MessageLoopForUI::current()->RemoveObserver(this);
#else
gdk_window_remove_filter(NULL, GdkEventFilter, this);
#endif
stopped_ = true;
}
AudioHandler* SystemKeyEventListener::GetAudioHandler() const {
AudioHandler* audio_handler = AudioHandler::GetInstance();
if (!audio_handler || !audio_handler->IsInitialized())
return NULL;
return audio_handler;
}
void SystemKeyEventListener::AddCapsLockObserver(CapsLockObserver* observer) {
caps_lock_observers_.AddObserver(observer);
}
void SystemKeyEventListener::RemoveCapsLockObserver(
CapsLockObserver* observer) {
caps_lock_observers_.RemoveObserver(observer);
}
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
base::EventStatus SystemKeyEventListener::WillProcessEvent(
const base::NativeEvent& event) {
return ProcessedXEvent(event) ? base::EVENT_HANDLED : base::EVENT_CONTINUE;
}
void SystemKeyEventListener::DidProcessEvent(const base::NativeEvent& event) {
}
#else // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
// static
GdkFilterReturn SystemKeyEventListener::GdkEventFilter(GdkXEvent* gxevent,
GdkEvent* gevent,
gpointer data) {
SystemKeyEventListener* listener = static_cast<SystemKeyEventListener*>(data);
XEvent* xevent = static_cast<XEvent*>(gxevent);
return listener->ProcessedXEvent(xevent) ? GDK_FILTER_REMOVE
: GDK_FILTER_CONTINUE;
}
#endif // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
void SystemKeyEventListener::GrabKey(int32 key, uint32 mask) {
uint32 num_lock_mask = Mod2Mask;
uint32 caps_lock_mask = LockMask;
Display* display = ui::GetXDisplay();
Window root = DefaultRootWindow(display);
XGrabKey(display, key, mask, root, True, GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | caps_lock_mask, root, True,
GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | num_lock_mask, root, True,
GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | caps_lock_mask | num_lock_mask, root,
True, GrabModeAsync, GrabModeAsync);
}
void SystemKeyEventListener::OnBrightnessDown() {
DBusThreadManager::Get()->power_manager_client()->
DecreaseScreenBrightness(true);
}
void SystemKeyEventListener::OnBrightnessUp() {
DBusThreadManager::Get()->power_manager_client()->
IncreaseScreenBrightness();
}
void SystemKeyEventListener::OnVolumeMute() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
// Always muting (and not toggling) as per final decision on
// http://crosbug.com/3751
audio_handler->SetMuted(true);
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnVolumeDown() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
if (audio_handler->IsMuted())
audio_handler->SetVolumePercent(0.0);
else
audio_handler->AdjustVolumeByPercent(-kStepPercentage);
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnVolumeUp() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
if (audio_handler->IsMuted()) {
audio_handler->SetMuted(false);
if (audio_handler->GetVolumePercent() <= 0.1) // float comparison
audio_handler->SetVolumePercent(kVolumePercentOnVolumeUpWhileMuted);
} else {
audio_handler->AdjustVolumeByPercent(kStepPercentage);
}
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnCapsLock(bool enabled) {
FOR_EACH_OBSERVER(
CapsLockObserver, caps_lock_observers_, OnCapsLockChange(enabled));
}
void SystemKeyEventListener::ShowVolumeBubble() {
AudioHandler* audio_handler = GetAudioHandler();
if (audio_handler) {
VolumeBubble::GetInstance()->ShowBubble(
audio_handler->GetVolumePercent(),
!audio_handler->IsMuted());
}
BrightnessBubble::GetInstance()->HideBubble();
}
bool SystemKeyEventListener::ProcessedXEvent(XEvent* xevent) {
if (xevent->type == KeyPress || xevent->type == KeyRelease) {
// Change the current keyboard layout (or input method) if xevent is one of
// the input method hotkeys.
input_method::HotkeyManager* hotkey_manager =
input_method::InputMethodManager::GetInstance()->GetHotkeyManager();
if (hotkey_manager->FilterKeyEvent(*xevent)) {
return true;
}
}
if (xevent->type == xkb_event_base_) {
XkbEvent* xkey_event = reinterpret_cast<XkbEvent*>(xevent);
if (xkey_event->any.xkb_type == XkbStateNotify) {
const bool new_lock_state = (xkey_event->state.locked_mods) & LockMask;
if (caps_lock_is_on_ != new_lock_state) {
caps_lock_is_on_ = new_lock_state;
OnCapsLock(caps_lock_is_on_);
}
return true;
}
} else if (xevent->type == KeyPress) {
const int32 keycode = xevent->xkey.keycode;
if (keycode) {
// Toggle Caps Lock if both Shift keys are pressed simultaneously.
if (keycode == key_left_shift_ || keycode == key_right_shift_) {
const bool other_shift_is_held = (xevent->xkey.state & ShiftMask);
const bool other_mods_are_held =
(xevent->xkey.state & ~(ShiftMask | LockMask));
if (other_shift_is_held && !other_mods_are_held)
input_method::XKeyboard::SetCapsLockEnabled(!caps_lock_is_on_);
}
// Only doing non-Alt/Shift/Ctrl modified keys
if (!(xevent->xkey.state & (Mod1Mask | ShiftMask | ControlMask))) {
if (keycode == key_f6_ || keycode == key_brightness_down_) {
if (keycode == key_f6_)
UserMetrics::RecordAction(
UserMetricsAction("Accel_BrightnessDown_F6"));
OnBrightnessDown();
return true;
} else if (keycode == key_f7_ || keycode == key_brightness_up_) {
if (keycode == key_f7_)
UserMetrics::RecordAction(
UserMetricsAction("Accel_BrightnessUp_F7"));
OnBrightnessUp();
return true;
} else if (keycode == key_f8_ || keycode == key_volume_mute_) {
if (keycode == key_f8_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeMute_F8"));
OnVolumeMute();
return true;
} else if (keycode == key_f9_ || keycode == key_volume_down_) {
if (keycode == key_f9_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeDown_F9"));
OnVolumeDown();
return true;
} else if (keycode == key_f10_ || keycode == key_volume_up_) {
if (keycode == key_f10_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeUp_F10"));
OnVolumeUp();
return true;
}
}
}
}
return false;
}
} // namespace chromeos
<commit_msg>Toggle Caps Lock on pressing both Shift keys even if Num Lock is enabled.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/system_key_event_listener.h"
// TODO(saintlou): should we handle this define in gyp even if only used once?
#define XK_MISCELLANY 1
#include <X11/keysymdef.h>
#include <X11/XF86keysym.h>
#include <X11/XKBlib.h>
#include "chrome/browser/accessibility_events.h"
#include "chrome/browser/chromeos/audio_handler.h"
#include "chrome/browser/chromeos/brightness_bubble.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/power_manager_client.h"
#include "chrome/browser/chromeos/input_method/hotkey_manager.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/volume_bubble.h"
#include "content/browser/user_metrics.h"
#include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h"
#include "ui/base/x/x11_util.h"
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
#include "base/message_pump_x.h"
#endif
namespace chromeos {
namespace {
// Percent by which the volume should be changed when a volume key is pressed.
const double kStepPercentage = 4.0;
// Percent to which the volume should be set when the "volume up" key is pressed
// while we're muted and have the volume set to 0. See
// http://crosbug.com/13618.
const double kVolumePercentOnVolumeUpWhileMuted = 25.0;
// In ProcessedXEvent(), we should check only Alt, Shift, Control, and Caps Lock
// modifiers, and should ignore Num Lock, Super, Hyper etc. See
// http://crosbug.com/21842.
const unsigned int kSupportedModifiers =
Mod1Mask | ShiftMask | ControlMask | LockMask;
static SystemKeyEventListener* g_system_key_event_listener = NULL;
} // namespace
// static
void SystemKeyEventListener::Initialize() {
CHECK(!g_system_key_event_listener);
g_system_key_event_listener = new SystemKeyEventListener();
}
// static
void SystemKeyEventListener::Shutdown() {
// We may call Shutdown without calling Initialize, e.g. if we exit early.
if (g_system_key_event_listener) {
delete g_system_key_event_listener;
g_system_key_event_listener = NULL;
}
}
// static
SystemKeyEventListener* SystemKeyEventListener::GetInstance() {
VLOG_IF(1, !g_system_key_event_listener)
<< "SystemKeyEventListener::GetInstance() with NULL global instance.";
return g_system_key_event_listener;
}
SystemKeyEventListener::SystemKeyEventListener()
: stopped_(false),
caps_lock_is_on_(input_method::XKeyboard::CapsLockIsEnabled()),
xkb_event_base_(0) {
Display* display = ui::GetXDisplay();
key_brightness_down_ = XKeysymToKeycode(display,
XF86XK_MonBrightnessDown);
key_brightness_up_ = XKeysymToKeycode(display, XF86XK_MonBrightnessUp);
key_volume_mute_ = XKeysymToKeycode(display, XF86XK_AudioMute);
key_volume_down_ = XKeysymToKeycode(display, XF86XK_AudioLowerVolume);
key_volume_up_ = XKeysymToKeycode(display, XF86XK_AudioRaiseVolume);
key_f6_ = XKeysymToKeycode(display, XK_F6);
key_f7_ = XKeysymToKeycode(display, XK_F7);
key_f8_ = XKeysymToKeycode(display, XK_F8);
key_f9_ = XKeysymToKeycode(display, XK_F9);
key_f10_ = XKeysymToKeycode(display, XK_F10);
key_left_shift_ = XKeysymToKeycode(display, XK_Shift_L);
key_right_shift_ = XKeysymToKeycode(display, XK_Shift_R);
if (key_brightness_down_)
GrabKey(key_brightness_down_, 0);
if (key_brightness_up_)
GrabKey(key_brightness_up_, 0);
if (key_volume_mute_)
GrabKey(key_volume_mute_, 0);
if (key_volume_down_)
GrabKey(key_volume_down_, 0);
if (key_volume_up_)
GrabKey(key_volume_up_, 0);
GrabKey(key_f6_, 0);
GrabKey(key_f7_, 0);
GrabKey(key_f8_, 0);
GrabKey(key_f9_, 0);
GrabKey(key_f10_, 0);
int xkb_major_version = XkbMajorVersion;
int xkb_minor_version = XkbMinorVersion;
if (!XkbQueryExtension(display,
NULL, // opcode_return
&xkb_event_base_,
NULL, // error_return
&xkb_major_version,
&xkb_minor_version)) {
LOG(WARNING) << "Could not query Xkb extension";
}
if (!XkbSelectEvents(display, XkbUseCoreKbd,
XkbStateNotifyMask,
XkbStateNotifyMask)) {
LOG(WARNING) << "Could not install Xkb Indicator observer";
}
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
MessageLoopForUI::current()->AddObserver(this);
#else
gdk_window_add_filter(NULL, GdkEventFilter, this);
#endif
}
SystemKeyEventListener::~SystemKeyEventListener() {
Stop();
}
void SystemKeyEventListener::Stop() {
if (stopped_)
return;
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
MessageLoopForUI::current()->RemoveObserver(this);
#else
gdk_window_remove_filter(NULL, GdkEventFilter, this);
#endif
stopped_ = true;
}
AudioHandler* SystemKeyEventListener::GetAudioHandler() const {
AudioHandler* audio_handler = AudioHandler::GetInstance();
if (!audio_handler || !audio_handler->IsInitialized())
return NULL;
return audio_handler;
}
void SystemKeyEventListener::AddCapsLockObserver(CapsLockObserver* observer) {
caps_lock_observers_.AddObserver(observer);
}
void SystemKeyEventListener::RemoveCapsLockObserver(
CapsLockObserver* observer) {
caps_lock_observers_.RemoveObserver(observer);
}
#if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
base::EventStatus SystemKeyEventListener::WillProcessEvent(
const base::NativeEvent& event) {
return ProcessedXEvent(event) ? base::EVENT_HANDLED : base::EVENT_CONTINUE;
}
void SystemKeyEventListener::DidProcessEvent(const base::NativeEvent& event) {
}
#else // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
// static
GdkFilterReturn SystemKeyEventListener::GdkEventFilter(GdkXEvent* gxevent,
GdkEvent* gevent,
gpointer data) {
SystemKeyEventListener* listener = static_cast<SystemKeyEventListener*>(data);
XEvent* xevent = static_cast<XEvent*>(gxevent);
return listener->ProcessedXEvent(xevent) ? GDK_FILTER_REMOVE
: GDK_FILTER_CONTINUE;
}
#endif // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK)
void SystemKeyEventListener::GrabKey(int32 key, uint32 mask) {
uint32 num_lock_mask = Mod2Mask;
uint32 caps_lock_mask = LockMask;
Display* display = ui::GetXDisplay();
Window root = DefaultRootWindow(display);
XGrabKey(display, key, mask, root, True, GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | caps_lock_mask, root, True,
GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | num_lock_mask, root, True,
GrabModeAsync, GrabModeAsync);
XGrabKey(display, key, mask | caps_lock_mask | num_lock_mask, root,
True, GrabModeAsync, GrabModeAsync);
}
void SystemKeyEventListener::OnBrightnessDown() {
DBusThreadManager::Get()->power_manager_client()->
DecreaseScreenBrightness(true);
}
void SystemKeyEventListener::OnBrightnessUp() {
DBusThreadManager::Get()->power_manager_client()->
IncreaseScreenBrightness();
}
void SystemKeyEventListener::OnVolumeMute() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
// Always muting (and not toggling) as per final decision on
// http://crosbug.com/3751
audio_handler->SetMuted(true);
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnVolumeDown() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
if (audio_handler->IsMuted())
audio_handler->SetVolumePercent(0.0);
else
audio_handler->AdjustVolumeByPercent(-kStepPercentage);
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnVolumeUp() {
AudioHandler* audio_handler = GetAudioHandler();
if (!audio_handler)
return;
if (audio_handler->IsMuted()) {
audio_handler->SetMuted(false);
if (audio_handler->GetVolumePercent() <= 0.1) // float comparison
audio_handler->SetVolumePercent(kVolumePercentOnVolumeUpWhileMuted);
} else {
audio_handler->AdjustVolumeByPercent(kStepPercentage);
}
SendAccessibilityVolumeNotification(
audio_handler->GetVolumePercent(),
audio_handler->IsMuted());
ShowVolumeBubble();
}
void SystemKeyEventListener::OnCapsLock(bool enabled) {
FOR_EACH_OBSERVER(
CapsLockObserver, caps_lock_observers_, OnCapsLockChange(enabled));
}
void SystemKeyEventListener::ShowVolumeBubble() {
AudioHandler* audio_handler = GetAudioHandler();
if (audio_handler) {
VolumeBubble::GetInstance()->ShowBubble(
audio_handler->GetVolumePercent(),
!audio_handler->IsMuted());
}
BrightnessBubble::GetInstance()->HideBubble();
}
bool SystemKeyEventListener::ProcessedXEvent(XEvent* xevent) {
if (xevent->type == KeyPress || xevent->type == KeyRelease) {
// Change the current keyboard layout (or input method) if xevent is one of
// the input method hotkeys.
input_method::HotkeyManager* hotkey_manager =
input_method::InputMethodManager::GetInstance()->GetHotkeyManager();
if (hotkey_manager->FilterKeyEvent(*xevent)) {
return true;
}
}
if (xevent->type == xkb_event_base_) {
XkbEvent* xkey_event = reinterpret_cast<XkbEvent*>(xevent);
if (xkey_event->any.xkb_type == XkbStateNotify) {
const bool new_lock_state = (xkey_event->state.locked_mods) & LockMask;
if (caps_lock_is_on_ != new_lock_state) {
caps_lock_is_on_ = new_lock_state;
OnCapsLock(caps_lock_is_on_);
}
return true;
}
} else if (xevent->type == KeyPress) {
const int32 keycode = xevent->xkey.keycode;
if (keycode) {
const unsigned int state = (xevent->xkey.state & kSupportedModifiers);
// Toggle Caps Lock if both Shift keys are pressed simultaneously.
if (keycode == key_left_shift_ || keycode == key_right_shift_) {
const bool other_shift_is_held = (state & ShiftMask);
const bool other_mods_are_held = (state & ~(ShiftMask | LockMask));
if (other_shift_is_held && !other_mods_are_held)
input_method::XKeyboard::SetCapsLockEnabled(!caps_lock_is_on_);
}
// Only doing non-Alt/Shift/Ctrl modified keys
if (!(state & (Mod1Mask | ShiftMask | ControlMask))) {
if (keycode == key_f6_ || keycode == key_brightness_down_) {
if (keycode == key_f6_)
UserMetrics::RecordAction(
UserMetricsAction("Accel_BrightnessDown_F6"));
OnBrightnessDown();
return true;
} else if (keycode == key_f7_ || keycode == key_brightness_up_) {
if (keycode == key_f7_)
UserMetrics::RecordAction(
UserMetricsAction("Accel_BrightnessUp_F7"));
OnBrightnessUp();
return true;
} else if (keycode == key_f8_ || keycode == key_volume_mute_) {
if (keycode == key_f8_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeMute_F8"));
OnVolumeMute();
return true;
} else if (keycode == key_f9_ || keycode == key_volume_down_) {
if (keycode == key_f9_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeDown_F9"));
OnVolumeDown();
return true;
} else if (keycode == key_f10_ || keycode == key_volume_up_) {
if (keycode == key_f10_)
UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeUp_F10"));
OnVolumeUp();
return true;
}
}
}
}
return false;
}
} // namespace chromeos
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.