text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
Modified 14 August 2012 by Alarus
Modified 3 December 2013 by Matthijs Kooijman
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "mem.h"
#include "uart_register.h"
#include "user_interface.h"
}
#include "HardwareSerial.h"
typedef void (*uart_rx_handler_t)(char);
uart_t* uart0_init(int baud_rate, uart_rx_handler_t rx_handler);
void uart0_set_baudrate(uart_t* uart, int baud_rate);
int uart0_get_baudrate(uart_t* uart);
void uart0_uninit(uart_t* uart);
void uart0_transmit(uart_t* uart, const char* buf, size_t size); // may block on TX fifo
void uart0_wait_for_transmit(uart_t* uart);
void uart0_transmit_char(uart_t* uart, char c); // does not block, but character will be lost if FIFO is full
void uart_set_debug(int enabled);
int uart_get_debug();
struct uart_
{
int baud_rate;
uart_rx_handler_t rx_handler;
};
#define UART_TX_FIFO_SIZE 0x7f
void ICACHE_FLASH_ATTR uart0_rx_handler(uart_t* uart)
{
if (READ_PERI_REG(UART_INT_ST(0)) & UART_RXFIFO_FULL_INT_ST)
{
while(true)
{
int rx_count = (READ_PERI_REG(UART_STATUS(0)) >> UART_RXFIFO_CNT_S) & UART_RXFIFO_CNT;
if (!rx_count)
break;
for(int cnt = 0; cnt < rx_count; ++cnt)
{
char c = READ_PERI_REG(UART_FIFO(0)) & 0xFF;
(*uart->rx_handler)(c);
}
}
WRITE_PERI_REG(UART_INT_CLR(0), UART_RXFIFO_FULL_INT_CLR);
}
}
void ICACHE_FLASH_ATTR uart0_wait_for_tx_fifo(size_t size_needed)
{
while (true)
{
size_t tx_count = (READ_PERI_REG(UART_STATUS(0)) >> UART_TXFIFO_CNT_S) & UART_TXFIFO_CNT;
if (tx_count <= (UART_TX_FIFO_SIZE - size_needed))
break;
}
}
void ICACHE_FLASH_ATTR uart0_wait_for_transmit(uart_t* uart)
{
uart0_wait_for_tx_fifo(UART_TX_FIFO_SIZE);
}
void ICACHE_FLASH_ATTR uart0_transmit_char(uart_t* uart, char c)
{
WRITE_PERI_REG(UART_FIFO(0), c);
}
void ICACHE_FLASH_ATTR uart0_transmit(uart_t* uart, const char* buf, size_t size)
{
while (size)
{
size_t part_size = (size > UART_TX_FIFO_SIZE) ? UART_TX_FIFO_SIZE : size;
size -= part_size;
uart0_wait_for_tx_fifo(part_size);
for(;part_size;--part_size, ++buf)
WRITE_PERI_REG(UART_FIFO(0), *buf);
}
}
void ICACHE_FLASH_ATTR uart0_flush(uart_t* uart)
{
SET_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST | UART_TXFIFO_RST);
CLEAR_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST | UART_TXFIFO_RST);
}
void ICACHE_FLASH_ATTR uart0_interrupt_enable(uart_t* uart)
{
WRITE_PERI_REG(UART_INT_CLR(0), 0x1ff);
ETS_UART_INTR_ATTACH(&uart0_rx_handler, uart);
SET_PERI_REG_MASK(UART_INT_ENA(0), UART_RXFIFO_FULL_INT_ENA);
ETS_UART_INTR_ENABLE();
}
void ICACHE_FLASH_ATTR uart0_interrupt_disable(uart_t* uart)
{
SET_PERI_REG_MASK(UART_INT_ENA(0), 0);
ETS_UART_INTR_DISABLE();
}
void ICACHE_FLASH_ATTR uart0_set_baudrate(uart_t* uart, int baud_rate)
{
uart->baud_rate = baud_rate;
uart_div_modify(0, UART_CLK_FREQ / (uart->baud_rate));
}
int ICACHE_FLASH_ATTR uart0_get_baudrate(uart_t* uart)
{
return uart->baud_rate;
}
uart_t* ICACHE_FLASH_ATTR uart0_init(int baudrate, uart_rx_handler_t rx_handler)
{
uart_t* uart = (uart_t*) os_malloc(sizeof(uart_t));
uart->rx_handler = rx_handler;
PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD);
uart0_set_baudrate(uart, baudrate);
WRITE_PERI_REG(UART_CONF0(0), 0x3 << UART_BIT_NUM_S); // 8n1
uart0_flush(uart);
uart0_interrupt_enable(uart);
WRITE_PERI_REG(UART_CONF1(0), ((0x01 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S));
return uart;
}
void ICACHE_FLASH_ATTR uart0_uninit(uart_t* uart)
{
uart0_interrupt_disable(uart);
// TODO: revert pin functions
os_free(uart);
}
void ICACHE_FLASH_ATTR
uart_ignore_char(char c)
{
}
void ICACHE_FLASH_ATTR
uart_write_char(char c)
{
if (c == '\n')
WRITE_PERI_REG(UART_FIFO(0), '\r');
WRITE_PERI_REG(UART_FIFO(0), c);
}
int s_uart_debug_enabled = 1;
void ICACHE_FLASH_ATTR uart_set_debug(int enabled)
{
s_uart_debug_enabled = enabled;
if (enabled)
ets_install_putc1((void *)&uart_write_char);
else
ets_install_putc1((void *)&uart_ignore_char);
}
int ICACHE_FLASH_ATTR uart_get_debug()
{
return s_uart_debug_enabled;
}
HardwareSerial Serial;
void ICACHE_FLASH_ATTR serial_rx_handler(char c)
{
Serial._rx_complete_irq(c);
}
extern "C" size_t ets_printf(const char*, ...);
ICACHE_FLASH_ATTR HardwareSerial::HardwareSerial() :
_rx_buffer_head(0), _rx_buffer_tail(0),
_tx_buffer_head(0), _tx_buffer_tail(0),
_uart(0)
{
}
void ICACHE_FLASH_ATTR HardwareSerial::begin(unsigned long baud, byte config)
{
_uart = uart0_init(baud, &serial_rx_handler);
_written = false;
}
void ICACHE_FLASH_ATTR HardwareSerial::end()
{
uart0_uninit(_uart);
_uart = 0;
}
int ICACHE_FLASH_ATTR HardwareSerial::available(void)
{
return ((unsigned int)(SERIAL_RX_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail)) % SERIAL_RX_BUFFER_SIZE;
}
int ICACHE_FLASH_ATTR HardwareSerial::peek(void)
{
if (_rx_buffer_head == _rx_buffer_tail) {
return -1;
} else {
return _rx_buffer[_rx_buffer_tail];
}
}
int ICACHE_FLASH_ATTR HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer_head == _rx_buffer_tail) {
return -1;
} else {
unsigned char c = _rx_buffer[_rx_buffer_tail];
_rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE;
return c;
}
}
int ICACHE_FLASH_ATTR HardwareSerial::availableForWrite(void)
{
tx_buffer_index_t head = _tx_buffer_head;
tx_buffer_index_t tail = _tx_buffer_tail;
if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;
return tail - head - 1;
}
void ICACHE_FLASH_ATTR HardwareSerial::flush()
{
if (!_written)
return;
}
size_t ICACHE_FLASH_ATTR HardwareSerial::write(uint8_t c)
{
uart0_transmit_char(_uart, c);
// // If the buffer and the data register is empty, just write the byte
// // to the data register and be done. This shortcut helps
// // significantly improve the effective datarate at high (>
// // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
// if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
// *_udr = c;
// sbi(*_ucsra, TXC0);
// return 1;
// }
// tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;
// // If the output buffer is full, there's nothing for it other than to
// // wait for the interrupt handler to empty it a bit
// while (i == _tx_buffer_tail) {
// if (bit_is_clear(SREG, SREG_I)) {
// // Interrupts are disabled, so we'll have to poll the data
// // register empty flag ourselves. If it is set, pretend an
// // interrupt has happened and call the handler to free up
// // space for us.
// if(bit_is_set(*_ucsra, UDRE0))
// _tx_udr_empty_irq();
// } else {
// // nop, the interrupt handler will free up space for us
// }
// }
// _tx_buffer[_tx_buffer_head] = c;
// _tx_buffer_head = i;
// sbi(*_ucsrb, UDRIE0);
_written = true;
return 1;
}
void ICACHE_FLASH_ATTR HardwareSerial::_rx_complete_irq(char c)
{
rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
if (i != _rx_buffer_tail) {
_rx_buffer[_rx_buffer_head] = c;
_rx_buffer_head = i;
}
}
// void HardwareSerial::_tx_udr_empty_irq(void)
// {
// // If interrupts are enabled, there must be more data in the output
// // buffer. Send the next byte
// unsigned char c = _tx_buffer[_tx_buffer_tail];
// _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_TX_BUFFER_SIZE;
// *_udr = c;
// // clear the TXC bit -- "can be cleared by writing a one to its bit
// // location". This makes sure flush() won't return until the bytes
// // actually got written
// sbi(*_ucsra, TXC0);
// if (_tx_buffer_head == _tx_buffer_tail) {
// // Buffer empty, so disable interrupts
// cbi(*_ucsrb, UDRIE0);
// }
// }
<commit_msg>Disable debug output in Serial.begin<commit_after>/*
HardwareSerial.cpp - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 28 September 2010 by Mark Sproul
Modified 14 August 2012 by Alarus
Modified 3 December 2013 by Matthijs Kooijman
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "Arduino.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "mem.h"
#include "uart_register.h"
#include "user_interface.h"
}
#include "HardwareSerial.h"
typedef void (*uart_rx_handler_t)(char);
uart_t* uart0_init(int baud_rate, uart_rx_handler_t rx_handler);
void uart0_set_baudrate(uart_t* uart, int baud_rate);
int uart0_get_baudrate(uart_t* uart);
void uart0_uninit(uart_t* uart);
void uart0_transmit(uart_t* uart, const char* buf, size_t size); // may block on TX fifo
void uart0_wait_for_transmit(uart_t* uart);
void uart0_transmit_char(uart_t* uart, char c); // does not block, but character will be lost if FIFO is full
void uart_set_debug(int enabled);
int uart_get_debug();
struct uart_
{
int baud_rate;
uart_rx_handler_t rx_handler;
};
#define UART_TX_FIFO_SIZE 0x7f
void ICACHE_FLASH_ATTR uart0_rx_handler(uart_t* uart)
{
if (READ_PERI_REG(UART_INT_ST(0)) & UART_RXFIFO_FULL_INT_ST)
{
while(true)
{
int rx_count = (READ_PERI_REG(UART_STATUS(0)) >> UART_RXFIFO_CNT_S) & UART_RXFIFO_CNT;
if (!rx_count)
break;
for(int cnt = 0; cnt < rx_count; ++cnt)
{
char c = READ_PERI_REG(UART_FIFO(0)) & 0xFF;
(*uart->rx_handler)(c);
}
}
WRITE_PERI_REG(UART_INT_CLR(0), UART_RXFIFO_FULL_INT_CLR);
}
}
void ICACHE_FLASH_ATTR uart0_wait_for_tx_fifo(size_t size_needed)
{
while (true)
{
size_t tx_count = (READ_PERI_REG(UART_STATUS(0)) >> UART_TXFIFO_CNT_S) & UART_TXFIFO_CNT;
if (tx_count <= (UART_TX_FIFO_SIZE - size_needed))
break;
}
}
void ICACHE_FLASH_ATTR uart0_wait_for_transmit(uart_t* uart)
{
uart0_wait_for_tx_fifo(UART_TX_FIFO_SIZE);
}
void ICACHE_FLASH_ATTR uart0_transmit_char(uart_t* uart, char c)
{
WRITE_PERI_REG(UART_FIFO(0), c);
}
void ICACHE_FLASH_ATTR uart0_transmit(uart_t* uart, const char* buf, size_t size)
{
while (size)
{
size_t part_size = (size > UART_TX_FIFO_SIZE) ? UART_TX_FIFO_SIZE : size;
size -= part_size;
uart0_wait_for_tx_fifo(part_size);
for(;part_size;--part_size, ++buf)
WRITE_PERI_REG(UART_FIFO(0), *buf);
}
}
void ICACHE_FLASH_ATTR uart0_flush(uart_t* uart)
{
SET_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST | UART_TXFIFO_RST);
CLEAR_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST | UART_TXFIFO_RST);
}
void ICACHE_FLASH_ATTR uart0_interrupt_enable(uart_t* uart)
{
WRITE_PERI_REG(UART_INT_CLR(0), 0x1ff);
ETS_UART_INTR_ATTACH(&uart0_rx_handler, uart);
SET_PERI_REG_MASK(UART_INT_ENA(0), UART_RXFIFO_FULL_INT_ENA);
ETS_UART_INTR_ENABLE();
}
void ICACHE_FLASH_ATTR uart0_interrupt_disable(uart_t* uart)
{
SET_PERI_REG_MASK(UART_INT_ENA(0), 0);
ETS_UART_INTR_DISABLE();
}
void ICACHE_FLASH_ATTR uart0_set_baudrate(uart_t* uart, int baud_rate)
{
uart->baud_rate = baud_rate;
uart_div_modify(0, UART_CLK_FREQ / (uart->baud_rate));
}
int ICACHE_FLASH_ATTR uart0_get_baudrate(uart_t* uart)
{
return uart->baud_rate;
}
uart_t* ICACHE_FLASH_ATTR uart0_init(int baudrate, uart_rx_handler_t rx_handler)
{
uart_t* uart = (uart_t*) os_malloc(sizeof(uart_t));
uart->rx_handler = rx_handler;
PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD);
uart0_set_baudrate(uart, baudrate);
WRITE_PERI_REG(UART_CONF0(0), 0x3 << UART_BIT_NUM_S); // 8n1
uart0_flush(uart);
uart0_interrupt_enable(uart);
WRITE_PERI_REG(UART_CONF1(0), ((0x01 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S));
return uart;
}
void ICACHE_FLASH_ATTR uart0_uninit(uart_t* uart)
{
uart0_interrupt_disable(uart);
// TODO: revert pin functions
os_free(uart);
}
void ICACHE_FLASH_ATTR
uart_ignore_char(char c)
{
}
void ICACHE_FLASH_ATTR
uart_write_char(char c)
{
if (c == '\n')
WRITE_PERI_REG(UART_FIFO(0), '\r');
WRITE_PERI_REG(UART_FIFO(0), c);
}
int s_uart_debug_enabled = 1;
void ICACHE_FLASH_ATTR uart_set_debug(int enabled)
{
s_uart_debug_enabled = enabled;
if (enabled)
ets_install_putc1((void *)&uart_write_char);
else
ets_install_putc1((void *)&uart_ignore_char);
}
int ICACHE_FLASH_ATTR uart_get_debug()
{
return s_uart_debug_enabled;
}
HardwareSerial Serial;
void ICACHE_FLASH_ATTR serial_rx_handler(char c)
{
Serial._rx_complete_irq(c);
}
extern "C" size_t ets_printf(const char*, ...);
ICACHE_FLASH_ATTR HardwareSerial::HardwareSerial() :
_rx_buffer_head(0), _rx_buffer_tail(0),
_tx_buffer_head(0), _tx_buffer_tail(0),
_uart(0)
{
}
void ICACHE_FLASH_ATTR HardwareSerial::begin(unsigned long baud, byte config)
{
_uart = uart0_init(baud, &serial_rx_handler);
_written = false;
uart_set_debug(0);
}
void ICACHE_FLASH_ATTR HardwareSerial::end()
{
uart0_uninit(_uart);
_uart = 0;
}
int ICACHE_FLASH_ATTR HardwareSerial::available(void)
{
return ((unsigned int)(SERIAL_RX_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail)) % SERIAL_RX_BUFFER_SIZE;
}
int ICACHE_FLASH_ATTR HardwareSerial::peek(void)
{
if (_rx_buffer_head == _rx_buffer_tail) {
return -1;
} else {
return _rx_buffer[_rx_buffer_tail];
}
}
int ICACHE_FLASH_ATTR HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer_head == _rx_buffer_tail) {
return -1;
} else {
unsigned char c = _rx_buffer[_rx_buffer_tail];
_rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE;
return c;
}
}
int ICACHE_FLASH_ATTR HardwareSerial::availableForWrite(void)
{
tx_buffer_index_t head = _tx_buffer_head;
tx_buffer_index_t tail = _tx_buffer_tail;
if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;
return tail - head - 1;
}
void ICACHE_FLASH_ATTR HardwareSerial::flush()
{
if (!_written)
return;
}
size_t ICACHE_FLASH_ATTR HardwareSerial::write(uint8_t c)
{
uart0_transmit_char(_uart, c);
// // If the buffer and the data register is empty, just write the byte
// // to the data register and be done. This shortcut helps
// // significantly improve the effective datarate at high (>
// // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
// if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
// *_udr = c;
// sbi(*_ucsra, TXC0);
// return 1;
// }
// tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;
// // If the output buffer is full, there's nothing for it other than to
// // wait for the interrupt handler to empty it a bit
// while (i == _tx_buffer_tail) {
// if (bit_is_clear(SREG, SREG_I)) {
// // Interrupts are disabled, so we'll have to poll the data
// // register empty flag ourselves. If it is set, pretend an
// // interrupt has happened and call the handler to free up
// // space for us.
// if(bit_is_set(*_ucsra, UDRE0))
// _tx_udr_empty_irq();
// } else {
// // nop, the interrupt handler will free up space for us
// }
// }
// _tx_buffer[_tx_buffer_head] = c;
// _tx_buffer_head = i;
// sbi(*_ucsrb, UDRIE0);
_written = true;
return 1;
}
void ICACHE_FLASH_ATTR HardwareSerial::_rx_complete_irq(char c)
{
rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;
if (i != _rx_buffer_tail) {
_rx_buffer[_rx_buffer_head] = c;
_rx_buffer_head = i;
}
}
// void HardwareSerial::_tx_udr_empty_irq(void)
// {
// // If interrupts are enabled, there must be more data in the output
// // buffer. Send the next byte
// unsigned char c = _tx_buffer[_tx_buffer_tail];
// _tx_buffer_tail = (_tx_buffer_tail + 1) % SERIAL_TX_BUFFER_SIZE;
// *_udr = c;
// // clear the TXC bit -- "can be cleared by writing a one to its bit
// // location". This makes sure flush() won't return until the bytes
// // actually got written
// sbi(*_ucsra, TXC0);
// if (_tx_buffer_head == _tx_buffer_tail) {
// // Buffer empty, so disable interrupts
// cbi(*_ucsrb, UDRIE0);
// }
// }
<|endoftext|>
|
<commit_before>#include "components/config.hpp"
#include <climits>
#include <fstream>
#include "cairo/utils.hpp"
#include "utils/color.hpp"
#include "utils/env.hpp"
#include "utils/factory.hpp"
#include "utils/string.hpp"
POLYBAR_NS
namespace chrono = std::chrono;
/**
* Create instance
*/
config::make_type config::make(string path, string bar) {
return *factory_util::singleton<std::remove_reference_t<config::make_type>>(logger::make(), move(path), move(bar));
}
/**
* Get path of loaded file
*/
const string& config::filepath() const {
return m_file;
}
/**
* Get the section name of the bar in use
*/
string config::section() const {
return "bar/" + m_barname;
}
void config::use_xrm() {
#if WITH_XRM
/*
* Initialize the xresource manager if there are any xrdb refs
* present in the configuration
*/
if (!m_xrm) {
m_log.info("Enabling xresource manager");
m_xrm.reset(new xresource_manager{connection::make()});
}
#endif
}
void config::set_sections(sectionmap_t sections) {
m_sections = move(sections);
copy_inherited();
}
void config::set_included(file_list included) {
m_included = move(included);
}
/**
* Print a deprecation warning if the given parameter is set
*/
void config::warn_deprecated(const string& section, const string& key, string replacement) const {
try {
auto value = get<string>(section, key);
m_log.warn(
"The config parameter `%s.%s` is deprecated, use `%s.%s` instead.", section, key, section, move(replacement));
} catch (const key_error& err) {
}
}
/**
* Look for sections set up to inherit from a base section
* and copy the missing parameters
*
* [sub/section]
* inherit = base/section
*/
void config::copy_inherited() {
for (auto&& section : m_sections) {
for (auto&& param : section.second) {
if (param.first == "inherit") {
// Get name of base section
auto inherit = param.second;
if ((inherit = dereference<string>(section.first, param.first, inherit, inherit)).empty()) {
throw value_error("Invalid section \"\" defined for \"" + section.first + ".inherit\"");
}
// Find and validate base section
auto base_section = m_sections.find(inherit);
if (base_section == m_sections.end()) {
throw value_error("Invalid section \"" + inherit + "\" defined for \"" + section.first + ".inherit\"");
}
m_log.trace("config: Copying missing params (sub=\"%s\", base=\"%s\")", section.first, inherit);
/*
* Iterate the base and copy the parameters that haven't been defined
* for the sub-section
*/
for (auto&& base_param : base_section->second) {
section.second.emplace(base_param.first, base_param.second);
}
}
}
}
}
template <>
string config::convert(string&& value) const {
return forward<string>(value);
}
template <>
const char* config::convert(string&& value) const {
return value.c_str();
}
template <>
char config::convert(string&& value) const {
return value.c_str()[0];
}
template <>
int config::convert(string&& value) const {
return std::strtol(value.c_str(), nullptr, 10);
}
template <>
short config::convert(string&& value) const {
return static_cast<short>(std::strtol(value.c_str(), nullptr, 10));
}
template <>
bool config::convert(string&& value) const {
string lower{string_util::lower(forward<string>(value))};
return (lower == "true" || lower == "yes" || lower == "on" || lower == "1");
}
template <>
float config::convert(string&& value) const {
return std::strtof(value.c_str(), nullptr);
}
template <>
double config::convert(string&& value) const {
return std::strtod(value.c_str(), nullptr);
}
template <>
long config::convert(string&& value) const {
return std::strtol(value.c_str(), nullptr, 10);
}
template <>
long long config::convert(string&& value) const {
return std::strtoll(value.c_str(), nullptr, 10);
}
template <>
unsigned char config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned short config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned int config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned long config::convert(string&& value) const {
unsigned long v{std::strtoul(value.c_str(), nullptr, 10)};
return v < ULONG_MAX ? v : 0UL;
}
template <>
unsigned long long config::convert(string&& value) const {
unsigned long long v{std::strtoull(value.c_str(), nullptr, 10)};
return v < ULLONG_MAX ? v : 0ULL;
}
template <>
chrono::seconds config::convert(string&& value) const {
return chrono::seconds{convert<chrono::seconds::rep>(forward<string>(value))};
}
template <>
chrono::milliseconds config::convert(string&& value) const {
return chrono::milliseconds{convert<chrono::milliseconds::rep>(forward<string>(value))};
}
template <>
chrono::duration<double> config::convert(string&& value) const {
return chrono::duration<double>{convert<double>(forward<string>(value))};
}
template <>
rgba config::convert(string&& value) const {
rgba ret{value};
if (!ret.has_color()) {
throw value_error("\"" + value + "\" is an invalid color value.");
}
return ret;
}
template <>
cairo_operator_t config::convert(string&& value) const {
return cairo::utils::str2operator(forward<string>(value), CAIRO_OPERATOR_OVER);
}
POLYBAR_NS_END
<commit_msg>fix(config): Reintroduce multiple inheritance (#2271)<commit_after>#include "components/config.hpp"
#include <climits>
#include <fstream>
#include "cairo/utils.hpp"
#include "utils/color.hpp"
#include "utils/env.hpp"
#include "utils/factory.hpp"
#include "utils/string.hpp"
POLYBAR_NS
namespace chrono = std::chrono;
/**
* Create instance
*/
config::make_type config::make(string path, string bar) {
return *factory_util::singleton<std::remove_reference_t<config::make_type>>(logger::make(), move(path), move(bar));
}
/**
* Get path of loaded file
*/
const string& config::filepath() const {
return m_file;
}
/**
* Get the section name of the bar in use
*/
string config::section() const {
return "bar/" + m_barname;
}
void config::use_xrm() {
#if WITH_XRM
/*
* Initialize the xresource manager if there are any xrdb refs
* present in the configuration
*/
if (!m_xrm) {
m_log.info("Enabling xresource manager");
m_xrm.reset(new xresource_manager{connection::make()});
}
#endif
}
void config::set_sections(sectionmap_t sections) {
m_sections = move(sections);
copy_inherited();
}
void config::set_included(file_list included) {
m_included = move(included);
}
/**
* Print a deprecation warning if the given parameter is set
*/
void config::warn_deprecated(const string& section, const string& key, string replacement) const {
try {
auto value = get<string>(section, key);
m_log.warn(
"The config parameter `%s.%s` is deprecated, use `%s.%s` instead.", section, key, section, move(replacement));
} catch (const key_error& err) {
}
}
/**
* Look for sections set up to inherit from a base section
* and copy the missing parameters
*
* Multiple sections can be specified, separated by a space.
*
* [sub/section]
* inherit = section1 section2
*/
void config::copy_inherited() {
for (auto&& section : m_sections) {
std::vector<string> inherit_sections;
// Collect all sections to be inherited
for (auto&& param : section.second) {
string key_name = param.first;
if (key_name == "inherit") {
auto inherit = param.second;
inherit = dereference<string>(section.first, key_name, inherit, inherit);
std::vector<string> sections = string_util::split(std::move(inherit), ' ');
inherit_sections.insert(inherit_sections.end(), sections.begin(), sections.end());
} else if (key_name.find("inherit") == 0) {
// Legacy support for keys that just start with 'inherit'
m_log.warn(
"\"%s.%s\": Using anything other than 'inherit' for inheriting section keys is deprecated. "
"The 'inherit' key supports multiple section names separated by a space.",
section.first, key_name);
auto inherit = param.second;
inherit = dereference<string>(section.first, key_name, inherit, inherit);
if (inherit.empty() || m_sections.find(inherit) == m_sections.end()) {
throw value_error(
"Invalid section \"" + inherit + "\" defined for \"" + section.first + "." + key_name + "\"");
}
inherit_sections.push_back(std::move(inherit));
}
}
for (const auto& base_name : inherit_sections) {
const auto base_section = m_sections.find(base_name);
if (base_section == m_sections.end()) {
throw value_error("Invalid section \"" + base_name + "\" defined for \"" + section.first + ".inherit\"");
}
m_log.trace("config: Inheriting keys from \"%s\" in \"%s\"", base_name, section.first);
/*
* Iterate the base and copy the parameters that haven't been defined
* yet.
*/
for (auto&& base_param : base_section->second) {
section.second.emplace(base_param.first, base_param.second);
}
}
}
}
template <>
string config::convert(string&& value) const {
return forward<string>(value);
}
template <>
const char* config::convert(string&& value) const {
return value.c_str();
}
template <>
char config::convert(string&& value) const {
return value.c_str()[0];
}
template <>
int config::convert(string&& value) const {
return std::strtol(value.c_str(), nullptr, 10);
}
template <>
short config::convert(string&& value) const {
return static_cast<short>(std::strtol(value.c_str(), nullptr, 10));
}
template <>
bool config::convert(string&& value) const {
string lower{string_util::lower(forward<string>(value))};
return (lower == "true" || lower == "yes" || lower == "on" || lower == "1");
}
template <>
float config::convert(string&& value) const {
return std::strtof(value.c_str(), nullptr);
}
template <>
double config::convert(string&& value) const {
return std::strtod(value.c_str(), nullptr);
}
template <>
long config::convert(string&& value) const {
return std::strtol(value.c_str(), nullptr, 10);
}
template <>
long long config::convert(string&& value) const {
return std::strtoll(value.c_str(), nullptr, 10);
}
template <>
unsigned char config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned short config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned int config::convert(string&& value) const {
return std::strtoul(value.c_str(), nullptr, 10);
}
template <>
unsigned long config::convert(string&& value) const {
unsigned long v{std::strtoul(value.c_str(), nullptr, 10)};
return v < ULONG_MAX ? v : 0UL;
}
template <>
unsigned long long config::convert(string&& value) const {
unsigned long long v{std::strtoull(value.c_str(), nullptr, 10)};
return v < ULLONG_MAX ? v : 0ULL;
}
template <>
chrono::seconds config::convert(string&& value) const {
return chrono::seconds{convert<chrono::seconds::rep>(forward<string>(value))};
}
template <>
chrono::milliseconds config::convert(string&& value) const {
return chrono::milliseconds{convert<chrono::milliseconds::rep>(forward<string>(value))};
}
template <>
chrono::duration<double> config::convert(string&& value) const {
return chrono::duration<double>{convert<double>(forward<string>(value))};
}
template <>
rgba config::convert(string&& value) const {
rgba ret{value};
if (!ret.has_color()) {
throw value_error("\"" + value + "\" is an invalid color value.");
}
return ret;
}
template <>
cairo_operator_t config::convert(string&& value) const {
return cairo::utils::str2operator(forward<string>(value), CAIRO_OPERATOR_OVER);
}
POLYBAR_NS_END
<|endoftext|>
|
<commit_before>/*
* Copyright 2012 Google 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.
*/
// Author: pulkitg@google.com (Pulkit Goyal)
#include "net/instaweb/rewriter/public/critical_images_finder.h"
#include <map>
#include <set>
#include <utility>
#include "base/logging.h"
#include "net/instaweb/http/public/log_record.h"
#include "net/instaweb/rewriter/critical_images.pb.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/util/public/property_cache.h"
#include "net/instaweb/util/public/proto_util.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
const char kEmptyValuePlaceholder[] = "\n";
// Setup the HTML and CSS critical image sets in critical_images_info from the
// property_value. Return true if property_value had a value, and
// deserialization of it succeeded.
bool PopulateCriticalImagesFromPropertyValue(
const PropertyValue* property_value,
CriticalImages* critical_images) {
DCHECK(property_value != NULL);
DCHECK(critical_images != NULL);
if (!property_value->has_value()) {
return false;
}
// Check if we have the placeholder string value, indicating an empty value.
// This will be stored when we have an empty set of critical images, since the
// property cache doesn't store empty values.
if (property_value->value() == kEmptyValuePlaceholder) {
critical_images->Clear();
return true;
}
ArrayInputStream input(property_value->value().data(),
property_value->value().size());
return critical_images->ParseFromZeroCopyStream(&input);
}
// Create CriticalImagesInfo object from the value of property_value. NULL if
// no value is found, or if the property value reflects that no results are
// available. Result is owned by caller.
CriticalImagesInfo* CriticalImagesInfoFromPropertyValue(
const PropertyValue* property_value) {
DCHECK(property_value != NULL);
CriticalImages crit_images;
if (!PopulateCriticalImagesFromPropertyValue(property_value, &crit_images)) {
return NULL;
}
if (crit_images.html_critical_images().size() == 0 &&
crit_images.css_critical_images().size() == 0 &&
crit_images.html_critical_images_sets().size() == 0 &&
crit_images.css_critical_images_sets().size() == 0) {
// Note: we check the summary set sizes above first since sometimes the
// summaries are populated but individual beacon sets are not. If nothing
// is populated yet then we return NULL (no data) rather than empty sets.
return NULL;
}
CriticalImagesInfo* critical_images_info = new CriticalImagesInfo();
critical_images_info->html_critical_images.insert(
crit_images.html_critical_images().begin(),
crit_images.html_critical_images().end());
critical_images_info->css_critical_images.insert(
crit_images.css_critical_images().begin(),
crit_images.css_critical_images().end());
return critical_images_info;
}
void UpdateCriticalImagesSetInProto(
const StringSet& critical_images_set,
int max_set_size,
int percent_needed_for_critical,
protobuf::RepeatedPtrField<CriticalImages::CriticalImageSet>* set_field,
protobuf::RepeatedPtrField<GoogleString>* critical_images_field) {
DCHECK_GT(max_set_size, 0);
// If we have a max_set_size of 1 we can just directly set the
// critical_images_field to the new set, we don't need to store any history of
// responses.
if (max_set_size == 1) {
critical_images_field->Clear();
for (StringSet::const_iterator it = critical_images_set.begin();
it != critical_images_set.end(); ++it) {
*critical_images_field->Add() = *it;
}
return;
}
// Update the set field first, which contains the history of up to
// max_set_size critical image responses. If we already have max_set_size,
// drop the first response, and append the new response to the end.
CriticalImages::CriticalImageSet* new_set;
if (set_field->size() >= max_set_size) {
DCHECK_EQ(set_field->size(), max_set_size);
for (int i = 1; i < set_field->size(); ++i) {
set_field->SwapElements(i - 1, i);
}
new_set = set_field->Mutable(set_field->size() - 1);
new_set->Clear();
} else {
new_set = set_field->Add();
}
for (StringSet::iterator i = critical_images_set.begin();
i != critical_images_set.end(); ++i) {
new_set->add_critical_images(*i);
}
// Now recalculate the critical image set.
std::map<GoogleString, int> image_count;
for (int i = 0; i < set_field->size(); ++i) {
const CriticalImages::CriticalImageSet& set = set_field->Get(i);
for (int j = 0; j < set.critical_images_size(); ++j) {
const GoogleString& img = set.critical_images(j);
image_count[img]++;
}
}
int num_needed_for_critical =
set_field->size() * percent_needed_for_critical / 100;
critical_images_field->Clear();
for (std::map<GoogleString, int>::const_iterator it = image_count.begin();
it != image_count.end(); ++it) {
if (it->second >= num_needed_for_critical) {
*critical_images_field->Add() = it->first;
}
}
}
} // namespace
const char CriticalImagesFinder::kCriticalImagesPropertyName[] =
"critical_images";
const char CriticalImagesFinder::kCriticalImagesValidCount[] =
"critical_images_valid_count";
const char CriticalImagesFinder::kCriticalImagesExpiredCount[] =
"critical_images_expired_count";
const char CriticalImagesFinder::kCriticalImagesNotFoundCount[] =
"critical_images_not_found_count";
CriticalImagesFinder::CriticalImagesFinder(Statistics* statistics) {
critical_images_valid_count_ = statistics->GetVariable(
kCriticalImagesValidCount);
critical_images_expired_count_ = statistics->GetVariable(
kCriticalImagesExpiredCount);
critical_images_not_found_count_ = statistics->GetVariable(
kCriticalImagesNotFoundCount);
}
CriticalImagesFinder::~CriticalImagesFinder() {
}
void CriticalImagesFinder::InitStats(Statistics* statistics) {
statistics->AddVariable(kCriticalImagesValidCount);
statistics->AddVariable(kCriticalImagesExpiredCount);
statistics->AddVariable(kCriticalImagesNotFoundCount);
}
namespace {
bool IsCriticalImage(const GoogleString& image_url,
const StringSet& critical_images_set) {
return (critical_images_set.find(image_url) != critical_images_set.end());
}
} // namespace
bool CriticalImagesFinder::IsHtmlCriticalImage(
const GoogleString& image_url, RewriteDriver* driver) {
return IsCriticalImage(image_url, GetHtmlCriticalImages(driver));
}
bool CriticalImagesFinder::IsCssCriticalImage(
const GoogleString& image_url, RewriteDriver* driver) {
return IsCriticalImage(image_url, GetCssCriticalImages(driver));
}
const StringSet& CriticalImagesFinder::GetHtmlCriticalImages(
RewriteDriver* driver) {
UpdateCriticalImagesSetInDriver(driver);
const CriticalImagesInfo* info = driver->critical_images_info();
CHECK(info != NULL);
return info->html_critical_images;
}
const StringSet& CriticalImagesFinder::GetCssCriticalImages(
RewriteDriver* driver) {
UpdateCriticalImagesSetInDriver(driver);
const CriticalImagesInfo* info = driver->critical_images_info();
CHECK(info != NULL);
return info->css_critical_images;
}
StringSet* CriticalImagesFinder::mutable_html_critical_images(
RewriteDriver* driver) {
DCHECK(driver != NULL);
CriticalImagesInfo* driver_info = driver->critical_images_info();
// Preserve CSS critical images if they have been updated already.
if (driver_info == NULL) {
driver_info = new CriticalImagesInfo;
driver->set_critical_images_info(driver_info);
}
return &driver_info->html_critical_images;
}
StringSet* CriticalImagesFinder::mutable_css_critical_images(
RewriteDriver* driver) {
DCHECK(driver != NULL);
CriticalImagesInfo* driver_info = driver->critical_images_info();
// Preserve CSS critical images if they have been updated already.
if (driver_info == NULL) {
driver_info = new CriticalImagesInfo;
driver->set_critical_images_info(driver_info);
}
return &driver_info->css_critical_images;
}
// Copy the critical images for this request from the property cache into the
// RewriteDriver. The critical images are not stored in CriticalImageFinder
// because the ServerContext holds the CriticalImageFinder and hence is shared
// between requests.
void CriticalImagesFinder::UpdateCriticalImagesSetInDriver(
RewriteDriver* driver) {
// Don't update critical_images_info if it's already been set.
if (driver->critical_images_info() != NULL) {
return;
}
CriticalImagesInfo* info = NULL;
PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
const PropertyCache::Cohort* cohort =
page_property_cache->GetCohort(GetCriticalImagesCohort());
// Fallback properties can be used for critical images.
AbstractPropertyPage* page = driver->fallback_property_page();
if (page != NULL && cohort != NULL) {
PropertyValue* property_value = page->GetProperty(
cohort, kCriticalImagesPropertyName);
info = ExtractCriticalImagesFromCache(driver, property_value);
if (info != NULL) {
driver->log_record()->SetNumHtmlCriticalImages(
info->html_critical_images.size());
driver->log_record()->SetNumCssCriticalImages(
info->css_critical_images.size());
}
}
// Store an empty CriticalImagesInfo back into the driver if we don't have any
// beacon results yet.
if (info == NULL) {
info = new CriticalImagesInfo;
}
driver->set_critical_images_info(info);
}
// TODO(pulkitg): Change all instances of critical_images_set to
// html_critical_images_set.
bool CriticalImagesFinder::UpdateCriticalImagesCacheEntryFromDriver(
RewriteDriver* driver, StringSet* critical_images_set,
StringSet* css_critical_images_set) {
// Update property cache if above the fold critical images are successfully
// determined.
// Fallback properties will be updated for critical images.
AbstractPropertyPage* page = driver->fallback_property_page();
PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
return UpdateCriticalImagesCacheEntry(
page, page_property_cache, critical_images_set, css_critical_images_set);
}
bool CriticalImagesFinder::UpdateCriticalImagesCacheEntry(
AbstractPropertyPage* page, PropertyCache* page_property_cache,
StringSet* html_critical_images_set, StringSet* css_critical_images_set) {
// Update property cache if above the fold critical images are successfully
// determined.
scoped_ptr<StringSet> html_critical_images(html_critical_images_set);
scoped_ptr<StringSet> css_critical_images(css_critical_images_set);
if (page_property_cache != NULL && page != NULL) {
const PropertyCache::Cohort* cohort =
page_property_cache->GetCohort(GetCriticalImagesCohort());
if (cohort != NULL) {
PropertyValue* property_value = page->GetProperty(
cohort, kCriticalImagesPropertyName);
// Read in the current critical images, and preserve the current HTML or
// CSS critical images if they are not being updated.
CriticalImages critical_images;
PopulateCriticalImagesFromPropertyValue(property_value, &critical_images);
bool updated = UpdateCriticalImages(
html_critical_images.get(), css_critical_images.get(),
&critical_images);
if (updated) {
GoogleString buf;
if (critical_images.SerializeToString(&buf)) {
// The property cache won't store an empty value, which is what an
// empty CriticalImages will serialize to. If buf is an empty string,
// repalce with a placeholder that we can then handle when decoding
// the property_cache value in
// PopulateCriticalImagesFromPropertyValue.
if (buf.empty()) {
buf = kEmptyValuePlaceholder;
}
page->UpdateValue(cohort, kCriticalImagesPropertyName, buf);
} else {
LOG(WARNING) << "Serialization of critical images protobuf failed.";
return false;
}
}
return updated;
} else {
LOG(WARNING) << "Critical Images Cohort is NULL.";
}
}
return false;
}
bool CriticalImagesFinder::UpdateCriticalImages(
const StringSet* html_critical_images,
const StringSet* css_critical_images,
CriticalImages* critical_images) const {
DCHECK(critical_images != NULL);
if (html_critical_images != NULL) {
UpdateCriticalImagesSetInProto(
*html_critical_images,
NumSetsToKeep(),
PercentSeenForCritical(),
critical_images->mutable_html_critical_images_sets(),
critical_images->mutable_html_critical_images());
}
if (css_critical_images != NULL) {
UpdateCriticalImagesSetInProto(
*css_critical_images,
NumSetsToKeep(),
PercentSeenForCritical(),
critical_images->mutable_css_critical_images_sets(),
critical_images->mutable_css_critical_images());
}
// We updated if either StringSet* was set.
return (html_critical_images != NULL || css_critical_images != NULL);
}
CriticalImagesInfo* CriticalImagesFinder::ExtractCriticalImagesFromCache(
RewriteDriver* driver,
const PropertyValue* property_value) {
CriticalImagesInfo* critical_images_info = NULL;
// Don't track stats if we are flushing early, since we will already be
// counting this when we are rewriting the full page.
bool track_stats = !driver->flushing_early();
const PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
int64 cache_ttl_ms =
driver->options()->finder_properties_cache_expiration_time_ms();
// Check if the cache value exists and is not expired.
if (property_value->has_value()) {
const bool is_valid =
!page_property_cache->IsExpired(property_value, cache_ttl_ms);
if (is_valid) {
critical_images_info =
CriticalImagesInfoFromPropertyValue(property_value);
if (track_stats) {
if (critical_images_info == NULL) {
critical_images_not_found_count_->Add(1);
} else {
critical_images_valid_count_->Add(1);
}
}
} else if (track_stats) {
critical_images_expired_count_->Add(1);
}
} else if (track_stats) {
critical_images_not_found_count_->Add(1);
}
return critical_images_info;
}
} // namespace net_instaweb
<commit_msg>kEmptyValuePlaceholder means we don't need to check state of protobuf after PopulateCriticalImagesFromPropertyValue call succeeds (we distinguish "no data yet" from "no critical images" there).<commit_after>/*
* Copyright 2012 Google 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.
*/
// Author: pulkitg@google.com (Pulkit Goyal)
#include "net/instaweb/rewriter/public/critical_images_finder.h"
#include <map>
#include <set>
#include <utility>
#include "base/logging.h"
#include "net/instaweb/http/public/log_record.h"
#include "net/instaweb/rewriter/critical_images.pb.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "net/instaweb/util/public/property_cache.h"
#include "net/instaweb/util/public/proto_util.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/statistics.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
const char kEmptyValuePlaceholder[] = "\n";
// Setup the HTML and CSS critical image sets in critical_images_info from the
// property_value. Return true if property_value had a value, and
// deserialization of it succeeded.
bool PopulateCriticalImagesFromPropertyValue(
const PropertyValue* property_value,
CriticalImages* critical_images) {
DCHECK(property_value != NULL);
DCHECK(critical_images != NULL);
if (!property_value->has_value()) {
return false;
}
// Check if we have the placeholder string value, indicating an empty value.
// This will be stored when we have an empty set of critical images, since the
// property cache doesn't store empty values.
if (property_value->value() == kEmptyValuePlaceholder) {
critical_images->Clear();
return true;
}
ArrayInputStream input(property_value->value().data(),
property_value->value().size());
return critical_images->ParseFromZeroCopyStream(&input);
}
// Create CriticalImagesInfo object from the value of property_value. NULL if
// no value is found, or if the property value reflects that no results are
// available. Result is owned by caller.
CriticalImagesInfo* CriticalImagesInfoFromPropertyValue(
const PropertyValue* property_value) {
DCHECK(property_value != NULL);
CriticalImages crit_images;
if (!PopulateCriticalImagesFromPropertyValue(property_value, &crit_images)) {
return NULL;
}
// The existence of kEmptyValuePlaceholder should mean that "no data" will be
// distinguished from "no critical images" by the above call.
CriticalImagesInfo* critical_images_info = new CriticalImagesInfo();
critical_images_info->html_critical_images.insert(
crit_images.html_critical_images().begin(),
crit_images.html_critical_images().end());
critical_images_info->css_critical_images.insert(
crit_images.css_critical_images().begin(),
crit_images.css_critical_images().end());
return critical_images_info;
}
void UpdateCriticalImagesSetInProto(
const StringSet& critical_images_set,
int max_set_size,
int percent_needed_for_critical,
protobuf::RepeatedPtrField<CriticalImages::CriticalImageSet>* set_field,
protobuf::RepeatedPtrField<GoogleString>* critical_images_field) {
DCHECK_GT(max_set_size, 0);
// If we have a max_set_size of 1 we can just directly set the
// critical_images_field to the new set, we don't need to store any history of
// responses.
if (max_set_size == 1) {
critical_images_field->Clear();
for (StringSet::const_iterator it = critical_images_set.begin();
it != critical_images_set.end(); ++it) {
*critical_images_field->Add() = *it;
}
return;
}
// Update the set field first, which contains the history of up to
// max_set_size critical image responses. If we already have max_set_size,
// drop the first response, and append the new response to the end.
CriticalImages::CriticalImageSet* new_set;
if (set_field->size() >= max_set_size) {
DCHECK_EQ(set_field->size(), max_set_size);
for (int i = 1; i < set_field->size(); ++i) {
set_field->SwapElements(i - 1, i);
}
new_set = set_field->Mutable(set_field->size() - 1);
new_set->Clear();
} else {
new_set = set_field->Add();
}
for (StringSet::iterator i = critical_images_set.begin();
i != critical_images_set.end(); ++i) {
new_set->add_critical_images(*i);
}
// Now recalculate the critical image set.
std::map<GoogleString, int> image_count;
for (int i = 0; i < set_field->size(); ++i) {
const CriticalImages::CriticalImageSet& set = set_field->Get(i);
for (int j = 0; j < set.critical_images_size(); ++j) {
const GoogleString& img = set.critical_images(j);
image_count[img]++;
}
}
int num_needed_for_critical =
set_field->size() * percent_needed_for_critical / 100;
critical_images_field->Clear();
for (std::map<GoogleString, int>::const_iterator it = image_count.begin();
it != image_count.end(); ++it) {
if (it->second >= num_needed_for_critical) {
*critical_images_field->Add() = it->first;
}
}
}
} // namespace
const char CriticalImagesFinder::kCriticalImagesPropertyName[] =
"critical_images";
const char CriticalImagesFinder::kCriticalImagesValidCount[] =
"critical_images_valid_count";
const char CriticalImagesFinder::kCriticalImagesExpiredCount[] =
"critical_images_expired_count";
const char CriticalImagesFinder::kCriticalImagesNotFoundCount[] =
"critical_images_not_found_count";
CriticalImagesFinder::CriticalImagesFinder(Statistics* statistics) {
critical_images_valid_count_ = statistics->GetVariable(
kCriticalImagesValidCount);
critical_images_expired_count_ = statistics->GetVariable(
kCriticalImagesExpiredCount);
critical_images_not_found_count_ = statistics->GetVariable(
kCriticalImagesNotFoundCount);
}
CriticalImagesFinder::~CriticalImagesFinder() {
}
void CriticalImagesFinder::InitStats(Statistics* statistics) {
statistics->AddVariable(kCriticalImagesValidCount);
statistics->AddVariable(kCriticalImagesExpiredCount);
statistics->AddVariable(kCriticalImagesNotFoundCount);
}
namespace {
bool IsCriticalImage(const GoogleString& image_url,
const StringSet& critical_images_set) {
return (critical_images_set.find(image_url) != critical_images_set.end());
}
} // namespace
bool CriticalImagesFinder::IsHtmlCriticalImage(
const GoogleString& image_url, RewriteDriver* driver) {
return IsCriticalImage(image_url, GetHtmlCriticalImages(driver));
}
bool CriticalImagesFinder::IsCssCriticalImage(
const GoogleString& image_url, RewriteDriver* driver) {
return IsCriticalImage(image_url, GetCssCriticalImages(driver));
}
const StringSet& CriticalImagesFinder::GetHtmlCriticalImages(
RewriteDriver* driver) {
UpdateCriticalImagesSetInDriver(driver);
const CriticalImagesInfo* info = driver->critical_images_info();
CHECK(info != NULL);
return info->html_critical_images;
}
const StringSet& CriticalImagesFinder::GetCssCriticalImages(
RewriteDriver* driver) {
UpdateCriticalImagesSetInDriver(driver);
const CriticalImagesInfo* info = driver->critical_images_info();
CHECK(info != NULL);
return info->css_critical_images;
}
StringSet* CriticalImagesFinder::mutable_html_critical_images(
RewriteDriver* driver) {
DCHECK(driver != NULL);
CriticalImagesInfo* driver_info = driver->critical_images_info();
// Preserve CSS critical images if they have been updated already.
if (driver_info == NULL) {
driver_info = new CriticalImagesInfo;
driver->set_critical_images_info(driver_info);
}
return &driver_info->html_critical_images;
}
StringSet* CriticalImagesFinder::mutable_css_critical_images(
RewriteDriver* driver) {
DCHECK(driver != NULL);
CriticalImagesInfo* driver_info = driver->critical_images_info();
// Preserve CSS critical images if they have been updated already.
if (driver_info == NULL) {
driver_info = new CriticalImagesInfo;
driver->set_critical_images_info(driver_info);
}
return &driver_info->css_critical_images;
}
// Copy the critical images for this request from the property cache into the
// RewriteDriver. The critical images are not stored in CriticalImageFinder
// because the ServerContext holds the CriticalImageFinder and hence is shared
// between requests.
void CriticalImagesFinder::UpdateCriticalImagesSetInDriver(
RewriteDriver* driver) {
// Don't update critical_images_info if it's already been set.
if (driver->critical_images_info() != NULL) {
return;
}
CriticalImagesInfo* info = NULL;
PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
const PropertyCache::Cohort* cohort =
page_property_cache->GetCohort(GetCriticalImagesCohort());
// Fallback properties can be used for critical images.
AbstractPropertyPage* page = driver->fallback_property_page();
if (page != NULL && cohort != NULL) {
PropertyValue* property_value = page->GetProperty(
cohort, kCriticalImagesPropertyName);
info = ExtractCriticalImagesFromCache(driver, property_value);
if (info != NULL) {
driver->log_record()->SetNumHtmlCriticalImages(
info->html_critical_images.size());
driver->log_record()->SetNumCssCriticalImages(
info->css_critical_images.size());
}
}
// Store an empty CriticalImagesInfo back into the driver if we don't have any
// beacon results yet.
if (info == NULL) {
info = new CriticalImagesInfo;
}
driver->set_critical_images_info(info);
}
// TODO(pulkitg): Change all instances of critical_images_set to
// html_critical_images_set.
bool CriticalImagesFinder::UpdateCriticalImagesCacheEntryFromDriver(
RewriteDriver* driver, StringSet* critical_images_set,
StringSet* css_critical_images_set) {
// Update property cache if above the fold critical images are successfully
// determined.
// Fallback properties will be updated for critical images.
AbstractPropertyPage* page = driver->fallback_property_page();
PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
return UpdateCriticalImagesCacheEntry(
page, page_property_cache, critical_images_set, css_critical_images_set);
}
bool CriticalImagesFinder::UpdateCriticalImagesCacheEntry(
AbstractPropertyPage* page, PropertyCache* page_property_cache,
StringSet* html_critical_images_set, StringSet* css_critical_images_set) {
// Update property cache if above the fold critical images are successfully
// determined.
scoped_ptr<StringSet> html_critical_images(html_critical_images_set);
scoped_ptr<StringSet> css_critical_images(css_critical_images_set);
if (page_property_cache != NULL && page != NULL) {
const PropertyCache::Cohort* cohort =
page_property_cache->GetCohort(GetCriticalImagesCohort());
if (cohort != NULL) {
PropertyValue* property_value = page->GetProperty(
cohort, kCriticalImagesPropertyName);
// Read in the current critical images, and preserve the current HTML or
// CSS critical images if they are not being updated.
CriticalImages critical_images;
PopulateCriticalImagesFromPropertyValue(property_value, &critical_images);
bool updated = UpdateCriticalImages(
html_critical_images.get(), css_critical_images.get(),
&critical_images);
if (updated) {
GoogleString buf;
if (critical_images.SerializeToString(&buf)) {
// The property cache won't store an empty value, which is what an
// empty CriticalImages will serialize to. If buf is an empty string,
// repalce with a placeholder that we can then handle when decoding
// the property_cache value in
// PopulateCriticalImagesFromPropertyValue.
if (buf.empty()) {
buf = kEmptyValuePlaceholder;
}
page->UpdateValue(cohort, kCriticalImagesPropertyName, buf);
} else {
LOG(WARNING) << "Serialization of critical images protobuf failed.";
return false;
}
}
return updated;
} else {
LOG(WARNING) << "Critical Images Cohort is NULL.";
}
}
return false;
}
bool CriticalImagesFinder::UpdateCriticalImages(
const StringSet* html_critical_images,
const StringSet* css_critical_images,
CriticalImages* critical_images) const {
DCHECK(critical_images != NULL);
if (html_critical_images != NULL) {
UpdateCriticalImagesSetInProto(
*html_critical_images,
NumSetsToKeep(),
PercentSeenForCritical(),
critical_images->mutable_html_critical_images_sets(),
critical_images->mutable_html_critical_images());
}
if (css_critical_images != NULL) {
UpdateCriticalImagesSetInProto(
*css_critical_images,
NumSetsToKeep(),
PercentSeenForCritical(),
critical_images->mutable_css_critical_images_sets(),
critical_images->mutable_css_critical_images());
}
// We updated if either StringSet* was set.
return (html_critical_images != NULL || css_critical_images != NULL);
}
CriticalImagesInfo* CriticalImagesFinder::ExtractCriticalImagesFromCache(
RewriteDriver* driver,
const PropertyValue* property_value) {
CriticalImagesInfo* critical_images_info = NULL;
// Don't track stats if we are flushing early, since we will already be
// counting this when we are rewriting the full page.
bool track_stats = !driver->flushing_early();
const PropertyCache* page_property_cache =
driver->server_context()->page_property_cache();
int64 cache_ttl_ms =
driver->options()->finder_properties_cache_expiration_time_ms();
// Check if the cache value exists and is not expired.
if (property_value->has_value()) {
const bool is_valid =
!page_property_cache->IsExpired(property_value, cache_ttl_ms);
if (is_valid) {
critical_images_info =
CriticalImagesInfoFromPropertyValue(property_value);
if (track_stats) {
if (critical_images_info == NULL) {
critical_images_not_found_count_->Add(1);
} else {
critical_images_valid_count_->Add(1);
}
}
} else if (track_stats) {
critical_images_expired_count_->Add(1);
}
} else if (track_stats) {
critical_images_not_found_count_->Add(1);
}
return critical_images_info;
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before>
// Copyright (c) 2013-2019 niXman (github dotty nixman doggy pm dotty me)
// All rights reserved.
//
// This file is part of EASYNET(https://github.com/niXman/easynet) project.
//
// 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 {organization} 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 <easynet/socket.hpp>
#include <easynet/acceptor.hpp>
#include "../tests_config.hpp"
#include <boost/asio/io_context.hpp>
#include <iostream>
/***************************************************************************/
struct session: std::enable_shared_from_this<session> {
session(easynet::socket sock)
:socket(std::move(sock))
{}
virtual ~session() {}
void start() {
socket.async_read(tests_config::buffer_size, shared_from_this(), &session::read_handler);
}
void read_handler(const boost::system::error_code& ec, easynet::shared_buffer buf, size_t rd) {
std::cout
<< "read_handler: ec = " << ec << ", buf = " << easynet::buffer_data(buf) << ", rd = " << rd
<< std::endl;
if ( !ec ) {
socket.async_write(buf, shared_from_this(), &session::write_handler);
} else {
std::cout << "[2] ec = " << ec << std::endl;
}
}
void write_handler(const boost::system::error_code& ec, easynet::shared_buffer buf, size_t wr) {
std::cout
<< "write_handler: ec = " << ec << ", buf = " << easynet::buffer_data(buf) << ", wr = " << wr
<< std::endl;
if ( !ec ) {
start();
} else {
std::cout << "[3] ec = " << ec << std::endl;
}
}
private:
easynet::socket socket;
};
/***************************************************************************/
struct server {
server(boost::asio::io_context& ios, const char* ip, boost::uint16_t port)
:acceptor(ios, ip, port)
{}
void start() {
acceptor.async_accept(this, &server::on_accept);
}
void on_accept(easynet::socket socket, const easynet::endpoint &ep, const easynet::error_code &ec) {
std::cout << "new connection from " << ep << ", ec = " << ec << std::endl;
if ( !ec ) {
auto s = std::make_shared<session>(std::move(socket));
s->start();
} else {
std::cout << "[1] ec = " << ec << std::endl;
}
}
private:
easynet::acceptor acceptor;
};
/***************************************************************************/
int main() {
try {
boost::asio::io_context ios;
server server(ios, tests_config::ip, tests_config::port);
server.start();
ios.run();
} catch (const std::exception &ex) {
std::cout << "[exception]: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/***************************************************************************/
<commit_msg>some fixes<commit_after>
// Copyright (c) 2013-2019 niXman (github dotty nixman doggy pm dotty me)
// All rights reserved.
//
// This file is part of EASYNET(https://github.com/niXman/easynet) project.
//
// 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 {organization} 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 <easynet/socket.hpp>
#include <easynet/acceptor.hpp>
#include "../tests_config.hpp"
#include <boost/asio/io_context.hpp>
#include <iostream>
/***************************************************************************/
struct session: std::enable_shared_from_this<session> {
session(easynet::socket sock)
:socket(std::move(sock))
{}
virtual ~session() {}
void start() {
socket.async_read(tests_config::buffer_size, shared_from_this(), &session::read_handler);
}
void read_handler(const easynet::error_code& ec, easynet::shared_buffer buf, size_t rd) {
std::cout
<< "read_handler: ec = " << ec << ", buf = " << easynet::buffer_data(buf) << ", rd = " << rd
<< std::endl;
if ( !ec ) {
socket.async_write(buf, shared_from_this(), &session::write_handler);
} else {
std::cout << "[2] ec = " << ec << std::endl;
}
}
void write_handler(const easynet::error_code& ec, easynet::shared_buffer buf, size_t wr) {
std::cout
<< "write_handler: ec = " << ec << ", buf = " << easynet::buffer_data(buf) << ", wr = " << wr
<< std::endl;
if ( !ec ) {
start();
} else {
std::cout << "[3] ec = " << ec << std::endl;
}
}
private:
easynet::socket socket;
};
/***************************************************************************/
struct server {
server(boost::asio::io_context &ios, const char *ip, boost::uint16_t port)
:acceptor(ios, ip, port)
{}
void start() {
acceptor.async_accept(this, &server::on_accept);
}
void on_accept(easynet::socket socket, const easynet::endpoint &ep, const easynet::error_code &ec) {
std::cout << "new connection from " << ep << ", ec = " << ec << std::endl;
if ( !ec ) {
auto s = std::make_shared<session>(std::move(socket));
s->start();
} else {
std::cout << "[1] ec = " << ec << std::endl;
}
}
private:
easynet::acceptor acceptor;
};
/***************************************************************************/
int main() {
try {
boost::asio::io_context ios;
server server(ios, tests_config::ip, tests_config::port);
server.start();
ios.run();
} catch (const std::exception &ex) {
std::cout << "[exception]: " << ex.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/***************************************************************************/
<|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-CHROMIUM file.
#include "brightray/browser/browser_main_parts.h"
#if defined(OSX_POSIX)
#include <stdlib.h>
#endif
#include <sys/stat.h>
#include <string>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/devtools_manager_delegate.h"
#include "brightray/browser/web_ui_controller_factory.h"
#include "brightray/common/application_info.h"
#include "brightray/common/main_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "brightray/browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
std::unique_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
base::string16 MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Communications");
#endif
default:
return base::string16();
}
}
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
#if defined(OS_WIN) || defined(OS_LINUX)
void OverrideAppLogsPath() {
#if defined(OS_WIN)
std::wstring app_name = base::UTF8ToWide(GetApplicationName());
std::wstring home = _wgetenv(L"HOMEDRIVE") + "\\" +_wgetenv(L"HOMEPATH");
std::wstring log_path = home + L"\\AppData\\Roaming\\";
std::wstring app_log_path = log_path + app_name + L"\\logs";
#else
std::string app_name = GetApplicationName();
std::string home_path = std::string(getenv("HOME"));
std::string app_log_path = home_path + "/.config/" + app_name + "/logs";
#endif
PathService::Override(DIR_APP_LOGS, base::FilePath(app_log_path));
}
#endif
void BrowserMainParts::PreEarlyInitialization() {
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
OverrideAppLogsPath();
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtkUi());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
ui::MaterialDesignController::Initialize();
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
#endif
#if defined(USE_AURA)
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
l10n_util::OverrideLocaleWithCocoaLocale();
#endif
InitializeResourceBundle("");
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
}
void BrowserMainParts::PreMainMessageLoopRun() {
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
DevToolsManagerDelegate::StartHttpHandler();
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
display::Screen* screen = views::CreateDesktopScreen();
display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif
if (!views::LayoutProvider::Get())
layout_provider_.reset(new views::LayoutProvider());
return 0;
}
void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}
} // namespace brightray
<commit_msg>appropriately cast pointers to strings<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-CHROMIUM file.
#include "brightray/browser/browser_main_parts.h"
#if defined(OSX_POSIX)
#include <stdlib.h>
#endif
#include <sys/stat.h>
#include <string>
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/devtools_manager_delegate.h"
#include "brightray/browser/web_ui_controller_factory.h"
#include "brightray/common/application_info.h"
#include "brightray/common/main_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "brightray/browser/views/views_delegate.h"
#endif
#if defined(USE_X11)
#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif
#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif
namespace brightray {
namespace {
#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
return 10;
}
#endif
#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;
// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;
void OverrideLinuxAppDataPath() {
base::FilePath path;
if (PathService::Get(DIR_APP_DATA, &path))
return;
std::unique_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
PathService::Override(DIR_APP_DATA, path);
}
int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
if (!g_in_x11_io_error_handler) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
}
return 0;
}
// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
// Ensure function isn't optimized away.
asm("");
sleep(kWaitForUIThreadSeconds);
}
int BrowserX11IOErrorHandler(Display* d) {
if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
// Wait for the UI thread (which has a different connection to the X server)
// to get the error. We can't call shutdown from this thread without
// tripping an error. Doing it through a function so that we'll be able
// to see it in any crash dumps.
WaitingForUIThreadToHandleIOError();
return 0;
}
// If there's an IO error it likely means the X server has gone away.
// If this CHECK fails, then that means SessionEnding() below triggered some
// code that tried to talk to the X server, resulting in yet another error.
CHECK(!g_in_x11_io_error_handler);
g_in_x11_io_error_handler = true;
LOG(ERROR) << "X IO error received (X server probably went away)";
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
return 0;
}
int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
return 0;
}
int X11EmptyIOErrorHandler(Display* d) {
return 0;
}
#endif
base::string16 MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return base::ASCIIToUTF16("Communications");
#endif
default:
return base::string16();
}
}
} // namespace
BrowserMainParts::BrowserMainParts() {
}
BrowserMainParts::~BrowserMainParts() {
}
#if defined(OS_WIN) || defined(OS_LINUX)
void OverrideAppLogsPath() {
#if defined(OS_WIN)
std::wstring app_name = base::UTF8ToWide(GetApplicationName());
std::wstring home = std::wstring(_wgetenv(L"HOMEDRIVE"));
std::wstring drive = std::wstring(_wgetenv(L"HOMEPATH"));
std::wstring log_path = home + L"\\" + drive + L"\\AppData\\Roaming\\";
std::wstring app_log_path = log_path + app_name + L"\\logs";
#else
std::string app_name = GetApplicationName();
std::string home_path = std::string(getenv("HOME"));
std::string app_log_path = home_path + "/.config/" + app_name + "/logs";
#endif
PathService::Override(DIR_APP_LOGS, base::FilePath(app_log_path));
}
#endif
void BrowserMainParts::PreEarlyInitialization() {
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine("", "");
base::FeatureList::SetInstance(std::move(feature_list));
OverrideAppLogsPath();
#if defined(USE_X11)
views::LinuxUI::SetInstance(BuildGtkUi());
OverrideLinuxAppDataPath();
// Installs the X11 error handlers for the browser process used during
// startup. They simply print error messages and exit because
// we can't shutdown properly while creating and initializing services.
ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}
void BrowserMainParts::ToolkitInitialized() {
ui::MaterialDesignController::Initialize();
#if defined(USE_AURA) && defined(USE_X11)
views::LinuxUI::instance()->Initialize();
#endif
#if defined(USE_AURA)
wm_state_.reset(new wm::WMState);
#endif
#if defined(TOOLKIT_VIEWS)
views_delegate_.reset(new ViewsDelegate);
#endif
#if defined(OS_WIN)
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
wchar_t module_name[MAX_PATH] = { 0 };
if (GetModuleFileName(NULL, module_name, MAX_PATH))
ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}
void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
l10n_util::OverrideLocaleWithCocoaLocale();
#endif
InitializeResourceBundle("");
#if defined(OS_MACOSX)
InitializeMainNib();
#endif
media::SetLocalizedStringProvider(MediaStringProvider);
}
void BrowserMainParts::PreMainMessageLoopRun() {
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
// --remote-debugging-port
auto command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
DevToolsManagerDelegate::StartHttpHandler();
}
void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
// Installs the X11 error handlers for the browser process after the
// main message loop has started. This will allow us to exit cleanly
// if X exits before us.
ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}
void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
// Unset the X11 error handlers. The X11 error handlers log the errors using a
// |PostTask()| on the message-loop. But since the message-loop is in the
// process of terminating, this can cause errors.
ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}
int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
display::Screen* screen = views::CreateDesktopScreen();
display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif
if (!views::LayoutProvider::Get())
layout_provider_.reset(new views::LayoutProvider());
return 0;
}
void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}
} // namespace brightray
<|endoftext|>
|
<commit_before>#include "rename_buffer.h"
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <sys/stat.h>
#include <utility>
#include <vector>
#include "../../log.h"
#include "batch_handler.h"
#include "recent_file_cache.h"
using std::endl;
using std::move;
using std::ostream;
using std::set;
using std::shared_ptr;
using std::static_pointer_cast;
using std::string;
using std::vector;
RenameBufferEntry::RenameBufferEntry(RenameBufferEntry &&original) noexcept :
entry(move(original.entry)),
current{original.current},
age{original.age}
{
//
}
RenameBufferEntry::RenameBufferEntry(std::shared_ptr<PresentEntry> entry, bool current) :
entry{std::move(entry)},
current{current},
age{0}
{
//
}
bool RenameBuffer::observe_event(Event &event, RecentFileCache &cache)
{
const shared_ptr<StatResult> &former = event.get_former();
const shared_ptr<StatResult> ¤t = event.get_current();
bool handled = false;
if (current->could_be_rename_of(*former)) {
// inode and entry kind are still the same. Stale ItemRenamed bit, most likely.
return false;
}
if (current->is_present()) {
shared_ptr<PresentEntry> current_present = static_pointer_cast<PresentEntry>(current);
if (observe_present_entry(event, cache, current_present, true)) handled = true;
}
if (former->is_present()) {
shared_ptr<PresentEntry> former_present = static_pointer_cast<PresentEntry>(former);
if (observe_present_entry(event, cache, former_present, false)) handled = true;
}
if (former->is_absent() && current->is_absent()) {
shared_ptr<AbsentEntry> current_absent = static_pointer_cast<AbsentEntry>(current);
if (observe_absent(event, cache, current_absent)) handled = true;
}
return handled;
}
bool RenameBuffer::observe_present_entry(Event &event,
RecentFileCache &cache,
const shared_ptr<PresentEntry> &present,
bool current)
{
ostream &logline = LOGGER << "Rename ";
auto maybe_entry = observed_by_inode.find(present->get_inode());
if (maybe_entry == observed_by_inode.end()) {
// The first-seen half of this rename event. Buffer a new entry to be paired with the second half when or if it's
// observed.
RenameBufferEntry entry(present, current);
observed_by_inode.emplace(present->get_inode(), move(entry));
logline << "first half " << *present << ": Remembering for later." << endl;
return true;
}
RenameBufferEntry &existing = maybe_entry->second;
if (present->could_be_rename_of(*(existing.entry))) {
// The inodes and entry kinds match, so with high probability, we've found the other half of the rename.
// Huzzah! Huzzah forever!
bool handled = false;
if (!existing.current && current) {
// The former end is the "from" end and the current end is the "to" end.
logline << "completed pair " << *existing.entry << " => " << *present << ": Emitting rename event." << endl;
cache.evict(existing.entry);
event.message_buffer().renamed(
string(existing.entry->get_path()), string(present->get_path()), present->get_entry_kind());
handled = true;
} else if (existing.current && !current) {
// The former end is the "to" end and the current end is the "from" end.
logline << "completed pair " << *present << " => " << *existing.entry << ": Emitting rename event." << endl;
cache.evict(present);
event.message_buffer().renamed(
string(present->get_path()), string(existing.entry->get_path()), existing.entry->get_entry_kind());
handled = true;
} else {
// Either both entries are still present (hardlink, re-used inode?) or both are missing (rapidly renamed and
// deleted?) This could happen if the entry is renamed again between the lstat() calls, possibly.
string existing_desc = existing.current ? " (current) " : " (former) ";
string incoming_desc = current ? " (current) " : " (former) ";
logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc
<< "are both present." << endl;
handled = false;
}
observed_by_inode.erase(maybe_entry);
return handled;
}
string existing_desc = existing.current ? " (current) " : " (former) ";
string incoming_desc = current ? " (current) " : " (former) ";
logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc
<< "have conflicting entry kinds." << endl;
return false;
}
bool RenameBuffer::observe_absent(Event &event, RecentFileCache & /*cache*/, const std::shared_ptr<AbsentEntry> &absent)
{
LOGGER << "Unable to correlate rename from " << absent->get_path() << " without an inode." << endl;
if (event.flag_created() ^ event.flag_deleted()) {
// this entry was created just before being renamed or deleted just after being renamed.
event.message_buffer().created(string(absent->get_path()), absent->get_entry_kind());
event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind());
} else if (!event.flag_created() && !event.flag_deleted()) {
// former must have been evicted from the cache.
event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind());
}
return true;
}
shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer)
{
shared_ptr<set<Key>> all(new set<Key>);
for (auto &it : observed_by_inode) {
all->insert(it.first);
}
return flush_unmatched(message_buffer, all);
}
shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer,
const shared_ptr<set<Key>> &keys)
{
shared_ptr<set<Key>> aged(new set<Key>);
vector<Key> to_erase;
for (auto &it : observed_by_inode) {
const Key &key = it.first;
if (keys->count(key) == 0) continue;
RenameBufferEntry &existing = it.second;
shared_ptr<PresentEntry> entry = existing.entry;
if (existing.age == 0u) {
existing.age++;
aged->insert(key);
continue;
}
if (existing.current) {
message_buffer.created(string(entry->get_path()), entry->get_entry_kind());
} else {
message_buffer.deleted(string(entry->get_path()), entry->get_entry_kind());
}
to_erase.push_back(key);
}
for (Key &key : to_erase) {
observed_by_inode.erase(key);
}
return aged;
}
void RenameBuffer::update_for_rename(const string &from_dir_path, const string &to_dir_path)
{
for (auto &pair : observed_by_inode) {
pair.second.update_for_rename(from_dir_path, to_dir_path);
}
}
<commit_msg>Update cached paths when a parent directory is renamed<commit_after>#include "rename_buffer.h"
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <sys/stat.h>
#include <utility>
#include <vector>
#include "../../log.h"
#include "batch_handler.h"
#include "recent_file_cache.h"
using std::endl;
using std::move;
using std::ostream;
using std::set;
using std::shared_ptr;
using std::static_pointer_cast;
using std::string;
using std::vector;
RenameBufferEntry::RenameBufferEntry(RenameBufferEntry &&original) noexcept :
entry(move(original.entry)),
current{original.current},
age{original.age}
{
//
}
RenameBufferEntry::RenameBufferEntry(std::shared_ptr<PresentEntry> entry, bool current) :
entry{std::move(entry)},
current{current},
age{0}
{
//
}
bool RenameBuffer::observe_event(Event &event, RecentFileCache &cache)
{
const shared_ptr<StatResult> &former = event.get_former();
const shared_ptr<StatResult> ¤t = event.get_current();
bool handled = false;
if (current->could_be_rename_of(*former)) {
// inode and entry kind are still the same. Stale ItemRenamed bit, most likely.
return false;
}
if (current->is_present()) {
shared_ptr<PresentEntry> current_present = static_pointer_cast<PresentEntry>(current);
if (observe_present_entry(event, cache, current_present, true)) handled = true;
}
if (former->is_present()) {
shared_ptr<PresentEntry> former_present = static_pointer_cast<PresentEntry>(former);
if (observe_present_entry(event, cache, former_present, false)) handled = true;
}
if (former->is_absent() && current->is_absent()) {
shared_ptr<AbsentEntry> current_absent = static_pointer_cast<AbsentEntry>(current);
if (observe_absent(event, cache, current_absent)) handled = true;
}
return handled;
}
bool RenameBuffer::observe_present_entry(Event &event,
RecentFileCache &cache,
const shared_ptr<PresentEntry> &present,
bool current)
{
ostream &logline = LOGGER << "Rename ";
auto maybe_entry = observed_by_inode.find(present->get_inode());
if (maybe_entry == observed_by_inode.end()) {
// The first-seen half of this rename event. Buffer a new entry to be paired with the second half when or if it's
// observed.
RenameBufferEntry entry(present, current);
observed_by_inode.emplace(present->get_inode(), move(entry));
logline << "first half " << *present << ": Remembering for later." << endl;
return true;
}
RenameBufferEntry &existing = maybe_entry->second;
if (present->could_be_rename_of(*(existing.entry))) {
// The inodes and entry kinds match, so with high probability, we've found the other half of the rename.
// Huzzah! Huzzah forever!
bool handled = false;
if (!existing.current && current) {
// The former end is the "from" end and the current end is the "to" end.
logline << "completed pair " << *existing.entry << " => " << *present << ": Emitting rename event." << endl;
EntryKind kind = present->get_entry_kind();
string from_path(existing.entry->get_path());
string to_path(present->get_path());
cache.evict(existing.entry);
if (kind == KIND_DIRECTORY || kind == KIND_UNKNOWN) {
cache.update_for_rename(from_path, to_path);
update_for_rename(from_path, to_path);
}
event.message_buffer().renamed(move(from_path), move(to_path), kind);
handled = true;
} else if (existing.current && !current) {
// The former end is the "to" end and the current end is the "from" end.
logline << "completed pair " << *present << " => " << *existing.entry << ": Emitting rename event." << endl;
EntryKind kind = existing.entry->get_entry_kind();
string from_path(present->get_path());
string to_path(existing.entry->get_path());
cache.evict(present);
if (kind == KIND_DIRECTORY || kind == KIND_UNKNOWN) {
cache.update_for_rename(from_path, to_path);
update_for_rename(from_path, to_path);
}
event.message_buffer().renamed(move(from_path), move(to_path), kind);
handled = true;
} else {
// Either both entries are still present (hardlink, re-used inode?) or both are missing (rapidly renamed and
// deleted?) This could happen if the entry is renamed again between the lstat() calls, possibly.
string existing_desc = existing.current ? " (current) " : " (former) ";
string incoming_desc = current ? " (current) " : " (former) ";
logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc
<< "are both present." << endl;
handled = false;
}
observed_by_inode.erase(maybe_entry);
return handled;
}
string existing_desc = existing.current ? " (current) " : " (former) ";
string incoming_desc = current ? " (current) " : " (former) ";
logline << "conflicting pair " << *present << incoming_desc << " =/= " << *(existing.entry) << existing_desc
<< "have conflicting entry kinds." << endl;
return false;
}
bool RenameBuffer::observe_absent(Event &event, RecentFileCache & /*cache*/, const std::shared_ptr<AbsentEntry> &absent)
{
LOGGER << "Unable to correlate rename from " << absent->get_path() << " without an inode." << endl;
if (event.flag_created() ^ event.flag_deleted()) {
// this entry was created just before being renamed or deleted just after being renamed.
event.message_buffer().created(string(absent->get_path()), absent->get_entry_kind());
event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind());
} else if (!event.flag_created() && !event.flag_deleted()) {
// former must have been evicted from the cache.
event.message_buffer().deleted(string(absent->get_path()), absent->get_entry_kind());
}
return true;
}
shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer)
{
shared_ptr<set<Key>> all(new set<Key>);
for (auto &it : observed_by_inode) {
all->insert(it.first);
}
return flush_unmatched(message_buffer, all);
}
shared_ptr<set<RenameBuffer::Key>> RenameBuffer::flush_unmatched(ChannelMessageBuffer &message_buffer,
const shared_ptr<set<Key>> &keys)
{
shared_ptr<set<Key>> aged(new set<Key>);
vector<Key> to_erase;
for (auto &it : observed_by_inode) {
const Key &key = it.first;
if (keys->count(key) == 0) continue;
RenameBufferEntry &existing = it.second;
shared_ptr<PresentEntry> entry = existing.entry;
if (existing.age == 0u) {
existing.age++;
aged->insert(key);
continue;
}
if (existing.current) {
message_buffer.created(string(entry->get_path()), entry->get_entry_kind());
} else {
message_buffer.deleted(string(entry->get_path()), entry->get_entry_kind());
}
to_erase.push_back(key);
}
for (Key &key : to_erase) {
observed_by_inode.erase(key);
}
return aged;
}
void RenameBuffer::update_for_rename(const string &from_dir_path, const string &to_dir_path)
{
for (auto &pair : observed_by_inode) {
pair.second.update_for_rename(from_dir_path, to_dir_path);
}
}
<|endoftext|>
|
<commit_before>#include "chr/FileSystem.h"
#include "chr/MemoryBuffer.h"
using namespace std;
namespace chr
{
bool hasFileResources()
{
#if defined(CHR_FS_APK) || defined(CHR_FS_RC) || defined(CHR_FS_JS_EMBED) || defined(CHR_FS_JS_PRELOAD)
return false;
#else
return true;
#endif
}
bool hasMemoryResources()
{
#if defined(CHR_FS_APK) || defined(CHR_FS_RC) || defined(CHR_FS_JS_EMBED) || defined(CHR_FS_JS_PRELOAD)
return true;
#else
return false;
#endif
}
fs::path getResourceFilePath(const fs::path &relativePath)
{
fs::path basePath;
#if defined(CHR_FS_APK) || defined(CHR_FS_RC)
return "";
#elif defined(CHR_FS_BUNDLE)
CFBundleRef bundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyBundleURL(bundle);
CFStringRef tmp = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
CFIndex length = CFStringGetLength(tmp);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
char *buffer = (char*)malloc(maxSize);
CFStringGetCString(tmp, buffer, maxSize, kCFStringEncodingUTF8);
basePath = fs::path(buffer);
CFRelease(url);
CFRelease(tmp);
free(buffer);
#elif defined(CHR_PLATFORM_ANDROID) // TODO: CONSIDER "GENERALIZING" TO LINUX
static char buf[PATH_MAX];
auto len = readlink("/proc/self/exe", buf, PATH_MAX - 1);
assert(len > 0);
basePath = fs::path(string(buf, len)).parent_path();
#elif defined(CHR_PLATFORM_EMSCRIPTEN)
basePath = "res";
#else
basePath = fs::current_path() / "res";
#endif
return basePath / relativePath;
}
shared_ptr<MemoryBuffer> getResourceBuffer(const fs::path &relativePath)
{
#if !defined(CHR_FS_APK) && !defined(CHR_FS_RC) && !defined(CHR_FS_JS_EMBED) && !defined(CHR_FS_JS_PRELOAD)
return nullptr;
#endif
auto buffer = make_shared<MemoryBuffer>();
buffer->lock(relativePath);
return buffer;
}
shared_ptr<istream> getResourceStream(const fs::path &relativePath)
{
istream *stream;
if (chr::hasMemoryResources())
{
auto memoryBuffer = chr::getResourceBuffer(relativePath);
if (memoryBuffer)
{
stream = new imemstream(memoryBuffer);
}
else
{
return nullptr;
}
}
else if (chr::hasFileResources())
{
stream = new fs::ifstream(chr::getResourceFilePath(relativePath), ifstream::binary);
}
return shared_ptr<istream>(stream);
}
}
<commit_msg>WARNING<commit_after>#include "chr/FileSystem.h"
#include "chr/MemoryBuffer.h"
using namespace std;
namespace chr
{
bool hasFileResources()
{
#if defined(CHR_FS_APK) || defined(CHR_FS_RC) || defined(CHR_FS_JS_EMBED) || defined(CHR_FS_JS_PRELOAD)
return false;
#else
return true;
#endif
}
bool hasMemoryResources()
{
#if defined(CHR_FS_APK) || defined(CHR_FS_RC) || defined(CHR_FS_JS_EMBED) || defined(CHR_FS_JS_PRELOAD)
return true;
#else
return false;
#endif
}
fs::path getResourceFilePath(const fs::path &relativePath)
{
fs::path basePath;
#if defined(CHR_FS_APK) || defined(CHR_FS_RC)
return "";
#elif defined(CHR_FS_BUNDLE)
CFBundleRef bundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyBundleURL(bundle);
CFStringRef tmp = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
CFIndex length = CFStringGetLength(tmp);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
char *buffer = (char*)malloc(maxSize);
CFStringGetCString(tmp, buffer, maxSize, kCFStringEncodingUTF8);
basePath = fs::path(buffer);
CFRelease(url);
CFRelease(tmp);
free(buffer);
#elif defined(CHR_PLATFORM_ANDROID) // TODO: CONSIDER "GENERALIZING" TO LINUX
static char buf[PATH_MAX];
auto len = readlink("/proc/self/exe", buf, PATH_MAX - 1);
assert(len > 0);
basePath = fs::path(string(buf, len)).parent_path();
#elif defined(CHR_PLATFORM_EMSCRIPTEN)
basePath = "res";
#else
basePath = fs::current_path() / "res";
#endif
return basePath / relativePath;
}
shared_ptr<MemoryBuffer> getResourceBuffer(const fs::path &relativePath)
{
#if !defined(CHR_FS_APK) && !defined(CHR_FS_RC) && !defined(CHR_FS_JS_EMBED) && !defined(CHR_FS_JS_PRELOAD)
return nullptr;
#endif
auto buffer = make_shared<MemoryBuffer>();
buffer->lock(relativePath);
return buffer;
}
shared_ptr<istream> getResourceStream(const fs::path &relativePath)
{
istream *stream;
if (chr::hasMemoryResources())
{
auto memoryBuffer = chr::getResourceBuffer(relativePath);
if (memoryBuffer)
{
stream = new imemstream(memoryBuffer); // FIXME: PROBLEMATIC BECAUSE memoryBuffer WILL BE DEALLOCATED
}
else
{
return nullptr;
}
}
else if (chr::hasFileResources())
{
stream = new fs::ifstream(chr::getResourceFilePath(relativePath), ifstream::binary);
}
return shared_ptr<istream>(stream);
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: SmoothingRecursiveGaussianImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {SmoothingRecursiveGaussianImageFilterOutput3.png}
// 3
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {SmoothingRecursiveGaussianImageFilterOutput5.png}
// 5
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The classical method of smoothing an image by convolution with a Gaussian
// kernel has the drawback that it is slow when the standard deviation $\sigma$ of
// the Gaussian is large. This is due to the larger size of the kernel,
// which results in a higher number of computations per pixel.
//
// The \doxygen{RecursiveGaussianImageFilter} implements an approximation of
// convolution with the Gaussian and its derivatives by using
// IIR\footnote{Infinite Impulse Response} filters. In practice this filter
// requires a constant number of operations for approximating the convolution,
// regardless of the $\sigma$ value \cite{Deriche1990,Deriche1993}.
//
// \index{itk::RecursiveGaussianImageFilter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step required to use this filter is to include its header file.
//
// \index{itk::RecursiveGaussianImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkRecursiveGaussianImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile sigma " << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// Types should be selected on the desired input and output pixel types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef float InputPixelType;
typedef float OutputPixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input and output image types are instantiated using the pixel types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
// Software Guide : BeginLatex
//
// The filter type is now instantiated using both the input image and the
// output image types.
//
// \index{itk::RecursiveGaussianImageFilter!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RecursiveGaussianImageFilter<
InputImageType, OutputImageType > FilterType;
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// Software Guide : BeginLatex
//
// This filter applies the approximation of the convolution along a single
// dimension. It is therefore necessary to concatenate several of these filters
// to produce smoothing in all directions. In this example, we create a pair
// of filters since we are processing a $2D$ image. The filters are
// created by invoking the \code{New()} method and assigning the result to
// a \doxygen{SmartPointer}.
//
// \index{itk::RecursiveGaussianImageFilter!New()}
// \index{itk::RecursiveGaussianImageFilter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FilterType::Pointer filterX = FilterType::New();
FilterType::Pointer filterY = FilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since each one of the newly created filters has the potential to perform
// filtering along any dimension, we have to restrict each one to a
// particular direction. This is done with the \code{SetDirection()} method.
//
// \index{RecursiveGaussianImageFilter!SetDirection()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetDirection( 0 ); // 0 --> X direction
filterY->SetDirection( 1 ); // 1 --> Y direction
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{RecursiveGaussianImageFilter} can approximate the
// convolution with the Gaussian or with its first and second
// derivatives. We select one of these options by using the
// \code{SetOrder()} method. Note that the argument is an \code{enum} whose
// values can be \code{ZeroOrder}, \code{FirstOrder} and
// \code{SecondOrder}. For example, to compute the $x$ partial derivative we
// should select \code{FirstOrder} for $x$ and \code{ZeroOrder} for
// $y$. Here we want only to smooth in $x$ and $y$, so we select
// \code{ZeroOrder} in both directions.
//
// \index{RecursiveGaussianImageFilter!SetOrder()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetOrder( FilterType::ZeroOrder );
filterY->SetOrder( FilterType::ZeroOrder );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// There are two typical ways of normalizing Gaussians depending on their
// application. For scale-space analysis it is desirable to use a
// normalization that will preserve the maximum value of the input. This
// normalization is represented by the following equation.
//
// \begin{equation}
// \frac{ 1 }{ \sigma \sqrt{ 2 \pi } }
// \end{equation}
//
// In applications that use the Gaussian as a solution of the diffusion
// equation it is desirable to use a normalization that preserve the
// integral of the signal. This last approach can be seen as a conservation
// of mass principle. This is represented by the following equation.
//
// \begin{equation}
// \frac{ 1 }{ \sigma^2 \sqrt{ 2 \pi } }
// \end{equation}
//
// The \doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows
// users to select between these two normalization options. Selection is
// done with the method \code{SetNormalizeAcrossScale()}. Enable this flag
// to analyzing an image across scale-space. In the current example, this
// setting has no impact because we are actually renormalizing the output to
// the dynamic range of the reader, so we simply disable the flag.
//
// \index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetNormalizeAcrossScale( false );
filterY->SetNormalizeAcrossScale( false );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input image can be obtained from the output of another
// filter. Here, an image reader is used as the source. The image is passed to
// the $x$ filter and then to the $y$ filter. The reason for keeping these
// two filters separate is that it is usual in scale-space applications to
// compute not only the smoothing but also combinations of derivatives at
// different orders and smoothing. Some factorization is possible when
// separate filters are used to generate the intermediate results. Here
// this capability is less interesting, though, since we only want to smooth
// the image in all directions.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetInput( reader->GetOutput() );
filterY->SetInput( filterX->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// It is now time to select the $\sigma$ of the Gaussian used to smooth the
// data. Note that $\sigma$ must be passed to both filters and that sigma
// is considered to be in millimeters. That is, at the moment of applying
// the smoothing process, the filter will take into account the spacing
// values defined in the image.
//
// \index{itk::RecursiveGaussianImageFilter!SetSigma()}
// \index{SetSigma()!itk::RecursiveGaussianImageFilter}
//
// Software Guide : EndLatex
const double sigma = atof( argv[3] );
// Software Guide : BeginCodeSnippet
filterX->SetSigma( sigma );
filterY->SetSigma( sigma );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally the pipeline is executed by invoking the \code{Update()} method.
//
// \index{itk::RecursiveGaussianImageFilter!Update()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterY->Update();
// Software Guide : EndCodeSnippet
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
OutputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
rescaler->SetInput( filterY->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{SmoothingRecursiveGaussianImageFilterOutput3.eps}
// \includegraphics[width=0.44\textwidth]{SmoothingRecursiveGaussianImageFilterOutput5.eps}
// \itkcaption[Output of the RecursiveGaussianImageFilter.]{Effect of the
// RecursiveGaussianImageFilter on a slice from a MRI proton density image
// of the brain.}
// \label{fig:RecursiveGaussianImageFilterInputOutput}
// \end{figure}
//
// Figure~\ref{fig:RecursiveGaussianImageFilterInputOutput} illustrates the
// effect of this filter on a MRI proton density image of the brain using
// $\sigma$ values of $3$ (left) and $5$ (right). The figure shows how the
// attenuation of noise can be regulated by selecting the appropriate
// standard deviation. This type of scale-tunable filter is suitable for
// performing scale-space analysis.
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<commit_msg>STYLE: Add comments after the recursive filters were extended to work on multi-component images<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: SmoothingRecursiveGaussianImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {SmoothingRecursiveGaussianImageFilterOutput3.png}
// 3
// Software Guide : EndCommandLineArgs
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {SmoothingRecursiveGaussianImageFilterOutput5.png}
// 5
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The classical method of smoothing an image by convolution with a Gaussian
// kernel has the drawback that it is slow when the standard deviation $\sigma$ of
// the Gaussian is large. This is due to the larger size of the kernel,
// which results in a higher number of computations per pixel.
//
// The \doxygen{RecursiveGaussianImageFilter} implements an approximation of
// convolution with the Gaussian and its derivatives by using
// IIR\footnote{Infinite Impulse Response} filters. In practice this filter
// requires a constant number of operations for approximating the convolution,
// regardless of the $\sigma$ value \cite{Deriche1990,Deriche1993}.
//
// \index{itk::RecursiveGaussianImageFilter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step required to use this filter is to include its header file.
//
// \index{itk::RecursiveGaussianImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkRecursiveGaussianImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile sigma " << std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// Types should be selected on the desired input and output pixel types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef float InputPixelType;
typedef float OutputPixelType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input and output image types are instantiated using the pixel types.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
// Software Guide : BeginLatex
//
// The filter type is now instantiated using both the input image and the
// output image types.
//
// \index{itk::RecursiveGaussianImageFilter!Instantiation}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::RecursiveGaussianImageFilter<
InputImageType, OutputImageType > FilterType;
// Software Guide : EndCodeSnippet
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
// Software Guide : BeginLatex
//
// This filter applies the approximation of the convolution along a single
// dimension. It is therefore necessary to concatenate several of these filters
// to produce smoothing in all directions. In this example, we create a pair
// of filters since we are processing a $2D$ image. The filters are
// created by invoking the \code{New()} method and assigning the result to
// a \doxygen{SmartPointer}.
//
// \index{itk::RecursiveGaussianImageFilter!New()}
// \index{itk::RecursiveGaussianImageFilter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
FilterType::Pointer filterX = FilterType::New();
FilterType::Pointer filterY = FilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since each one of the newly created filters has the potential to perform
// filtering along any dimension, we have to restrict each one to a
// particular direction. This is done with the \code{SetDirection()} method.
//
// \index{RecursiveGaussianImageFilter!SetDirection()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetDirection( 0 ); // 0 --> X direction
filterY->SetDirection( 1 ); // 1 --> Y direction
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \doxygen{RecursiveGaussianImageFilter} can approximate the
// convolution with the Gaussian or with its first and second
// derivatives. We select one of these options by using the
// \code{SetOrder()} method. Note that the argument is an \code{enum} whose
// values can be \code{ZeroOrder}, \code{FirstOrder} and
// \code{SecondOrder}. For example, to compute the $x$ partial derivative we
// should select \code{FirstOrder} for $x$ and \code{ZeroOrder} for
// $y$. Here we want only to smooth in $x$ and $y$, so we select
// \code{ZeroOrder} in both directions.
//
// \index{RecursiveGaussianImageFilter!SetOrder()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetOrder( FilterType::ZeroOrder );
filterY->SetOrder( FilterType::ZeroOrder );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// There are two typical ways of normalizing Gaussians depending on their
// application. For scale-space analysis it is desirable to use a
// normalization that will preserve the maximum value of the input. This
// normalization is represented by the following equation.
//
// \begin{equation}
// \frac{ 1 }{ \sigma \sqrt{ 2 \pi } }
// \end{equation}
//
// In applications that use the Gaussian as a solution of the diffusion
// equation it is desirable to use a normalization that preserve the
// integral of the signal. This last approach can be seen as a conservation
// of mass principle. This is represented by the following equation.
//
// \begin{equation}
// \frac{ 1 }{ \sigma^2 \sqrt{ 2 \pi } }
// \end{equation}
//
// The \doxygen{RecursiveGaussianImageFilter} has a boolean flag that allows
// users to select between these two normalization options. Selection is
// done with the method \code{SetNormalizeAcrossScale()}. Enable this flag
// to analyzing an image across scale-space. In the current example, this
// setting has no impact because we are actually renormalizing the output to
// the dynamic range of the reader, so we simply disable the flag.
//
// \index{RecursiveGaussianImageFilter!SetNormalizeAcrossScale()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetNormalizeAcrossScale( false );
filterY->SetNormalizeAcrossScale( false );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input image can be obtained from the output of another
// filter. Here, an image reader is used as the source. The image is passed to
// the $x$ filter and then to the $y$ filter. The reason for keeping these
// two filters separate is that it is usual in scale-space applications to
// compute not only the smoothing but also combinations of derivatives at
// different orders and smoothing. Some factorization is possible when
// separate filters are used to generate the intermediate results. Here
// this capability is less interesting, though, since we only want to smooth
// the image in all directions.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterX->SetInput( reader->GetOutput() );
filterY->SetInput( filterX->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// It is now time to select the $\sigma$ of the Gaussian used to smooth the
// data. Note that $\sigma$ must be passed to both filters and that sigma
// is considered to be in millimeters. That is, at the moment of applying
// the smoothing process, the filter will take into account the spacing
// values defined in the image.
//
// \index{itk::RecursiveGaussianImageFilter!SetSigma()}
// \index{SetSigma()!itk::RecursiveGaussianImageFilter}
//
// Software Guide : EndLatex
const double sigma = atof( argv[3] );
// Software Guide : BeginCodeSnippet
filterX->SetSigma( sigma );
filterY->SetSigma( sigma );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally the pipeline is executed by invoking the \code{Update()} method.
//
// \index{itk::RecursiveGaussianImageFilter!Update()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filterY->Update();
// Software Guide : EndCodeSnippet
typedef unsigned char WritePixelType;
typedef itk::Image< WritePixelType, 2 > WriteImageType;
typedef itk::RescaleIntensityImageFilter<
OutputImageType, WriteImageType > RescaleFilterType;
RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
typedef itk::ImageFileWriter< WriteImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[2] );
rescaler->SetInput( filterY->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
writer->Update();
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{SmoothingRecursiveGaussianImageFilterOutput3.eps}
// \includegraphics[width=0.44\textwidth]{SmoothingRecursiveGaussianImageFilterOutput5.eps}
// \itkcaption[Output of the RecursiveGaussianImageFilter.]{Effect of the
// RecursiveGaussianImageFilter on a slice from a MRI proton density image
// of the brain.}
// \label{fig:RecursiveGaussianImageFilterInputOutput}
// \end{figure}
//
// Figure~\ref{fig:RecursiveGaussianImageFilterInputOutput} illustrates the
// effect of this filter on a MRI proton density image of the brain using
// $\sigma$ values of $3$ (left) and $5$ (right). The figure shows how the
// attenuation of noise can be regulated by selecting the appropriate
// standard deviation. This type of scale-tunable filter is suitable for
// performing scale-space analysis.
//
// The RecursiveGaussianFilters can also be applied on multi-component images. For instance,
// the above filter could have applied with RGBPixel as the pixel type. Each component is
// then independently filtered. However the RescaleIntensityImageFilter will not work on
// RGBPixels since it does not mathematically make sense to rescale the output
// of multi-component images.
//
// Software Guide : EndLatex
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/expression_string.hpp>
using mapnik::rule;
using mapnik::expr_node;
using mapnik::expression_ptr;
using mapnik::Feature;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::glyph_symbolizer;
using mapnik::symbolizer;
using mapnik::to_expression_string;
struct pickle_symbolizer : public boost::static_visitor<>
{
public:
pickle_symbolizer( boost::python::list syms):
syms_(syms) {}
template <typename T>
void operator () ( T const& sym )
{
syms_.append(sym);
}
private:
boost::python::list syms_;
};
struct extract_symbolizer : public boost::static_visitor<>
{
public:
extract_symbolizer( rule& r):
r_(r) {}
template <typename T>
void operator () ( T const& sym )
{
r_.append(sym);
}
private:
rule& r_;
};
struct rule_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const rule& r)
{
return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale());
}
static boost::python::tuple
getstate(const rule& r)
{
boost::python::list syms;
rule::symbolizers::const_iterator begin = r.get_symbolizers().begin();
rule::symbolizers::const_iterator end = r.get_symbolizers().end();
pickle_symbolizer serializer( syms );
std::for_each( begin, end , boost::apply_visitor( serializer ));
// We serialize filter expressions AST as strings
std::string filter_expr = to_expression_string(*r.get_filter());
return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms);
}
static void
setstate (rule& r, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 4)
{
PyErr_SetObject(PyExc_ValueError,
("expected 4-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
r.set_title(extract<std::string>(state[0]));
}
if (state[1])
{
rule dfl;
std::string filter = extract<std::string>(state[1]);
std::string default_filter = "<TODO>";//dfl.get_filter()->to_string();
if ( filter != default_filter)
{
r.set_filter(mapnik::parse_expression(filter,"utf8"));
}
}
if (state[2])
{
r.set_else(true);
}
boost::python::list syms=extract<boost::python::list>(state[3]);
extract_symbolizer serializer( r );
for (int i=0;i<len(syms);++i)
{
symbolizer symbol = extract<symbolizer>(syms[i]);
boost::apply_visitor( serializer, symbol );
}
}
};
void export_rule()
{
using namespace boost::python;
implicitly_convertible<point_symbolizer,symbolizer>();
implicitly_convertible<line_symbolizer,symbolizer>();
implicitly_convertible<line_pattern_symbolizer,symbolizer>();
implicitly_convertible<polygon_symbolizer,symbolizer>();
implicitly_convertible<building_symbolizer,symbolizer>();
implicitly_convertible<polygon_pattern_symbolizer,symbolizer>();
implicitly_convertible<raster_symbolizer,symbolizer>();
implicitly_convertible<shield_symbolizer,symbolizer>();
implicitly_convertible<text_symbolizer,symbolizer>();
implicitly_convertible<glyph_symbolizer,symbolizer>();
class_<rule::symbolizers>("Symbolizers",init<>("TODO"))
.def(vector_indexing_suite<rule::symbolizers>())
;
class_<rule>("Rule",init<>("default constructor"))
.def(init<std::string const&,
boost::python::optional<std::string const&,double,double> >())
.def_pickle(rule_pickle_suite())
.add_property("name",make_function
(&rule::get_name,
return_value_policy<copy_const_reference>()),
&rule::set_name)
.add_property("title",make_function
(&rule::get_title,return_value_policy<copy_const_reference>()),
&rule::set_title)
.add_property("abstract",make_function
(&rule::get_abstract,return_value_policy<copy_const_reference>()),
&rule::set_abstract)
.add_property("filter",make_function
(&rule::get_filter,return_value_policy<copy_const_reference>()),
&rule::set_filter)
.add_property("min_scale",&rule::get_min_scale,&rule::set_min_scale)
.add_property("max_scale",&rule::get_max_scale,&rule::set_max_scale)
.def("set_else",&rule::set_else)
.def("has_else",&rule::has_else_filter)
.def("active",&rule::active)
.add_property("symbols",make_function
(&rule::get_symbolizers,return_value_policy<reference_existing_object>()))
;
}
<commit_msg>allow markers_symbolizer to be created from python<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/detail/api_placeholder.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/expression_string.hpp>
using mapnik::rule;
using mapnik::expr_node;
using mapnik::expression_ptr;
using mapnik::Feature;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::glyph_symbolizer;
using mapnik::symbolizer;
using mapnik::to_expression_string;
struct pickle_symbolizer : public boost::static_visitor<>
{
public:
pickle_symbolizer( boost::python::list syms):
syms_(syms) {}
template <typename T>
void operator () ( T const& sym )
{
syms_.append(sym);
}
private:
boost::python::list syms_;
};
struct extract_symbolizer : public boost::static_visitor<>
{
public:
extract_symbolizer( rule& r):
r_(r) {}
template <typename T>
void operator () ( T const& sym )
{
r_.append(sym);
}
private:
rule& r_;
};
struct rule_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const rule& r)
{
return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale());
}
static boost::python::tuple
getstate(const rule& r)
{
boost::python::list syms;
rule::symbolizers::const_iterator begin = r.get_symbolizers().begin();
rule::symbolizers::const_iterator end = r.get_symbolizers().end();
pickle_symbolizer serializer( syms );
std::for_each( begin, end , boost::apply_visitor( serializer ));
// We serialize filter expressions AST as strings
std::string filter_expr = to_expression_string(*r.get_filter());
return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms);
}
static void
setstate (rule& r, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 4)
{
PyErr_SetObject(PyExc_ValueError,
("expected 4-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
r.set_title(extract<std::string>(state[0]));
}
if (state[1])
{
rule dfl;
std::string filter = extract<std::string>(state[1]);
std::string default_filter = "<TODO>";//dfl.get_filter()->to_string();
if ( filter != default_filter)
{
r.set_filter(mapnik::parse_expression(filter,"utf8"));
}
}
if (state[2])
{
r.set_else(true);
}
boost::python::list syms=extract<boost::python::list>(state[3]);
extract_symbolizer serializer( r );
for (int i=0;i<len(syms);++i)
{
symbolizer symbol = extract<symbolizer>(syms[i]);
boost::apply_visitor( serializer, symbol );
}
}
};
void export_rule()
{
using namespace boost::python;
implicitly_convertible<point_symbolizer,symbolizer>();
implicitly_convertible<line_symbolizer,symbolizer>();
implicitly_convertible<line_pattern_symbolizer,symbolizer>();
implicitly_convertible<polygon_symbolizer,symbolizer>();
implicitly_convertible<building_symbolizer,symbolizer>();
implicitly_convertible<polygon_pattern_symbolizer,symbolizer>();
implicitly_convertible<raster_symbolizer,symbolizer>();
implicitly_convertible<shield_symbolizer,symbolizer>();
implicitly_convertible<text_symbolizer,symbolizer>();
implicitly_convertible<glyph_symbolizer,symbolizer>();
implicitly_convertible<markers_symbolizer,symbolizer>();
class_<rule::symbolizers>("Symbolizers",init<>("TODO"))
.def(vector_indexing_suite<rule::symbolizers>())
;
class_<rule>("Rule",init<>("default constructor"))
.def(init<std::string const&,
boost::python::optional<std::string const&,double,double> >())
.def_pickle(rule_pickle_suite())
.add_property("name",make_function
(&rule::get_name,
return_value_policy<copy_const_reference>()),
&rule::set_name)
.add_property("title",make_function
(&rule::get_title,return_value_policy<copy_const_reference>()),
&rule::set_title)
.add_property("abstract",make_function
(&rule::get_abstract,return_value_policy<copy_const_reference>()),
&rule::set_abstract)
.add_property("filter",make_function
(&rule::get_filter,return_value_policy<copy_const_reference>()),
&rule::set_filter)
.add_property("min_scale",&rule::get_min_scale,&rule::set_min_scale)
.add_property("max_scale",&rule::get_max_scale,&rule::set_max_scale)
.def("set_else",&rule::set_else)
.def("has_else",&rule::has_else_filter)
.def("active",&rule::active)
.add_property("symbols",make_function
(&rule::get_symbolizers,return_value_policy<reference_existing_object>()))
;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * 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 other 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 "stdafx.h"
#include "ConsoleLayout.h"
#include <cursespp/Screen.h>
#include <core/sdk/IPlugin.h>
#include <core/plugin/PluginFactory.h>
#include <app/util/Hotkeys.h>
#include <app/util/Version.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
template <class T>
bool tostr(T& t, const std::string& s) {
std::istringstream iss(s);
return !(iss >> t).fail();
}
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::sdk;
using namespace musik::box;
using namespace cursespp;
ConsoleLayout::ConsoleLayout(ITransport& transport, LibraryPtr library)
: LayoutBase()
, transport(transport)
, library(library) {
this->SetFrameVisible(false);
this->logs.reset(new LogWindow(this));
this->output.reset(new OutputWindow(this));
this->commands.reset(new cursespp::TextInput());
this->commands->SetFocusOrder(0);
this->output->SetFocusOrder(1);
this->logs->SetFocusOrder(2);
this->AddWindow(this->commands);
this->AddWindow(this->logs);
this->AddWindow(this->output);
this->commands->EnterPressed.connect(this, &ConsoleLayout::OnEnterPressed);
this->Help();
}
ConsoleLayout::~ConsoleLayout() {
}
void ConsoleLayout::OnLayout() {
const int cx = this->GetWidth();
const int cy = this->GetHeight();
const int x = this->GetX();
const int y = this->GetY();
const int leftCx = cx / 2;
const int rightCx = cx - leftCx;
/* top left */
this->output->MoveAndResize(x, y, leftCx, cy - 3);
/* bottom left */
this->commands->MoveAndResize(x, cy - 3, leftCx, 3);
/* right */
this->logs->MoveAndResize(cx / 2, 0, rightCx, cy);
}
void ConsoleLayout::SetShortcutsWindow(ShortcutsWindow* shortcuts) {
if (shortcuts) {
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateConsole), "console");
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateLibrary), "library");
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateSettings), "settings");
shortcuts->AddShortcut("^D", "quit");
shortcuts->SetActive(Hotkeys::Get(Hotkeys::NavigateConsole));
}
}
void ConsoleLayout::OnEnterPressed(TextInput *input) {
std::string command = this->commands->GetText();
this->commands->SetText("");
output->WriteLine("> " + command + "\n", COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
if (!this->ProcessCommand(command)) {
if (command.size()) {
output->WriteLine(
"illegal command: '" +
command +
"'\n", COLOR_PAIR(CURSESPP_TEXT_ERROR));
}
}
}
void ConsoleLayout::Seek(const std::vector<std::string>& args) {
if (args.size() > 0) {
double newPosition = 0;
if (tostr<double>(newPosition, args[0])) {
transport.SetPosition(newPosition);
}
}
}
void ConsoleLayout::SetVolume(const std::vector<std::string>& args) {
if (args.size() > 0) {
float newVolume = 0;
if (tostr<float>(newVolume, args[0])) {
this->SetVolume(newVolume / 100.0f);
}
}
}
void ConsoleLayout::SetVolume(float volume) {
transport.SetVolume(volume);
}
void ConsoleLayout::Help() {
int64 s = -1;
this->output->WriteLine("help:\n", s);
this->output->WriteLine(" <tab> to switch between windows", s);
this->output->WriteLine("", s);
this->output->WriteLine(" addir <dir>: add a music directory", s);
this->output->WriteLine(" rmdir <dir>: remove a music directory", s);
this->output->WriteLine(" lsdirs: list scanned directories", s);
this->output->WriteLine(" rescan: rescan paths for new metadata", s);
this->output->WriteLine("", s);
this->output->WriteLine(" play <uri>: play audio at <uri>", s);
this->output->WriteLine(" pause: pause/resume", s);
this->output->WriteLine(" stop: stop and clean up everything", s);
this->output->WriteLine(" volume: <0 - 100>: set % volume", s);
this->output->WriteLine(" clear: clear the log window", s);
this->output->WriteLine(" seek <seconds>: seek to <seconds> into track", s);
this->output->WriteLine("", s);
this->output->WriteLine(" plugins: list loaded plugins", s);
this->output->WriteLine("", s);
this->output->WriteLine(" version: show musikbox app version", s);
this->output->WriteLine("", s);
this->output->WriteLine(" <ctrl+d>: quit\n", s);
}
bool ConsoleLayout::ProcessCommand(const std::string& cmd) {
std::vector<std::string> args;
boost::algorithm::split(args, cmd, boost::is_any_of(" "));
auto it = args.begin();
while (it != args.end()) {
std::string trimmed = boost::algorithm::trim_copy(*it);
if (trimmed.size()) {
*it = trimmed;
++it;
}
else {
it = args.erase(it);
}
}
if (args.size() == 0) {
return true;
}
std::string name = args.size() > 0 ? args[0] : "";
args.erase(args.begin());
if (name == "plugins") {
this->ListPlugins();
}
else if (name == "clear") {
this->logs->ClearContents();
}
else if (name == "version") {
const std::string v = boost::str(boost::format("v%s") % VERSION);
this->output->WriteLine(v, -1);
}
else if (name == "play" || name == "pl" || name == "p") {
return this->PlayFile(args);
}
else if (name == "addir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->AddPath(path);
}
else if (name == "rmdir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->RemovePath(path);
}
else if (name == "lsdirs") {
std::vector<std::string> paths;
library->Indexer()->GetPaths(paths);
this->output->WriteLine("paths:");
for (size_t i = 0; i < paths.size(); i++) {
this->output->WriteLine(" " + paths.at(i));
}
this->output->WriteLine("");
}
else if (name == "rescan" || name == "scan" || name == "index") {
library->Indexer()->Synchronize();
}
else if (name == "h" || name == "help") {
this->Help();
}
else if (name == "pa" || name == "pause") {
this->Pause();
}
else if (name == "s" || name =="stop") {
this->Stop();
}
else if (name == "sk" || name == "seek") {
this->Seek(args);
}
else if (name == "plugins") {
this->ListPlugins();
}
else if (name == "v" || name == "volume") {
this->SetVolume(args);
}
else {
return false;
}
return true;
}
bool ConsoleLayout::PlayFile(const std::vector<std::string>& args) {
if (args.size() > 0) {
std::string filename = boost::algorithm::join(args, " ");
transport.Start(filename);
return true;
}
return false;
}
void ConsoleLayout::Pause() {
int state = this->transport.GetPlaybackState();
if (state == PlaybackPaused) {
this->transport.Resume();
}
else if (state == PlaybackPlaying) {
this->transport.Pause();
}
}
void ConsoleLayout::Stop() {
this->transport.Stop();
}
void ConsoleLayout::ListPlugins() const {
using musik::core::sdk::IPlugin;
using musik::core::PluginFactory;
typedef std::vector<std::shared_ptr<IPlugin> > PluginList;
typedef PluginFactory::NullDeleter<IPlugin> Deleter;
PluginList plugins = PluginFactory::Instance()
.QueryInterface<IPlugin, Deleter>("GetPlugin");
PluginList::iterator it = plugins.begin();
for (; it != plugins.end(); it++) {
std::string format =
" " + std::string((*it)->Name()) + "\n"
" version: " + std::string((*it)->Version()) + "\n"
" by " + std::string((*it)->Author()) + "\n";
this->output->WriteLine(format, COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
}
}
<commit_msg>Added an "sdk" command to the console layout.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * 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 other 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 "stdafx.h"
#include "ConsoleLayout.h"
#include <cursespp/Screen.h>
#include <core/sdk/IPlugin.h>
#include <core/plugin/PluginFactory.h>
#include <app/util/Hotkeys.h>
#include <app/util/Version.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
template <class T>
bool tostr(T& t, const std::string& s) {
std::istringstream iss(s);
return !(iss >> t).fail();
}
using namespace musik::core;
using namespace musik::core::audio;
using namespace musik::core::sdk;
using namespace musik::box;
using namespace cursespp;
ConsoleLayout::ConsoleLayout(ITransport& transport, LibraryPtr library)
: LayoutBase()
, transport(transport)
, library(library) {
this->SetFrameVisible(false);
this->logs.reset(new LogWindow(this));
this->output.reset(new OutputWindow(this));
this->commands.reset(new cursespp::TextInput());
this->commands->SetFocusOrder(0);
this->output->SetFocusOrder(1);
this->logs->SetFocusOrder(2);
this->AddWindow(this->commands);
this->AddWindow(this->logs);
this->AddWindow(this->output);
this->commands->EnterPressed.connect(this, &ConsoleLayout::OnEnterPressed);
this->Help();
}
ConsoleLayout::~ConsoleLayout() {
}
void ConsoleLayout::OnLayout() {
const int cx = this->GetWidth();
const int cy = this->GetHeight();
const int x = this->GetX();
const int y = this->GetY();
const int leftCx = cx / 2;
const int rightCx = cx - leftCx;
/* top left */
this->output->MoveAndResize(x, y, leftCx, cy - 3);
/* bottom left */
this->commands->MoveAndResize(x, cy - 3, leftCx, 3);
/* right */
this->logs->MoveAndResize(cx / 2, 0, rightCx, cy);
}
void ConsoleLayout::SetShortcutsWindow(ShortcutsWindow* shortcuts) {
if (shortcuts) {
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateConsole), "console");
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateLibrary), "library");
shortcuts->AddShortcut(Hotkeys::Get(Hotkeys::NavigateSettings), "settings");
shortcuts->AddShortcut("^D", "quit");
shortcuts->SetActive(Hotkeys::Get(Hotkeys::NavigateConsole));
}
}
void ConsoleLayout::OnEnterPressed(TextInput *input) {
std::string command = this->commands->GetText();
this->commands->SetText("");
output->WriteLine("> " + command + "\n", COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
if (!this->ProcessCommand(command)) {
if (command.size()) {
output->WriteLine(
"illegal command: '" +
command +
"'\n", COLOR_PAIR(CURSESPP_TEXT_ERROR));
}
}
}
void ConsoleLayout::Seek(const std::vector<std::string>& args) {
if (args.size() > 0) {
double newPosition = 0;
if (tostr<double>(newPosition, args[0])) {
transport.SetPosition(newPosition);
}
}
}
void ConsoleLayout::SetVolume(const std::vector<std::string>& args) {
if (args.size() > 0) {
float newVolume = 0;
if (tostr<float>(newVolume, args[0])) {
this->SetVolume(newVolume / 100.0f);
}
}
}
void ConsoleLayout::SetVolume(float volume) {
transport.SetVolume(volume);
}
void ConsoleLayout::Help() {
int64 s = -1;
this->output->WriteLine("help:\n", s);
this->output->WriteLine(" <tab> to switch between windows", s);
this->output->WriteLine("", s);
this->output->WriteLine(" addir <dir>: add a music directory", s);
this->output->WriteLine(" rmdir <dir>: remove a music directory", s);
this->output->WriteLine(" lsdirs: list scanned directories", s);
this->output->WriteLine(" rescan: rescan paths for new metadata", s);
this->output->WriteLine("", s);
this->output->WriteLine(" play <uri>: play audio at <uri>", s);
this->output->WriteLine(" pause: pause/resume", s);
this->output->WriteLine(" stop: stop and clean up everything", s);
this->output->WriteLine(" volume: <0 - 100>: set % volume", s);
this->output->WriteLine(" clear: clear the log window", s);
this->output->WriteLine(" seek <seconds>: seek to <seconds> into track", s);
this->output->WriteLine("", s);
this->output->WriteLine(" plugins: list loaded plugins", s);
this->output->WriteLine("", s);
this->output->WriteLine(" version: show musikbox app version", s);
this->output->WriteLine("", s);
this->output->WriteLine(" <ctrl+d>: quit\n", s);
}
bool ConsoleLayout::ProcessCommand(const std::string& cmd) {
std::vector<std::string> args;
boost::algorithm::split(args, cmd, boost::is_any_of(" "));
auto it = args.begin();
while (it != args.end()) {
std::string trimmed = boost::algorithm::trim_copy(*it);
if (trimmed.size()) {
*it = trimmed;
++it;
}
else {
it = args.erase(it);
}
}
if (args.size() == 0) {
return true;
}
std::string name = args.size() > 0 ? args[0] : "";
args.erase(args.begin());
if (name == "plugins") {
this->ListPlugins();
}
else if (name == "clear") {
this->logs->ClearContents();
}
else if (name == "version") {
const std::string v = boost::str(boost::format("v%s") % VERSION);
this->output->WriteLine(v, -1);
}
else if (name == "play" || name == "pl" || name == "p") {
return this->PlayFile(args);
}
else if (name == "addir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->AddPath(path);
}
else if (name == "rmdir") {
std::string path = boost::algorithm::join(args, " ");
library->Indexer()->RemovePath(path);
}
else if (name == "lsdirs") {
std::vector<std::string> paths;
library->Indexer()->GetPaths(paths);
this->output->WriteLine("paths:");
for (size_t i = 0; i < paths.size(); i++) {
this->output->WriteLine(" " + paths.at(i));
}
this->output->WriteLine("");
}
else if (name == "rescan" || name == "scan" || name == "index") {
library->Indexer()->Synchronize();
}
else if (name == "h" || name == "help") {
this->Help();
}
else if (name == "pa" || name == "pause") {
this->Pause();
}
else if (name == "s" || name =="stop") {
this->Stop();
}
else if (name == "sk" || name == "seek") {
this->Seek(args);
}
else if (name == "plugins") {
this->ListPlugins();
}
else if (name == "sdk") {
this->output->WriteLine(" sdk/api revision: " +
std::to_string(musik::core::sdk::SdkVersion));
}
else if (name == "v" || name == "volume") {
this->SetVolume(args);
}
else {
return false;
}
return true;
}
bool ConsoleLayout::PlayFile(const std::vector<std::string>& args) {
if (args.size() > 0) {
std::string filename = boost::algorithm::join(args, " ");
transport.Start(filename);
return true;
}
return false;
}
void ConsoleLayout::Pause() {
int state = this->transport.GetPlaybackState();
if (state == PlaybackPaused) {
this->transport.Resume();
}
else if (state == PlaybackPlaying) {
this->transport.Pause();
}
}
void ConsoleLayout::Stop() {
this->transport.Stop();
}
void ConsoleLayout::ListPlugins() const {
using musik::core::sdk::IPlugin;
using musik::core::PluginFactory;
typedef std::vector<std::shared_ptr<IPlugin> > PluginList;
typedef PluginFactory::NullDeleter<IPlugin> Deleter;
PluginList plugins = PluginFactory::Instance()
.QueryInterface<IPlugin, Deleter>("GetPlugin");
PluginList::iterator it = plugins.begin();
for (; it != plugins.end(); it++) {
std::string format =
" " + std::string((*it)->Name()) + "\n"
" version: " + std::string((*it)->Version()) + "\n"
" by " + std::string((*it)->Author()) + "\n";
this->output->WriteLine(format, COLOR_PAIR(CURSESPP_TEXT_DEFAULT));
}
}
<|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 "media/audio/mac/audio_low_latency_output_mac.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/mac/mac_logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
// Reorder PCM from AAC layout to Core Audio 5.1 layout.
// TODO(fbarchard): Switch layout when ffmpeg is updated.
template<class Format>
static void SwizzleCoreAudioLayout5_1(Format* b, uint32 filled) {
static const int kNumSurroundChannels = 6;
Format aac[kNumSurroundChannels];
for (uint32 i = 0; i < filled; i += sizeof(aac), b += kNumSurroundChannels) {
memcpy(aac, b, sizeof(aac));
b[0] = aac[1]; // L
b[1] = aac[2]; // R
b[2] = aac[0]; // C
b[3] = aac[5]; // LFE
b[4] = aac[3]; // Ls
b[5] = aac[4]; // Rs
}
}
// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, const AudioParameters& params)
: manager_(manager),
source_(NULL),
output_unit_(0),
output_device_id_(kAudioObjectUnknown),
volume_(1),
hardware_latency_frames_(0) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate;
format_.mFormatID = kAudioFormatLinearPCM;
format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kLinearPCMFormatFlagIsSignedInteger;
format_.mBitsPerChannel = params.bits_per_sample;
format_.mChannelsPerFrame = params.channels;
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
format_.mReserved = 0;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Obtain the current input device selected by the user.
UInt32 size = sizeof(output_device_id_);
AudioObjectPropertyAddress default_output_device_address = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_output_device_address,
0,
0,
&size,
&output_device_id_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Open and initialize the DefaultOutputUnit.
Component comp;
ComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = FindNextComponent(0, &desc);
DCHECK(comp);
result = OpenAComponent(comp, &output_unit_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
result = AudioUnitInitialize(output_unit_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
hardware_latency_frames_ = GetHardwareLatency();
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
AURenderCallbackStruct input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&input,
sizeof(input));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Set the stream format.
result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&format_,
sizeof(format_));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Set the buffer frame size.
UInt32 buffer_size = number_of_frames_;
result = AudioUnitSetProperty(
output_unit_,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output,
0,
&buffer_size,
sizeof(buffer_size));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
CloseComponent(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
DLOG_IF(ERROR, !output_unit_) << "Open() has not been called successfully";
if (!output_unit_)
return;
source_ = callback;
AudioOutputUnitStart(output_unit_);
}
void AUAudioOutputStream::Stop() {
// We request a synchronous stop, so the next call can take some time. In
// the windows implementation we block here as well.
source_ = NULL;
AudioOutputUnitStop(output_unit_);
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data,
const AudioTimeStamp* output_time_stamp) {
// Update the playout latency.
double playout_latency_frames = GetPlayoutLatency(output_time_stamp);
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 hardware_pending_bytes = static_cast<uint32>
((playout_latency_frames + 0.5) * format_.mBytesPerFrame);
uint32 filled = source_->OnMoreData(
this, audio_data, buffer.mDataByteSize,
AudioBuffersState(0, hardware_pending_bytes));
// Handle channel order for 5.1 audio.
if (format_.mChannelsPerFrame == 6) {
if (format_.mBitsPerChannel == 8) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 16) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 32) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
}
}
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
AudioUnitRenderActionFlags*,
const AudioTimeStamp* output_time_stamp,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
DCHECK(audio_output);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data, output_time_stamp);
}
double AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioObjectUnknown;
UInt32 info_size = sizeof(device_id);
AudioObjectPropertyAddress default_output_device_address = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_output_device_address,
0,
0,
&info_size,
&device_id);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return 0.0; // error
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
AudioObjectPropertyAddress nominal_sample_rate_address = {
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
result = AudioObjectGetPropertyData(device_id,
&nominal_sample_rate_address,
0,
0,
&info_size,
&nominal_sample_rate);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return 0.0; // error
return nominal_sample_rate;
}
double AUAudioOutputStream::GetHardwareLatency() {
if (!output_unit_ || output_device_id_ == kAudioObjectUnknown) {
DLOG(WARNING) << "Audio unit object is NULL or device ID is unknown";
return 0.0;
}
// Get audio unit latency.
Float64 audio_unit_latency_sec = 0.0;
UInt32 size = sizeof(audio_unit_latency_sec);
OSStatus result = AudioUnitGetProperty(output_unit_,
kAudioUnitProperty_Latency,
kAudioUnitScope_Global,
0,
&audio_unit_latency_sec,
&size);
OSSTATUS_DLOG_IF(WARNING, result != noErr, result)
<< "Could not get audio unit latency";
// Get output audio device latency.
AudioObjectPropertyAddress property_address = {
kAudioDevicePropertyLatency,
kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster
};
UInt32 device_latency_frames = 0;
size = sizeof(device_latency_frames);
result = AudioObjectGetPropertyData(output_device_id_,
&property_address,
0,
NULL,
&size,
&device_latency_frames);
OSSTATUS_DLOG_IF(WARNING, result != noErr, result)
<< "Could not get audio device latency";
// Get the stream latency.
property_address.mSelector = kAudioDevicePropertyStreams;
UInt32 stream_latency_frames = 0;
result = AudioObjectGetPropertyDataSize(output_device_id_,
&property_address,
0,
NULL,
&size);
if (!result) {
scoped_ptr_malloc<AudioStreamID>
streams(reinterpret_cast<AudioStreamID*>(malloc(size)));
AudioStreamID* stream_ids = streams.get();
result = AudioObjectGetPropertyData(output_device_id_,
&property_address,
0,
NULL,
&size,
stream_ids);
if (!result) {
property_address.mSelector = kAudioStreamPropertyLatency;
result = AudioObjectGetPropertyData(stream_ids[0],
&property_address,
0,
NULL,
&size,
&stream_latency_frames);
}
}
OSSTATUS_DLOG_IF(WARNING, result != noErr, result)
<< "Could not get audio stream latency";
return static_cast<double>((audio_unit_latency_sec *
format_.mSampleRate) + device_latency_frames + stream_latency_frames);
}
double AUAudioOutputStream::GetPlayoutLatency(
const AudioTimeStamp* output_time_stamp) {
// Get the delay between the moment getting the callback and the scheduled
// time stamp that tells when the data is going to be played out.
UInt64 output_time_ns = AudioConvertHostTimeToNanos(
output_time_stamp->mHostTime);
UInt64 now_ns = AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
double delay_frames = static_cast<double>
(1e-9 * (output_time_ns - now_ns) * format_.mSampleRate);
return (delay_frames + hardware_latency_frames_);
}
<commit_msg>Fix crash on Mac OS X caused by querying audio stream latency. BUG=109959 TEST=none (covered by existing tests and tested locally with built-in audio, Metric Halo 2882, and Stanton FinalScratch Firewire devices to verify that crashes are fixed)<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 "media/audio/mac/audio_low_latency_output_mac.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/mac/mac_logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
// Reorder PCM from AAC layout to Core Audio 5.1 layout.
// TODO(fbarchard): Switch layout when ffmpeg is updated.
template<class Format>
static void SwizzleCoreAudioLayout5_1(Format* b, uint32 filled) {
static const int kNumSurroundChannels = 6;
Format aac[kNumSurroundChannels];
for (uint32 i = 0; i < filled; i += sizeof(aac), b += kNumSurroundChannels) {
memcpy(aac, b, sizeof(aac));
b[0] = aac[1]; // L
b[1] = aac[2]; // R
b[2] = aac[0]; // C
b[3] = aac[5]; // LFE
b[4] = aac[3]; // Ls
b[5] = aac[4]; // Rs
}
}
// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, const AudioParameters& params)
: manager_(manager),
source_(NULL),
output_unit_(0),
output_device_id_(kAudioObjectUnknown),
volume_(1),
hardware_latency_frames_(0) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate;
format_.mFormatID = kAudioFormatLinearPCM;
format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kLinearPCMFormatFlagIsSignedInteger;
format_.mBitsPerChannel = params.bits_per_sample;
format_.mChannelsPerFrame = params.channels;
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
format_.mReserved = 0;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Obtain the current input device selected by the user.
UInt32 size = sizeof(output_device_id_);
AudioObjectPropertyAddress default_output_device_address = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_output_device_address,
0,
0,
&size,
&output_device_id_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Open and initialize the DefaultOutputUnit.
Component comp;
ComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = FindNextComponent(0, &desc);
DCHECK(comp);
result = OpenAComponent(comp, &output_unit_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
result = AudioUnitInitialize(output_unit_);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
hardware_latency_frames_ = GetHardwareLatency();
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
AURenderCallbackStruct input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&input,
sizeof(input));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Set the stream format.
result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&format_,
sizeof(format_));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
// Set the buffer frame size.
UInt32 buffer_size = number_of_frames_;
result = AudioUnitSetProperty(
output_unit_,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output,
0,
&buffer_size,
sizeof(buffer_size));
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return false;
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
CloseComponent(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
DLOG_IF(ERROR, !output_unit_) << "Open() has not been called successfully";
if (!output_unit_)
return;
source_ = callback;
AudioOutputUnitStart(output_unit_);
}
void AUAudioOutputStream::Stop() {
// We request a synchronous stop, so the next call can take some time. In
// the windows implementation we block here as well.
source_ = NULL;
AudioOutputUnitStop(output_unit_);
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data,
const AudioTimeStamp* output_time_stamp) {
// Update the playout latency.
double playout_latency_frames = GetPlayoutLatency(output_time_stamp);
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 hardware_pending_bytes = static_cast<uint32>
((playout_latency_frames + 0.5) * format_.mBytesPerFrame);
uint32 filled = source_->OnMoreData(
this, audio_data, buffer.mDataByteSize,
AudioBuffersState(0, hardware_pending_bytes));
// Handle channel order for 5.1 audio.
if (format_.mChannelsPerFrame == 6) {
if (format_.mBitsPerChannel == 8) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 16) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
} else if (format_.mBitsPerChannel == 32) {
SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
}
}
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
AudioUnitRenderActionFlags*,
const AudioTimeStamp* output_time_stamp,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
DCHECK(audio_output);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data, output_time_stamp);
}
double AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioObjectUnknown;
UInt32 info_size = sizeof(device_id);
AudioObjectPropertyAddress default_output_device_address = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&default_output_device_address,
0,
0,
&info_size,
&device_id);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return 0.0; // error
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
AudioObjectPropertyAddress nominal_sample_rate_address = {
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
result = AudioObjectGetPropertyData(device_id,
&nominal_sample_rate_address,
0,
0,
&info_size,
&nominal_sample_rate);
OSSTATUS_DCHECK(result == noErr, result);
if (result)
return 0.0; // error
return nominal_sample_rate;
}
double AUAudioOutputStream::GetHardwareLatency() {
if (!output_unit_ || output_device_id_ == kAudioObjectUnknown) {
DLOG(WARNING) << "Audio unit object is NULL or device ID is unknown";
return 0.0;
}
// Get audio unit latency.
Float64 audio_unit_latency_sec = 0.0;
UInt32 size = sizeof(audio_unit_latency_sec);
OSStatus result = AudioUnitGetProperty(output_unit_,
kAudioUnitProperty_Latency,
kAudioUnitScope_Global,
0,
&audio_unit_latency_sec,
&size);
OSSTATUS_DLOG_IF(WARNING, result != noErr, result)
<< "Could not get audio unit latency";
// Get output audio device latency.
AudioObjectPropertyAddress property_address = {
kAudioDevicePropertyLatency,
kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster
};
UInt32 device_latency_frames = 0;
size = sizeof(device_latency_frames);
result = AudioObjectGetPropertyData(output_device_id_,
&property_address,
0,
NULL,
&size,
&device_latency_frames);
OSSTATUS_DLOG_IF(WARNING, result != noErr, result)
<< "Could not get audio device latency";
return static_cast<double>((audio_unit_latency_sec *
format_.mSampleRate) + device_latency_frames);
}
double AUAudioOutputStream::GetPlayoutLatency(
const AudioTimeStamp* output_time_stamp) {
// Get the delay between the moment getting the callback and the scheduled
// time stamp that tells when the data is going to be played out.
UInt64 output_time_ns = AudioConvertHostTimeToNanos(
output_time_stamp->mHostTime);
UInt64 now_ns = AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
double delay_frames = static_cast<double>
(1e-9 * (output_time_ns - now_ns) * format_.mSampleRate);
return (delay_frames + hardware_latency_frames_);
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "stx/wallclock.h"
#include "stx/protobuf/msg.h"
#include "stx/io/BufferedOutputStream.h"
#include "zbase/api/LogfileAPIServlet.h"
using namespace stx;
namespace zbase {
LogfileAPIServlet::LogfileAPIServlet(
LogfileService* service,
ConfigDirectory* cdir,
const String& cachedir) :
service_(service),
cdir_(cdir),
cachedir_(cachedir) {}
void LogfileAPIServlet::handle(
const AnalyticsSession& session,
RefPtr<stx::http::HTTPRequestStream> req_stream,
RefPtr<stx::http::HTTPResponseStream> res_stream) {
const auto& req = req_stream->request();
URI uri(req.uri());
http::HTTPResponse res;
res.populateFromRequest(req);
if (uri.path() == "/analytics/api/v1/logfiles") {
req_stream->readBody();
listLogfiles(session, uri, &req, &res);
res_stream->writeResponse(res);
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/scan") {
scanLogfile(session, uri, req_stream.get(), res_stream.get());
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/scan_partition") {
scanLogfilePartition(session, uri, req_stream.get(), res_stream.get());
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/upload") {
uploadLogfile(session, uri, req_stream.get(), &res);
res_stream->writeResponse(res);
return;
}
res.setStatus(http::kStatusNotFound);
res.addBody("not found");
res_stream->writeResponse(res);
}
void LogfileAPIServlet::listLogfiles(
const AnalyticsSession& session,
const URI& uri,
const http::HTTPRequest* req,
http::HTTPResponse* res) {
auto customer_conf = cdir_->configFor(session.customer());
const auto& logfile_cfg = customer_conf->config.logfile_import_config();
Buffer buf;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf));
json.beginObject();
json.addObjectEntry("logfile_definitions");
json.beginArray();
size_t nlogs = 0;
for (const auto& logfile : logfile_cfg.logfiles()) {
if (++nlogs > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("name");
json.addString(logfile.name());
json.addComma();
json.addObjectEntry("regex");
json.addString(logfile.regex());
json.addComma();
json.addObjectEntry("source_fields");
json.beginArray();
{
size_t nfields = 0;
for (const auto& field : logfile.source_fields()) {
if (++nfields > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("name");
json.addString(field.name());
json.addComma();
json.addObjectEntry("id");
json.addInteger(field.id());
json.addComma();
json.addObjectEntry("type");
json.addString(field.type());
json.addComma();
json.addObjectEntry("format");
json.addString(field.format());
json.endObject();
}
}
json.endArray();
json.addObjectEntry("row_fields");
json.beginArray();
json.endArray();
json.endObject();
}
json.endArray();
json.endObject();
res->setStatus(http::kStatusOK);
res->setHeader("Content-Type", "application/json; charset=utf-8");
res->addBody(buf);
}
void LogfileAPIServlet::scanLogfile(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponseStream* res_stream) {
req_stream->readBody();
const auto& params = uri.queryParams();
String logfile_name;
if (!URI::getParam(params, "logfile", &logfile_name)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?logfile=... parameter");
res_stream->writeResponse(res);
return;
}
LogfileScanParams scan_params;
scan_params.set_end_time(WallClock::unixMicros());
scan_params.set_scan_type(LOGSCAN_ALL);
String time_str;
if (URI::getParam(params, "time", &time_str)) {
scan_params.set_end_time(std::stoull(time_str));
}
size_t limit = 1000;
String limit_str;
if (URI::getParam(params, "limit", &limit_str)) {
limit = std::stoull(limit_str);
}
String raw_str;
if (URI::getParam(params, "raw", &limit_str)) {
scan_params.set_return_raw (true);
}
String columns_str;
if (URI::getParam(params, "columns", &columns_str)) {
if (columns_str == "__all__") {
scan_params.set_all_columns(true);
scan_params.set_return_raw(true);
} else {
for (const auto& c : StringUtil::split(columns_str, ",")) {
*scan_params.add_columns() = c;
}
}
}
String filter_sql_str;
if (URI::getParam(params, "filter_sql", &filter_sql_str)) {
scan_params.set_scan_type(LOGSCAN_SQL);
scan_params.set_condition(filter_sql_str);
}
LogfileScanResult result(limit);
http::HTTPSSEStream sse_stream(req_stream, res_stream);
sse_stream.start();
auto send_status_update = [&sse_stream, &result, &scan_params] (bool done) {
Buffer buf;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf));
json.beginObject();
json.addObjectEntry("status");
json.addString(done ? "finished" : "running");
json.addComma();
json.addObjectEntry("scanned_until");
json.addInteger(result.scannedUntil().unixMicros());
json.addComma();
json.addObjectEntry("rows_scanned");
json.addInteger(result.rowScanned());
json.addComma();
json.addObjectEntry("columns");
json::toJSON(result.columns(), &json);
json.addComma();
json.addObjectEntry("result");
json.beginArray();
size_t nline = 0;
for (const auto& l : result.lines()) {
if (++nline > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("time");
json.addInteger(l.time.unixMicros());
json.addComma();
if (scan_params.return_raw()) {
json.addObjectEntry("raw");
json.addString(l.raw);
json.addComma();
}
json.addObjectEntry("columns");
json::toJSON(l.columns, &json);
json.endObject();
}
json.endArray();
json.endObject();
sse_stream.sendEvent(buf, None<String>());
};
service_->scanLogfile(
session,
logfile_name,
scan_params,
&result,
send_status_update);
sse_stream.finish();
}
void LogfileAPIServlet::scanLogfilePartition(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponseStream* res_stream) {
req_stream->readBody();
const auto& params = uri.queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?table=... parameter");
res_stream->writeResponse(res);
return;
}
String partition;
if (!URI::getParam(params, "partition", &partition)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?partition=... parameter");
res_stream->writeResponse(res);
return;
}
String limit_str;
if (!URI::getParam(params, "limit", &limit_str)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?limit=... parameter");
res_stream->writeResponse(res);
return;
}
auto limit = std::stoull(limit_str);
auto scan_params = msg::decode<LogfileScanParams>(
req_stream->request().body());
LogfileScanResult result(limit);
service_->scanLocalLogfilePartition(
session,
table,
SHA1Hash::fromHexString(partition),
scan_params,
&result);
Buffer res_body;
{
BufferedOutputStream res_os(BufferOutputStream::fromBuffer(&res_body));
result.encode(&res_os);
}
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusOK);
res.addBody(res_body);
res_stream->writeResponse(res);
}
void LogfileAPIServlet::uploadLogfile(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponse* res) {
const auto& params = uri.queryParams();
if (req_stream->request().method() != http::HTTPMessage::M_POST) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody("error: expected HTTP POST request");
return;
}
String logfile_name;
if (!URI::getParam(params, "logfile", &logfile_name)) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody("error: missing ?logfile=... parameter");
return;
}
auto logfile_def = service_->findLogfileDefinition(
session.customer(),
logfile_name);
if (logfile_def.isEmpty()) {
req_stream->discardBody();
res->setStatus(http::kStatusNotFound);
res->addBody("error: logfile not found");
return;
}
Vector<Pair<String, String>> source_fields;
for (const auto& source_field : logfile_def.get().source_fields()) {
String field_val;
if (!URI::getParam(params, source_field.name(), &field_val)) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody(
StringUtil::format(
"error: missing ?$0=... parameter",
source_field.name()));
return;
}
source_fields.emplace_back(source_field.name(), field_val);
}
auto tmpfile_path = FileUtil::joinPaths(
cachedir_,
StringUtil::format("upload_$0.tmp", Random::singleton()->hex128()));
auto tmpfile = File::openFile(
tmpfile_path,
File::O_CREATE | File::O_READ | File::O_WRITE | File::O_AUTODELETE);
size_t body_size = 0;
req_stream->readBody([&tmpfile, &body_size] (const void* data, size_t size) {
tmpfile.write(data, size);
body_size += size;
});
tmpfile.seekTo(0);
auto is = FileInputStream::fromFile(std::move(tmpfile));
service_->insertLoglines(
session.customer(),
logfile_def.get(),
source_fields,
is.get());
res->setStatus(http::kStatusCreated);
}
}
<commit_msg>list logfiles endpoint...<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "stx/wallclock.h"
#include "stx/protobuf/msg.h"
#include "stx/io/BufferedOutputStream.h"
#include "zbase/api/LogfileAPIServlet.h"
using namespace stx;
namespace zbase {
LogfileAPIServlet::LogfileAPIServlet(
LogfileService* service,
ConfigDirectory* cdir,
const String& cachedir) :
service_(service),
cdir_(cdir),
cachedir_(cachedir) {}
void LogfileAPIServlet::handle(
const AnalyticsSession& session,
RefPtr<stx::http::HTTPRequestStream> req_stream,
RefPtr<stx::http::HTTPResponseStream> res_stream) {
const auto& req = req_stream->request();
URI uri(req.uri());
http::HTTPResponse res;
res.populateFromRequest(req);
if (uri.path() == "/analytics/api/v1/logfiles") {
req_stream->readBody();
listLogfiles(session, uri, &req, &res);
res_stream->writeResponse(res);
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/scan") {
scanLogfile(session, uri, req_stream.get(), res_stream.get());
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/scan_partition") {
scanLogfilePartition(session, uri, req_stream.get(), res_stream.get());
return;
}
if (uri.path() == "/analytics/api/v1/logfiles/upload") {
uploadLogfile(session, uri, req_stream.get(), &res);
res_stream->writeResponse(res);
return;
}
res.setStatus(http::kStatusNotFound);
res.addBody("not found");
res_stream->writeResponse(res);
}
void LogfileAPIServlet::listLogfiles(
const AnalyticsSession& session,
const URI& uri,
const http::HTTPRequest* req,
http::HTTPResponse* res) {
auto customer_conf = cdir_->configFor(session.customer());
const auto& logfile_cfg = customer_conf->config.logfile_import_config();
Buffer buf;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf));
json.beginObject();
json.addObjectEntry("logfile_definitions");
json.beginArray();
size_t nlogs = 0;
for (const auto& logfile : logfile_cfg.logfiles()) {
if (++nlogs > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("name");
json.addString(logfile.name());
json.addComma();
json.addObjectEntry("regex");
json.addString(logfile.regex());
json.addComma();
json.addObjectEntry("source_fields");
json.beginArray();
{
size_t nfields = 0;
for (const auto& field : logfile.source_fields()) {
if (++nfields > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("name");
json.addString(field.name());
json.addComma();
json.addObjectEntry("id");
json.addInteger(field.id());
json.addComma();
json.addObjectEntry("type");
json.addString(field.type());
json.addComma();
json.addObjectEntry("format");
json.addString(field.format());
json.endObject();
}
}
json.endArray();
json.addObjectEntry("row_fields");
json.beginArray();
{
size_t nfields = 0;
for (const auto& field : logfile.row_fields()) {
if (++nfields > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("name");
json.addString(field.name());
json.addComma();
json.addObjectEntry("id");
json.addInteger(field.id());
json.addComma();
json.addObjectEntry("type");
json.addString(field.type());
json.addComma();
json.addObjectEntry("format");
json.addString(field.format());
json.endObject();
}
}
json.endArray();
json.endObject();
}
json.endArray();
json.endObject();
res->setStatus(http::kStatusOK);
res->setHeader("Content-Type", "application/json; charset=utf-8");
res->addBody(buf);
}
void LogfileAPIServlet::scanLogfile(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponseStream* res_stream) {
req_stream->readBody();
const auto& params = uri.queryParams();
String logfile_name;
if (!URI::getParam(params, "logfile", &logfile_name)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?logfile=... parameter");
res_stream->writeResponse(res);
return;
}
LogfileScanParams scan_params;
scan_params.set_end_time(WallClock::unixMicros());
scan_params.set_scan_type(LOGSCAN_ALL);
String time_str;
if (URI::getParam(params, "time", &time_str)) {
scan_params.set_end_time(std::stoull(time_str));
}
size_t limit = 1000;
String limit_str;
if (URI::getParam(params, "limit", &limit_str)) {
limit = std::stoull(limit_str);
}
String raw_str;
if (URI::getParam(params, "raw", &limit_str)) {
scan_params.set_return_raw (true);
}
String columns_str;
if (URI::getParam(params, "columns", &columns_str)) {
if (columns_str == "__all__") {
scan_params.set_all_columns(true);
scan_params.set_return_raw(true);
} else {
for (const auto& c : StringUtil::split(columns_str, ",")) {
*scan_params.add_columns() = c;
}
}
}
String filter_sql_str;
if (URI::getParam(params, "filter_sql", &filter_sql_str)) {
scan_params.set_scan_type(LOGSCAN_SQL);
scan_params.set_condition(filter_sql_str);
}
LogfileScanResult result(limit);
http::HTTPSSEStream sse_stream(req_stream, res_stream);
sse_stream.start();
auto send_status_update = [&sse_stream, &result, &scan_params] (bool done) {
Buffer buf;
json::JSONOutputStream json(BufferOutputStream::fromBuffer(&buf));
json.beginObject();
json.addObjectEntry("status");
json.addString(done ? "finished" : "running");
json.addComma();
json.addObjectEntry("scanned_until");
json.addInteger(result.scannedUntil().unixMicros());
json.addComma();
json.addObjectEntry("rows_scanned");
json.addInteger(result.rowScanned());
json.addComma();
json.addObjectEntry("columns");
json::toJSON(result.columns(), &json);
json.addComma();
json.addObjectEntry("result");
json.beginArray();
size_t nline = 0;
for (const auto& l : result.lines()) {
if (++nline > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("time");
json.addInteger(l.time.unixMicros());
json.addComma();
if (scan_params.return_raw()) {
json.addObjectEntry("raw");
json.addString(l.raw);
json.addComma();
}
json.addObjectEntry("columns");
json::toJSON(l.columns, &json);
json.endObject();
}
json.endArray();
json.endObject();
sse_stream.sendEvent(buf, None<String>());
};
service_->scanLogfile(
session,
logfile_name,
scan_params,
&result,
send_status_update);
sse_stream.finish();
}
void LogfileAPIServlet::scanLogfilePartition(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponseStream* res_stream) {
req_stream->readBody();
const auto& params = uri.queryParams();
String table;
if (!URI::getParam(params, "table", &table)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?table=... parameter");
res_stream->writeResponse(res);
return;
}
String partition;
if (!URI::getParam(params, "partition", &partition)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?partition=... parameter");
res_stream->writeResponse(res);
return;
}
String limit_str;
if (!URI::getParam(params, "limit", &limit_str)) {
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusBadRequest);
res.addBody("error: missing ?limit=... parameter");
res_stream->writeResponse(res);
return;
}
auto limit = std::stoull(limit_str);
auto scan_params = msg::decode<LogfileScanParams>(
req_stream->request().body());
LogfileScanResult result(limit);
service_->scanLocalLogfilePartition(
session,
table,
SHA1Hash::fromHexString(partition),
scan_params,
&result);
Buffer res_body;
{
BufferedOutputStream res_os(BufferOutputStream::fromBuffer(&res_body));
result.encode(&res_os);
}
http::HTTPResponse res;
res.populateFromRequest(req_stream->request());
res.setStatus(http::kStatusOK);
res.addBody(res_body);
res_stream->writeResponse(res);
}
void LogfileAPIServlet::uploadLogfile(
const AnalyticsSession& session,
const URI& uri,
http::HTTPRequestStream* req_stream,
http::HTTPResponse* res) {
const auto& params = uri.queryParams();
if (req_stream->request().method() != http::HTTPMessage::M_POST) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody("error: expected HTTP POST request");
return;
}
String logfile_name;
if (!URI::getParam(params, "logfile", &logfile_name)) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody("error: missing ?logfile=... parameter");
return;
}
auto logfile_def = service_->findLogfileDefinition(
session.customer(),
logfile_name);
if (logfile_def.isEmpty()) {
req_stream->discardBody();
res->setStatus(http::kStatusNotFound);
res->addBody("error: logfile not found");
return;
}
Vector<Pair<String, String>> source_fields;
for (const auto& source_field : logfile_def.get().source_fields()) {
String field_val;
if (!URI::getParam(params, source_field.name(), &field_val)) {
req_stream->discardBody();
res->setStatus(http::kStatusBadRequest);
res->addBody(
StringUtil::format(
"error: missing ?$0=... parameter",
source_field.name()));
return;
}
source_fields.emplace_back(source_field.name(), field_val);
}
auto tmpfile_path = FileUtil::joinPaths(
cachedir_,
StringUtil::format("upload_$0.tmp", Random::singleton()->hex128()));
auto tmpfile = File::openFile(
tmpfile_path,
File::O_CREATE | File::O_READ | File::O_WRITE | File::O_AUTODELETE);
size_t body_size = 0;
req_stream->readBody([&tmpfile, &body_size] (const void* data, size_t size) {
tmpfile.write(data, size);
body_size += size;
});
tmpfile.seekTo(0);
auto is = FileInputStream::fromFile(std::move(tmpfile));
service_->insertLoglines(
session.customer(),
logfile_def.get(),
source_fields,
is.get());
res->setStatus(http::kStatusCreated);
}
}
<|endoftext|>
|
<commit_before>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Chris Kilner <ckilner@aldebaran-robotics.com>
*
* Copyright (C) 2010, 2011 Aldebaran Robotics
*/
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/log/consoleloghandler.hpp>
#ifdef _WIN32
# include <windows.h>
# include <io.h>
# define isatty _isatty
#else
# include <unistd.h>
#endif
#define CATSIZEMAX 16
namespace qi {
namespace log {
ConsoleLogHandler::ConsoleLogHandler()
: _color(1)
{
#ifdef WIN32
_winScreenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
const char *verbose = std::getenv("VERBOSE");
const char *context = std::getenv("CONTEXT");
const char *color = std::getenv("CLICOLOR");
if (verbose)
qi::log::setVerbosity((LogLevel)atoi(verbose));
if (context)
qi::log::setContext(atoi(context) > 0 ? true: false);
if (color)
_color = atoi(color) > 0 ? true: false;
if (!isatty(1))
_color = 0;
}
void cutCat(const char* category, char* res)
{
int categorySize = strlen(category);
if (categorySize < CATSIZEMAX)
{
memset(res, ' ', CATSIZEMAX);
memcpy(res, category, strlen(category));
}
else
{
memset(res, '.', CATSIZEMAX);
memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);
}
res[CATSIZEMAX] = '\0';
}
void ConsoleLogHandler::log(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
if (verb > qi::log::getVerbosity())
{
return;
}
else
{
header(verb);
char fixedCategory[CATSIZEMAX + 1];
fixedCategory[CATSIZEMAX] = '\0';
cutCat(category, fixedCategory);
if (qi::log::getContext() != 0)
{
printf("%s: %s(%d) %s %s", fixedCategory, file, line, fct, msg);
fflush (stdout);
}
else
{
printf("%s: ", fixedCategory);
if (qi::log::getContext())
{
printf("%s(%d) %s ", file, line, fct);
}
printf("%s", msg);
fflush (stdout);
}
}
fflush (stdout);
}
void ConsoleLogHandler::textColor(char fg, char bg, char attr) const
{
if (!_color)
return;
#ifdef _WIN32
if (fg == reset)
{
SetConsoleTextAttribute(_winScreenHandle, whitegray);
}
else
{
SetConsoleTextAttribute(_winScreenHandle, fg);
}
return;
#endif
if (attr != -1 && bg != -1)
printf("%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
else if (bg != -1)
printf("%c[%d;%dm", 0x1B, fg + 30, bg + 40);
else
printf("%c[%dm", 0x1B, fg + 30);
}
void ConsoleLogHandler::textColorBG(char bg) const
{
if (!_color)
return;
#ifdef _WIN32
return;
#endif
printf("%c[%dm", 0x1B, bg + 40);
}
void ConsoleLogHandler::textColorAttr(char attr) const
{
if (!_color)
return;
#ifdef _WIN32
if (attr == reset)
{
SetConsoleTextAttribute(_winScreenHandle, whitegray);
}
else
{
SetConsoleTextAttribute(_winScreenHandle, attr);
}
return;
#endif
printf("%c[%dm", 0x1B, attr);
}
void ConsoleLogHandler::header(const LogLevel verb) const
{
//display log level
textColorAttr(bright);
if (verb == fatal)
textColor(magenta);
if (verb == error)
textColor(red);
if (verb == warning)
textColor(yellow);
if (verb == info)
textColor(white);
if (verb == verbose)
textColorAttr(dim);
if (verb == debug)
textColorAttr(dim);
printf("%s ", logLevelToString(verb));
textColorAttr(reset);
textColor(reset);
}
}
}
<commit_msg>libqi: Same color on windows and linux (console log handler)<commit_after>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Chris Kilner <ckilner@aldebaran-robotics.com>
*
* Copyright (C) 2010, 2011 Aldebaran Robotics
*/
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/log/consoleloghandler.hpp>
#ifdef _WIN32
# include <windows.h>
# include <io.h>
# define isatty _isatty
#else
# include <unistd.h>
#endif
#define CATSIZEMAX 16
namespace qi {
namespace log {
ConsoleLogHandler::ConsoleLogHandler()
: _color(1)
{
#ifdef _WIN32
_winScreenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
const char *verbose = std::getenv("VERBOSE");
const char *context = std::getenv("CONTEXT");
const char *color = std::getenv("CLICOLOR");
if (verbose)
qi::log::setVerbosity((LogLevel)atoi(verbose));
if (context)
qi::log::setContext(atoi(context) > 0 ? true: false);
if (color)
_color = atoi(color) > 0 ? true: false;
if (!isatty(1))
_color = 0;
}
void cutCat(const char* category, char* res)
{
int categorySize = strlen(category);
if (categorySize < CATSIZEMAX)
{
memset(res, ' ', CATSIZEMAX);
memcpy(res, category, strlen(category));
}
else
{
memset(res, '.', CATSIZEMAX);
memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);
}
res[CATSIZEMAX] = '\0';
}
void ConsoleLogHandler::log(const LogLevel verb,
const char *file,
const char *fct,
const char *category,
const int line,
const char *msg)
{
if (verb > qi::log::getVerbosity())
{
return;
}
else
{
header(verb);
char fixedCategory[CATSIZEMAX + 1];
fixedCategory[CATSIZEMAX] = '\0';
cutCat(category, fixedCategory);
if (qi::log::getContext() != 0)
{
printf("%s: %s(%d) %s %s", fixedCategory, file, line, fct, msg);
fflush (stdout);
}
else
{
#ifndef WIN32
textColorAttr(reset);
textColor(gray);
#endif
printf("%s: ", fixedCategory);
if (qi::log::getContext())
{
printf("%s(%d) %s ", file, line, fct);
}
printf("%s", msg);
fflush (stdout);
}
}
fflush (stdout);
}
void ConsoleLogHandler::textColor(char fg, char bg, char attr) const
{
if (!_color)
return;
#ifdef _WIN32
if (fg == reset)
{
SetConsoleTextAttribute(_winScreenHandle, whitegray);
}
else
{
SetConsoleTextAttribute(_winScreenHandle, fg);
}
return;
#endif
if (attr != -1 && bg != -1)
printf("%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
else if (bg != -1)
printf("%c[%d;%dm", 0x1B, fg + 30, bg + 40);
else
printf("%c[%dm", 0x1B, fg + 30);
}
void ConsoleLogHandler::textColorBG(char bg) const
{
if (!_color)
return;
#ifdef _WIN32
return;
#endif
printf("%c[%dm", 0x1B, bg + 40);
}
void ConsoleLogHandler::textColorAttr(char attr) const
{
if (!_color)
return;
#ifdef _WIN32
if (attr == reset)
{
SetConsoleTextAttribute(_winScreenHandle, whitegray);
}
else
{
SetConsoleTextAttribute(_winScreenHandle, attr);
}
return;
#endif
printf("%c[%dm", 0x1B, attr);
}
void ConsoleLogHandler::header(const LogLevel verb) const
{
//display log level
textColorAttr(bright);
if (verb == fatal)
textColor(magenta);
if (verb == error)
textColor(red);
if (verb == warning)
textColor(yellow);
if (verb == info)
textColor(white);
if (verb == verbose)
textColorAttr(dim);
if (verb == debug)
textColorAttr(dim);
printf("%s ", logLevelToString(verb));
textColorAttr(reset);
textColor(reset);
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemosshrunner.h"
#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"
#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>
#include <QtCore/QFileInfo>
#include <limits>
#define ASSERT_STATE(state) assertState(state, Q_FUNC_INFO)
using namespace Core;
namespace Qt4ProjectManager {
namespace Internal {
MaemoSshRunner::MaemoSshRunner(QObject *parent,
MaemoRunConfiguration *runConfig, bool debugging)
: QObject(parent), m_runConfig(runConfig),
m_mounter(new MaemoRemoteMounter(this)),
m_devConfig(runConfig->deviceConfig()),
m_debugging(debugging), m_state(Inactive)
{
m_procsToKill
<< QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
<< QLatin1String("utfs-client");
if (debugging)
m_procsToKill << QLatin1String("gdbserver");
connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
connect(m_mounter, SIGNAL(error(QString)), this,
SLOT(handleMounterError(QString)));
connect(m_mounter, SIGNAL(reportProgress(QString)), this,
SIGNAL(reportProgress(QString)));
connect(m_mounter, SIGNAL(debugOutput(QString)), this,
SIGNAL(mountDebugOutput(QString)));
}
MaemoSshRunner::~MaemoSshRunner() {}
void MaemoSshRunner::start()
{
ASSERT_STATE(QList<State>() << Inactive << StopRequested);
setState(Connecting);
m_exitStatus = -1;
if (m_connection)
disconnect(m_connection.data(), 0, this, 0);
m_connection = m_runConfig->deployStep()->sshConnection();
const bool reUse = isConnectionUsable();
if (!reUse)
m_connection = SshConnection::create();
connect(m_connection.data(), SIGNAL(connected()), this,
SLOT(handleConnected()));
connect(m_connection.data(), SIGNAL(error(Core::SshError)), this,
SLOT(handleConnectionFailure()));
if (reUse) {
handleConnected();
} else {
emit reportProgress(tr("Connecting to device..."));
m_connection->connectToHost(m_devConfig.server);
}
}
void MaemoSshRunner::stop()
{
if (m_state == PostRunCleaning || m_state == StopRequested
|| m_state == Inactive)
return;
setState(StopRequested);
cleanup();
}
void MaemoSshRunner::handleConnected()
{
ASSERT_STATE(QList<State>() << Connecting << StopRequested);
if (m_state == StopRequested) {
setState(Inactive);
} else {
setState(PreRunCleaning);
cleanup();
}
}
void MaemoSshRunner::handleConnectionFailure()
{
if (m_state == Inactive)
qWarning("Unexpected state %d in %s.", m_state, Q_FUNC_INFO);
const QString errorTemplate = m_state == Connecting
? tr("Could not connect to host: %1") : tr("Connection failed: %1");
emitError(errorTemplate.arg(m_connection->errorString()));
}
void MaemoSshRunner::cleanup()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< StopRequested);
emit reportProgress(tr("Killing remote process(es)..."));
// pkill behaves differently on Fremantle and Harmattan.
const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";
QString niceKill;
QString brutalKill;
foreach (const QString &proc, m_procsToKill) {
niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
connect(m_cleaner.data(), SIGNAL(closed(int)), this,
SLOT(handleCleanupFinished(int)));
m_cleaner->start();
}
void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< StopRequested << Inactive);
if (m_state == Inactive)
return;
if (m_state == StopRequested || m_state == PostRunCleaning) {
unmount();
return;
}
if (exitStatus != SshRemoteProcess::ExitedNormally) {
emitError(tr("Initial cleanup failed: %1")
.arg(m_cleaner->errorString()));
} else {
m_mounter->setConnection(m_connection);
unmount();
}
}
void MaemoSshRunner::handleUnmounted()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
<< PostRunCleaning << StopRequested);
switch (m_state) {
case PreRunCleaning: {
m_mounter->resetMountSpecifications();
MaemoPortList portList = m_devConfig.freePorts();
if (m_debugging) { // gdbserver and QML inspector need one port each.
MaemoRunConfiguration::DebuggingType debuggingType
= m_runConfig->debuggingType();
if (debuggingType != MaemoRunConfiguration::DebugQmlOnly
&& !m_runConfig->useRemoteGdb())
portList.getNext();
if (debuggingType != MaemoRunConfiguration::DebugCppOnly)
portList.getNext();
}
m_mounter->setToolchain(m_runConfig->toolchain());
m_mounter->setPortList(portList);
const MaemoRemoteMountsModel * const remoteMounts
= m_runConfig->remoteMounts();
for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
return;
}
if (m_debugging && m_runConfig->useRemoteGdb()) {
if (!addMountSpecification(MaemoMountSpecification(
m_runConfig->localDirToMountForRemoteGdb(),
MaemoGlobal::remoteProjectSourcesMountPoint())))
return;
}
setState(PreMountUnmounting);
unmount();
break;
}
case PreMountUnmounting:
mount();
break;
case PostRunCleaning:
case StopRequested:
m_mounter->resetMountSpecifications();
if (m_state == StopRequested) {
emit remoteProcessFinished(InvalidExitCode);
} else if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
emit remoteProcessFinished(m_runner->exitCode());
} else {
emit error(tr("Error running remote process: %1")
.arg(m_runner->errorString()));
}
setState(Inactive);
break;
default: ;
}
}
void MaemoSshRunner::handleMounted()
{
ASSERT_STATE(QList<State>() << Mounting << StopRequested);
if (m_state == Mounting) {
setState(ReadyForExecution);
emit readyForExecution();
}
}
void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< PreMountUnmounting << Mounting << StopRequested << Inactive);
emitError(errorMsg);
}
void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
ASSERT_STATE(ReadyForExecution);
if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
emitError(tr("Cannot run: No remote executable set."));
return;
}
m_runner = m_connection->createRemoteProcess(remoteCall);
connect(m_runner.data(), SIGNAL(started()), this,
SIGNAL(remoteProcessStarted()));
connect(m_runner.data(), SIGNAL(closed(int)), this,
SLOT(handleRemoteProcessFinished(int)));
connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
SIGNAL(remoteOutput(QByteArray)));
connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
SIGNAL(remoteErrorOutput(QByteArray)));
setState(ProcessStarting);
m_runner->start();
}
void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
ASSERT_STATE(QList<State>() << ProcessStarting << StopRequested << Inactive);
m_exitStatus = exitStatus;
if (m_state != StopRequested && m_state != Inactive) {
setState(PostRunCleaning);
cleanup();
}
}
bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
if (!m_mounter->addMountSpecification(mountSpec, false)) {
emitError(tr("The device does not have enough free ports "
"for this run configuration."));
return false;
}
return true;
}
bool MaemoSshRunner::isConnectionUsable() const
{
return m_connection && m_connection->state() == SshConnection::Connected
&& m_connection->connectionParameters() == m_devConfig.server;
}
void MaemoSshRunner::assertState(State expectedState, const char *func)
{
assertState(QList<State>() << expectedState, func);
}
void MaemoSshRunner::assertState(const QList<State> &expectedStates,
const char *func)
{
if (!expectedStates.contains(m_state))
qWarning("Unexpected state %d at %s.", m_state, func);
}
void MaemoSshRunner::setState(State newState)
{
if (newState == Inactive) {
m_mounter->setConnection(SshConnection::Ptr());
if (m_connection) {
disconnect(m_connection.data(), 0, this, 0);
m_connection = SshConnection::Ptr();
}
if (m_cleaner)
disconnect(m_cleaner.data(), 0, this, 0);
}
m_state = newState;
}
void MaemoSshRunner::emitError(const QString &errorMsg)
{
if (m_state != Inactive) {
emit error(errorMsg);
setState(Inactive);
}
}
void MaemoSshRunner::mount()
{
setState(Mounting);
if (m_mounter->hasValidMountSpecifications()) {
emit reportProgress(tr("Mounting host directories..."));
m_mounter->mount();
} else {
handleMounted();
}
}
void MaemoSshRunner::unmount()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
<< PostRunCleaning << StopRequested);
if (m_mounter->hasValidMountSpecifications()) {
QString message;
switch (m_state) {
case PreRunCleaning:
message = tr("Unmounting left-over host directory mounts...");
break;
case PreMountUnmounting:
message = tr("Potentially unmounting left-over host directory mounts...");
case StopRequested: case PostRunCleaning:
message = tr("Unmounting host directories...");
break;
default:
break;
}
emit reportProgress(message);
m_mounter->unmount();
} else {
handleUnmounted();
}
}
const qint64 MaemoSshRunner::InvalidExitCode
= std::numeric_limits<qint64>::min();
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Fix Creator crash on SSH connection loss.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemosshrunner.h"
#include "maemodeploystep.h"
#include "maemodeviceconfigurations.h"
#include "maemoglobal.h"
#include "maemoremotemounter.h"
#include "maemoremotemountsmodel.h"
#include "maemorunconfiguration.h"
#include <coreplugin/ssh/sshconnection.h>
#include <coreplugin/ssh/sshremoteprocess.h>
#include <QtCore/QFileInfo>
#include <limits>
#define ASSERT_STATE(state) assertState(state, Q_FUNC_INFO)
using namespace Core;
namespace Qt4ProjectManager {
namespace Internal {
MaemoSshRunner::MaemoSshRunner(QObject *parent,
MaemoRunConfiguration *runConfig, bool debugging)
: QObject(parent), m_runConfig(runConfig),
m_mounter(new MaemoRemoteMounter(this)),
m_devConfig(runConfig->deviceConfig()),
m_debugging(debugging), m_state(Inactive)
{
m_procsToKill
<< QFileInfo(m_runConfig->localExecutableFilePath()).fileName()
<< QLatin1String("utfs-client");
if (debugging)
m_procsToKill << QLatin1String("gdbserver");
connect(m_mounter, SIGNAL(mounted()), this, SLOT(handleMounted()));
connect(m_mounter, SIGNAL(unmounted()), this, SLOT(handleUnmounted()));
connect(m_mounter, SIGNAL(error(QString)), this,
SLOT(handleMounterError(QString)));
connect(m_mounter, SIGNAL(reportProgress(QString)), this,
SIGNAL(reportProgress(QString)));
connect(m_mounter, SIGNAL(debugOutput(QString)), this,
SIGNAL(mountDebugOutput(QString)));
}
MaemoSshRunner::~MaemoSshRunner() {}
void MaemoSshRunner::start()
{
ASSERT_STATE(QList<State>() << Inactive << StopRequested);
setState(Connecting);
m_exitStatus = -1;
if (m_connection)
disconnect(m_connection.data(), 0, this, 0);
m_connection = m_runConfig->deployStep()->sshConnection();
const bool reUse = isConnectionUsable();
if (!reUse)
m_connection = SshConnection::create();
connect(m_connection.data(), SIGNAL(connected()), this,
SLOT(handleConnected()));
connect(m_connection.data(), SIGNAL(error(Core::SshError)), this,
SLOT(handleConnectionFailure()));
if (reUse) {
handleConnected();
} else {
emit reportProgress(tr("Connecting to device..."));
m_connection->connectToHost(m_devConfig.server);
}
}
void MaemoSshRunner::stop()
{
if (m_state == PostRunCleaning || m_state == StopRequested
|| m_state == Inactive)
return;
setState(StopRequested);
cleanup();
}
void MaemoSshRunner::handleConnected()
{
ASSERT_STATE(QList<State>() << Connecting << StopRequested);
if (m_state == StopRequested) {
setState(Inactive);
} else {
setState(PreRunCleaning);
cleanup();
}
}
void MaemoSshRunner::handleConnectionFailure()
{
if (m_state == Inactive)
qWarning("Unexpected state %d in %s.", m_state, Q_FUNC_INFO);
const QString errorTemplate = m_state == Connecting
? tr("Could not connect to host: %1") : tr("Connection failed: %1");
emitError(errorTemplate.arg(m_connection->errorString()));
}
void MaemoSshRunner::cleanup()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< StopRequested);
emit reportProgress(tr("Killing remote process(es)..."));
// pkill behaves differently on Fremantle and Harmattan.
const char *const killTemplate = "pkill -%2 '^%1$'; pkill -%2 '/%1$';";
QString niceKill;
QString brutalKill;
foreach (const QString &proc, m_procsToKill) {
niceKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGTERM");
brutalKill += QString::fromLocal8Bit(killTemplate).arg(proc).arg("SIGKILL");
}
QString remoteCall = niceKill + QLatin1String("sleep 1; ") + brutalKill;
remoteCall.remove(remoteCall.count() - 1, 1); // Get rid of trailing semicolon.
m_cleaner = m_connection->createRemoteProcess(remoteCall.toUtf8());
connect(m_cleaner.data(), SIGNAL(closed(int)), this,
SLOT(handleCleanupFinished(int)));
m_cleaner->start();
}
void MaemoSshRunner::handleCleanupFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< StopRequested << Inactive);
if (m_state == Inactive)
return;
if (m_state == StopRequested || m_state == PostRunCleaning) {
unmount();
return;
}
if (exitStatus != SshRemoteProcess::ExitedNormally) {
emitError(tr("Initial cleanup failed: %1")
.arg(m_cleaner->errorString()));
} else {
m_mounter->setConnection(m_connection);
unmount();
}
}
void MaemoSshRunner::handleUnmounted()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
<< PostRunCleaning << StopRequested);
switch (m_state) {
case PreRunCleaning: {
m_mounter->resetMountSpecifications();
MaemoPortList portList = m_devConfig.freePorts();
if (m_debugging) { // gdbserver and QML inspector need one port each.
MaemoRunConfiguration::DebuggingType debuggingType
= m_runConfig->debuggingType();
if (debuggingType != MaemoRunConfiguration::DebugQmlOnly
&& !m_runConfig->useRemoteGdb())
portList.getNext();
if (debuggingType != MaemoRunConfiguration::DebugCppOnly)
portList.getNext();
}
m_mounter->setToolchain(m_runConfig->toolchain());
m_mounter->setPortList(portList);
const MaemoRemoteMountsModel * const remoteMounts
= m_runConfig->remoteMounts();
for (int i = 0; i < remoteMounts->mountSpecificationCount(); ++i) {
if (!addMountSpecification(remoteMounts->mountSpecificationAt(i)))
return;
}
if (m_debugging && m_runConfig->useRemoteGdb()) {
if (!addMountSpecification(MaemoMountSpecification(
m_runConfig->localDirToMountForRemoteGdb(),
MaemoGlobal::remoteProjectSourcesMountPoint())))
return;
}
setState(PreMountUnmounting);
unmount();
break;
}
case PreMountUnmounting:
mount();
break;
case PostRunCleaning:
case StopRequested: {
m_mounter->resetMountSpecifications();
const bool stopRequested = m_state == StopRequested;
setState(Inactive);
if (stopRequested) {
emit remoteProcessFinished(InvalidExitCode);
} else if (m_exitStatus == SshRemoteProcess::ExitedNormally) {
emit remoteProcessFinished(m_runner->exitCode());
} else {
emit error(tr("Error running remote process: %1")
.arg(m_runner->errorString()));
}
break;
}
default: ;
}
}
void MaemoSshRunner::handleMounted()
{
ASSERT_STATE(QList<State>() << Mounting << StopRequested);
if (m_state == Mounting) {
setState(ReadyForExecution);
emit readyForExecution();
}
}
void MaemoSshRunner::handleMounterError(const QString &errorMsg)
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PostRunCleaning
<< PreMountUnmounting << Mounting << StopRequested << Inactive);
emitError(errorMsg);
}
void MaemoSshRunner::startExecution(const QByteArray &remoteCall)
{
ASSERT_STATE(ReadyForExecution);
if (m_runConfig->remoteExecutableFilePath().isEmpty()) {
emitError(tr("Cannot run: No remote executable set."));
return;
}
m_runner = m_connection->createRemoteProcess(remoteCall);
connect(m_runner.data(), SIGNAL(started()), this,
SIGNAL(remoteProcessStarted()));
connect(m_runner.data(), SIGNAL(closed(int)), this,
SLOT(handleRemoteProcessFinished(int)));
connect(m_runner.data(), SIGNAL(outputAvailable(QByteArray)), this,
SIGNAL(remoteOutput(QByteArray)));
connect(m_runner.data(), SIGNAL(errorOutputAvailable(QByteArray)), this,
SIGNAL(remoteErrorOutput(QByteArray)));
setState(ProcessStarting);
m_runner->start();
}
void MaemoSshRunner::handleRemoteProcessFinished(int exitStatus)
{
Q_ASSERT(exitStatus == SshRemoteProcess::FailedToStart
|| exitStatus == SshRemoteProcess::KilledBySignal
|| exitStatus == SshRemoteProcess::ExitedNormally);
ASSERT_STATE(QList<State>() << ProcessStarting << StopRequested << Inactive);
m_exitStatus = exitStatus;
if (m_state != StopRequested && m_state != Inactive) {
setState(PostRunCleaning);
cleanup();
}
}
bool MaemoSshRunner::addMountSpecification(const MaemoMountSpecification &mountSpec)
{
if (!m_mounter->addMountSpecification(mountSpec, false)) {
emitError(tr("The device does not have enough free ports "
"for this run configuration."));
return false;
}
return true;
}
bool MaemoSshRunner::isConnectionUsable() const
{
return m_connection && m_connection->state() == SshConnection::Connected
&& m_connection->connectionParameters() == m_devConfig.server;
}
void MaemoSshRunner::assertState(State expectedState, const char *func)
{
assertState(QList<State>() << expectedState, func);
}
void MaemoSshRunner::assertState(const QList<State> &expectedStates,
const char *func)
{
if (!expectedStates.contains(m_state))
qWarning("Unexpected state %d at %s.", m_state, func);
}
void MaemoSshRunner::setState(State newState)
{
if (newState == Inactive) {
m_mounter->setConnection(SshConnection::Ptr());
if (m_connection) {
disconnect(m_connection.data(), 0, this, 0);
m_connection = SshConnection::Ptr();
}
if (m_cleaner)
disconnect(m_cleaner.data(), 0, this, 0);
}
m_state = newState;
}
void MaemoSshRunner::emitError(const QString &errorMsg)
{
if (m_state != Inactive) {
setState(Inactive);
emit error(errorMsg);
}
}
void MaemoSshRunner::mount()
{
setState(Mounting);
if (m_mounter->hasValidMountSpecifications()) {
emit reportProgress(tr("Mounting host directories..."));
m_mounter->mount();
} else {
handleMounted();
}
}
void MaemoSshRunner::unmount()
{
ASSERT_STATE(QList<State>() << PreRunCleaning << PreMountUnmounting
<< PostRunCleaning << StopRequested);
if (m_mounter->hasValidMountSpecifications()) {
QString message;
switch (m_state) {
case PreRunCleaning:
message = tr("Unmounting left-over host directory mounts...");
break;
case PreMountUnmounting:
message = tr("Potentially unmounting left-over host directory mounts...");
case StopRequested: case PostRunCleaning:
message = tr("Unmounting host directories...");
break;
default:
break;
}
emit reportProgress(message);
m_mounter->unmount();
} else {
handleUnmounted();
}
}
const qint64 MaemoSshRunner::InvalidExitCode
= std::numeric_limits<qint64>::min();
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>// Copyright 2022 The Ray Authors.
//
// 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 "ray/gcs/gcs_server/gcs_heartbeat_manager.h"
#include <chrono>
#include "absl/synchronization/mutex.h"
#include "gtest/gtest.h"
using namespace ray;
using namespace ray::gcs;
using namespace std::chrono_literals;
class GcsHeartbeatManagerTest : public ::testing::Test {
public:
GcsHeartbeatManagerTest() {
RayConfig::instance().initialize(
R"(
{
"num_heartbeats_timeout": 3,
"gcs_failover_worker_reconnect_timeout": 5
}
)");
}
void SetUp() override {
heartbeat_manager =
std::make_unique<GcsHeartbeatManager>(io_service, [this](const NodeID &node_id) {
absl::MutexLock lock(&mutex_);
dead_nodes.push_back(node_id);
});
heartbeat_manager->Start();
}
void AddNode(const NodeID &node_id) {
rpc::GcsNodeInfo node_info;
node_info.set_node_id(node_id.Binary());
heartbeat_manager->AddNode(node_info);
}
void TearDown() override { heartbeat_manager->Stop(); }
instrumented_io_context io_service;
std::unique_ptr<GcsHeartbeatManager> heartbeat_manager;
mutable absl::Mutex mutex_;
// This field needs to be protected because it is accessed
// by a different thread created by `heartbeat_manager`.
std::vector<NodeID> dead_nodes GUARDED_BY(mutex_);
;
};
TEST_F(GcsHeartbeatManagerTest, TestBasicTimeout) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
AddNode(node_1);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Microseconds(1800)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
TEST_F(GcsHeartbeatManagerTest, TestBasicReport) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
AddNode(node_1);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(4)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
io_service.post(
[&]() {
rpc::ReportHeartbeatReply reply;
rpc::ReportHeartbeatRequest request;
request.mutable_heartbeat()->set_node_id(node_1.Binary());
heartbeat_manager->HandleReportHeartbeat(
request, &reply, [](auto, auto, auto) {});
},
"HandleReportHeartbeat");
std::this_thread::sleep_for(0.1s);
}
}
TEST_F(GcsHeartbeatManagerTest, TestBasicRestart) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
struct GcsInitDataTest : public GcsInitData {
GcsInitDataTest() : GcsInitData(nullptr) {}
auto &NodeData() { return node_table_data_; }
};
GcsInitDataTest init_data;
rpc::GcsNodeInfo node_info;
node_info.set_state(rpc::GcsNodeInfo::ALIVE);
node_info.set_node_id(node_1.Binary());
init_data.NodeData()[node_1] = node_info;
heartbeat_manager->Initialize(init_data);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(4)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
TEST_F(GcsHeartbeatManagerTest, TestBasicRestart2) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
struct GcsInitDataTest : public GcsInitData {
GcsInitDataTest() : GcsInitData(nullptr) {}
auto &NodeData() { return node_table_data_; }
};
GcsInitDataTest init_data;
rpc::GcsNodeInfo node_info;
node_info.set_state(rpc::GcsNodeInfo::ALIVE);
node_info.set_node_id(node_1.Binary());
init_data.NodeData()[node_1] = node_info;
heartbeat_manager->Initialize(init_data);
while (absl::Now() - start < absl::Seconds(2)) {
io_service.post(
[&]() {
rpc::ReportHeartbeatReply reply;
rpc::ReportHeartbeatRequest request;
request.mutable_heartbeat()->set_node_id(node_1.Binary());
heartbeat_manager->HandleReportHeartbeat(
request, &reply, [](auto, auto, auto) {});
},
"HandleReportHeartbeat");
// Added a sleep to avoid io service overloaded.
std::this_thread::sleep_for(0.1s);
}
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(2)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
<commit_msg>[core] Disable some `gcs_heartbeat_manager_test` in Mac. (#28229)<commit_after>// Copyright 2022 The Ray Authors.
//
// 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 "ray/gcs/gcs_server/gcs_heartbeat_manager.h"
#include <chrono>
#include "absl/synchronization/mutex.h"
#include "gtest/gtest.h"
using namespace ray;
using namespace ray::gcs;
using namespace std::chrono_literals;
class GcsHeartbeatManagerTest : public ::testing::Test {
public:
GcsHeartbeatManagerTest() {
RayConfig::instance().initialize(
R"(
{
"num_heartbeats_timeout": 3,
"gcs_failover_worker_reconnect_timeout": 5
}
)");
}
void SetUp() override {
heartbeat_manager =
std::make_unique<GcsHeartbeatManager>(io_service, [this](const NodeID &node_id) {
absl::MutexLock lock(&mutex_);
dead_nodes.push_back(node_id);
});
heartbeat_manager->Start();
}
void AddNode(const NodeID &node_id) {
rpc::GcsNodeInfo node_info;
node_info.set_node_id(node_id.Binary());
heartbeat_manager->AddNode(node_info);
}
void TearDown() override { heartbeat_manager->Stop(); }
instrumented_io_context io_service;
std::unique_ptr<GcsHeartbeatManager> heartbeat_manager;
mutable absl::Mutex mutex_;
// This field needs to be protected because it is accessed
// by a different thread created by `heartbeat_manager`.
std::vector<NodeID> dead_nodes GUARDED_BY(mutex_);
;
};
#ifndef __APPLE__
TEST_F(GcsHeartbeatManagerTest, TestBasicTimeout) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
AddNode(node_1);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Microseconds(1800)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
#endif
TEST_F(GcsHeartbeatManagerTest, TestBasicReport) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
AddNode(node_1);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(4)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
io_service.post(
[&]() {
rpc::ReportHeartbeatReply reply;
rpc::ReportHeartbeatRequest request;
request.mutable_heartbeat()->set_node_id(node_1.Binary());
heartbeat_manager->HandleReportHeartbeat(
request, &reply, [](auto, auto, auto) {});
},
"HandleReportHeartbeat");
std::this_thread::sleep_for(0.1s);
}
}
TEST_F(GcsHeartbeatManagerTest, TestBasicRestart) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
struct GcsInitDataTest : public GcsInitData {
GcsInitDataTest() : GcsInitData(nullptr) {}
auto &NodeData() { return node_table_data_; }
};
GcsInitDataTest init_data;
rpc::GcsNodeInfo node_info;
node_info.set_state(rpc::GcsNodeInfo::ALIVE);
node_info.set_node_id(node_1.Binary());
init_data.NodeData()[node_1] = node_info;
heartbeat_manager->Initialize(init_data);
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(4)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
TEST_F(GcsHeartbeatManagerTest, TestBasicRestart2) {
auto node_1 = NodeID::FromRandom();
auto start = absl::Now();
struct GcsInitDataTest : public GcsInitData {
GcsInitDataTest() : GcsInitData(nullptr) {}
auto &NodeData() { return node_table_data_; }
};
GcsInitDataTest init_data;
rpc::GcsNodeInfo node_info;
node_info.set_state(rpc::GcsNodeInfo::ALIVE);
node_info.set_node_id(node_1.Binary());
init_data.NodeData()[node_1] = node_info;
heartbeat_manager->Initialize(init_data);
while (absl::Now() - start < absl::Seconds(2)) {
io_service.post(
[&]() {
rpc::ReportHeartbeatReply reply;
rpc::ReportHeartbeatRequest request;
request.mutable_heartbeat()->set_node_id(node_1.Binary());
heartbeat_manager->HandleReportHeartbeat(
request, &reply, [](auto, auto, auto) {});
},
"HandleReportHeartbeat");
// Added a sleep to avoid io service overloaded.
std::this_thread::sleep_for(0.1s);
}
while (true) {
absl::MutexLock lock(&mutex_);
if (absl::Now() - start >= absl::Seconds(2)) {
break;
}
ASSERT_TRUE(dead_nodes.empty());
}
std::this_thread::sleep_for(3s);
{
absl::MutexLock lock(&mutex_);
ASSERT_EQ(std::vector<NodeID>{node_1}, dead_nodes);
}
}
<|endoftext|>
|
<commit_before>#include <tuple>
#include <integer_sequence>
#include <type_traits>
template<typename T, typename Tuple, size_t... I>
T __make_from_tuple(Tuple&& t, std::index_sequence<I...>)
{
return T(std::get<I>(std::forward<Tuple>(t))...);
}
template<typename T, typename Tuple>
T make_from_tuple(Tuple&& t)
{
using indices = std::make_index_sequence<std::tuple_size<typename std::decay<Tuple>::type>::value>;
return __make_from_tuple<T>(std::forward<Tuple>(t), indices{});
}
<commit_msg>Eliminate superfluous file<commit_after><|endoftext|>
|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011-2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "nearest_neighbor_serv.hpp"
#include <string>
#include <vector>
#include "jubatus/util/concurrent/lock.h"
#include "jubatus/util/lang/cast.h"
#include "jubatus/util/text/json.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/jsonconfig.hpp"
#include "jubatus/core/storage/column_table.hpp"
#include "jubatus/core/fv_converter/converter_config.hpp"
#include "jubatus/core/fv_converter/datum.hpp"
#include "jubatus/core/fv_converter/revert.hpp"
#include "jubatus/core/nearest_neighbor/nearest_neighbor_factory.hpp"
#include "../common/logger/logger.hpp"
#include "../framework/mixer/mixer_factory.hpp"
using std::string;
using jubatus::util::lang::lexical_cast;
using jubatus::util::lang::shared_ptr;
using jubatus::core::fv_converter::datum;
using jubatus::server::framework::mixer::create_mixer;
namespace jubatus {
namespace server {
namespace {
struct nearest_neighbor_serv_config {
std::string method;
jubatus::util::data::optional<core::common::jsonconfig::config> parameter;
core::fv_converter::converter_config converter;
template<typename Ar>
void serialize(Ar& ar) {
ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter);
}
};
} // namespace
nearest_neighbor_serv::nearest_neighbor_serv(
const framework::server_argv& a,
const shared_ptr<common::lock_service>& zk)
: server_base(a),
mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) {
}
nearest_neighbor_serv::~nearest_neighbor_serv() {
}
void nearest_neighbor_serv::get_status(status_t& status) const {
status_t my_status;
my_status["clear_row_cnt"] = lexical_cast<string>(clear_row_cnt_);
my_status["update_row_cnt"] = lexical_cast<string>(update_row_cnt_);
my_status["build_cnt"] = lexical_cast<string>(build_cnt_);
my_status["mix_cnt"] = lexical_cast<string>(mix_cnt_);
my_status["data"] = lexical_cast<string>(
nearest_neighbor_->get_table()->dump_json());
status.insert(my_status.begin(), my_status.end());
}
uint64_t nearest_neighbor_serv::user_data_version() const {
return 1; // should be inclemented when model data is modified
}
void nearest_neighbor_serv::set_config(const std::string& config) {
core::common::jsonconfig::config config_root(
lexical_cast<jubatus::util::text::json::json>(config));
nearest_neighbor_serv_config conf =
core::common::jsonconfig::config_cast_check<nearest_neighbor_serv_config>(
config_root);
config_ = config;
core::common::jsonconfig::config param;
if (conf.parameter) {
param = *conf.parameter;
}
DLOG(INFO) << __func__;
shared_ptr<core::fv_converter::datum_to_fv_converter> converter =
core::fv_converter::make_fv_converter(conf.converter, &so_loader_);
shared_ptr<core::storage::column_table> table(new core::storage::column_table);
std::string my_id;
#ifdef HAVE_ZOOKEEPER_H_
my_id = common::build_loc_str(argv().eth, argv().port);
#endif
shared_ptr<jubatus::core::nearest_neighbor::nearest_neighbor_base>
nn(jubatus::core::nearest_neighbor::create_nearest_neighbor(
conf.method, param, table, my_id));
nearest_neighbor_.reset(new core::driver::nearest_neighbor(nn, converter));
mixer_->set_driver(nearest_neighbor_.get());
}
std::string nearest_neighbor_serv::get_config() const {
DLOG(INFO) << __func__;
check_set_config();
return config_;
}
bool nearest_neighbor_serv::clear() {
DLOG(INFO) << __func__;
check_set_config();
clear_row_cnt_ = 0;
update_row_cnt_ = 0;
build_cnt_ = 0;
mix_cnt_ = 0;
nearest_neighbor_->clear();
return true;
}
bool nearest_neighbor_serv::set_row(const std::string& id, const datum& d) {
// DLOG(INFO) << __func__ << " " << id;
check_set_config();
++update_row_cnt_;
nearest_neighbor_->set_row(id, d);
return true;
}
neighbor_result nearest_neighbor_serv::neighbor_row_from_id(
const std::string& id,
size_t size) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->neighbor_row_from_id(id, size);
}
neighbor_result nearest_neighbor_serv::neighbor_row_from_datum(
const datum& d,
size_t size) {
// DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->neighbor_row_from_datum(d, size);
}
neighbor_result nearest_neighbor_serv::similar_row_from_id(
const std::string& id,
size_t ret_num) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->similar_row(id, ret_num);
}
neighbor_result nearest_neighbor_serv::similar_row_from_datum(
const datum& d,
size_t ret_num) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->similar_row(d, ret_num);
}
std::vector<std::string> nearest_neighbor_serv::get_all_rows() const {
check_set_config();
return nearest_neighbor_->get_all_rows();
}
void nearest_neighbor_serv::check_set_config() const {
if (!nearest_neighbor_) {
throw JUBATUS_EXCEPTION(core::common::config_not_set());
}
}
} // namespace server
} // namespace jubatus
<commit_msg>Fix for cpplint.<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011-2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "nearest_neighbor_serv.hpp"
#include <string>
#include <vector>
#include "jubatus/util/concurrent/lock.h"
#include "jubatus/util/lang/cast.h"
#include "jubatus/util/text/json.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/jsonconfig.hpp"
#include "jubatus/core/storage/column_table.hpp"
#include "jubatus/core/fv_converter/converter_config.hpp"
#include "jubatus/core/fv_converter/datum.hpp"
#include "jubatus/core/fv_converter/revert.hpp"
#include "jubatus/core/nearest_neighbor/nearest_neighbor_factory.hpp"
#include "../common/logger/logger.hpp"
#include "../framework/mixer/mixer_factory.hpp"
using std::string;
using jubatus::util::lang::lexical_cast;
using jubatus::util::lang::shared_ptr;
using jubatus::core::fv_converter::datum;
using jubatus::server::framework::mixer::create_mixer;
namespace jubatus {
namespace server {
namespace {
struct nearest_neighbor_serv_config {
std::string method;
jubatus::util::data::optional<core::common::jsonconfig::config> parameter;
core::fv_converter::converter_config converter;
template<typename Ar>
void serialize(Ar& ar) {
ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter);
}
};
} // namespace
nearest_neighbor_serv::nearest_neighbor_serv(
const framework::server_argv& a,
const shared_ptr<common::lock_service>& zk)
: server_base(a),
mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) {
}
nearest_neighbor_serv::~nearest_neighbor_serv() {
}
void nearest_neighbor_serv::get_status(status_t& status) const {
status_t my_status;
my_status["clear_row_cnt"] = lexical_cast<string>(clear_row_cnt_);
my_status["update_row_cnt"] = lexical_cast<string>(update_row_cnt_);
my_status["build_cnt"] = lexical_cast<string>(build_cnt_);
my_status["mix_cnt"] = lexical_cast<string>(mix_cnt_);
my_status["data"] = lexical_cast<string>(
nearest_neighbor_->get_table()->dump_json());
status.insert(my_status.begin(), my_status.end());
}
uint64_t nearest_neighbor_serv::user_data_version() const {
return 1; // should be inclemented when model data is modified
}
void nearest_neighbor_serv::set_config(const std::string& config) {
core::common::jsonconfig::config config_root(
lexical_cast<jubatus::util::text::json::json>(config));
nearest_neighbor_serv_config conf =
core::common::jsonconfig::config_cast_check<nearest_neighbor_serv_config>(
config_root);
config_ = config;
core::common::jsonconfig::config param;
if (conf.parameter) {
param = *conf.parameter;
}
DLOG(INFO) << __func__;
shared_ptr<core::fv_converter::datum_to_fv_converter> converter =
core::fv_converter::make_fv_converter(conf.converter, &so_loader_);
shared_ptr<core::storage::column_table>
table(new core::storage::column_table);
std::string my_id;
#ifdef HAVE_ZOOKEEPER_H_
my_id = common::build_loc_str(argv().eth, argv().port);
#endif
shared_ptr<jubatus::core::nearest_neighbor::nearest_neighbor_base>
nn(jubatus::core::nearest_neighbor::create_nearest_neighbor(
conf.method, param, table, my_id));
nearest_neighbor_.reset(new core::driver::nearest_neighbor(nn, converter));
mixer_->set_driver(nearest_neighbor_.get());
}
std::string nearest_neighbor_serv::get_config() const {
DLOG(INFO) << __func__;
check_set_config();
return config_;
}
bool nearest_neighbor_serv::clear() {
DLOG(INFO) << __func__;
check_set_config();
clear_row_cnt_ = 0;
update_row_cnt_ = 0;
build_cnt_ = 0;
mix_cnt_ = 0;
nearest_neighbor_->clear();
return true;
}
bool nearest_neighbor_serv::set_row(const std::string& id, const datum& d) {
// DLOG(INFO) << __func__ << " " << id;
check_set_config();
++update_row_cnt_;
nearest_neighbor_->set_row(id, d);
return true;
}
neighbor_result nearest_neighbor_serv::neighbor_row_from_id(
const std::string& id,
size_t size) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->neighbor_row_from_id(id, size);
}
neighbor_result nearest_neighbor_serv::neighbor_row_from_datum(
const datum& d,
size_t size) {
// DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->neighbor_row_from_datum(d, size);
}
neighbor_result nearest_neighbor_serv::similar_row_from_id(
const std::string& id,
size_t ret_num) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->similar_row(id, ret_num);
}
neighbor_result nearest_neighbor_serv::similar_row_from_datum(
const datum& d,
size_t ret_num) {
DLOG(INFO) << __func__;
check_set_config();
return nearest_neighbor_->similar_row(d, ret_num);
}
std::vector<std::string> nearest_neighbor_serv::get_all_rows() const {
check_set_config();
return nearest_neighbor_->get_all_rows();
}
void nearest_neighbor_serv::check_set_config() const {
if (!nearest_neighbor_) {
throw JUBATUS_EXCEPTION(core::common::config_not_set());
}
}
} // namespace server
} // namespace jubatus
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2013 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "OsmDatabase.h"
#include "DatabaseQuery.h"
#include "GeoDataLatLonAltBox.h"
#include "MarbleDebug.h"
#include "MarbleMath.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "PositionTracking.h"
#include <QFile>
#include <QDataStream>
#include <QStringList>
#include <QRegExp>
#include <QVariant>
#include <QTime>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
namespace Marble {
namespace {
class PlacemarkSmallerDistance
{
public:
PlacemarkSmallerDistance( const GeoDataCoordinates ¤tPosition ) :
m_currentPosition( currentPosition )
{}
bool operator()( const OsmPlacemark &a, const OsmPlacemark &b ) const
{
return distanceSphere( a.longitude() * DEG2RAD, a.latitude() * DEG2RAD,
m_currentPosition.longitude(), m_currentPosition.latitude() )
< distanceSphere( b.longitude() * DEG2RAD, b.latitude() * DEG2RAD,
m_currentPosition.longitude(), m_currentPosition.latitude() );
}
private:
GeoDataCoordinates m_currentPosition;
};
class PlacemarkHigherScore
{
public:
PlacemarkHigherScore( const DatabaseQuery *currentQuery ) :
m_currentQuery( currentQuery )
{}
bool operator()( const OsmPlacemark &a, const OsmPlacemark &b ) const
{
return a.matchScore( m_currentQuery ) > b.matchScore( m_currentQuery );
}
private:
const DatabaseQuery *const m_currentQuery;
};
}
OsmDatabase::OsmDatabase( const QStringList &databaseFiles ) :
m_databaseFiles( databaseFiles )
{
}
QVector<OsmPlacemark> OsmDatabase::find( const DatabaseQuery &userQuery )
{
if ( m_databaseFiles.isEmpty() ) {
return QVector<OsmPlacemark>();
}
QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE", QString( "marble/local-osm-search-%1" ).arg( reinterpret_cast<size_t>( this ) ) );
QVector<OsmPlacemark> result;
QTime timer;
timer.start();
foreach( const QString &databaseFile, m_databaseFiles ) {
database.setDatabaseName( databaseFile );
if ( !database.open() ) {
qWarning() << "Failed to connect to database" << databaseFile;
}
QString regionRestriction;
if ( !userQuery.region().isEmpty() ) {
QTime regionTimer;
regionTimer.start();
// Nested set model to support region hierarchies, see http://en.wikipedia.org/wiki/Nested_set_model
const QString regionsQueryString = "SELECT lft, rgt FROM regions WHERE name LIKE '%" + userQuery.region() + "%';";
QSqlQuery regionsQuery( regionsQueryString, database );
if ( regionsQuery.lastError().isValid() ) {
qWarning() << regionsQuery.lastError() << "in" << databaseFile << "with query" << regionsQuery.lastQuery();
}
regionRestriction = " AND (";
int regionCount = 0;
while ( regionsQuery.next() ) {
if ( regionCount > 0 ) {
regionRestriction += " OR ";
}
regionRestriction += " (regions.lft >= " + regionsQuery.value( 0 ).toString();
regionRestriction += " AND regions.lft <= " + regionsQuery.value( 1 ).toString() + ')';
regionCount++;
}
regionRestriction += ')';
mDebug() << Q_FUNC_INFO << "region query in" << databaseFile << "with query" << regionsQueryString
<< "took" << regionTimer.elapsed() << "ms for" << regionCount << "results";
if ( regionCount == 0 ) {
continue;
}
}
QString queryString;
queryString = " SELECT regions.name,"
" places.name, places.number,"
" places.category, places.lon, places.lat"
" FROM regions, places";
if ( userQuery.queryType() == DatabaseQuery::CategorySearch ) {
queryString += " WHERE regions.id = places.region";
if( userQuery.category() == OsmPlacemark::UnknownCategory ) {
// search for all pois which are not street nor address
queryString += " AND places.category <> 0 AND places.category <> 6";
} else {
// search for specific category
queryString += " AND places.category = %1";
queryString = queryString.arg( (qint32) userQuery.category() );
}
if ( userQuery.position().isValid() && userQuery.region().isEmpty() ) {
// sort by distance
queryString += " ORDER BY ((places.lat-%1)*(places.lat-%1)+(places.lon-%2)*(places.lon-%2))";
GeoDataCoordinates position = userQuery.position();
queryString = queryString.arg( position.latitude( GeoDataCoordinates::Degree ), 0, 'f', 8 )
.arg( position.longitude( GeoDataCoordinates::Degree ), 0, 'f', 8 );
} else {
queryString += regionRestriction;
}
} else if ( userQuery.queryType() == DatabaseQuery::BroadSearch ) {
queryString += " WHERE regions.id = places.region"
" AND places.name " + wildcardQuery( userQuery.searchTerm() );
} else {
queryString += " WHERE regions.id = places.region"
" AND places.name " + wildcardQuery( userQuery.street() );
if ( !userQuery.houseNumber().isEmpty() ) {
queryString += " AND places.number " + wildcardQuery( userQuery.houseNumber() );
} else {
queryString += " AND places.number IS NULL";
}
queryString += regionRestriction;
}
queryString += " LIMIT 50;";
/** @todo: sort/filter results from several databases */
QSqlQuery query( database );
query.setForwardOnly( true );
QTime queryTimer;
queryTimer.start();
if ( !query.exec( queryString ) ) {
qWarning() << query.lastError() << "in" << databaseFile << "with query" << query.lastQuery();
continue;
}
int resultCount = 0;
while ( query.next() ) {
OsmPlacemark placemark;
if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat ) {
GeoDataCoordinates coordinates( query.value(4).toFloat(), query.value(5).toFloat(), 0.0, GeoDataCoordinates::Degree );
placemark.setAdditionalInformation( formatDistance( coordinates, userQuery.position() ) );
} else {
placemark.setAdditionalInformation( query.value( 0 ).toString() );
}
placemark.setName( query.value(1).toString() );
placemark.setHouseNumber( query.value(2).toString() );
placemark.setCategory( (OsmPlacemark::OsmCategory) query.value(3).toInt() );
placemark.setLongitude( query.value(4).toFloat() );
placemark.setLatitude( query.value(5).toFloat() );
result.push_back( placemark );
resultCount++;
}
mDebug() << Q_FUNC_INFO << "query in" << databaseFile << "with query" << queryString
<< "took" << queryTimer.elapsed() << "ms for" << resultCount << "results";
}
mDebug() << "Offline OSM search query took" << timer.elapsed() << "ms for" << result.count() << "results.";
qSort( result.begin(), result.end() );
makeUnique( result );
if ( userQuery.position().isValid() ) {
const PlacemarkSmallerDistance placemarkSmallerDistance( userQuery.position() );
qSort( result.begin(), result.end(), placemarkSmallerDistance );
} else {
const PlacemarkHigherScore placemarkHigherScore( &userQuery );
qSort( result.begin(), result.end(), placemarkHigherScore );
}
if ( result.size() > 50 ) {
result.remove( 50, result.size()-50 );
}
return result;
}
void OsmDatabase::makeUnique( QVector<OsmPlacemark> &placemarks )
{
for ( int i=1; i<placemarks.size(); ++i ) {
if ( placemarks[i-1] == placemarks[i] ) {
placemarks.remove( i );
--i;
}
}
}
QString OsmDatabase::formatDistance( const GeoDataCoordinates &a, const GeoDataCoordinates &b )
{
qreal distance = EARTH_RADIUS * distanceSphere( a, b);
int precision = 0;
QString distanceUnit = QLatin1String( "m" );
if ( MarbleGlobal::getInstance()->locale()->measurementSystem() == MarbleLocale::MetricSystem ) {
precision = 1;
distanceUnit = "mi";
distance *= METER2KM;
distance *= KM2MI;
} else if (MarbleGlobal::getInstance()->locale()->measurementSystem() ==
MarbleLocale::MetricSystem) {
if ( distance >= 1000 ) {
distance /= 1000;
distanceUnit = "km";
precision = 1;
} else if ( distance >= 200 ) {
distance = 50 * qRound( distance / 50 );
} else if ( distance >= 100 ) {
distance = 25 * qRound( distance / 25 );
} else {
distance = 10 * qRound( distance / 10 );
}
} else if (MarbleGlobal::getInstance()->locale()->measurementSystem() ==
MarbleLocale::NauticalSystem) {
precision = 2;
distanceUnit = "nm";
distance *= METER2KM;
distance *= KM2NM;
}
QString const fuzzyDistance = QString( "%1 %2" ).arg( distance, 0, 'f', precision ).arg( distanceUnit );
int direction = 180 + bearing( a, b ) * RAD2DEG;
QString heading = QObject::tr( "north" );
if ( direction > 337 ) {
heading = QObject::tr( "north" );
} else if ( direction > 292 ) {
heading = QObject::tr( "north-west" );
} else if ( direction > 247 ) {
heading = QObject::tr( "west" );
} else if ( direction > 202 ) {
heading = QObject::tr( "south-west" );
} else if ( direction > 157 ) {
heading = QObject::tr( "south" );
} else if ( direction > 112 ) {
heading = QObject::tr( "south-east" );
} else if ( direction > 67 ) {
heading = QObject::tr( "east" );
} else if ( direction > 22 ) {
heading = QObject::tr( "north-east" );
}
return fuzzyDistance + ' ' + heading;
}
qreal OsmDatabase::bearing( const GeoDataCoordinates &a, const GeoDataCoordinates &b )
{
qreal delta = b.longitude() - a.longitude();
qreal lat1 = a.latitude();
qreal lat2 = b.latitude();
return fmod( atan2( sin ( delta ) * cos ( lat2 ),
cos( lat1 ) * sin( lat2 ) - sin( lat1 ) * cos( lat2 ) * cos ( delta ) ), 2 * M_PI );
}
QString OsmDatabase::wildcardQuery( const QString &term )
{
QString result = term;
if ( term.contains( '*' ) ) {
return " LIKE '" + result.replace( '*', '%' ) + '\'';
} else {
return " = '" + result + '\'';
}
}
}
<commit_msg>cppcheck: Fix wrong check of enum values<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2013 Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//
#include "OsmDatabase.h"
#include "DatabaseQuery.h"
#include "GeoDataLatLonAltBox.h"
#include "MarbleDebug.h"
#include "MarbleMath.h"
#include "MarbleLocale.h"
#include "MarbleModel.h"
#include "PositionTracking.h"
#include <QFile>
#include <QDataStream>
#include <QStringList>
#include <QRegExp>
#include <QVariant>
#include <QTime>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
namespace Marble {
namespace {
class PlacemarkSmallerDistance
{
public:
PlacemarkSmallerDistance( const GeoDataCoordinates ¤tPosition ) :
m_currentPosition( currentPosition )
{}
bool operator()( const OsmPlacemark &a, const OsmPlacemark &b ) const
{
return distanceSphere( a.longitude() * DEG2RAD, a.latitude() * DEG2RAD,
m_currentPosition.longitude(), m_currentPosition.latitude() )
< distanceSphere( b.longitude() * DEG2RAD, b.latitude() * DEG2RAD,
m_currentPosition.longitude(), m_currentPosition.latitude() );
}
private:
GeoDataCoordinates m_currentPosition;
};
class PlacemarkHigherScore
{
public:
PlacemarkHigherScore( const DatabaseQuery *currentQuery ) :
m_currentQuery( currentQuery )
{}
bool operator()( const OsmPlacemark &a, const OsmPlacemark &b ) const
{
return a.matchScore( m_currentQuery ) > b.matchScore( m_currentQuery );
}
private:
const DatabaseQuery *const m_currentQuery;
};
}
OsmDatabase::OsmDatabase( const QStringList &databaseFiles ) :
m_databaseFiles( databaseFiles )
{
}
QVector<OsmPlacemark> OsmDatabase::find( const DatabaseQuery &userQuery )
{
if ( m_databaseFiles.isEmpty() ) {
return QVector<OsmPlacemark>();
}
QSqlDatabase database = QSqlDatabase::addDatabase( "QSQLITE", QString( "marble/local-osm-search-%1" ).arg( reinterpret_cast<size_t>( this ) ) );
QVector<OsmPlacemark> result;
QTime timer;
timer.start();
foreach( const QString &databaseFile, m_databaseFiles ) {
database.setDatabaseName( databaseFile );
if ( !database.open() ) {
qWarning() << "Failed to connect to database" << databaseFile;
}
QString regionRestriction;
if ( !userQuery.region().isEmpty() ) {
QTime regionTimer;
regionTimer.start();
// Nested set model to support region hierarchies, see http://en.wikipedia.org/wiki/Nested_set_model
const QString regionsQueryString = "SELECT lft, rgt FROM regions WHERE name LIKE '%" + userQuery.region() + "%';";
QSqlQuery regionsQuery( regionsQueryString, database );
if ( regionsQuery.lastError().isValid() ) {
qWarning() << regionsQuery.lastError() << "in" << databaseFile << "with query" << regionsQuery.lastQuery();
}
regionRestriction = " AND (";
int regionCount = 0;
while ( regionsQuery.next() ) {
if ( regionCount > 0 ) {
regionRestriction += " OR ";
}
regionRestriction += " (regions.lft >= " + regionsQuery.value( 0 ).toString();
regionRestriction += " AND regions.lft <= " + regionsQuery.value( 1 ).toString() + ')';
regionCount++;
}
regionRestriction += ')';
mDebug() << Q_FUNC_INFO << "region query in" << databaseFile << "with query" << regionsQueryString
<< "took" << regionTimer.elapsed() << "ms for" << regionCount << "results";
if ( regionCount == 0 ) {
continue;
}
}
QString queryString;
queryString = " SELECT regions.name,"
" places.name, places.number,"
" places.category, places.lon, places.lat"
" FROM regions, places";
if ( userQuery.queryType() == DatabaseQuery::CategorySearch ) {
queryString += " WHERE regions.id = places.region";
if( userQuery.category() == OsmPlacemark::UnknownCategory ) {
// search for all pois which are not street nor address
queryString += " AND places.category <> 0 AND places.category <> 6";
} else {
// search for specific category
queryString += " AND places.category = %1";
queryString = queryString.arg( (qint32) userQuery.category() );
}
if ( userQuery.position().isValid() && userQuery.region().isEmpty() ) {
// sort by distance
queryString += " ORDER BY ((places.lat-%1)*(places.lat-%1)+(places.lon-%2)*(places.lon-%2))";
GeoDataCoordinates position = userQuery.position();
queryString = queryString.arg( position.latitude( GeoDataCoordinates::Degree ), 0, 'f', 8 )
.arg( position.longitude( GeoDataCoordinates::Degree ), 0, 'f', 8 );
} else {
queryString += regionRestriction;
}
} else if ( userQuery.queryType() == DatabaseQuery::BroadSearch ) {
queryString += " WHERE regions.id = places.region"
" AND places.name " + wildcardQuery( userQuery.searchTerm() );
} else {
queryString += " WHERE regions.id = places.region"
" AND places.name " + wildcardQuery( userQuery.street() );
if ( !userQuery.houseNumber().isEmpty() ) {
queryString += " AND places.number " + wildcardQuery( userQuery.houseNumber() );
} else {
queryString += " AND places.number IS NULL";
}
queryString += regionRestriction;
}
queryString += " LIMIT 50;";
/** @todo: sort/filter results from several databases */
QSqlQuery query( database );
query.setForwardOnly( true );
QTime queryTimer;
queryTimer.start();
if ( !query.exec( queryString ) ) {
qWarning() << query.lastError() << "in" << databaseFile << "with query" << query.lastQuery();
continue;
}
int resultCount = 0;
while ( query.next() ) {
OsmPlacemark placemark;
if ( userQuery.resultFormat() == DatabaseQuery::DistanceFormat ) {
GeoDataCoordinates coordinates( query.value(4).toFloat(), query.value(5).toFloat(), 0.0, GeoDataCoordinates::Degree );
placemark.setAdditionalInformation( formatDistance( coordinates, userQuery.position() ) );
} else {
placemark.setAdditionalInformation( query.value( 0 ).toString() );
}
placemark.setName( query.value(1).toString() );
placemark.setHouseNumber( query.value(2).toString() );
placemark.setCategory( (OsmPlacemark::OsmCategory) query.value(3).toInt() );
placemark.setLongitude( query.value(4).toFloat() );
placemark.setLatitude( query.value(5).toFloat() );
result.push_back( placemark );
resultCount++;
}
mDebug() << Q_FUNC_INFO << "query in" << databaseFile << "with query" << queryString
<< "took" << queryTimer.elapsed() << "ms for" << resultCount << "results";
}
mDebug() << "Offline OSM search query took" << timer.elapsed() << "ms for" << result.count() << "results.";
qSort( result.begin(), result.end() );
makeUnique( result );
if ( userQuery.position().isValid() ) {
const PlacemarkSmallerDistance placemarkSmallerDistance( userQuery.position() );
qSort( result.begin(), result.end(), placemarkSmallerDistance );
} else {
const PlacemarkHigherScore placemarkHigherScore( &userQuery );
qSort( result.begin(), result.end(), placemarkHigherScore );
}
if ( result.size() > 50 ) {
result.remove( 50, result.size()-50 );
}
return result;
}
void OsmDatabase::makeUnique( QVector<OsmPlacemark> &placemarks )
{
for ( int i=1; i<placemarks.size(); ++i ) {
if ( placemarks[i-1] == placemarks[i] ) {
placemarks.remove( i );
--i;
}
}
}
QString OsmDatabase::formatDistance( const GeoDataCoordinates &a, const GeoDataCoordinates &b )
{
qreal distance = EARTH_RADIUS * distanceSphere( a, b);
int precision = 0;
QString distanceUnit = QLatin1String( "m" );
if ( MarbleGlobal::getInstance()->locale()->measurementSystem() == MarbleLocale::ImperialSystem ) {
precision = 1;
distanceUnit = "mi";
distance *= METER2KM;
distance *= KM2MI;
} else if (MarbleGlobal::getInstance()->locale()->measurementSystem() ==
MarbleLocale::MetricSystem) {
if ( distance >= 1000 ) {
distance /= 1000;
distanceUnit = "km";
precision = 1;
} else if ( distance >= 200 ) {
distance = 50 * qRound( distance / 50 );
} else if ( distance >= 100 ) {
distance = 25 * qRound( distance / 25 );
} else {
distance = 10 * qRound( distance / 10 );
}
} else if (MarbleGlobal::getInstance()->locale()->measurementSystem() ==
MarbleLocale::NauticalSystem) {
precision = 2;
distanceUnit = "nm";
distance *= METER2KM;
distance *= KM2NM;
}
QString const fuzzyDistance = QString( "%1 %2" ).arg( distance, 0, 'f', precision ).arg( distanceUnit );
int direction = 180 + bearing( a, b ) * RAD2DEG;
QString heading = QObject::tr( "north" );
if ( direction > 337 ) {
heading = QObject::tr( "north" );
} else if ( direction > 292 ) {
heading = QObject::tr( "north-west" );
} else if ( direction > 247 ) {
heading = QObject::tr( "west" );
} else if ( direction > 202 ) {
heading = QObject::tr( "south-west" );
} else if ( direction > 157 ) {
heading = QObject::tr( "south" );
} else if ( direction > 112 ) {
heading = QObject::tr( "south-east" );
} else if ( direction > 67 ) {
heading = QObject::tr( "east" );
} else if ( direction > 22 ) {
heading = QObject::tr( "north-east" );
}
return fuzzyDistance + ' ' + heading;
}
qreal OsmDatabase::bearing( const GeoDataCoordinates &a, const GeoDataCoordinates &b )
{
qreal delta = b.longitude() - a.longitude();
qreal lat1 = a.latitude();
qreal lat2 = b.latitude();
return fmod( atan2( sin ( delta ) * cos ( lat2 ),
cos( lat1 ) * sin( lat2 ) - sin( lat1 ) * cos( lat2 ) * cos ( delta ) ), 2 * M_PI );
}
QString OsmDatabase::wildcardQuery( const QString &term )
{
QString result = term;
if ( term.contains( '*' ) ) {
return " LIKE '" + result.replace( '*', '%' ) + '\'';
} else {
return " = '" + result + '\'';
}
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "gitsubmiteditorwidget.h"
#include "commitdata.h"
#include <texteditor/texteditorsettings.h>
#include <texteditor/fontsettings.h>
#include <utils/qtcassert.h>
#include <QRegExpValidator>
#include <QSyntaxHighlighter>
#include <QTextEdit>
#include <QDebug>
#include <QDir>
#include <QRegExp>
namespace Git {
namespace Internal {
// Retrieve the comment char format from the text editor.
static QTextCharFormat commentFormat()
{
const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
return settings.toTextCharFormat(TextEditor::C_COMMENT);
}
// Highlighter for git submit messages. Make the first line bold, indicates
// comments as such (retrieving the format from the text editor) and marks up
// keywords (words in front of a colon as in 'Task: <bla>').
class GitSubmitHighlighter : QSyntaxHighlighter {
public:
explicit GitSubmitHighlighter(QTextEdit *parent);
void highlightBlock(const QString &text);
private:
enum State { Header, Comment, Other };
const QTextCharFormat m_commentFormat;
QRegExp m_keywordPattern;
const QChar m_hashChar;
};
GitSubmitHighlighter::GitSubmitHighlighter(QTextEdit * parent) :
QSyntaxHighlighter(parent),
m_commentFormat(commentFormat()),
m_keywordPattern(QLatin1String("^\\w+:")),
m_hashChar(QLatin1Char('#'))
{
QTC_CHECK(m_keywordPattern.isValid());
}
void GitSubmitHighlighter::highlightBlock(const QString &text)
{
// figure out current state
State state = Other;
const QTextBlock block = currentBlock();
if (block.position() == 0) {
state = Header;
} else {
if (text.startsWith(m_hashChar))
state = Comment;
}
// Apply format.
switch (state) {
case Header: {
QTextCharFormat charFormat = format(0);
charFormat.setFontWeight(QFont::Bold);
setFormat(0, text.size(), charFormat);
}
break;
case Comment:
setFormat(0, text.size(), m_commentFormat);
break;
case Other:
// Format key words ("Task:") italic
if (m_keywordPattern.indexIn(text, 0, QRegExp::CaretAtZero) == 0) {
QTextCharFormat charFormat = format(0);
charFormat.setFontItalic(true);
setFormat(0, m_keywordPattern.matchedLength(), charFormat);
}
break;
}
}
// ------------------
GitSubmitEditorWidget::GitSubmitEditorWidget(QWidget *parent) :
VcsBase::SubmitEditorWidget(parent),
m_gitSubmitPanel(new QWidget),
m_hasUnmerged(false)
{
m_gitSubmitPanelUi.setupUi(m_gitSubmitPanel);
insertTopWidget(m_gitSubmitPanel);
new GitSubmitHighlighter(descriptionEdit());
m_emailValidator = new QRegExpValidator(QRegExp(QLatin1String("[^@ ]+@[^@ ]+\\.[a-zA-Z]+")), this);
connect(m_gitSubmitPanelUi.authorLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(authorInformationChanged()));
connect(m_gitSubmitPanelUi.emailLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(authorInformationChanged()));
}
void GitSubmitEditorWidget::setPanelInfo(const GitSubmitEditorPanelInfo &info)
{
m_gitSubmitPanelUi.repositoryLabel->setText(QDir::toNativeSeparators(info.repository));
if (info.branch.contains(QLatin1String("(no branch)")))
m_gitSubmitPanelUi.branchLabel->setText(QString::fromLatin1("<span style=\"color:red\">%1</span>")
.arg(tr("Detached HEAD")));
else
m_gitSubmitPanelUi.branchLabel->setText(info.branch);
}
void GitSubmitEditorWidget::setHasUnmerged(bool e)
{
m_hasUnmerged = e;
}
GitSubmitEditorPanelData GitSubmitEditorWidget::panelData() const
{
GitSubmitEditorPanelData rc;
rc.author = m_gitSubmitPanelUi.authorLineEdit->text();
rc.email = m_gitSubmitPanelUi.emailLineEdit->text();
rc.bypassHooks = m_gitSubmitPanelUi.bypassHooksCheckBox->isChecked();
return rc;
}
void GitSubmitEditorWidget::setPanelData(const GitSubmitEditorPanelData &data)
{
m_gitSubmitPanelUi.authorLineEdit->setText(data.author);
m_gitSubmitPanelUi.emailLineEdit->setText(data.email);
m_gitSubmitPanelUi.bypassHooksCheckBox->setChecked(data.bypassHooks);
authorInformationChanged();
}
bool GitSubmitEditorWidget::canSubmit() const
{
if (m_gitSubmitPanelUi.invalidAuthorLabel->isVisible()
|| m_gitSubmitPanelUi.invalidEmailLabel->isVisible()
|| m_hasUnmerged)
return false;
return SubmitEditorWidget::canSubmit();
}
QString GitSubmitEditorWidget::cleanupDescription(const QString &input) const
{
// We need to manually purge out comment lines starting with
// hash '#' since git does not do that when using -F.
const QChar newLine = QLatin1Char('\n');
const QChar hash = QLatin1Char('#');
QString message = input;
for (int pos = 0; pos < message.size(); ) {
const int newLinePos = message.indexOf(newLine, pos);
const int startOfNextLine = newLinePos == -1 ? message.size() : newLinePos + 1;
if (message.at(pos) == hash)
message.remove(pos, startOfNextLine - pos);
else
pos = startOfNextLine;
}
return message;
}
void GitSubmitEditorWidget::authorInformationChanged()
{
bool bothEmpty = m_gitSubmitPanelUi.authorLineEdit->text().isEmpty() &&
m_gitSubmitPanelUi.emailLineEdit->text().isEmpty();
m_gitSubmitPanelUi.invalidAuthorLabel->
setVisible(m_gitSubmitPanelUi.authorLineEdit->text().isEmpty() && !bothEmpty);
m_gitSubmitPanelUi.invalidEmailLabel->
setVisible(!emailIsValid() && !bothEmpty);
updateSubmitAction();
}
bool GitSubmitEditorWidget::emailIsValid() const
{
int pos = m_gitSubmitPanelUi.emailLineEdit->cursorPosition();
QString text = m_gitSubmitPanelUi.emailLineEdit->text();
return m_emailValidator->validate(text, pos) == QValidator::Acceptable;
}
} // namespace Internal
} // namespace Git
<commit_msg>Git: Fix commit message highlighting<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "gitsubmiteditorwidget.h"
#include "commitdata.h"
#include <texteditor/texteditorsettings.h>
#include <texteditor/fontsettings.h>
#include <utils/qtcassert.h>
#include <QRegExpValidator>
#include <QSyntaxHighlighter>
#include <QTextEdit>
#include <QDebug>
#include <QDir>
#include <QRegExp>
namespace Git {
namespace Internal {
// Retrieve the comment char format from the text editor.
static QTextCharFormat commentFormat()
{
const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
return settings.toTextCharFormat(TextEditor::C_COMMENT);
}
// Highlighter for git submit messages. Make the first line bold, indicates
// comments as such (retrieving the format from the text editor) and marks up
// keywords (words in front of a colon as in 'Task: <bla>').
class GitSubmitHighlighter : QSyntaxHighlighter {
public:
explicit GitSubmitHighlighter(QTextEdit *parent);
void highlightBlock(const QString &text);
private:
enum State { None = -1, Header, Other };
const QTextCharFormat m_commentFormat;
QRegExp m_keywordPattern;
const QChar m_hashChar;
};
GitSubmitHighlighter::GitSubmitHighlighter(QTextEdit * parent) :
QSyntaxHighlighter(parent),
m_commentFormat(commentFormat()),
m_keywordPattern(QLatin1String("^[\\w-]+:")),
m_hashChar(QLatin1Char('#'))
{
QTC_CHECK(m_keywordPattern.isValid());
}
void GitSubmitHighlighter::highlightBlock(const QString &text)
{
// figure out current state
State state = static_cast<State>(previousBlockState());
if (text.isEmpty()) {
if (state == Header)
state = Other;
setCurrentBlockState(state);
return;
} else if (text.startsWith(m_hashChar)) {
setFormat(0, text.size(), m_commentFormat);
return;
} else if (state == None) {
state = Header;
}
setCurrentBlockState(state);
// Apply format.
switch (state) {
case None:
break;
case Header: {
QTextCharFormat charFormat = format(0);
charFormat.setFontWeight(QFont::Bold);
setFormat(0, text.size(), charFormat);
break;
}
case Other:
// Format key words ("Task:") italic
if (m_keywordPattern.indexIn(text, 0, QRegExp::CaretAtZero) == 0) {
QTextCharFormat charFormat = format(0);
charFormat.setFontItalic(true);
setFormat(0, m_keywordPattern.matchedLength(), charFormat);
}
break;
}
}
// ------------------
GitSubmitEditorWidget::GitSubmitEditorWidget(QWidget *parent) :
VcsBase::SubmitEditorWidget(parent),
m_gitSubmitPanel(new QWidget),
m_hasUnmerged(false)
{
m_gitSubmitPanelUi.setupUi(m_gitSubmitPanel);
insertTopWidget(m_gitSubmitPanel);
new GitSubmitHighlighter(descriptionEdit());
m_emailValidator = new QRegExpValidator(QRegExp(QLatin1String("[^@ ]+@[^@ ]+\\.[a-zA-Z]+")), this);
connect(m_gitSubmitPanelUi.authorLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(authorInformationChanged()));
connect(m_gitSubmitPanelUi.emailLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(authorInformationChanged()));
}
void GitSubmitEditorWidget::setPanelInfo(const GitSubmitEditorPanelInfo &info)
{
m_gitSubmitPanelUi.repositoryLabel->setText(QDir::toNativeSeparators(info.repository));
if (info.branch.contains(QLatin1String("(no branch)")))
m_gitSubmitPanelUi.branchLabel->setText(QString::fromLatin1("<span style=\"color:red\">%1</span>")
.arg(tr("Detached HEAD")));
else
m_gitSubmitPanelUi.branchLabel->setText(info.branch);
}
void GitSubmitEditorWidget::setHasUnmerged(bool e)
{
m_hasUnmerged = e;
}
GitSubmitEditorPanelData GitSubmitEditorWidget::panelData() const
{
GitSubmitEditorPanelData rc;
rc.author = m_gitSubmitPanelUi.authorLineEdit->text();
rc.email = m_gitSubmitPanelUi.emailLineEdit->text();
rc.bypassHooks = m_gitSubmitPanelUi.bypassHooksCheckBox->isChecked();
return rc;
}
void GitSubmitEditorWidget::setPanelData(const GitSubmitEditorPanelData &data)
{
m_gitSubmitPanelUi.authorLineEdit->setText(data.author);
m_gitSubmitPanelUi.emailLineEdit->setText(data.email);
m_gitSubmitPanelUi.bypassHooksCheckBox->setChecked(data.bypassHooks);
authorInformationChanged();
}
bool GitSubmitEditorWidget::canSubmit() const
{
if (m_gitSubmitPanelUi.invalidAuthorLabel->isVisible()
|| m_gitSubmitPanelUi.invalidEmailLabel->isVisible()
|| m_hasUnmerged)
return false;
return SubmitEditorWidget::canSubmit();
}
QString GitSubmitEditorWidget::cleanupDescription(const QString &input) const
{
// We need to manually purge out comment lines starting with
// hash '#' since git does not do that when using -F.
const QChar newLine = QLatin1Char('\n');
const QChar hash = QLatin1Char('#');
QString message = input;
for (int pos = 0; pos < message.size(); ) {
const int newLinePos = message.indexOf(newLine, pos);
const int startOfNextLine = newLinePos == -1 ? message.size() : newLinePos + 1;
if (message.at(pos) == hash)
message.remove(pos, startOfNextLine - pos);
else
pos = startOfNextLine;
}
return message;
}
void GitSubmitEditorWidget::authorInformationChanged()
{
bool bothEmpty = m_gitSubmitPanelUi.authorLineEdit->text().isEmpty() &&
m_gitSubmitPanelUi.emailLineEdit->text().isEmpty();
m_gitSubmitPanelUi.invalidAuthorLabel->
setVisible(m_gitSubmitPanelUi.authorLineEdit->text().isEmpty() && !bothEmpty);
m_gitSubmitPanelUi.invalidEmailLabel->
setVisible(!emailIsValid() && !bothEmpty);
updateSubmitAction();
}
bool GitSubmitEditorWidget::emailIsValid() const
{
int pos = m_gitSubmitPanelUi.emailLineEdit->cursorPosition();
QString text = m_gitSubmitPanelUi.emailLineEdit->text();
return m_emailValidator->validate(text, pos) == QValidator::Acceptable;
}
} // namespace Internal
} // namespace Git
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for sparse matrix setup (assembly of system matrix).
// This provides a measure of the effect and performance of using the "sparsity
// learner".
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono/utils/ChBenchmark.h"
#include "chrono/core/ChCSMatrix.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/fea/ChElementShellANCF.h"
#include "chrono/fea/ChMesh.h"
#ifdef CHRONO_MKL
#include "chrono_mkl/ChSolverMKL.h"
#endif
#ifdef CHRONO_MUMPS
#include "chrono_mumps/ChSolverMumps.h"
#endif
using namespace chrono;
using namespace chrono::fea;
template <int N>
class SystemFixture : public ::benchmark::Fixture {
public:
void SetUp(const ::benchmark::State& st) override {
m_system = new ChSystemSMC();
m_system->Set_G_acc(ChVector<>(0, -9.8, 0));
// Mesh properties
double length = 1;
double width = 0.1;
double thickness = 0.01;
double rho = 500;
ChVector<> E(2.1e7, 2.1e7, 2.1e7);
ChVector<> nu(0.3, 0.3, 0.3);
ChVector<> G(8.0769231e6, 8.0769231e6, 8.0769231e6);
auto mat = chrono_types::make_shared<ChMaterialShellANCF>(rho, E, nu, G);
// Create mesh nodes and elements
auto mesh = chrono_types::make_shared<ChMesh>();
m_system->Add(mesh);
int n_nodes = 2 * (1 + N);
double dx = length / N;
ChVector<> dir(0, 1, 0);
auto nodeA = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, -width / 2), dir);
auto nodeB = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, +width / 2), dir);
nodeA->SetFixed(true);
nodeB->SetFixed(true);
mesh->AddNode(nodeA);
mesh->AddNode(nodeB);
for (int i = 1; i <= N; i++) {
auto nodeC = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, -width / 2), dir);
auto nodeD = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, +width / 2), dir);
mesh->AddNode(nodeC);
mesh->AddNode(nodeD);
auto element = chrono_types::make_shared<ChElementShellANCF>();
element->SetNodes(nodeA, nodeB, nodeD, nodeC);
element->SetDimensions(dx, width);
element->AddLayer(thickness, 0 * CH_C_DEG_TO_RAD, mat);
element->SetAlphaDamp(0.0);
element->SetGravityOn(false);
mesh->AddElement(element);
nodeA = nodeC;
nodeB = nodeD;
}
}
void TearDown(const ::benchmark::State&) override { delete m_system; }
void Report(benchmark::State& st) {
auto descr = m_system->GetSystemDescriptor();
auto num_it = st.iterations();
st.counters["SIZE"] = descr->CountActiveVariables() + descr->CountActiveConstraints();
st.counters["LS_Jacobian"] = m_system->GetTimerJacobian() * 1e3 / num_it;
st.counters["LS_Setup"] = m_system->GetTimerSetup() * 1e3 / num_it;
st.counters["LS_Solve"] = m_system->GetTimerSolver() * 1e3 / num_it;
}
protected:
ChSystemSMC* m_system;
};
#define BM_SOLVER_MKL(TEST_NAME, N, WITH_LEARNER) \
BENCHMARK_TEMPLATE_DEFINE_F(SystemFixture, TEST_NAME, N)(benchmark::State & st) { \
auto solver = chrono_types::make_shared<ChSolverMKL<>>(); \
solver->SetSparsityPatternLock(true); \
solver->SetVerbose(false); \
m_system->SetSolver(solver); \
while (st.KeepRunning()) { \
solver->ForceSparsityPatternUpdate(WITH_LEARNER); \
m_system->DoStaticLinear(); \
} \
Report(st); \
} \
BENCHMARK_REGISTER_F(SystemFixture, TEST_NAME)->Unit(benchmark::kMillisecond);
#define BM_SOLVER_MUMPS(TEST_NAME, N, WITH_LEARNER) \
BENCHMARK_TEMPLATE_DEFINE_F(SystemFixture, TEST_NAME, N)(benchmark::State & st) { \
auto solver = chrono_types::make_shared<ChSolverMumps>(); \
solver->SetSparsityPatternLock(true); \
solver->SetVerbose(false); \
m_system->SetSolver(solver); \
while (st.KeepRunning()) { \
solver->ForceSparsityPatternUpdate(WITH_LEARNER); \
m_system->DoStaticLinear(); \
} \
Report(st); \
} \
BENCHMARK_REGISTER_F(SystemFixture, TEST_NAME)->Unit(benchmark::kMillisecond);
BM_SOLVER_MKL(MKL_learner_500, 500, true)
BM_SOLVER_MKL(MKL_no_learner_500, 500, false)
BM_SOLVER_MUMPS(MUMPS_learner_500, 500, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_500, 500, false)
BM_SOLVER_MKL(MKL_learner_1000, 1000, true)
BM_SOLVER_MKL(MKL_no_learner_1000, 1000, false)
BM_SOLVER_MUMPS(MUMPS_learner_1000, 1000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_1000, 1000, false)
BM_SOLVER_MKL(MKL_learner_2000, 2000, true)
BM_SOLVER_MKL(MKL_no_learner_2000, 2000, false)
BM_SOLVER_MUMPS(MUMPS_learner_2000, 2000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_2000, 2000, false)
BM_SOLVER_MKL(MKL_learner_4000, 4000, true)
BM_SOLVER_MKL(MKL_no_learner_4000, 4000, false)
BM_SOLVER_MUMPS(MUMPS_learner_4000, 4000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_4000, 4000, false)
BM_SOLVER_MKL(MKL_learner_8000, 8000, true)
BM_SOLVER_MKL(MKL_no_learner_8000, 8000, false)
BM_SOLVER_MUMPS(MUMPS_learner_8000, 8000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_8000, 8000, false)
<commit_msg>Fix case where only one of Chrono::MKL and Chrono::MUMPS is enabled<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Benchmark test for sparse matrix setup (assembly of system matrix).
// This provides a measure of the effect and performance of using the "sparsity
// learner".
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono/utils/ChBenchmark.h"
#include "chrono/core/ChCSMatrix.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/fea/ChElementShellANCF.h"
#include "chrono/fea/ChMesh.h"
#ifdef CHRONO_MKL
#include "chrono_mkl/ChSolverMKL.h"
#endif
#ifdef CHRONO_MUMPS
#include "chrono_mumps/ChSolverMumps.h"
#endif
using namespace chrono;
using namespace chrono::fea;
template <int N>
class SystemFixture : public ::benchmark::Fixture {
public:
void SetUp(const ::benchmark::State& st) override {
m_system = new ChSystemSMC();
m_system->Set_G_acc(ChVector<>(0, -9.8, 0));
// Mesh properties
double length = 1;
double width = 0.1;
double thickness = 0.01;
double rho = 500;
ChVector<> E(2.1e7, 2.1e7, 2.1e7);
ChVector<> nu(0.3, 0.3, 0.3);
ChVector<> G(8.0769231e6, 8.0769231e6, 8.0769231e6);
auto mat = chrono_types::make_shared<ChMaterialShellANCF>(rho, E, nu, G);
// Create mesh nodes and elements
auto mesh = chrono_types::make_shared<ChMesh>();
m_system->Add(mesh);
int n_nodes = 2 * (1 + N);
double dx = length / N;
ChVector<> dir(0, 1, 0);
auto nodeA = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, -width / 2), dir);
auto nodeB = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(0, 0, +width / 2), dir);
nodeA->SetFixed(true);
nodeB->SetFixed(true);
mesh->AddNode(nodeA);
mesh->AddNode(nodeB);
for (int i = 1; i <= N; i++) {
auto nodeC = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, -width / 2), dir);
auto nodeD = chrono_types::make_shared<ChNodeFEAxyzD>(ChVector<>(i * dx, 0, +width / 2), dir);
mesh->AddNode(nodeC);
mesh->AddNode(nodeD);
auto element = chrono_types::make_shared<ChElementShellANCF>();
element->SetNodes(nodeA, nodeB, nodeD, nodeC);
element->SetDimensions(dx, width);
element->AddLayer(thickness, 0 * CH_C_DEG_TO_RAD, mat);
element->SetAlphaDamp(0.0);
element->SetGravityOn(false);
mesh->AddElement(element);
nodeA = nodeC;
nodeB = nodeD;
}
}
void TearDown(const ::benchmark::State&) override { delete m_system; }
void Report(benchmark::State& st) {
auto descr = m_system->GetSystemDescriptor();
auto num_it = st.iterations();
st.counters["SIZE"] = descr->CountActiveVariables() + descr->CountActiveConstraints();
st.counters["LS_Jacobian"] = m_system->GetTimerJacobian() * 1e3 / num_it;
st.counters["LS_Setup"] = m_system->GetTimerSetup() * 1e3 / num_it;
st.counters["LS_Solve"] = m_system->GetTimerSolver() * 1e3 / num_it;
}
protected:
ChSystemSMC* m_system;
};
#define BM_SOLVER_MKL(TEST_NAME, N, WITH_LEARNER) \
BENCHMARK_TEMPLATE_DEFINE_F(SystemFixture, TEST_NAME, N)(benchmark::State & st) { \
auto solver = chrono_types::make_shared<ChSolverMKL<>>(); \
solver->SetSparsityPatternLock(true); \
solver->SetVerbose(false); \
m_system->SetSolver(solver); \
while (st.KeepRunning()) { \
solver->ForceSparsityPatternUpdate(WITH_LEARNER); \
m_system->DoStaticLinear(); \
} \
Report(st); \
} \
BENCHMARK_REGISTER_F(SystemFixture, TEST_NAME)->Unit(benchmark::kMillisecond);
#define BM_SOLVER_MUMPS(TEST_NAME, N, WITH_LEARNER) \
BENCHMARK_TEMPLATE_DEFINE_F(SystemFixture, TEST_NAME, N)(benchmark::State & st) { \
auto solver = chrono_types::make_shared<ChSolverMumps>(); \
solver->SetSparsityPatternLock(true); \
solver->SetVerbose(false); \
m_system->SetSolver(solver); \
while (st.KeepRunning()) { \
solver->ForceSparsityPatternUpdate(WITH_LEARNER); \
m_system->DoStaticLinear(); \
} \
Report(st); \
} \
BENCHMARK_REGISTER_F(SystemFixture, TEST_NAME)->Unit(benchmark::kMillisecond);
#ifdef CHRONO_MKL
BM_SOLVER_MKL(MKL_learner_500, 500, true)
BM_SOLVER_MKL(MKL_no_learner_500, 500, false)
BM_SOLVER_MKL(MKL_learner_1000, 1000, true)
BM_SOLVER_MKL(MKL_no_learner_1000, 1000, false)
BM_SOLVER_MKL(MKL_learner_2000, 2000, true)
BM_SOLVER_MKL(MKL_no_learner_2000, 2000, false)
BM_SOLVER_MKL(MKL_learner_4000, 4000, true)
BM_SOLVER_MKL(MKL_no_learner_4000, 4000, false)
BM_SOLVER_MKL(MKL_learner_8000, 8000, true)
BM_SOLVER_MKL(MKL_no_learner_8000, 8000, false)
#endif
#ifdef CHRONO_MUMPS
BM_SOLVER_MUMPS(MUMPS_learner_500, 500, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_500, 500, false)
BM_SOLVER_MUMPS(MUMPS_learner_1000, 1000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_1000, 1000, false)
BM_SOLVER_MUMPS(MUMPS_learner_2000, 2000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_2000, 2000, false)
BM_SOLVER_MUMPS(MUMPS_learner_4000, 4000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_4000, 4000, false)
BM_SOLVER_MUMPS(MUMPS_learner_8000, 8000, true)
BM_SOLVER_MUMPS(MUMPS_no_learner_8000, 8000, false)
#endif
<|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 <map>
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <stout/option.hpp>
#include <stout/uuid.hpp>
#include "messages/messages.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/composing.hpp"
#include "tests/mesos.hpp"
#include "tests/containerizer/mock_containerizer.hpp"
using namespace mesos::internal::slave;
using namespace process;
using std::map;
using std::string;
using std::vector;
using testing::_;
using testing::DoAll;
using testing::Return;
using mesos::slave::ContainerTermination;
namespace mesos {
namespace internal {
namespace tests {
class ComposingContainerizerTest : public MesosTest {};
// This test ensures that destroy can be called while in the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is not supported by the 1st containerizer,
// the composing containerizer should stop the launch loop and
// set the value of destroy future to true.
TEST_F(ComposingContainerizerTest, DestroyDuringUnsupportedLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
EXPECT_CALL(*mockContainerizer2, launch(_, _, _, _))
.Times(0);
// We make sure the destroy is being called on the first containerizer.
// The second containerizer shouldn't be called as well since the
// container is already destroyed.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::NOT_SUPPORTED);
destroyPromise.set(false);
// `launched` should be a failure and `destroyed` should be true
// because the launch was stopped from being tried on the 2nd
// containerizer because of the destroy.
AWAIT_FAILED(launched);
AWAIT_EXPECT_EQ(true, destroyed);
}
// This test ensures that destroy can be called while in the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is successful the destroy future
// value depends on the containerizer's destroy.
TEST_F(ComposingContainerizerTest, DestroyDuringSupportedLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
EXPECT_CALL(*mockContainerizer2, launch(_, _, _, _))
.Times(0);
// We make sure the destroy is being called on the first containerizer.
// The second containerizer shouldn't be called as well since the
// container is already destroyed.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::SUCCESS);
destroyPromise.set(false);
// `launched` should return true and `destroyed` should return false
// because the launch succeeded and `destroyPromise` was set to false.
AWAIT_EXPECT_EQ(Containerizer::LaunchResult::SUCCESS, launched);
AWAIT_EXPECT_EQ(false, destroyed);
}
// This test ensures that destroy can be called at the end of the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is not supported by any containerizers
// both the launch and destroy futures should be false.
TEST_F(ComposingContainerizerTest, DestroyAfterLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
// We make sure the destroy is being called on the containerizer.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::NOT_SUPPORTED);
destroyPromise.set(false);
// `launch` should return false and `destroyed` should return false
// because none of the containerizers support the launch.
AWAIT_EXPECT_EQ(Containerizer::LaunchResult::NOT_SUPPORTED, launched);
AWAIT_EXPECT_EQ(false, destroyed);
}
// Ensures the containerizer responds correctly (false Future) to
// a request to destroy an unknown container.
TEST_F(ComposingContainerizerTest, DestroyUnknownContainer)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
AWAIT_EXPECT_FALSE(containerizer.destroy(containerId));
}
// Ensures the containerizer responds correctly (returns None)
// to a request to wait on an unknown container.
TEST_F(ComposingContainerizerTest, WaitUnknownContainer)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
Future<Option<ContainerTermination>> wait = containerizer.wait(containerId);
AWAIT_READY(wait);
EXPECT_NONE(wait.get());
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Updated composing containerizer tests.<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 <map>
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <stout/option.hpp>
#include <stout/uuid.hpp>
#include "messages/messages.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/composing.hpp"
#include "tests/mesos.hpp"
#include "tests/containerizer/mock_containerizer.hpp"
using namespace mesos::internal::slave;
using namespace process;
using std::map;
using std::string;
using std::vector;
using testing::_;
using testing::DoAll;
using testing::Return;
using mesos::slave::ContainerTermination;
namespace mesos {
namespace internal {
namespace tests {
class ComposingContainerizerTest : public MesosTest {};
// This test ensures that destroy can be called while in the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is not supported by the 1st containerizer,
// the composing containerizer should stop the launch loop and
// set the value of destroy future to true.
TEST_F(ComposingContainerizerTest, DestroyDuringUnsupportedLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> wait;
Promise<Option<ContainerTermination>> waitPromise;
EXPECT_CALL(*mockContainerizer1, wait(_))
.WillOnce(DoAll(FutureSatisfy(&wait),
Return(waitPromise.future())));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
EXPECT_CALL(*mockContainerizer2, launch(_, _, _, _))
.Times(0);
// We make sure the wait is being called on the first containerizer.
AWAIT_READY(wait);
// We make sure the destroy is being called on the first containerizer.
// The second containerizer shouldn't be called as well since the
// container is already destroyed.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::NOT_SUPPORTED);
destroyPromise.set(false);
waitPromise.set(Option<ContainerTermination>::none());
// `launched` should be a failure and `destroyed` should be true
// because the launch was stopped from being tried on the 2nd
// containerizer because of the destroy.
AWAIT_FAILED(launched);
AWAIT_EXPECT_EQ(true, destroyed);
}
// This test ensures that destroy can be called while in the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is successful the destroy future
// value depends on the containerizer's termination future.
TEST_F(ComposingContainerizerTest, DestroyDuringSupportedLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> wait;
Promise<Option<ContainerTermination>> waitPromise;
EXPECT_CALL(*mockContainerizer1, wait(_))
.WillOnce(DoAll(FutureSatisfy(&wait),
Return(waitPromise.future())));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
EXPECT_CALL(*mockContainerizer2, launch(_, _, _, _))
.Times(0);
// We make sure the wait is being called on the first containerizer.
AWAIT_READY(wait);
// We make sure the destroy is being called on the first containerizer.
// The second containerizer shouldn't be called as well since the
// container is already destroyed.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::SUCCESS);
destroyPromise.set(false);
waitPromise.set(Option<ContainerTermination>::none());
// `launched` should return true and `destroyed` should return false
// because the launch succeeded and `waitPromise` was set to `None`.
AWAIT_EXPECT_EQ(Containerizer::LaunchResult::SUCCESS, launched);
AWAIT_EXPECT_EQ(false, destroyed);
}
// This test ensures that destroy can be called at the end of the
// launch loop. The composing containerizer still calls the
// underlying containerizer's destroy (because it's not sure
// if the containerizer can handle the type of container being
// launched). If the launch is not supported by any containerizers
// both the launch and destroy futures should be false.
TEST_F(ComposingContainerizerTest, DestroyAfterLaunchLoop)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value("container");
TaskInfo taskInfo;
ExecutorInfo executorInfo;
SlaveID slaveId;
map<string, string> environment;
Promise<Containerizer::LaunchResult> launchPromise;
EXPECT_CALL(*mockContainerizer1, launch(_, _, _, _))
.WillOnce(Return(launchPromise.future()));
Future<Nothing> wait;
Promise<Option<ContainerTermination>> waitPromise;
EXPECT_CALL(*mockContainerizer1, wait(_))
.WillOnce(DoAll(FutureSatisfy(&wait),
Return(waitPromise.future())));
Future<Nothing> destroy;
Promise<bool> destroyPromise;
EXPECT_CALL(*mockContainerizer1, destroy(_))
.WillOnce(DoAll(FutureSatisfy(&destroy),
Return(destroyPromise.future())));
Future<Containerizer::LaunchResult> launched = containerizer.launch(
containerId,
createContainerConfig(taskInfo, executorInfo, "dir", "user"),
environment,
None());
Resources resources = Resources::parse("cpus:1;mem:256").get();
EXPECT_TRUE(launched.isPending());
Future<bool> destroyed = containerizer.destroy(containerId);
// We make sure the wait is being called on the containerizer.
AWAIT_READY(wait);
// We make sure the destroy is being called on the containerizer.
AWAIT_READY(destroy);
launchPromise.set(Containerizer::LaunchResult::NOT_SUPPORTED);
destroyPromise.set(false);
waitPromise.set(Option<ContainerTermination>::none());
// `launch` should return false and `destroyed` should return false
// because none of the containerizers support the launch.
AWAIT_EXPECT_EQ(Containerizer::LaunchResult::NOT_SUPPORTED, launched);
AWAIT_EXPECT_EQ(false, destroyed);
}
// Ensures the containerizer responds correctly (false Future) to
// a request to destroy an unknown container.
TEST_F(ComposingContainerizerTest, DestroyUnknownContainer)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
AWAIT_EXPECT_FALSE(containerizer.destroy(containerId));
}
// Ensures the containerizer responds correctly (returns None)
// to a request to wait on an unknown container.
TEST_F(ComposingContainerizerTest, WaitUnknownContainer)
{
vector<Containerizer*> containerizers;
MockContainerizer* mockContainerizer1 = new MockContainerizer();
MockContainerizer* mockContainerizer2 = new MockContainerizer();
containerizers.push_back(mockContainerizer1);
containerizers.push_back(mockContainerizer2);
ComposingContainerizer containerizer(containerizers);
ContainerID containerId;
containerId.set_value(UUID::random().toString());
Future<Option<ContainerTermination>> wait = containerizer.wait(containerId);
AWAIT_READY(wait);
EXPECT_NONE(wait.get());
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N;
int T;
int t[110];
int v[110];
int w[50000];
int main () {
cin >> N;
T = 0;
for (auto i = 0; i < N; ++i) {
cin >> t[i];
t[i] *= 2;
T += t[i];
}
for (auto i = 0; i < N; ++i) {
cin >> v[i];
v[i] *= 2;
}
w[0] = 0;
w[T] = 0;
for (auto i = 0; i <= T; ++i) {
w[i] = i;
}
for (auto i = 0; i <= T; ++i) {
w[i] = min(w[i], T - i);
}
int sum = 0;
for (auto i = 0; i < N; ++i) {
int all = sum + t[i];
for (auto j = 0; sum-j >= 0; --j) {
w[sum-j] = min(w[sum-j], v[i]+j);
}
for (auto j = sum; j <= all; ++j) {
w[j] = min(w[j], v[i]);
}
for (auto j = 0; all+j <= T; ++j) {
w[all+j] = min(w[all+j], v[i]+j);
}
sum += t[i];
}
double ans = 0;
for (auto i = 0; i < T; ++i) {
ans += ((double)w[i] + (double)w[i+1])/2;
}
cout << fixed << setprecision(10) << ans/4 << endl;
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N;
int T;
int t[110];
int v[110];
int w[50000];
int main () {
cin >> N;
T = 0;
for (auto i = 0; i < N; ++i) {
cin >> t[i];
t[i] *= 2;
T += t[i];
}
for (auto i = 0; i < N; ++i) {
cin >> v[i];
v[i] *= 2;
}
for (auto i = 0; i <= T; ++i) {
w[i] = min(i, T - i);
}
int sum = 0;
for (auto i = 0; i < N; ++i) {
cerr << "i = " << i << endl;
int all = sum + t[i];
for (auto j = 0; sum-j >= 0; --j) {
w[sum-j] = min(w[sum-j], v[i]+j);
}
for (auto j = sum; j <= all; ++j) {
w[j] = min(w[j], v[i]);
}
for (auto j = 0; all+j <= T; ++j) {
w[all+j] = min(w[all+j], v[i]+j);
}
sum += t[i];
}
double ans = 0;
for (auto i = 0; i < T; ++i) {
ans += ((double)w[i] + (double)w[i+1])/2;
}
cout << fixed << setprecision(10) << ans/4 << endl;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/proto/heap_graph_tracker.h"
namespace perfetto {
namespace trace_processor {
HeapGraphTracker::HeapGraphTracker(TraceProcessorContext* context)
: context_(context) {}
HeapGraphTracker::SequenceState& HeapGraphTracker::GetOrCreateSequence(
uint32_t seq_id) {
auto seq_it = sequence_state_.find(seq_id);
if (seq_it == sequence_state_.end()) {
std::tie(seq_it, std::ignore) = sequence_state_.emplace(seq_id, this);
}
return seq_it->second;
}
bool HeapGraphTracker::SetPidAndTimestamp(SequenceState* sequence_state,
UniquePid upid,
int64_t ts) {
if (sequence_state->current_upid != 0 &&
sequence_state->current_upid != upid) {
context_->storage->IncrementStats(stats::heap_graph_non_finalized_graph);
return false;
}
if (sequence_state->current_ts != 0 && sequence_state->current_ts != ts) {
context_->storage->IncrementStats(stats::heap_graph_non_finalized_graph);
return false;
}
sequence_state->current_upid = upid;
sequence_state->current_ts = ts;
return true;
}
void HeapGraphTracker::AddObject(uint32_t seq_id,
UniquePid upid,
int64_t ts,
SourceObject obj) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (!SetPidAndTimestamp(&sequence_state, upid, ts))
return;
sequence_state.current_objects.emplace_back(std::move(obj));
}
void HeapGraphTracker::AddRoot(uint32_t seq_id,
UniquePid upid,
int64_t ts,
SourceRoot root) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (!SetPidAndTimestamp(&sequence_state, upid, ts))
return;
sequence_state.current_roots.emplace_back(std::move(root));
}
void HeapGraphTracker::AddInternedTypeName(uint32_t seq_id,
uint64_t intern_id,
StringPool::Id strid) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
sequence_state.interned_type_names.emplace(intern_id, strid);
}
void HeapGraphTracker::AddInternedFieldName(uint32_t seq_id,
uint64_t intern_id,
StringPool::Id strid) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
sequence_state.interned_field_names.emplace(intern_id, strid);
}
void HeapGraphTracker::SetPacketIndex(uint32_t seq_id, uint64_t index) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (sequence_state.prev_index != 0 &&
sequence_state.prev_index + 1 != index) {
PERFETTO_ELOG("Missing packets between %" PRIu64 " and %" PRIu64,
sequence_state.prev_index, index);
context_->storage->IncrementIndexedStats(
stats::heap_graph_missing_packet,
static_cast<int>(sequence_state.current_upid));
}
sequence_state.prev_index = index;
}
void HeapGraphTracker::FinalizeProfile(uint32_t seq_id) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
for (const SourceObject& obj : sequence_state.current_objects) {
auto it = sequence_state.interned_type_names.find(obj.type_id);
if (it == sequence_state.interned_type_names.end()) {
context_->storage->IncrementIndexedStats(
stats::heap_graph_invalid_string_id,
static_cast<int>(sequence_state.current_upid));
continue;
}
StringPool::Id type_name = it->second;
context_->storage->mutable_heap_graph_object_table()->Insert(
{sequence_state.current_upid, sequence_state.current_ts,
static_cast<int64_t>(obj.object_id),
static_cast<int64_t>(obj.self_size), /*retained_size=*/-1,
/*unique_retained_size=*/-1, /*reference_set_id=*/-1,
/*reachable=*/0, /*type_name=*/type_name,
/*deobfuscated_type_name=*/base::nullopt,
/*root_type=*/base::nullopt});
int64_t row = context_->storage->heap_graph_object_table().row_count() - 1;
sequence_state.object_id_to_row.emplace(obj.object_id, row);
class_to_rows_[type_name].emplace_back(row);
sequence_state.walker.AddNode(row, obj.self_size,
static_cast<int32_t>(type_name.id));
}
for (const SourceObject& obj : sequence_state.current_objects) {
auto it = sequence_state.object_id_to_row.find(obj.object_id);
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t owner_row = it->second;
int64_t reference_set_id =
context_->storage->heap_graph_reference_table().row_count();
std::set<int64_t> seen_owned;
for (const SourceObject::Reference& ref : obj.references) {
// This is true for unset reference fields.
if (ref.owned_object_id == 0)
continue;
it = sequence_state.object_id_to_row.find(ref.owned_object_id);
// This can only happen for an invalid type string id, which is already
// reported as an error. Silently continue here.
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t owned_row = it->second;
bool inserted;
std::tie(std::ignore, inserted) = seen_owned.emplace(owned_row);
if (inserted)
sequence_state.walker.AddEdge(owner_row, owned_row);
auto field_name_it =
sequence_state.interned_field_names.find(ref.field_name_id);
if (field_name_it == sequence_state.interned_field_names.end()) {
context_->storage->IncrementIndexedStats(
stats::heap_graph_invalid_string_id,
static_cast<int>(sequence_state.current_upid));
continue;
}
StringPool::Id field_name = field_name_it->second;
context_->storage->mutable_heap_graph_reference_table()->Insert(
{reference_set_id, owner_row, owned_row, field_name,
/*deobfuscated_field_name=*/base::nullopt});
int64_t row =
context_->storage->heap_graph_reference_table().row_count() - 1;
field_to_rows_[field_name].emplace_back(row);
}
context_->storage->mutable_heap_graph_object_table()
->mutable_reference_set_id()
->Set(static_cast<uint32_t>(owner_row), reference_set_id);
}
for (const SourceRoot& root : sequence_state.current_roots) {
for (uint64_t obj_id : root.object_ids) {
auto it = sequence_state.object_id_to_row.find(obj_id);
// This can only happen for an invalid type string id, which is already
// reported as an error. Silently continue here.
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t obj_row = it->second;
sequence_state.walker.MarkRoot(obj_row);
context_->storage->mutable_heap_graph_object_table()
->mutable_root_type()
->Set(static_cast<uint32_t>(obj_row), root.root_type);
}
}
TraceStorage::StackProfileMappings::Row mapping_row{};
mapping_row.name_id = context_->storage->InternString("JAVA");
uint32_t mapping_id =
context_->storage->mutable_stack_profile_mappings()->Insert(mapping_row);
auto paths = sequence_state.walker.FindPathsFromRoot();
for (const auto& p : paths.children)
WriteFlamegraph(sequence_state, p.second, -1, 0, mapping_id);
sequence_state_.erase(seq_id);
}
void HeapGraphTracker::WriteFlamegraph(
const SequenceState& sequence_state,
const HeapGraphWalker::PathFromRoot& path,
int32_t parent_id,
uint32_t depth,
uint32_t mapping_id) {
TraceStorage::StackProfileFrames::Row row{};
row.name_id = StringId(static_cast<uint32_t>(path.class_name));
row.mapping_row = mapping_id;
int32_t frame_id = static_cast<int32_t>(
context_->storage->mutable_stack_profile_frames()->Insert(row));
parent_id = static_cast<int32_t>(
context_->storage->mutable_stack_profile_callsite_table()->Insert(
{depth, parent_id, frame_id}));
depth++;
TraceStorage::HeapProfileAllocations::Row alloc_row{
sequence_state.current_ts, sequence_state.current_upid, parent_id,
static_cast<int64_t>(path.count), static_cast<int64_t>(path.size)};
// TODO(fmayer): Maybe add a separate table for heap graph flamegraphs.
context_->storage->mutable_heap_profile_allocations()->Insert(alloc_row);
for (const auto& p : path.children) {
const HeapGraphWalker::PathFromRoot& child = p.second;
WriteFlamegraph(sequence_state, child, parent_id, depth, mapping_id);
}
}
void HeapGraphTracker::MarkReachable(int64_t row) {
context_->storage->mutable_heap_graph_object_table()
->mutable_reachable()
->Set(static_cast<uint32_t>(row), 1);
}
void HeapGraphTracker::SetRetained(int64_t row,
int64_t retained,
int64_t unique_retained) {
context_->storage->mutable_heap_graph_object_table()
->mutable_retained_size()
->Set(static_cast<uint32_t>(row), retained);
context_->storage->mutable_heap_graph_object_table()
->mutable_unique_retained_size()
->Set(static_cast<uint32_t>(row), unique_retained);
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>trace_processor: fix compile am: 9b0c60f683 am: 7d8f0a86a2 am: 38e8d4d658<commit_after>/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/importers/proto/heap_graph_tracker.h"
namespace perfetto {
namespace trace_processor {
HeapGraphTracker::HeapGraphTracker(TraceProcessorContext* context)
: context_(context) {}
HeapGraphTracker::SequenceState& HeapGraphTracker::GetOrCreateSequence(
uint32_t seq_id) {
auto seq_it = sequence_state_.find(seq_id);
if (seq_it == sequence_state_.end()) {
std::tie(seq_it, std::ignore) = sequence_state_.emplace(seq_id, this);
}
return seq_it->second;
}
bool HeapGraphTracker::SetPidAndTimestamp(SequenceState* sequence_state,
UniquePid upid,
int64_t ts) {
if (sequence_state->current_upid != 0 &&
sequence_state->current_upid != upid) {
context_->storage->IncrementStats(stats::heap_graph_non_finalized_graph);
return false;
}
if (sequence_state->current_ts != 0 && sequence_state->current_ts != ts) {
context_->storage->IncrementStats(stats::heap_graph_non_finalized_graph);
return false;
}
sequence_state->current_upid = upid;
sequence_state->current_ts = ts;
return true;
}
void HeapGraphTracker::AddObject(uint32_t seq_id,
UniquePid upid,
int64_t ts,
SourceObject obj) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (!SetPidAndTimestamp(&sequence_state, upid, ts))
return;
sequence_state.current_objects.emplace_back(std::move(obj));
}
void HeapGraphTracker::AddRoot(uint32_t seq_id,
UniquePid upid,
int64_t ts,
SourceRoot root) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (!SetPidAndTimestamp(&sequence_state, upid, ts))
return;
sequence_state.current_roots.emplace_back(std::move(root));
}
void HeapGraphTracker::AddInternedTypeName(uint32_t seq_id,
uint64_t intern_id,
StringPool::Id strid) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
sequence_state.interned_type_names.emplace(intern_id, strid);
}
void HeapGraphTracker::AddInternedFieldName(uint32_t seq_id,
uint64_t intern_id,
StringPool::Id strid) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
sequence_state.interned_field_names.emplace(intern_id, strid);
}
void HeapGraphTracker::SetPacketIndex(uint32_t seq_id, uint64_t index) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
if (sequence_state.prev_index != 0 &&
sequence_state.prev_index + 1 != index) {
PERFETTO_ELOG("Missing packets between %" PRIu64 " and %" PRIu64,
sequence_state.prev_index, index);
context_->storage->IncrementIndexedStats(
stats::heap_graph_missing_packet,
static_cast<int>(sequence_state.current_upid));
}
sequence_state.prev_index = index;
}
void HeapGraphTracker::FinalizeProfile(uint32_t seq_id) {
SequenceState& sequence_state = GetOrCreateSequence(seq_id);
for (const SourceObject& obj : sequence_state.current_objects) {
auto it = sequence_state.interned_type_names.find(obj.type_id);
if (it == sequence_state.interned_type_names.end()) {
context_->storage->IncrementIndexedStats(
stats::heap_graph_invalid_string_id,
static_cast<int>(sequence_state.current_upid));
continue;
}
StringPool::Id type_name = it->second;
context_->storage->mutable_heap_graph_object_table()->Insert(
{sequence_state.current_upid, sequence_state.current_ts,
static_cast<int64_t>(obj.object_id),
static_cast<int64_t>(obj.self_size), /*retained_size=*/-1,
/*unique_retained_size=*/-1, /*reference_set_id=*/-1,
/*reachable=*/0, /*type_name=*/type_name,
/*deobfuscated_type_name=*/base::nullopt,
/*root_type=*/base::nullopt});
int64_t row = context_->storage->heap_graph_object_table().row_count() - 1;
sequence_state.object_id_to_row.emplace(obj.object_id, row);
class_to_rows_[type_name].emplace_back(row);
sequence_state.walker.AddNode(row, obj.self_size,
static_cast<int32_t>(type_name.id));
}
for (const SourceObject& obj : sequence_state.current_objects) {
auto it = sequence_state.object_id_to_row.find(obj.object_id);
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t owner_row = it->second;
int64_t reference_set_id =
context_->storage->heap_graph_reference_table().row_count();
std::set<int64_t> seen_owned;
for (const SourceObject::Reference& ref : obj.references) {
// This is true for unset reference fields.
if (ref.owned_object_id == 0)
continue;
it = sequence_state.object_id_to_row.find(ref.owned_object_id);
// This can only happen for an invalid type string id, which is already
// reported as an error. Silently continue here.
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t owned_row = it->second;
bool inserted;
std::tie(std::ignore, inserted) = seen_owned.emplace(owned_row);
if (inserted)
sequence_state.walker.AddEdge(owner_row, owned_row);
auto field_name_it =
sequence_state.interned_field_names.find(ref.field_name_id);
if (field_name_it == sequence_state.interned_field_names.end()) {
context_->storage->IncrementIndexedStats(
stats::heap_graph_invalid_string_id,
static_cast<int>(sequence_state.current_upid));
continue;
}
StringPool::Id field_name = field_name_it->second;
context_->storage->mutable_heap_graph_reference_table()->Insert(
{reference_set_id, owner_row, owned_row, field_name,
/*deobfuscated_field_name=*/base::nullopt});
int64_t row =
context_->storage->heap_graph_reference_table().row_count() - 1;
field_to_rows_[field_name].emplace_back(row);
}
context_->storage->mutable_heap_graph_object_table()
->mutable_reference_set_id()
->Set(static_cast<uint32_t>(owner_row), reference_set_id);
}
for (const SourceRoot& root : sequence_state.current_roots) {
for (uint64_t obj_id : root.object_ids) {
auto it = sequence_state.object_id_to_row.find(obj_id);
// This can only happen for an invalid type string id, which is already
// reported as an error. Silently continue here.
if (it == sequence_state.object_id_to_row.end())
continue;
int64_t obj_row = it->second;
sequence_state.walker.MarkRoot(obj_row);
context_->storage->mutable_heap_graph_object_table()
->mutable_root_type()
->Set(static_cast<uint32_t>(obj_row), root.root_type);
}
}
TraceStorage::StackProfileMappings::Row mapping_row{};
mapping_row.name_id = context_->storage->InternString("JAVA");
uint32_t mapping_id =
context_->storage->mutable_stack_profile_mappings()->Insert(mapping_row);
auto paths = sequence_state.walker.FindPathsFromRoot();
for (const auto& p : paths.children)
WriteFlamegraph(sequence_state, p.second, -1, 0, mapping_id);
sequence_state_.erase(seq_id);
}
void HeapGraphTracker::WriteFlamegraph(
const SequenceState& sequence_state,
const HeapGraphWalker::PathFromRoot& path,
int32_t parent_id,
uint32_t depth,
uint32_t mapping_id) {
TraceStorage::StackProfileFrames::Row row{};
row.name_id = StringId(static_cast<uint32_t>(path.class_name));
row.mapping_row = mapping_id;
int32_t frame_id = static_cast<int32_t>(
context_->storage->mutable_stack_profile_frames()->Insert(row));
parent_id = static_cast<int32_t>(
context_->storage->mutable_stack_profile_callsite_table()->Insert(
{depth, parent_id, frame_id}));
depth++;
tables::HeapProfileAllocationTable::Row alloc_row{
sequence_state.current_ts, sequence_state.current_upid, parent_id,
static_cast<int64_t>(path.count), static_cast<int64_t>(path.size)};
// TODO(fmayer): Maybe add a separate table for heap graph flamegraphs.
context_->storage->mutable_heap_profile_allocation_table()->Insert(alloc_row);
for (const auto& p : path.children) {
const HeapGraphWalker::PathFromRoot& child = p.second;
WriteFlamegraph(sequence_state, child, parent_id, depth, mapping_id);
}
}
void HeapGraphTracker::MarkReachable(int64_t row) {
context_->storage->mutable_heap_graph_object_table()
->mutable_reachable()
->Set(static_cast<uint32_t>(row), 1);
}
void HeapGraphTracker::SetRetained(int64_t row,
int64_t retained,
int64_t unique_retained) {
context_->storage->mutable_heap_graph_object_table()
->mutable_retained_size()
->Set(static_cast<uint32_t>(row), retained);
context_->storage->mutable_heap_graph_object_table()
->mutable_unique_retained_size()
->Set(static_cast<uint32_t>(row), unique_retained);
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|>
|
<commit_before>/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2018-9-8 21:12:40
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
bool a[510][510];
typedef tuple<int, int, int, int> X;
vector<X> V;
int odd[510];
void flush()
{
int N = (int)V.size();
cout << N << endl;
for (auto i = 0; i < N; i++)
{
X x = V[i];
cout << get<0>(x) + 1 << " " << get<1>(x) + 1 << " " << get<2>(x) + 1 << " " << get<3>(x) + 1 << endl;
}
}
void make_swap(int x, int y, int z, int w)
{
// swap(a[x][y], a[z][w]);
V.push_back(X(x, y, z, w));
}
int main()
{
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
int x;
cin >> x;
a[i][j] = (x % 2 == 1);
}
}
fill(odd, odd + 510, -1);
for (auto i = 0; i < H; i++)
{
int y = -1;
int cnt = 0;
for (auto j = 0; j < W; j++)
{
if (a[i][j])
{
cerr << "(" << i << ", " << j << ")" << endl;
if (cnt % 2 == 0)
{
y = j;
}
else
{
int z = j;
cerr << "y = " << y << ", z = " << z << endl;
for (auto k = y; k < z - 1; k++)
{
make_swap(i, k, i, k + 1);
}
}
cnt++;
}
}
if (cnt % 2 == 1)
{
odd[i] = y;
for (auto k = y; k < W - 1; k++)
{
make_swap(i, k, i, k + 1);
}
}
}
int x;
int cnt = 0;
for (auto i = 0; i < H; i++)
{
if (odd[i] >= 0)
{
if (cnt % 2 == 0)
{
x = i;
}
else
{
int z = i;
for (auto k = x; k < z - 1; k++)
{
make_swap(k, W - 1, k + 1, W - 1);
}
}
cnt++;
}
}
flush();
}<commit_msg>tried D.cpp to 'D'<commit_after>/**
* File : D.cpp
* Author : Kazune Takahashi
* Created : 2018-9-8 21:12:40
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W;
bool a[510][510];
typedef tuple<int, int, int, int> X;
vector<X> V;
int odd[510];
void flush()
{
int N = (int)V.size();
cout << N << endl;
for (auto i = 0; i < N; i++)
{
X x = V[i];
cout << get<0>(x) + 1 << " " << get<1>(x) + 1 << " " << get<2>(x) + 1 << " " << get<3>(x) + 1 << endl;
}
}
void make_swap(int x, int y, int z, int w)
{
// swap(a[x][y], a[z][w]);
V.push_back(X(x, y, z, w));
}
int main()
{
cin >> H >> W;
for (auto i = 0; i < H; i++)
{
for (auto j = 0; j < W; j++)
{
int x;
cin >> x;
a[i][j] = (x % 2 == 1);
}
}
fill(odd, odd + 510, -1);
for (auto i = 0; i < H; i++)
{
int y = -1;
int cnt = 0;
for (auto j = 0; j < W; j++)
{
if (a[i][j])
{
cerr << "(" << i << ", " << j << ")" << endl;
if (cnt % 2 == 0)
{
y = j;
}
else
{
int z = j;
cerr << "y = " << y << ", z = " << z << endl;
for (auto k = y; k < z; k++)
{
make_swap(i, k, i, k + 1);
}
}
cnt++;
}
}
if (cnt % 2 == 1)
{
odd[i] = y;
for (auto k = y; k < W - 1; k++)
{
make_swap(i, k, i, k + 1);
}
}
}
int x = -1;
int cnt = 0;
for (auto i = 0; i < H; i++)
{
if (odd[i] >= 0)
{
if (cnt % 2 == 0)
{
x = i;
}
else
{
int z = i;
for (auto k = x; k < z; k++)
{
make_swap(k, W - 1, k + 1, W - 1);
}
}
cnt++;
}
}
flush();
}<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_receiver_video.h"
#include <cassert> //assert
#include <cstring> // memcpy()
#include <math.h>
#include "critical_section_wrapper.h"
#include "receiver_fec.h"
#include "rtp_rtcp_impl.h"
#include "rtp_utility.h"
#include "trace.h"
namespace webrtc {
WebRtc_UWord32 BitRateBPS(WebRtc_UWord16 x )
{
return (x & 0x3fff) * WebRtc_UWord32(pow(10.0f,(2 + (x >> 14))));
}
RTPReceiverVideo::RTPReceiverVideo(const WebRtc_Word32 id,
ModuleRtpRtcpImpl* owner)
: _id(id),
_criticalSectionReceiverVideo(
CriticalSectionWrapper::CreateCriticalSection()),
_currentFecFrameDecoded(false),
_receiveFEC(NULL) {
}
RTPReceiverVideo::~RTPReceiverVideo() {
delete _criticalSectionReceiverVideo;
delete _receiveFEC;
}
ModuleRTPUtility::Payload* RTPReceiverVideo::RegisterReceiveVideoPayload(
const char payloadName[RTP_PAYLOAD_NAME_SIZE],
const WebRtc_Word8 payloadType,
const WebRtc_UWord32 maxRate) {
RtpVideoCodecTypes videoType = kRtpNoVideo;
if (ModuleRTPUtility::StringCompare(payloadName, "VP8", 3)) {
videoType = kRtpVp8Video;
} else if (ModuleRTPUtility::StringCompare(payloadName, "I420", 4)) {
videoType = kRtpNoVideo;
} else if (ModuleRTPUtility::StringCompare(payloadName, "ULPFEC", 6)) {
// store this
if (_receiveFEC == NULL) {
_receiveFEC = new ReceiverFEC(_id, this);
}
_receiveFEC->SetPayloadTypeFEC(payloadType);
videoType = kRtpFecVideo;
} else {
return NULL;
}
ModuleRTPUtility::Payload* payload = new ModuleRTPUtility::Payload;
payload->name[RTP_PAYLOAD_NAME_SIZE - 1] = 0;
strncpy(payload->name, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
payload->typeSpecific.Video.videoCodecType = videoType;
payload->typeSpecific.Video.maxRate = maxRate;
payload->audio = false;
return payload;
}
// we have no critext when calling this
// we are not allowed to have any critsects when calling
// CallbackOfReceivedPayloadData
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecific(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType,
const bool isRED,
const WebRtc_UWord8* incomingRtpPacket,
const WebRtc_UWord16 incomingRtpPacketSize,
const WebRtc_Word64 nowMS) {
WebRtc_Word32 retVal = 0;
_criticalSectionReceiverVideo->Enter();
if (isRED) {
if(_receiveFEC == NULL) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
bool FECpacket = false;
retVal = _receiveFEC->AddReceivedFECPacket(
rtpHeader,
incomingRtpPacket,
payloadDataLength,
FECpacket);
if (retVal != -1) {
retVal = _receiveFEC->ProcessReceivedFEC();
}
_criticalSectionReceiverVideo->Leave();
if(retVal == 0 && FECpacket) {
// Callback with the received FEC packet.
// The normal packets are delivered after parsing.
// This contains the original RTP packet header but with
// empty payload and data length.
rtpHeader->frameType = kFrameEmpty;
// We need this for the routing.
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if(retVal != 0) {
return retVal;
}
// Pass the length of FEC packets so that they can be accounted for in
// the bandwidth estimator.
retVal = CallbackOfReceivedPayloadData(NULL, payloadDataLength,
rtpHeader);
}
} else {
// will leave the _criticalSectionReceiverVideo critsect
retVal = ParseVideoCodecSpecificSwitch(rtpHeader,
payloadData,
payloadDataLength,
videoType);
}
return retVal;
}
WebRtc_Word32 RTPReceiverVideo::BuildRTPheader(
const WebRtcRTPHeader* rtpHeader,
WebRtc_UWord8* dataBuffer) const {
dataBuffer[0] = static_cast<WebRtc_UWord8>(0x80); // version 2
dataBuffer[1] = static_cast<WebRtc_UWord8>(rtpHeader->header.payloadType);
if (rtpHeader->header.markerBit) {
dataBuffer[1] |= kRtpMarkerBitMask; // MarkerBit is 1
}
ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer + 2,
rtpHeader->header.sequenceNumber);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 4,
rtpHeader->header.timestamp);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 8,
rtpHeader->header.ssrc);
WebRtc_Word32 rtpHeaderLength = 12;
// Add the CSRCs if any
if (rtpHeader->header.numCSRCs > 0) {
if (rtpHeader->header.numCSRCs > 16) {
// error
assert(false);
}
WebRtc_UWord8* ptr = &dataBuffer[rtpHeaderLength];
for (WebRtc_UWord32 i = 0; i < rtpHeader->header.numCSRCs; ++i) {
ModuleRTPUtility::AssignUWord32ToBuffer(ptr,
rtpHeader->header.arrOfCSRCs[i]);
ptr +=4;
}
dataBuffer[0] = (dataBuffer[0]&0xf0) | rtpHeader->header.numCSRCs;
// Update length of header
rtpHeaderLength += sizeof(WebRtc_UWord32)*rtpHeader->header.numCSRCs;
}
return rtpHeaderLength;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveRecoveredPacketCallback(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
// TODO(pwestin) Re-factor this to avoid the messy critsect handling.
_criticalSectionReceiverVideo->Enter();
_currentFecFrameDecoded = true;
ModuleRTPUtility::Payload* payload = NULL;
if (PayloadTypeToPayload(rtpHeader->header.payloadType, payload) != 0) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
// here we can re-create the original lost packet so that we can use it for
// the relay we need to re-create the RED header too
WebRtc_UWord8 recoveredPacket[IP_PACKET_SIZE];
WebRtc_UWord16 rtpHeaderLength = (WebRtc_UWord16)BuildRTPheader(
rtpHeader, recoveredPacket);
const WebRtc_UWord8 REDForFECHeaderLength = 1;
// replace pltype
recoveredPacket[1] &= 0x80; // reset
recoveredPacket[1] += REDPayloadType(); // replace with RED payload type
// add RED header
recoveredPacket[rtpHeaderLength] = rtpHeader->header.payloadType;
// f-bit always 0
memcpy(recoveredPacket + rtpHeaderLength + REDForFECHeaderLength, payloadData,
payloadDataLength);
return ParseVideoCodecSpecificSwitch(
rtpHeader,
payloadData,
payloadDataLength,
payload->typeSpecific.Video.videoCodecType);
}
WebRtc_Word32 RTPReceiverVideo::SetCodecType(const RtpVideoCodecTypes videoType,
WebRtcRTPHeader* rtpHeader) const {
switch (videoType) {
case kRtpNoVideo:
rtpHeader->type.Video.codec = kRTPVideoGeneric;
break;
case kRtpVp8Video:
rtpHeader->type.Video.codec = kRTPVideoVP8;
break;
case kRtpFecVideo:
rtpHeader->type.Video.codec = kRTPVideoFEC;
break;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecificSwitch(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType) {
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if (retVal != 0) {
_criticalSectionReceiverVideo->Leave();
return retVal;
}
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, _id, "%s(timestamp:%u)",
__FUNCTION__, rtpHeader->header.timestamp);
// All receive functions release _criticalSectionReceiverVideo before
// returning.
switch (videoType) {
case kRtpNoVideo:
return ReceiveGenericCodec(rtpHeader, payloadData, payloadDataLength);
case kRtpVp8Video:
return ReceiveVp8Codec(rtpHeader, payloadData, payloadDataLength);
case kRtpFecVideo:
break;
}
_criticalSectionReceiverVideo->Leave();
return -1;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveVp8Codec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
bool success;
ModuleRTPUtility::RTPPayload parsedPacket;
if (payloadDataLength == 0) {
success = true;
parsedPacket.info.VP8.dataLength = 0;
} else {
ModuleRTPUtility::RTPPayloadParser rtpPayloadParser(kRtpVp8Video,
payloadData,
payloadDataLength,
_id);
success = rtpPayloadParser.Parse(parsedPacket);
}
// from here down we only work on local data
_criticalSectionReceiverVideo->Leave();
if (!success) {
return -1;
}
if (parsedPacket.info.VP8.dataLength == 0) {
// we have an "empty" VP8 packet, it's ok, could be one way video
// Inform the jitter buffer about this packet.
rtpHeader->frameType = kFrameEmpty;
if (CallbackOfReceivedPayloadData(NULL, 0, rtpHeader) != 0) {
return -1;
}
return 0;
}
rtpHeader->frameType = (parsedPacket.frameType == ModuleRTPUtility::kIFrame) ?
kVideoFrameKey : kVideoFrameDelta;
RTPVideoHeaderVP8 *toHeader = &rtpHeader->type.Video.codecHeader.VP8;
ModuleRTPUtility::RTPPayloadVP8 *fromHeader = &parsedPacket.info.VP8;
rtpHeader->type.Video.isFirstPacket = fromHeader->beginningOfPartition
&& (fromHeader->partitionID == 0);
toHeader->pictureId = fromHeader->hasPictureID ? fromHeader->pictureID :
kNoPictureId;
toHeader->tl0PicIdx = fromHeader->hasTl0PicIdx ? fromHeader->tl0PicIdx :
kNoTl0PicIdx;
if (fromHeader->hasTID) {
toHeader->temporalIdx = fromHeader->tID;
toHeader->layerSync = fromHeader->layerSync;
} else {
toHeader->temporalIdx = kNoTemporalIdx;
toHeader->layerSync = false;
}
toHeader->keyIdx = fromHeader->hasKeyIdx ? fromHeader->keyIdx : kNoKeyIdx;
toHeader->frameWidth = fromHeader->frameWidth;
toHeader->frameHeight = fromHeader->frameHeight;
toHeader->partitionId = fromHeader->partitionID;
toHeader->beginningOfPartition = fromHeader->beginningOfPartition;
if(CallbackOfReceivedPayloadData(parsedPacket.info.VP8.data,
parsedPacket.info.VP8.dataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveGenericCodec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
rtpHeader->frameType = kVideoFrameKey;
if(((SequenceNumber() + 1) == rtpHeader->header.sequenceNumber) &&
(TimeStamp() != rtpHeader->header.timestamp)) {
rtpHeader->type.Video.isFirstPacket = true;
}
_criticalSectionReceiverVideo->Leave();
if(CallbackOfReceivedPayloadData(payloadData, payloadDataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
} // namespace webrtc
<commit_msg>Update parsed non ref frame info. Review URL: https://webrtc-codereview.appspot.com/932015<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_receiver_video.h"
#include <cassert> //assert
#include <cstring> // memcpy()
#include <math.h>
#include "critical_section_wrapper.h"
#include "receiver_fec.h"
#include "rtp_rtcp_impl.h"
#include "rtp_utility.h"
#include "trace.h"
namespace webrtc {
WebRtc_UWord32 BitRateBPS(WebRtc_UWord16 x )
{
return (x & 0x3fff) * WebRtc_UWord32(pow(10.0f,(2 + (x >> 14))));
}
RTPReceiverVideo::RTPReceiverVideo(const WebRtc_Word32 id,
ModuleRtpRtcpImpl* owner)
: _id(id),
_criticalSectionReceiverVideo(
CriticalSectionWrapper::CreateCriticalSection()),
_currentFecFrameDecoded(false),
_receiveFEC(NULL) {
}
RTPReceiverVideo::~RTPReceiverVideo() {
delete _criticalSectionReceiverVideo;
delete _receiveFEC;
}
ModuleRTPUtility::Payload* RTPReceiverVideo::RegisterReceiveVideoPayload(
const char payloadName[RTP_PAYLOAD_NAME_SIZE],
const WebRtc_Word8 payloadType,
const WebRtc_UWord32 maxRate) {
RtpVideoCodecTypes videoType = kRtpNoVideo;
if (ModuleRTPUtility::StringCompare(payloadName, "VP8", 3)) {
videoType = kRtpVp8Video;
} else if (ModuleRTPUtility::StringCompare(payloadName, "I420", 4)) {
videoType = kRtpNoVideo;
} else if (ModuleRTPUtility::StringCompare(payloadName, "ULPFEC", 6)) {
// store this
if (_receiveFEC == NULL) {
_receiveFEC = new ReceiverFEC(_id, this);
}
_receiveFEC->SetPayloadTypeFEC(payloadType);
videoType = kRtpFecVideo;
} else {
return NULL;
}
ModuleRTPUtility::Payload* payload = new ModuleRTPUtility::Payload;
payload->name[RTP_PAYLOAD_NAME_SIZE - 1] = 0;
strncpy(payload->name, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
payload->typeSpecific.Video.videoCodecType = videoType;
payload->typeSpecific.Video.maxRate = maxRate;
payload->audio = false;
return payload;
}
// we have no critext when calling this
// we are not allowed to have any critsects when calling
// CallbackOfReceivedPayloadData
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecific(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType,
const bool isRED,
const WebRtc_UWord8* incomingRtpPacket,
const WebRtc_UWord16 incomingRtpPacketSize,
const WebRtc_Word64 nowMS) {
WebRtc_Word32 retVal = 0;
_criticalSectionReceiverVideo->Enter();
if (isRED) {
if(_receiveFEC == NULL) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
bool FECpacket = false;
retVal = _receiveFEC->AddReceivedFECPacket(
rtpHeader,
incomingRtpPacket,
payloadDataLength,
FECpacket);
if (retVal != -1) {
retVal = _receiveFEC->ProcessReceivedFEC();
}
_criticalSectionReceiverVideo->Leave();
if(retVal == 0 && FECpacket) {
// Callback with the received FEC packet.
// The normal packets are delivered after parsing.
// This contains the original RTP packet header but with
// empty payload and data length.
rtpHeader->frameType = kFrameEmpty;
// We need this for the routing.
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if(retVal != 0) {
return retVal;
}
// Pass the length of FEC packets so that they can be accounted for in
// the bandwidth estimator.
retVal = CallbackOfReceivedPayloadData(NULL, payloadDataLength,
rtpHeader);
}
} else {
// will leave the _criticalSectionReceiverVideo critsect
retVal = ParseVideoCodecSpecificSwitch(rtpHeader,
payloadData,
payloadDataLength,
videoType);
}
return retVal;
}
WebRtc_Word32 RTPReceiverVideo::BuildRTPheader(
const WebRtcRTPHeader* rtpHeader,
WebRtc_UWord8* dataBuffer) const {
dataBuffer[0] = static_cast<WebRtc_UWord8>(0x80); // version 2
dataBuffer[1] = static_cast<WebRtc_UWord8>(rtpHeader->header.payloadType);
if (rtpHeader->header.markerBit) {
dataBuffer[1] |= kRtpMarkerBitMask; // MarkerBit is 1
}
ModuleRTPUtility::AssignUWord16ToBuffer(dataBuffer + 2,
rtpHeader->header.sequenceNumber);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 4,
rtpHeader->header.timestamp);
ModuleRTPUtility::AssignUWord32ToBuffer(dataBuffer + 8,
rtpHeader->header.ssrc);
WebRtc_Word32 rtpHeaderLength = 12;
// Add the CSRCs if any
if (rtpHeader->header.numCSRCs > 0) {
if (rtpHeader->header.numCSRCs > 16) {
// error
assert(false);
}
WebRtc_UWord8* ptr = &dataBuffer[rtpHeaderLength];
for (WebRtc_UWord32 i = 0; i < rtpHeader->header.numCSRCs; ++i) {
ModuleRTPUtility::AssignUWord32ToBuffer(ptr,
rtpHeader->header.arrOfCSRCs[i]);
ptr +=4;
}
dataBuffer[0] = (dataBuffer[0]&0xf0) | rtpHeader->header.numCSRCs;
// Update length of header
rtpHeaderLength += sizeof(WebRtc_UWord32)*rtpHeader->header.numCSRCs;
}
return rtpHeaderLength;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveRecoveredPacketCallback(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
// TODO(pwestin) Re-factor this to avoid the messy critsect handling.
_criticalSectionReceiverVideo->Enter();
_currentFecFrameDecoded = true;
ModuleRTPUtility::Payload* payload = NULL;
if (PayloadTypeToPayload(rtpHeader->header.payloadType, payload) != 0) {
_criticalSectionReceiverVideo->Leave();
return -1;
}
// here we can re-create the original lost packet so that we can use it for
// the relay we need to re-create the RED header too
WebRtc_UWord8 recoveredPacket[IP_PACKET_SIZE];
WebRtc_UWord16 rtpHeaderLength = (WebRtc_UWord16)BuildRTPheader(
rtpHeader, recoveredPacket);
const WebRtc_UWord8 REDForFECHeaderLength = 1;
// replace pltype
recoveredPacket[1] &= 0x80; // reset
recoveredPacket[1] += REDPayloadType(); // replace with RED payload type
// add RED header
recoveredPacket[rtpHeaderLength] = rtpHeader->header.payloadType;
// f-bit always 0
memcpy(recoveredPacket + rtpHeaderLength + REDForFECHeaderLength, payloadData,
payloadDataLength);
return ParseVideoCodecSpecificSwitch(
rtpHeader,
payloadData,
payloadDataLength,
payload->typeSpecific.Video.videoCodecType);
}
WebRtc_Word32 RTPReceiverVideo::SetCodecType(const RtpVideoCodecTypes videoType,
WebRtcRTPHeader* rtpHeader) const {
switch (videoType) {
case kRtpNoVideo:
rtpHeader->type.Video.codec = kRTPVideoGeneric;
break;
case kRtpVp8Video:
rtpHeader->type.Video.codec = kRTPVideoVP8;
break;
case kRtpFecVideo:
rtpHeader->type.Video.codec = kRTPVideoFEC;
break;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ParseVideoCodecSpecificSwitch(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength,
const RtpVideoCodecTypes videoType) {
WebRtc_Word32 retVal = SetCodecType(videoType, rtpHeader);
if (retVal != 0) {
_criticalSectionReceiverVideo->Leave();
return retVal;
}
WEBRTC_TRACE(kTraceStream, kTraceRtpRtcp, _id, "%s(timestamp:%u)",
__FUNCTION__, rtpHeader->header.timestamp);
// All receive functions release _criticalSectionReceiverVideo before
// returning.
switch (videoType) {
case kRtpNoVideo:
return ReceiveGenericCodec(rtpHeader, payloadData, payloadDataLength);
case kRtpVp8Video:
return ReceiveVp8Codec(rtpHeader, payloadData, payloadDataLength);
case kRtpFecVideo:
break;
}
_criticalSectionReceiverVideo->Leave();
return -1;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveVp8Codec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
bool success;
ModuleRTPUtility::RTPPayload parsedPacket;
if (payloadDataLength == 0) {
success = true;
parsedPacket.info.VP8.dataLength = 0;
} else {
ModuleRTPUtility::RTPPayloadParser rtpPayloadParser(kRtpVp8Video,
payloadData,
payloadDataLength,
_id);
success = rtpPayloadParser.Parse(parsedPacket);
}
// from here down we only work on local data
_criticalSectionReceiverVideo->Leave();
if (!success) {
return -1;
}
if (parsedPacket.info.VP8.dataLength == 0) {
// we have an "empty" VP8 packet, it's ok, could be one way video
// Inform the jitter buffer about this packet.
rtpHeader->frameType = kFrameEmpty;
if (CallbackOfReceivedPayloadData(NULL, 0, rtpHeader) != 0) {
return -1;
}
return 0;
}
rtpHeader->frameType = (parsedPacket.frameType == ModuleRTPUtility::kIFrame) ?
kVideoFrameKey : kVideoFrameDelta;
RTPVideoHeaderVP8 *toHeader = &rtpHeader->type.Video.codecHeader.VP8;
ModuleRTPUtility::RTPPayloadVP8 *fromHeader = &parsedPacket.info.VP8;
rtpHeader->type.Video.isFirstPacket = fromHeader->beginningOfPartition
&& (fromHeader->partitionID == 0);
toHeader->nonReference = fromHeader->nonReferenceFrame;
toHeader->pictureId = fromHeader->hasPictureID ? fromHeader->pictureID :
kNoPictureId;
toHeader->tl0PicIdx = fromHeader->hasTl0PicIdx ? fromHeader->tl0PicIdx :
kNoTl0PicIdx;
if (fromHeader->hasTID) {
toHeader->temporalIdx = fromHeader->tID;
toHeader->layerSync = fromHeader->layerSync;
} else {
toHeader->temporalIdx = kNoTemporalIdx;
toHeader->layerSync = false;
}
toHeader->keyIdx = fromHeader->hasKeyIdx ? fromHeader->keyIdx : kNoKeyIdx;
toHeader->frameWidth = fromHeader->frameWidth;
toHeader->frameHeight = fromHeader->frameHeight;
toHeader->partitionId = fromHeader->partitionID;
toHeader->beginningOfPartition = fromHeader->beginningOfPartition;
if(CallbackOfReceivedPayloadData(parsedPacket.info.VP8.data,
parsedPacket.info.VP8.dataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
WebRtc_Word32 RTPReceiverVideo::ReceiveGenericCodec(
WebRtcRTPHeader* rtpHeader,
const WebRtc_UWord8* payloadData,
const WebRtc_UWord16 payloadDataLength) {
rtpHeader->frameType = kVideoFrameKey;
if(((SequenceNumber() + 1) == rtpHeader->header.sequenceNumber) &&
(TimeStamp() != rtpHeader->header.timestamp)) {
rtpHeader->type.Video.isFirstPacket = true;
}
_criticalSectionReceiverVideo->Leave();
if(CallbackOfReceivedPayloadData(payloadData, payloadDataLength,
rtpHeader) != 0) {
return -1;
}
return 0;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2019-5-28 15:35:36
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M;
vector<int> V[100010];
int parent[100010];
int start = -1;
int goal = -1;
bool dfs(int s)
{
for (auto x : V[s])
{
if (x != parent[s])
{
if (x == start)
{
return false;
}
else if (x == goal)
{
return true;
}
parent[x] = s;
if (!dfs(x))
{
return false;
}
}
}
return true;
}
int main()
{
cin >> N >> M;
for (auto i = 0; i < M; i++)
{
int a, b;
cin >> a >> b;
a--;
b--;
V[a].push_back(b);
V[b].push_back(a);
}
bool odd = false;
bool six = false;
int four = 0;
for (auto i = 0; i < N; i++)
{
int s = V[i].size();
if (s % 2 == 1)
{
odd = true;
break;
}
if (s >= 6)
{
six = true;
break;
}
if (s == 4)
{
four++;
}
}
if (odd)
{
cout << "No" << endl;
}
else if (six)
{
cout << "Yes" << endl;
}
else if (four >= 3)
{
cout << "Yes" << endl;
}
else if (four == 2)
{
assert(false);
for (auto i = 0; i < N; i++)
{
if ((int)V[i].size() == 4)
{
if (start == -1)
{
start = i;
}
else
{
goal = i;
break;
}
}
}
fill(parent, parent + N, -1);
if (!dfs(start))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
}
else
{
cout << "No" << endl;
}
}<commit_msg>submit C.cpp to 'C - Three Circuits' (agc032) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 2019-5-28 15:35:36
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int N, M;
vector<int> V[100010];
int parent[100010];
int start = -1;
int goal = -1;
bool dfs(int s)
{
for (auto x : V[s])
{
if (x != parent[s])
{
if (x == start)
{
return false;
}
else if (x == goal)
{
return true;
}
parent[x] = s;
if (!dfs(x))
{
return false;
}
}
}
return true;
}
int main()
{
cin >> N >> M;
for (auto i = 0; i < M; i++)
{
int a, b;
cin >> a >> b;
a--;
b--;
V[a].push_back(b);
V[b].push_back(a);
}
bool odd = false;
bool six = false;
int four = 0;
for (auto i = 0; i < N; i++)
{
int s = V[i].size();
if (s % 2 == 1)
{
odd = true;
}
if (s >= 6)
{
six = true;
}
if (s == 4)
{
four++;
}
}
if (odd)
{
cout << "No" << endl;
}
else if (six)
{
cout << "Yes" << endl;
}
else if (four >= 3)
{
cout << "Yes" << endl;
}
else if (four == 2)
{
for (auto i = 0; i < N; i++)
{
if ((int)V[i].size() == 4)
{
if (start == -1)
{
start = i;
}
else
{
goal = i;
break;
}
}
}
fill(parent, parent + N, -1);
if (!dfs(start))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
}
else
{
cout << "No" << endl;
}
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 5/16/2020, 6:32:30 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int M, K;
cin >> M >> K;
if (M == 0)
{
cout << "0 0" << endl;
}
else if (M == 1)
{
if (K == 0)
{
cout << "0 0 1 1" << endl;
}
else
{
cout << "-1" << endl;
}
}
else
{
vector<int> A;
for (auto i = 0; i < (1 << M); ++i)
{
if (i == K)
{
continue;
}
A.push_back(i);
}
auto B{A};
reverse(B.begin(), B.end());
vector<int> ans;
copy(A.begin(), A.end(), back_inserter(ans));
ans.push_back(K);
copy(B.begin(), B.end(), back_inserter(ans));
ans.push_back(K);
for (auto it = ans.begin(); it != ans.end(); ++it)
{
cout << *it;
if (it + 1 != ans.end())
{
cout << " ";
}
else
{
cout << endl;
}
}
}
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 5/16/2020, 6:32:30 PM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int M, K;
cin >> M >> K;
if (M == 0)
{
cout << "0 0" << endl;
}
else if (M == 1)
{
if (K == 0)
{
cout << "0 0 1 1" << endl;
}
else
{
cout << "-1" << endl;
}
}
else if (K >= (1 << M))
{
cout << "-1" << endl;
}
else
{
vector<int> A;
for (auto i = 0; i < (1 << M); ++i)
{
if (i == K)
{
continue;
}
A.push_back(i);
}
auto B{A};
reverse(B.begin(), B.end());
vector<int> ans;
copy(A.begin(), A.end(), back_inserter(ans));
ans.push_back(K);
copy(B.begin(), B.end(), back_inserter(ans));
ans.push_back(K);
for (auto it = ans.begin(); it != ans.end(); ++it)
{
cout << *it;
if (it + 1 != ans.end())
{
cout << " ";
}
else
{
cout << endl;
}
}
}
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
error,
};
class Go
{
public:
ban B;
int cnt[2];
Go() {}
Go(ban V) : B(V)
{
cnt[0] = cnt[1] = 0;
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = -1; a < 2; a++)
{
for (auto b = -1; b < 2; b++)
{
if (a == 0 && b == 0)
{
continue;
}
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + a * k;
int y = j + b * k;
if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::error;
}
bool black_turn = t;
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
}
else
{
return (black_turn ? state::black_even : state::white_even);
}
return state::error;
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
if (I_state == state::error)
{
No();
}
if (I_state == state::white_even || I_state == state::black_even)
{
Yes();
}
if (I_state == state::black_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
Go before = I;
if (before.B[i][j] == 'o')
{
before.B[i][j] = '.';
before.cnt[0]--;
if (before.st() == state::white_even)
{
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
Go before = I;
if (before.B[i][j] == 'x')
{
before.B[i][j] = '.';
before.cnt[1]--;
if (before.st() == state::black_even)
{
Yes();
}
}
}
}
No();
}
}<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
error,
};
class Go
{
public:
ban B;
int cnt[2];
Go() {}
Go(ban V) : B(V)
{
cnt[0] = cnt[1] = 0;
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = -1; a < 2; a++)
{
for (auto b = -1; b < 2; b++)
{
if (a == 0 && b == 0)
{
continue;
}
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + a * k;
int y = j + b * k;
if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::error;
}
bool black_turn = t;
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
}
else
{
return (black_turn ? state::black_even : state::white_even);
}
return state::error;
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
if (I_state == state::error)
{
No();
}
if (I_state == state::black_win || I_state == state::black_even)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
Go before = I;
if (before.B[i][j] == 'o')
{
before.B[i][j] = '.';
before.cnt[0]--;
if (before.st() == state::white_even)
{
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win || I_state == state::white_even)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
Go before = I;
if (before.B[i][j] == 'x')
{
before.B[i][j] = '.';
before.cnt[1]--;
if (before.st() == state::black_even)
{
Yes();
}
}
}
}
No();
}
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
count_error,
double_win_error,
error,
};
class Go
{
public:
ban B;
vector<int> cnt = vector<int>(2, 0);
Go() {}
Go(ban V) : B(V)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = 0; a < 8; a++)
{
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + dx[a] * k;
int y = j + dy[a] * k;
if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::count_error;
}
bool black_turn = (t == 1);
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::double_win_error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
else
{
return state::error;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
else
{
return state::error;
}
}
else
{
if (black_turn)
{
return state::black_even;
}
else
{
return state::white_even;
}
}
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
#if DEBUG == 1
cerr << I.cnt[0] << " VS " << I.cnt[1] << endl;
cerr << "I_state: " << (int)I_state << endl;
#endif
if (I_state == state::count_error)
{
No();
}
if (I_state == state::double_win_error)
{
assert(false);
No();
}
if (I_state == state::error)
{
No();
}
if (I_state == state::white_even || I_state == state::black_even)
{
Yes();
}
if (I_state == state::black_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::white_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
cerr << before.cnt[0] << " VS " << before.cnt[1] << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'x')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::black_even)
{
#if DEBUG == 1
cerr << "Prev Board: " << endl;
for (auto i = 0; i < C; i++)
{
cerr << before.B[i] << endl;
}
#endif
Yes();
}
}
}
}
No();
}
}<commit_msg>submit C.cpp to 'C - 五目並べチェッカー' (arc012) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : C.cpp
* Author : Kazune Takahashi
* Created : 6/18/2019, 2:02:05 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
cout << "YES" << endl;
exit(0);
}
void No()
{
cout << "NO" << endl;
exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint choose(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
typedef vector<string> ban;
const int C = 19;
enum class state
{
black_win,
white_win,
black_even,
white_even,
error,
};
class Go
{
public:
ban B;
vector<int> cnt = vector<int>(2, 0);
Go() {}
Go(ban V) : B(V)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
cnt[0]++;
}
else if (B[i][j] == 'x')
{
cnt[1]++;
}
}
}
}
bool win(char c)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
for (auto a = 0; a < 8; a++)
{
bool ok = true;
for (auto k = 0; k < 5; k++)
{
int x = i + dx[a] * k;
int y = j + dy[a] * k;
if (!(0 <= x && x < C && 0 <= y && y < C && B[x][y] == c))
{
ok = false;
break;
}
}
if (ok)
{
return true;
}
}
}
}
return false;
}
state st()
{
int t = cnt[0] - cnt[1];
if (!(t == 0 || t == 1))
{
return state::error;
}
bool black_turn = (t == 1);
bool black_win = win('o');
bool white_win = win('x');
if (black_win && white_win)
{
return state::error;
}
else if (black_win)
{
if (black_turn)
{
return state::black_win;
}
else
{
return state::error;
}
}
else if (white_win)
{
if (!black_turn)
{
return state::white_win;
}
else
{
return state::error;
}
}
else
{
if (black_turn)
{
return state::black_even;
}
else
{
return state::white_even;
}
}
}
};
int main()
{
// init();
ban B;
for (auto i = 0; i < C; i++)
{
string S;
cin >> S;
B.push_back(S);
}
Go I(B);
state I_state = I.st();
if (I_state == state::error)
{
No();
}
if (I_state == state::white_even || I_state == state::black_even)
{
Yes();
}
if (I_state == state::black_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'o')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::white_even)
{
Yes();
}
}
}
}
No();
}
if (I_state == state::white_win)
{
for (auto i = 0; i < C; i++)
{
for (auto j = 0; j < C; j++)
{
if (B[i][j] == 'x')
{
ban V = B;
V[i][j] = '.';
Go before(V);
if (before.st() == state::black_even)
{
Yes();
}
}
}
}
No();
}
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 7/28/2019, 1:18:49 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "-1" << endl;
exit(0);
}
class UnionFind
{
vector<long long> par;
public:
UnionFind() {}
UnionFind(int n) : par(n, -1) {}
bool is_same(int x, int y)
{
return root(x) == root(y);
}
bool merge(int x, int y)
{
x = root(x);
y = root(y);
if (x == y)
{
return false;
}
if (par[x] > par[y])
{
swap(x, y);
}
par[x] += par[y];
par[y] = x;
return true;
}
long long size(int x)
{
return -par[root(x)];
}
private:
int root(int x)
{
if (par[x] < 0)
{
return x;
}
return par[x] = root(par[x]);
}
};
int main()
{
string S, T, U;
int N = S.size();
cin >> S >> T;
U = S + S + S;
while (T.size() * 2 > U.size())
{
U += S;
}
S = U;
vector<bool> ok(N, false);
for (int i = 0; i < N; i++)
{
if (S.substr(i, N) == T)
{
ok[i] = true;
}
}
UnionFind uf{N};
for (auto i = 0; i < N; i++)
{
int j = (i + T.size()) % N;
if (ok[i] && ok[j])
{
if (!uf.merge(i, j))
{
No();
}
}
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
if (ok[i])
{
maxs(ans, uf.size(i));
}
}
cout << ans << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 7/28/2019, 1:18:49 AM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "-1" << endl;
exit(0);
}
class UnionFind
{
vector<long long> par;
public:
UnionFind() {}
UnionFind(int n) : par(n, -1) {}
bool is_same(int x, int y)
{
return root(x) == root(y);
}
bool merge(int x, int y)
{
x = root(x);
y = root(y);
if (x == y)
{
return false;
}
if (par[x] > par[y])
{
swap(x, y);
}
par[x] += par[y];
par[y] = x;
return true;
}
long long size(int x)
{
return -par[root(x)];
}
private:
int root(int x)
{
if (par[x] < 0)
{
return x;
}
return par[x] = root(par[x]);
}
};
int main()
{
string S, T, U;
int N = S.size();
cin >> S >> T;
U = S + S + S;
while (T.size() * 2 > U.size())
{
U += S;
}
S = U;
vector<bool> ok(N, false);
for (int i = 0; i < N; i++)
{
if (S.substr(i, N) == T)
{
ok[i] = true;
}
}
UnionFind uf{N};
for (auto i = 0; i < N; i++)
{
int j = (i + T.size()) % N;
if (ok[i] && ok[j])
{
if (!uf.is_same(i, j))
{
uf.merge(i, j);
}
else
{
No();
}
}
}
ll ans = 0;
for (auto i = 0; i < N; i++)
{
if (ok[i])
{
maxs(ans, uf.size(i));
}
}
cout << ans << endl;
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019/11/5 22:01:12
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 30000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
combination C;
mint catalan(ll x, ll y)
{
return C(x + y, y) - C(x + y, y - 1);
}
int main()
{
ll N, A, B;
cin >> N >> A >> B;
ll M{min({A, N - B, B - 1})};
mint ans{0};
for (auto i = 0; i < M; i++)
{
mint tmp{catalan(B - 1, i)};
if (i + B == N && A == i)
{
ans += tmp;
}
else
{
ll x{N - B - i - 1};
ll y{A - i + 1};
ans += tmp * C(x + y - 1, x);
}
}
cout << ans << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
* File : F.cpp
* Author : Kazune Takahashi
* Created : 2019/11/5 22:01:12
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
using ll = long long;
class mint
{
public:
static ll MOD;
ll x;
mint() : x(0) {}
mint(ll x) : x(x % MOD) {}
mint operator-() const { return x ? MOD - x : 0; }
mint &operator+=(const mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
mint &operator-=(const mint &a) { return *this += -a; }
mint &operator*=(const mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
mint &operator/=(const mint &a)
{
mint b{a};
return *this *= b.power(MOD - 2);
}
mint operator+(const mint &a) const { return mint(*this) += a; }
mint operator-(const mint &a) const { return mint(*this) -= a; }
mint operator*(const mint &a) const { return mint(*this) *= a; }
mint operator/(const mint &a) const { return mint(*this) /= a; }
bool operator<(const mint &a) const { return x < a.x; }
bool operator==(const mint &a) const { return x == a.x; }
const mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
mint half = power(N / 2);
return half * half;
}
}
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
vector<mint> inv, fact, factinv;
static int MAX_SIZE;
combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2; i < MAX_SIZE; i++)
{
inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1; i < MAX_SIZE; i++)
{
fact[i] = mint(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
mint operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
};
int combination::MAX_SIZE = 20000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
combination C;
mint catalan(ll x, ll y)
{
return C(x + y, y) - C(x + y, y - 1);
}
int main()
{
ll N, A, B;
cin >> N >> A >> B;
ll M{min({A, N - B, B - 1})};
mint ans{0};
for (auto i = 0; i < M; i++)
{
mint tmp{catalan(B - 1, i)};
if (i + B == N && A == i)
{
ans += tmp;
}
else
{
ll x{N - B - i - 1};
ll y{A - i + 1};
ans += tmp * C(x + y - 1, x);
}
}
cout << ans << endl;
}<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 6/7/2020, 1:08:56 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, M;
ll L;
cin >> N >> M >> L;
vector<vector<ll>> T(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < M; ++i)
{
int A, B;
ll C;
cin >> A >> B >> C;
--A;
--B;
T[A][B] = C;
T[B][A] = C;
}
for (auto i{0}; i < N; ++i)
{
T[i][i] = 0;
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (T[i][k] == INT64_MAX || T[k][j] == INT64_MAX)
{
continue;
}
ch_min(T[i][j], T[i][k] + T[k][j]);
}
}
}
vector<vector<ll>> H(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
H[i][j] = (T[i][j] <= L ? 1 : INT64_MAX);
}
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (H[i][k] == INT64_MAX || H[k][j] == INT64_MAX)
{
continue;
}
ch_min(H[i][j], H[i][k] + H[k][j]);
}
}
}
int Q;
cin >> Q;
for (auto q{0}; q < Q; ++q)
{
int s, t;
cin >> s >> t;
--s;
--t;
ll ans{H[s][t]};
cout << (ans == INT64_MAX ? -1 : ans) << endl;
}
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 6/7/2020, 1:08:56 AM
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(Mint const &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(Mint const &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(Mint const &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(Mint const &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(Mint const &a) const { return Mint(*this) += a; }
Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
bool operator<(Mint const &a) const { return x < a.x; }
bool operator<=(Mint const &a) const { return x <= a.x; }
bool operator>(Mint const &a) const { return x > a.x; }
bool operator>=(Mint const &a) const { return x >= a.x; }
bool operator==(Mint const &a) const { return x == a.x; }
bool operator!=(Mint const &a) const { return !(*this == a); }
Mint power(ll N) const
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i{2LL}; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i{1LL}; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, M;
ll L;
cin >> N >> M >> L;
vector<vector<ll>> T(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < M; ++i)
{
int A, B;
ll C;
cin >> A >> B >> C;
--A;
--B;
T[A][B] = C;
T[B][A] = C;
}
for (auto i{0}; i < N; ++i)
{
T[i][i] = 0;
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (T[i][k] == INT64_MAX || T[k][j] == INT64_MAX)
{
continue;
}
ch_min(T[i][j], T[i][k] + T[k][j]);
}
}
}
vector<vector<ll>> H(N, vector<ll>(N, INT64_MAX));
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
H[i][j] = (T[i][j] <= L ? 1 : INT64_MAX);
}
}
for (auto k{0}; k < N; ++k)
{
for (auto i{0}; i < N; ++i)
{
for (auto j{0}; j < N; ++j)
{
if (H[i][k] == INT64_MAX || H[k][j] == INT64_MAX)
{
continue;
}
ch_min(H[i][j], H[i][k] + H[k][j]);
}
}
}
int Q;
cin >> Q;
for (auto q{0}; q < Q; ++q)
{
int s, t;
cin >> s >> t;
--s;
--t;
ll ans{H[s][t]};
cout << (ans == INT64_MAX ? -1 : ans + 1) << endl;
}
}
<|endoftext|>
|
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2020/3/7 21:44:32
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, P;
cin >> N >> P;
string S;
if (P == 2 || P == 5)
{
int ans{0};
for (auto i = 0; i < N; ++i)
{
if ((S[i] - '0') % P == 0)
{
ans += i + 1;
}
}
cout << ans << endl;
return 0;
}
reverse(S.begin(), S.end());
vector<int> X(N);
int pw{1};
int now{0};
for (auto i = 0; i < N; ++i)
{
int c{S[i] - '0'};
now += (c * pw) % P;
now %= P;
X[i] = now;
pw *= 10;
pw %= P;
}
vector<int> R(P, 0);
R[0] = 1;
int ans{0};
for (auto i = 0; i < N; ++i)
{
ans += R[X[i]];
R[X[i]]++;
}
cout << ans << endl;
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2020/3/7 21:44:32
* Powered by Visual Studio Code
*/
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
if (left < right)
{
left = right;
}
}
template <typename T>
void ch_min(T &left, T right)
{
if (left > right)
{
left = right;
}
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
ll x;
Mint() : x{0LL} {}
Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
Mint operator-() const { return x ? MOD - x : 0; }
Mint &operator+=(const Mint &a)
{
if ((x += a.x) >= MOD)
{
x -= MOD;
}
return *this;
}
Mint &operator-=(const Mint &a) { return *this += -a; }
Mint &operator++() { return *this += 1; }
Mint &operator++(int)
{
Mint tmp{*this};
++*this;
return tmp;
}
Mint &operator--() { return *this -= 1; }
Mint &operator--(int)
{
Mint tmp{*this};
--*this;
return tmp;
}
Mint &operator*=(const Mint &a)
{
(x *= a.x) %= MOD;
return *this;
}
Mint &operator/=(const Mint &a)
{
Mint b{a};
return *this *= b.power(MOD - 2);
}
Mint operator+(const Mint &a) const { return Mint(*this) += a; }
Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
bool operator<(const Mint &a) const { return x < a.x; }
bool operator<=(const Mint &a) const { return x <= a.x; }
bool operator>(const Mint &a) const { return x > a.x; }
bool operator>=(const Mint &a) const { return x >= a.x; }
bool operator==(const Mint &a) const { return x == a.x; }
bool operator!=(const Mint &a) const { return !(*this == a); }
const Mint power(ll N)
{
if (N == 0)
{
return 1;
}
else if (N % 2 == 1)
{
return *this * power(N - 1);
}
else
{
Mint half = power(N / 2);
return half * half;
}
}
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
vector<Mint<MOD>> inv, fact, factinv;
Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
{
inv[1] = 1;
for (auto i = 2LL; i < MAX_SIZE; i++)
{
inv[i] = (-inv[MOD % i]) * (MOD / i);
}
fact[0] = factinv[0] = 1;
for (auto i = 1LL; i < MAX_SIZE; i++)
{
fact[i] = Mint<MOD>(i) * fact[i - 1];
factinv[i] = inv[i] * factinv[i - 1];
}
}
Mint<MOD> operator()(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return fact[n] * factinv[k] * factinv[n - k];
}
return 0;
}
Mint<MOD> catalan(int x, int y)
{
return (*this)(x + y, y) - (*this)(x + y, y - 1);
}
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
int ans{0};
while (x != 0)
{
ans += x & 1;
x >>= 1;
}
return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
// ----- main() -----
int main()
{
int N, P;
cin >> N >> P;
string S;
if (P == 2 || P == 5)
{
int ans{0};
for (auto i = 0; i < N; ++i)
{
if ((S[i] - '0') % P == 0)
{
ans += i + 1;
}
}
cout << ans << endl;
return 0;
}
reverse(S.begin(), S.end());
vector<int> X(N);
int pw{1};
int now{0};
for (auto i = 0; i < N; ++i)
{
int c{S[i] - '0'};
now += (c * pw) % P;
now %= P;
X[i] = now;
#if DEBUG == 1
cerr << "X[" << i << "] = " << X[i] << endl;
#endif
pw *= 10;
pw %= P;
}
vector<int> R(P, 0);
R[0] = 1;
int ans{0};
for (auto i = 0; i < N; ++i)
{
ans += R[X[i]];
R[X[i]]++;
}
cout << ans << endl;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ChartPlotAreaOOoTContext.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-11-09 18:29:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ChartPlotAreaOOoTContext.hxx"
#ifndef _XMLOFF_TRANSFORMER_BASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOOO_HXX
#include "ActionMapTypesOOo.hxx"
#endif
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
TYPEINIT1( XMLChartPlotAreaOOoTContext, XMLProcAttrTransformerContext )
XMLChartPlotAreaOOoTContext::XMLChartPlotAreaOOoTContext(
XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName ) :
XMLProcAttrTransformerContext( rTransformer, rQName, OOO_SHAPE_ACTIONS )
{
}
XMLChartPlotAreaOOoTContext::~XMLChartPlotAreaOOoTContext()
{}
XMLTransformerContext * XMLChartPlotAreaOOoTContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext *pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
::xmloff::token::IsXMLToken( rLocalName, ::xmloff::token::XML_AXIS ) )
{
pContext = new XMLPersElemContentTContext(
GetTransformer(), rQName );
AddContent( pContext );
}
else if( XML_NAMESPACE_CHART == nPrefix &&
::xmloff::token::IsXMLToken( rLocalName, ::xmloff::token::XML_CATEGORIES ) )
{
pContext = new XMLPersAttrListTContext( GetTransformer(), rQName );
// put categories at correct axis
XMLTransformerContextVector::iterator aIter = m_aChildContexts.begin();
bool bFound =false;
// iterate over axis elements
for( ; ! bFound && aIter != m_aChildContexts.end(); ++aIter )
{
XMLPersElemContentTContext* pPersContext =
PTR_CAST( XMLPersElemContentTContext, (*aIter).get() );
if( pPersContext != 0 )
{
// iterate over attributes to find category axis
Reference< xml::sax::XAttributeList > xNewAttrList( pPersContext->GetAttrList());
sal_Int16 nAttrCount = xNewAttrList.is() ? xNewAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString & rAttrName = xNewAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nNewPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
if( nNewPrefix == XML_NAMESPACE_CHART &&
::xmloff::token::IsXMLToken( aLocalName, ::xmloff::token::XML_CLASS ) &&
::xmloff::token::IsXMLToken( xNewAttrList->getValueByIndex( i ), ::xmloff::token::XML_CATEGORY ))
{
// category axis found
pPersContext->AddContent( pContext );
bFound = true;
break;
}
}
}
}
OSL_ENSURE( bFound, "No suitable axis for categories found." );
}
else
{
ExportContent();
pContext = XMLProcAttrTransformerContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
void XMLChartPlotAreaOOoTContext::EndElement()
{
ExportContent();
XMLProcAttrTransformerContext::EndElement();
}
void XMLChartPlotAreaOOoTContext::AddContent( XMLTransformerContext *pContext )
{
OSL_ENSURE( pContext && pContext->IsPersistent(),
"non-persistent context" );
XMLTransformerContextVector::value_type aVal( pContext );
m_aChildContexts.push_back( aVal );
}
void XMLChartPlotAreaOOoTContext::ExportContent()
{
XMLTransformerContextVector::iterator aIter = m_aChildContexts.begin();
for( ; aIter != m_aChildContexts.end(); ++aIter )
{
(*aIter)->Export();
}
m_aChildContexts.clear();
}
<commit_msg>INTEGRATION: CWS schoasis02 (1.2.92); FILE MERGED 2004/11/04 17:19:29 bm 1.2.92.1: #i36581# axis: class->dimension<commit_after>/*************************************************************************
*
* $RCSfile: ChartPlotAreaOOoTContext.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2004-11-15 12:49:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ChartPlotAreaOOoTContext.hxx"
#ifndef _XMLOFF_TRANSFORMER_BASE_HXX
#include "TransformerBase.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_DEEPTCONTEXT_HXX
#include "DeepTContext.hxx"
#endif
#ifndef _XMLOFF_ACTIONMAPTYPESOOO_HXX
#include "ActionMapTypesOOo.hxx"
#endif
#ifndef _XMLOFF_MUTABLEATTRLIST_HXX
#include "MutableAttrList.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using ::com::sun::star::uno::Reference;
using ::rtl::OUString;
class XMLAxisOOoContext : public XMLPersElemContentTContext
{
public:
TYPEINFO();
XMLAxisOOoContext( XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName );
~XMLAxisOOoContext();
virtual void StartElement( const Reference< xml::sax::XAttributeList >& rAttrList );
bool IsCategoryAxis() const;
private:
bool m_bIsCategoryAxis;
};
TYPEINIT1( XMLAxisOOoContext, XMLPersElemContentTContext );
XMLAxisOOoContext::XMLAxisOOoContext(
XMLTransformerBase& rTransformer,
const ::rtl::OUString& rQName ) :
XMLPersElemContentTContext( rTransformer, rQName ),
m_bIsCategoryAxis( false )
{}
XMLAxisOOoContext::~XMLAxisOOoContext()
{}
void XMLAxisOOoContext::StartElement(
const Reference< xml::sax::XAttributeList >& rAttrList )
{
OUString aLocation, aMacroName;
Reference< xml::sax::XAttributeList > xAttrList( rAttrList );
XMLMutableAttributeList *pMutableAttrList = 0;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
if( nPrefix == XML_NAMESPACE_CHART &&
IsXMLToken( aLocalName, XML_CLASS ) )
{
if( !pMutableAttrList )
{
pMutableAttrList = new XMLMutableAttributeList( xAttrList );
xAttrList = pMutableAttrList;
}
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
XMLTokenEnum eToken = XML_TOKEN_INVALID;
if( IsXMLToken( rAttrValue, XML_DOMAIN ) ||
IsXMLToken( rAttrValue, XML_CATEGORY ))
{
eToken = XML_X;
if( IsXMLToken( rAttrValue, XML_CATEGORY ) )
m_bIsCategoryAxis = true;
}
else if( IsXMLToken( rAttrValue, XML_VALUE ))
{
eToken = XML_Y;
}
else if( IsXMLToken( rAttrValue, XML_SERIES ))
{
eToken = XML_Z;
}
else
{
OSL_ENSURE( false, "ChartAxis: Invalid attribute value" );
}
if( eToken != XML_TOKEN_INVALID )
{
OUString aNewAttrQName(
GetTransformer().GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_CHART, GetXMLToken( XML_DIMENSION )));
pMutableAttrList->RenameAttributeByIndex( i, aNewAttrQName );
pMutableAttrList->SetValueByIndex( i, GetXMLToken( eToken ));
}
}
}
XMLPersElemContentTContext::StartElement( xAttrList );
}
bool XMLAxisOOoContext::IsCategoryAxis() const
{
return m_bIsCategoryAxis;
}
TYPEINIT1( XMLChartPlotAreaOOoTContext, XMLProcAttrTransformerContext )
XMLChartPlotAreaOOoTContext::XMLChartPlotAreaOOoTContext(
XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName ) :
XMLProcAttrTransformerContext( rTransformer, rQName, OOO_SHAPE_ACTIONS )
{
}
XMLChartPlotAreaOOoTContext::~XMLChartPlotAreaOOoTContext()
{}
XMLTransformerContext * XMLChartPlotAreaOOoTContext::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const ::rtl::OUString& rQName,
const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
XMLTransformerContext *pContext = 0;
if( XML_NAMESPACE_CHART == nPrefix &&
IsXMLToken( rLocalName, XML_AXIS ) )
{
XMLAxisOOoContext * pAxisContext( new XMLAxisOOoContext( GetTransformer(), rQName ));
AddContent( pAxisContext );
pContext = pAxisContext;
}
else if( XML_NAMESPACE_CHART == nPrefix &&
IsXMLToken( rLocalName, XML_CATEGORIES ) )
{
pContext = new XMLPersAttrListTContext( GetTransformer(), rQName );
// put categories at correct axis
XMLAxisContextVector::iterator aIter = m_aChildContexts.begin();
bool bFound =false;
// iterate over axis elements
for( ; ! bFound && aIter != m_aChildContexts.end(); ++aIter )
{
XMLAxisOOoContext * pAxisContext = (*aIter).get();
if( pAxisContext != 0 )
{
// iterate over attributes to find category axis
Reference< xml::sax::XAttributeList > xNewAttrList( pAxisContext->GetAttrList());
sal_Int16 nAttrCount = xNewAttrList.is() ? xNewAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
const OUString & rAttrName = xNewAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nNewPrefix =
GetTransformer().GetNamespaceMap().GetKeyByAttrName( rAttrName,
&aLocalName );
if( nNewPrefix == XML_NAMESPACE_CHART &&
pAxisContext->IsCategoryAxis() &&
IsXMLToken( aLocalName, XML_DIMENSION ) )
{
// category axis found
pAxisContext->AddContent( pContext );
bFound = true;
break;
}
}
}
}
OSL_ENSURE( bFound, "No suitable axis for categories found." );
}
else
{
ExportContent();
pContext = XMLProcAttrTransformerContext::CreateChildContext(
nPrefix, rLocalName, rQName, xAttrList );
}
return pContext;
}
void XMLChartPlotAreaOOoTContext::EndElement()
{
ExportContent();
XMLProcAttrTransformerContext::EndElement();
}
void XMLChartPlotAreaOOoTContext::AddContent( XMLAxisOOoContext *pContext )
{
OSL_ENSURE( pContext && pContext->IsPersistent(),
"non-persistent context" );
XMLAxisContextVector::value_type aVal( pContext );
m_aChildContexts.push_back( aVal );
}
void XMLChartPlotAreaOOoTContext::ExportContent()
{
XMLAxisContextVector::iterator aIter = m_aChildContexts.begin();
for( ; aIter != m_aChildContexts.end(); ++aIter )
{
(*aIter)->Export();
}
m_aChildContexts.clear();
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2015, Itseez Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef OPENCV_CORE_FAST_MATH_HPP
#define OPENCV_CORE_FAST_MATH_HPP
#include "opencv2/core/cvdef.h"
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
#include <emmintrin.h>
#endif
//! @addtogroup core_utils
//! @{
/****************************************************************************************\
* fast math *
\****************************************************************************************/
#ifdef __cplusplus
# include <cmath>
#else
# ifdef __BORLANDC__
# include <fastmath.h>
# else
# include <math.h>
# endif
#endif
#ifdef HAVE_TEGRA_OPTIMIZATION
# include "tegra_round.hpp"
#endif
#if defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON__) && !defined __SOFTFP__ && !defined(__CUDACC__)
// 1. general scheme
#define ARM_ROUND(_value, _asm_string) \
int res; \
float temp; \
CV_UNUSED(temp); \
__asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \
return res
// 2. version for double
#ifdef __clang__
#define ARM_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]")
#else
#define ARM_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]")
#endif
// 3. version for float
#define ARM_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]")
#endif
#if defined __PPC64__ && !defined OPENCV_USE_FASTMATH_GCC_BUILTINS
/* Let GCC inline C math functions when available. Dedicated hardware is available to
round and covert FP values. */
#define OPENCV_USE_FASTMATH_GCC_BUILTINS
#endif
/* Enable GCC builtin math functions if possible, desired, and available.
Note, not all math functions inline equally. E.g lrint will not inline
without the -fno-math-errno option. */
#if defined OPENCV_USE_FASTMATH_GCC_BUILTINS && defined __GNUC__ && !defined __clang__ && !defined (__CUDACC__)
#define _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
#endif
/** @brief Rounds floating-point number to the nearest integer
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int
cvRound( double value )
{
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__) || CV_SSE2) && !defined(__CUDACC__)
__m128d t = _mm_set_sd( value );
return _mm_cvtsd_si32(t);
#elif defined _MSC_VER && defined _M_IX86
int t;
__asm
{
fld value;
fistp t;
}
return t;
#elif ((defined _MSC_VER && defined _M_ARM) || defined CV_ICC || \
defined __GNUC__) && defined HAVE_TEGRA_OPTIMIZATION
TEGRA_ROUND_DBL(value);
#elif defined CV_ICC || defined __GNUC__
# if defined ARM_ROUND_DBL
ARM_ROUND_DBL(value);
# else
return (int)lrint(value);
# endif
#else
/* it's ok if round does not comply with IEEE754 standard;
the tests should allow +/-1 difference when the tested functions use round */
return (int)(value + (value >= 0 ? 0.5 : -0.5));
#endif
}
/** @brief Rounds floating-point number to the nearest integer not larger than the original.
The function computes an integer i such that:
\f[i \le \texttt{value} < i+1\f]
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int cvFloor( double value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_floor(value);
#else
int i = (int)value;
return i - (i > value);
#endif
}
/** @brief Rounds floating-point number to the nearest integer not smaller than the original.
The function computes an integer i such that:
\f[i \le \texttt{value} < i+1\f]
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int cvCeil( double value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_ceil(value);
#else
int i = (int)value;
return i + (i < value);
#endif
}
/** @brief Determines if the argument is Not A Number.
@param value The input floating-point value
The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0
otherwise. */
CV_INLINE int cvIsNaN( double value )
{
Cv64suf ieee754;
ieee754.f = value;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
((unsigned)ieee754.u != 0) > 0x7ff00000;
}
/** @brief Determines if the argument is Infinity.
@param value The input floating-point value
The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard)
and 0 otherwise. */
CV_INLINE int cvIsInf( double value )
{
Cv64suf ieee754;
ieee754.f = value;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
(unsigned)ieee754.u == 0;
}
#ifdef __cplusplus
/** @overload */
CV_INLINE int cvRound(float value)
{
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__) || CV_SSE2) && !defined(__CUDACC__)
__m128 t = _mm_set_ss( value );
return _mm_cvtss_si32(t);
#elif defined _MSC_VER && defined _M_IX86
int t;
__asm
{
fld value;
fistp t;
}
return t;
#elif ((defined _MSC_VER && defined _M_ARM) || defined CV_ICC || \
defined __GNUC__) && defined HAVE_TEGRA_OPTIMIZATION
TEGRA_ROUND_FLT(value);
#elif defined CV_ICC || defined __GNUC__
# if defined ARM_ROUND_FLT
ARM_ROUND_FLT(value);
# else
return (int)lrintf(value);
# endif
#else
/* it's ok if round does not comply with IEEE754 standard;
the tests should allow +/-1 difference when the tested functions use round */
return (int)(value + (value >= 0 ? 0.5f : -0.5f));
#endif
}
/** @overload */
CV_INLINE int cvRound( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvFloor( float value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_floorf(value);
#else
int i = (int)value;
return i - (i > value);
#endif
}
/** @overload */
CV_INLINE int cvFloor( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvCeil( float value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_ceilf(value);
#else
int i = (int)value;
return i + (i < value);
#endif
}
/** @overload */
CV_INLINE int cvCeil( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvIsNaN( float value )
{
Cv32suf ieee754;
ieee754.f = value;
return (ieee754.u & 0x7fffffff) > 0x7f800000;
}
/** @overload */
CV_INLINE int cvIsInf( float value )
{
Cv32suf ieee754;
ieee754.f = value;
return (ieee754.u & 0x7fffffff) == 0x7f800000;
}
#endif // __cplusplus
//! @} core_utils
#endif
<commit_msg>fast_math: implement optimized PPC routines<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2015, Itseez Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef OPENCV_CORE_FAST_MATH_HPP
#define OPENCV_CORE_FAST_MATH_HPP
#include "opencv2/core/cvdef.h"
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
#include <emmintrin.h>
#endif
//! @addtogroup core_utils
//! @{
/****************************************************************************************\
* fast math *
\****************************************************************************************/
#ifdef __cplusplus
# include <cmath>
#else
# ifdef __BORLANDC__
# include <fastmath.h>
# else
# include <math.h>
# endif
#endif
#ifdef HAVE_TEGRA_OPTIMIZATION
# include "tegra_round.hpp"
#endif
#if defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 && !defined (__CUDACC__)
# include <altivec.h>
#endif
#if ((defined _MSC_VER && defined _M_ARM) || defined CV_ICC || \
defined __GNUC__) && defined HAVE_TEGRA_OPTIMIZATION
#define CV_INLINE_ROUND_DBL(value) TEGRA_ROUND_DBL(value);
#define CV_INLINE_ROUND_FLT(value) TEGRA_ROUND_FLT(value);
#elif defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON__) && !defined __SOFTFP__ && !defined(__CUDACC__)
// 1. general scheme
#define ARM_ROUND(_value, _asm_string) \
int res; \
float temp; \
CV_UNUSED(temp); \
__asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \
return res
// 2. version for double
#ifdef __clang__
#define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]")
#else
#define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]")
#endif
// 3. version for float
#define CV_INLINE_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]")
#elif defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 && !defined (__CUDACC__)
// P8 and newer machines can convert fp32/64 to int quickly.
#define CV_INLINE_ROUND_DBL(value) \
int out; \
double temp; \
__asm__( "fctiw %[temp],%[in]\n\tmffprwz %[out],%[temp]\n\t" : [out] "=r" (out), [temp] "=d" (temp) : [in] "d" ((double)(value)) : ); \
return out;
// FP32 also works with FP64 routine above
#define CV_INLINE_ROUND_FLT(value) CV_INLINE_ROUND_DBL(value)
#ifdef _ARCH_PWR9
#define CV_INLINE_ISINF_DBL(value) return scalar_test_data_class(value, 0x30);
#define CV_INLINE_ISNAN_DBL(value) return scalar_test_data_class(value, 0x40);
#define CV_INLINE_ISINF_FLT(value) CV_INLINE_ISINF_DBL(value)
#define CV_INLINE_ISNAN_FLT(value) CV_INLINE_ISNAN_DBL(value)
#endif
#elif defined CV_ICC || defined __GNUC__
#define CV_INLINE_ROUND_DBL(value) return (int)(lrint(value));
#define CV_INLINE_ROUND_FLT(value) return (int)(lrintf(value));
#endif
#if defined __PPC64__ && !defined OPENCV_USE_FASTMATH_GCC_BUILTINS
/* Let GCC inline C math functions when available. Dedicated hardware is available to
round and covert FP values. */
#define OPENCV_USE_FASTMATH_GCC_BUILTINS
#endif
/* Enable GCC builtin math functions if possible, desired, and available.
Note, not all math functions inline equally. E.g lrint will not inline
without the -fno-math-errno option. */
#if defined OPENCV_USE_FASTMATH_GCC_BUILTINS && defined __GNUC__ && !defined __clang__ && !defined (__CUDACC__)
#define _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
#endif
/* Allow overrides for some functions which may benefit from tuning. Likewise,
note that isinf is not used as the return value is signed. */
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS && !defined CV_INLINE_ISNAN_DBL
#define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value);
#endif
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS && !defined CV_INLINE_ISNAN_FLT
#define CV_INLINE_ISNAN_FLT(value) return __builtin_isnanf(value);
#endif
/** @brief Rounds floating-point number to the nearest integer
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int
cvRound( double value )
{
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__) || CV_SSE2) && !defined(__CUDACC__)
__m128d t = _mm_set_sd( value );
return _mm_cvtsd_si32(t);
#elif defined _MSC_VER && defined _M_IX86
int t;
__asm
{
fld value;
fistp t;
}
return t;
#elif defined CV_INLINE_ROUND_DBL
CV_INLINE_ROUND_DBL(value);
#else
/* it's ok if round does not comply with IEEE754 standard;
the tests should allow +/-1 difference when the tested functions use round */
return (int)(value + (value >= 0 ? 0.5 : -0.5));
#endif
}
/** @brief Rounds floating-point number to the nearest integer not larger than the original.
The function computes an integer i such that:
\f[i \le \texttt{value} < i+1\f]
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int cvFloor( double value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_floor(value);
#else
int i = (int)value;
return i - (i > value);
#endif
}
/** @brief Rounds floating-point number to the nearest integer not smaller than the original.
The function computes an integer i such that:
\f[i \le \texttt{value} < i+1\f]
@param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the
result is not defined.
*/
CV_INLINE int cvCeil( double value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_ceil(value);
#else
int i = (int)value;
return i + (i < value);
#endif
}
/** @brief Determines if the argument is Not A Number.
@param value The input floating-point value
The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0
otherwise. */
CV_INLINE int cvIsNaN( double value )
{
#if defined CV_INLINE_ISNAN_DBL
CV_INLINE_ISNAN_DBL(value);
#else
Cv64suf ieee754;
ieee754.f = value;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
((unsigned)ieee754.u != 0) > 0x7ff00000;
#endif
}
/** @brief Determines if the argument is Infinity.
@param value The input floating-point value
The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard)
and 0 otherwise. */
CV_INLINE int cvIsInf( double value )
{
#if defined CV_INLINE_ISINF_DBL
CV_INLINE_ISINF_DBL(value);
#else
Cv64suf ieee754;
ieee754.f = value;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
(unsigned)ieee754.u == 0;
#endif
}
#ifdef __cplusplus
/** @overload */
CV_INLINE int cvRound(float value)
{
#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ \
&& defined __SSE2__ && !defined __APPLE__) || CV_SSE2) && !defined(__CUDACC__)
__m128 t = _mm_set_ss( value );
return _mm_cvtss_si32(t);
#elif defined _MSC_VER && defined _M_IX86
int t;
__asm
{
fld value;
fistp t;
}
return t;
#elif defined CV_INLINE_ROUND_FLT
CV_INLINE_ROUND_FLT(value);
#else
/* it's ok if round does not comply with IEEE754 standard;
the tests should allow +/-1 difference when the tested functions use round */
return (int)(value + (value >= 0 ? 0.5f : -0.5f));
#endif
}
/** @overload */
CV_INLINE int cvRound( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvFloor( float value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_floorf(value);
#else
int i = (int)value;
return i - (i > value);
#endif
}
/** @overload */
CV_INLINE int cvFloor( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvCeil( float value )
{
#if defined _OPENCV_FASTMATH_ENABLE_GCC_MATH_BUILTINS
return __builtin_ceilf(value);
#else
int i = (int)value;
return i + (i < value);
#endif
}
/** @overload */
CV_INLINE int cvCeil( int value )
{
return value;
}
/** @overload */
CV_INLINE int cvIsNaN( float value )
{
#if defined CV_INLINE_ISNAN_FLT
CV_INLINE_ISNAN_FLT(value);
#else
Cv32suf ieee754;
ieee754.f = value;
return (ieee754.u & 0x7fffffff) > 0x7f800000;
#endif
}
/** @overload */
CV_INLINE int cvIsInf( float value )
{
#if defined CV_INLINE_ISINF_FLT
CV_INLINE_ISINF_FLT(value);
#else
Cv32suf ieee754;
ieee754.f = value;
return (ieee754.u & 0x7fffffff) == 0x7f800000;
#endif
}
#endif // __cplusplus
//! @} core_utils
#endif
<|endoftext|>
|
<commit_before>/***********************************************************************
created: 21/7/2015
author: Yaron Cohen-Tal
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2015 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 "CEGUI/RendererModules/OpenGL/GL.h"
#include "CEGUI/String.h"
#include "CEGUI/Exceptions.h"
#include <list>
#include <iostream>
#if defined CEGUI_USE_GLEW
#include <sstream>
#include <cstring>
#endif
namespace CEGUI
{
OpenGLInfo OpenGLInfo::s_instance;
//----------------------------------------------------------------------------//
OpenGLInfo::OpenGLInfo() :
d_type(TYPE_NONE),
d_verMajor(-1),
d_verMinor(-1),
d_verMajorForce(-1),
d_verMinorForce(-1),
d_isS3tcSupported(false),
d_isNpotTextureSupported(false),
d_isReadBufferSupported(false),
d_isPolygonModeSupported(false),
d_isSeperateReadAndDrawFramebufferSupported(false),
d_areVaosSupported(false)
{
}
//----------------------------------------------------------------------------//
void OpenGLInfo::init()
{
initTypeAndVer();
initSupportedFeatures();
}
void OpenGLInfo::verForce(GLint verMajor_, GLint verMinor_)
{
d_verMajorForce = verMajor_;
d_verMinorForce = verMinor_;
}
//----------------------------------------------------------------------------//
void OpenGLInfo::initTypeAndVer()
{
#if defined CEGUI_USE_EPOXY
d_type = epoxy_is_desktop_gl() ? TYPE_DESKTOP : TYPE_ES;
if (d_verMajorForce >= 0)
{
d_verMajor = d_verMajorForce;
d_verMinor = d_verMinorForce;
}
else
{
int ver(epoxy_gl_version());
if (!ver)
{
if (isUsingDesktopOpengl())
CEGUI_THROW(RendererException
("Failed to obtain desktop OpenGL version."));
else
CEGUI_THROW(RendererException
("Failed to obtain OpenGL ES version."));
}
d_verMajor = ver / 10;
d_verMinor = ver % 10;
}
#elif defined CEGUI_USE_GLEW
d_type = TYPE_DESKTOP;
glGetError ();
d_verMajor = d_verMinor = -1;
#endif
}
//----------------------------------------------------------------------------//
void OpenGLInfo::initSupportedFeatures()
{
#if defined CEGUI_USE_EPOXY
d_isS3tcSupported = epoxy_has_gl_extension("GL_EXT_texture_compression_s3tc");
d_isNpotTextureSupported =
(isUsingDesktopOpengl() && verMajor() >= 2)
|| (isUsingOpenglEs() && verMajor() >= 3)
|| epoxy_has_gl_extension("GL_ARB_texture_non_power_of_two");
d_isReadBufferSupported =
(isUsingDesktopOpengl() && verAtLeast(1, 3))
|| (isUsingOpenglEs() && verMajor() >= 3);
d_isPolygonModeSupported = isUsingDesktopOpengl() && verAtLeast(1, 3);
d_isSeperateReadAndDrawFramebufferSupported =
(isUsingDesktopOpengl() && verAtLeast(3, 1))
|| (isUsingOpenglEs() && verMajor() >= 3);
d_areVaosSupported = (isUsingDesktopOpengl() && verAtLeast(3, 2))
|| (isUsingOpenglEs() && verMajor() >= 3);
#elif defined CEGUI_USE_GLEW
d_isS3tcSupported = false;
// Why do we do this and not use GLEW_EXT_texture_compression_s3tc?
// Because of glewExperimental, of course!
int ext_count;
glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count);
for(int i = 0; i < ext_count; ++i)
{
if (!std::strcmp(
reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)),
"GL_EXT_texture_compression_s3tc"))
{
d_isS3tcSupported = true;
break;
}
}
d_isNpotTextureSupported =
(GLEW_VERSION_2_0 == GL_TRUE)
|| (GLEW_ARB_texture_non_power_of_two == GL_TRUE);
d_isPolygonModeSupported
= (GLEW_VERSION_1_3 == GL_TRUE);
d_isSeperateReadAndDrawFramebufferSupported = (GLEW_VERSION_3_1 == GL_TRUE);
d_areVaosSupported = (GLEW_VERSION_3_2 == GL_TRUE);
#endif
}
} // namespace CEGUI
<commit_msg>MOD: Outstanding rename changes in OpenGL info<commit_after>/***********************************************************************
created: 21/7/2015
author: Yaron Cohen-Tal
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2015 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 "CEGUI/RendererModules/OpenGL/GL.h"
#include "CEGUI/String.h"
#include "CEGUI/Exceptions.h"
#include <list>
#include <iostream>
#if defined CEGUI_USE_GLEW
#include <sstream>
#include <cstring>
#endif
namespace CEGUI
{
OpenGLInfo OpenGLInfo::s_instance;
//----------------------------------------------------------------------------//
OpenGLInfo::OpenGLInfo() :
d_type(TYPE_NONE),
d_verMajor(-1),
d_verMinor(-1),
d_verMajorForce(-1),
d_verMinorForce(-1),
d_isS3tcSupported(false),
d_isNpotTextureSupported(false),
d_isReadBufferSupported(false),
d_isPolygonModeSupported(false),
d_isSeperateReadAndDrawFramebufferSupported(false),
d_isVaoSupported(false)
{
}
//----------------------------------------------------------------------------//
void OpenGLInfo::init()
{
initTypeAndVer();
initSupportedFeatures();
}
void OpenGLInfo::verForce(GLint verMajor_, GLint verMinor_)
{
d_verMajorForce = verMajor_;
d_verMinorForce = verMinor_;
}
//----------------------------------------------------------------------------//
void OpenGLInfo::initTypeAndVer()
{
#if defined CEGUI_USE_EPOXY
d_type = epoxy_is_desktop_gl() ? TYPE_DESKTOP : TYPE_ES;
if (d_verMajorForce >= 0)
{
d_verMajor = d_verMajorForce;
d_verMinor = d_verMinorForce;
}
else
{
int ver(epoxy_gl_version());
if (!ver)
{
if (isUsingDesktopOpengl())
CEGUI_THROW(RendererException
("Failed to obtain desktop OpenGL version."));
else
CEGUI_THROW(RendererException
("Failed to obtain OpenGL ES version."));
}
d_verMajor = ver / 10;
d_verMinor = ver % 10;
}
#elif defined CEGUI_USE_GLEW
d_type = TYPE_DESKTOP;
glGetError ();
d_verMajor = d_verMinor = -1;
#endif
}
//----------------------------------------------------------------------------//
void OpenGLInfo::initSupportedFeatures()
{
#if defined CEGUI_USE_EPOXY
d_isS3tcSupported = epoxy_has_gl_extension("GL_EXT_texture_compression_s3tc");
d_isNpotTextureSupported =
(isUsingDesktopOpengl() && verMajor() >= 2)
|| (isUsingOpenglEs() && verMajor() >= 3)
|| epoxy_has_gl_extension("GL_ARB_texture_non_power_of_two");
d_isReadBufferSupported =
(isUsingDesktopOpengl() && verAtLeast(1, 3))
|| (isUsingOpenglEs() && verMajor() >= 3);
d_isPolygonModeSupported = isUsingDesktopOpengl() && verAtLeast(1, 3);
d_isSeperateReadAndDrawFramebufferSupported =
(isUsingDesktopOpengl() && verAtLeast(3, 1))
|| (isUsingOpenglEs() && verMajor() >= 3);
d_isVaoSupported = (isUsingDesktopOpengl() && verAtLeast(3, 2))
|| (isUsingOpenglEs() && verMajor() >= 3);
#elif defined CEGUI_USE_GLEW
d_isS3tcSupported = false;
// Why do we do this and not use GLEW_EXT_texture_compression_s3tc?
// Because of glewExperimental, of course!
int ext_count;
glGetIntegerv(GL_NUM_EXTENSIONS, &ext_count);
for(int i = 0; i < ext_count; ++i)
{
if (!std::strcmp(
reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, i)),
"GL_EXT_texture_compression_s3tc"))
{
d_isS3tcSupported = true;
break;
}
}
d_isNpotTextureSupported =
(GLEW_VERSION_2_0 == GL_TRUE)
|| (GLEW_ARB_texture_non_power_of_two == GL_TRUE);
d_isPolygonModeSupported
= (GLEW_VERSION_1_3 == GL_TRUE);
d_isSeperateReadAndDrawFramebufferSupported = (GLEW_VERSION_3_1 == GL_TRUE);
d_isVaoSupported = (GLEW_VERSION_3_2 == GL_TRUE);
#endif
}
} // namespace CEGUI
<|endoftext|>
|
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "singleeditablecommands.h"
#include <Models/Editing/combinedartworksmodel.h>
#include <Models/Editing/artworkproxymodel.h>
#include <Models/Artworks/artworkslistmodel.h>
#include <Models/Artworks/filteredartworkslistmodel.h>
#include <Services/SpellCheck/spellchecksuggestionmodel.h>
#include <Services/SpellCheck/duplicatesreviewmodel.h>
#include <Services/SpellCheck/spellsuggestionstarget.h>
#include <Services/AutoComplete/autocompleteservice.h>
#include <Suggestion/keywordssuggestor.h>
#include <Helpers/uihelpers.h>
namespace Commands {
namespace UI {
void FixSpellingInBasicModelCommand::execute(const QVariant &) {
LOG_DEBUG << m_CommandID;
auto &basicMetadataModel = dynamic_cast<Artworks::BasicMetadataModel&>(m_BasicModelSource.getBasicModel());
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::BasicModelSuggestionTarget>(
basicMetadataModel, m_SpellCheckService),
Common::SpellCheckFlags::All);
}
void FixSpellingInArtworkProxyCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
Artworks::ArtworksSnapshot snapshot({m_Source.getArtwork()});
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::ArtworksSuggestionTarget>(
snapshot, m_SpellCheckService, m_ArtworksUpdater),
Common::SpellCheckFlags::All);
}
void FixSpellingForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int index = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(index, artwork)) {
Artworks::ArtworksSnapshot snapshot({artwork});
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::ArtworksSuggestionTarget>(
snapshot, m_SpellCheckService, m_ArtworksUpdater),
Common::SpellCheckFlags::All);
} else {
LOG_WARNING << "Cannot find artwork at" << index;
}
}
void ShowDuplicatesForSingleCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setupModel(m_Source.getArtwork()->getBasicMetadataModel());
}
void ShowDuplicatesForCombinedCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setupModel(m_Source.getBasicModel());
}
void ShowDuplicatesForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int proxyIndex = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(proxyIndex, artwork)) {
m_Target.setupModel(artwork->getBasicModel());
}
}
void AcceptPresetCompletionForCombinedCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int completionID = Helpers::convertToInt(value, 0);
bool accepted = m_Target.acceptCompletionAsPreset(m_Source, completionID);
LOG_INFO << "completion" << completionID << "accepted:" << accepted;
}
void AcceptPresetCompletionForSingleCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int completionID = Helpers::convertToInt(value, 0);
bool accepted = m_Target.acceptCompletionAsPreset(m_Source, completionID);
LOG_INFO << "completion" << completionID << "accepted:" << accepted;
}
void AcceptPresetCompletionForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int artworkIndex = 0;
int completionID = 0;
if (value.isValid()) {
auto map = value.toMap();
auto completionValue = map.value("completion", QVariant(0));
if (completionValue.type() == QVariant::Int) {
completionID = completionValue.toInt();
}
auto indexValue = map.value("index", QVariant(0));
if (indexValue.type() == QVariant::Int) {
artworkIndex = indexValue.toInt();
}
}
m_Target.acceptCompletionAsPreset(artworkIndex, m_Source, completionID);
}
void GenerateCompletionsForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int artworkIndex = 0;
QString prefix;
if (value.isValid()) {
auto map = value.toMap();
auto prefixValue = map.value("prefix", QVariant(""));
if (prefixValue.type() == QVariant::String) {
prefix = prefixValue.toString();
}
auto indexValue = map.value("index", QVariant(0));
if (indexValue.type() == QVariant::Int) {
artworkIndex = indexValue.toInt();
}
}
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(artworkIndex, artwork)) {
m_Target.generateCompletions(prefix, artwork->getBasicModel());
}
}
void InitSuggestionForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int index = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(index, artwork)) {
m_Target.setExistingKeywords(artwork->getKeywords().toSet());
}
}
void InitSuggestionForCombinedCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setExistingKeywords(m_Source.getKeywords().toSet());
}
void InitSuggestionForSingleCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setExistingKeywords(m_Source.getKeywords().toSet());
}
void EditArtworkCommand::execute(const QVariant &value) {
LOG_DEBUG << value;
int proxyIndex = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(proxyIndex, artwork)) {
m_Target.setSourceArtwork(artwork, proxyIndex);
}
}
}
}
<commit_msg>Fix build<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "singleeditablecommands.h"
#include <Models/Editing/combinedartworksmodel.h>
#include <Models/Editing/artworkproxymodel.h>
#include <Models/Artworks/artworkslistmodel.h>
#include <Models/Artworks/filteredartworkslistmodel.h>
#include <Services/SpellCheck/spellchecksuggestionmodel.h>
#include <Services/SpellCheck/duplicatesreviewmodel.h>
#include <Services/SpellCheck/spellsuggestionstarget.h>
#include <Services/AutoComplete/autocompleteservice.h>
#include <Suggestion/keywordssuggestor.h>
#include <Helpers/uihelpers.h>
namespace Commands {
namespace UI {
void FixSpellingInBasicModelCommand::execute(const QVariant &) {
LOG_DEBUG << m_CommandID;
auto &basicMetadataModel = dynamic_cast<Artworks::BasicMetadataModel&>(m_BasicModelSource.getBasicModel());
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::BasicModelSuggestionTarget>(
basicMetadataModel, m_SpellCheckService),
Common::SpellCheckFlags::All);
}
void FixSpellingInArtworkProxyCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
Artworks::ArtworksSnapshot snapshot({m_Source.getArtwork()});
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::ArtworksSuggestionTarget>(
snapshot, m_SpellCheckService, m_ArtworksUpdater),
Common::SpellCheckFlags::All);
}
void FixSpellingForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int index = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(index, artwork)) {
Artworks::ArtworksSnapshot snapshot({artwork});
m_SpellSuggestionsModel.setupModel(
std::make_shared<SpellCheck::ArtworksSuggestionTarget>(
snapshot, m_SpellCheckService, m_ArtworksUpdater),
Common::SpellCheckFlags::All);
} else {
LOG_WARNING << "Cannot find artwork at" << index;
}
}
void ShowDuplicatesForSingleCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setupModel(m_Source.getArtwork()->getBasicMetadataModel());
}
void ShowDuplicatesForCombinedCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setupModel(m_Source.getBasicModel());
}
void ShowDuplicatesForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int proxyIndex = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(proxyIndex, artwork)) {
m_Target.setupModel(artwork->getBasicMetadataModel());
}
}
void AcceptPresetCompletionForCombinedCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int completionID = Helpers::convertToInt(value, 0);
bool accepted = m_Target.acceptCompletionAsPreset(m_Source, completionID);
LOG_INFO << "completion" << completionID << "accepted:" << accepted;
}
void AcceptPresetCompletionForSingleCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int completionID = Helpers::convertToInt(value, 0);
bool accepted = m_Target.acceptCompletionAsPreset(m_Source, completionID);
LOG_INFO << "completion" << completionID << "accepted:" << accepted;
}
void AcceptPresetCompletionForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int artworkIndex = 0;
int completionID = 0;
if (value.isValid()) {
auto map = value.toMap();
auto completionValue = map.value("completion", QVariant(0));
if (completionValue.type() == QVariant::Int) {
completionID = completionValue.toInt();
}
auto indexValue = map.value("index", QVariant(0));
if (indexValue.type() == QVariant::Int) {
artworkIndex = indexValue.toInt();
}
}
m_Target.acceptCompletionAsPreset(artworkIndex, m_Source, completionID);
}
void GenerateCompletionsForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int artworkIndex = 0;
QString prefix;
if (value.isValid()) {
auto map = value.toMap();
auto prefixValue = map.value("prefix", QVariant(""));
if (prefixValue.type() == QVariant::String) {
prefix = prefixValue.toString();
}
auto indexValue = map.value("index", QVariant(0));
if (indexValue.type() == QVariant::Int) {
artworkIndex = indexValue.toInt();
}
}
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(artworkIndex, artwork)) {
m_Target.generateCompletions(prefix, artwork->getBasicModel());
}
}
void InitSuggestionForArtworkCommand::execute(QVariant const &value) {
LOG_DEBUG << value;
int index = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(index, artwork)) {
m_Target.setExistingKeywords(artwork->getKeywords().toSet());
}
}
void InitSuggestionForCombinedCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setExistingKeywords(m_Source.getKeywords().toSet());
}
void InitSuggestionForSingleCommand::execute(QVariant const &) {
LOG_DEBUG << "#";
m_Target.setExistingKeywords(m_Source.getKeywords().toSet());
}
void EditArtworkCommand::execute(const QVariant &value) {
LOG_DEBUG << value;
int proxyIndex = Helpers::convertToInt(value, -1);
std::shared_ptr<Artworks::ArtworkMetadata> artwork;
if (m_Source.tryGetArtwork(proxyIndex, artwork)) {
m_Target.setSourceArtwork(artwork, proxyIndex);
}
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2021 Stanford University
* Copyright 2021 Los Alamos National Laboratory
*
* 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 <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <time.h>
#include "task_throughput.h"
#include <realm/cmdline.h>
namespace TestConfig {
int tasks_per_processor = 256;
int launching_processors = 1;
int task_argument_size = 0;
bool remote_tasks = false;
bool chain_tasks = false;
bool with_profiling = false;
bool skip_launch_procs = false;
bool use_posttriger_barrier = false;
bool group_procs = false;
bool run_immediately = false;
};
// TASK IDs
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
TASK_LAUNCHER,
DUMMY_TASK,
DUMMY_GPU_TASK,
PROFILER_TASK,
};
Logger log_app("app");
// dummy tasks are marked as either "first", "middle", or "last", and prioritized the same way
enum TaskOrder {
FIRST_TASK = 10,
MIDDLE_TASK = 9,
LAST_TASK = 8,
};
struct TestTaskArgs {
int which_task;
RegionInstance instance;
Barrier posttrigger_barrier;
Barrier finish_barrier;
};
struct TestTaskData {
int first_count;
int last_count;
int total_tasks;
double start_time;
};
namespace FieldIDs {
enum {
TASKDATA,
};
};
void dummy_task_body(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const TestTaskArgs& ta = *(const TestTaskArgs *)args;
int task_type = ta.which_task;
// quick out for most tasks
if(task_type == MIDDLE_TASK) return;
if(TestConfig::use_posttriger_barrier && (task_type == FIRST_TASK)) {
#if 0
// need scheduler lock stuff
Processor::enable_scheduler_lock();
ta.posttrigger_barrier.wait();
Processor::disable_scheduler_lock();
#else
while(!ta.posttrigger_barrier.has_triggered());
#endif
}
AffineAccessor<TestTaskData, 1> ra(ta.instance, FieldIDs::TASKDATA);
TestTaskData& mydata = ra[0];
if(task_type == FIRST_TASK) {
double t = Clock::current_time();
log_app.debug() << "first task on " << p << ": " << t;
assert(mydata.last_count == 0);
if(mydata.first_count == 0)
mydata.start_time = t;
mydata.first_count++;
}
if(task_type == LAST_TASK) {
double t = Clock::current_time();
log_app.debug() << "last task on " << p << ": " << t;
assert(mydata.last_count < mydata.first_count);
mydata.last_count++;
if(mydata.last_count == mydata.first_count) {
double elapsed = t - mydata.start_time;
double per_task = elapsed / (mydata.last_count *
TestConfig::tasks_per_processor);
log_app.print() << "tasks complete on " << p << ": "
<< (1e6 * per_task) << " us/task, "
<< (1.0 / per_task) << " tasks/s";
ta.finish_barrier.arrive();
}
}
}
void dummy_cpu_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
dummy_task_body(args, arglen, userdata, userlen, p);
}
void profiler_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
// do nothing with the data
}
struct LauncherArgs {
Barrier start_barrier;
Barrier posttrigger_barrier;
Barrier finish_barrier;
std::map<Processor, RegionInstance> instances;
};
template<typename S>
bool serdez(S& s, const LauncherArgs& t)
{
return ((s & t.start_barrier) &&
(s & t.posttrigger_barrier) &&
(s & t.finish_barrier) &&
(s & t.instances));
}
void task_launcher(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
Serialization::FixedBufferDeserializer fbd(args, arglen);
LauncherArgs la;
bool ok = fbd >> la;
assert(ok);
Machine::ProcessorQuery pq(Machine::get_machine());
if(!TestConfig::remote_tasks)
pq = pq.same_address_space_as(p);
ProfilingRequestSet prs;
if(TestConfig::with_profiling) {
using namespace Realm::ProfilingMeasurements;
prs.add_request(p, PROFILER_TASK).add_measurement<OperationTimeline>();
}
// allocate some space for our test arguments
int argsize = sizeof(TestTaskArgs);
if(TestConfig::task_argument_size > argsize)
argsize = TestConfig::task_argument_size;
TestTaskArgs *tta = (TestTaskArgs *)(alloca(argsize));
// time how long this takes us
double t1 = Clock::current_time();
int total_tasks = 0;
std::vector<Processor> targets;
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it)
if(!(TestConfig::skip_launch_procs && ((*it) == p)))
targets.push_back(*it);
if(TestConfig::group_procs && !targets.empty()) {
Processor p = ProcessorGroup::create_group(targets);
la.instances[p] = la.instances[targets[0]];
if(targets.size() > 1)
la.finish_barrier.arrive(targets.size() - 1);
targets.clear();
targets.push_back(p);
}
// round-robin tasks across target processors in case barrier trigger
// is slower than task execution rate
std::map<Processor, Event> preconds;
// always have to have at least 2 tasks - one FIRST and one LAST
if(TestConfig::tasks_per_processor < 2)
TestConfig::tasks_per_processor = 2;
for(int i = 0; i < TestConfig::tasks_per_processor; i++) {
int which = ((i == 0) ? FIRST_TASK :
(i == (TestConfig::tasks_per_processor - 1)) ? LAST_TASK :
MIDDLE_TASK);
tta->which_task = which;
tta->posttrigger_barrier = la.posttrigger_barrier;
tta->finish_barrier = la.finish_barrier;
for(std::vector<Processor>::const_iterator it = targets.begin(); it != targets.end(); ++it) {
tta->instance = la.instances[*it];
assert(tta->instance.exists());
Processor::TaskFuncID task_id = DUMMY_TASK;
#ifdef REALM_USE_CUDA
if((*it).kind() == Processor::TOC_PROC)
task_id = DUMMY_GPU_TASK;
#endif
if(i == 0)
preconds[*it] = la.start_barrier;
Event e = (*it).spawn(task_id, tta, argsize, prs, preconds[*it], which);
if(TestConfig::chain_tasks)
preconds[*it] = e;
total_tasks++;
}
}
double t2 = Clock::current_time();
double spawn_rate = total_tasks / (t2 - t1);
log_app.print() << "spawn rate on " << p << ": " << spawn_rate << " tasks/s";
if(!TestConfig::run_immediately) {
// we're all done - we can arrive at the start barrier and then finish this task
double t3 = Clock::current_time();
la.start_barrier.arrive();
double t4 = Clock::current_time();
if(!TestConfig::chain_tasks) {
double trigger_rate = total_tasks / (t4 - t3);
log_app.print() << "trigger rate on " << p << ": " << trigger_rate << " tasks/s";
}
}
if(TestConfig::use_posttriger_barrier)
la.posttrigger_barrier.arrive();
if(TestConfig::skip_launch_procs)
la.finish_barrier.arrive();
}
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
LauncherArgs launch_args;
// go through all processors and organize by address space
std::map<AddressSpace, std::vector<Processor> > all_procs;
std::map<AddressSpace, std::vector<Processor> > loc_procs;
int total_procs = 0;
{
std::set<Event> events;
Machine::ProcessorQuery pq(Machine::get_machine());
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it) {
Processor p = *it;
AddressSpace a = p.address_space();
all_procs[a].push_back(p);
if(p.kind() == Processor::LOC_PROC)
loc_procs[a].push_back(p);
total_procs++;
Memory m = Machine::MemoryQuery(Machine::get_machine())
.has_affinity_to(p)
.first();
#ifdef REALM_USE_CUDA
// instance is used by host-side code, so pick a sysmem for GPUs
if(p.kind() == Processor::TOC_PROC)
m = Machine::MemoryQuery(Machine::get_machine())
.same_address_space_as(p)
.only_kind(Memory::SYSTEM_MEM)
.first();
#endif
assert(m.exists());
Rect<1> r(0, 0);
RegionInstance i;
std::map<FieldID, size_t> field_sizes;
field_sizes[FieldIDs::TASKDATA] = sizeof(TestTaskData);
RegionInstance::create_instance(i, m, r,
field_sizes,
0, // SOA
ProfilingRequestSet()).wait();
assert(i.exists());
launch_args.instances[p] = i;
{
std::vector<CopySrcDstField> dsts(1);
dsts[0].inst = i;
dsts[0].field_id = FieldIDs::TASKDATA;
dsts[0].size = sizeof(TestTaskData);
TestTaskData ival;
ival.first_count = 0;
ival.last_count = 0;
ival.start_time = 0;
r.fill(dsts, ProfilingRequestSet(),
&ival, sizeof(ival)).wait();
}
}
}
// two barriers will coordinate the running of the test tasks
// 1) one triggered by each of the launcher tasks that starts the tasks running
// 2) one triggered by each processor when all task launches have been seen
if(TestConfig::run_immediately)
launch_args.start_barrier = Barrier::NO_BARRIER;
else
launch_args.start_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.posttrigger_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.finish_barrier = Barrier::create_barrier(total_procs);
// serialize the launcher args
void *args_data;
size_t args_size;
{
Serialization::DynamicBufferSerializer dbs(256);
bool ok = dbs << launch_args;
assert(ok);
args_size = dbs.bytes_used();
args_data = dbs.detach_buffer();
}
// spawn launcher tasks in each address space
for(std::map<AddressSpace, std::vector<Processor> >::const_iterator it = all_procs.begin();
it != all_procs.end();
++it) {
const std::vector<Processor>& lp = loc_procs[it->first];
assert(lp.size() >= (size_t)(TestConfig::launching_processors));
for(int i = 0; i < TestConfig::launching_processors; i++) {
Processor p = lp[i];
// no need to grab the finish event - we wait indirectly via the barrier
p.spawn(TASK_LAUNCHER, args_data, args_size);
}
}
free(args_data);
// all done - wait for everything to finish via the finish_barrier
launch_args.finish_barrier.wait();
}
int main(int argc, char **argv)
{
Runtime r;
bool ok = r.init(&argc, &argv);
assert(ok);
CommandLineParser cp;
cp.add_option_int("-tpp", TestConfig::tasks_per_processor)
.add_option_int("-lp", TestConfig::launching_processors)
.add_option_int("-args", TestConfig::task_argument_size)
.add_option_bool("-remote", TestConfig::remote_tasks)
.add_option_bool("-chain", TestConfig::chain_tasks)
.add_option_bool("-noself", TestConfig::skip_launch_procs)
.add_option_bool("-post", TestConfig::use_posttriger_barrier)
.add_option_bool("-prof", TestConfig::with_profiling)
.add_option_bool("-group", TestConfig::group_procs)
.add_option_bool("-immed", TestConfig::run_immediately);
ok = cp.parse_command_line(argc, (const char **)argv);
assert(ok);
r.register_task(TOP_LEVEL_TASK, top_level_task);
r.register_task(TASK_LAUNCHER, task_launcher);
r.register_task(DUMMY_TASK, dummy_cpu_task);
r.register_task(PROFILER_TASK, profiler_task);
#ifdef REALM_USE_CUDA
Processor::register_task_by_kind(Processor::TOC_PROC,
false /*!global*/,
DUMMY_GPU_TASK,
CodeDescriptor(dummy_gpu_task),
ProfilingRequestSet()).wait();
#endif
// select a processor to run the top level task on
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
assert(p.exists());
// collective launch of a single task - everybody gets the same finish event
Event e = r.collective_spawn(p, TOP_LEVEL_TASK, 0, 0);
// request shutdown once that task is complete
r.shutdown(e);
// now sleep this thread until that shutdown actually happens
r.wait_for_shutdown();
return 0;
}
<commit_msg>test: fix shutdown race in task_throughput test<commit_after>/* Copyright 2021 Stanford University
* Copyright 2021 Los Alamos National Laboratory
*
* 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 <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <time.h>
#include "task_throughput.h"
#include <realm/cmdline.h>
namespace TestConfig {
int tasks_per_processor = 256;
int launching_processors = 1;
int task_argument_size = 0;
bool remote_tasks = false;
bool chain_tasks = false;
bool with_profiling = false;
bool skip_launch_procs = false;
bool use_posttriger_barrier = false;
bool group_procs = false;
bool run_immediately = false;
};
// TASK IDs
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
TASK_LAUNCHER,
DUMMY_TASK,
DUMMY_GPU_TASK,
PROFILER_TASK,
};
Logger log_app("app");
// dummy tasks are marked as either "first", "middle", or "last", and prioritized the same way
enum TaskOrder {
FIRST_TASK = 10,
MIDDLE_TASK = 9,
LAST_TASK = 8,
};
struct TestTaskArgs {
int which_task;
RegionInstance instance;
Barrier posttrigger_barrier;
Barrier finish_barrier;
};
struct TestTaskData {
int first_count;
int last_count;
int total_tasks;
double start_time;
};
namespace FieldIDs {
enum {
TASKDATA,
};
};
void dummy_task_body(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const TestTaskArgs& ta = *(const TestTaskArgs *)args;
int task_type = ta.which_task;
// quick out for most tasks
if(task_type == MIDDLE_TASK) return;
if(TestConfig::use_posttriger_barrier && (task_type == FIRST_TASK)) {
#if 0
// need scheduler lock stuff
Processor::enable_scheduler_lock();
ta.posttrigger_barrier.wait();
Processor::disable_scheduler_lock();
#else
while(!ta.posttrigger_barrier.has_triggered());
#endif
}
AffineAccessor<TestTaskData, 1> ra(ta.instance, FieldIDs::TASKDATA);
TestTaskData& mydata = ra[0];
if(task_type == FIRST_TASK) {
double t = Clock::current_time();
log_app.debug() << "first task on " << p << ": " << t;
assert(mydata.last_count == 0);
if(mydata.first_count == 0)
mydata.start_time = t;
mydata.first_count++;
}
if(task_type == LAST_TASK) {
double t = Clock::current_time();
log_app.debug() << "last task on " << p << ": " << t;
assert(mydata.last_count < mydata.first_count);
mydata.last_count++;
if(mydata.last_count == mydata.first_count) {
double elapsed = t - mydata.start_time;
double per_task = elapsed / (mydata.last_count *
TestConfig::tasks_per_processor);
log_app.print() << "tasks complete on " << p << ": "
<< (1e6 * per_task) << " us/task, "
<< (1.0 / per_task) << " tasks/s";
ta.finish_barrier.arrive();
}
}
}
void dummy_cpu_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
dummy_task_body(args, arglen, userdata, userlen, p);
}
void profiler_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
// do nothing with the data
}
struct LauncherArgs {
Barrier start_barrier;
Barrier posttrigger_barrier;
Barrier finish_barrier;
std::map<Processor, RegionInstance> instances;
};
template<typename S>
bool serdez(S& s, const LauncherArgs& t)
{
return ((s & t.start_barrier) &&
(s & t.posttrigger_barrier) &&
(s & t.finish_barrier) &&
(s & t.instances));
}
void task_launcher(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
Serialization::FixedBufferDeserializer fbd(args, arglen);
LauncherArgs la;
bool ok = fbd >> la;
assert(ok);
Machine::ProcessorQuery pq(Machine::get_machine());
if(!TestConfig::remote_tasks)
pq = pq.same_address_space_as(p);
ProfilingRequestSet prs;
if(TestConfig::with_profiling) {
using namespace Realm::ProfilingMeasurements;
prs.add_request(p, PROFILER_TASK).add_measurement<OperationTimeline>();
}
// allocate some space for our test arguments
int argsize = sizeof(TestTaskArgs);
if(TestConfig::task_argument_size > argsize)
argsize = TestConfig::task_argument_size;
TestTaskArgs *tta = (TestTaskArgs *)(alloca(argsize));
// time how long this takes us
double t1 = Clock::current_time();
int total_tasks = 0;
std::vector<Processor> targets;
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it)
if(!(TestConfig::skip_launch_procs && ((*it) == p)))
targets.push_back(*it);
if(TestConfig::group_procs && !targets.empty()) {
Processor p = ProcessorGroup::create_group(targets);
la.instances[p] = la.instances[targets[0]];
if(targets.size() > 1)
la.finish_barrier.arrive(targets.size() - 1);
targets.clear();
targets.push_back(p);
}
// round-robin tasks across target processors in case barrier trigger
// is slower than task execution rate
std::map<Processor, Event> preconds;
// always have to have at least 2 tasks - one FIRST and one LAST
if(TestConfig::tasks_per_processor < 2)
TestConfig::tasks_per_processor = 2;
// keep completion events for all tasks for race-free cleanup
std::vector<Event> events;
for(int i = 0; i < TestConfig::tasks_per_processor; i++) {
int which = ((i == 0) ? FIRST_TASK :
(i == (TestConfig::tasks_per_processor - 1)) ? LAST_TASK :
MIDDLE_TASK);
tta->which_task = which;
tta->posttrigger_barrier = la.posttrigger_barrier;
tta->finish_barrier = la.finish_barrier;
for(std::vector<Processor>::const_iterator it = targets.begin(); it != targets.end(); ++it) {
tta->instance = la.instances[*it];
assert(tta->instance.exists());
Processor::TaskFuncID task_id = DUMMY_TASK;
#ifdef REALM_USE_CUDA
if((*it).kind() == Processor::TOC_PROC)
task_id = DUMMY_GPU_TASK;
#endif
if(i == 0)
preconds[*it] = la.start_barrier;
Event e = (*it).spawn(task_id, tta, argsize, prs, preconds[*it], which);
if(TestConfig::chain_tasks)
preconds[*it] = e;
events.push_back(e);
total_tasks++;
}
}
double t2 = Clock::current_time();
double spawn_rate = total_tasks / (t2 - t1);
log_app.print() << "spawn rate on " << p << ": " << spawn_rate << " tasks/s";
if(!TestConfig::run_immediately) {
// we're all done - we can arrive at the start barrier and then finish this task
double t3 = Clock::current_time();
la.start_barrier.arrive();
double t4 = Clock::current_time();
if(!TestConfig::chain_tasks) {
double trigger_rate = total_tasks / (t4 - t3);
log_app.print() << "trigger rate on " << p << ": " << trigger_rate << " tasks/s";
}
}
if(TestConfig::use_posttriger_barrier)
la.posttrigger_barrier.arrive();
if(TestConfig::skip_launch_procs)
la.finish_barrier.arrive();
// don't actually terminate until all the tasks we spawned are done
Event::merge_events(events).wait();
}
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
LauncherArgs launch_args;
// go through all processors and organize by address space
std::map<AddressSpace, std::vector<Processor> > all_procs;
std::map<AddressSpace, std::vector<Processor> > loc_procs;
int total_procs = 0;
{
std::set<Event> events;
Machine::ProcessorQuery pq(Machine::get_machine());
for(Machine::ProcessorQuery::iterator it = pq.begin(); it != pq.end(); ++it) {
Processor p = *it;
AddressSpace a = p.address_space();
all_procs[a].push_back(p);
if(p.kind() == Processor::LOC_PROC)
loc_procs[a].push_back(p);
total_procs++;
Memory m = Machine::MemoryQuery(Machine::get_machine())
.has_affinity_to(p)
.first();
#ifdef REALM_USE_CUDA
// instance is used by host-side code, so pick a sysmem for GPUs
if(p.kind() == Processor::TOC_PROC)
m = Machine::MemoryQuery(Machine::get_machine())
.same_address_space_as(p)
.only_kind(Memory::SYSTEM_MEM)
.first();
#endif
assert(m.exists());
Rect<1> r(0, 0);
RegionInstance i;
std::map<FieldID, size_t> field_sizes;
field_sizes[FieldIDs::TASKDATA] = sizeof(TestTaskData);
RegionInstance::create_instance(i, m, r,
field_sizes,
0, // SOA
ProfilingRequestSet()).wait();
assert(i.exists());
launch_args.instances[p] = i;
{
std::vector<CopySrcDstField> dsts(1);
dsts[0].inst = i;
dsts[0].field_id = FieldIDs::TASKDATA;
dsts[0].size = sizeof(TestTaskData);
TestTaskData ival;
ival.first_count = 0;
ival.last_count = 0;
ival.start_time = 0;
r.fill(dsts, ProfilingRequestSet(),
&ival, sizeof(ival)).wait();
}
}
}
// two barriers will coordinate the running of the test tasks
// 1) one triggered by each of the launcher tasks that starts the tasks running
// 2) one triggered by each processor when all task launches have been seen
if(TestConfig::run_immediately)
launch_args.start_barrier = Barrier::NO_BARRIER;
else
launch_args.start_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.posttrigger_barrier = Barrier::create_barrier(all_procs.size() *
TestConfig::launching_processors);
launch_args.finish_barrier = Barrier::create_barrier(total_procs);
// serialize the launcher args
void *args_data;
size_t args_size;
{
Serialization::DynamicBufferSerializer dbs(256);
bool ok = dbs << launch_args;
assert(ok);
args_size = dbs.bytes_used();
args_data = dbs.detach_buffer();
}
// spawn launcher tasks in each address space
std::vector<Event> launchers_done;
for(std::map<AddressSpace, std::vector<Processor> >::const_iterator it = all_procs.begin();
it != all_procs.end();
++it) {
const std::vector<Processor>& lp = loc_procs[it->first];
assert(lp.size() >= (size_t)(TestConfig::launching_processors));
for(int i = 0; i < TestConfig::launching_processors; i++) {
Processor p = lp[i];
Event e = p.spawn(TASK_LAUNCHER, args_data, args_size);
launchers_done.push_back(e);
}
}
free(args_data);
// all done - wait for everything to finish via the finish_barrier
launch_args.finish_barrier.wait();
// for orderly shutdown, make sure the launcher tasks themselves are done
Event::merge_events(launchers_done).wait();
}
int main(int argc, char **argv)
{
Runtime r;
bool ok = r.init(&argc, &argv);
assert(ok);
CommandLineParser cp;
cp.add_option_int("-tpp", TestConfig::tasks_per_processor)
.add_option_int("-lp", TestConfig::launching_processors)
.add_option_int("-args", TestConfig::task_argument_size)
.add_option_bool("-remote", TestConfig::remote_tasks)
.add_option_bool("-chain", TestConfig::chain_tasks)
.add_option_bool("-noself", TestConfig::skip_launch_procs)
.add_option_bool("-post", TestConfig::use_posttriger_barrier)
.add_option_bool("-prof", TestConfig::with_profiling)
.add_option_bool("-group", TestConfig::group_procs)
.add_option_bool("-immed", TestConfig::run_immediately);
ok = cp.parse_command_line(argc, (const char **)argv);
assert(ok);
r.register_task(TOP_LEVEL_TASK, top_level_task);
r.register_task(TASK_LAUNCHER, task_launcher);
r.register_task(DUMMY_TASK, dummy_cpu_task);
r.register_task(PROFILER_TASK, profiler_task);
#ifdef REALM_USE_CUDA
Processor::register_task_by_kind(Processor::TOC_PROC,
false /*!global*/,
DUMMY_GPU_TASK,
CodeDescriptor(dummy_gpu_task),
ProfilingRequestSet()).wait();
#endif
// select a processor to run the top level task on
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
assert(p.exists());
// collective launch of a single task - everybody gets the same finish event
Event e = r.collective_spawn(p, TOP_LEVEL_TASK, 0, 0);
// request shutdown once that task is complete
r.shutdown(e);
// now sleep this thread until that shutdown actually happens
r.wait_for_shutdown();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#ifndef __KURENTO_EXCEPTION_HPP__
#define __KURENTO_EXCEPTION_HPP__
#include <exception>
#include <string>
/* Error codes */
#define ERROR_MIN 40000
#define ERROR_MAX 49999
/* GENERIC MEDIA ERRORS */
#define MEDIA_ERROR_MIN 40000
#define MEDIA_ERROR_MAX 40099
// #define MEDIA_ERROR 40000
#define MARSHALL_ERROR 40001
// #define UNMARSHALL_ERROR 40002
#define UNEXPECTED_ERROR 40003
#define CONNECT_ERROR 40004
#define UNSUPPORTED_MEDIA_TYPE 40005
#define NOT_IMPLEMENTED 40006
#define INVALID_SESSION 40007
#define MALFORMED_TRANSACTION 40008
#define NOT_ENOUGH_RESOURCES 40009
/* MediaObject ERRORS */
#define MEDIA_OBJECT_ERROR_MIN 40100
#define MEDIA_OBJECT_ERROR_MAX 40199
#define MEDIA_OBJECT_TYPE_NOT_FOUND 40100
#define MEDIA_OBJECT_NOT_FOUND 40101
// #define MEDIA_OBJECT_CAST_ERROR 40102
// #define MEDIA_OBJECT_HAS_NOT_PARENT 40103
#define MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND 40104
#define MEDIA_OBJECT_METHOD_NOT_FOUND 40105
#define MEDIA_OBJECT_EVENT_NOT_SUPPORTED 40106
#define MEDIA_OBJECT_ILLEGAL_PARAM_ERROR 40107
#define MEDIA_OBJECT_NOT_AVAILABLE 40108
#define MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT 40109
#define MEDIA_OBJECT_TAG_KEY_NOT_FOUND 40110
#define MEDIA_OBJECT_OPERATION_NOT_SUPPORTED 40111
/* SDP ERRORS */
#define SDP_ERROR_MIN 40200
#define SDP_ERROR_MAX 40299
#define SDP_CREATE_ERROR 40200
#define SDP_PARSE_ERROR 40201
#define SDP_END_POINT_NO_LOCAL_SDP_ERROR 40202
#define SDP_END_POINT_NO_REMOTE_SDP_ERROR 40203
#define SDP_END_POINT_GENERATE_OFFER_ERROR 40204
#define SDP_END_POINT_PROCESS_OFFER_ERROR 40205
#define SDP_END_POINT_PROCESS_ANSWER_ERROR 40206
#define SDP_CONFIGURATION_ERROR 40207
#define SDP_END_POINT_ALREADY_NEGOTIATED 40208
#define SDP_END_POINT_NOT_OFFER_GENERATED 40209
#define SDP_END_POINT_ANSWER_ALREADY_PROCCESED 40210
#define SDP_END_POINT_CANNOT_CREATE_SESSON 40211
/* HTTP ERRORS */
#define HTTP_ERROR_MIN 40300
#define HTTP_ERROR_MAX 40399
#define HTTP_END_POINT_REGISTRATION_ERROR 40300
/* ICE ERRORS */
#define ICE_ERROR_MIN 40400
#define ICE_ERROR_MAX 40499
#define ICE_GATHER_CANDIDATES_ERROR 40400
#define ICE_ADD_CANDIDATE_ERROR 40401
/* SERVER MANAGER ERRORS */
#define SERVER_MANAGER_ERROR_MIN 40500
#define SERVER_MANAGER_ERROR_MAX 40599
#define SERVER_MANAGER_ERROR_KMD_NOT_FOUND 40500
/* Custom ERRORS */
/* Reserved codes for custom modules */
#define CUSTOM_ERROR_MIN 49000
#define CUSTOM_ERROR_MAX 49999
namespace kurento
{
class KurentoException: public virtual std::exception
{
public:
KurentoException (int code, const std::string &message) : message (message),
code (code) {};
virtual ~KurentoException() {};
virtual const char *what() const noexcept {
return message.c_str();
};
const std::string &getMessage() const {
return message;
};
int getCode() const {
return code;
}
std::string getType() {
switch (code) {
/* Error codes */
/* GENERIC MEDIA ERRORS */
// case MEDIA_ERROR:
// return "MEDIA_ERROR";
case MARSHALL_ERROR:
return "MARSHALL_ERROR";
// case UNMARSHALL_ERROR:
// return "UNMARSHALL_ERROR";
case UNEXPECTED_ERROR:
return "UNEXPECTED_ERROR";
case CONNECT_ERROR:
return "CONNECT_ERROR";
case UNSUPPORTED_MEDIA_TYPE:
return "UNSUPPORTED_MEDIA_TYPE";
case NOT_IMPLEMENTED:
return "NOT_IMPLEMENTED";
case INVALID_SESSION:
return "INVALID_SESSION";
case MALFORMED_TRANSACTION:
return "MALFORMED_TRANSACTION";
case NOT_ENOUGH_RESOURCES:
return "NOT_ENOUGH_RESOURCES";
/* MediaObject ERRORS */
case MEDIA_OBJECT_TYPE_NOT_FOUND:
return "MEDIA_OBJECT_TYPE_NOT_FOUND";
case MEDIA_OBJECT_NOT_FOUND:
return "MEDIA_OBJECT_NOT_FOUND";
// case MEDIA_OBJECT_CAST_ERROR:
// return "MEDIA_OBJECT_CAST_ERROR";
// case MEDIA_OBJECT_HAS_NOT_PARENT:
// return "MEDIA_OBJECT_HAS_NOT_PARENT";
case MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND:
return "MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND";
case MEDIA_OBJECT_METHOD_NOT_FOUND:
return "MEDIA_OBJECT_METHOD_NOT_FOUND";
case MEDIA_OBJECT_EVENT_NOT_SUPPORTED:
return "MEDIA_OBJECT_EVENT_NOT_SUPPORTED";
case MEDIA_OBJECT_ILLEGAL_PARAM_ERROR:
return "MEDIA_OBJECT_ILLEGAL_PARAM_ERROR";
case MEDIA_OBJECT_NOT_AVAILABLE:
return "MEDIA_OBJECT_NOT_AVAILABLE";
case MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT:
return "MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT";
case MEDIA_OBJECT_TAG_KEY_NOT_FOUND:
return "MEDIA_OBJECT_TAG_KEY_NOT_FOUND";
case MEDIA_OBJECT_OPERATION_NOT_SUPPORTED:
return "MEDIA_OBJECT_OPERATION_NOT_SUPPORTED";
/* SDP ERRORS */
case SDP_CREATE_ERROR:
return "SDP_CREATE_ERROR";
case SDP_PARSE_ERROR:
return "SDP_PARSE_ERROR";
case SDP_END_POINT_NO_LOCAL_SDP_ERROR:
return "SDP_END_POINT_NO_LOCAL_SDP_ERROR";
case SDP_END_POINT_NO_REMOTE_SDP_ERROR:
return "SDP_END_POINT_NO_REMOTE_SDP_ERROR";
case SDP_END_POINT_GENERATE_OFFER_ERROR:
return "SDP_END_POINT_GENERATE_OFFER_ERROR";
case SDP_END_POINT_PROCESS_OFFER_ERROR:
return "SDP_END_POINT_PROCESS_OFFER_ERROR";
case SDP_END_POINT_PROCESS_ANSWER_ERROR:
return "SDP_END_POINT_PROCESS_ANSWER_ERROR";
case SDP_CONFIGURATION_ERROR:
return "SDP_CONFIGURATION_ERROR";
case SDP_END_POINT_ALREADY_NEGOTIATED:
return "SDP_END_POINT_ALREADY_NEGOTIATED";
case SDP_END_POINT_NOT_OFFER_GENERATED:
return "SDP_END_POINT_NOT_OFFER_GENERATED";
case SDP_END_POINT_ANSWER_ALREADY_PROCCESED:
return "SDP_END_POINT_ANSWER_ALREADY_PROCCESED";
case SDP_END_POINT_CANNOT_CREATE_SESSON:
return "SDP_END_POINT_CANNOT_CREATE_SESSON";
/* HTTP ERRORS */
case HTTP_END_POINT_REGISTRATION_ERROR:
return "HTTP_END_POINT_REGISTRATION_ERROR";
default:
return "UNDEFINED";
}
}
protected:
std::string message;
int code;
};
} /* kurento */
#endif /* __KURENTO_EXCEPTION_HPP__ */
<commit_msg>KurentoException: Add error codes to avoid throw ice exceptions as UNDEFINED<commit_after>/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#ifndef __KURENTO_EXCEPTION_HPP__
#define __KURENTO_EXCEPTION_HPP__
#include <exception>
#include <string>
/* Error codes */
#define ERROR_MIN 40000
#define ERROR_MAX 49999
/* GENERIC MEDIA ERRORS */
#define MEDIA_ERROR_MIN 40000
#define MEDIA_ERROR_MAX 40099
// #define MEDIA_ERROR 40000
#define MARSHALL_ERROR 40001
// #define UNMARSHALL_ERROR 40002
#define UNEXPECTED_ERROR 40003
#define CONNECT_ERROR 40004
#define UNSUPPORTED_MEDIA_TYPE 40005
#define NOT_IMPLEMENTED 40006
#define INVALID_SESSION 40007
#define MALFORMED_TRANSACTION 40008
#define NOT_ENOUGH_RESOURCES 40009
/* MediaObject ERRORS */
#define MEDIA_OBJECT_ERROR_MIN 40100
#define MEDIA_OBJECT_ERROR_MAX 40199
#define MEDIA_OBJECT_TYPE_NOT_FOUND 40100
#define MEDIA_OBJECT_NOT_FOUND 40101
// #define MEDIA_OBJECT_CAST_ERROR 40102
// #define MEDIA_OBJECT_HAS_NOT_PARENT 40103
#define MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND 40104
#define MEDIA_OBJECT_METHOD_NOT_FOUND 40105
#define MEDIA_OBJECT_EVENT_NOT_SUPPORTED 40106
#define MEDIA_OBJECT_ILLEGAL_PARAM_ERROR 40107
#define MEDIA_OBJECT_NOT_AVAILABLE 40108
#define MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT 40109
#define MEDIA_OBJECT_TAG_KEY_NOT_FOUND 40110
#define MEDIA_OBJECT_OPERATION_NOT_SUPPORTED 40111
/* SDP ERRORS */
#define SDP_ERROR_MIN 40200
#define SDP_ERROR_MAX 40299
#define SDP_CREATE_ERROR 40200
#define SDP_PARSE_ERROR 40201
#define SDP_END_POINT_NO_LOCAL_SDP_ERROR 40202
#define SDP_END_POINT_NO_REMOTE_SDP_ERROR 40203
#define SDP_END_POINT_GENERATE_OFFER_ERROR 40204
#define SDP_END_POINT_PROCESS_OFFER_ERROR 40205
#define SDP_END_POINT_PROCESS_ANSWER_ERROR 40206
#define SDP_CONFIGURATION_ERROR 40207
#define SDP_END_POINT_ALREADY_NEGOTIATED 40208
#define SDP_END_POINT_NOT_OFFER_GENERATED 40209
#define SDP_END_POINT_ANSWER_ALREADY_PROCCESED 40210
#define SDP_END_POINT_CANNOT_CREATE_SESSON 40211
/* HTTP ERRORS */
#define HTTP_ERROR_MIN 40300
#define HTTP_ERROR_MAX 40399
#define HTTP_END_POINT_REGISTRATION_ERROR 40300
/* ICE ERRORS */
#define ICE_ERROR_MIN 40400
#define ICE_ERROR_MAX 40499
#define ICE_GATHER_CANDIDATES_ERROR 40400
#define ICE_ADD_CANDIDATE_ERROR 40401
/* SERVER MANAGER ERRORS */
#define SERVER_MANAGER_ERROR_MIN 40500
#define SERVER_MANAGER_ERROR_MAX 40599
#define SERVER_MANAGER_ERROR_KMD_NOT_FOUND 40500
/* Custom ERRORS */
/* Reserved codes for custom modules */
#define CUSTOM_ERROR_MIN 49000
#define CUSTOM_ERROR_MAX 49999
namespace kurento
{
class KurentoException: public virtual std::exception
{
public:
KurentoException (int code, const std::string &message) : message (message),
code (code) {};
virtual ~KurentoException() {};
virtual const char *what() const noexcept {
return message.c_str();
};
const std::string &getMessage() const {
return message;
};
int getCode() const {
return code;
}
std::string getType() {
switch (code) {
/* Error codes */
/* GENERIC MEDIA ERRORS */
// case MEDIA_ERROR:
// return "MEDIA_ERROR";
case MARSHALL_ERROR:
return "MARSHALL_ERROR";
// case UNMARSHALL_ERROR:
// return "UNMARSHALL_ERROR";
case UNEXPECTED_ERROR:
return "UNEXPECTED_ERROR";
case CONNECT_ERROR:
return "CONNECT_ERROR";
case UNSUPPORTED_MEDIA_TYPE:
return "UNSUPPORTED_MEDIA_TYPE";
case NOT_IMPLEMENTED:
return "NOT_IMPLEMENTED";
case INVALID_SESSION:
return "INVALID_SESSION";
case MALFORMED_TRANSACTION:
return "MALFORMED_TRANSACTION";
case NOT_ENOUGH_RESOURCES:
return "NOT_ENOUGH_RESOURCES";
/* MediaObject ERRORS */
case MEDIA_OBJECT_TYPE_NOT_FOUND:
return "MEDIA_OBJECT_TYPE_NOT_FOUND";
case MEDIA_OBJECT_NOT_FOUND:
return "MEDIA_OBJECT_NOT_FOUND";
// case MEDIA_OBJECT_CAST_ERROR:
// return "MEDIA_OBJECT_CAST_ERROR";
// case MEDIA_OBJECT_HAS_NOT_PARENT:
// return "MEDIA_OBJECT_HAS_NOT_PARENT";
case MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND:
return "MEDIA_OBJECT_CONSTRUCTOR_NOT_FOUND";
case MEDIA_OBJECT_METHOD_NOT_FOUND:
return "MEDIA_OBJECT_METHOD_NOT_FOUND";
case MEDIA_OBJECT_EVENT_NOT_SUPPORTED:
return "MEDIA_OBJECT_EVENT_NOT_SUPPORTED";
case MEDIA_OBJECT_ILLEGAL_PARAM_ERROR:
return "MEDIA_OBJECT_ILLEGAL_PARAM_ERROR";
case MEDIA_OBJECT_NOT_AVAILABLE:
return "MEDIA_OBJECT_NOT_AVAILABLE";
case MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT:
return "MEDIA_OBJECT_NOT_FOUND_TRANSACTION_NO_COMMIT";
case MEDIA_OBJECT_TAG_KEY_NOT_FOUND:
return "MEDIA_OBJECT_TAG_KEY_NOT_FOUND";
case MEDIA_OBJECT_OPERATION_NOT_SUPPORTED:
return "MEDIA_OBJECT_OPERATION_NOT_SUPPORTED";
/* SDP ERRORS */
case SDP_CREATE_ERROR:
return "SDP_CREATE_ERROR";
case SDP_PARSE_ERROR:
return "SDP_PARSE_ERROR";
case SDP_END_POINT_NO_LOCAL_SDP_ERROR:
return "SDP_END_POINT_NO_LOCAL_SDP_ERROR";
case SDP_END_POINT_NO_REMOTE_SDP_ERROR:
return "SDP_END_POINT_NO_REMOTE_SDP_ERROR";
case SDP_END_POINT_GENERATE_OFFER_ERROR:
return "SDP_END_POINT_GENERATE_OFFER_ERROR";
case SDP_END_POINT_PROCESS_OFFER_ERROR:
return "SDP_END_POINT_PROCESS_OFFER_ERROR";
case SDP_END_POINT_PROCESS_ANSWER_ERROR:
return "SDP_END_POINT_PROCESS_ANSWER_ERROR";
case SDP_CONFIGURATION_ERROR:
return "SDP_CONFIGURATION_ERROR";
case SDP_END_POINT_ALREADY_NEGOTIATED:
return "SDP_END_POINT_ALREADY_NEGOTIATED";
case SDP_END_POINT_NOT_OFFER_GENERATED:
return "SDP_END_POINT_NOT_OFFER_GENERATED";
case SDP_END_POINT_ANSWER_ALREADY_PROCCESED:
return "SDP_END_POINT_ANSWER_ALREADY_PROCCESED";
case SDP_END_POINT_CANNOT_CREATE_SESSON:
return "SDP_END_POINT_CANNOT_CREATE_SESSON";
/* HTTP ERRORS */
case HTTP_END_POINT_REGISTRATION_ERROR:
return "HTTP_END_POINT_REGISTRATION_ERROR";
/* ICE ERRORS */
case ICE_GATHER_CANDIDATES_ERROR:
return "ICE_GATHER_CANDIDATES_ERROR";
case ICE_ADD_CANDIDATE_ERROR:
return "ICE_ADD_CANDIDATE_ERROR";
default:
return "UNDEFINED";
}
}
protected:
std::string message;
int code;
};
} /* kurento */
#endif /* __KURENTO_EXCEPTION_HPP__ */
<|endoftext|>
|
<commit_before><commit_msg>tdf#91100 - don't Notify focus changes after dispose.<commit_after><|endoftext|>
|
<commit_before>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
if (A.empty()) {
return NULL;
}
stack<TreeNode *> nodeStack;
nodeStack.push(new TreeNode(A[0]));
for (int i = 1; i < A.size(); ++i) {
// The stack stores nodes in descending order.
if (A[i] <= nodeStack.top()->val) {
TreeNode *node = new TreeNode(A[i]);
nodeStack.push(node);
} else {
// Pop every node which value is less than A[i],
// and let them as right children of the last node less than A[i]
TreeNode *smaller_node = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty() && nodeStack.top()->val < A[i]){
nodeStack.top()->right = smaller_node;
smaller_node = nodeStack.top();
nodeStack.pop();
}
// Pop the last node which value is less than A[i], and let it as right child,
// and push A[i] to the stack.
TreeNode *node = new TreeNode(A[i]);
node->left = smaller_node;
nodeStack.push(node);
}
}
// Pop every node in the stack,
// and let them as right children of the root
TreeNode *root = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty()){
nodeStack.top()->right = root;
root = nodeStack.top();
nodeStack.pop();
}
return root;
}
};
<commit_msg>Update max-tree.cpp<commit_after>// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param A: Given an integer array with no duplicates.
* @return: The root of max tree.
*/
TreeNode* maxTree(vector<int> A) {
if (A.empty()) {
return NULL;
}
stack<TreeNode *> nodeStack;
nodeStack.push(new TreeNode(A[0]));
for (int i = 1; i < A.size(); ++i) {
// The stack stores nodes in descending order.
if (A[i] <= nodeStack.top()->val) {
TreeNode *node = new TreeNode(A[i]);
nodeStack.push(node);
} else {
// Pop every node which value is less than A[i],
// and let them as right children of
// the last node less than A[i]
TreeNode *smaller_node = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty() && nodeStack.top()->val < A[i]) {
nodeStack.top()->right = smaller_node;
smaller_node = nodeStack.top();
nodeStack.pop();
}
// Pop the last node which value is less
// than A[i], and let it as right child,
// and push A[i] to the stack.
TreeNode *node = new TreeNode(A[i]);
node->left = smaller_node;
nodeStack.push(node);
}
}
// Pop every node in the stack,
// and let them as right children of the root
TreeNode *root = nodeStack.top();
nodeStack.pop();
while (!nodeStack.empty()) {
nodeStack.top()->right = root;
root = nodeStack.top();
nodeStack.pop();
}
return root;
}
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sfxpicklist.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:11:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_PICKLIST_HXX_
#define _SFX_PICKLIST_HXX_
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XSTRINGWIDTH_HPP_
#include <com/sun/star/util/XStringWidth.hpp>
#endif
#include <vector>
#define PICKLIST_MAXSIZE 100
class SfxPickList : public SfxListener
{
struct PickListEntry
{
PickListEntry( const String& _aName, const String& _aFilter, const String& _aTitle ) :
aName( _aName ), aFilter( _aFilter ), aTitle( _aTitle ) {}
String aName;
String aFilter;
String aTitle;
String aOptions;
};
static SfxPickList* pUniqueInstance;
static osl::Mutex* pMutex;
std::vector< PickListEntry* > m_aPicklistVector;
sal_uInt32 m_nAllowedMenuSize;
::com::sun::star::uno::Reference< ::com::sun::star::util::XStringWidth > m_xStringLength;
SfxPickList( ULONG nMenuSize );
~SfxPickList();
static osl::Mutex* GetOrCreateMutex();
void CreatePicklistMenuTitle( Menu* pMenu, USHORT nItemId, const String& aURL, sal_uInt32 nNo );
PickListEntry* GetPickListEntry( sal_uInt32 nIndex );
void CreatePickListEntries();
void RemovePickListEntries();
public:
static SfxPickList* GetOrCreate( const ULONG nMenuSize );
static SfxPickList* Get();
static void Delete();
sal_uInt32 GetAllowedMenuSize() { return m_nAllowedMenuSize; }
sal_uInt32 GetNumOfEntries() const { return m_aPicklistVector.size(); }
void CreateMenuEntries( Menu* pMenu );
void ExecuteMenuEntry( USHORT nId );
void ExecuteEntry( sal_uInt32 nIndex );
String GetMenuEntryTitle( sal_uInt32 nIndex );
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif // _SFX_PICKLIST_HXX_
<commit_msg>INTEGRATION: CWS long2int (1.4.48); FILE MERGED 2005/10/26 18:07:22 kendy 1.4.48.1: #i56715# Trivial long/ULONG -> sal_Int32/sal_uInt32 patches extracted from ooo64bit02 CWS.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sfxpicklist.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2006-03-31 09:34:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_PICKLIST_HXX_
#define _SFX_PICKLIST_HXX_
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef _COM_SUN_STAR_UTIL_XSTRINGWIDTH_HPP_
#include <com/sun/star/util/XStringWidth.hpp>
#endif
#include <vector>
#define PICKLIST_MAXSIZE 100
class SfxPickList : public SfxListener
{
struct PickListEntry
{
PickListEntry( const String& _aName, const String& _aFilter, const String& _aTitle ) :
aName( _aName ), aFilter( _aFilter ), aTitle( _aTitle ) {}
String aName;
String aFilter;
String aTitle;
String aOptions;
};
static SfxPickList* pUniqueInstance;
static osl::Mutex* pMutex;
std::vector< PickListEntry* > m_aPicklistVector;
sal_uInt32 m_nAllowedMenuSize;
::com::sun::star::uno::Reference< ::com::sun::star::util::XStringWidth > m_xStringLength;
SfxPickList( sal_uInt32 nMenuSize );
~SfxPickList();
static osl::Mutex* GetOrCreateMutex();
void CreatePicklistMenuTitle( Menu* pMenu, USHORT nItemId, const String& aURL, sal_uInt32 nNo );
PickListEntry* GetPickListEntry( sal_uInt32 nIndex );
void CreatePickListEntries();
void RemovePickListEntries();
public:
static SfxPickList* GetOrCreate( const sal_uInt32 nMenuSize );
static SfxPickList* Get();
static void Delete();
sal_uInt32 GetAllowedMenuSize() { return m_nAllowedMenuSize; }
sal_uInt32 GetNumOfEntries() const { return m_aPicklistVector.size(); }
void CreateMenuEntries( Menu* pMenu );
void ExecuteMenuEntry( USHORT nId );
void ExecuteEntry( sal_uInt32 nIndex );
String GetMenuEntryTitle( sal_uInt32 nIndex );
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif // _SFX_PICKLIST_HXX_
<|endoftext|>
|
<commit_before>#include "AlembicPointsUtils.h"
#include <IParticleObjectExt.h>
#include <ParticleFlow/IParticleChannelID.h>
#include <ParticleFlow/IParticleChannelShape.h>
#include <ParticleFlow/IParticleContainer.h>
#include <ParticleFlow/IParticleGroup.h>
#include <ParticleFlow/IPFSystem.h>
#include <ParticleFlow/IPFActionList.h>
#include <ParticleFlow/PFSimpleOperator.h>
#include <ParticleFlow/IParticleChannels.h>
#include <ParticleFlow/IChannelContainer.h>
#include <ParticleFlow/IParticleChannelLifespan.h>
#include <ParticleFlow/IPFRender.h>
#include <ParticleFlow/IChannelContainer.h>
#include <ParticleFlow/IParticleContainer.h>
#include <map>
#include <vector>
#include "AlembicParticles.h"
//class NullView: public View
//{
//public:
// Point2 ViewToScreen(Point3 p) { return Point2(p.x,p.y); }
// NullView() { worldToView.IdentityMatrix(); screenW=640.0f; screenH = 480.0f; }
//};
typedef std::map<INode*, IParticleGroup*> groupMapT;
void getParticleGroups(TimeValue ticks, Object* obj, INode* node, std::vector<IParticleGroup*>& groups)
{
IParticleObjectExt* particlesExt = GetParticleObjectExtInterface(obj);
groupMapT groupMap;
for(int i=0; i< particlesExt->NumParticles(); i++){
INode *particleGroupNode = particlesExt->GetParticleGroup(i);
Object *particleGroupObj = (particleGroupNode != NULL) ? particleGroupNode->EvalWorldState(ticks).obj : NULL;
IParticleGroup *particleGroup = GetParticleGroupInterface(particleGroupObj);
groupMap[particleGroupNode] = particleGroup;
}
for( groupMapT::iterator it=groupMap.begin(); it!=groupMap.end(); it++)
{
groups.push_back((*it).second);
}
}
void getParticleSystemRenderMeshes(TimeValue ticks, Object* obj, INode* node, std::vector<particleMeshData>& meshes)
{
SimpleParticle* pSimpleParticle = (SimpleParticle*) obj->GetInterface(I_SIMPLEPARTICLEOBJ);
if(pSimpleParticle){
NullView nullView;
AlembicParticles* pAlembicParticles = NULL;
if(obj->CanConvertToType(ALEMBIC_SIMPLE_PARTICLE_CLASSID))
{
pAlembicParticles = reinterpret_cast<AlembicParticles*>(obj->ConvertToType(ticks, ALEMBIC_SIMPLE_PARTICLE_CLASSID));
}
if(pAlembicParticles){
pSimpleParticle->Update(ticks, node);
int numParticles = pSimpleParticle->parts.points.Count();
for(int i=0; i<numParticles; i++){
particleMeshData mdata;
mdata.pMtl = NULL; //TODO: where get material?
mdata.animHandle = 0; //TODO: where to get handle?
Interval interval = FOREVER;
pAlembicParticles->GetMultipleRenderMeshTM_Internal(ticks, NULL, nullView, i, mdata.meshTM, interval);
//Matrix3 objectToWorld = inode->GetObjectTM( ticks );
//mdata.meshTM = mdata.meshTM * Inverse(objectToWorld);
mdata.pMesh = pAlembicParticles->GetMultipleRenderMesh(ticks, node /*system node or particle node?*/ , nullView, mdata.bNeedDelete, i);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
else{
particleMeshData mdata;
mdata.pMtl = NULL;//TODO: where to get material?
mdata.animHandle = 0;//TODO: where to get handle?
mdata.meshTM.IdentityMatrix();
mdata.pMesh = pSimpleParticle->GetRenderMesh(ticks, node, nullView, mdata.bNeedDelete);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
else{
IPFActionList* particleActionList = GetPFActionListInterface(obj);
if(!particleActionList){
return;
}
std::vector<IParticleGroup*> groups;
getParticleGroups(ticks, obj, node, groups);
IPFRender* particleRender = NULL;
int numActions = particleActionList->NumActions();
for (int p = particleActionList->NumActions()-1; p >= 0; p -= 1)
{
INode *pActionNode = particleActionList->GetAction(p);
Object *pActionObj = (pActionNode != NULL ? pActionNode->EvalWorldState(ticks).obj : NULL);
if (pActionObj == NULL){
continue;
}
//MSTR name;
//pActionObj->GetClassName(name);
particleRender = GetPFRenderInterface(pActionObj);
if(particleRender){
break;
}
}
if(particleRender){
NullView nullView;
for(int g=0; g<groups.size(); g++){
::IObject *pCont = groups[g]->GetParticleContainer();
::INode *pNode = groups[g]->GetParticleSystem();
particleMeshData mdata;
mdata.pMtl = groups[g]->GetMaterial();
mdata.animHandle = Animatable::GetHandleByAnim(groups[g]->GetActionList());
mdata.meshTM.IdentityMatrix();
mdata.pMesh = particleRender->GetRenderMesh(pCont, ticks, obj, pNode, nullView, mdata.bNeedDelete);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
}
}
const Mesh* GetShapeMesh(IParticleObjectExt *pExt, int particleId, TimeValue ticks)
{
// Go into the particle's action list
INode *particleGroupNode = pExt->GetParticleGroup(particleId);
Object *particleGroupObj = (particleGroupNode != NULL) ? particleGroupNode->EvalWorldState(ticks).obj : NULL;
if (!particleGroupObj){
return NULL;
}
IParticleGroup *particleGroup = GetParticleGroupInterface(particleGroupObj);
::IObject *pCont = particleGroup->GetParticleContainer();
if(!pCont){
return NULL;
}
IChannelContainer* chCont = GetChannelContainerInterface(pCont);
if (!chCont){
return NULL;
}
IParticleChannelMeshR* pShapeChannel = GetParticleChannelShapeRInterface(chCont);
if(!pShapeChannel){
return NULL;
}
//IParticleChannelINodeR* pNodeChannel = GetParticleChannelRefNodeRInterface(chCont);
//if(!pNodeChannel){
// return;
//}
//int nSize = pShapeChannel->GetValueCount();
//if(particleId >= nSize){
// return;
//}
//bool bIsShared = pShapeChannel->IsShared();//if true, particle meshes are not unique, and we should avoid writing out copies
int nMeshIndex = pShapeChannel->GetValueIndex(particleId);
const Mesh* pMesh = pShapeChannel->GetValueByIndex(nMeshIndex);
if(!pMesh){
int n=0;
n++;
}
return pMesh;
}<commit_msg>added call to updateParticles (not sure why this call is needed to export some systems but not others) fixes issue #83<commit_after>#include "AlembicPointsUtils.h"
#include <IParticleObjectExt.h>
#include <ParticleFlow/IParticleChannelID.h>
#include <ParticleFlow/IParticleChannelShape.h>
#include <ParticleFlow/IParticleContainer.h>
#include <ParticleFlow/IParticleGroup.h>
#include <ParticleFlow/IPFSystem.h>
#include <ParticleFlow/IPFActionList.h>
#include <ParticleFlow/PFSimpleOperator.h>
#include <ParticleFlow/IParticleChannels.h>
#include <ParticleFlow/IChannelContainer.h>
#include <ParticleFlow/IParticleChannelLifespan.h>
#include <ParticleFlow/IPFRender.h>
#include <ParticleFlow/IChannelContainer.h>
#include <ParticleFlow/IParticleContainer.h>
#include <map>
#include <vector>
#include "AlembicParticles.h"
//class NullView: public View
//{
//public:
// Point2 ViewToScreen(Point3 p) { return Point2(p.x,p.y); }
// NullView() { worldToView.IdentityMatrix(); screenW=640.0f; screenH = 480.0f; }
//};
typedef std::map<INode*, IParticleGroup*> groupMapT;
void getParticleGroups(TimeValue ticks, Object* obj, INode* node, std::vector<IParticleGroup*>& groups)
{
IParticleObjectExt* particlesExt = GetParticleObjectExtInterface(obj);
particlesExt->UpdateParticles(node, ticks);
groupMapT groupMap;
for(int i=0; i< particlesExt->NumParticles(); i++){
INode *particleGroupNode = particlesExt->GetParticleGroup(i);
Object *particleGroupObj = (particleGroupNode != NULL) ? particleGroupNode->EvalWorldState(ticks).obj : NULL;
IParticleGroup *particleGroup = GetParticleGroupInterface(particleGroupObj);
groupMap[particleGroupNode] = particleGroup;
}
for( groupMapT::iterator it=groupMap.begin(); it!=groupMap.end(); it++)
{
groups.push_back((*it).second);
}
}
void getParticleSystemRenderMeshes(TimeValue ticks, Object* obj, INode* node, std::vector<particleMeshData>& meshes)
{
SimpleParticle* pSimpleParticle = (SimpleParticle*) obj->GetInterface(I_SIMPLEPARTICLEOBJ);
if(pSimpleParticle){
NullView nullView;
AlembicParticles* pAlembicParticles = NULL;
if(obj->CanConvertToType(ALEMBIC_SIMPLE_PARTICLE_CLASSID))
{
pAlembicParticles = reinterpret_cast<AlembicParticles*>(obj->ConvertToType(ticks, ALEMBIC_SIMPLE_PARTICLE_CLASSID));
}
if(pAlembicParticles){
pSimpleParticle->Update(ticks, node);
int numParticles = pSimpleParticle->parts.points.Count();
for(int i=0; i<numParticles; i++){
particleMeshData mdata;
mdata.pMtl = NULL; //TODO: where get material?
mdata.animHandle = 0; //TODO: where to get handle?
Interval interval = FOREVER;
pAlembicParticles->GetMultipleRenderMeshTM_Internal(ticks, NULL, nullView, i, mdata.meshTM, interval);
//Matrix3 objectToWorld = inode->GetObjectTM( ticks );
//mdata.meshTM = mdata.meshTM * Inverse(objectToWorld);
mdata.pMesh = pAlembicParticles->GetMultipleRenderMesh(ticks, node /*system node or particle node?*/ , nullView, mdata.bNeedDelete, i);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
else{
particleMeshData mdata;
mdata.pMtl = NULL;//TODO: where to get material?
mdata.animHandle = 0;//TODO: where to get handle?
mdata.meshTM.IdentityMatrix();
mdata.pMesh = pSimpleParticle->GetRenderMesh(ticks, node, nullView, mdata.bNeedDelete);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
else{
IPFActionList* particleActionList = GetPFActionListInterface(obj);
if(!particleActionList){
return;
}
std::vector<IParticleGroup*> groups;
getParticleGroups(ticks, obj, node, groups);
IPFRender* particleRender = NULL;
int numActions = particleActionList->NumActions();
for (int p = particleActionList->NumActions()-1; p >= 0; p -= 1)
{
INode *pActionNode = particleActionList->GetAction(p);
Object *pActionObj = (pActionNode != NULL ? pActionNode->EvalWorldState(ticks).obj : NULL);
if (pActionObj == NULL){
continue;
}
//MSTR name;
//pActionObj->GetClassName(name);
particleRender = GetPFRenderInterface(pActionObj);
if(particleRender){
break;
}
}
if(particleRender){
NullView nullView;
for(int g=0; g<groups.size(); g++){
::IObject *pCont = groups[g]->GetParticleContainer();
::INode *pNode = groups[g]->GetParticleSystem();
particleMeshData mdata;
mdata.pMtl = groups[g]->GetMaterial();
mdata.animHandle = Animatable::GetHandleByAnim(groups[g]->GetActionList());
mdata.meshTM.IdentityMatrix();
mdata.pMesh = particleRender->GetRenderMesh(pCont, ticks, obj, pNode, nullView, mdata.bNeedDelete);
if(mdata.pMesh){
meshes.push_back(mdata);
}
}
}
}
}
const Mesh* GetShapeMesh(IParticleObjectExt *pExt, int particleId, TimeValue ticks)
{
// Go into the particle's action list
INode *particleGroupNode = pExt->GetParticleGroup(particleId);
Object *particleGroupObj = (particleGroupNode != NULL) ? particleGroupNode->EvalWorldState(ticks).obj : NULL;
if (!particleGroupObj){
return NULL;
}
IParticleGroup *particleGroup = GetParticleGroupInterface(particleGroupObj);
::IObject *pCont = particleGroup->GetParticleContainer();
if(!pCont){
return NULL;
}
IChannelContainer* chCont = GetChannelContainerInterface(pCont);
if (!chCont){
return NULL;
}
IParticleChannelMeshR* pShapeChannel = GetParticleChannelShapeRInterface(chCont);
if(!pShapeChannel){
return NULL;
}
//IParticleChannelINodeR* pNodeChannel = GetParticleChannelRefNodeRInterface(chCont);
//if(!pNodeChannel){
// return;
//}
//int nSize = pShapeChannel->GetValueCount();
//if(particleId >= nSize){
// return;
//}
//bool bIsShared = pShapeChannel->IsShared();//if true, particle meshes are not unique, and we should avoid writing out copies
int nMeshIndex = pShapeChannel->GetValueIndex(particleId);
const Mesh* pMesh = pShapeChannel->GetValueByIndex(nMeshIndex);
if(!pMesh){
int n=0;
n++;
}
return pMesh;
}<|endoftext|>
|
<commit_before>#ifndef slic3r_GUI_ObjectManipulation_hpp_
#define slic3r_GUI_ObjectManipulation_hpp_
#include <memory>
#include "GUI_ObjectSettings.hpp"
#include "GLCanvas3D.hpp"
class wxStaticText;
class PrusaLockButton;
namespace Slic3r {
namespace GUI {
class ObjectManipulation : public OG_Settings
{
#if ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
struct Cache
{
Vec3d position;
Vec3d rotation;
Vec3d scale;
Vec3d size;
std::string move_label_string;
std::string rotate_label_string;
std::string scale_label_string;
struct Instance
{
int object_idx;
int instance_idx;
Vec3d box_size;
Instance() { reset(); }
void reset() { this->object_idx = -1; this->instance_idx = -1; this->box_size = Vec3d::Zero(); }
void set(int object_idx, int instance_idx, const Vec3d& box_size) { this->object_idx = object_idx; this->instance_idx = instance_idx; this->box_size = box_size; }
bool matches(int object_idx, int instance_idx) const { return (this->object_idx == object_idx) && (this->instance_idx == instance_idx); }
bool matches_object(int object_idx) const { return (this->object_idx == object_idx); }
bool matches_instance(int instance_idx) const { return (this->instance_idx == instance_idx); }
};
Instance instance;
Cache() : position(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX)) , rotation(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX))
, scale(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX)) , size(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX))
, move_label_string("") , rotate_label_string("") , scale_label_string("")
{
}
};
Cache m_cache;
#else
Vec3d m_cache_position{ 0., 0., 0. };
Vec3d m_cache_rotation{ 0., 0., 0. };
Vec3d m_cache_scale{ 100., 100., 100. };
Vec3d m_cache_size{ 0., 0., 0. };
#endif // ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
wxStaticText* m_move_Label = nullptr;
wxStaticText* m_scale_Label = nullptr;
wxStaticText* m_rotate_Label = nullptr;
#if !ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
// Needs to be updated from OnIdle?
bool m_dirty = false;
#endif // !ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
// Cached labels for the delayed update, not localized!
std::string m_new_move_label_string;
std::string m_new_rotate_label_string;
std::string m_new_scale_label_string;
Vec3d m_new_position;
Vec3d m_new_rotation;
Vec3d m_new_scale;
Vec3d m_new_size;
bool m_new_enabled;
bool m_uniform_scale {false};
PrusaLockButton* m_lock_bnt{ nullptr };
public:
ObjectManipulation(wxWindow* parent);
~ObjectManipulation() {}
void Show(const bool show) override;
bool IsShown() override;
void UpdateAndShow(const bool show) override;
void update_settings_value(const GLCanvas3D::Selection& selection);
// Called from the App to update the UI if dirty.
void update_if_dirty();
void set_uniform_scaling(const bool uniform_scale) { m_uniform_scale = uniform_scale;}
bool get_uniform_scaling() const { return m_uniform_scale; }
private:
void reset_settings_value();
// update size values after scale unit changing or "gizmos"
void update_size_value(const Vec3d& size);
// update rotation value after "gizmos"
void update_rotation_value(const Vec3d& rotation);
// change values
void change_position_value(const Vec3d& position);
void change_rotation_value(const Vec3d& rotation);
void change_scale_value(const Vec3d& scale);
void change_size_value(const Vec3d& size);
};
}}
#endif // slic3r_GUI_ObjectManipulation_hpp_
<commit_msg>Set uniformly scaling by default<commit_after>#ifndef slic3r_GUI_ObjectManipulation_hpp_
#define slic3r_GUI_ObjectManipulation_hpp_
#include <memory>
#include "GUI_ObjectSettings.hpp"
#include "GLCanvas3D.hpp"
class wxStaticText;
class PrusaLockButton;
namespace Slic3r {
namespace GUI {
class ObjectManipulation : public OG_Settings
{
#if ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
struct Cache
{
Vec3d position;
Vec3d rotation;
Vec3d scale;
Vec3d size;
std::string move_label_string;
std::string rotate_label_string;
std::string scale_label_string;
struct Instance
{
int object_idx;
int instance_idx;
Vec3d box_size;
Instance() { reset(); }
void reset() { this->object_idx = -1; this->instance_idx = -1; this->box_size = Vec3d::Zero(); }
void set(int object_idx, int instance_idx, const Vec3d& box_size) { this->object_idx = object_idx; this->instance_idx = instance_idx; this->box_size = box_size; }
bool matches(int object_idx, int instance_idx) const { return (this->object_idx == object_idx) && (this->instance_idx == instance_idx); }
bool matches_object(int object_idx) const { return (this->object_idx == object_idx); }
bool matches_instance(int instance_idx) const { return (this->instance_idx == instance_idx); }
};
Instance instance;
Cache() : position(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX)) , rotation(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX))
, scale(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX)) , size(Vec3d(DBL_MAX, DBL_MAX, DBL_MAX))
, move_label_string("") , rotate_label_string("") , scale_label_string("")
{
}
};
Cache m_cache;
#else
Vec3d m_cache_position{ 0., 0., 0. };
Vec3d m_cache_rotation{ 0., 0., 0. };
Vec3d m_cache_scale{ 100., 100., 100. };
Vec3d m_cache_size{ 0., 0., 0. };
#endif // ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
wxStaticText* m_move_Label = nullptr;
wxStaticText* m_scale_Label = nullptr;
wxStaticText* m_rotate_Label = nullptr;
#if !ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
// Needs to be updated from OnIdle?
bool m_dirty = false;
#endif // !ENABLE_IMPROVED_SIDEBAR_OBJECTS_MANIPULATION
// Cached labels for the delayed update, not localized!
std::string m_new_move_label_string;
std::string m_new_rotate_label_string;
std::string m_new_scale_label_string;
Vec3d m_new_position;
Vec3d m_new_rotation;
Vec3d m_new_scale;
Vec3d m_new_size;
bool m_new_enabled;
bool m_uniform_scale {true};
PrusaLockButton* m_lock_bnt{ nullptr };
public:
ObjectManipulation(wxWindow* parent);
~ObjectManipulation() {}
void Show(const bool show) override;
bool IsShown() override;
void UpdateAndShow(const bool show) override;
void update_settings_value(const GLCanvas3D::Selection& selection);
// Called from the App to update the UI if dirty.
void update_if_dirty();
void set_uniform_scaling(const bool uniform_scale) { m_uniform_scale = uniform_scale;}
bool get_uniform_scaling() const { return m_uniform_scale; }
private:
void reset_settings_value();
// update size values after scale unit changing or "gizmos"
void update_size_value(const Vec3d& size);
// update rotation value after "gizmos"
void update_rotation_value(const Vec3d& rotation);
// change values
void change_position_value(const Vec3d& position);
void change_rotation_value(const Vec3d& rotation);
void change_scale_value(const Vec3d& scale);
void change_size_value(const Vec3d& size);
};
}}
#endif // slic3r_GUI_ObjectManipulation_hpp_
<|endoftext|>
|
<commit_before>#include "TFile.h"
#include "TH1.h"
#include "TH1D.h"
#include "TMath.h"
#include <Riostream.h>
//
// Multiply two histos of variable bin width
//
TH1 * MultiplyHistos(TH1 *h1, TH1 *h2) {
Int_t nbins1 = h1->GetNbinsX();
Int_t nbins2 = h2->GetNbinsX();
Double_t binwidth1 = h1->GetBinWidth(1);
Double_t binwidth2 = h2->GetBinWidth(1);
if ( nbins1!=nbins2 || binwidth1!=binwidth2 ) {
cout << "Histos do not have the same binning, do not seem compatible" << endl;
return NULL;
}
//
// Get the bins & limits
Double_t *limits = new Double_t[nbins1+1];
Double_t xlow=0., binwidth=0.;
for (Int_t i=0; i<=nbins1; i++) {
binwidth = h1->GetBinWidth(i);
xlow = h1->GetBinLowEdge(i);
limits[i-1] = xlow;
}
limits[nbins1] = xlow + binwidth;
TH1D *hMultiply = new TH1D("hMultiply","hMultiply",nbins1,limits);
Double_t value=0., err=0.;
for (Int_t ibin=0; ibin<nbins1; ibin++) {
value = h1->GetBinContent(ibin) * h2->GetBinContent(ibin);
err = value * TMath::Sqrt( (h1->GetBinError(ibin)/h1->GetBinContent(ibin)) * (h1->GetBinError(ibin)/h1->GetBinContent(ibin)) +
(h2->GetBinError(ibin)/h2->GetBinContent(ibin)) * (h2->GetBinError(ibin)/h2->GetBinContent(ibin)) );
hMultiply->SetBinContent(ibin,value);
hMultiply->SetBinError(ibin,err);
}
return (TH1*)hMultiply;
}
//
// Main function
//
void ComputeEfficiencyInputFromTwoSteps (const char* recolhc10d3filename="Distributions.root",
const char* recolhc10d3histoname="RECPIDpt",
const char* simuAcclhc10d3filename="Distributions.root",
const char* simuAcclhc10d3histoname="MCAccpt",
const char* simuLimAcclhc10d4filename="",
const char* simuLimAcclhc10d4histoname="MCLimAccpt",
const char* simuAcclhc10d4filename="",
const char* simuAcclhc10d4histoname="MCAccpt",
const char* outfilename="ComputeEfficiencyInputFromTwoSteps.root")
{
TFile *recolhc10d3file = new TFile(recolhc10d3filename,"read");
TH1D *hrecolhc10d3 = (TH1D*)recolhc10d3file->Get(recolhc10d3histoname);
TFile *simuAcclhc10d3file = new TFile(simuAcclhc10d3filename,"read");
TH1D *hsimuAcclhc10d3 = (TH1D*)simuAcclhc10d3file->Get(simuAcclhc10d3histoname);
TFile *simuLimAcclhc10d4file = new TFile(simuLimAcclhc10d4filename,"read");
TH1D *hsimuLimAcclhc10d4 = (TH1D*)simuLimAcclhc10d4file->Get(simuLimAcclhc10d4histoname);
TFile *simuAcclhc10d4file = new TFile(simuAcclhc10d4filename,"read");
TH1D *hsimuAcclhc10d4 = (TH1D*)simuAcclhc10d4file->Get(simuAcclhc10d4histoname);
TFile *out = new TFile(outfilename,"recreate");
TH1D *hRecoPIDCorr = (TH1D*)MultiplyHistos(hrecolhc10d3,hsimuAcclhc10d4);
hRecoPIDCorr->SetNameTitle("hRecoPIDCorr","hRecoPIDCorr");
TH1D *hSimuCorr = (TH1D*)MultiplyHistos(hsimuAcclhc10d3,hsimuLimAcclhc10d4);
hSimuCorr->SetNameTitle("hSimuCorr","hSimuCorr");
out->cd();
hRecoPIDCorr->Write();
hSimuCorr->Write();
out->Close();
}
<commit_msg>Fix (Zaida)<commit_after>#include "TFile.h"
#include "TH1.h"
#include "TH1D.h"
#include "TMath.h"
#include <Riostream.h>
//
// Multiply two histos of variable bin width
//
TH1 * MultiplyHistos(TH1 *h1, TH1 *h2) {
Int_t nbins1 = h1->GetNbinsX();
Int_t nbins2 = h2->GetNbinsX();
Double_t binwidth1 = h1->GetBinWidth(1);
Double_t binwidth2 = h2->GetBinWidth(1);
if ( nbins1!=nbins2 || binwidth1!=binwidth2 ) {
cout << "Histos do not have the same binning, do not seem compatible" << endl;
return NULL;
}
//
// Get the bins & limits
Double_t *limits = new Double_t[nbins1+1];
Double_t xlow=0., binwidth=0.;
for (Int_t i=1; i<=nbins1; i++) {
binwidth = h1->GetBinWidth(i);
xlow = h1->GetBinLowEdge(i);
limits[i-1] = xlow;
}
limits[nbins1] = xlow + binwidth;
TH1D *hMultiply = new TH1D("hMultiply","hMultiply",nbins1,limits);
Double_t value=0., err=0.;
for (Int_t ibin=1; ibin<=nbins1; ibin++) {
value = h1->GetBinContent(ibin) * h2->GetBinContent(ibin);
err = value * TMath::Sqrt( (h1->GetBinError(ibin)/h1->GetBinContent(ibin)) * (h1->GetBinError(ibin)/h1->GetBinContent(ibin)) +
(h2->GetBinError(ibin)/h2->GetBinContent(ibin)) * (h2->GetBinError(ibin)/h2->GetBinContent(ibin)) );
hMultiply->SetBinContent(ibin,value);
hMultiply->SetBinError(ibin,err);
}
return (TH1*)hMultiply;
}
//
// Main function
//
void ComputeEfficiencyInputFromTwoSteps (const char* recolhc10d3filename="Distributions.root",
const char* recolhc10d3histoname="RECPIDpt",
const char* simuAcclhc10d3filename="Distributions.root",
const char* simuAcclhc10d3histoname="MCAccpt",
const char* simuLimAcclhc10d4filename="",
const char* simuLimAcclhc10d4histoname="MCLimAccpt",
const char* simuAcclhc10d4filename="",
const char* simuAcclhc10d4histoname="MCAccpt",
const char* outfilename="ComputeEfficiencyInputFromTwoSteps.root")
{
TFile *recolhc10d3file = new TFile(recolhc10d3filename,"read");
TH1D *hrecolhc10d3 = (TH1D*)recolhc10d3file->Get(recolhc10d3histoname);
TFile *simuAcclhc10d3file = new TFile(simuAcclhc10d3filename,"read");
TH1D *hsimuAcclhc10d3 = (TH1D*)simuAcclhc10d3file->Get(simuAcclhc10d3histoname);
TFile *simuLimAcclhc10d4file = new TFile(simuLimAcclhc10d4filename,"read");
TH1D *hsimuLimAcclhc10d4 = (TH1D*)simuLimAcclhc10d4file->Get(simuLimAcclhc10d4histoname);
TFile *simuAcclhc10d4file = new TFile(simuAcclhc10d4filename,"read");
TH1D *hsimuAcclhc10d4 = (TH1D*)simuAcclhc10d4file->Get(simuAcclhc10d4histoname);
TFile *out = new TFile(outfilename,"recreate");
TH1D *hRecoPIDCorr = (TH1D*)MultiplyHistos(hrecolhc10d3,hsimuAcclhc10d4);
hRecoPIDCorr->SetNameTitle("hRecoPIDCorr","hRecoPIDCorr");
TH1D *hSimuCorr = (TH1D*)MultiplyHistos(hsimuAcclhc10d3,hsimuLimAcclhc10d4);
hSimuCorr->SetNameTitle("hSimuCorr","hSimuCorr");
out->cd();
hRecoPIDCorr->Write();
hSimuCorr->Write();
out->Close();
}
<|endoftext|>
|
<commit_before>#include "discord.h"
#include "../logger.h"
#include "../util.h"
#include "../config.h"
#include <sleepy_discord/sleepy_discord.h>
namespace shanghai {
namespace system {
namespace {
const std::string HELP_TEXT =
R"(/help
Show this help
/server
Show server list
)";
struct DiscordConfig {
std::string DefaultReply = "";
};
} // namespace
class Discord::MyClient : public SleepyDiscord::DiscordClient {
public:
// コンストラクタ
MyClient(const DiscordConfig &conf,
const std::string &token, char numOfThreads)
: SleepyDiscord::DiscordClient(token, numOfThreads),
m_conf(conf)
{}
virtual ~MyClient() = default;
private:
DiscordConfig m_conf;
bool ExecuteCommand(SleepyDiscord::Snowflake<SleepyDiscord::Channel> ch,
std::vector<std::string> args)
{
if (args.size() == 0) {
return false;
}
if (args.at(0) == "/help") {
sendMessage(ch, HELP_TEXT);
return true;
}
else if (args.at(0) == "/server") {
std::vector<SleepyDiscord::Server> resp = getServers();
std::string msg = util::Format("{0} Server(s)",
{std::to_string(resp.size())});
for (const auto &server : resp) {
msg += '\n';
msg += server.ID;
msg += ' ';
msg += server.name;
}
sendMessage(ch, msg);
return true;
}
return false;
}
protected:
void onReady(SleepyDiscord::Ready ready) override
{
logger.Log(LogLevel::Info, "[Discord] Ready");
{
const SleepyDiscord::User &user = ready.user;
const std::string &id = user.ID;
logger.Log(LogLevel::Info, "[Discord] user %s %s bot:%s",
id.c_str(), user.username.c_str(),
user.bot ? "Yes" : "No");
}
}
void onMessage(SleepyDiscord::Message message) override
{
// ミラーマッチ対策として bot には反応しないようにする
if (message.author.bot) {
return;
}
logger.Log(LogLevel::Info, "[Discord] Message");
logger.Log(LogLevel::Info, "[Discord] %s", message.content.c_str());
// メンション時のみでフィルタ
if (message.isMentioned(getID())) {
// 半角スペースで区切ってメンションを削除
// 例: <@!123456789>
std::vector<std::string> tokens = util::Split(
message.content, ' ', true);
auto result = std::remove_if(tokens.begin(), tokens.end(),
[](const std::string &s) {
return s.find("<") == 0 && s.rfind(">") == s.size() - 1;
});
tokens.erase(result, tokens.end());
// コマンドとして実行
// できなかったらデフォルト返信
if (!ExecuteCommand(message.channelID, tokens)) {
sendMessage(message.channelID, m_conf.DefaultReply);
}
}
}
void onError(SleepyDiscord::ErrorCode errorCode,
const std::string errorMessage) override
{
logger.Log(LogLevel::Error, "[Discord] %s", errorMessage.c_str());
}
};
Discord::Discord()
{
logger.Log(LogLevel::Info, "Initialize Discord...");
bool enabled = config.GetBool({"Discord", "Enabled"});
std::string token = config.GetStr({"Discord", "Token"});
if (enabled) {
DiscordConfig dconf;
dconf.DefaultReply = config.GetStr({"Discord", "DefaultReply"});
m_client = std::make_unique<MyClient>(
dconf, token, SleepyDiscord::USE_RUN_THREAD);
m_thread = std::thread([this]() {
try {
m_client->run();
}
catch (std::exception &e) {
logger.Log(LogLevel::Error, "Discord thread error: %s", e.what());
}
});
logger.Log(LogLevel::Info, "Initialize Discord OK");
}
else {
logger.Log(LogLevel::Info, "Initialize Discord OK (Disabled)");
}
}
Discord::~Discord()
{
logger.Log(LogLevel::Info, "Finalize Discord...");
if (m_client != nullptr) {
logger.Log(LogLevel::Info, "Quit asio...");
logger.Flush();
m_client->quit();
logger.Log(LogLevel::Info, "Join discord thread...");
logger.Flush();
m_thread.join();
}
logger.Log(LogLevel::Info, "Finalize Discord OK");
}
} // namespace system
} // namespace shanghai
<commit_msg>/ch チャネルリストコマンド<commit_after>#include "discord.h"
#include "../logger.h"
#include "../util.h"
#include "../config.h"
#include <sleepy_discord/sleepy_discord.h>
namespace shanghai {
namespace system {
namespace {
const std::string HELP_TEXT =
R"(/help
Show this help
/server
Show server list
/ch <server_id>
Show channel list
)";
struct DiscordConfig {
std::string DefaultReply = "";
};
} // namespace
class Discord::MyClient : public SleepyDiscord::DiscordClient {
public:
// コンストラクタ
MyClient(const DiscordConfig &conf,
const std::string &token, char numOfThreads)
: SleepyDiscord::DiscordClient(token, numOfThreads),
m_conf(conf)
{}
virtual ~MyClient() = default;
private:
DiscordConfig m_conf;
// コマンドとして処理出来たら true
bool ExecuteCommand(SleepyDiscord::Snowflake<SleepyDiscord::Channel> ch,
std::vector<std::string> args)
{
if (args.size() == 0) {
return false;
}
if (args.at(0) == "/help") {
sendMessage(ch, HELP_TEXT);
return true;
}
else if (args.at(0) == "/server") {
std::vector<SleepyDiscord::Server> resp = getServers();
std::string msg = util::Format("{0} Server(s)",
{std::to_string(resp.size())});
for (const auto &server : resp) {
msg += '\n';
msg += server.ID;
msg += ' ';
msg += server.name;
}
sendMessage(ch, msg);
return true;
}
else if (args.at(0) == "/ch") {
if (args.size() < 2) {
sendMessage(ch, "Argument error.");
return true;
}
std::vector<SleepyDiscord::Channel> resp =
getServerChannels(args.at(1));
std::string msg = util::Format("{0} Channels(s)",
{std::to_string(resp.size())});
for (const auto &ch : resp) {
if (ch.type != SleepyDiscord::Channel::ChannelType::SERVER_TEXT) {
continue;
}
msg += '\n';
msg += ch.ID;
msg += ' ';
msg += ch.name;
}
sendMessage(ch, msg);
return true;
}
else {
return false;
}
}
protected:
void onReady(SleepyDiscord::Ready ready) override
{
logger.Log(LogLevel::Info, "[Discord] Ready");
{
const SleepyDiscord::User &user = ready.user;
const std::string &id = user.ID;
logger.Log(LogLevel::Info, "[Discord] user %s %s bot:%s",
id.c_str(), user.username.c_str(),
user.bot ? "Yes" : "No");
}
}
void onMessage(SleepyDiscord::Message message) override
{
// ミラーマッチ対策として bot には反応しないようにする
if (message.author.bot) {
return;
}
logger.Log(LogLevel::Info, "[Discord] Message");
logger.Log(LogLevel::Info, "[Discord] %s", message.content.c_str());
// メンション時のみでフィルタ
if (message.isMentioned(getID())) {
// 半角スペースで区切ってメンションを削除
// 例: <@!123456789>
std::vector<std::string> tokens = util::Split(
message.content, ' ', true);
auto result = std::remove_if(tokens.begin(), tokens.end(),
[](const std::string &s) {
return s.find("<") == 0 && s.rfind(">") == s.size() - 1;
});
tokens.erase(result, tokens.end());
// コマンドとして実行
// できなかったらデフォルト返信
if (!ExecuteCommand(message.channelID, tokens)) {
sendMessage(message.channelID, m_conf.DefaultReply);
}
}
}
void onError(SleepyDiscord::ErrorCode errorCode,
const std::string errorMessage) override
{
logger.Log(LogLevel::Error, "[Discord] %s", errorMessage.c_str());
}
};
Discord::Discord()
{
logger.Log(LogLevel::Info, "Initialize Discord...");
bool enabled = config.GetBool({"Discord", "Enabled"});
std::string token = config.GetStr({"Discord", "Token"});
if (enabled) {
DiscordConfig dconf;
dconf.DefaultReply = config.GetStr({"Discord", "DefaultReply"});
m_client = std::make_unique<MyClient>(
dconf, token, SleepyDiscord::USE_RUN_THREAD);
m_thread = std::thread([this]() {
try {
m_client->run();
}
catch (std::exception &e) {
logger.Log(LogLevel::Error, "Discord thread error: %s", e.what());
}
});
logger.Log(LogLevel::Info, "Initialize Discord OK");
}
else {
logger.Log(LogLevel::Info, "Initialize Discord OK (Disabled)");
}
}
Discord::~Discord()
{
logger.Log(LogLevel::Info, "Finalize Discord...");
if (m_client != nullptr) {
logger.Log(LogLevel::Info, "Quit asio...");
logger.Flush();
m_client->quit();
logger.Log(LogLevel::Info, "Join discord thread...");
logger.Flush();
m_thread.join();
}
logger.Log(LogLevel::Info, "Finalize Discord OK");
}
} // namespace system
} // namespace shanghai
<|endoftext|>
|
<commit_before>// Time: O(log(min(m, n)))
// Space: O(1)
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if ((nums1.size() + nums2.size()) % 2 == 1) {
return findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
} else {
return (findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2) +
findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
}
}
int findKthInTwoSortedArrays(const vector<int>& A, const vector<int>& B,
int k) {
const int m = A.size();
const int n = B.size();
// Make sure m is the smaller one.
if (m > n) {
return findKthInTwoSortedArrays(B, A, k);
}
int left = 0;
int right = m;
// Find a partition of A and B
// where min left s.t. A[left] >= B[k - 1 - left]. Thus left is the (k + 1)-th element.
while (left < right) {
int mid = left + (right - left) / 2;
if (0 <= k - 1 - mid && k - 1 - mid < n && A[mid] >= B[k - 1 - mid]) {
right = mid;
} else {
left = mid + 1;
}
}
int Ai_minus_1 = left - 1 >= 0 ? A[left - 1] : numeric_limits<int>::min();
int Bj = k - 1 - left >= 0 ? B[k - 1 - left] : numeric_limits<int>::min();
// kth element would be A[left - 1] or B[k - 1 - left].
return max(Ai_minus_1, Bj);
}
};
// Time: O(log(max(m, n)) * log(max_val - min_val))
// Space: O(1)
// Generic solution.
class Solution_Generic {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<vector<int> *> arrays{&nums1, &nums2};
if ((nums1.size() + nums2.size()) % 2 == 1) {
return findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1);
} else {
return (findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2) +
findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
}
}
private:
int findKthInSortedArrays(const vector<vector<int> *>& arrays, int k) {
int left = numeric_limits<int>::max();
int right = numeric_limits<int>::min();
for (const auto array : arrays) {
if (!array->empty()) {
left = min(left, array->front());
right = max(right, array->back());
}
}
// left xxxxxxxooooooo right, find first xo or oo
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (match(arrays, mid, k)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
bool match(const vector<vector<int> *>& arrays, int num, int target) {
int res = 0;
for (const auto array : arrays) {
if (!array->empty()) {
res += distance(upper_bound(array->cbegin(), array->cend(), num),
array->cend());
}
}
return res < target;
}
};
<commit_msg>Update median-of-two-sorted-arrays.cpp<commit_after>// Time: O(log(min(m, n)))
// Space: O(1)
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if ((nums1.size() + nums2.size()) % 2 == 1) {
return findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1);
} else {
return (findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2) +
findKthInTwoSortedArrays(nums1, nums2, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
}
}
int findKthInTwoSortedArrays(const vector<int>& A, const vector<int>& B,
int k) {
const int m = A.size();
const int n = B.size();
// Make sure m is the smaller one.
if (m > n) {
return findKthInTwoSortedArrays(B, A, k);
}
int left = 0;
int right = m;
// Find a partition of A and B
// where min left s.t. A[left - 1] >= B[k - 1 - left]. Thus left is the k-th element.
while (left < right) {
int mid = left + (right - left) / 2;
if (0 <= k - 1 - mid && k - 1 - mid < n && A[mid] >= B[k - 1 - mid]) {
right = mid;
} else {
left = mid + 1;
}
}
int Ai_minus_1 = left - 1 >= 0 ? A[left - 1] : numeric_limits<int>::min();
int Bj = k - 1 - left >= 0 ? B[k - 1 - left] : numeric_limits<int>::min();
// kth element would be A[left - 1] or B[k - 1 - left].
return max(Ai_minus_1, Bj);
}
};
// Time: O(log(max(m, n)) * log(max_val - min_val))
// Space: O(1)
// Generic solution.
class Solution_Generic {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<vector<int> *> arrays{&nums1, &nums2};
if ((nums1.size() + nums2.size()) % 2 == 1) {
return findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1);
} else {
return (findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2) +
findKthInSortedArrays(arrays, (nums1.size() + nums2.size()) / 2 + 1)) / 2.0;
}
}
private:
int findKthInSortedArrays(const vector<vector<int> *>& arrays, int k) {
int left = numeric_limits<int>::max();
int right = numeric_limits<int>::min();
for (const auto array : arrays) {
if (!array->empty()) {
left = min(left, array->front());
right = max(right, array->back());
}
}
// left xxxxxxxooooooo right, find first xo or oo
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (match(arrays, mid, k)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
bool match(const vector<vector<int> *>& arrays, int num, int target) {
int res = 0;
for (const auto array : arrays) {
if (!array->empty()) {
res += distance(upper_bound(array->cbegin(), array->cend(), num),
array->cend());
}
}
return res < target;
}
};
<|endoftext|>
|
<commit_before>#include "spritesheet_importer.h"
#include "halley/core/graphics/sprite/sprite_sheet.h"
#include "halley/tools/file/filesystem.h"
#include "halley/file/byte_serializer.h"
std::vector<Halley::Path> Halley::SpriteSheetImporter::import(const ImportingAsset& asset, Path dstDir, ProgressReporter reporter, AssetCollector collector)
{
SpriteSheet sheet;
Path dstFile = dstDir / asset.inputFiles[0].name.replaceExtension("");
sheet.loadJson(gsl::as_bytes(gsl::span<const Byte>(asset.inputFiles.at(0).data)));
FileSystem::writeFile(dstFile, Serializer::toBytes(sheet));
return { dstFile };
}
<commit_msg>Fix spritesheet importing.<commit_after>#include "spritesheet_importer.h"
#include "halley/core/graphics/sprite/sprite_sheet.h"
#include "halley/tools/file/filesystem.h"
#include "halley/file/byte_serializer.h"
std::vector<Halley::Path> Halley::SpriteSheetImporter::import(const ImportingAsset& asset, Path dstDir, ProgressReporter reporter, AssetCollector collector)
{
SpriteSheet sheet;
Path dstFile = asset.inputFiles[0].name.replaceExtension("");
sheet.loadJson(gsl::as_bytes(gsl::span<const Byte>(asset.inputFiles.at(0).data)));
FileSystem::writeFile(dstDir / dstFile, Serializer::toBytes(sheet));
return { dstFile };
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// CS372C++11Spring2014
//
// Created by Chris Hartman on 1/22/14.
// Copyright (c) 2014 Chris Hartman. All rights reserved.
//
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <memory>
using std::unique_ptr;
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
class SpaceObject
{
public:
virtual void speak() const=0;
virtual bool isDead() const=0;
virtual ~SpaceObject()
{}
};
class Bullet : public SpaceObject
{
public:
Bullet(int value):_value(value)
{
cout << "Made a Bullet" << endl;
}
~Bullet()
{
cout << "Destroyed a Bullet:" << _value << endl;
}
virtual void speak() const override
{
cout << "I'm a bullet with value " << _value << endl;
}
virtual bool isDead() const override
{
return _value%2==1;
}
private:
int _value;
};
class Star : public SpaceObject
{
public:
Star()
{
cout << "Made a Star" << endl;
}
~Star()
{
cout << "Destroyed a Star " << endl;
}
virtual void speak() const override
{
cout << "I'm a star!" << endl;
}
virtual bool isDead() const override
{
return false;
}
private:
};
bool killIt(const unique_ptr<SpaceObject> & p)
{
return p->isDead();
}
void unique_ptr_main()
{
vector<unique_ptr<SpaceObject>> v;
v.push_back(make_unique<Star>());
v.push_back(make_unique<Star>());
for(int ii=0;ii<10;++ii)
v.push_back(make_unique<Bullet>(ii));
for( auto & o : v)
o->speak();
cout << "Killing objects " << endl;
v.erase(remove_if(v.begin(),v.end(),killIt),v.end());
for( auto &o : v)
o->speak();
}
<commit_msg>Changed killIt to use a lambda function.<commit_after>//
// main.cpp
// CS372C++11Spring2014
//
// Created by Chris Hartman on 1/22/14.
// Copyright (c) 2014 Chris Hartman. All rights reserved.
//
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <memory>
using std::unique_ptr;
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
class SpaceObject
{
public:
virtual void speak() const=0;
virtual bool isDead() const=0;
virtual ~SpaceObject()
{}
};
class Bullet : public SpaceObject
{
public:
Bullet(int value):_value(value)
{
cout << "Made a Bullet" << endl;
}
~Bullet()
{
cout << "Destroyed a Bullet:" << _value << endl;
}
virtual void speak() const override
{
cout << "I'm a bullet with value " << _value << endl;
}
virtual bool isDead() const override
{
return _value%2==1;
}
private:
int _value;
};
class Star : public SpaceObject
{
public:
Star()
{
cout << "Made a Star" << endl;
}
~Star()
{
cout << "Destroyed a Star " << endl;
}
virtual void speak() const override
{
cout << "I'm a star!" << endl;
}
virtual bool isDead() const override
{
return false;
}
private:
};
void unique_ptr_main()
{
vector<unique_ptr<SpaceObject>> v;
v.push_back(make_unique<Star>());
v.push_back(make_unique<Star>());
for(int ii=0;ii<10;++ii)
v.push_back(make_unique<Bullet>(ii));
for( auto & o : v)
o->speak();
cout << "Killing objects " << endl;
v.erase(remove_if(v.begin(),v.end(),[](unique_ptr<SpaceObject> &p){return p->isDead();}),v.end());
for( auto &o : v)
o->speak();
}
<|endoftext|>
|
<commit_before>//
// main.cpp
// CS372C++11Spring2014
//
// Created by Chris Hartman on 1/22/14.
// Copyright (c) 2014 Chris Hartman. All rights reserved.
//
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <memory>
using std::unique_ptr;
#include <functional>
using std::function;
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
class SpaceObject
{
public:
virtual void speak() const=0;
virtual bool isDead(int) const=0;
virtual ~SpaceObject()
{}
};
class Bullet : public SpaceObject
{
public:
Bullet(int value):_value(value)
{
cout << "Made a Bullet" << endl;
}
~Bullet()
{
cout << "Destroyed a Bullet:" << _value << endl;
}
virtual void speak() const override
{
cout << "I'm a bullet with value " << _value << endl;
}
virtual bool isDead(int modulus) const override
{
return _value%modulus==0;
}
private:
int _value;
};
class Star : public SpaceObject
{
public:
Star()
{
cout << "Made a Star" << endl;
}
~Star()
{
cout << "Destroyed a Star " << endl;
}
virtual void speak() const override
{
cout << "I'm a star!" << endl;
}
virtual bool isDead(int) const override
{
return false;
}
private:
};
void unique_ptr_main()
{
vector<unique_ptr<SpaceObject>> v;
v.push_back(make_unique<Star>());
v.push_back(make_unique<Star>());
for(int ii=0;ii<10;++ii)
v.push_back(make_unique<Bullet>(ii));
for( auto & o : v)
o->speak();
cout << "Killing objects " << endl;
int m=3;
auto killIt = [m](unique_ptr<SpaceObject> &p){return p->isDead(m);};
function< bool (unique_ptr<SpaceObject> &p)> x = killIt;
using std::placeholders::_1;
v.erase(remove_if(v.begin(),v.end(),x),v.end());
for( auto &o : v)
o->speak();
}
<commit_msg>Added const in lambda killIt<commit_after>//
// main.cpp
// CS372C++11Spring2014
//
// Created by Chris Hartman on 1/22/14.
// Copyright (c) 2014 Chris Hartman. All rights reserved.
//
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <memory>
using std::unique_ptr;
#include <functional>
using std::function;
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
class SpaceObject
{
public:
virtual void speak() const=0;
virtual bool isDead(int) const=0;
virtual ~SpaceObject()
{}
};
class Bullet : public SpaceObject
{
public:
Bullet(int value):_value(value)
{
cout << "Made a Bullet" << endl;
}
~Bullet()
{
cout << "Destroyed a Bullet:" << _value << endl;
}
virtual void speak() const override
{
cout << "I'm a bullet with value " << _value << endl;
}
virtual bool isDead(int modulus) const override
{
return _value%modulus==0;
}
private:
int _value;
};
class Star : public SpaceObject
{
public:
Star()
{
cout << "Made a Star" << endl;
}
~Star()
{
cout << "Destroyed a Star " << endl;
}
virtual void speak() const override
{
cout << "I'm a star!" << endl;
}
virtual bool isDead(int) const override
{
return false;
}
private:
};
void unique_ptr_main()
{
vector<unique_ptr<SpaceObject>> v;
v.push_back(make_unique<Star>());
v.push_back(make_unique<Star>());
for(int ii=0;ii<10;++ii)
v.push_back(make_unique<Bullet>(ii));
for( auto & o : v)
o->speak();
cout << "Killing objects " << endl;
int m=3;
auto killIt = [m](const unique_ptr<SpaceObject> &p){return p->isDead(m);};
function< bool (const unique_ptr<SpaceObject> &p)> x = killIt;
using std::placeholders::_1;
v.erase(remove_if(v.begin(),v.end(),x),v.end());
for( auto &o : v)
o->speak();
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "visitor.h"
#include <vespa/document/fieldset/fieldsets.h>
#include <vespa/vespalib/util/array.hpp>
#include <climits>
namespace storage::api {
IMPLEMENT_COMMAND(CreateVisitorCommand, CreateVisitorReply)
IMPLEMENT_REPLY(CreateVisitorReply)
IMPLEMENT_COMMAND(DestroyVisitorCommand, DestroyVisitorReply)
IMPLEMENT_REPLY(DestroyVisitorReply)
IMPLEMENT_COMMAND(VisitorInfoCommand, VisitorInfoReply)
IMPLEMENT_REPLY(VisitorInfoReply)
CreateVisitorCommand::CreateVisitorCommand(document::BucketSpace bucketSpace,
vespalib::stringref libraryName,
vespalib::stringref instanceId,
vespalib::stringref docSelection)
: StorageCommand(MessageType::VISITOR_CREATE),
_bucketSpace(bucketSpace),
_libName(libraryName),
_params(),
_controlDestination(),
_dataDestination(),
_docSelection(docSelection),
_buckets(),
_fromTime(0),
_toTime(api::MAX_TIMESTAMP),
_visitorCmdId(getMsgId()),
_instanceId(instanceId),
_visitorId(0),
_visitRemoves(false),
_fieldSet(document::AllFields::NAME),
_visitInconsistentBuckets(false),
_queueTimeout(2000ms),
_maxPendingReplyCount(2),
_version(50),
_maxBucketsPerVisitor(1)
{
}
CreateVisitorCommand::CreateVisitorCommand(const CreateVisitorCommand& o)
: StorageCommand(o),
_bucketSpace(o._bucketSpace),
_libName(o._libName),
_params(o._params),
_controlDestination(o._controlDestination),
_dataDestination(o._dataDestination),
_docSelection(o._docSelection),
_buckets(o._buckets),
_fromTime(o._fromTime),
_toTime(o._toTime),
_visitorCmdId(getMsgId()),
_instanceId(o._instanceId),
_visitorId(o._visitorId),
_visitRemoves(o._visitRemoves),
_fieldSet(o._fieldSet),
_visitInconsistentBuckets(o._visitInconsistentBuckets),
_queueTimeout(o._queueTimeout),
_maxPendingReplyCount(o._maxPendingReplyCount),
_version(o._version),
_maxBucketsPerVisitor(o._maxBucketsPerVisitor)
{
}
CreateVisitorCommand::~CreateVisitorCommand() = default;
document::Bucket
CreateVisitorCommand::getBucket() const
{
return document::Bucket(_bucketSpace, document::BucketId());
}
void
CreateVisitorCommand::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
out << "CreateVisitorCommand(" << _libName << ", " << _docSelection;
if (verbose) {
out << ") {";
out << "\n" << indent << " Library name: '" << _libName << "'";
out << "\n" << indent << " Instance Id: '" << _instanceId << "'";
out << "\n" << indent << " Control Destination: '" << _controlDestination << "'";
out << "\n" << indent << " Data Destination: '" << _dataDestination << "'";
out << "\n" << indent << " Doc Selection: '" << _docSelection << "'";
out << "\n" << indent << " Max pending: '" << _maxPendingReplyCount << "'";
out << "\n" << indent << " Timeout: " << vespalib::count_ms(getTimeout()) << " ms";
out << "\n" << indent << " Queue timeout: " << vespalib::count_ms(_queueTimeout) << " ms";
out << "\n" << indent << " VisitorDispatcher version: '" << _version << "'";
if (visitRemoves()) {
out << "\n" << indent << " Visiting remove entries too";
}
out << "\n" << indent << " Returning fields: " << _fieldSet;
if (visitInconsistentBuckets()) {
out << "\n" << indent << " Visiting inconsistent buckets";
}
out << "\n" << indent << " From " << _fromTime << " to " << _toTime;
for (std::vector<document::BucketId>::const_iterator it
= _buckets.begin(); it != _buckets.end(); ++it)
{
out << "\n" << indent << " " << (*it);
}
out << "\n" << indent << " ";
_params.print(out, verbose, indent + " ");
out << "\n" << indent << " Max buckets: '" << _maxBucketsPerVisitor << "'";
out << "\n" << indent << "} : ";
StorageCommand::print(out, verbose, indent);
} else if (_buckets.size() == 2) {
out << ", top " << _buckets[0] << ", progress " << _buckets[1] << ")";
} else {
out << ", " << _buckets.size() << " buckets)";
}
}
CreateVisitorReply::CreateVisitorReply(const CreateVisitorCommand& cmd)
: StorageReply(cmd),
_lastBucket(document::BucketId(INT_MAX))
{
}
void
CreateVisitorReply::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
out << "CreateVisitorReply(last=" << _lastBucket << ")";
if (verbose) {
out << " : ";
StorageReply::print(out, verbose, indent);
}
}
DestroyVisitorCommand::DestroyVisitorCommand(vespalib::stringref instanceId)
: StorageCommand(MessageType::VISITOR_DESTROY),
_instanceId(instanceId)
{
}
void
DestroyVisitorCommand::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "DestroyVisitorCommand(" << _instanceId << ")";
if (verbose) {
out << " : ";
StorageCommand::print(out, verbose, indent);
}
}
DestroyVisitorReply::DestroyVisitorReply(const DestroyVisitorCommand& cmd)
: StorageReply(cmd)
{
}
void
DestroyVisitorReply::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "DestroyVisitorReply()";
if (verbose) {
out << " : ";
StorageReply::print(out, verbose, indent);
}
}
VisitorInfoCommand::VisitorInfoCommand()
: StorageCommand(MessageType::VISITOR_INFO),
_completed(false),
_bucketsCompleted(),
_error(ReturnCode::OK)
{
}
VisitorInfoCommand::~VisitorInfoCommand() = default;
void
VisitorInfoCommand::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "VisitorInfoCommand(";
if (_completed) { out << "completed"; }
if (_error.failed()) {
out << _error;
}
if (verbose) {
out << ") : ";
StorageCommand::print(out, verbose, indent);
} else {
if (!_bucketsCompleted.empty()) {
out << _bucketsCompleted.size() << " buckets completed";
}
out << ")";
}
}
VisitorInfoReply::VisitorInfoReply(const VisitorInfoCommand& cmd)
: StorageReply(cmd),
_completed(cmd.visitorCompleted())
{
}
void
VisitorInfoReply::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "VisitorInfoReply(";
if (_completed) { out << "completed"; }
if (verbose) {
out << ") : ";
StorageReply::print(out, verbose, indent);
} else {
out << ")";
}
}
std::ostream&
operator<<(std::ostream& out, const VisitorInfoCommand::BucketTimestampPair& pair) {
return out << pair.bucketId << " - " << pair.timestamp;
}
}
<commit_msg>Restore include of ostream in storageapi.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "visitor.h"
#include <vespa/document/fieldset/fieldsets.h>
#include <vespa/vespalib/util/array.hpp>
#include <climits>
#include <ostream>
namespace storage::api {
IMPLEMENT_COMMAND(CreateVisitorCommand, CreateVisitorReply)
IMPLEMENT_REPLY(CreateVisitorReply)
IMPLEMENT_COMMAND(DestroyVisitorCommand, DestroyVisitorReply)
IMPLEMENT_REPLY(DestroyVisitorReply)
IMPLEMENT_COMMAND(VisitorInfoCommand, VisitorInfoReply)
IMPLEMENT_REPLY(VisitorInfoReply)
CreateVisitorCommand::CreateVisitorCommand(document::BucketSpace bucketSpace,
vespalib::stringref libraryName,
vespalib::stringref instanceId,
vespalib::stringref docSelection)
: StorageCommand(MessageType::VISITOR_CREATE),
_bucketSpace(bucketSpace),
_libName(libraryName),
_params(),
_controlDestination(),
_dataDestination(),
_docSelection(docSelection),
_buckets(),
_fromTime(0),
_toTime(api::MAX_TIMESTAMP),
_visitorCmdId(getMsgId()),
_instanceId(instanceId),
_visitorId(0),
_visitRemoves(false),
_fieldSet(document::AllFields::NAME),
_visitInconsistentBuckets(false),
_queueTimeout(2000ms),
_maxPendingReplyCount(2),
_version(50),
_maxBucketsPerVisitor(1)
{
}
CreateVisitorCommand::CreateVisitorCommand(const CreateVisitorCommand& o)
: StorageCommand(o),
_bucketSpace(o._bucketSpace),
_libName(o._libName),
_params(o._params),
_controlDestination(o._controlDestination),
_dataDestination(o._dataDestination),
_docSelection(o._docSelection),
_buckets(o._buckets),
_fromTime(o._fromTime),
_toTime(o._toTime),
_visitorCmdId(getMsgId()),
_instanceId(o._instanceId),
_visitorId(o._visitorId),
_visitRemoves(o._visitRemoves),
_fieldSet(o._fieldSet),
_visitInconsistentBuckets(o._visitInconsistentBuckets),
_queueTimeout(o._queueTimeout),
_maxPendingReplyCount(o._maxPendingReplyCount),
_version(o._version),
_maxBucketsPerVisitor(o._maxBucketsPerVisitor)
{
}
CreateVisitorCommand::~CreateVisitorCommand() = default;
document::Bucket
CreateVisitorCommand::getBucket() const
{
return document::Bucket(_bucketSpace, document::BucketId());
}
void
CreateVisitorCommand::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
out << "CreateVisitorCommand(" << _libName << ", " << _docSelection;
if (verbose) {
out << ") {";
out << "\n" << indent << " Library name: '" << _libName << "'";
out << "\n" << indent << " Instance Id: '" << _instanceId << "'";
out << "\n" << indent << " Control Destination: '" << _controlDestination << "'";
out << "\n" << indent << " Data Destination: '" << _dataDestination << "'";
out << "\n" << indent << " Doc Selection: '" << _docSelection << "'";
out << "\n" << indent << " Max pending: '" << _maxPendingReplyCount << "'";
out << "\n" << indent << " Timeout: " << vespalib::count_ms(getTimeout()) << " ms";
out << "\n" << indent << " Queue timeout: " << vespalib::count_ms(_queueTimeout) << " ms";
out << "\n" << indent << " VisitorDispatcher version: '" << _version << "'";
if (visitRemoves()) {
out << "\n" << indent << " Visiting remove entries too";
}
out << "\n" << indent << " Returning fields: " << _fieldSet;
if (visitInconsistentBuckets()) {
out << "\n" << indent << " Visiting inconsistent buckets";
}
out << "\n" << indent << " From " << _fromTime << " to " << _toTime;
for (std::vector<document::BucketId>::const_iterator it
= _buckets.begin(); it != _buckets.end(); ++it)
{
out << "\n" << indent << " " << (*it);
}
out << "\n" << indent << " ";
_params.print(out, verbose, indent + " ");
out << "\n" << indent << " Max buckets: '" << _maxBucketsPerVisitor << "'";
out << "\n" << indent << "} : ";
StorageCommand::print(out, verbose, indent);
} else if (_buckets.size() == 2) {
out << ", top " << _buckets[0] << ", progress " << _buckets[1] << ")";
} else {
out << ", " << _buckets.size() << " buckets)";
}
}
CreateVisitorReply::CreateVisitorReply(const CreateVisitorCommand& cmd)
: StorageReply(cmd),
_lastBucket(document::BucketId(INT_MAX))
{
}
void
CreateVisitorReply::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
out << "CreateVisitorReply(last=" << _lastBucket << ")";
if (verbose) {
out << " : ";
StorageReply::print(out, verbose, indent);
}
}
DestroyVisitorCommand::DestroyVisitorCommand(vespalib::stringref instanceId)
: StorageCommand(MessageType::VISITOR_DESTROY),
_instanceId(instanceId)
{
}
void
DestroyVisitorCommand::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "DestroyVisitorCommand(" << _instanceId << ")";
if (verbose) {
out << " : ";
StorageCommand::print(out, verbose, indent);
}
}
DestroyVisitorReply::DestroyVisitorReply(const DestroyVisitorCommand& cmd)
: StorageReply(cmd)
{
}
void
DestroyVisitorReply::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "DestroyVisitorReply()";
if (verbose) {
out << " : ";
StorageReply::print(out, verbose, indent);
}
}
VisitorInfoCommand::VisitorInfoCommand()
: StorageCommand(MessageType::VISITOR_INFO),
_completed(false),
_bucketsCompleted(),
_error(ReturnCode::OK)
{
}
VisitorInfoCommand::~VisitorInfoCommand() = default;
void
VisitorInfoCommand::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "VisitorInfoCommand(";
if (_completed) { out << "completed"; }
if (_error.failed()) {
out << _error;
}
if (verbose) {
out << ") : ";
StorageCommand::print(out, verbose, indent);
} else {
if (!_bucketsCompleted.empty()) {
out << _bucketsCompleted.size() << " buckets completed";
}
out << ")";
}
}
VisitorInfoReply::VisitorInfoReply(const VisitorInfoCommand& cmd)
: StorageReply(cmd),
_completed(cmd.visitorCompleted())
{
}
void
VisitorInfoReply::print(std::ostream& out, bool verbose, const std::string& indent) const
{
out << "VisitorInfoReply(";
if (_completed) { out << "completed"; }
if (verbose) {
out << ") : ";
StorageReply::print(out, verbose, indent);
} else {
out << ")";
}
}
std::ostream&
operator<<(std::ostream& out, const VisitorInfoCommand::BucketTimestampPair& pair) {
return out << pair.bucketId << " - " << pair.timestamp;
}
}
<|endoftext|>
|
<commit_before>// Source : https://oj.leetcode.com/problems/wildcard-matching/
// Author : Hao Chen
// Date : 2014-07-19
/**********************************************************************************
*
* Implement wildcard pattern matching with support for '?' and '*'.
*
* '?' Matches any single character.
* '*' Matches any sequence of characters (including the empty sequence).
*
* The matching should cover the entire input string (not partial).
*
* The function prototype should be:
* bool isMatch(const char *s, const char *p)
*
* Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa", "*") → true
* isMatch("aa", "a*") → true
* isMatch("ab", "?*") → true
* isMatch("aab", "c*a*b") → false
*
*
**********************************************************************************/
#include <iostream>
#include <string>
using namespace std;
bool isMatch(const char *s, const char *p) {
bool star = false;
const char *s1, *p1;
while( *s && (*p || star) ){
if (*p=='?' || *s == *p){
s++; p++;
}else if (*p=='*'){
//skip the "*", and mark a flag
star = true;
p++;
//edge case
if (*p=='\0') return true;
//use s1 and p1 to store where the "*" match starts.
s1 = s;
p1 = p;
}else{
if (star==false) return false;
// if meet "*" previously, but the *s != *p
// reset the p, using '*' to match this situation
p = p1;
s = ++s1;
}
}
//edge case: "s" is done, but "p" still have chars.
if (*s=='\0') {
while (*p=='*') p++; //filter all of '*'
if (*p=='\0') return true;
}
return false;
}
int main(int argc, char** argv)
{
const char *s = "aab";
const char *p = "a*a*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abbb";
p = "a*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abb";
p = "a*bb";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abddbbb";
p = "a*d*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abdb";
p = "a**";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "a";
p = "a**";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
if (argc>2){
s = argv[1];
p = argv[2];
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
}
return 0;
}
<commit_msg>fix<commit_after>// Source : https://oj.leetcode.com/problems/wildcard-matching/
// Author : Hao Chen
// Date : 2014-07-19
/**********************************************************************************
*
* Implement wildcard pattern matching with support for '?' and '*'.
*
* '?' Matches any single character.
* '*' Matches any sequence of characters (including the empty sequence).
*
* The matching should cover the entire input string (not partial).
*
* The function prototype should be:
* bool isMatch(const char *s, const char *p)
*
* Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa", "*") → true
* isMatch("aa", "a*") → true
* isMatch("ab", "?*") → true
* isMatch("aab", "c*a*b") → false
*
*
**********************************************************************************/
#include <iostream>
#include <string>
using namespace std;
bool isMatch(const char *s, const char *p) {
const char *last_s = NULL;
const char *last_p = NULL;
while (*s != '\0') {
// Here, '*' in the pattern is ungreedy. This means we are trying to
// build one or more one-character-to-one-character mappings between
// the pattern string and the target string as much as possible.
if (*p == '*') {
last_s = s;
last_p = p++;
} else if (*p == '?' || *p == *s) {
s++;
p++;
} else if (last_s) {
// Why not use stacks? Because '*' is ungreedy and it can match any
// character. If s becomes '\0' and the rest of p contains
// characters other than '*', that means:
// len(original_s) < len(original_p) - count(original_p, '*')
s = ++last_s;
p = last_p + 1;
} else {
return false;
}
}
while (*p == '*') p++;
return *p == '\0';
}
int main(int argc, char** argv)
{
const char *s = "aab";
const char *p = "a*a*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abbb";
p = "a*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abb";
p = "a*bb";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abddbbb";
p = "a*d*b";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "abdb";
p = "a**";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "a";
p = "a**";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
s = "*aa";
p = "*a";
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
if (argc>2){
s = argv[1];
p = argv[2];
cout << s << ", " << p << " : " << isMatch(s, p) << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.4 2003/11/21 17:34:04 knoaman
* PSVI update
*
* Revision 1.3 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.2 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSWildCard.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSParticle: Constructors and Destructor
// ---------------------------------------------------------------------------
XSParticle::XSParticle(TERM_TYPE termType,
XSModel* const xsModel,
XSObject* const particleTerm,
int minOccurs,
int maxOccurs,
MemoryManager* const manager)
: XSObject(XSConstants::PARTICLE, xsModel, manager)
, fTermType(termType)
, fMinOccurs(minOccurs)
, fMaxOccurs(maxOccurs)
, fTerm(particleTerm)
{
}
XSParticle::~XSParticle()
{
if (fTerm && (fTermType == TERM_MODELGROUP))
delete ((XSModelGroup*) fTerm);
}
// ---------------------------------------------------------------------------
// XSParticle: methods
// ---------------------------------------------------------------------------
XSElementDeclaration *XSParticle::getElementTerm()
{
if (fTermType == TERM_ELEMENT)
return (XSElementDeclaration*) fTerm;
return 0;
}
XSModelGroup *XSParticle::getModelGroupTerm()
{
if (fTermType == TERM_MODELGROUP)
return (XSModelGroup*) fTerm;
return 0;
}
XSWildcard *XSParticle::getWildcardTerm()
{
if (fTermType == TERM_WILDCARD)
return (XSWildcard*) fTerm;
return 0;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>fixed typo in include<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.5 2003/11/24 10:30:53 gareth
* fixed typo in include
*
* Revision 1.4 2003/11/21 17:34:04 knoaman
* PSVI update
*
* Revision 1.3 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.2 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/XSParticle.hpp>
#include <xercesc/framework/psvi/XSElementDeclaration.hpp>
#include <xercesc/framework/psvi/XSModelGroup.hpp>
#include <xercesc/framework/psvi/XSWildcard.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSParticle: Constructors and Destructor
// ---------------------------------------------------------------------------
XSParticle::XSParticle(TERM_TYPE termType,
XSModel* const xsModel,
XSObject* const particleTerm,
int minOccurs,
int maxOccurs,
MemoryManager* const manager)
: XSObject(XSConstants::PARTICLE, xsModel, manager)
, fTermType(termType)
, fMinOccurs(minOccurs)
, fMaxOccurs(maxOccurs)
, fTerm(particleTerm)
{
}
XSParticle::~XSParticle()
{
if (fTerm && (fTermType == TERM_MODELGROUP))
delete ((XSModelGroup*) fTerm);
}
// ---------------------------------------------------------------------------
// XSParticle: methods
// ---------------------------------------------------------------------------
XSElementDeclaration *XSParticle::getElementTerm()
{
if (fTermType == TERM_ELEMENT)
return (XSElementDeclaration*) fTerm;
return 0;
}
XSModelGroup *XSParticle::getModelGroupTerm()
{
if (fTermType == TERM_MODELGROUP)
return (XSModelGroup*) fTerm;
return 0;
}
XSWildcard *XSParticle::getWildcardTerm()
{
if (fTermType == TERM_WILDCARD)
return (XSWildcard*) fTerm;
return 0;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#include <stan/math/prim/mat/fun/to_array_1d.hpp>
#include <stan/math/prim/mat/fun/to_vector.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/rev/mat/functor/jacobian.hpp>
#include <kinsol/kinsol.h>
#include <sunmatrix/sunmatrix_dense.h>
#include <sunlinsol/sunlinsol_dense.h>
#include <nvector/nvector_serial.h>
#include <vector>
namespace stan {
namespace math {
/**
* Default Jacobian builder using revser-mode autodiff.
*/
struct kinsol_J_f {
template <typename F>
inline int operator()(const F& f, const Eigen::VectorXd& x,
const Eigen::VectorXd& y,
const std::vector<double>& dat,
const std::vector<int>& dat_int, std::ostream* msgs,
const double x_sun[], SUNMatrix J) const {
size_t N = x.size();
const std::vector<double> x_vec(x_sun, x_sun + N);
system_functor<F, double, double, 1> system(f, x, y, dat, dat_int, msgs);
Eigen::VectorXd fx;
Eigen::MatrixXd Jac;
jacobian(system, to_vector(x_vec), fx, Jac);
for (int i = 0; i < Jac.rows(); i++)
for (int j = 0; j < Jac.cols(); j++)
SM_ELEMENT_D(J, i, j) = Jac(i, j);
return 0;
}
};
/**
* KINSOL algebraic system data holder.
* Based on cvodes_ode_data.
*
* @tparam F1 functor type for system function.
* @tparam F2 functor type for jacobian function. Default is 0.
* If 0, use rev mode autodiff to compute the Jacobian.
*/
template <typename F1, typename F2>
class kinsol_system_data {
const F1& f_;
const F2& J_f_;
const Eigen::VectorXd& x_;
const Eigen::VectorXd& y_;
const size_t N_;
const std::vector<double>& dat_;
const std::vector<int>& dat_int_;
std::ostream* msgs_;
typedef kinsol_system_data<F1, F2> system_data;
public:
N_Vector nv_x_;
SUNMatrix J_;
SUNLinearSolver LS_;
/* Constructor */
kinsol_system_data(const F1& f, const F2& J_f, const Eigen::VectorXd& x,
const Eigen::VectorXd& y, const std::vector<double>& dat,
const std::vector<int>& dat_int, std::ostream* msgs)
: f_(f),
J_f_(J_f),
x_(x),
y_(y),
dat_(dat),
dat_int_(dat_int),
msgs_(msgs),
N_(x.size()),
nv_x_(N_VMake_Serial(N_, &to_array_1d(x_)[0])),
J_(SUNDenseMatrix(N_, N_)),
LS_(SUNLinSol_Dense(nv_x_, J_)) {}
~kinsol_system_data() {
N_VDestroy_Serial(nv_x_);
SUNLinSolFree(LS_);
SUNMatDestroy(J_);
}
/* Implements the user-defined function passed to KINSOL. */
static int kinsol_f_system(N_Vector x, N_Vector f, void* user_data) {
const system_data* explicit_system
= static_cast<const system_data*>(user_data);
explicit_system->f_system(NV_DATA_S(x), NV_DATA_S(f));
return 0;
}
/**
* Implements the function of type CVDlsJacFn which is the user-defined
* callbacks for KINSOL to calculate the jacobian of the system.
* The Jacobian is stored in column major format.
*
* REMARK - tmp1 and tmp2 are pointers to memory allocated for variables
* of type N_Vector which can be used by KINJacFN (the function which
* computes the Jacobian) as temporary storage or work space.
* See
* https://computation.llnl.gov/sites/default/files/public/kin_guide-dev.pdf,
* page 55.
*/
static int kinsol_jacobian(N_Vector x, N_Vector f, SUNMatrix J,
void* user_data, N_Vector tmp1, N_Vector tmp2) {
return
static_cast<const system_data*>(user_data)->
jacobian_states(NV_DATA_S(x), J);
}
private:
/**
* Calculates the root function, using the user-supplied functor
* for a given value of x.
*/
inline void f_system(const double x[], double f[]) const {
const std::vector<double> x_vec(x, x + N_);
const std::vector<double>& f_vec
= to_array_1d(f_(to_vector(x_vec), y_, dat_, dat_int_, msgs_));
std::move(f_vec.begin(), f_vec.end(), f);
}
/**
* Calculate the Jacobian of the system function with respect to x
* using the method specified by J_f_.
* By default, J_f is constructed as a method that computes the
* Jacobian with reverse-mode autodiff.
*/
inline int jacobian_states(const double x[], SUNMatrix J) const {
return J_f_(f_, x_, y_, dat_, dat_int_, msgs_, x, J);
}
};
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags/RELEASE_500/final)<commit_after>#ifndef STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#define STAN_MATH_REV_MAT_FUNCTOR_KINSOL_DATA_HPP
#include <stan/math/prim/mat/fun/to_array_1d.hpp>
#include <stan/math/prim/mat/fun/to_vector.hpp>
#include <stan/math/rev/mat/functor/algebra_system.hpp>
#include <stan/math/rev/mat/functor/jacobian.hpp>
#include <kinsol/kinsol.h>
#include <sunmatrix/sunmatrix_dense.h>
#include <sunlinsol/sunlinsol_dense.h>
#include <nvector/nvector_serial.h>
#include <vector>
namespace stan {
namespace math {
/**
* Default Jacobian builder using revser-mode autodiff.
*/
struct kinsol_J_f {
template <typename F>
inline int operator()(const F& f, const Eigen::VectorXd& x,
const Eigen::VectorXd& y,
const std::vector<double>& dat,
const std::vector<int>& dat_int, std::ostream* msgs,
const double x_sun[], SUNMatrix J) const {
size_t N = x.size();
const std::vector<double> x_vec(x_sun, x_sun + N);
system_functor<F, double, double, 1> system(f, x, y, dat, dat_int, msgs);
Eigen::VectorXd fx;
Eigen::MatrixXd Jac;
jacobian(system, to_vector(x_vec), fx, Jac);
for (int i = 0; i < Jac.rows(); i++)
for (int j = 0; j < Jac.cols(); j++)
SM_ELEMENT_D(J, i, j) = Jac(i, j);
return 0;
}
};
/**
* KINSOL algebraic system data holder.
* Based on cvodes_ode_data.
*
* @tparam F1 functor type for system function.
* @tparam F2 functor type for jacobian function. Default is 0.
* If 0, use rev mode autodiff to compute the Jacobian.
*/
template <typename F1, typename F2>
class kinsol_system_data {
const F1& f_;
const F2& J_f_;
const Eigen::VectorXd& x_;
const Eigen::VectorXd& y_;
const size_t N_;
const std::vector<double>& dat_;
const std::vector<int>& dat_int_;
std::ostream* msgs_;
typedef kinsol_system_data<F1, F2> system_data;
public:
N_Vector nv_x_;
SUNMatrix J_;
SUNLinearSolver LS_;
/* Constructor */
kinsol_system_data(const F1& f, const F2& J_f, const Eigen::VectorXd& x,
const Eigen::VectorXd& y, const std::vector<double>& dat,
const std::vector<int>& dat_int, std::ostream* msgs)
: f_(f),
J_f_(J_f),
x_(x),
y_(y),
dat_(dat),
dat_int_(dat_int),
msgs_(msgs),
N_(x.size()),
nv_x_(N_VMake_Serial(N_, &to_array_1d(x_)[0])),
J_(SUNDenseMatrix(N_, N_)),
LS_(SUNLinSol_Dense(nv_x_, J_)) {}
~kinsol_system_data() {
N_VDestroy_Serial(nv_x_);
SUNLinSolFree(LS_);
SUNMatDestroy(J_);
}
/* Implements the user-defined function passed to KINSOL. */
static int kinsol_f_system(N_Vector x, N_Vector f, void* user_data) {
const system_data* explicit_system
= static_cast<const system_data*>(user_data);
explicit_system->f_system(NV_DATA_S(x), NV_DATA_S(f));
return 0;
}
/**
* Implements the function of type CVDlsJacFn which is the user-defined
* callbacks for KINSOL to calculate the jacobian of the system.
* The Jacobian is stored in column major format.
*
* REMARK - tmp1 and tmp2 are pointers to memory allocated for variables
* of type N_Vector which can be used by KINJacFN (the function which
* computes the Jacobian) as temporary storage or work space.
* See
* https://computation.llnl.gov/sites/default/files/public/kin_guide-dev.pdf,
* page 55.
*/
static int kinsol_jacobian(N_Vector x, N_Vector f, SUNMatrix J,
void* user_data, N_Vector tmp1, N_Vector tmp2) {
return static_cast<const system_data*>(user_data)->jacobian_states(
NV_DATA_S(x), J);
}
private:
/**
* Calculates the root function, using the user-supplied functor
* for a given value of x.
*/
inline void f_system(const double x[], double f[]) const {
const std::vector<double> x_vec(x, x + N_);
const std::vector<double>& f_vec
= to_array_1d(f_(to_vector(x_vec), y_, dat_, dat_int_, msgs_));
std::move(f_vec.begin(), f_vec.end(), f);
}
/**
* Calculate the Jacobian of the system function with respect to x
* using the method specified by J_f_.
* By default, J_f is constructed as a method that computes the
* Jacobian with reverse-mode autodiff.
*/
inline int jacobian_states(const double x[], SUNMatrix J) const {
return J_f_(f_, x_, y_, dat_, dat_int_, msgs_, x, J);
}
};
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: swmodule.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: vg $ $Date: 2003-05-22 08:40:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SWMODULE_HXX
#define _SWMODULE_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#include "shellid.hxx"
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEEVENTLISTENER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceEventListener.hpp>
#endif
#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif
class SvStringsDtor;
class Color;
class AuthorCharAttr;
class SfxItemSet;
class SfxRequest;
class SfxErrorHandler;
class SwDBConfig;
class SwModuleOptions;
class SwMasterUsrPref;
class SwViewOption;
class SwView;
class SwWrtShell;
class SwPrintOptions;
class SwAutoFmtOpt;
class SwChapterNumRules;
class SwStdFontConfig;
class SwNavigationConfig;
class SwTransferable;
class SwToolbarConfigItem;
class SwAttrPool;
namespace svtools{ class ColorConfig;}
class SvtAccessibilityOptions;
class SvtCTLOptions;
struct SwDBData;
#define VIEWOPT_DEST_VIEW 0
#define VIEWOPT_DEST_TEXT 1
#define VIEWOPT_DEST_WEB 2
#define VIEWOPT_DEST_VIEW_ONLY 3 //ViewOptions werden nur an der ::com::sun::star::sdbcx::View, nicht an der Appl. gesetzt
namespace com{ namespace sun{ namespace star{ namespace scanner{
class XScannerManager;
}}}}
class SwModule: public SwModuleDummy , public SfxListener
{
String sActAuthor;
// ConfigItems
SwModuleOptions* pModuleConfig;
SwMasterUsrPref* pUsrPref;
SwMasterUsrPref* pWebUsrPref;
SwPrintOptions* pPrtOpt;
SwPrintOptions* pWebPrtOpt;
SwChapterNumRules* pChapterNumRules;
SwStdFontConfig* pStdFontConfig;
SwNavigationConfig* pNavigationConfig;
SwToolbarConfigItem*pToolbarConfig; //fuer gestackte Toolbars, welche
SwToolbarConfigItem*pWebToolbarConfig; //war sichtbar?
SwDBConfig* pDBConfig;
svtools::ColorConfig* pColorConfig;
SvtAccessibilityOptions* pAccessibilityOptions;
SvtCTLOptions* pCTLOptions;
SfxErrorHandler* pErrorHdl;
SwAttrPool *pAttrPool;
// Die aktuelle View wird hier gehalten um nicht ueber
// GetActiveView arbeiten zu muessen
// Die View ist solange gueltig bis Sie im Activate
// zerstoert oder ausgetauscht wird
SwView* pView;
// Liste aller Redline-Autoren
SvStringsDtor* pAuthorNames;
// DictionaryList listener to trigger spellchecking or hyphenation
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > xLngSvcEvtListener;
::com::sun::star::uno::Reference<
::com::sun::star::scanner::XScannerManager > m_xScannerManager;
sal_Bool bAuthorInitialised : 1;
sal_Bool bEmbeddedLoadSave : 1;
virtual void FillStatusBar( StatusBar& );
// Hint abfangen fuer DocInfo
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
protected:
// Briefumschlaege, Etiketten
void InsertEnv(SfxRequest&);
void InsertLab(SfxRequest&, sal_Bool bLabel);
public:
// public Data - used for internal Clipboard / Drag & Drop / XSelection
SwTransferable *pClipboard, *pDragDrop, *pXSelection;
TYPEINFO();
SFX_DECL_INTERFACE(SW_INTERFACE_MODULE);
// dieser Ctor nur fuer SW-Dll
SwModule( SvFactory* pFact,
SvFactory* pWebFact,
SvFactory* pGlobalFact );
// dieser Ctor nur fuer Web-Dll
SwModule( SvFactory* pWebFact );
~SwModule();
virtual SfxModule* Load();
// View setzen nur fuer internen Gebrauch,
// aus techn. Gruenden public
//
inline void SetView(SwView* pVw) { pView = pVw; }
inline SwView* GetView() { return pView; }
//Die Handler fuer die Slots
void StateOther(SfxItemSet &); // andere
void StateViewOptions(SfxItemSet &);
void StateIsView(SfxItemSet &);
void ExecOther(SfxRequest &); // Felder, Formel ..
void ExecViewOptions(SfxRequest &);
void ExecWizzard(SfxRequest &);
// Benutzereinstellungen modifizieren
const SwMasterUsrPref *GetUsrPref(sal_Bool bWeb) const;
const SwViewOption* GetViewOption(sal_Bool bWeb);
void MakeUsrPref( SwViewOption &rToFill, sal_Bool bWeb ) const;
void ApplyUsrPref(const SwViewOption &, SwView*,
sal_uInt16 nDest = VIEWOPT_DEST_VIEW );
void ApplyUserMetric( FieldUnit eMetric, BOOL bWeb );
void ApplyFldUpdateFlags(sal_Int32 nFldFlags);
void ApplyLinkMode(sal_Int32 nNewLinkMode);
// ConfigItems erzeugen
SwModuleOptions* GetModuleConfig() { return pModuleConfig;}
SwPrintOptions* GetPrtOptions(sal_Bool bWeb);
SwChapterNumRules* GetChapterNumRules();
SwStdFontConfig* GetStdFontConfig() { return pStdFontConfig; }
SwNavigationConfig* GetNavigationConfig();
SwToolbarConfigItem*GetToolbarConfig() { return pToolbarConfig; }
SwToolbarConfigItem*GetWebToolbarConfig() { return pWebToolbarConfig; }
SwDBConfig* GetDBConfig();
svtools::ColorConfig& GetColorConfig();
SvtAccessibilityOptions& GetAccessibilityOptions();
SvtCTLOptions& GetCTLOptions();
// Ueber Sichten iterieren
static SwView* GetFirstView();
static SwView* GetNextView(SwView*);
sal_Bool IsEmbeddedLoadSave() const { return bEmbeddedLoadSave; }
void SetEmbeddedLoadSave( sal_Bool bFlag ) { bEmbeddedLoadSave = bFlag; }
void ShowDBObj( SwView& rView, const SwDBData& rData, BOOL bOnlyIfAvailable = FALSE);
// Tabellenmodi
sal_Bool IsInsTblFormatNum(sal_Bool bHTML) const;
sal_Bool IsInsTblChangeNumFormat(sal_Bool bHTML) const;
sal_Bool IsInsTblAlignNum(sal_Bool bHTML) const;
// Redlining
sal_uInt16 GetRedlineAuthor();
sal_uInt16 GetRedlineAuthorCount();
const String& GetRedlineAuthor(sal_uInt16 nPos);
sal_uInt16 InsertRedlineAuthor(const String& rAuthor);
void GetInsertAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
void GetDeletedAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
void GetFormatAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
const AuthorCharAttr& GetInsertAuthorAttr() const;
const AuthorCharAttr& GetDeletedAuthorAttr() const;
const AuthorCharAttr& GetFormatAuthorAttr() const;
sal_uInt16 GetRedlineMarkPos();
const Color& GetRedlineMarkColor();
// returne den definierten DocStat - WordDelimiter
const String& GetDocStatWordDelim() const;
// Durchreichen der Metric von der ModuleConfig (fuer HTML-Export)
sal_uInt16 GetMetric( sal_Bool bWeb ) const;
// Update-Stati durchreichen
sal_uInt16 GetLinkUpdMode( sal_Bool bWeb ) const;
sal_uInt16 GetFldUpdateFlags( sal_Bool bWeb ) const;
//virtuelle Methoden fuer den Optionendialog
virtual SfxItemSet* CreateItemSet( sal_uInt16 nId );
virtual void ApplyItemSet( sal_uInt16 nId, const SfxItemSet& rSet );
virtual SfxTabPage* CreateTabPage( sal_uInt16 nId, Window* pParent, const SfxItemSet& rSet );
//hier wird der Pool angelegt und an der SfxShell gesetzt
void InitAttrPool();
//Pool loeschen bevor es zu spaet ist
void RemoveAttrPool();
// Invalidiert ggf. OnlineSpell-WrongListen
void CheckSpellChanges( sal_Bool bOnlineSpelling,
sal_Bool bIsSpellWrongAgain, sal_Bool bIsSpellAllAgain );
inline ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener >
GetLngSvcEvtListener();
inline void SetLngSvcEvtListener( ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > & xLstnr);
void CreateLngSvcEvtListener();
::com::sun::star::uno::Reference<
::com::sun::star::scanner::XScannerManager >
GetScannerManager() const {return m_xScannerManager;}
};
inline ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener >
SwModule::GetLngSvcEvtListener()
{
return xLngSvcEvtListener;
}
inline void SwModule::SetLngSvcEvtListener(
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > & xLstnr)
{
xLngSvcEvtListener = xLstnr;
}
/*-----------------08.07.97 10.33-------------------
Zugriff auf das SwModule, die ::com::sun::star::sdbcx::View und die Shell
--------------------------------------------------*/
#define SW_MOD() ( *(SwModule**) GetAppData(SHL_WRITER))
SwView* GetActiveView();
SwWrtShell* GetActiveWrtShell();
#endif
<commit_msg>INTEGRATION: CWS fwkq1 (1.19.44); FILE MERGED 2003/08/13 08:37:43 mba 1.19.44.2: #110843#: get rid of factories 2003/07/15 06:35:55 mba 1.19.44.1: #110843#: get rid of factories<commit_after>/*************************************************************************
*
* $RCSfile: swmodule.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: rt $ $Date: 2003-09-19 08:43:03 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SWMODULE_HXX
#define _SWMODULE_HXX
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef SW_SWDLL_HXX
//#include <swdll.hxx>
#endif
#include "shellid.hxx"
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_LINGUISTIC2_XLINGUSERVICEEVENTLISTENER_HPP_
#include <com/sun/star/linguistic2/XLinguServiceEventListener.hpp>
#endif
#ifndef _VCL_FLDUNIT_HXX
#include <vcl/fldunit.hxx>
#endif
class SvStringsDtor;
class Color;
class AuthorCharAttr;
class SfxItemSet;
class SfxRequest;
class SfxErrorHandler;
class SwDBConfig;
class SwModuleOptions;
class SwMasterUsrPref;
class SwViewOption;
class SwView;
class SwWrtShell;
class SwPrintOptions;
class SwAutoFmtOpt;
class SwChapterNumRules;
class SwStdFontConfig;
class SwNavigationConfig;
class SwTransferable;
class SwToolbarConfigItem;
class SwAttrPool;
namespace svtools{ class ColorConfig;}
class SvtAccessibilityOptions;
class SvtCTLOptions;
struct SwDBData;
#define VIEWOPT_DEST_VIEW 0
#define VIEWOPT_DEST_TEXT 1
#define VIEWOPT_DEST_WEB 2
#define VIEWOPT_DEST_VIEW_ONLY 3 //ViewOptions werden nur an der ::com::sun::star::sdbcx::View, nicht an der Appl. gesetzt
namespace com{ namespace sun{ namespace star{ namespace scanner{
class XScannerManager;
}}}}
class SwModule: public SfxModule, public SfxListener
{
String sActAuthor;
// ConfigItems
SwModuleOptions* pModuleConfig;
SwMasterUsrPref* pUsrPref;
SwMasterUsrPref* pWebUsrPref;
SwPrintOptions* pPrtOpt;
SwPrintOptions* pWebPrtOpt;
SwChapterNumRules* pChapterNumRules;
SwStdFontConfig* pStdFontConfig;
SwNavigationConfig* pNavigationConfig;
SwToolbarConfigItem*pToolbarConfig; //fuer gestackte Toolbars, welche
SwToolbarConfigItem*pWebToolbarConfig; //war sichtbar?
SwDBConfig* pDBConfig;
svtools::ColorConfig* pColorConfig;
SvtAccessibilityOptions* pAccessibilityOptions;
SvtCTLOptions* pCTLOptions;
SfxErrorHandler* pErrorHdl;
SwAttrPool *pAttrPool;
// Die aktuelle View wird hier gehalten um nicht ueber
// GetActiveView arbeiten zu muessen
// Die View ist solange gueltig bis Sie im Activate
// zerstoert oder ausgetauscht wird
SwView* pView;
// Liste aller Redline-Autoren
SvStringsDtor* pAuthorNames;
// DictionaryList listener to trigger spellchecking or hyphenation
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > xLngSvcEvtListener;
::com::sun::star::uno::Reference<
::com::sun::star::scanner::XScannerManager > m_xScannerManager;
sal_Bool bAuthorInitialised : 1;
sal_Bool bEmbeddedLoadSave : 1;
virtual void FillStatusBar( StatusBar& );
// Hint abfangen fuer DocInfo
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
protected:
// Briefumschlaege, Etiketten
void InsertEnv(SfxRequest&);
void InsertLab(SfxRequest&, sal_Bool bLabel);
public:
// public Data - used for internal Clipboard / Drag & Drop / XSelection
SwTransferable *pClipboard, *pDragDrop, *pXSelection;
TYPEINFO();
SFX_DECL_INTERFACE(SW_INTERFACE_MODULE);
// dieser Ctor nur fuer SW-Dll
SwModule( SfxObjectFactory* pFact,
SfxObjectFactory* pWebFact,
SfxObjectFactory* pGlobalFact );
~SwModule();
// View setzen nur fuer internen Gebrauch,
// aus techn. Gruenden public
//
inline void SetView(SwView* pVw) { pView = pVw; }
inline SwView* GetView() { return pView; }
//Die Handler fuer die Slots
void StateOther(SfxItemSet &); // andere
void StateViewOptions(SfxItemSet &);
void StateIsView(SfxItemSet &);
void ExecOther(SfxRequest &); // Felder, Formel ..
void ExecViewOptions(SfxRequest &);
void ExecWizzard(SfxRequest &);
// Benutzereinstellungen modifizieren
const SwMasterUsrPref *GetUsrPref(sal_Bool bWeb) const;
const SwViewOption* GetViewOption(sal_Bool bWeb);
void MakeUsrPref( SwViewOption &rToFill, sal_Bool bWeb ) const;
void ApplyUsrPref(const SwViewOption &, SwView*,
sal_uInt16 nDest = VIEWOPT_DEST_VIEW );
void ApplyUserMetric( FieldUnit eMetric, BOOL bWeb );
void ApplyFldUpdateFlags(sal_Int32 nFldFlags);
void ApplyLinkMode(sal_Int32 nNewLinkMode);
// ConfigItems erzeugen
SwModuleOptions* GetModuleConfig() { return pModuleConfig;}
SwPrintOptions* GetPrtOptions(sal_Bool bWeb);
SwChapterNumRules* GetChapterNumRules();
SwStdFontConfig* GetStdFontConfig() { return pStdFontConfig; }
SwNavigationConfig* GetNavigationConfig();
SwToolbarConfigItem*GetToolbarConfig() { return pToolbarConfig; }
SwToolbarConfigItem*GetWebToolbarConfig() { return pWebToolbarConfig; }
SwDBConfig* GetDBConfig();
svtools::ColorConfig& GetColorConfig();
SvtAccessibilityOptions& GetAccessibilityOptions();
SvtCTLOptions& GetCTLOptions();
// Ueber Sichten iterieren
static SwView* GetFirstView();
static SwView* GetNextView(SwView*);
sal_Bool IsEmbeddedLoadSave() const { return bEmbeddedLoadSave; }
void SetEmbeddedLoadSave( sal_Bool bFlag ) { bEmbeddedLoadSave = bFlag; }
void ShowDBObj( SwView& rView, const SwDBData& rData, BOOL bOnlyIfAvailable = FALSE);
// Tabellenmodi
sal_Bool IsInsTblFormatNum(sal_Bool bHTML) const;
sal_Bool IsInsTblChangeNumFormat(sal_Bool bHTML) const;
sal_Bool IsInsTblAlignNum(sal_Bool bHTML) const;
// Redlining
sal_uInt16 GetRedlineAuthor();
sal_uInt16 GetRedlineAuthorCount();
const String& GetRedlineAuthor(sal_uInt16 nPos);
sal_uInt16 InsertRedlineAuthor(const String& rAuthor);
void GetInsertAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
void GetDeletedAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
void GetFormatAuthorAttr(sal_uInt16 nAuthor, SfxItemSet &rSet);
const AuthorCharAttr& GetInsertAuthorAttr() const;
const AuthorCharAttr& GetDeletedAuthorAttr() const;
const AuthorCharAttr& GetFormatAuthorAttr() const;
sal_uInt16 GetRedlineMarkPos();
const Color& GetRedlineMarkColor();
// returne den definierten DocStat - WordDelimiter
const String& GetDocStatWordDelim() const;
// Durchreichen der Metric von der ModuleConfig (fuer HTML-Export)
sal_uInt16 GetMetric( sal_Bool bWeb ) const;
// Update-Stati durchreichen
sal_uInt16 GetLinkUpdMode( sal_Bool bWeb ) const;
sal_uInt16 GetFldUpdateFlags( sal_Bool bWeb ) const;
//virtuelle Methoden fuer den Optionendialog
virtual SfxItemSet* CreateItemSet( sal_uInt16 nId );
virtual void ApplyItemSet( sal_uInt16 nId, const SfxItemSet& rSet );
virtual SfxTabPage* CreateTabPage( sal_uInt16 nId, Window* pParent, const SfxItemSet& rSet );
//hier wird der Pool angelegt und an der SfxShell gesetzt
void InitAttrPool();
//Pool loeschen bevor es zu spaet ist
void RemoveAttrPool();
// Invalidiert ggf. OnlineSpell-WrongListen
void CheckSpellChanges( sal_Bool bOnlineSpelling,
sal_Bool bIsSpellWrongAgain, sal_Bool bIsSpellAllAgain );
inline ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener >
GetLngSvcEvtListener();
inline void SetLngSvcEvtListener( ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > & xLstnr);
void CreateLngSvcEvtListener();
::com::sun::star::uno::Reference<
::com::sun::star::scanner::XScannerManager >
GetScannerManager() const {return m_xScannerManager;}
};
inline ::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener >
SwModule::GetLngSvcEvtListener()
{
return xLngSvcEvtListener;
}
inline void SwModule::SetLngSvcEvtListener(
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XLinguServiceEventListener > & xLstnr)
{
xLngSvcEvtListener = xLstnr;
}
/*-----------------08.07.97 10.33-------------------
Zugriff auf das SwModule, die ::com::sun::star::sdbcx::View und die Shell
--------------------------------------------------*/
#define SW_MOD() ( *(SwModule**) GetAppData(SHL_WRITER))
SwView* GetActiveView();
SwWrtShell* GetActiveWrtShell();
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
void swap(void *vp1, void *vp2, int size)
{
if (vp1 == NULL || vp2 == NULL)
return;
char *buffer = (char *)malloc(size);
memcpy(buffer, vp1, size);
memcpy(vp1, vp2, size);
memcpy(vp2, buffer, size);
free(buffer);
}
int main(int argc, char const *argv[])
{
int x = 28;
int y = 4;
swap(&x, &y, sizeof(int));
std::cout << x << std::endl;
std::cout << y << std::endl;
return 0;
}
<commit_msg>Delete genericSwap.cc<commit_after><|endoftext|>
|
<commit_before>#include "intro_screen.hpp"
#include "../core/units.hpp"
#include "../core/renderer/graphics_ctx.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <game/game_screen.hpp>
#include <game/example_screen.hpp>
namespace mo {
using namespace unit_literals;
using namespace renderer;
namespace {
struct ui_controller : sys::controller::Controllable_interface{
ui_controller(Game_engine& engine) : _engine(engine){}
void move(glm::vec2 direction) override {}
void look_at(glm::vec2 position) override {}
void look_in_dir(glm::vec2 direction) override {}
void attack() override { enter_game(); }
void use() override { enter_game(); }
void take() override { enter_game(); }
void switch_weapon(uint32_t weapon_id) override { enter_game(); }
void enter_game(){
_engine.enter_screen<Game_screen>("default", std::vector<ecs::ETO>{}, util::just(0));
}
Game_engine& _engine;
};
}
Intro_screen::Intro_screen(Game_engine& game_engine) :
Screen(game_engine),
_game_engine(game_engine),
_box(game_engine.assets(), "tex:ui_intro"_aid, 2.f, 2.f)
{
glm::vec2 win_size = glm::vec2(2, 2);
_camera.reset(new renderer::Camera(win_size));
}
void Intro_screen::_update(float delta_time) {
ui_controller uic(_game_engine);
_game_engine.controllers().main_controller()(uic);
}
void Intro_screen::_draw(float time ) {
Graphics_ctx& ctx = _game_engine.graphics_ctx();
_box.set_vp(_camera->vp());
_box.draw(glm::vec2(0.f, 0.f));
}
}
<commit_msg>removed unused code<commit_after>#include "intro_screen.hpp"
#include "../core/units.hpp"
#include "../core/renderer/graphics_ctx.hpp"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <game/game_screen.hpp>
#include <game/example_screen.hpp>
namespace mo {
using namespace unit_literals;
using namespace renderer;
namespace {
struct ui_controller : sys::controller::Controllable_interface{
ui_controller(Game_engine& engine) : _engine(engine){}
void move(glm::vec2 direction) override {}
void look_at(glm::vec2 position) override {}
void look_in_dir(glm::vec2 direction) override {}
void attack() override { enter_game(); }
void use() override { enter_game(); }
void take() override { enter_game(); }
void switch_weapon(uint32_t weapon_id) override { enter_game(); }
void enter_game(){
_engine.enter_screen<Game_screen>("default", std::vector<ecs::ETO>{}, util::just(0));
}
Game_engine& _engine;
};
}
Intro_screen::Intro_screen(Game_engine& game_engine) :
Screen(game_engine),
_game_engine(game_engine),
_box(game_engine.assets(), "tex:ui_intro"_aid, 2.f, 2.f)
{
glm::vec2 win_size = glm::vec2(2, 2);
_camera.reset(new renderer::Camera(win_size));
}
void Intro_screen::_update(float delta_time) {
ui_controller uic(_game_engine);
_game_engine.controllers().main_controller()(uic);
}
void Intro_screen::_draw(float time ) {
_box.set_vp(_camera->vp());
_box.draw(glm::vec2(0.f, 0.f));
}
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkModuleView.h"
#include <QmitkModuleTableModel.h>
#include <QTableView>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QSettings>
QmitkModuleView::QmitkModuleView()
: tableView(0)
{
}
void QmitkModuleView::SetFocus()
{
//tableView->setFocus();
}
void QmitkModuleView::CreateQtPartControl(QWidget *parent)
{
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
parent->setLayout(layout);
tableView = new QTableView(parent);
QmitkModuleTableModel* tableModel = new QmitkModuleTableModel(tableView);
QSortFilterProxyModel* sortProxyModel = new QSortFilterProxyModel(tableView);
sortProxyModel->setSourceModel(tableModel);
sortProxyModel->setDynamicSortFilter(true);
tableView->setModel(sortProxyModel);
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
tableView->setTextElideMode(Qt::ElideMiddle);
tableView->setSortingEnabled(true);
tableView->sortByColumn(0, Qt::AscendingOrder);
tableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setStretchLastSection(true);
tableView->horizontalHeader()->setCascadingSectionResizes(true);
layout->addWidget(tableView);
if (viewState)
{
berry::IMemento::Pointer tableHeaderState = viewState->GetChild("tableHeader");
if (tableHeaderState)
{
std::string key;
tableHeaderState->GetString("qsettings-key", key);
if (!key.empty())
{
QSettings settings;
QByteArray ba = settings.value(QString::fromStdString(key)).toByteArray();
tableView->horizontalHeader()->restoreState(ba);
}
}
}
}
void QmitkModuleView::Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento)
{
berry::QtViewPart::Init(site, memento);
viewState = memento;
}
void QmitkModuleView::SaveState(berry::IMemento::Pointer memento)
{
QString key = "QmitkModuleView_tableHeader";
QByteArray ba = tableView->horizontalHeader()->saveState();
QSettings settings;
settings.setValue(key, ba);
berry::IMemento::Pointer tableHeaderState = memento->CreateChild("tableHeader");
tableHeaderState->PutString("qsettings-key", key.toStdString());
}
<commit_msg>Don't set resize mode for non-existing column index.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkModuleView.h"
#include <QmitkModuleTableModel.h>
#include <QTableView>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QSortFilterProxyModel>
#include <QSettings>
QmitkModuleView::QmitkModuleView()
: tableView(0)
{
}
void QmitkModuleView::SetFocus()
{
//tableView->setFocus();
}
void QmitkModuleView::CreateQtPartControl(QWidget *parent)
{
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
parent->setLayout(layout);
tableView = new QTableView(parent);
QmitkModuleTableModel* tableModel = new QmitkModuleTableModel(tableView);
QSortFilterProxyModel* sortProxyModel = new QSortFilterProxyModel(tableView);
sortProxyModel->setSourceModel(tableModel);
sortProxyModel->setDynamicSortFilter(true);
tableView->setModel(sortProxyModel);
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
tableView->setTextElideMode(Qt::ElideMiddle);
tableView->setSortingEnabled(true);
tableView->sortByColumn(0, Qt::AscendingOrder);
// Fixed size for "Id" column
tableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
// Fixed size for "Version" column
tableView->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
tableView->horizontalHeader()->setStretchLastSection(true);
tableView->horizontalHeader()->setCascadingSectionResizes(true);
layout->addWidget(tableView);
if (viewState)
{
berry::IMemento::Pointer tableHeaderState = viewState->GetChild("tableHeader");
if (tableHeaderState)
{
std::string key;
tableHeaderState->GetString("qsettings-key", key);
if (!key.empty())
{
QSettings settings;
QByteArray ba = settings.value(QString::fromStdString(key)).toByteArray();
tableView->horizontalHeader()->restoreState(ba);
}
}
}
}
void QmitkModuleView::Init(berry::IViewSite::Pointer site, berry::IMemento::Pointer memento)
{
berry::QtViewPart::Init(site, memento);
viewState = memento;
}
void QmitkModuleView::SaveState(berry::IMemento::Pointer memento)
{
QString key = "QmitkModuleView_tableHeader";
QByteArray ba = tableView->horizontalHeader()->saveState();
QSettings settings;
settings.setValue(key, ba);
berry::IMemento::Pointer tableHeaderState = memento->CreateChild("tableHeader");
tableHeaderState->PutString("qsettings-key", key.toStdString());
}
<|endoftext|>
|
<commit_before>#include "InputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include "util.h"
InputMesh::InputMesh(int assetId, int inputIdx) :
Input(assetId, inputIdx),
myInputObjectId(-1),
myInputGeoId(-1)
{
CHECK_HAPI(HAPI_CreateInputAsset(&myInputAssetId, NULL));
if(!Util::statusCheckLoop())
{
DISPLAY_ERROR(MString("Unexpected error when creating input asset."));
}
myInputObjectId = 0;
myInputGeoId = 0;
CHECK_HAPI(HAPI_ConnectAssetGeometry(
myInputAssetId, myInputObjectId,
myAssetId, myInputIdx
));
}
InputMesh::~InputMesh()
{
CHECK_HAPI(HAPI_DestroyAsset(myInputAssetId));
}
Input::AssetInputType
InputMesh::assetInputType() const
{
return Input::AssetInputType_Mesh;
}
void
InputMesh::setInputTransform(MDataHandle &dataHandle)
{
MMatrix transformMatrix = dataHandle.asMatrix();
float matrix[16];
transformMatrix.get(reinterpret_cast<float(*)[4]>(matrix));
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler(matrix, HAPI_SRT, HAPI_XYZ, &transformEuler);
HAPI_SetObjectTransform(
myInputAssetId, myInputObjectId,
&transformEuler
);
}
void
InputMesh::setInputGeo(
MDataBlock &dataBlock,
const MPlug &plug
)
{
MDataHandle dataHandle = dataBlock.inputValue(plug);
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
meshFn.getVertices(faceCounts, vertexList);
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = meshFn.numVertices();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
// Set the data
HAPI_SetPartInfo(
myInputAssetId, myInputObjectId, myInputGeoId,
&partInfo
);
HAPI_SetFaceCounts(
myInputAssetId, myInputObjectId, myInputGeoId,
fc, 0, partInfo.faceCount
);
HAPI_SetVertexList(
myInputAssetId, myInputObjectId, myInputGeoId,
vl, 0, partInfo.vertexCount
);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = meshFn.numVertices();
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info,
meshFn.getRawPoints(NULL), 0, meshFn.numVertices()
);
// normals
{
// get normal IDs
MIntArray normalCounts;
MIntArray normalIds;
meshFn.getNormalIds(normalCounts, normalIds);
if(normalIds.length())
{
// reverse winding order
Util::reverseWindingOrder(normalIds, faceCounts);
// get normal values
const float* rawNormals = meshFn.getRawNormals(NULL);
// build the per-vertex normals
std::vector<float> vertexNormals;
vertexNormals.reserve(normalIds.length() * 3);
for(unsigned int i = 0; i < normalIds.length(); ++i)
{
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = normalIds.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo
);
HAPI_SetAttributeFloatData(myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo,
&vertexNormals.front(), 0, normalIds.length()
);
}
}
// UVs
{
// get UV IDs
MIntArray uvCounts;
MIntArray uvIds;
meshFn.getAssignedUVs(uvCounts, uvIds);
// if there's UVs
if(uvIds.length())
{
// reverse winding order
Util::reverseWindingOrder(uvIds, uvCounts);
// get UV values
MFloatArray uArray;
MFloatArray vArray;
meshFn.getUVs(uArray, vArray);
// build the per-vertex UVs
std::vector<float> vertexUVs;
vertexUVs.reserve(vertexList.length() * 3);
unsigned int uvIdIndex = 0;
for(unsigned int i = 0; i < uvCounts.length(); ++i)
{
if(uvCounts[i] == faceCounts[i])
{
// has UVs assigned
for(int j = 0; j < uvCounts[i]; ++j)
{
vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(0);
uvIdIndex++;
}
}
else
{
// no UVs assigned
for(int j = 0; j < faceCounts[i]; ++j)
{
vertexUVs.push_back(0);
vertexUVs.push_back(0);
vertexUVs.push_back(0);
}
}
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = vertexList.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"uv", &attributeInfo,
&vertexUVs.front(), 0, vertexList.length()
);
}
}
// Colors and Alphas
{
MString currentColorSetName;
currentColorSetName = meshFn.currentColorSetName();
MStringArray colorSetNames;
meshFn.getColorSetNames(colorSetNames);
MColor defaultUnsetColor;
MColorArray colors;
std::vector<float> buffer;
for(unsigned int i = 0; i < colorSetNames.length(); i++)
{
const MString colorSetName = colorSetNames[i];
MString colorAttributeName;
MString alphaAttributeName;
if(colorSetName == currentColorSetName)
{
colorAttributeName = "Cd";
alphaAttributeName = "Alpha";
}
else
{
colorAttributeName = colorSetName;
alphaAttributeName = colorSetName + "Alpha";
}
bool hasColor = false;
bool hasAlpha = false;
{
MFnMesh::MColorRepresentation colorSetRepresentation =
meshFn.getColorRepresentation(colorSetName);
switch(colorSetRepresentation)
{
case MFnMesh::kAlpha:
hasAlpha = true;
break;
case MFnMesh::kRGB:
hasColor = true;
break;
case MFnMesh::kRGBA:
hasColor = true;
hasAlpha = true;
break;
}
}
CHECK_MSTATUS(meshFn.getFaceVertexColors(
colors,
&colorSetName,
&defaultUnsetColor
));
// reverse winding order
Util::reverseWindingOrder(colors, faceCounts);
if(hasColor)
{
buffer.resize(3 * vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j * 3 + 0] = colors[j].r;
buffer[j * 3 + 1] = colors[j].g;
buffer[j * 3 + 2] = colors[j].b;
}
// add and set Cd
HAPI_AttributeInfo colorAttributeInfo;
colorAttributeInfo.exists = true;
colorAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
colorAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
colorAttributeInfo.count = vertexList.length();
colorAttributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
if(hasAlpha)
{
buffer.resize(vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j] = colors[j].a;
}
// add and set Alpha
HAPI_AttributeInfo alphaAttributeInfo;
alphaAttributeInfo.exists = true;
alphaAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
alphaAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
alphaAttributeInfo.count = vertexList.length();
alphaAttributeInfo.tupleSize = 1;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
}
}
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputObjectId, myInputGeoId);
delete[] vl;
delete[] fc;
}
<commit_msg>Add support for multiple UVs for input meshes<commit_after>#include "InputMesh.h"
#include <maya/MFnMesh.h>
#include <maya/MDataBlock.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MIntArray.h>
#include <maya/MMatrix.h>
#include "util.h"
InputMesh::InputMesh(int assetId, int inputIdx) :
Input(assetId, inputIdx),
myInputObjectId(-1),
myInputGeoId(-1)
{
CHECK_HAPI(HAPI_CreateInputAsset(&myInputAssetId, NULL));
if(!Util::statusCheckLoop())
{
DISPLAY_ERROR(MString("Unexpected error when creating input asset."));
}
myInputObjectId = 0;
myInputGeoId = 0;
CHECK_HAPI(HAPI_ConnectAssetGeometry(
myInputAssetId, myInputObjectId,
myAssetId, myInputIdx
));
}
InputMesh::~InputMesh()
{
CHECK_HAPI(HAPI_DestroyAsset(myInputAssetId));
}
Input::AssetInputType
InputMesh::assetInputType() const
{
return Input::AssetInputType_Mesh;
}
void
InputMesh::setInputTransform(MDataHandle &dataHandle)
{
MMatrix transformMatrix = dataHandle.asMatrix();
float matrix[16];
transformMatrix.get(reinterpret_cast<float(*)[4]>(matrix));
HAPI_TransformEuler transformEuler;
HAPI_ConvertMatrixToEuler(matrix, HAPI_SRT, HAPI_XYZ, &transformEuler);
HAPI_SetObjectTransform(
myInputAssetId, myInputObjectId,
&transformEuler
);
}
void
InputMesh::setInputGeo(
MDataBlock &dataBlock,
const MPlug &plug
)
{
MDataHandle dataHandle = dataBlock.inputValue(plug);
// extract mesh data from Maya
MObject meshObj = dataHandle.asMesh();
MFnMesh meshFn(meshObj);
// get face data
MIntArray faceCounts;
MIntArray vertexList;
meshFn.getVertices(faceCounts, vertexList);
Util::reverseWindingOrder(vertexList, faceCounts);
// set up part info
HAPI_PartInfo partInfo;
HAPI_PartInfo_Init(&partInfo);
partInfo.id = 0;
partInfo.faceCount = faceCounts.length();
partInfo.vertexCount = vertexList.length();
partInfo.pointCount = meshFn.numVertices();
// copy data to arrays
int * vl = new int[partInfo.vertexCount];
int * fc = new int[partInfo.faceCount];
vertexList.get(vl);
faceCounts.get(fc);
// Set the data
HAPI_SetPartInfo(
myInputAssetId, myInputObjectId, myInputGeoId,
&partInfo
);
HAPI_SetFaceCounts(
myInputAssetId, myInputObjectId, myInputGeoId,
fc, 0, partInfo.faceCount
);
HAPI_SetVertexList(
myInputAssetId, myInputObjectId, myInputGeoId,
vl, 0, partInfo.vertexCount
);
// Set position attributes.
HAPI_AttributeInfo pos_attr_info;
pos_attr_info.exists = true;
pos_attr_info.owner = HAPI_ATTROWNER_POINT;
pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT;
pos_attr_info.count = meshFn.numVertices();
pos_attr_info.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
"P", &pos_attr_info,
meshFn.getRawPoints(NULL), 0, meshFn.numVertices()
);
// normals
{
// get normal IDs
MIntArray normalCounts;
MIntArray normalIds;
meshFn.getNormalIds(normalCounts, normalIds);
if(normalIds.length())
{
// reverse winding order
Util::reverseWindingOrder(normalIds, faceCounts);
// get normal values
const float* rawNormals = meshFn.getRawNormals(NULL);
// build the per-vertex normals
std::vector<float> vertexNormals;
vertexNormals.reserve(normalIds.length() * 3);
for(unsigned int i = 0; i < normalIds.length(); ++i)
{
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]);
vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]);
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = normalIds.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo
);
HAPI_SetAttributeFloatData(myInputAssetId, myInputObjectId, myInputGeoId,
"N", &attributeInfo,
&vertexNormals.front(), 0, normalIds.length()
);
}
}
// UVs
{
MString currentUVSetName;
currentUVSetName = meshFn.currentUVSetName();
MStringArray uvSetNames;
meshFn.getUVSetNames(uvSetNames);
for(unsigned int i = 0; i < uvSetNames.length(); i++)
{
const MString uvSetName = uvSetNames[i];
MString uvAttributeName;
if(uvSetName == currentUVSetName)
{
uvAttributeName = "uv";
}
else
{
uvAttributeName = uvSetName;
}
// get UV IDs
MIntArray uvCounts;
MIntArray uvIds;
meshFn.getAssignedUVs(uvCounts, uvIds, &uvSetName);
// reverse winding order
Util::reverseWindingOrder(uvIds, uvCounts);
// get UV values
MFloatArray uArray;
MFloatArray vArray;
meshFn.getUVs(uArray, vArray, &uvSetName);
// build the per-vertex UVs
std::vector<float> vertexUVs;
vertexUVs.reserve(vertexList.length() * 3);
unsigned int uvIdIndex = 0;
for(unsigned int i = 0; i < uvCounts.length(); ++i)
{
if(uvCounts[i] == faceCounts[i])
{
// has UVs assigned
for(int j = 0; j < uvCounts[i]; ++j)
{
vertexUVs.push_back(uArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(vArray[uvIds[uvIdIndex]]);
vertexUVs.push_back(0);
uvIdIndex++;
}
}
else
{
// no UVs assigned
for(int j = 0; j < faceCounts[i]; ++j)
{
vertexUVs.push_back(0);
vertexUVs.push_back(0);
vertexUVs.push_back(0);
}
}
}
// add and set it to HAPI
HAPI_AttributeInfo attributeInfo;
attributeInfo.exists = true;
attributeInfo.owner = HAPI_ATTROWNER_VERTEX;
attributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
attributeInfo.count = vertexList.length();
attributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
uvAttributeName.asChar(), &attributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
uvAttributeName.asChar(), &attributeInfo,
&vertexUVs.front(), 0, vertexList.length()
);
}
}
// Colors and Alphas
{
MString currentColorSetName;
currentColorSetName = meshFn.currentColorSetName();
MStringArray colorSetNames;
meshFn.getColorSetNames(colorSetNames);
MColor defaultUnsetColor;
MColorArray colors;
std::vector<float> buffer;
for(unsigned int i = 0; i < colorSetNames.length(); i++)
{
const MString colorSetName = colorSetNames[i];
MString colorAttributeName;
MString alphaAttributeName;
if(colorSetName == currentColorSetName)
{
colorAttributeName = "Cd";
alphaAttributeName = "Alpha";
}
else
{
colorAttributeName = colorSetName;
alphaAttributeName = colorSetName + "Alpha";
}
bool hasColor = false;
bool hasAlpha = false;
{
MFnMesh::MColorRepresentation colorSetRepresentation =
meshFn.getColorRepresentation(colorSetName);
switch(colorSetRepresentation)
{
case MFnMesh::kAlpha:
hasAlpha = true;
break;
case MFnMesh::kRGB:
hasColor = true;
break;
case MFnMesh::kRGBA:
hasColor = true;
hasAlpha = true;
break;
}
}
CHECK_MSTATUS(meshFn.getFaceVertexColors(
colors,
&colorSetName,
&defaultUnsetColor
));
// reverse winding order
Util::reverseWindingOrder(colors, faceCounts);
if(hasColor)
{
buffer.resize(3 * vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j * 3 + 0] = colors[j].r;
buffer[j * 3 + 1] = colors[j].g;
buffer[j * 3 + 2] = colors[j].b;
}
// add and set Cd
HAPI_AttributeInfo colorAttributeInfo;
colorAttributeInfo.exists = true;
colorAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
colorAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
colorAttributeInfo.count = vertexList.length();
colorAttributeInfo.tupleSize = 3;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
colorAttributeName.asChar(), &colorAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
if(hasAlpha)
{
buffer.resize(vertexList.length());
for(unsigned int j = 0; j < vertexList.length(); j++)
{
buffer[j] = colors[j].a;
}
// add and set Alpha
HAPI_AttributeInfo alphaAttributeInfo;
alphaAttributeInfo.exists = true;
alphaAttributeInfo.owner = HAPI_ATTROWNER_VERTEX;
alphaAttributeInfo.storage = HAPI_STORAGETYPE_FLOAT;
alphaAttributeInfo.count = vertexList.length();
alphaAttributeInfo.tupleSize = 1;
HAPI_AddAttribute(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo
);
HAPI_SetAttributeFloatData(
myInputAssetId, myInputObjectId, myInputGeoId,
alphaAttributeName.asChar(), &alphaAttributeInfo,
&buffer.front(), 0, vertexList.length()
);
}
}
}
// Commit it
HAPI_CommitGeo(myInputAssetId, myInputObjectId, myInputGeoId);
delete[] vl;
delete[] fc;
}
<|endoftext|>
|
<commit_before><commit_msg>Remove dead code<commit_after><|endoftext|>
|
<commit_before><commit_msg>sw/paint: replace bools by enum in DrawGraphic method<commit_after><|endoftext|>
|
<commit_before><commit_msg>sw: fix sw_unoapi UnvisitedCharStyleName regression<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/import_dialog_gtk.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "grit/generated_resources.h"
// static
void ImportDialogGtk::Show(GtkWindow* parent, Profile* profile) {
new ImportDialogGtk(parent, profile);
}
////////////////////////////////////////////////////////////////////////////////
// ImportObserver implementation:
void ImportDialogGtk::ImportCanceled() {
ImportComplete();
}
void ImportDialogGtk::ImportComplete() {
gtk_widget_destroy(dialog_);
delete this;
}
ImportDialogGtk::ImportDialogGtk(GtkWindow* parent, Profile* profile) :
parent_(parent), profile_(profile), importer_host_(new ImporterHost()) {
// Build the dialog.
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_IMPORT_SETTINGS_TITLE).c_str(),
parent,
(GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_CANCEL,
GTK_RESPONSE_REJECT,
l10n_util::GetStringUTF8(IDS_IMPORT_COMMIT).c_str(),
GTK_RESPONSE_ACCEPT,
NULL);
// TODO(rahulk): find how to set size properly so that the dialog
// box width is at least enough to display full title.
gtk_widget_set_size_request(dialog_, 300, -1);
GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
gtk_box_set_spacing(GTK_BOX(content_area), 18);
GtkWidget* combo_hbox = gtk_hbox_new(FALSE, 12);
GtkWidget* from = gtk_label_new(
l10n_util::GetStringUTF8(IDS_IMPORT_FROM_LABEL).c_str());
gtk_box_pack_start(GTK_BOX(combo_hbox), from, FALSE, FALSE, 0);
combo_ = gtk_combo_box_new_text();
int profiles_count = importer_host_->GetAvailableProfileCount();
for (int i = 0; i < profiles_count; i++) {
std::wstring profile = importer_host_->GetSourceProfileNameAt(i);
gtk_combo_box_append_text(GTK_COMBO_BOX(combo_),
WideToUTF8(profile).c_str());
}
gtk_combo_box_set_active(GTK_COMBO_BOX(combo_), 0);
gtk_box_pack_start(GTK_BOX(combo_hbox), combo_, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), combo_hbox, FALSE, FALSE, 0);
GtkWidget* vbox = gtk_vbox_new(FALSE, 6);
GtkWidget* description = gtk_label_new(
l10n_util::GetStringUTF8(IDS_IMPORT_ITEMS_LABEL).c_str());
gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);
bookmarks_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_FAVORITES_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), bookmarks_, FALSE, FALSE, 0);
search_engines_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_SEARCH_ENGINES_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), search_engines_, FALSE, FALSE, 0);
passwords_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_PASSWORDS_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), passwords_, FALSE, FALSE, 0);
history_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_HISTORY_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), history_, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(content_area), vbox, FALSE, FALSE, 0);
g_signal_connect(dialog_, "response",
G_CALLBACK(HandleOnResponseDialog), this);
gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
gtk_widget_show_all(dialog_);
}
void ImportDialogGtk::OnDialogResponse(GtkWidget* widget, int response) {
gtk_widget_hide_all(dialog_);
if (response == GTK_RESPONSE_ACCEPT) {
uint16 items = NONE;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_)))
items |= FAVORITES;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(search_engines_)))
items |= SEARCH_ENGINES;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(passwords_)))
items |= PASSWORDS;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(history_)))
items |= HISTORY;
const ProfileInfo& source_profile = importer_host_->GetSourceProfileInfoAt(
gtk_combo_box_get_active(GTK_COMBO_BOX(combo_)));
StartImportingWithUI(parent_, items, importer_host_.get(),
source_profile, profile_, this, false);
} else {
ImportCanceled();
}
}
<commit_msg>If there is nothing to import, return.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/import_dialog_gtk.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "grit/generated_resources.h"
// static
void ImportDialogGtk::Show(GtkWindow* parent, Profile* profile) {
new ImportDialogGtk(parent, profile);
}
////////////////////////////////////////////////////////////////////////////////
// ImportObserver implementation:
void ImportDialogGtk::ImportCanceled() {
ImportComplete();
}
void ImportDialogGtk::ImportComplete() {
gtk_widget_destroy(dialog_);
delete this;
}
ImportDialogGtk::ImportDialogGtk(GtkWindow* parent, Profile* profile) :
parent_(parent), profile_(profile), importer_host_(new ImporterHost()) {
// Build the dialog.
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_IMPORT_SETTINGS_TITLE).c_str(),
parent,
(GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_CANCEL,
GTK_RESPONSE_REJECT,
l10n_util::GetStringUTF8(IDS_IMPORT_COMMIT).c_str(),
GTK_RESPONSE_ACCEPT,
NULL);
// TODO(rahulk): find how to set size properly so that the dialog
// box width is at least enough to display full title.
gtk_widget_set_size_request(dialog_, 300, -1);
GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox;
gtk_box_set_spacing(GTK_BOX(content_area), 18);
GtkWidget* combo_hbox = gtk_hbox_new(FALSE, 12);
GtkWidget* from = gtk_label_new(
l10n_util::GetStringUTF8(IDS_IMPORT_FROM_LABEL).c_str());
gtk_box_pack_start(GTK_BOX(combo_hbox), from, FALSE, FALSE, 0);
combo_ = gtk_combo_box_new_text();
int profiles_count = importer_host_->GetAvailableProfileCount();
for (int i = 0; i < profiles_count; i++) {
std::wstring profile = importer_host_->GetSourceProfileNameAt(i);
gtk_combo_box_append_text(GTK_COMBO_BOX(combo_),
WideToUTF8(profile).c_str());
}
gtk_combo_box_set_active(GTK_COMBO_BOX(combo_), 0);
gtk_box_pack_start(GTK_BOX(combo_hbox), combo_, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(content_area), combo_hbox, FALSE, FALSE, 0);
GtkWidget* vbox = gtk_vbox_new(FALSE, 6);
GtkWidget* description = gtk_label_new(
l10n_util::GetStringUTF8(IDS_IMPORT_ITEMS_LABEL).c_str());
gtk_misc_set_alignment(GTK_MISC(description), 0, 0);
gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0);
bookmarks_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_FAVORITES_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), bookmarks_, FALSE, FALSE, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(bookmarks_), TRUE);
search_engines_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_SEARCH_ENGINES_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), search_engines_, FALSE, FALSE, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(search_engines_), TRUE);
passwords_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_PASSWORDS_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), passwords_, FALSE, FALSE, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(passwords_), TRUE);
history_ = gtk_check_button_new_with_label(
l10n_util::GetStringUTF8(IDS_IMPORT_HISTORY_CHKBOX).c_str());
gtk_box_pack_start(GTK_BOX(vbox), history_, FALSE, FALSE, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(history_), TRUE);
gtk_box_pack_start(GTK_BOX(content_area), vbox, FALSE, FALSE, 0);
g_signal_connect(dialog_, "response",
G_CALLBACK(HandleOnResponseDialog), this);
gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
gtk_widget_show_all(dialog_);
}
void ImportDialogGtk::OnDialogResponse(GtkWidget* widget, int response) {
gtk_widget_hide_all(dialog_);
if (response == GTK_RESPONSE_ACCEPT) {
uint16 items = NONE;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_)))
items |= FAVORITES;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(search_engines_)))
items |= SEARCH_ENGINES;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(passwords_)))
items |= PASSWORDS;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(history_)))
items |= HISTORY;
if (items == 0) {
ImportComplete();
} else {
const ProfileInfo& source_profile =
importer_host_->GetSourceProfileInfoAt(
gtk_combo_box_get_active(GTK_COMBO_BOX(combo_)));
StartImportingWithUI(parent_, items, importer_host_.get(),
source_profile, profile_, this, false);
}
} else {
ImportCanceled();
}
}
<|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/ui/webui/theme_source.h"
#include "base/message_loop.h"
#include "base/ref_counted_memory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resources_util.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/browser/ui/webui/ntp_resource_cache.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "googleurl/src/gurl.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/theme_provider.h"
// use a resource map rather than hard-coded strings.
static const char* kNewTabCSSPath = "css/newtab.css";
static const char* kNewIncognitoTabCSSPath = "css/newincognitotab.css";
static std::string StripQueryParams(const std::string& path) {
GURL path_url = GURL(std::string(chrome::kChromeUIScheme) + "://" +
std::string(chrome::kChromeUIThemePath) + "/" + path);
return path_url.path().substr(1); // path() always includes a leading '/'.
}
////////////////////////////////////////////////////////////////////////////////
// ThemeSource, public:
ThemeSource::ThemeSource(Profile* profile)
: DataSource(chrome::kChromeUIThemePath, MessageLoop::current()),
profile_(profile->GetOriginalProfile()) {
css_bytes_ = profile_->GetNTPResourceCache()->GetNewTabCSS(
profile->IsOffTheRecord());
}
ThemeSource::~ThemeSource() {
}
void ThemeSource::StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id) {
// Our path may include cachebuster arguments, so trim them off.
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK((uncached_path == kNewTabCSSPath && !is_off_the_record) ||
(uncached_path == kNewIncognitoTabCSSPath && is_off_the_record));
SendResponse(request_id, css_bytes_);
return;
} else {
int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path);
if (resource_id != -1) {
SendThemeBitmap(request_id, resource_id);
return;
}
}
// We don't have any data to send back.
SendResponse(request_id, NULL);
}
std::string ThemeSource::GetMimeType(const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
return "text/css";
}
return "image/png";
}
MessageLoop* ThemeSource::MessageLoopForRequestPath(
const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
// We generated and cached this when we initialized the object. We don't
// have to go back to the UI thread to send the data.
return NULL;
}
// If it's not a themeable image, we don't need to go to the UI thread.
int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path);
if (!BrowserThemeProvider::IsThemeableImage(resource_id))
return NULL;
return DataSource::MessageLoopForRequestPath(path);
}
bool ThemeSource::ShouldReplaceExistingSource() const {
// We currently get the css_bytes_ in the ThemeSource constructor, so we need
// to recreate the source itself when a theme changes.
return true;
}
////////////////////////////////////////////////////////////////////////////////
// ThemeSource, private:
void ThemeSource::SendThemeBitmap(int request_id, int resource_id) {
if (BrowserThemeProvider::IsThemeableImage(resource_id)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ui::ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
scoped_refptr<RefCountedMemory> image_data(tp->GetRawData(resource_id));
SendResponse(request_id, image_data);
} else {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SendResponse(request_id, rb.LoadDataResourceBytes(resource_id));
}
}
<commit_msg>Revert 77517 - Force NTP reload when a new theme is installed.<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/ui/webui/theme_source.h"
#include "base/message_loop.h"
#include "base/ref_counted_memory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/resources_util.h"
#include "chrome/browser/themes/browser_theme_provider.h"
#include "chrome/browser/ui/webui/ntp_resource_cache.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "googleurl/src/gurl.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/theme_provider.h"
// use a resource map rather than hard-coded strings.
static const char* kNewTabCSSPath = "css/newtab.css";
static const char* kNewIncognitoTabCSSPath = "css/newincognitotab.css";
static std::string StripQueryParams(const std::string& path) {
GURL path_url = GURL(std::string(chrome::kChromeUIScheme) + "://" +
std::string(chrome::kChromeUIThemePath) + "/" + path);
return path_url.path().substr(1); // path() always includes a leading '/'.
}
////////////////////////////////////////////////////////////////////////////////
// ThemeSource, public:
ThemeSource::ThemeSource(Profile* profile)
: DataSource(chrome::kChromeUIThemePath, MessageLoop::current()),
profile_(profile->GetOriginalProfile()) {
css_bytes_ = profile_->GetNTPResourceCache()->GetNewTabCSS(
profile->IsOffTheRecord());
}
ThemeSource::~ThemeSource() {
}
void ThemeSource::StartDataRequest(const std::string& path,
bool is_off_the_record,
int request_id) {
// Our path may include cachebuster arguments, so trim them off.
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK((uncached_path == kNewTabCSSPath && !is_off_the_record) ||
(uncached_path == kNewIncognitoTabCSSPath && is_off_the_record));
SendResponse(request_id, css_bytes_);
return;
} else {
int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path);
if (resource_id != -1) {
SendThemeBitmap(request_id, resource_id);
return;
}
}
// We don't have any data to send back.
SendResponse(request_id, NULL);
}
std::string ThemeSource::GetMimeType(const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
return "text/css";
}
return "image/png";
}
MessageLoop* ThemeSource::MessageLoopForRequestPath(
const std::string& path) const {
std::string uncached_path = StripQueryParams(path);
if (uncached_path == kNewTabCSSPath ||
uncached_path == kNewIncognitoTabCSSPath) {
// We generated and cached this when we initialized the object. We don't
// have to go back to the UI thread to send the data.
return NULL;
}
// If it's not a themeable image, we don't need to go to the UI thread.
int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path);
if (!BrowserThemeProvider::IsThemeableImage(resource_id))
return NULL;
return DataSource::MessageLoopForRequestPath(path);
}
bool ThemeSource::ShouldReplaceExistingSource() const {
return false;
}
////////////////////////////////////////////////////////////////////////////////
// ThemeSource, private:
void ThemeSource::SendThemeBitmap(int request_id, int resource_id) {
if (BrowserThemeProvider::IsThemeableImage(resource_id)) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
ui::ThemeProvider* tp = profile_->GetThemeProvider();
DCHECK(tp);
scoped_refptr<RefCountedMemory> image_data(tp->GetRawData(resource_id));
SendResponse(request_id, image_data);
} else {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SendResponse(request_id, rb.LoadDataResourceBytes(resource_id));
}
}
<|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/common/temp_scaffolding_stubs.h"
#include <vector>
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/rlz/rlz.h"
#if defined(OS_LINUX)
#include "chrome/browser/dock_info.h"
#include "chrome/common/render_messages.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/fonts_languages_window.h"
#include "chrome/browser/memory_details.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_manager.h"
#include "chrome/browser/download/download_request_dialog_delegate.h"
#include "chrome/browser/download/download_request_manager.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#endif
class TabContents;
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
void AutomationProvider::GetAutocompleteEditForBrowser(
int browser_handle,
bool* success,
int* autocomplete_edit_handle) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle,
bool* success,
std::wstring* text) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle,
const std::wstring& text,
bool* success) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditGetMatches(
int autocomplete_edit_handle,
bool* success,
std::vector<AutocompleteMatchData>* matches) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditIsQueryInProgress(
int autocomplete_edit_handle,
bool* success,
bool* query_in_progress) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::OnMessageFromExternalHost(
int handle, const std::string& message, const std::string& origin,
const std::string& target) {
NOTIMPLEMENTED();
}
#endif // defined(OS_MACOSX)
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
// static
bool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,
const FilePath& master_prefs_path,
std::vector<std::wstring>* new_tabs,
int* ping_delay,
bool* homepage_defined) {
// http://code.google.com/p/chromium/issues/detail?id=11971
// Pretend we processed them correctly.
return true;
}
// static
int FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {
// http://code.google.com/p/chromium/issues/detail?id=11971
return 0;
}
#endif
bool FirstRun::CreateChromeDesktopShortcut() {
NOTIMPLEMENTED();
return false;
}
bool FirstRun::CreateChromeQuickLaunchShortcut() {
NOTIMPLEMENTED();
return false;
}
// static
bool Upgrade::IsBrowserAlreadyRunning() {
// http://code.google.com/p/chromium/issues/detail?id=9295
return false;
}
// static
bool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {
// http://code.google.com/p/chromium/issues/detail?id=9295
return true;
}
// static
bool Upgrade::SwapNewChromeExeIfPresent() {
// http://code.google.com/p/chromium/issues/detail?id=9295
return true;
}
// static
Upgrade::TryResult ShowTryChromeDialog(size_t version) {
return Upgrade::TD_NOT_NOW;
}
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
void InstallJankometer(const CommandLine&) {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
void UninstallJankometer() {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
#endif
//--------------------------------------------------------------------------
void RLZTracker::CleanupRlz() {
// http://code.google.com/p/chromium/issues/detail?id=8152
}
bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
// http://code.google.com/p/chromium/issues/detail?id=8152
return false;
}
bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
Event event) {
// http://code.google.com/p/chromium/issues/detail?id=8152
return false;
}
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
MemoryDetails::MemoryDetails() {
NOTIMPLEMENTED();
process_data_.push_back(ProcessData());
}
void MemoryDetails::StartFetch() {
NOTIMPLEMENTED();
OnDetailsAvailable();
// When we get the real implementation this can be removed. The Release that
// ends up deleting this object is done as the result of the PostTask in
// CollectProcessData.
Release();
}
#endif
#if defined(TOOLKIT_VIEWS)
// This should prompt the user if she wants to allow more than one concurrent
// download per tab. Until this is in place, always allow multiple downloads.
class DownloadRequestDialogDelegateStub
: public DownloadRequestDialogDelegate {
public:
explicit DownloadRequestDialogDelegateStub(
DownloadRequestManager::TabDownloadState* host)
: DownloadRequestDialogDelegate(host) { DoCancel(); }
virtual void CloseWindow() {}
};
DownloadRequestDialogDelegate* DownloadRequestDialogDelegate::Create(
TabContents* tab,
DownloadRequestManager::TabDownloadState* host) {
NOTIMPLEMENTED();
return new DownloadRequestDialogDelegateStub(host);
}
#endif
#if !defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX)
namespace download_util {
void DragDownload(const DownloadItem* download,
SkBitmap* icon,
gfx::NativeView view) {
NOTIMPLEMENTED();
}
} // namespace download_util
#endif
#if defined(OS_MACOSX)
void BrowserList::AllBrowsersClosed() {
// TODO(port): Close any dependent windows if necessary when the last browser
// window is closed.
}
//--------------------------------------------------------------------------
bool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds,
bool* maximize_new_window) const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
return true;
}
void DockInfo::AdjustOtherWindowBounds() const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
}
#endif
//------------------------------------------------------------------------------
#if defined(OS_MACOSX)
void ShowFontsLanguagesWindow(gfx::NativeWindow window,
FontsLanguagesPage page,
Profile* profile) {
NOTIMPLEMENTED();
}
#endif
//------------------------------------------------------------------------------
#if defined(TOOLKIT_VIEWS)
ConstrainedWindow* ConstrainedWindow::CreateConstrainedDialog(
TabContents* owner,
ConstrainedWindowDelegate* delegate) {
NOTIMPLEMENTED();
return NULL;
}
void BookmarkEditor::Show(gfx::NativeView parent_window,
Profile* profile,
const BookmarkNode* parent,
const BookmarkNode* node,
Configuration configuration,
Handler* handler) {
NOTIMPLEMENTED();
}
#endif
<commit_msg>[Mac] Don't call MemoryDetails::Release() from AboutMemoryHandler's constructor.<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/common/temp_scaffolding_stubs.h"
#include <vector>
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/rlz/rlz.h"
#if defined(OS_LINUX)
#include "chrome/browser/dock_info.h"
#include "chrome/common/render_messages.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/automation/automation_provider.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/fonts_languages_window.h"
#include "chrome/browser/memory_details.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_manager.h"
#include "chrome/browser/download/download_request_dialog_delegate.h"
#include "chrome/browser/download/download_request_manager.h"
#include "chrome/browser/tab_contents/constrained_window.h"
#endif
class TabContents;
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
void AutomationProvider::GetAutocompleteEditForBrowser(
int browser_handle,
bool* success,
int* autocomplete_edit_handle) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::GetAutocompleteEditText(int autocomplete_edit_handle,
bool* success,
std::wstring* text) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::SetAutocompleteEditText(int autocomplete_edit_handle,
const std::wstring& text,
bool* success) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditGetMatches(
int autocomplete_edit_handle,
bool* success,
std::vector<AutocompleteMatchData>* matches) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::AutocompleteEditIsQueryInProgress(
int autocomplete_edit_handle,
bool* success,
bool* query_in_progress) {
*success = false;
NOTIMPLEMENTED();
}
void AutomationProvider::OnMessageFromExternalHost(
int handle, const std::string& message, const std::string& origin,
const std::string& target) {
NOTIMPLEMENTED();
}
#endif // defined(OS_MACOSX)
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
// static
bool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,
const FilePath& master_prefs_path,
std::vector<std::wstring>* new_tabs,
int* ping_delay,
bool* homepage_defined) {
// http://code.google.com/p/chromium/issues/detail?id=11971
// Pretend we processed them correctly.
return true;
}
// static
int FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {
// http://code.google.com/p/chromium/issues/detail?id=11971
return 0;
}
#endif
bool FirstRun::CreateChromeDesktopShortcut() {
NOTIMPLEMENTED();
return false;
}
bool FirstRun::CreateChromeQuickLaunchShortcut() {
NOTIMPLEMENTED();
return false;
}
// static
bool Upgrade::IsBrowserAlreadyRunning() {
// http://code.google.com/p/chromium/issues/detail?id=9295
return false;
}
// static
bool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {
// http://code.google.com/p/chromium/issues/detail?id=9295
return true;
}
// static
bool Upgrade::SwapNewChromeExeIfPresent() {
// http://code.google.com/p/chromium/issues/detail?id=9295
return true;
}
// static
Upgrade::TryResult ShowTryChromeDialog(size_t version) {
return Upgrade::TD_NOT_NOW;
}
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
void InstallJankometer(const CommandLine&) {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
void UninstallJankometer() {
// http://code.google.com/p/chromium/issues/detail?id=8077
}
#endif
//--------------------------------------------------------------------------
void RLZTracker::CleanupRlz() {
// http://code.google.com/p/chromium/issues/detail?id=8152
}
bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
// http://code.google.com/p/chromium/issues/detail?id=8152
return false;
}
bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
Event event) {
// http://code.google.com/p/chromium/issues/detail?id=8152
return false;
}
//--------------------------------------------------------------------------
#if defined(OS_MACOSX)
MemoryDetails::MemoryDetails() {
NOTIMPLEMENTED();
process_data_.push_back(ProcessData());
}
void MemoryDetails::StartFetch() {
NOTIMPLEMENTED();
// Other implementations implicitly own the object by passing it to
// IO and UI tasks. This code is called from AboutMemoryHandler's
// constructor, so there is no reference to Release(), yet.
MessageLoop::current()->PostTask(
FROM_HERE, NewRunnableMethod(this, &MemoryDetails::OnDetailsAvailable));
}
#endif
#if defined(TOOLKIT_VIEWS)
// This should prompt the user if she wants to allow more than one concurrent
// download per tab. Until this is in place, always allow multiple downloads.
class DownloadRequestDialogDelegateStub
: public DownloadRequestDialogDelegate {
public:
explicit DownloadRequestDialogDelegateStub(
DownloadRequestManager::TabDownloadState* host)
: DownloadRequestDialogDelegate(host) { DoCancel(); }
virtual void CloseWindow() {}
};
DownloadRequestDialogDelegate* DownloadRequestDialogDelegate::Create(
TabContents* tab,
DownloadRequestManager::TabDownloadState* host) {
NOTIMPLEMENTED();
return new DownloadRequestDialogDelegateStub(host);
}
#endif
#if !defined(TOOLKIT_VIEWS) && !defined(OS_MACOSX)
namespace download_util {
void DragDownload(const DownloadItem* download,
SkBitmap* icon,
gfx::NativeView view) {
NOTIMPLEMENTED();
}
} // namespace download_util
#endif
#if defined(OS_MACOSX)
void BrowserList::AllBrowsersClosed() {
// TODO(port): Close any dependent windows if necessary when the last browser
// window is closed.
}
//--------------------------------------------------------------------------
bool DockInfo::GetNewWindowBounds(gfx::Rect* new_window_bounds,
bool* maximize_new_window) const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
return true;
}
void DockInfo::AdjustOtherWindowBounds() const {
// TODO(pinkerton): Implement on Mac.
// http://crbug.com/9274
}
#endif
//------------------------------------------------------------------------------
#if defined(OS_MACOSX)
void ShowFontsLanguagesWindow(gfx::NativeWindow window,
FontsLanguagesPage page,
Profile* profile) {
NOTIMPLEMENTED();
}
#endif
//------------------------------------------------------------------------------
#if defined(TOOLKIT_VIEWS)
ConstrainedWindow* ConstrainedWindow::CreateConstrainedDialog(
TabContents* owner,
ConstrainedWindowDelegate* delegate) {
NOTIMPLEMENTED();
return NULL;
}
void BookmarkEditor::Show(gfx::NativeView parent_window,
Profile* profile,
const BookmarkNode* parent,
const BookmarkNode* node,
Configuration configuration,
Handler* handler) {
NOTIMPLEMENTED();
}
#endif
<|endoftext|>
|
<commit_before>//
// DocumentParser.cpp
// Emojicode
//
// Created by Theo Weidmann on 24/04/16.
// Copyright © 2016 Theo Weidmann. All rights reserved.
//
#include "DocumentParser.hpp"
#include "FunctionParser.hpp"
#include "Functions/Function.hpp"
#include "Functions/Initializer.hpp"
#include "ProtocolTypeBodyParser.hpp"
#include "TypeBodyParser.hpp"
#include "Types/Class.hpp"
#include "Types/Enum.hpp"
#include "Types/Protocol.hpp"
#include "Types/TypeContext.hpp"
#include "Types/ValueType.hpp"
#include <cstring>
#include <experimental/optional>
namespace EmojicodeCompiler {
void DocumentParser::parse() {
while (stream_.hasMoreTokens()) {
auto documentation = Documentation().parse(&stream_);
auto attributes = PackageAttributeParser().parse(&stream_);
auto &theToken = stream_.consumeToken(TokenType::Identifier);
switch (theToken.value()[0]) {
case E_PACKAGE:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parsePackageImport(theToken.position());
continue;
case E_CROCODILE:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseProtocol(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_TURKEY:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseEnum(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_TRIANGLE_POINTED_DOWN: {
attributes.check(theToken.position(), package_->compiler());
TypeIdentifier alias = parseTypeIdentifier();
Type type = package_->getRawType(parseTypeIdentifier(), false);
package_->offerType(type, alias.name, alias.ns, false, theToken.position());
continue;
}
case E_CRYSTAL_BALL:
attributes.check(theToken.position(), package_->compiler());
parseVersion(documentation, theToken.position());
continue;
case E_WALE:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parseExtension(documentation, theToken.position());
continue;
case E_RABBIT:
parseClass(documentation.get(), theToken, attributes.has(Attribute::Export),
attributes.has(Attribute::Final));
continue;
case E_DOVE_OF_PEACE:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseValueType(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_SCROLL:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parseInclude(theToken.position());
continue;
case E_CHEQUERED_FLAG:
attributes.check(theToken.position(), package_->compiler());
parseStartFlag(documentation, theToken.position());
break;
default:
throw CompilerError(theToken.position(), "Unexpected identifier ", utf8(theToken.value()));
}
}
}
TypeIdentifier DocumentParser::parseAndValidateNewTypeName() {
auto parsedTypeName = parseTypeIdentifier();
Type type = Type::noReturn();
if (package_->lookupRawType(parsedTypeName, false, &type)) {
auto str = type.toString(TypeContext());
throw CompilerError(parsedTypeName.position, "Type ", str, " is already defined.");
}
return parsedTypeName;
}
void DocumentParser::parsePackageImport(const SourcePosition &p) {
auto &nameToken = stream_.consumeToken(TokenType::Variable);
auto &namespaceToken = stream_.consumeToken(TokenType::Identifier);
package_->importPackage(utf8(nameToken.value()), namespaceToken.value(), p);
}
void DocumentParser::parseStartFlag(const Documentation &documentation, const SourcePosition &p) {
if (package_->hasStartFlagFunction()) {
throw CompilerError(p, "Duplicate 🏁.");
}
auto function = package_->add(std::make_unique<Function>(std::u32string(1, E_CHEQUERED_FLAG), AccessLevel::Public,
false, Type::noReturn(), package_, p, false,
documentation.get(), false, false, true,
FunctionType::Function));
parseReturnType(function, TypeContext());
if (function->returnType.type() != TypeType::NoReturn &&
!function->returnType.compatibleTo(Type(package_->compiler()->sInteger, false), TypeContext())) {
throw CompilerError(p, "🏁 must either return ✨ or 🚂.");
}
stream_.consumeToken(TokenType::BlockBegin);
try {
auto ast = factorFunctionParser(package_, stream_, function->typeContext(), function)->parse();
function->setAst(ast);
}
catch (CompilerError &ce) {
package_->compiler()->error(ce);
}
package_->setStartFlagFunction(function);
}
void DocumentParser::parseInclude(const SourcePosition &p) {
auto &pathString = stream_.consumeToken(TokenType::String);
auto relativePath = std::string(pathString.position().file);
auto originalPathString = utf8(pathString.value());
auto fileString = originalPathString;
auto lastSlash = relativePath.find_last_of('/');
if (lastSlash != relativePath.npos) {
fileString = relativePath.substr(0, lastSlash) + "/" + fileString;
}
package_->includeDocument(fileString, originalPathString);
}
void DocumentParser::parseVersion(const Documentation &documentation, const SourcePosition &p) {
if (package_->validVersion()) {
package_->compiler()->error(CompilerError(p, "Package version already declared."));
return;
}
auto major = std::stoi(utf8(stream_.consumeToken(TokenType::Integer).value()));
auto minor = std::stoi(utf8(stream_.consumeToken(TokenType::Integer).value()));
package_->setPackageVersion(PackageVersion(major, minor));
if (!package_->validVersion()) {
throw CompilerError(p, "The provided package version is not valid.");
}
package_->setDocumentation(documentation.get());
}
void DocumentParser::parseExtension(const Documentation &documentation, const SourcePosition &p) {
Type type = package_->getRawType(parseTypeIdentifier(), false);
auto extension = package_->add(std::make_unique<Extension>(type, package_, p, documentation.get()));
Type extendedType = Type(extension);
switch (type.type()) {
case TypeType::Class:
ClassTypeBodyParser(extendedType, package_, stream_, interface_, std::set<std::u32string>()).parse();
break;
case TypeType::ValueType:
ValueTypeBodyParser(extendedType, package_, stream_, interface_).parse();
break;
default:
throw CompilerError(p, "Only classes and value types are extendable.");
}
}
void DocumentParser::parseProtocol(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto protocol = package_->add(std::make_unique<Protocol>(parsedTypeName.name, package_,
theToken.position(), documentation, exported));
parseGenericParameters(protocol, TypeContext(Type(protocol, false)));
auto protocolType = Type(protocol, false);
package_->offerType(protocolType, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
ProtocolTypeBodyParser(protocolType, package_, stream_, interface_).parse();
}
void DocumentParser::parseEnum(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto enumUniq = std::make_unique<Enum>(parsedTypeName.name, package_, theToken.position(), documentation, exported);
Enum *enumeration = enumUniq.get();
package_->add(std::move(enumUniq));
auto type = Type(enumeration, false);
package_->offerType(type, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
EnumTypeBodyParser(type, package_, stream_, interface_).parse();
}
void DocumentParser::parseClass(const std::u32string &documentation, const Token &theToken, bool exported, bool final) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto eclass = package_->add(std::make_unique<Class>(parsedTypeName.name, package_, theToken.position(),
documentation, exported, final));
parseGenericParameters(eclass, TypeContext(Type(eclass, false)));
if (!stream_.nextTokenIs(TokenType::BlockBegin)) {
auto classType = Type(eclass, false); // New Type due to generic arguments now (partly) available.
Type type = parseType(TypeContext(classType));
if (type.type() != TypeType::Class && !type.optional() && !type.meta()) {
throw CompilerError(parsedTypeName.position, "The superclass must be a class.");
}
if (type.eclass()->final()) {
package_->compiler()->error(CompilerError(parsedTypeName.position, type.toString(TypeContext(classType)),
" can’t be used as superclass as it was marked with 🔏."));
}
eclass->setSuperType(type);
}
auto classType = Type(eclass, false); // New Type due to generic arguments now available.
package_->offerType(classType, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
auto requiredInits = eclass->superclass() != nullptr ? eclass->superclass()->requiredInitializers() : std::set<std::u32string>();
ClassTypeBodyParser(classType, package_, stream_, interface_, requiredInits).parse();
}
void DocumentParser::parseValueType(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto valueType = package_->add(std::make_unique<ValueType>(parsedTypeName.name, package_,
theToken.position(), documentation, exported));
if (stream_.consumeTokenIf(E_WHITE_CIRCLE)) {
valueType->makePrimitive();
}
parseGenericParameters(valueType, TypeContext(Type(valueType, false)));
auto valueTypeContent = Type(valueType, false);
package_->offerType(valueTypeContent, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
ValueTypeBodyParser(valueTypeContent, package_, stream_, interface_).parse();
}
} // namespace EmojicodeCompiler
<commit_msg>🥨 Improve error message<commit_after>//
// DocumentParser.cpp
// Emojicode
//
// Created by Theo Weidmann on 24/04/16.
// Copyright © 2016 Theo Weidmann. All rights reserved.
//
#include "DocumentParser.hpp"
#include "FunctionParser.hpp"
#include "Functions/Function.hpp"
#include "Functions/Initializer.hpp"
#include "ProtocolTypeBodyParser.hpp"
#include "TypeBodyParser.hpp"
#include "Types/Class.hpp"
#include "Types/Enum.hpp"
#include "Types/Protocol.hpp"
#include "Types/TypeContext.hpp"
#include "Types/ValueType.hpp"
#include <cstring>
#include <experimental/optional>
namespace EmojicodeCompiler {
void DocumentParser::parse() {
while (stream_.hasMoreTokens()) {
auto documentation = Documentation().parse(&stream_);
auto attributes = PackageAttributeParser().parse(&stream_);
auto &theToken = stream_.consumeToken(TokenType::Identifier);
switch (theToken.value()[0]) {
case E_PACKAGE:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parsePackageImport(theToken.position());
continue;
case E_CROCODILE:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseProtocol(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_TURKEY:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseEnum(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_TRIANGLE_POINTED_DOWN: {
attributes.check(theToken.position(), package_->compiler());
TypeIdentifier alias = parseTypeIdentifier();
Type type = package_->getRawType(parseTypeIdentifier(), false);
package_->offerType(type, alias.name, alias.ns, false, theToken.position());
continue;
}
case E_CRYSTAL_BALL:
attributes.check(theToken.position(), package_->compiler());
parseVersion(documentation, theToken.position());
continue;
case E_WALE:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parseExtension(documentation, theToken.position());
continue;
case E_RABBIT:
parseClass(documentation.get(), theToken, attributes.has(Attribute::Export),
attributes.has(Attribute::Final));
continue;
case E_DOVE_OF_PEACE:
attributes.allow(Attribute::Export).check(theToken.position(), package_->compiler());
parseValueType(documentation.get(), theToken, attributes.has(Attribute::Export));
continue;
case E_SCROLL:
attributes.check(theToken.position(), package_->compiler());
documentation.disallow();
parseInclude(theToken.position());
continue;
case E_CHEQUERED_FLAG:
attributes.check(theToken.position(), package_->compiler());
parseStartFlag(documentation, theToken.position());
break;
default:
throw CompilerError(theToken.position(), "Unexpected identifier ", utf8(theToken.value()));
}
}
}
TypeIdentifier DocumentParser::parseAndValidateNewTypeName() {
auto parsedTypeName = parseTypeIdentifier();
Type type = Type::noReturn();
if (package_->lookupRawType(parsedTypeName, false, &type)) {
auto str = type.toString(TypeContext());
throw CompilerError(parsedTypeName.position, "Type ", str, " is already defined.");
}
return parsedTypeName;
}
void DocumentParser::parsePackageImport(const SourcePosition &p) {
auto &nameToken = stream_.consumeToken(TokenType::Variable);
auto &namespaceToken = stream_.consumeToken(TokenType::Identifier);
package_->importPackage(utf8(nameToken.value()), namespaceToken.value(), p);
}
void DocumentParser::parseStartFlag(const Documentation &documentation, const SourcePosition &p) {
if (package_->hasStartFlagFunction()) {
throw CompilerError(p, "Duplicate 🏁.");
}
auto function = package_->add(std::make_unique<Function>(std::u32string(1, E_CHEQUERED_FLAG), AccessLevel::Public,
false, Type::noReturn(), package_, p, false,
documentation.get(), false, false, true,
FunctionType::Function));
parseReturnType(function, TypeContext());
if (function->returnType().type() != TypeType::NoReturn &&
!function->returnType().compatibleTo(Type(package_->compiler()->sInteger, false), TypeContext())) {
package_->compiler()->error(CompilerError(p, "🏁 must either have no return or return 🔢."));
}
stream_.consumeToken(TokenType::BlockBegin);
try {
auto ast = factorFunctionParser(package_, stream_, function->typeContext(), function)->parse();
function->setAst(ast);
}
catch (CompilerError &ce) {
package_->compiler()->error(ce);
}
package_->setStartFlagFunction(function);
}
void DocumentParser::parseInclude(const SourcePosition &p) {
auto &pathString = stream_.consumeToken(TokenType::String);
auto relativePath = std::string(pathString.position().file);
auto originalPathString = utf8(pathString.value());
auto fileString = originalPathString;
auto lastSlash = relativePath.find_last_of('/');
if (lastSlash != relativePath.npos) {
fileString = relativePath.substr(0, lastSlash) + "/" + fileString;
}
package_->includeDocument(fileString, originalPathString);
}
void DocumentParser::parseVersion(const Documentation &documentation, const SourcePosition &p) {
if (package_->validVersion()) {
package_->compiler()->error(CompilerError(p, "Package version already declared."));
return;
}
auto major = std::stoi(utf8(stream_.consumeToken(TokenType::Integer).value()));
auto minor = std::stoi(utf8(stream_.consumeToken(TokenType::Integer).value()));
package_->setPackageVersion(PackageVersion(major, minor));
if (!package_->validVersion()) {
throw CompilerError(p, "The provided package version is not valid.");
}
package_->setDocumentation(documentation.get());
}
void DocumentParser::parseExtension(const Documentation &documentation, const SourcePosition &p) {
Type type = package_->getRawType(parseTypeIdentifier(), false);
auto extension = package_->add(std::make_unique<Extension>(type, package_, p, documentation.get()));
Type extendedType = Type(extension);
switch (type.type()) {
case TypeType::Class:
ClassTypeBodyParser(extendedType, package_, stream_, interface_, std::set<std::u32string>()).parse();
break;
case TypeType::ValueType:
ValueTypeBodyParser(extendedType, package_, stream_, interface_).parse();
break;
default:
throw CompilerError(p, "Only classes and value types are extendable.");
}
}
void DocumentParser::parseProtocol(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto protocol = package_->add(std::make_unique<Protocol>(parsedTypeName.name, package_,
theToken.position(), documentation, exported));
parseGenericParameters(protocol, TypeContext(Type(protocol, false)));
auto protocolType = Type(protocol, false);
package_->offerType(protocolType, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
ProtocolTypeBodyParser(protocolType, package_, stream_, interface_).parse();
}
void DocumentParser::parseEnum(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto enumUniq = std::make_unique<Enum>(parsedTypeName.name, package_, theToken.position(), documentation, exported);
Enum *enumeration = enumUniq.get();
package_->add(std::move(enumUniq));
auto type = Type(enumeration, false);
package_->offerType(type, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
EnumTypeBodyParser(type, package_, stream_, interface_).parse();
}
void DocumentParser::parseClass(const std::u32string &documentation, const Token &theToken, bool exported, bool final) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto eclass = package_->add(std::make_unique<Class>(parsedTypeName.name, package_, theToken.position(),
documentation, exported, final));
parseGenericParameters(eclass, TypeContext(Type(eclass, false)));
if (!stream_.nextTokenIs(TokenType::BlockBegin)) {
auto classType = Type(eclass, false); // New Type due to generic arguments now (partly) available.
Type type = parseType(TypeContext(classType));
if (type.type() != TypeType::Class && !type.optional() && !type.meta()) {
throw CompilerError(parsedTypeName.position, "The superclass must be a class.");
}
if (type.eclass()->final()) {
package_->compiler()->error(CompilerError(parsedTypeName.position, type.toString(TypeContext(classType)),
" can’t be used as superclass as it was marked with 🔏."));
}
eclass->setSuperType(type);
}
auto classType = Type(eclass, false); // New Type due to generic arguments now available.
package_->offerType(classType, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
auto requiredInits = eclass->superclass() != nullptr ? eclass->superclass()->requiredInitializers() : std::set<std::u32string>();
ClassTypeBodyParser(classType, package_, stream_, interface_, requiredInits).parse();
}
void DocumentParser::parseValueType(const std::u32string &documentation, const Token &theToken, bool exported) {
auto parsedTypeName = parseAndValidateNewTypeName();
auto valueType = package_->add(std::make_unique<ValueType>(parsedTypeName.name, package_,
theToken.position(), documentation, exported));
if (stream_.consumeTokenIf(E_WHITE_CIRCLE)) {
valueType->makePrimitive();
}
parseGenericParameters(valueType, TypeContext(Type(valueType, false)));
auto valueTypeContent = Type(valueType, false);
package_->offerType(valueTypeContent, parsedTypeName.name, parsedTypeName.ns, exported, theToken.position());
ValueTypeBodyParser(valueTypeContent, package_, stream_, interface_).parse();
}
} // namespace EmojicodeCompiler
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cmath>
#include <limits>
#include <utility>
#include "geom/bounding_box.h"
namespace Svit
{
void
BoundingBox::extend (Point3& _point)
{
switch (size_type)
{
case EMPTY:
min = _point;
max = _point;
size_type = BOUNDED;
break;
case BOUNDED:
{
float min_x = fmin(min.x, _point.x);
float min_y = fmin(min.y, _point.y);
float min_z = fmin(min.z, _point.z);
min = Point3(min_x, min_y, min_z);
float max_x = fmax(max.x, _point.x);
float max_y = fmax(max.y, _point.y);
float max_z = fmax(max.z, _point.z);
max = Point3(max_x, max_y, max_z);
}
break;
case FULL:
default:
break;
}
}
void
BoundingBox::extend (BoundingBox& _bounding_box)
{
switch (size_type)
{
case EMPTY:
switch (_bounding_box.size_type)
{
case FULL:
size_type = FULL;
break;
case BOUNDED:
min = _bounding_box.min;
max = _bounding_box.max;
size_type = BOUNDED;
break;
case EMPTY:
default:
break;
}
case BOUNDED:
switch (_bounding_box.size_type)
{
case FULL:
size_type = FULL;
break;
case BOUNDED:
extend(_bounding_box.min);
extend(_bounding_box.max);
break;
case EMPTY:
default:
break;
}
case FULL:
default:
break;
}
}
bool
BoundingBox::intersect (Ray& _ray, float* _t_near, float* _t_far)
{
float t0 = std::numeric_limits<float>::min();
float t1 = std::numeric_limits<float>::max();
for (int i = 0; i < 3; ++i)
{
float inv_ray_dir = 1.0f / _ray.direction[i];
float t_near = (min[i] - _ray.origin[i]) * inv_ray_dir;
float t_far = (max[i] - _ray.origin[i]) * inv_ray_dir;
if (tNear > tFar)
std::swap(tNear, tFar);
t0 = tNear > t0 ? tNear : t0;
t1 = tFar < t1 ? tFar : t1;
if (t0 > t1)
return false;
}
*_t_near = t0;
*_t_far = t1;
return true;
}
bool
BoundingBox::contains (Point3& _point)
{
return (_point.x > min.x && _point.x < max.x &&
_point.y > min.y && _point.y < max.y &&
_point.z > min.z && _point.z < max.z);
}
Point3
BoundingBox::centroid ()
{
return (min + max) / 2.0f;
}
void
BoundingBox::dump (std::string _name, unsigned int _level)
{
std::cout << std::string(' ', _level*2)
<< _name
<< " = BoundingBox"
<< std::endl;
min.dump("min", _level+1);
max.dump("max", _level+1);
}
}
<commit_msg>Fixed wrong variable names<commit_after>#include <algorithm>
#include <cmath>
#include <limits>
#include <utility>
#include "geom/bounding_box.h"
namespace Svit
{
void
BoundingBox::extend (Point3& _point)
{
switch (size_type)
{
case EMPTY:
min = _point;
max = _point;
size_type = BOUNDED;
break;
case BOUNDED:
{
float min_x = fmin(min.x, _point.x);
float min_y = fmin(min.y, _point.y);
float min_z = fmin(min.z, _point.z);
min = Point3(min_x, min_y, min_z);
float max_x = fmax(max.x, _point.x);
float max_y = fmax(max.y, _point.y);
float max_z = fmax(max.z, _point.z);
max = Point3(max_x, max_y, max_z);
}
break;
case FULL:
default:
break;
}
}
void
BoundingBox::extend (BoundingBox& _bounding_box)
{
switch (size_type)
{
case EMPTY:
switch (_bounding_box.size_type)
{
case FULL:
size_type = FULL;
break;
case BOUNDED:
min = _bounding_box.min;
max = _bounding_box.max;
size_type = BOUNDED;
break;
case EMPTY:
default:
break;
}
case BOUNDED:
switch (_bounding_box.size_type)
{
case FULL:
size_type = FULL;
break;
case BOUNDED:
extend(_bounding_box.min);
extend(_bounding_box.max);
break;
case EMPTY:
default:
break;
}
case FULL:
default:
break;
}
}
bool
BoundingBox::intersect (Ray& _ray, float* _t_near, float* _t_far)
{
float t0 = std::numeric_limits<float>::min();
float t1 = std::numeric_limits<float>::max();
for (int i = 0; i < 3; ++i)
{
float inv_ray_dir = 1.0f / _ray.direction[i];
float t_near = (min[i] - _ray.origin[i]) * inv_ray_dir;
float t_far = (max[i] - _ray.origin[i]) * inv_ray_dir;
if (t_near > t_far)
std::swap(t_near, t_far);
t0 = t_near > t0 ? t_near : t0;
t1 = t_far < t1 ? t_far : t1;
if (t0 > t1)
return false;
}
*_t_near = t0;
*_t_far = t1;
return true;
}
bool
BoundingBox::contains (Point3& _point)
{
return (_point.x > min.x && _point.x < max.x &&
_point.y > min.y && _point.y < max.y &&
_point.z > min.z && _point.z < max.z);
}
Point3
BoundingBox::centroid ()
{
return (min + max) / 2.0f;
}
void
BoundingBox::dump (std::string _name, unsigned int _level)
{
std::cout << std::string(' ', _level*2)
<< _name
<< " = BoundingBox"
<< std::endl;
min.dump("min", _level+1);
max.dump("max", _level+1);
}
}
<|endoftext|>
|
<commit_before>/*
FILENAME: DrawManager.cpp
AUTHOR: Salinder Sidhu
DESCRIPTION: Implementation for DrawManager.h.
UPDATE DATE: 12/22/2015
*/
#include "DrawManager.h"
/* PhyfsStreamException class*/
PhyfsStreamException::PhyfsStreamException(string action) {
message = "PhyfsStreamException: Could not perform required action: '" + action + "'";
}
/* ResourceNotLoadedException class */
ResourceNotLoadedException::ResourceNotLoadedException(string resourceType, string resourceFilePath) {
message = "ResourceNotLoadedException: Can't load resource of type '" + resourceType + "' from '" + resourceFilePath + "'";
}
/* ResourceNotFoundException class */
ResourceNotFoundException::ResourceNotFoundException(string resourceType, int resourceID) {
message = "ResourceNotFoundException: Can't locate resource of type '" + resourceType + "' with ID '" + to_string(resourceID) + "'";
}
/* DrawManager class */
DrawManager::DrawManager(sf::RenderWindow *window, string *resourceArchive) {
canvasWindow = window;
// Initalize the PHYSFS system
PHYSFS_init(NULL);
// Open the resource archive with PHYSFS
PHYSFS_addToSearchPath(resourceArchive->c_str(), 1);
}
DrawManager::~DrawManager() {
// De initalize the PHYSFS system
PHYSFS_deinit();
}
void DrawManager::loadSpriteTexture(SPRITE spriteId, string filePath) {
// Load the texture from the resource file using the custom input stream
if (!archiveStream.open(&filePath)) {
// Throw PhyfsStreamException
throw PhyfsStreamException("Loading from archive: " + filePath);
}
// Obtain the texture from the stream
sf::Texture texture;
if (texture.loadFromStream(archiveStream)) {
texturesMap[spriteId] = texture;
// Close the stream
archiveStream.close();
} else {
// Throw a ResourceNotLoadedException
throw ResourceNotLoadedException("Texture", filePath);
}
}
void DrawManager::loadTextFont(TEXTS fontId, string filePath) {
// Load the texture from the resource file using the custom input stream
if (!archiveStream.open(&filePath)) {
// Throw PhyfsStreamException
throw PhyfsStreamException("Loading from archive: " + filePath);
}
sf::Font font;
if (font.loadFromStream(archiveStream)) {
fontsMap[fontId] = font;
// Note: Stream is not closed because SFML can't preload all the data.
} else {
// Throw a ResourceNotLoadedException
throw ResourceNotLoadedException("Font", filePath);
}
}
void DrawManager::configSpritePosition(SPRITE spriteId, float positionX, float positionY) {
if (texturesMap.find(spriteId) != texturesMap.end()) {
sf::Sprite sprite;
sprite.setTexture(texturesMap[spriteId]);
sprite.setPosition(positionX, positionY);
spritesMap[spriteId] = sprite;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Sprite", spriteId);
}
}
void DrawManager::configText(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float positionX, float positionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
text.setPosition(positionX, positionY);
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::configTextCenterHorizontal(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float positionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
sf::FloatRect textRect;
// Configure text's attributes
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
// Center the text horizontally
textRect = text.getLocalBounds();
text.setOrigin((textRect.left + textRect.width) / 2, 0);
text.setPosition(WINDOW_WIDTH / 2, positionY);
// Add the text to the map
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::configTextCenterRectangle(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float startPositionX, float startPositionY, float endPositionX, float endPositionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
sf::FloatRect textRect;
// Configure text's attributes
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
// Center the text in a rectangular area
textRect = text.getLocalBounds();
text.setOrigin((textRect.left + textRect.width) / 2, (textRect.top + textRect.height) / 2);
text.setPosition(startPositionX + ((endPositionX - startPositionX) / 2), (startPositionY - 5) + ((endPositionY - startPositionY) / 2));
// Add the text to the map
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::drawSprite(SPRITE spriteId) {
if (spritesMap.find(spriteId) != spritesMap.end()) {
canvasWindow->draw(spritesMap[spriteId]);
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Sprite", spriteId);
}
}
void DrawManager::drawText(TEXTS fontId) {
if (textsMap.find(fontId) != textsMap.end()) {
canvasWindow->draw(textsMap[fontId]);
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}<commit_msg>Updated resource related error messages<commit_after>/*
FILENAME: DrawManager.cpp
AUTHOR: Salinder Sidhu
DESCRIPTION: Implementation for DrawManager.h.
UPDATE DATE: 12/22/2015
*/
#include "DrawManager.h"
/* PhyfsStreamException class*/
PhyfsStreamException::PhyfsStreamException(string action) {
message = "Error: Could not perform required action: '" + action + "'";
}
/* ResourceNotLoadedException class */
ResourceNotLoadedException::ResourceNotLoadedException(string resourceType, string resourceFilePath) {
message = "Error: Can't load resource of type '" + resourceType + "' from '" + resourceFilePath + "'";
}
/* ResourceNotFoundException class */
ResourceNotFoundException::ResourceNotFoundException(string resourceType, int resourceID) {
message = "Error: Can't locate resource of type '" + resourceType + "' with ID '" + to_string(resourceID) + "'";
}
/* DrawManager class */
DrawManager::DrawManager(sf::RenderWindow *window, string *resourceArchive) {
canvasWindow = window;
// Initalize the PHYSFS system
PHYSFS_init(NULL);
// Open the resource archive with PHYSFS
PHYSFS_addToSearchPath(resourceArchive->c_str(), 1);
}
DrawManager::~DrawManager() {
// De initalize the PHYSFS system
PHYSFS_deinit();
}
void DrawManager::loadSpriteTexture(SPRITE spriteId, string filePath) {
// Load the texture from the resource file using the custom input stream
if (!archiveStream.open(&filePath)) {
// Throw PhyfsStreamException
throw PhyfsStreamException("Loading from archive: " + filePath);
}
// Obtain the texture from the stream
sf::Texture texture;
if (texture.loadFromStream(archiveStream)) {
texturesMap[spriteId] = texture;
// Close the stream
archiveStream.close();
} else {
// Throw a ResourceNotLoadedException
throw ResourceNotLoadedException("Texture", filePath);
}
}
void DrawManager::loadTextFont(TEXTS fontId, string filePath) {
// Load the texture from the resource file using the custom input stream
if (!archiveStream.open(&filePath)) {
// Throw PhyfsStreamException
throw PhyfsStreamException("Loading from archive: " + filePath);
}
sf::Font font;
if (font.loadFromStream(archiveStream)) {
fontsMap[fontId] = font;
// Note: Stream is not closed because SFML can't preload all the data.
} else {
// Throw a ResourceNotLoadedException
throw ResourceNotLoadedException("Font", filePath);
}
}
void DrawManager::configSpritePosition(SPRITE spriteId, float positionX, float positionY) {
if (texturesMap.find(spriteId) != texturesMap.end()) {
sf::Sprite sprite;
sprite.setTexture(texturesMap[spriteId]);
sprite.setPosition(positionX, positionY);
spritesMap[spriteId] = sprite;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Sprite", spriteId);
}
}
void DrawManager::configText(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float positionX, float positionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
text.setPosition(positionX, positionY);
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::configTextCenterHorizontal(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float positionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
sf::FloatRect textRect;
// Configure text's attributes
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
// Center the text horizontally
textRect = text.getLocalBounds();
text.setOrigin((textRect.left + textRect.width) / 2, 0);
text.setPosition(WINDOW_WIDTH / 2, positionY);
// Add the text to the map
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::configTextCenterRectangle(TEXTS fontId, unsigned int fontSize, sf::Color fontColor, string textString, float startPositionX, float startPositionY, float endPositionX, float endPositionY) {
if (fontsMap.find(fontId) != fontsMap.end()) {
sf::Text text;
sf::FloatRect textRect;
// Configure text's attributes
text.setFont(fontsMap[fontId]);
text.setCharacterSize(fontSize);
text.setColor(fontColor);
text.setString(textString);
// Center the text in a rectangular area
textRect = text.getLocalBounds();
text.setOrigin((textRect.left + textRect.width) / 2, (textRect.top + textRect.height) / 2);
text.setPosition(startPositionX + ((endPositionX - startPositionX) / 2), (startPositionY - 5) + ((endPositionY - startPositionY) / 2));
// Add the text to the map
textsMap[fontId] = text;
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}
void DrawManager::drawSprite(SPRITE spriteId) {
if (spritesMap.find(spriteId) != spritesMap.end()) {
canvasWindow->draw(spritesMap[spriteId]);
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Sprite", spriteId);
}
}
void DrawManager::drawText(TEXTS fontId) {
if (textsMap.find(fontId) != textsMap.end()) {
canvasWindow->draw(textsMap[fontId]);
} else {
// Throw a ResourceNotFoundException
throw ResourceNotFoundException("Text", fontId);
}
}<|endoftext|>
|
<commit_before>#include <iostream>
#include <cmath>
using namespace std;
bool is_prime(unsigned long long n){
if (n == 2) return true;
if (n % 2 == 0 || n < 2) return false;
for (unsigned long i = 3; i <= sqrt(n); i += 2){
if (n % i == 0) return false;
}
return true;
}
int main(){
int c = 0;
unsigned long long n = 1;
while(n++){
if (is_prime(n))
c++;
if (c == 10001){
cout << n << endl;
break;
}
}
return 0;
}<commit_msg>Formata código.<commit_after>#include <iostream>
#include <cmath>
using namespace std;
bool is_prime(unsigned long long n) {
if (n == 2) return true;
if (n % 2 == 0 || n < 2) return false;
for (unsigned long i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) return false;
}
return true;
}
int main(){
int c = 0;
unsigned long long n = 1;
while(n++) {
if (is_prime(n)) c++;
if (c == 10001) {
cout << n << endl;
break;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@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 <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QGraphicsProxyWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QQuickItem>
#include <QQuickView>
#include <QLocale>
#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MLocale>
#endif
TasUiTraverser::TasUiTraverser(QHash<QString, TasTraverseInterface*> traversers)
{
mTraversers = traversers;
}
TasUiTraverser::~TasUiTraverser()
{
mTraversers.clear();
mPluginBlackList.clear();
mPluginWhiteList.clear();
}
void TasUiTraverser::setFilterLists(TasCommand* command)
{
mPluginBlackList.clear();
mPluginWhiteList.clear();
if(!command) return;
if(!command->apiParameter("pluginBlackList").isEmpty()){
mPluginBlackList = command->apiParameter("pluginBlackList").split(",");
}
if(!command->apiParameter("pluginWhiteList").isEmpty()){
mPluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
}
}
bool TasUiTraverser::filterPlugin(const QString& pluginName)
{
bool filter = true;
if(mPluginWhiteList.isEmpty() && mPluginBlackList.isEmpty()){
filter = false;
}
//black list is valued higher than white list
else if(mPluginWhiteList.contains(pluginName) && !mPluginBlackList.contains(pluginName)){
filter = false;
}
else if(mPluginWhiteList.isEmpty() && !mPluginBlackList.contains(pluginName)){
filter = false;
}
return filter;
}
void TasUiTraverser::initializeTraverse(TasCommand* command)
{
setFilterLists(command);
//let traversers know that a new traverse operation is starting
QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
while (traversers.hasNext()) {
traversers.next();
traversers.value()->beginTraverse(command);
}
}
void TasUiTraverser::finalizeTraverse()
{
//let traversers know that a new traverse operation is starting
QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
while (traversers.hasNext()) {
traversers.next();
traversers.value()->endTraverse();
}
}
TasObject& TasUiTraverser::addModelRoot(TasDataModel& model, TasCommand* command)
{
TasObjectContainer& container = model.addNewObjectContainer("qt", "sut");
container.setId(qVersion());
QString appName = getApplicationName();
TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), appName, "application");
if(appName == PENINPUT_SERVER){
application.setType(VKB_IDENTIFIER);
}
addApplicationDetails(application, command);
return application;
}
TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
initializeTraverse(command);
TasDataModel* model = new TasDataModel();
TasObject& application = addModelRoot(*model, command);
QWidgetList widgetList = qApp->topLevelWidgets();
if (!widgetList.empty()){
QListIterator<QWidget*> iter(qApp->topLevelWidgets());
while(iter.hasNext()){
QWidget *widget = iter.next();
//only print widgets if they are visible
if (!widget->graphicsProxyWidget() && (TestabilityUtils::isCustomTraverse() || widget->isVisible())){
//widgets that have a parent will not be traversed unless the parent is the app
//this is done to avoid objects being traversed more than once
if(!widget->parent() || widget->parent() == qApp){
traverseObject(application.addObject(), widget, command);
}
}
}
}
foreach (QWindow* w, qApp->topLevelWindows()) {
traverseObject(application.addObject(), w, command);
}
finalizeTraverse();
return model;
}
void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command, bool traverseChildren)
{
QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
while (i.hasNext()) {
i.next();
if(!filterPlugin(i.key())){
i.value()->traverseObject(&objectInfo, object, command);
}
}
if(traverseChildren){
printActions(objectInfo, object);
}
if (traverseChildren) {
QQuickView* quickView = qobject_cast<QQuickView*>(object);
if (quickView) {
QQuickItem* root = quickView->rootObject();
if (root) {
traverseObject(objectInfo.addObject(), root, command);
}
}
QQuickItem* quickItem = qobject_cast<QQuickItem*>(object);
if (quickItem) {
foreach(QQuickItem* child, quickItem->childItems()) {
traverseObject(objectInfo.addObject(), child, command);
}
}
// support for QML Window.
QQuickWindow* quickWindow = qobject_cast<QQuickWindow*>(object);
if (quickWindow) {
QQuickItem* root = quickWindow->contentItem();
if (root) {
traverseObject(objectInfo.addObject(), root, command);
}
}
//check decendants
//1. is graphicsview
QGraphicsView* gView = qobject_cast<QGraphicsView*>(object);
if(gView){
traverseGraphicsViewItems(objectInfo, gView, command);
}
//2. is QGraphicsObject
QGraphicsObject* graphicsObject = qobject_cast<QGraphicsObject*>(object);
if(graphicsObject){
traverseGraphicsItemList(objectInfo, graphicsObject,command);
}
//3. Widget children
else{
QObjectList children = object->children();
if (!children.isEmpty()) {
for (int i = 0; i < children.size(); ++i){
QObject *obj = children.at(i);
//only include widgets
if (obj->isWidgetType() && obj->parent() == object){
QWidget *widget = qobject_cast<QWidget*>(obj);
// TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
traverseObject(objectInfo.addObject(), widget, command);
}
}
}
}
}
}
}
void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command, bool traverseChildren)
{
QGraphicsObject* object = graphicsItem->toGraphicsObject();
if (object) {
traverseObject(objectInfo, object, command);
// Traverse the actual widget under the proxy, if available
QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
if (proxy) {
traverseObject(objectInfo.addObject(), proxy->widget(), command, traverseChildren);
}
}
else{
objectInfo.setType("QGraphicsItem");
QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
while (i.hasNext()) {
i.next();
if(!filterPlugin(i.key())){
i.value()->traverseGraphicsItem(&objectInfo, graphicsItem, command);
}
}
if(traverseChildren){
traverseGraphicsItemList(objectInfo, graphicsItem, command);
}
}
}
void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
foreach (QGraphicsItem* item, graphicsItem->childItems()){
if(graphicsItem == item->parentItem()){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
foreach(QGraphicsItem* item, view->items()){
if(item->parentItem() == 0){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse() || item->isVisible()) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
traverseObject(application, qApp, command, false);
application.setEnv("qt");
//set these again cause properties overwrite them
application.setName(getApplicationName());
application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
application.addAttribute("applicationUid", QString::number(uid));
CWsScreenDevice* sws = new ( ELeave ) CWsScreenDevice( CEikonEnv::Static()->WsSession() );
CleanupStack::PushL( sws );
if( sws->Construct() == KErrNone)
{
TPixelsAndRotation sizeAndRotation;
sws->GetDefaultScreenSizeAndRotation( sizeAndRotation );
qApp->setProperty(APP_ROTATION, QVariant(sizeAndRotation.iRotation));
application.addAttribute(APP_ROTATION, sizeAndRotation.iRotation);
}
CleanupStack::PopAndDestroy( sws );
#endif
application.addAttribute("arguments", qApp->arguments().join(" ").toLatin1().data());
application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
application.addAttribute("objectId", TasCoreUtils::objectId(qApp));
int mem = TasDeviceUtils::currentProcessHeapSize();
if(mem != -1){
application.addAttribute("memUsage", mem);
}
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
MApplication* app = MApplication::instance();
if (app){
MLocale defaultMLocale;
application.addAttribute("localeName", defaultMLocale.name());
application.addAttribute("localeCountry", defaultMLocale.country());
application.addAttribute("localeLanguage", defaultMLocale.language());
}
else{
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
}
#else
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
#endif
}
/*!
Prints all of the actions that a widget has under the widget.
Makes it possible to easily map the correct action to the
correct widget and also command the correct widget.
Returns true if an action was added.
*/
void TasUiTraverser::printActions(TasObject& objectInfo, QObject* object)
{
QWidget* widget = qobject_cast<QWidget*>(object);
if(widget){
addActions(objectInfo, widget->actions());
}
else{
QGraphicsWidget* gWidget = qobject_cast<QGraphicsWidget*>(object);
if(gWidget){
addActions(objectInfo, gWidget->actions());
}
}
}
void TasUiTraverser::addActions(TasObject& parentObject, QList<QAction*> actions)
{
if(actions.size() > 0){
for(int i = 0 ; i < actions.size(); i++){
QObject* action = actions.at(i);
traverseObject(parentObject.addObject(), action, 0);
}
}
}
<commit_msg>Fix duplicate items in traversal tree when using QGuiApplication and QQuickView with QQuickItem as root. The QQuickView can be casted into QQuickWindow so it needs to be handled with care.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@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 <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QGraphicsProxyWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QQuickItem>
#include <QQuickView>
#include <QLocale>
#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
#include <MApplication>
#include <MLocale>
#endif
TasUiTraverser::TasUiTraverser(QHash<QString, TasTraverseInterface*> traversers)
{
mTraversers = traversers;
}
TasUiTraverser::~TasUiTraverser()
{
mTraversers.clear();
mPluginBlackList.clear();
mPluginWhiteList.clear();
}
void TasUiTraverser::setFilterLists(TasCommand* command)
{
mPluginBlackList.clear();
mPluginWhiteList.clear();
if(!command) return;
if(!command->apiParameter("pluginBlackList").isEmpty()){
mPluginBlackList = command->apiParameter("pluginBlackList").split(",");
}
if(!command->apiParameter("pluginWhiteList").isEmpty()){
mPluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
}
}
bool TasUiTraverser::filterPlugin(const QString& pluginName)
{
bool filter = true;
if(mPluginWhiteList.isEmpty() && mPluginBlackList.isEmpty()){
filter = false;
}
//black list is valued higher than white list
else if(mPluginWhiteList.contains(pluginName) && !mPluginBlackList.contains(pluginName)){
filter = false;
}
else if(mPluginWhiteList.isEmpty() && !mPluginBlackList.contains(pluginName)){
filter = false;
}
return filter;
}
void TasUiTraverser::initializeTraverse(TasCommand* command)
{
setFilterLists(command);
//let traversers know that a new traverse operation is starting
QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
while (traversers.hasNext()) {
traversers.next();
traversers.value()->beginTraverse(command);
}
}
void TasUiTraverser::finalizeTraverse()
{
//let traversers know that a new traverse operation is starting
QHashIterator<QString, TasTraverseInterface*> traversers(mTraversers);
while (traversers.hasNext()) {
traversers.next();
traversers.value()->endTraverse();
}
}
TasObject& TasUiTraverser::addModelRoot(TasDataModel& model, TasCommand* command)
{
TasObjectContainer& container = model.addNewObjectContainer("qt", "sut");
container.setId(qVersion());
QString appName = getApplicationName();
TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), appName, "application");
if(appName == PENINPUT_SERVER){
application.setType(VKB_IDENTIFIER);
}
addApplicationDetails(application, command);
return application;
}
TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
initializeTraverse(command);
TasDataModel* model = new TasDataModel();
TasObject& application = addModelRoot(*model, command);
QWidgetList widgetList = qApp->topLevelWidgets();
if (!widgetList.empty()){
QListIterator<QWidget*> iter(qApp->topLevelWidgets());
while(iter.hasNext()){
QWidget *widget = iter.next();
//only print widgets if they are visible
if (!widget->graphicsProxyWidget() && (TestabilityUtils::isCustomTraverse() || widget->isVisible())){
//widgets that have a parent will not be traversed unless the parent is the app
//this is done to avoid objects being traversed more than once
if(!widget->parent() || widget->parent() == qApp){
traverseObject(application.addObject(), widget, command);
}
}
}
}
foreach (QWindow* w, qApp->topLevelWindows()) {
traverseObject(application.addObject(), w, command);
}
finalizeTraverse();
return model;
}
void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command, bool traverseChildren)
{
QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
while (i.hasNext()) {
i.next();
if(!filterPlugin(i.key())){
i.value()->traverseObject(&objectInfo, object, command);
}
}
if(traverseChildren){
printActions(objectInfo, object);
}
if (traverseChildren) {
QQuickView* quickView = qobject_cast<QQuickView*>(object);
if (quickView) {
QQuickItem* root = quickView->rootObject();
if (root) {
traverseObject(objectInfo.addObject(), root, command);
}
}
QQuickItem* quickItem = qobject_cast<QQuickItem*>(object);
if (quickItem) {
foreach(QQuickItem* child, quickItem->childItems()) {
traverseObject(objectInfo.addObject(), child, command);
}
}
// support for QML Window.
if (QString::fromLatin1(object->metaObject()->className()).compare("QQuickView")!=0) {
QQuickWindow* quickWindow = qobject_cast<QQuickWindow*>(object);
if (quickWindow) {
QQuickItem* root = quickWindow->contentItem();
if (root) {
traverseObject(objectInfo.addObject(), root, command);
}
}
}
//check decendants
//1. is graphicsview
QGraphicsView* gView = qobject_cast<QGraphicsView*>(object);
if(gView){
traverseGraphicsViewItems(objectInfo, gView, command);
}
//2. is QGraphicsObject
QGraphicsObject* graphicsObject = qobject_cast<QGraphicsObject*>(object);
if(graphicsObject){
traverseGraphicsItemList(objectInfo, graphicsObject,command);
}
//3. Widget children
else{
QObjectList children = object->children();
if (!children.isEmpty()) {
for (int i = 0; i < children.size(); ++i){
QObject *obj = children.at(i);
//only include widgets
if (obj->isWidgetType() && obj->parent() == object){
QWidget *widget = qobject_cast<QWidget*>(obj);
// TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
traverseObject(objectInfo.addObject(), widget, command);
}
}
}
}
}
}
}
void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command, bool traverseChildren)
{
QGraphicsObject* object = graphicsItem->toGraphicsObject();
if (object) {
traverseObject(objectInfo, object, command);
// Traverse the actual widget under the proxy, if available
QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
if (proxy) {
traverseObject(objectInfo.addObject(), proxy->widget(), command, traverseChildren);
}
}
else{
objectInfo.setType("QGraphicsItem");
QHashIterator<QString, TasTraverseInterface*> i(mTraversers);
while (i.hasNext()) {
i.next();
if(!filterPlugin(i.key())){
i.value()->traverseGraphicsItem(&objectInfo, graphicsItem, command);
}
}
if(traverseChildren){
traverseGraphicsItemList(objectInfo, graphicsItem, command);
}
}
}
void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
foreach (QGraphicsItem* item, graphicsItem->childItems()){
if(graphicsItem == item->parentItem()){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
foreach(QGraphicsItem* item, view->items()){
if(item->parentItem() == 0){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse() || item->isVisible()) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
traverseObject(application, qApp, command, false);
application.setEnv("qt");
//set these again cause properties overwrite them
application.setName(getApplicationName());
application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
application.addAttribute("applicationUid", QString::number(uid));
CWsScreenDevice* sws = new ( ELeave ) CWsScreenDevice( CEikonEnv::Static()->WsSession() );
CleanupStack::PushL( sws );
if( sws->Construct() == KErrNone)
{
TPixelsAndRotation sizeAndRotation;
sws->GetDefaultScreenSizeAndRotation( sizeAndRotation );
qApp->setProperty(APP_ROTATION, QVariant(sizeAndRotation.iRotation));
application.addAttribute(APP_ROTATION, sizeAndRotation.iRotation);
}
CleanupStack::PopAndDestroy( sws );
#endif
application.addAttribute("arguments", qApp->arguments().join(" ").toLatin1().data());
application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
application.addAttribute("objectId", TasCoreUtils::objectId(qApp));
int mem = TasDeviceUtils::currentProcessHeapSize();
if(mem != -1){
application.addAttribute("memUsage", mem);
}
#if defined(TAS_MAEMO) && defined(HAVE_QAPP)
MApplication* app = MApplication::instance();
if (app){
MLocale defaultMLocale;
application.addAttribute("localeName", defaultMLocale.name());
application.addAttribute("localeCountry", defaultMLocale.country());
application.addAttribute("localeLanguage", defaultMLocale.language());
}
else{
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
}
#else
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
#endif
}
/*!
Prints all of the actions that a widget has under the widget.
Makes it possible to easily map the correct action to the
correct widget and also command the correct widget.
Returns true if an action was added.
*/
void TasUiTraverser::printActions(TasObject& objectInfo, QObject* object)
{
QWidget* widget = qobject_cast<QWidget*>(object);
if(widget){
addActions(objectInfo, widget->actions());
}
else{
QGraphicsWidget* gWidget = qobject_cast<QGraphicsWidget*>(object);
if(gWidget){
addActions(objectInfo, gWidget->actions());
}
}
}
void TasUiTraverser::addActions(TasObject& parentObject, QList<QAction*> actions)
{
if(actions.size() > 0){
for(int i = 0 ; i < actions.size(); i++){
QObject* action = actions.at(i);
traverseObject(parentObject.addObject(), action, 0);
}
}
}
<|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/test/test_navigation_observer.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
TestNavigationObserver::JsInjectionReadyObserver::JsInjectionReadyObserver() {
}
TestNavigationObserver::JsInjectionReadyObserver::~JsInjectionReadyObserver() {
}
TestNavigationObserver::TestNavigationObserver(
NavigationController* controller,
TestNavigationObserver::JsInjectionReadyObserver*
js_injection_ready_observer,
int number_of_navigations)
: navigation_started_(false),
navigation_entry_committed_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations),
js_injection_ready_observer_(js_injection_ready_observer),
done_(false),
running_(false) {
RegisterAsObserver(controller);
}
TestNavigationObserver::~TestNavigationObserver() {
}
void TestNavigationObserver::WaitForObservation() {
if (!done_) {
EXPECT_FALSE(running_);
running_ = true;
ui_test_utils::RunMessageLoop();
}
}
TestNavigationObserver::TestNavigationObserver(
TestNavigationObserver::JsInjectionReadyObserver*
js_injection_ready_observer,
int number_of_navigations)
: navigation_started_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations),
js_injection_ready_observer_(js_injection_ready_observer),
done_(false),
running_(false) {
}
void TestNavigationObserver::RegisterAsObserver(
NavigationController* controller) {
registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
Source<NavigationController>(controller));
registrar_.Add(this, content::NOTIFICATION_LOAD_START,
Source<NavigationController>(controller));
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
Source<NavigationController>(controller));
}
void TestNavigationObserver::Observe(
int type, const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_NAV_ENTRY_COMMITTED:
if (!navigation_entry_committed_ && js_injection_ready_observer_)
js_injection_ready_observer_->OnJsInjectionReady();
navigation_started_ = true;
navigation_entry_committed_ = true;
break;
case content::NOTIFICATION_LOAD_START:
navigation_started_ = true;
break;
case content::NOTIFICATION_LOAD_STOP:
if (navigation_started_ &&
++navigations_completed_ == number_of_navigations_) {
navigation_started_ = false;
done_ = true;
if (running_)
MessageLoopForUI::current()->Quit();
}
break;
default:
assert(false);
}
}
<commit_msg>Use FAIL() rather than assert().<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/test/test_navigation_observer.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
TestNavigationObserver::JsInjectionReadyObserver::JsInjectionReadyObserver() {
}
TestNavigationObserver::JsInjectionReadyObserver::~JsInjectionReadyObserver() {
}
TestNavigationObserver::TestNavigationObserver(
NavigationController* controller,
TestNavigationObserver::JsInjectionReadyObserver*
js_injection_ready_observer,
int number_of_navigations)
: navigation_started_(false),
navigation_entry_committed_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations),
js_injection_ready_observer_(js_injection_ready_observer),
done_(false),
running_(false) {
RegisterAsObserver(controller);
}
TestNavigationObserver::~TestNavigationObserver() {
}
void TestNavigationObserver::WaitForObservation() {
if (!done_) {
EXPECT_FALSE(running_);
running_ = true;
ui_test_utils::RunMessageLoop();
}
}
TestNavigationObserver::TestNavigationObserver(
TestNavigationObserver::JsInjectionReadyObserver*
js_injection_ready_observer,
int number_of_navigations)
: navigation_started_(false),
navigations_completed_(0),
number_of_navigations_(number_of_navigations),
js_injection_ready_observer_(js_injection_ready_observer),
done_(false),
running_(false) {
}
void TestNavigationObserver::RegisterAsObserver(
NavigationController* controller) {
registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED,
Source<NavigationController>(controller));
registrar_.Add(this, content::NOTIFICATION_LOAD_START,
Source<NavigationController>(controller));
registrar_.Add(this, content::NOTIFICATION_LOAD_STOP,
Source<NavigationController>(controller));
}
void TestNavigationObserver::Observe(
int type, const NotificationSource& source,
const NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_NAV_ENTRY_COMMITTED:
if (!navigation_entry_committed_ && js_injection_ready_observer_)
js_injection_ready_observer_->OnJsInjectionReady();
navigation_started_ = true;
navigation_entry_committed_ = true;
break;
case content::NOTIFICATION_LOAD_START:
navigation_started_ = true;
break;
case content::NOTIFICATION_LOAD_STOP:
if (navigation_started_ &&
++navigations_completed_ == number_of_navigations_) {
navigation_started_ = false;
done_ = true;
if (running_)
MessageLoopForUI::current()->Quit();
}
break;
default:
NOTREACHED();
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "EnhancedCustomShapeToken.hxx"
#include <osl/mutex.hxx>
#include <boost/unordered_map.hpp>
#include <string.h>
namespace xmloff { namespace EnhancedCustomShapeToken {
struct TCheck
{
bool operator()( const char* s1, const char* s2 ) const
{
return strcmp( s1, s2 ) == 0;
}
};
typedef boost::unordered_map< const char*, EnhancedCustomShapeTokenEnum, boost::hash<const char*>, TCheck> TypeNameHashMap;
static TypeNameHashMap* pHashMap = NULL;
static ::osl::Mutex& getHashMapMutex()
{
static osl::Mutex s_aHashMapProtection;
return s_aHashMapProtection;
}
struct TokenTable
{
const char* pS;
EnhancedCustomShapeTokenEnum pE;
};
static const TokenTable pTokenTableArray[] =
{
{ "type", EAS_type },
{ "name", EAS_name },
{ "mirror-horizontal", EAS_mirror_horizontal },
{ "mirror-vertical", EAS_mirror_vertical },
{ "viewBox", EAS_viewBox },
{ "text-rotate-angle", EAS_text_rotate_angle },
{ "extrusion-allowed", EAS_extrusion_allowed },
{ "extrusion-text-path-allowed", EAS_text_path_allowed },
{ "extrusion-concentric-gradient-fill", EAS_concentric_gradient_fill_allowed },
{ "extrusion", EAS_extrusion },
{ "extrusion-brightness", EAS_extrusion_brightness },
{ "extrusion-depth", EAS_extrusion_depth },
{ "extrusion-diffusion", EAS_extrusion_diffusion },
{ "extrusion-number-of-line-segments", EAS_extrusion_number_of_line_segments },
{ "extrusion-light-face", EAS_extrusion_light_face },
{ "extrusion-first-light-harsh", EAS_extrusion_first_light_harsh },
{ "extrusion-second-light-harsh", EAS_extrusion_second_light_harsh },
{ "extrusion-first-light-livel", EAS_extrusion_first_light_level },
{ "extrusion-second-light-level", EAS_extrusion_second_light_level },
{ "extrusion-first-light-direction", EAS_extrusion_first_light_direction },
{ "extrusion-second-light-direction", EAS_extrusion_second_light_direction },
{ "extrusion-metal", EAS_extrusion_metal },
{ "shade-mode", EAS_shade_mode },
{ "extrusion-rotation-angle", EAS_extrusion_rotation_angle },
{ "extrusion-rotation-center", EAS_extrusion_rotation_center },
{ "extrusion-shininess", EAS_extrusion_shininess },
{ "extrusion-skew", EAS_extrusion_skew },
{ "extrusion-specularity", EAS_extrusion_specularity },
{ "projection", EAS_projection },
{ "extrusion-viewpoint", EAS_extrusion_viewpoint },
{ "extrusion-origin", EAS_extrusion_origin },
{ "extrusion-color", EAS_extrusion_color },
{ "enhanced-path", EAS_enhanced_path },
{ "path-stretchpoint-x", EAS_path_stretchpoint_x },
{ "path-stretchpoint-y", EAS_path_stretchpoint_y },
{ "text-areas", EAS_text_areas },
{ "glue-points", EAS_glue_points },
{ "glue-point-type", EAS_glue_point_type },
{ "glue-point-leaving-directions", EAS_glue_point_leaving_directions },
{ "text-path", EAS_text_path },
{ "text-path-mode", EAS_text_path_mode },
{ "text-path-scale", EAS_text_path_scale },
{ "text-path-same-letter-heights", EAS_text_path_same_letter_heights },
{ "modifiers", EAS_modifiers },
{ "equation", EAS_equation },
{ "formula", EAS_formula },
{ "handle", EAS_handle },
{ "handle-mirror-horizontal", EAS_handle_mirror_horizontal },
{ "handle-mirror-vertical", EAS_handle_mirror_vertical },
{ "handle-switched", EAS_handle_switched },
{ "handle-position", EAS_handle_position },
{ "handle-range-x-minimum", EAS_handle_range_x_minimum },
{ "handle-range-x-maximum", EAS_handle_range_x_maximum },
{ "handle-range-y-minimum", EAS_handle_range_y_minimum },
{ "handle-range-y-maximum", EAS_handle_range_y_maximum },
{ "handle-polar", EAS_handle_polar },
{ "handle-radius-range-minimum", EAS_handle_radius_range_minimum },
{ "handle-radius-range-maximum", EAS_handle_radius_range_maximum },
{ "CustomShapeEngine", EAS_CustomShapeEngine },
{ "CustomShapeData", EAS_CustomShapeData },
{ "Type", EAS_Type },
{ "MirroredX", EAS_MirroredX },
{ "MirroredY", EAS_MirroredY },
{ "ViewBox", EAS_ViewBox },
{ "TextRotateAngle", EAS_TextRotateAngle },
{ "ExtrusionAllowed", EAS_ExtrusionAllowed },
{ "TextPathAllowed", EAS_TextPathAllowed },
{ "ConcentricGradientFillAllowed", EAS_ConcentricGradientFillAllowed },
{ "Extrusion", EAS_Extrusion },
{ "Equations", EAS_Equations },
{ "Equation", EAS_Equation },
{ "Path", EAS_Path },
{ "TextPath", EAS_TextPath },
{ "Handles", EAS_Handles },
{ "Handle", EAS_Handle },
{ "Brightness", EAS_Brightness },
{ "Depth", EAS_Depth },
{ "Diffusion", EAS_Diffusion },
{ "NumberOfLineSegments", EAS_NumberOfLineSegments },
{ "LightFace", EAS_LightFace },
{ "FirstLightHarsh", EAS_FirstLightHarsh },
{ "SecondLightHarsh", EAS_SecondLightHarsh },
{ "FirstLightLevel", EAS_FirstLightLevel },
{ "SecondLightLevel", EAS_SecondLightLevel },
{ "FirstLightDirection", EAS_FirstLightDirection },
{ "SecondLightDirection", EAS_SecondLightDirection },
{ "Metal", EAS_Metal },
{ "ShadeMode", EAS_ShadeMode },
{ "RotateAngle", EAS_RotateAngle },
{ "RotationCenter", EAS_RotationCenter },
{ "Shininess", EAS_Shininess },
{ "Skew", EAS_Skew },
{ "Specularity", EAS_Specularity },
{ "ProjectionMode", EAS_ProjectionMode },
{ "ViewPoint", EAS_ViewPoint },
{ "Origin", EAS_Origin },
{ "Color", EAS_Color },
{ "Switched", EAS_Switched },
{ "Polar", EAS_Polar },
{ "RangeXMinimum", EAS_RangeXMinimum },
{ "RangeXMaximum", EAS_RangeXMaximum },
{ "RangeYMinimum", EAS_RangeYMinimum },
{ "RangeYMaximum", EAS_RangeYMaximum },
{ "RadiusRangeMinimum", EAS_RadiusRangeMinimum },
{ "RadiusRangeMaximum", EAS_RadiusRangeMaximum },
{ "Coordinates", EAS_Coordinates },
{ "Segments", EAS_Segments },
{ "StretchX", EAS_StretchX },
{ "StretchY", EAS_StretchY },
{ "TextFrames", EAS_TextFrames },
{ "GluePoints", EAS_GluePoints },
{ "GluePointLeavingDirections", EAS_GluePointLeavingDirections },
{ "GluePointType", EAS_GluePointType },
{ "TextPathMode", EAS_TextPathMode },
{ "ScaleX", EAS_ScaleX },
{ "SameLetterHeights", EAS_SameLetterHeights },
{ "Position", EAS_Position },
{ "AdjustmentValues", EAS_AdjustmentValues },
{ "Last", EAS_Last },
{ "NotFound", EAS_NotFound }
};
EnhancedCustomShapeTokenEnum EASGet( const rtl::OUString& rShapeType )
{
if ( !pHashMap )
{ // init hash map
::osl::MutexGuard aGuard( getHashMapMutex() );
if ( !pHashMap )
{
TypeNameHashMap* pH = new TypeNameHashMap;
const TokenTable* pPtr = pTokenTableArray;
const TokenTable* pEnd = pPtr + ( sizeof( pTokenTableArray ) / sizeof( TokenTable ) );
for ( ; pPtr < pEnd; pPtr++ )
(*pH)[ pPtr->pS ] = pPtr->pE;
pHashMap = pH;
}
}
EnhancedCustomShapeTokenEnum eRetValue = EAS_NotFound;
int i, nLen = rShapeType.getLength();
char* pBuf = new char[ nLen + 1 ];
for ( i = 0; i < nLen; i++ )
pBuf[ i ] = (char)rShapeType[ i ];
pBuf[ i ] = 0;
TypeNameHashMap::iterator aHashIter( pHashMap->find( pBuf ) );
delete[] pBuf;
if ( aHashIter != pHashMap->end() )
eRetValue = (*aHashIter).second;
return eRetValue;
}
rtl::OUString EASGet( const EnhancedCustomShapeTokenEnum eToken )
{
sal_uInt32 i = eToken >= EAS_Last
? (sal_uInt32)EAS_NotFound
: (sal_uInt32)eToken;
return rtl::OUString::createFromAscii( pTokenTableArray[ i ].pS );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>(std|boost)::hash on a const char* hashes the pointer not the contents<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "EnhancedCustomShapeToken.hxx"
#include <osl/mutex.hxx>
#include <boost/unordered_map.hpp>
#include <string.h>
namespace xmloff { namespace EnhancedCustomShapeToken {
struct THash
{
size_t operator()( const char* s ) const
{
return rtl_str_hashCode(s);
}
};
struct TCheck
{
bool operator()( const char* s1, const char* s2 ) const
{
return strcmp( s1, s2 ) == 0;
}
};
typedef boost::unordered_map< const char*, EnhancedCustomShapeTokenEnum, THash, TCheck> TypeNameHashMap;
static TypeNameHashMap* pHashMap = NULL;
static ::osl::Mutex& getHashMapMutex()
{
static osl::Mutex s_aHashMapProtection;
return s_aHashMapProtection;
}
struct TokenTable
{
const char* pS;
EnhancedCustomShapeTokenEnum pE;
};
static const TokenTable pTokenTableArray[] =
{
{ "type", EAS_type },
{ "name", EAS_name },
{ "mirror-horizontal", EAS_mirror_horizontal },
{ "mirror-vertical", EAS_mirror_vertical },
{ "viewBox", EAS_viewBox },
{ "text-rotate-angle", EAS_text_rotate_angle },
{ "extrusion-allowed", EAS_extrusion_allowed },
{ "extrusion-text-path-allowed", EAS_text_path_allowed },
{ "extrusion-concentric-gradient-fill", EAS_concentric_gradient_fill_allowed },
{ "extrusion", EAS_extrusion },
{ "extrusion-brightness", EAS_extrusion_brightness },
{ "extrusion-depth", EAS_extrusion_depth },
{ "extrusion-diffusion", EAS_extrusion_diffusion },
{ "extrusion-number-of-line-segments", EAS_extrusion_number_of_line_segments },
{ "extrusion-light-face", EAS_extrusion_light_face },
{ "extrusion-first-light-harsh", EAS_extrusion_first_light_harsh },
{ "extrusion-second-light-harsh", EAS_extrusion_second_light_harsh },
{ "extrusion-first-light-livel", EAS_extrusion_first_light_level },
{ "extrusion-second-light-level", EAS_extrusion_second_light_level },
{ "extrusion-first-light-direction", EAS_extrusion_first_light_direction },
{ "extrusion-second-light-direction", EAS_extrusion_second_light_direction },
{ "extrusion-metal", EAS_extrusion_metal },
{ "shade-mode", EAS_shade_mode },
{ "extrusion-rotation-angle", EAS_extrusion_rotation_angle },
{ "extrusion-rotation-center", EAS_extrusion_rotation_center },
{ "extrusion-shininess", EAS_extrusion_shininess },
{ "extrusion-skew", EAS_extrusion_skew },
{ "extrusion-specularity", EAS_extrusion_specularity },
{ "projection", EAS_projection },
{ "extrusion-viewpoint", EAS_extrusion_viewpoint },
{ "extrusion-origin", EAS_extrusion_origin },
{ "extrusion-color", EAS_extrusion_color },
{ "enhanced-path", EAS_enhanced_path },
{ "path-stretchpoint-x", EAS_path_stretchpoint_x },
{ "path-stretchpoint-y", EAS_path_stretchpoint_y },
{ "text-areas", EAS_text_areas },
{ "glue-points", EAS_glue_points },
{ "glue-point-type", EAS_glue_point_type },
{ "glue-point-leaving-directions", EAS_glue_point_leaving_directions },
{ "text-path", EAS_text_path },
{ "text-path-mode", EAS_text_path_mode },
{ "text-path-scale", EAS_text_path_scale },
{ "text-path-same-letter-heights", EAS_text_path_same_letter_heights },
{ "modifiers", EAS_modifiers },
{ "equation", EAS_equation },
{ "formula", EAS_formula },
{ "handle", EAS_handle },
{ "handle-mirror-horizontal", EAS_handle_mirror_horizontal },
{ "handle-mirror-vertical", EAS_handle_mirror_vertical },
{ "handle-switched", EAS_handle_switched },
{ "handle-position", EAS_handle_position },
{ "handle-range-x-minimum", EAS_handle_range_x_minimum },
{ "handle-range-x-maximum", EAS_handle_range_x_maximum },
{ "handle-range-y-minimum", EAS_handle_range_y_minimum },
{ "handle-range-y-maximum", EAS_handle_range_y_maximum },
{ "handle-polar", EAS_handle_polar },
{ "handle-radius-range-minimum", EAS_handle_radius_range_minimum },
{ "handle-radius-range-maximum", EAS_handle_radius_range_maximum },
{ "CustomShapeEngine", EAS_CustomShapeEngine },
{ "CustomShapeData", EAS_CustomShapeData },
{ "Type", EAS_Type },
{ "MirroredX", EAS_MirroredX },
{ "MirroredY", EAS_MirroredY },
{ "ViewBox", EAS_ViewBox },
{ "TextRotateAngle", EAS_TextRotateAngle },
{ "ExtrusionAllowed", EAS_ExtrusionAllowed },
{ "TextPathAllowed", EAS_TextPathAllowed },
{ "ConcentricGradientFillAllowed", EAS_ConcentricGradientFillAllowed },
{ "Extrusion", EAS_Extrusion },
{ "Equations", EAS_Equations },
{ "Equation", EAS_Equation },
{ "Path", EAS_Path },
{ "TextPath", EAS_TextPath },
{ "Handles", EAS_Handles },
{ "Handle", EAS_Handle },
{ "Brightness", EAS_Brightness },
{ "Depth", EAS_Depth },
{ "Diffusion", EAS_Diffusion },
{ "NumberOfLineSegments", EAS_NumberOfLineSegments },
{ "LightFace", EAS_LightFace },
{ "FirstLightHarsh", EAS_FirstLightHarsh },
{ "SecondLightHarsh", EAS_SecondLightHarsh },
{ "FirstLightLevel", EAS_FirstLightLevel },
{ "SecondLightLevel", EAS_SecondLightLevel },
{ "FirstLightDirection", EAS_FirstLightDirection },
{ "SecondLightDirection", EAS_SecondLightDirection },
{ "Metal", EAS_Metal },
{ "ShadeMode", EAS_ShadeMode },
{ "RotateAngle", EAS_RotateAngle },
{ "RotationCenter", EAS_RotationCenter },
{ "Shininess", EAS_Shininess },
{ "Skew", EAS_Skew },
{ "Specularity", EAS_Specularity },
{ "ProjectionMode", EAS_ProjectionMode },
{ "ViewPoint", EAS_ViewPoint },
{ "Origin", EAS_Origin },
{ "Color", EAS_Color },
{ "Switched", EAS_Switched },
{ "Polar", EAS_Polar },
{ "RangeXMinimum", EAS_RangeXMinimum },
{ "RangeXMaximum", EAS_RangeXMaximum },
{ "RangeYMinimum", EAS_RangeYMinimum },
{ "RangeYMaximum", EAS_RangeYMaximum },
{ "RadiusRangeMinimum", EAS_RadiusRangeMinimum },
{ "RadiusRangeMaximum", EAS_RadiusRangeMaximum },
{ "Coordinates", EAS_Coordinates },
{ "Segments", EAS_Segments },
{ "StretchX", EAS_StretchX },
{ "StretchY", EAS_StretchY },
{ "TextFrames", EAS_TextFrames },
{ "GluePoints", EAS_GluePoints },
{ "GluePointLeavingDirections", EAS_GluePointLeavingDirections },
{ "GluePointType", EAS_GluePointType },
{ "TextPathMode", EAS_TextPathMode },
{ "ScaleX", EAS_ScaleX },
{ "SameLetterHeights", EAS_SameLetterHeights },
{ "Position", EAS_Position },
{ "AdjustmentValues", EAS_AdjustmentValues },
{ "Last", EAS_Last },
{ "NotFound", EAS_NotFound }
};
EnhancedCustomShapeTokenEnum EASGet( const rtl::OUString& rShapeType )
{
if ( !pHashMap )
{ // init hash map
::osl::MutexGuard aGuard( getHashMapMutex() );
if ( !pHashMap )
{
TypeNameHashMap* pH = new TypeNameHashMap;
const TokenTable* pPtr = pTokenTableArray;
const TokenTable* pEnd = pPtr + ( sizeof( pTokenTableArray ) / sizeof( TokenTable ) );
for ( ; pPtr < pEnd; pPtr++ )
(*pH)[ pPtr->pS ] = pPtr->pE;
pHashMap = pH;
}
}
EnhancedCustomShapeTokenEnum eRetValue = EAS_NotFound;
int i, nLen = rShapeType.getLength();
char* pBuf = new char[ nLen + 1 ];
for ( i = 0; i < nLen; i++ )
pBuf[ i ] = (char)rShapeType[ i ];
pBuf[ i ] = 0;
TypeNameHashMap::iterator aHashIter( pHashMap->find( pBuf ) );
delete[] pBuf;
if ( aHashIter != pHashMap->end() )
eRetValue = (*aHashIter).second;
return eRetValue;
}
rtl::OUString EASGet( const EnhancedCustomShapeTokenEnum eToken )
{
sal_uInt32 i = eToken >= EAS_Last
? (sal_uInt32)EAS_NotFound
: (sal_uInt32)eToken;
return rtl::OUString::createFromAscii( pTokenTableArray[ i ].pS );
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMaximumProjectionImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkMaximumProjectionImageFilter.h"
#include "itkExtractImageFilter.h"
int itkMaximumProjectionImageFilterTest2(int argc, char * argv[])
{
if( argc < 4 )
{
std::cerr << "Missing parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << "Dimension Inputimage Outputimage " << std::endl;
return EXIT_FAILURE;
}
int dim = atoi(argv[1]);
typedef unsigned char PixelType;
typedef itk::Image< PixelType, 3 > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
typedef itk::MaximumProjectionImageFilter< ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetProjectionDimension( dim );
// to be sure that the result is ok with several threads, even on a single
// proc computer
filter->SetNumberOfThreads( 2 );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[3] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>STYLE: Fixing indentation problems and alignment of typedefs.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMaximumProjectionImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkMaximumProjectionImageFilter.h"
#include "itkExtractImageFilter.h"
int itkMaximumProjectionImageFilterTest2(int argc, char * argv[])
{
if( argc < 4 )
{
std::cerr << "Missing parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << "Dimension Inputimage Outputimage " << std::endl;
return EXIT_FAILURE;
}
int dim = atoi(argv[1]);
typedef unsigned char PixelType;
typedef itk::Image< PixelType, 3 > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
typedef itk::MaximumProjectionImageFilter< ImageType, ImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetProjectionDimension( dim );
// to be sure that the result is ok with several threads, even on a single
// proc computer
filter->SetNumberOfThreads( 2 );
itk::SimpleFilterWatcher watcher(filter, "filter");
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[3] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "uvc_interface_v4l.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <dirent.h>
UvcInterfaceV4L::UvcInterfaceV4L()
{
mFd = -1;
mReadFrameThread = NULL;
mReadFrameThreadExitFlag = true;
}
UvcInterfaceV4L::~UvcInterfaceV4L()
{
Close();
}
bool UvcInterfaceV4L::GetCameraList(std::vector<std::string>& camera_list, const char * filter)
{
DIR *dir;
struct dirent *ptr;
if ((dir=opendir("/dev/")) == NULL)
return false;
while ((ptr=readdir(dir)) != NULL){
if(ptr->d_type == 2){ // file
if(strstr(ptr->d_name, "video")){
std::string full_path = std::string("/dev/") + ptr->d_name;
struct v4l2_capability cap;
int ffd;
if ((ffd = open(full_path.c_str(), O_RDWR)) != -1) {
int rt = ioctl(ffd, VIDIOC_QUERYCAP, &cap);
if(rt == 0 && strstr((const char *)cap.card, filter)){
full_path += "__" + std::string((const char *)cap.bus_info) +
"__" + std::string((const char *)cap.card);
camera_list.push_back(full_path);
}
close(ffd);
}
}
}
}
closedir(dir);
return true;
}
bool UvcInterfaceV4L::Open(std::string & camera_name)
{
std::size_t pos = camera_name.find("__");
mDeviceName = camera_name.substr(0, pos);
if (InitV4L() == false) {
fprintf(stderr, " Init v4L2 failed !! exit fatal \n");
goto error;
}
if(StartStream() < 0){
fprintf(stderr, " Start Stream failed \n");
goto error;
}
mReadFrameThreadExitFlag = false;
mReadFrameThread = new std::thread(ReadFrameThreadProc, this);
return true;
error:
close(mFd);
mFd = -1;
return false;
}
bool UvcInterfaceV4L::Close()
{
if(mIsVideoOpened == false)
return true;
mReadFrameThreadExitFlag = true;
if(mReadFrameThread){
if(mReadFrameThread->joinable())
mReadFrameThread->join();
delete mReadFrameThread;
mReadFrameThread = NULL;
}
if (mIsVideoOpened)
StopStream();
for (int i = 0; i < NB_BUFFER; i++){
if(mMemBuffers[i])
munmap(mMemBuffers[i], mVideoWidth * mVideoHeight * 2);
}
if(mFd != -1){
close(mFd);
mFd = -1;
}
return true;
}
bool UvcInterfaceV4L::InitV4L()
{
int i;
int ret = 0;
struct v4l2_capability cap;
struct v4l2_format fmt;
struct v4l2_requestbuffers rb;
struct v4l2_buffer buf;
if ((mFd = open(mDeviceName.c_str(), O_RDWR)) == -1) {
perror("ERROR opening V4L interface \n");
exit(1);
}
memset(&cap, 0, sizeof (struct v4l2_capability));
ret = ioctl(mFd, VIDIOC_QUERYCAP, &cap);
if (ret < 0) {
fprintf(stderr, "Error opening device %s: unable to query device.\n",
mDeviceName.c_str());
return false;
}
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
fprintf(stderr,
"Error opening device %s: video capture not supported.\n",
mDeviceName.c_str());
return false;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
fprintf(stderr, "%s does not support streaming i/o\n",
mDeviceName.c_str());
return false;
}
/* set format in */
memset(&fmt, 0, sizeof (struct v4l2_format));
fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(mFd, VIDIOC_G_FMT, &fmt);
if (ret < 0) {
fprintf(stderr, "Unable to get format: %d.\n", errno);
return false;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_ANY;
mVideoWidth = fmt.fmt.pix.width;
mVideoHeight = fmt.fmt.pix.height;
ret = ioctl(mFd, VIDIOC_S_FMT, &fmt);
if (ret < 0) {
fprintf(stderr, "Unable to set format: %d.\n", errno);
return false;
}
/* request buffers */
memset(&rb, 0, sizeof (struct v4l2_requestbuffers));
rb.count = NB_BUFFER;
rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
rb.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_REQBUFS, &rb);
if (ret < 0) {
fprintf(stderr, "Unable to allocate buffers: %d.\n", errno);
return false;
}
/* map the buffers */
for (i = 0; i < NB_BUFFER; i++) {
memset(&buf, 0, sizeof (struct v4l2_buffer));
buf.index = i;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_QUERYBUF, &buf);
if (ret < 0) {
fprintf(stderr, "Unable to query buffer (%d).\n", errno);
return false;
}
mMemBuffers[i] = mmap(0,buf.length, PROT_READ, MAP_SHARED, mFd, buf.m.offset);
if (mMemBuffers[i] == MAP_FAILED) {
fprintf(stderr, "Unable to map buffer (%d)\n", errno);
return false;
}
}
/* Queue the buffers. */
for (i = 0; i < NB_BUFFER; ++i) {
memset(&buf, 0, sizeof (struct v4l2_buffer));
buf.index = i;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_QBUF, &buf);
if (ret < 0) {
fprintf(stderr, "Unable to queue buffer (%d).\n", errno);
return false;
}
}
return true;
}
int32_t UvcInterfaceV4L::StartStream()
{
int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret;
ret = ioctl(mFd, VIDIOC_STREAMON, &type);
if (ret < 0) {
fprintf(stderr, "Unable to %s capture: %d.\n", "start", errno);
return ret;
}
mIsVideoOpened = 1;
return 0;
}
int32_t UvcInterfaceV4L::StopStream()
{
int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret;
ret = ioctl(mFd, VIDIOC_STREAMOFF, &type);
if (ret < 0) {
fprintf(stderr, "Unable to %s capture: %d.\n", "stop", errno);
return ret;
}
mIsVideoOpened = false;
return 0;
}
void UvcInterfaceV4L::ReadFrameThreadProc(UvcInterfaceV4L *v4l_if)
{
uint32_t frame_size = v4l_if->mVideoHeight * v4l_if->mVideoWidth * 2;
struct v4l2_buffer v4l_buf;
while(v4l_if->mReadFrameThreadExitFlag == false){
memset(&v4l_buf, 0, sizeof (struct v4l2_buffer));
v4l_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
v4l_buf.memory = V4L2_MEMORY_MMAP;
v4l_buf.length = frame_size;
int ret = ioctl(v4l_if->mFd, VIDIOC_DQBUF, &v4l_buf);
if (ret < 0) {
fprintf(stderr, "Unable to dequeue buffer (%d).\n", errno);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if(v4l_buf.bytesused == frame_size && v4l_if->mFrameCallBack){
v4l_if->mFrameCallBack(0, (uint8_t *)v4l_if->mMemBuffers[v4l_buf.index], frame_size, v4l_if->mFrameCallBackParam);
}
ret = ioctl(v4l_if->mFd, VIDIOC_QBUF, &v4l_buf);
if (ret < 0) {
fprintf(stderr, "Unable to requeue buffer (%d).\n", errno);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
bool UvcInterfaceV4L::GetDepthCameraList(std::vector <std::string> &camera_list) {
return GetCameraList(camera_list, "INMOTION");
}
<commit_msg>fix linux uvc_interface_v4l open issue<commit_after>#include "uvc_interface_v4l.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <dirent.h>
UvcInterfaceV4L::UvcInterfaceV4L()
{
mFd = -1;
mReadFrameThread = NULL;
mReadFrameThreadExitFlag = true;
}
UvcInterfaceV4L::~UvcInterfaceV4L()
{
Close();
}
bool UvcInterfaceV4L::GetCameraList(std::vector<std::string>& camera_list, const char * filter)
{
DIR *dir;
struct dirent *ptr;
if ((dir=opendir("/dev/")) == NULL)
return false;
while ((ptr=readdir(dir)) != NULL){
if(ptr->d_type == 2){ // file
if(strstr(ptr->d_name, "video")){
std::string full_path = std::string("/dev/") + ptr->d_name;
struct v4l2_capability cap;
int ffd;
if ((ffd = open(full_path.c_str(), O_RDWR)) != -1) {
int rt = ioctl(ffd, VIDIOC_QUERYCAP, &cap);
if(rt == 0 && strstr((const char *)cap.card, filter)){
full_path += "__" + std::string((const char *)cap.bus_info) +
"__" + std::string((const char *)cap.card);
camera_list.push_back(full_path);
}
close(ffd);
}
}
}
}
closedir(dir);
return true;
}
bool UvcInterfaceV4L::Open(std::string & camera_name)
{
std::size_t pos = camera_name.find("__");
mDeviceName = camera_name.substr(0, pos);
if (InitV4L() == false) {
fprintf(stderr, " Init v4L2 failed !! exit fatal \n");
goto error;
}
if(StartStream() < 0){
fprintf(stderr, " Start Stream failed \n");
goto error;
}
mReadFrameThreadExitFlag = false;
mReadFrameThread = new std::thread(ReadFrameThreadProc, this);
return DepthVideoInterface::Open(camera_name);
error:
close(mFd);
mFd = -1;
return false;
}
bool UvcInterfaceV4L::Close()
{
if(mIsVideoOpened == false)
return true;
mReadFrameThreadExitFlag = true;
if(mReadFrameThread){
if(mReadFrameThread->joinable())
mReadFrameThread->join();
delete mReadFrameThread;
mReadFrameThread = NULL;
}
if (mIsVideoOpened)
StopStream();
for (int i = 0; i < NB_BUFFER; i++){
if(mMemBuffers[i])
munmap(mMemBuffers[i], mVideoWidth * mVideoHeight * 2);
}
if(mFd != -1){
close(mFd);
mFd = -1;
}
return true;
}
bool UvcInterfaceV4L::InitV4L()
{
int i;
int ret = 0;
struct v4l2_capability cap;
struct v4l2_format fmt;
struct v4l2_requestbuffers rb;
struct v4l2_buffer buf;
if ((mFd = open(mDeviceName.c_str(), O_RDWR)) == -1) {
perror("ERROR opening V4L interface \n");
exit(1);
}
memset(&cap, 0, sizeof (struct v4l2_capability));
ret = ioctl(mFd, VIDIOC_QUERYCAP, &cap);
if (ret < 0) {
fprintf(stderr, "Error opening device %s: unable to query device.\n",
mDeviceName.c_str());
return false;
}
if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
fprintf(stderr,
"Error opening device %s: video capture not supported.\n",
mDeviceName.c_str());
return false;
}
if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
fprintf(stderr, "%s does not support streaming i/o\n",
mDeviceName.c_str());
return false;
}
/* set format in */
memset(&fmt, 0, sizeof (struct v4l2_format));
fmt.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(mFd, VIDIOC_G_FMT, &fmt);
if (ret < 0) {
fprintf(stderr, "Unable to get format: %d.\n", errno);
return false;
}
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_ANY;
mVideoWidth = fmt.fmt.pix.width;
mVideoHeight = fmt.fmt.pix.height;
ret = ioctl(mFd, VIDIOC_S_FMT, &fmt);
if (ret < 0) {
fprintf(stderr, "Unable to set format: %d.\n", errno);
return false;
}
/* request buffers */
memset(&rb, 0, sizeof (struct v4l2_requestbuffers));
rb.count = NB_BUFFER;
rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
rb.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_REQBUFS, &rb);
if (ret < 0) {
fprintf(stderr, "Unable to allocate buffers: %d.\n", errno);
return false;
}
/* map the buffers */
for (i = 0; i < NB_BUFFER; i++) {
memset(&buf, 0, sizeof (struct v4l2_buffer));
buf.index = i;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_QUERYBUF, &buf);
if (ret < 0) {
fprintf(stderr, "Unable to query buffer (%d).\n", errno);
return false;
}
mMemBuffers[i] = mmap(0,buf.length, PROT_READ, MAP_SHARED, mFd, buf.m.offset);
if (mMemBuffers[i] == MAP_FAILED) {
fprintf(stderr, "Unable to map buffer (%d)\n", errno);
return false;
}
}
/* Queue the buffers. */
for (i = 0; i < NB_BUFFER; ++i) {
memset(&buf, 0, sizeof (struct v4l2_buffer));
buf.index = i;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(mFd, VIDIOC_QBUF, &buf);
if (ret < 0) {
fprintf(stderr, "Unable to queue buffer (%d).\n", errno);
return false;
}
}
return true;
}
int32_t UvcInterfaceV4L::StartStream()
{
int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret;
ret = ioctl(mFd, VIDIOC_STREAMON, &type);
if (ret < 0) {
fprintf(stderr, "Unable to %s capture: %d.\n", "start", errno);
return ret;
}
mIsVideoOpened = 1;
return 0;
}
int32_t UvcInterfaceV4L::StopStream()
{
int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
int ret;
ret = ioctl(mFd, VIDIOC_STREAMOFF, &type);
if (ret < 0) {
fprintf(stderr, "Unable to %s capture: %d.\n", "stop", errno);
return ret;
}
mIsVideoOpened = false;
return 0;
}
void UvcInterfaceV4L::ReadFrameThreadProc(UvcInterfaceV4L *v4l_if)
{
uint32_t frame_size = v4l_if->mVideoHeight * v4l_if->mVideoWidth * 2;
struct v4l2_buffer v4l_buf;
while(v4l_if->mReadFrameThreadExitFlag == false){
memset(&v4l_buf, 0, sizeof (struct v4l2_buffer));
v4l_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
v4l_buf.memory = V4L2_MEMORY_MMAP;
v4l_buf.length = frame_size;
int ret = ioctl(v4l_if->mFd, VIDIOC_DQBUF, &v4l_buf);
if (ret < 0) {
fprintf(stderr, "Unable to dequeue buffer (%d).\n", errno);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if(v4l_buf.bytesused == frame_size && v4l_if->mFrameCallBack){
v4l_if->mFrameCallBack(0, (uint8_t *)v4l_if->mMemBuffers[v4l_buf.index], frame_size, v4l_if->mFrameCallBackParam);
}
ret = ioctl(v4l_if->mFd, VIDIOC_QBUF, &v4l_buf);
if (ret < 0) {
fprintf(stderr, "Unable to requeue buffer (%d).\n", errno);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
bool UvcInterfaceV4L::GetDepthCameraList(std::vector <std::string> &camera_list) {
return GetCameraList(camera_list, "INMOTION");
}
<|endoftext|>
|
<commit_before>//
// Thread.hpp
// Emojicode
//
// Created by Theo Weidmann on 04/01/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#ifndef Thread_hpp
#define Thread_hpp
#include "Engine.hpp"
#include "RetainedObjectPointer.hpp"
#include "ThreadsManager.hpp"
#include <mutex>
namespace Emojicode {
struct StackFrame {
StackFrame *returnPointer;
StackFrame *returnFutureStack;
Value *destination;
EmojicodeInstruction *executionPointer;
Function *function;
unsigned int argPushIndex;
Value thisContext; // This must always be the very last field!
Value* variableDestination(int index) { return &thisContext + index + 1; }
};
class Thread {
public:
friend void gc(std::unique_lock<std::mutex> &, size_t);
friend Thread* ThreadsManager::allocateThread();
friend void ThreadsManager::deallocateThread(Thread *thread);
friend Thread* ThreadsManager::nextThread(Thread *thread);
/// Pops the stack associated with this thread
void popStack();
/// Pushes a new stack frame
void pushStack(Value self, int frameSize, int argCount, Function *function, Value *destination,
EmojicodeInstruction *executionPointer);
/// Pushes the reserved stack frame onto the stack
void pushReservedFrame();
/// Reserves a new stack frame which can later be pushed with @c stackPushReservedFrame
/// @returns A pointer to the memory reserved for the variables.
StackFrame* reserveFrame(Value self, int size, Function *function, Value *destination,
EmojicodeInstruction *executionPointer);
StackFrame* currentStackFrame() const { return stack_; }
/// Returns the content of the variable slot at the specific index from the stack associated with this thread
Value variable(int index) const { return *variableDestination(index); }
/// Returns a pointer to the variable slot at the specific index from the stack associated with this thread
Value* variableDestination(int index) const { return stack_->variableDestination(index); }
/// Returns the value on which the method was called.
Value thisContext() const { return stack_->thisContext; }
/** Returns the object on which the method was called. */
Object* thisObject() const { return stack_->thisContext.object; }
/// Consumes the next instruction from the current stack frame’s execution pointer, i.e. returns the value to which
/// the pointer currently points and increments the pointer.
EmojicodeInstruction consumeInstruction() { return *(stack_->executionPointer++); }
/// Leaves the function currently executed. Effectively sets the execution pointer of
/// the current stack frame to the null pointer.
void returnFromFunction() { stack_->executionPointer = nullptr; }
/// Leaves the function and sets the value of the return destination to the given value.
void returnFromFunction(Value value) {
*stack_->destination = value;
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to Nothingness. (See @c makeNothingness())
void returnNothingnessFromFunction() {
stack_->destination->makeNothingness();
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to the given value. The destination is treated
/// as optional. (See @c optionalSet())
void returnOEValueFromFunction(Value value) {
stack_->destination->optionalSet(value);
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to an error with the given value.
void returnErrorFromFunction(EmojicodeInteger error) {
stack_->destination->storeError(error);
returnFromFunction();
}
/// Retains the given object.
/// This method is used in native function code to "retain" an object, i.e. to prevent the object from being
/// deallocated by the garbage collector and to keep a pointer to it.
/// @warning You must retain all objects which you wish to keep, before you perform a potentially garbage-collector
/// invoking operation. As well, you must "release" the object before your function returns by calling @c release().
/// @returns A @c RetainedObjectPointer pointing to the retained object.
RetainedObjectPointer retain(Object *object) {
*retainPointer = object;
return RetainedObjectPointer(retainPointer++);
}
/// Release @c n objects previously retained by @c retain().
/// @warning Releasing more objects than you retained leads to undefined behavior.
void release(int n) { retainPointer -= n; }
/// Returns the this object as a retained object pointer. This method is only provided to allow convenient passing
/// of the this object as retained object pointer. The this object itself is, of course, retained already in the
/// stack frame and calls to @c thisObject() will always return a valid object pointer.
/// @attention Unlike after a call to @c retain() you must not call @c release() for a call to this method.
RetainedObjectPointer thisObjectAsRetained() const {
return RetainedObjectPointer(&stack_->thisContext.object);
}
/// Returns the object pointer in the given variable slot as retained object pointer. This method is only provided
/// to allow convenient passing of the object pointer as retained object pointer as variables are naturally always
/// retained.
/// @attention Unlike after a call to @c retain() you must not call @c release() for a call to this method.
RetainedObjectPointer variableObjectPointerAsRetained(int index) const {
return RetainedObjectPointer(&variableDestination(index)->object);
}
private:
Thread();
~Thread();
void markStack();
void markRetainList() const {
for (Object **pointer = retainPointer - 1; pointer >= retainList; pointer--) mark(pointer);
}
StackFrame *stackLimit_;
StackFrame *stackBottom_;
StackFrame *stack_;
StackFrame *futureStack_;
Thread *threadBefore_;
Thread *threadAfter_;
Object *retainList[100];
Object **retainPointer = retainList;
};
}
#endif /* Thread_hpp */
<commit_msg>🤠 Remove faulty const<commit_after>//
// Thread.hpp
// Emojicode
//
// Created by Theo Weidmann on 04/01/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#ifndef Thread_hpp
#define Thread_hpp
#include "Engine.hpp"
#include "RetainedObjectPointer.hpp"
#include "ThreadsManager.hpp"
#include <mutex>
namespace Emojicode {
struct StackFrame {
StackFrame *returnPointer;
StackFrame *returnFutureStack;
Value *destination;
EmojicodeInstruction *executionPointer;
Function *function;
unsigned int argPushIndex;
Value thisContext; // This must always be the very last field!
Value* variableDestination(int index) { return &thisContext + index + 1; }
};
class Thread {
public:
friend void gc(std::unique_lock<std::mutex> &, size_t);
friend Thread* ThreadsManager::allocateThread();
friend void ThreadsManager::deallocateThread(Thread *thread);
friend Thread* ThreadsManager::nextThread(Thread *thread);
/// Pops the stack associated with this thread
void popStack();
/// Pushes a new stack frame
void pushStack(Value self, int frameSize, int argCount, Function *function, Value *destination,
EmojicodeInstruction *executionPointer);
/// Pushes the reserved stack frame onto the stack
void pushReservedFrame();
/// Reserves a new stack frame which can later be pushed with @c stackPushReservedFrame
/// @returns A pointer to the memory reserved for the variables.
StackFrame* reserveFrame(Value self, int size, Function *function, Value *destination,
EmojicodeInstruction *executionPointer);
StackFrame* currentStackFrame() const { return stack_; }
/// Returns the content of the variable slot at the specific index from the stack associated with this thread
Value variable(int index) const { return *variableDestination(index); }
/// Returns a pointer to the variable slot at the specific index from the stack associated with this thread
Value* variableDestination(int index) const { return stack_->variableDestination(index); }
/// Returns the value on which the method was called.
Value thisContext() const { return stack_->thisContext; }
/** Returns the object on which the method was called. */
Object* thisObject() const { return stack_->thisContext.object; }
/// Consumes the next instruction from the current stack frame’s execution pointer, i.e. returns the value to which
/// the pointer currently points and increments the pointer.
EmojicodeInstruction consumeInstruction() { return *(stack_->executionPointer++); }
/// Leaves the function currently executed. Effectively sets the execution pointer of
/// the current stack frame to the null pointer.
void returnFromFunction() { stack_->executionPointer = nullptr; }
/// Leaves the function and sets the value of the return destination to the given value.
void returnFromFunction(Value value) {
*stack_->destination = value;
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to Nothingness. (See @c makeNothingness())
void returnNothingnessFromFunction() {
stack_->destination->makeNothingness();
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to the given value. The destination is treated
/// as optional. (See @c optionalSet())
void returnOEValueFromFunction(Value value) {
stack_->destination->optionalSet(value);
returnFromFunction();
}
/// Leaves the function and sets the value of the return destination to an error with the given value.
void returnErrorFromFunction(EmojicodeInteger error) {
stack_->destination->storeError(error);
returnFromFunction();
}
/// Retains the given object.
/// This method is used in native function code to "retain" an object, i.e. to prevent the object from being
/// deallocated by the garbage collector and to keep a pointer to it.
/// @warning You must retain all objects which you wish to keep, before you perform a potentially garbage-collector
/// invoking operation. As well, you must "release" the object before your function returns by calling @c release().
/// @returns A @c RetainedObjectPointer pointing to the retained object.
RetainedObjectPointer retain(Object *object) {
*retainPointer = object;
return RetainedObjectPointer(retainPointer++);
}
/// Release @c n objects previously retained by @c retain().
/// @warning Releasing more objects than you retained leads to undefined behavior.
void release(int n) { retainPointer -= n; }
/// Returns the this object as a retained object pointer. This method is only provided to allow convenient passing
/// of the this object as retained object pointer. The this object itself is, of course, retained already in the
/// stack frame and calls to @c thisObject() will always return a valid object pointer.
/// @attention Unlike after a call to @c retain() you must not call @c release() for a call to this method.
RetainedObjectPointer thisObjectAsRetained() const {
return RetainedObjectPointer(&stack_->thisContext.object);
}
/// Returns the object pointer in the given variable slot as retained object pointer. This method is only provided
/// to allow convenient passing of the object pointer as retained object pointer as variables are naturally always
/// retained.
/// @attention Unlike after a call to @c retain() you must not call @c release() for a call to this method.
RetainedObjectPointer variableObjectPointerAsRetained(int index) const {
return RetainedObjectPointer(&variableDestination(index)->object);
}
private:
Thread();
~Thread();
void markStack();
void markRetainList() {
for (Object **pointer = retainList; pointer < retainPointer; pointer++) mark(pointer);
}
StackFrame *stackLimit_;
StackFrame *stackBottom_;
StackFrame *stack_;
StackFrame *futureStack_;
Thread *threadBefore_;
Thread *threadAfter_;
Object *retainList[100];
Object **retainPointer = retainList;
};
}
#endif /* Thread_hpp */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtRichTextView.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkAlgorithm.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataObjectToTable.h"
#include "vtkDataRepresentation.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkQtRichTextView.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionSource.h"
#include "vtkSmartPointer.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include <ui_vtkQtRichTextView.h>
#include <QFrame>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QObject>
#include <QPointer>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWebFrame>
#include <QWebHistory>
#include <QWebView>
#include <QHttpHeader>
#include <QHttpRequestHeader>
vtkCxxRevisionMacro(vtkQtRichTextView, "1.16");
vtkStandardNewMacro(vtkQtRichTextView);
/////////////////////////////////////////////////////////////////////////////
// vtkQtRichTextView::Implementation
class vtkQtRichTextView::Implementation
{
public:
~Implementation()
{
delete this->Widget;
}
// Handles conversion of our input data to a table for display
vtkSmartPointer<vtkDataObjectToTable> DataObjectToTable;
// Caches displayed content so we can navigate backwards to it
vtkStdString Content;
QPointer<QWidget> Widget;
Ui::vtkQtRichTextView UI;
};
/////////////////////////////////////////////////////////////////////////////
// vtkQtRichTextView
vtkQtRichTextView::vtkQtRichTextView()
{
this->ContentColumnName=NULL;
this->ProxyPort = 0;
this->ProxyURL = NULL;
this->SetContentColumnName("html");
this->Internal = new Implementation();
this->Internal->DataObjectToTable = vtkSmartPointer<vtkDataObjectToTable>::New();
this->Internal->DataObjectToTable->SetFieldType(ROW_DATA);
this->Internal->Widget = new QWidget();
this->Internal->UI.setupUi(this->Internal->Widget);
this->Internal->UI.WebView->setHtml("");
//QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,"wwwproxy.sandia.gov",80);
//QNetworkProxy::setApplicationProxy(proxy);
QObject::connect(this->Internal->UI.BackButton, SIGNAL(clicked()), this, SLOT(onBack()));
QObject::connect(this->Internal->UI.WebView, SIGNAL(loadProgress(int)), this, SLOT(onLoadProgress(int)));
}
vtkQtRichTextView::~vtkQtRichTextView()
{
delete this->Internal;
}
void vtkQtRichTextView::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "ProxyURL : " << (this->ProxyURL ? this->ProxyURL : "(none)") << endl;
os << indent << "ProxyPort: " << this->ProxyPort << endl;
os << indent << "ContentColumnName: " << this->ContentColumnName << endl;
}
QWidget* vtkQtRichTextView::GetWidget()
{
return this->Internal->Widget;
}
void vtkQtRichTextView::SetFieldType(int type)
{
this->Internal->DataObjectToTable->SetFieldType(type);
this->Update();
}
int vtkQtRichTextView::GetFieldType()
{
return this->Internal->DataObjectToTable->GetFieldType();
}
void vtkQtRichTextView::Update()
{
// Set the proxy (if needed)
if(this->ProxyURL && this->ProxyPort >=0)
{
if(this->ProxyPort > 65535)
{
vtkWarningMacro(<<"Proxy port number, "<<this->ProxyPort<<", > 65535 (max for TCP/UDP)");
}
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy, ProxyURL, ProxyPort);
QNetworkProxy::setApplicationProxy(proxy);
}
else
{
QNetworkProxy proxy(QNetworkProxy::NoProxy);
QNetworkProxy::setApplicationProxy(proxy);
}
// Make sure the input connection is up to date ...
vtkDataRepresentation* const representation = this->GetRepresentation();
if(!representation)
{
this->Internal->UI.WebView->setHtml("");
return;
}
representation->Update();
if(this->Internal->DataObjectToTable->GetTotalNumberOfInputConnections() == 0
|| this->Internal->DataObjectToTable->GetInputConnection(0, 0) != representation->GetInternalOutputPort(0))
{
this->Internal->DataObjectToTable->SetInputConnection(0, representation->GetInternalOutputPort(0));
}
this->Internal->DataObjectToTable->Update();
// Get our input table ...
vtkTable* const table = this->Internal->DataObjectToTable->GetOutput();
if(!table)
{
this->Internal->UI.WebView->setHtml("");
return;
}
vtkIdType row = 0;
bool row_valid = false;
// Special-case: if the table is empty, we're done ...
if(0 == table->GetNumberOfRows())
{
this->Internal->UI.WebView->setHtml("");
return;
}
// Special-case #2: If the table has only one row just use it.
else if( 1 == table->GetNumberOfRows())
{
row = 0;
row_valid=true;
}
// For everything else, use the SelectionLink.
else
{
// Figure-out which row of the table we're going to display (if any) ...
row_valid = false;
if(vtkSelection* const selection = representation->GetAnnotationLink()->GetCurrentSelection())
{
if(vtkSelectionNode* const selection_node = selection->GetNumberOfNodes() ? selection->GetNode(0) : 0)
{
if(vtkIdTypeArray* const selection_array = vtkIdTypeArray::SafeDownCast(selection_node->GetSelectionList()))
{
if(selection_array->GetNumberOfTuples() && selection_array->GetValue(0) >= 0 && selection_array->GetValue(0) < table->GetNumberOfRows())
{
row = selection_array->GetValue(0);
row_valid = true;
}
}
}
}
}
this->Internal->UI.WebView->history()->clear(); // Workaround for a quirk in QWebHistory
if(row_valid)
{
this->Internal->Content = table->GetValueByName(row, this->ContentColumnName).ToString();
}
else
{
this->Internal->Content.clear();
}
#if 0
QHttpRequestHeader header( this->Internal->Content.c_str());
QString key("style");
QString css("body: { font-weight: bold; }");
header.addValue(key, css);
cout << header.toString().toStdString() << endl;
#endif
//cerr << this->Internal->Content << endl;
this->Internal->UI.WebView->setHtml(this->Internal->Content.c_str());
}
void vtkQtRichTextView::onBack()
{
// This logic is a workaround for a quirk in QWebHistory
if(this->Internal->UI.WebView->history()->currentItemIndex() <= 1)
{
this->Internal->UI.WebView->setHtml(this->Internal->Content.c_str());
this->Internal->UI.WebView->history()->clear();
}
else
{
this->Internal->UI.WebView->back();
}
}
void vtkQtRichTextView::onLoadProgress(int progress)
{
ViewProgressEventCallData callData("Web Page Loading", progress/100.0);
this->InvokeEvent(vtkCommand::ViewProgressEvent, &callData);
}
<commit_msg>BUG: Clean up rich text view. Convert selection to indices correctly.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtRichTextView.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkAlgorithm.h"
#include "vtkAlgorithmOutput.h"
#include "vtkAnnotationLink.h"
#include "vtkCommand.h"
#include "vtkConvertSelection.h"
#include "vtkDataObjectToTable.h"
#include "vtkDataRepresentation.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkObjectFactory.h"
#include "vtkQtRichTextView.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionSource.h"
#include "vtkSmartPointer.h"
#include "vtkTable.h"
#include "vtkVariantArray.h"
#include <ui_vtkQtRichTextView.h>
#include <QFrame>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QObject>
#include <QPointer>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWebFrame>
#include <QWebHistory>
#include <QWebView>
#include <QHttpHeader>
#include <QHttpRequestHeader>
vtkCxxRevisionMacro(vtkQtRichTextView, "1.17");
vtkStandardNewMacro(vtkQtRichTextView);
/////////////////////////////////////////////////////////////////////////////
// vtkQtRichTextView::Implementation
class vtkQtRichTextView::Implementation
{
public:
~Implementation()
{
delete this->Widget;
}
// Handles conversion of our input data to a table for display
vtkSmartPointer<vtkDataObjectToTable> DataObjectToTable;
// Caches displayed content so we can navigate backwards to it
vtkStdString Content;
QPointer<QWidget> Widget;
Ui::vtkQtRichTextView UI;
};
/////////////////////////////////////////////////////////////////////////////
// vtkQtRichTextView
vtkQtRichTextView::vtkQtRichTextView()
{
this->ContentColumnName=NULL;
this->ProxyPort = 0;
this->ProxyURL = NULL;
this->SetContentColumnName("html");
this->Internal = new Implementation();
this->Internal->DataObjectToTable = vtkSmartPointer<vtkDataObjectToTable>::New();
this->Internal->DataObjectToTable->SetFieldType(ROW_DATA);
this->Internal->Widget = new QWidget();
this->Internal->UI.setupUi(this->Internal->Widget);
this->Internal->UI.WebView->setHtml("");
//QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,"wwwproxy.sandia.gov",80);
//QNetworkProxy::setApplicationProxy(proxy);
QObject::connect(this->Internal->UI.BackButton, SIGNAL(clicked()), this, SLOT(onBack()));
QObject::connect(this->Internal->UI.WebView, SIGNAL(loadProgress(int)), this, SLOT(onLoadProgress(int)));
}
vtkQtRichTextView::~vtkQtRichTextView()
{
delete this->Internal;
}
void vtkQtRichTextView::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "ProxyURL : " << (this->ProxyURL ? this->ProxyURL : "(none)") << endl;
os << indent << "ProxyPort: " << this->ProxyPort << endl;
os << indent << "ContentColumnName: " << this->ContentColumnName << endl;
}
QWidget* vtkQtRichTextView::GetWidget()
{
return this->Internal->Widget;
}
void vtkQtRichTextView::SetFieldType(int type)
{
this->Internal->DataObjectToTable->SetFieldType(type);
this->Update();
}
int vtkQtRichTextView::GetFieldType()
{
return this->Internal->DataObjectToTable->GetFieldType();
}
void vtkQtRichTextView::Update()
{
// Set the proxy (if needed)
if(this->ProxyURL && this->ProxyPort >=0)
{
if(this->ProxyPort > 65535)
{
vtkWarningMacro(<<"Proxy port number, "<<this->ProxyPort<<", > 65535 (max for TCP/UDP)");
}
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy, ProxyURL, ProxyPort);
QNetworkProxy::setApplicationProxy(proxy);
}
else
{
QNetworkProxy proxy(QNetworkProxy::NoProxy);
QNetworkProxy::setApplicationProxy(proxy);
}
// Make sure the input connection is up to date ...
vtkDataRepresentation* const representation = this->GetRepresentation();
if(!representation)
{
this->Internal->UI.WebView->setHtml("");
return;
}
representation->Update();
if(this->Internal->DataObjectToTable->GetTotalNumberOfInputConnections() == 0
|| this->Internal->DataObjectToTable->GetInputConnection(0, 0) != representation->GetInternalOutputPort(0))
{
this->Internal->DataObjectToTable->SetInputConnection(0, representation->GetInternalOutputPort(0));
}
this->Internal->DataObjectToTable->Update();
// Get our input table ...
vtkTable* const table = this->Internal->DataObjectToTable->GetOutput();
if(!table)
{
this->Internal->UI.WebView->setHtml("");
return;
}
// Special-case: if the table is empty, we're done ...
if(table->GetNumberOfRows() == 0)
{
this->Internal->UI.WebView->setHtml("");
return;
}
vtkSelection* s = representation->GetAnnotationLink()->GetCurrentSelection();
vtkSmartPointer<vtkSelection> selection;
selection.TakeReference(vtkConvertSelection::ToSelectionType(
s, table, vtkSelectionNode::INDICES, 0, vtkSelectionNode::ROW));
if(!selection.GetPointer() || selection->GetNumberOfNodes() == 0)
{
this->Internal->UI.WebView->setHtml("");
return;
}
vtkIdTypeArray* selectedRows = vtkIdTypeArray::SafeDownCast(selection->GetNode(0)->GetSelectionList());
if(selectedRows->GetNumberOfTuples() == 0)
{
this->Internal->UI.WebView->setHtml("");
return;
}
vtkIdType row = selectedRows->GetValue(0);
this->Internal->UI.WebView->history()->clear(); // Workaround for a quirk in QWebHistory
this->Internal->Content = table->GetValueByName(row, this->ContentColumnName).ToString();
#if 0
QHttpRequestHeader header( this->Internal->Content.c_str());
QString key("style");
QString css("body: { font-weight: bold; }");
header.addValue(key, css);
cout << header.toString().toStdString() << endl;
#endif
//cerr << this->Internal->Content << endl;
this->Internal->UI.WebView->setHtml(this->Internal->Content.c_str());
}
void vtkQtRichTextView::onBack()
{
// This logic is a workaround for a quirk in QWebHistory
if(this->Internal->UI.WebView->history()->currentItemIndex() <= 1)
{
this->Internal->UI.WebView->setHtml(this->Internal->Content.c_str());
this->Internal->UI.WebView->history()->clear();
}
else
{
this->Internal->UI.WebView->back();
}
}
void vtkQtRichTextView::onLoadProgress(int progress)
{
ViewProgressEventCallData callData("Web Page Loading", progress/100.0);
this->InvokeEvent(vtkCommand::ViewProgressEvent, &callData);
}
<|endoftext|>
|
<commit_before>// @(#) $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
* for The ALICE HLT Project. *
* *
* 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. *
**************************************************************************/
/** @file AliHLTAgentSample.cxx
@author Matthias Richter
@date
@brief Agent of the libAliHLTSample library
*/
#include "AliHLTAgentSample.h"
#include "AliHLTConfiguration.h"
#include "TSystem.h"
/** global instance for agent registration */
AliHLTAgentSample gAliHLTAgentSample;
const char* AliHLTAgentSample::fgkAliHLTAgentSampleData="/tmp/testdata";
const char* AliHLTAgentSample::fgkAliHLTAgentSampleOut="/tmp/hltout";
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAgentSample)
AliHLTAgentSample::AliHLTAgentSample()
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTAgentSample::~AliHLTAgentSample()
{
// see header file for class documentation
// delete the test data
ofstream dump(fgkAliHLTAgentSampleData, ios::in);
if (dump.good()) {
TString arg("rm -f ");
arg+=fgkAliHLTAgentSampleData;
gSystem->Exec(arg.Data());
}
}
int AliHLTAgentSample::CreateConfigurations(AliHLTConfigurationHandler* handler,
AliRunLoader* runloader) const
{
// see header file for class documentation
// create some test data
ofstream dump(fgkAliHLTAgentSampleData, (ios::openmode)0);
dump << "This is just some test data for the ALICE HLT analysis example";
dump << "---- not copied" << endl;
dump.close();
if (handler) {
// the publisher configuration for the test data
TString arg("-datafile ");
arg+=fgkAliHLTAgentSampleData;
HLTDebug(arg.Data());
handler->CreateConfiguration("sample-fp1" , "FilePublisher", NULL , arg.Data());
// the configuration for the dummy component
handler->CreateConfiguration("sample-cp" , "Dummy" , "sample-fp1", "output_percentage 80");
// the writer configuration
arg="-datafile "; arg+=fgkAliHLTAgentSampleOut;
handler->CreateConfiguration("sample-sink1", "FileWriter" , "sample-cp" , arg.Data());
// sample offline source
handler->CreateConfiguration("sample-offsrc", "AliLoaderPublisher" , NULL , "-loader TPCLoader -tree digits -verbose");
// sample offline sink
handler->CreateConfiguration("sample-offsnk", "SampleOfflineDataSink" , "sample-offsrc" , NULL);
}
return 0;
}
const char* AliHLTAgentSample::GetLocalRecConfigurations(AliRunLoader* runloader) const
{
// see header file for class documentation
return "sample-sink1 sample-offsnk";
}
const char* AliHLTAgentSample::GetRequiredComponentLibraries() const
{
// see header file for class documentation
return "libAliHLTUtil.so libAliHLTSample.so";
}
<commit_msg>minor bugfix to avoid warning<commit_after>// @(#) $Id$
/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* ALICE Experiment at CERN, All rights reserved. *
* *
* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *
* for The ALICE HLT Project. *
* *
* 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. *
**************************************************************************/
/** @file AliHLTAgentSample.cxx
@author Matthias Richter
@date
@brief Agent of the libAliHLTSample library
*/
#include "AliHLTAgentSample.h"
#include "AliHLTConfiguration.h"
#include "TSystem.h"
/** global instance for agent registration */
AliHLTAgentSample gAliHLTAgentSample;
const char* AliHLTAgentSample::fgkAliHLTAgentSampleData="/tmp/testdata";
const char* AliHLTAgentSample::fgkAliHLTAgentSampleOut="/tmp/hltout";
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTAgentSample)
AliHLTAgentSample::AliHLTAgentSample()
{
// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}
AliHLTAgentSample::~AliHLTAgentSample()
{
// see header file for class documentation
// delete the test data
ofstream dump(fgkAliHLTAgentSampleData, ios::in);
if (dump.good()) {
TString arg("rm -f ");
arg+=fgkAliHLTAgentSampleData;
gSystem->Exec(arg.Data());
}
}
int AliHLTAgentSample::CreateConfigurations(AliHLTConfigurationHandler* handler,
AliRunLoader* runloader) const
{
// see header file for class documentation
// create some test data
ofstream dump(fgkAliHLTAgentSampleData, (ios::openmode)0);
dump << "This is just some test data for the ALICE HLT analysis example";
dump << "---- not copied" << endl;
dump.close();
if (handler) {
// the publisher configuration for the test data
TString arg("-datatype DUMMYDAT TEST -datafile ");
arg+=fgkAliHLTAgentSampleData;
HLTDebug(arg.Data());
handler->CreateConfiguration("sample-fp1" , "FilePublisher", NULL , arg.Data());
// the configuration for the dummy component
handler->CreateConfiguration("sample-cp" , "Dummy" , "sample-fp1", "output_percentage 80");
// the writer configuration
arg="-datafile "; arg+=fgkAliHLTAgentSampleOut;
handler->CreateConfiguration("sample-sink1", "FileWriter" , "sample-cp" , arg.Data());
// sample offline source
handler->CreateConfiguration("sample-offsrc", "AliLoaderPublisher" , NULL , "-loader TPCLoader -tree digits -verbose");
// sample offline sink
handler->CreateConfiguration("sample-offsnk", "SampleOfflineDataSink" , "sample-offsrc" , NULL);
}
return 0;
}
const char* AliHLTAgentSample::GetLocalRecConfigurations(AliRunLoader* runloader) const
{
// see header file for class documentation
return "sample-sink1 sample-offsnk";
}
const char* AliHLTAgentSample::GetRequiredComponentLibraries() const
{
// see header file for class documentation
return "libAliHLTUtil.so libAliHLTSample.so";
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkEnSightMasterServerReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkEnSightMasterServerReader.h"
#include "vtkObjectFactory.h"
#ifdef _MSC_VER
#pragma warning (push, 3)
#endif
#include <string>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
vtkCxxRevisionMacro(vtkEnSightMasterServerReader, "1.6");
vtkStandardNewMacro(vtkEnSightMasterServerReader);
static int vtkEnSightMasterServerReaderStartsWith(const char* str1, const char* str2)
{
if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
{
return 0;
}
return !strncmp(str1, str2, strlen(str2));
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::vtkEnSightMasterServerReader()
{
this->PieceCaseFileName = 0;
this->MaxNumberOfPieces = 0;
this->CurrentPiece = -1;
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::~vtkEnSightMasterServerReader()
{
this->SetPieceCaseFileName(0);
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::Execute()
{
if ( !this->MaxNumberOfPieces )
{
vtkErrorMacro("No pices to read");
return;
}
if ( this->CurrentPiece < 0 ||
this->CurrentPiece >= this->MaxNumberOfPieces )
{
vtkErrorMacro("Current piece has to be set before reading the file");
return;
}
if ( this->DetermineFileName(this->CurrentPiece) != VTK_OK )
{
vtkErrorMacro("Cannot update piece: " << this->CurrentPiece);
return;
}
if ( !this->Reader )
{
this->Reader = vtkGenericEnSightReader::New();
}
this->Reader->SetCaseFileName(this->PieceCaseFileName);
if ( !this->Reader->GetFilePath() )
{
this->Reader->SetFilePath( this->GetFilePath() );
}
this->Superclass::Execute();
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::ExecuteInformation()
{
if ( this->DetermineFileName(-1) != VTK_OK )
{
vtkErrorMacro("Problem parsing the case file");
return;
}
}
//----------------------------------------------------------------------------
int vtkEnSightMasterServerReader::DetermineFileName(int piece)
{
char line[1024];
if (!this->CaseFileName)
{
vtkErrorMacro("A case file name must be specified.");
return VTK_ERROR;
}
vtkstd::string sfilename;
if (this->FilePath)
{
sfilename = this->FilePath;
sfilename += this->CaseFileName;
vtkDebugMacro("full path to case file: " << sfilename.c_str());
}
else
{
sfilename = this->CaseFileName;
}
this->IS = new ifstream(sfilename.c_str(), ios::in);
if (this->IS->fail())
{
vtkErrorMacro("Unable to open file: " << sfilename.c_str());
delete this->IS;
this->IS = NULL;
return 0;
}
char result[1024];
int servers = 0;
int numberservers = 0;
int currentserver = 0;
while ( this->ReadNextDataLine(result) )
{
if ( strcmp(result, "FORMAT") == 0 )
{
// Format
}
else if ( strcmp(result, "SERVERS") == 0 )
{
servers = 1;
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "number of servers:") )
{
sscanf(result, "number of servers: %i", &numberservers);
if ( !numberservers )
{
vtkErrorMacro("The case file is corrupted");
break;
}
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "casefile:") )
{
if ( currentserver == piece )
{
char filename[1024] = "";
sscanf(result, "casefile: %s", filename);
if ( filename[0] == 0 )
{
vtkErrorMacro("Problem parsing file name from: " << result);
return VTK_ERROR;
}
this->SetPieceCaseFileName(filename);
break;
}
currentserver ++;
}
}
if ( piece == -1 && currentserver != numberservers )
{
//cout << "Number of servers (" << numberservers
//<< ") is not equal to the actual number of servers ("
//<< currentserver << ")" << endl;
return VTK_ERROR;
}
this->MaxNumberOfPieces = numberservers;
delete this->IS;
this->IS = 0;
return VTK_OK;
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Current piece: " << this->CurrentPiece << endl;
os << indent << "Piece Case File name: "
<< (this->PieceCaseFileName?this->PieceCaseFileName:"<none>") << endl;
os << indent << "Maximum numbe of pieces: " << this->MaxNumberOfPieces
<< endl;
}
<commit_msg>Remove unused variable<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkEnSightMasterServerReader.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkEnSightMasterServerReader.h"
#include "vtkObjectFactory.h"
#ifdef _MSC_VER
#pragma warning (push, 3)
#endif
#include <string>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
vtkCxxRevisionMacro(vtkEnSightMasterServerReader, "1.7");
vtkStandardNewMacro(vtkEnSightMasterServerReader);
static int vtkEnSightMasterServerReaderStartsWith(const char* str1, const char* str2)
{
if ( !str1 || !str2 || strlen(str1) < strlen(str2) )
{
return 0;
}
return !strncmp(str1, str2, strlen(str2));
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::vtkEnSightMasterServerReader()
{
this->PieceCaseFileName = 0;
this->MaxNumberOfPieces = 0;
this->CurrentPiece = -1;
}
//----------------------------------------------------------------------------
vtkEnSightMasterServerReader::~vtkEnSightMasterServerReader()
{
this->SetPieceCaseFileName(0);
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::Execute()
{
if ( !this->MaxNumberOfPieces )
{
vtkErrorMacro("No pices to read");
return;
}
if ( this->CurrentPiece < 0 ||
this->CurrentPiece >= this->MaxNumberOfPieces )
{
vtkErrorMacro("Current piece has to be set before reading the file");
return;
}
if ( this->DetermineFileName(this->CurrentPiece) != VTK_OK )
{
vtkErrorMacro("Cannot update piece: " << this->CurrentPiece);
return;
}
if ( !this->Reader )
{
this->Reader = vtkGenericEnSightReader::New();
}
this->Reader->SetCaseFileName(this->PieceCaseFileName);
if ( !this->Reader->GetFilePath() )
{
this->Reader->SetFilePath( this->GetFilePath() );
}
this->Superclass::Execute();
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::ExecuteInformation()
{
if ( this->DetermineFileName(-1) != VTK_OK )
{
vtkErrorMacro("Problem parsing the case file");
return;
}
}
//----------------------------------------------------------------------------
int vtkEnSightMasterServerReader::DetermineFileName(int piece)
{
if (!this->CaseFileName)
{
vtkErrorMacro("A case file name must be specified.");
return VTK_ERROR;
}
vtkstd::string sfilename;
if (this->FilePath)
{
sfilename = this->FilePath;
sfilename += this->CaseFileName;
vtkDebugMacro("full path to case file: " << sfilename.c_str());
}
else
{
sfilename = this->CaseFileName;
}
this->IS = new ifstream(sfilename.c_str(), ios::in);
if (this->IS->fail())
{
vtkErrorMacro("Unable to open file: " << sfilename.c_str());
delete this->IS;
this->IS = NULL;
return 0;
}
char result[1024];
int servers = 0;
int numberservers = 0;
int currentserver = 0;
while ( this->ReadNextDataLine(result) )
{
if ( strcmp(result, "FORMAT") == 0 )
{
// Format
}
else if ( strcmp(result, "SERVERS") == 0 )
{
servers = 1;
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "number of servers:") )
{
sscanf(result, "number of servers: %i", &numberservers);
if ( !numberservers )
{
vtkErrorMacro("The case file is corrupted");
break;
}
}
else if ( servers &&
vtkEnSightMasterServerReaderStartsWith(result, "casefile:") )
{
if ( currentserver == piece )
{
char filename[1024] = "";
sscanf(result, "casefile: %s", filename);
if ( filename[0] == 0 )
{
vtkErrorMacro("Problem parsing file name from: " << result);
return VTK_ERROR;
}
this->SetPieceCaseFileName(filename);
break;
}
currentserver ++;
}
}
if ( piece == -1 && currentserver != numberservers )
{
//cout << "Number of servers (" << numberservers
//<< ") is not equal to the actual number of servers ("
//<< currentserver << ")" << endl;
return VTK_ERROR;
}
this->MaxNumberOfPieces = numberservers;
delete this->IS;
this->IS = 0;
return VTK_OK;
}
//----------------------------------------------------------------------------
void vtkEnSightMasterServerReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Current piece: " << this->CurrentPiece << endl;
os << indent << "Piece Case File name: "
<< (this->PieceCaseFileName?this->PieceCaseFileName:"<none>") << endl;
os << indent << "Maximum numbe of pieces: " << this->MaxNumberOfPieces
<< endl;
}
<|endoftext|>
|
<commit_before>#include "include/properties_reader.h"
//Constructor
PropertiesReader::PropertiesReader(std::string file_path) {
//Open the file
std::string line;
//Check if the file exists
struct stat buffer;
if (stat (file_path.c_str(), &buffer) == 0) {
std::ifstream file (file_path);
if (file.is_open()) {
while (getline (file, line) ) {
//Read a line from the property file
//Figure out if we have a blank or comment line
if (line.length() > 0) {
if (line[0] != '/' || line[1] != '/') {
std::size_t eq_pos = line.find("=", 0);
if (eq_pos != std::string::npos) {
std::string var_name = line.substr(0, eq_pos);
std::string var_value = line.substr(eq_pos+1, line.length() - eq_pos);
opts.emplace(var_name, var_value);
}
else
{
//We have a line that's non-blank and not a comment, as well as not a key-value pair
//In this case, we assume that we have a list, which uses the syntax -list_name-list_value
std::cout << "list case encountered: " << line << std::endl;
std::size_t eq_pos = line.find("-", 1);
if (eq_pos != std::string::npos) {
std::string list_name = line.substr(0, eq_pos);
std::string list_value = line.substr(eq_pos+1, line.length() - eq_pos);
if (!list_exist(list_name))
{
//Create a new list and add it to the map
std::vector<std::string> val_list;
val_list.push_back(list_value);
opt_lists.emplace(list_name, val_list);
std::cout << "New List Created: " << list_name << std::endl;
}
else
{
//Add to an existing list in the map
std::vector<std::string> val_list;
val_list = get_list(list_name);
val_list.push_back(list_value);
opt_lists[list_name] = val_list;
std::cout << "List Updated: " << list_name << std::endl;
}
}
}
}
}
}
file.close();
}
}
}
//Does a key exist?
bool PropertiesReader::opt_exist( std::string key )
{
auto search = opts.find(key);
if (search != opts.end())
{
return true;
}
return false;
}
//Does a key exist?
bool PropertiesReader::list_exist( std::string key )
{
auto search = opt_lists.find(key);
if (search != opt_lists.end())
{
return true;
}
return false;
}
<commit_msg>Properties Reader Lists<commit_after>#include "include/properties_reader.h"
//Constructor
PropertiesReader::PropertiesReader(std::string file_path) {
//Open the file
std::string line;
//Check if the file exists
struct stat buffer;
if (stat (file_path.c_str(), &buffer) == 0) {
std::ifstream file (file_path);
if (file.is_open()) {
while (getline (file, line) ) {
//Read a line from the property file
//Figure out if we have a blank or comment line
if (line.length() > 0) {
if (line[0] != '/' || line[1] != '/') {
std::size_t eq_pos = line.find("=", 0);
if (eq_pos != std::string::npos) {
std::string var_name = line.substr(0, eq_pos);
std::string var_value = line.substr(eq_pos+1, line.length() - eq_pos);
opts.emplace(var_name, var_value);
}
else
{
//We have a line that's non-blank and not a comment, as well as not a key-value pair
//In this case, we assume that we have a list, which uses the syntax -list_name-list_value
std::cout << "list case encountered: " << line << std::endl;
std::size_t eq_pos = line.find("-", 1);
if (eq_pos != std::string::npos) {
std::string list_name = line.substr(1, eq_pos);
std::string list_value = line.substr(eq_pos+1, line.length() - eq_pos);
if (!list_exist(list_name))
{
//Create a new list and add it to the map
std::vector<std::string> val_list;
val_list.push_back(list_value);
opt_lists.emplace(list_name, val_list);
std::cout << "New List Created: " << list_name << std::endl;
}
else
{
//Add to an existing list in the map
std::vector<std::string> val_list;
val_list = get_list(list_name);
val_list.push_back(list_value);
opt_lists[list_name] = val_list;
std::cout << "List Updated: " << list_name << std::endl;
}
}
}
}
}
}
file.close();
}
}
}
//Does a key exist?
bool PropertiesReader::opt_exist( std::string key )
{
auto search = opts.find(key);
if (search != opts.end())
{
return true;
}
return false;
}
//Does a key exist?
bool PropertiesReader::list_exist( std::string key )
{
auto search = opt_lists.find(key);
if (search != opt_lists.end())
{
return true;
}
return false;
}
<|endoftext|>
|
<commit_before><commit_msg>lokdocview: ensure that the cursor is at least 30 twips wide<commit_after><|endoftext|>
|
<commit_before>/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2011-2016. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include "egl_impl.h"
#define WX_DEF_EXTS
#include "gen/gl_fdefs.h"
#include "gen/gl_finit.h"
#include "gen/glu_finit.h"
void init_tess();
void exit_tess();
int load_gl_functions();
/* ****************************************************************************
* OPENGL INITIALIZATION
*****************************************************************************/
int egl_initiated = 0;
#ifdef _WIN32
#define RTLD_LAZY 0
#define OPENGL_LIB L"opengl32.dll"
#define OPENGLU_LIB L"glu32.dll"
typedef HMODULE DL_LIB_P;
typedef WCHAR DL_CHAR;
void * dlsym(HMODULE Lib, const char *func) {
void * funcp;
if((funcp = (void *) GetProcAddress(Lib, func)))
return funcp;
else
return (void *) wglGetProcAddress(func);
}
HMODULE dlopen(const WCHAR *DLL, int unused) {
return LoadLibrary(DLL);
}
void dlclose(HMODULE Lib) {
FreeLibrary(Lib);
}
#else
typedef void * DL_LIB_P;
typedef char DL_CHAR;
# ifdef _MACOSX
# define OPENGL_LIB "/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib"
# define OPENGLU_LIB "/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLU.dylib"
# else
# define OPENGL_LIB "libGL.so.1"
# define OPENGLU_LIB "libGLU.so.1"
# endif
#endif
extern "C" {
DRIVER_INIT(EGL_DRIVER) {
return NULL;
}
}
int egl_init_opengl(void *erlCallbacks)
{
#ifdef _WIN32
driver_init((TWinDynDriverCallbacks *) erlCallbacks);
#endif
if(egl_initiated == 0) {
if(load_gl_functions()) {
init_tess();
egl_initiated = 1;
}
}
return 1;
}
int load_gl_functions() {
DL_CHAR * DLName = (DL_CHAR *) OPENGL_LIB;
DL_LIB_P LIBhandle = dlopen(DLName, RTLD_LAZY);
//fprintf(stderr, "Loading GL: %s\r\n", (const char*)DLName);
void * func = NULL;
int i;
if(LIBhandle) {
for(i=0; gl_fns[i].name != NULL; i++) {
if((func = dlsym(LIBhandle, gl_fns[i].name))) {
* (void **) (gl_fns[i].func) = func;
// fprintf(stderr, "GL LOADED %s \r\n", gl_fns[i].name);
} else {
if(gl_fns[i].alt != NULL) {
if((func = dlsym(LIBhandle, gl_fns[i].alt))) {
* (void **) (gl_fns[i].func) = func;
// fprintf(stderr, "GL LOADED %s \r\n", gl_fns[i].alt);
} else {
* (void **) (gl_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GL Skipped %s and %s \r\n", gl_fns[i].name, gl_fns[i].alt);
};
} else {
* (void **) (gl_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GL Skipped %s \r\n", gl_fns[i].name);
}
}
}
// dlclose(LIBhandle);
// fprintf(stderr, "OPENGL library is loaded\r\n");
} else {
fprintf(stderr, "Could NOT load OpenGL library: %s\r\n", DLName);
};
DLName = (DL_CHAR *) OPENGLU_LIB;
LIBhandle = dlopen(DLName, RTLD_LAZY);
// fprintf(stderr, "Loading GLU: %s\r\n", (const char*)DLName);
func = NULL;
if(LIBhandle) {
for(i=0; glu_fns[i].name != NULL; i++) {
if((func = dlsym(LIBhandle, glu_fns[i].name))) {
* (void **) (glu_fns[i].func) = func;
} else {
if(glu_fns[i].alt != NULL) {
if((func = dlsym(LIBhandle, glu_fns[i].alt))) {
* (void **) (glu_fns[i].func) = func;
} else {
* (void **) (glu_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GLU Skipped %s\r\n", glu_fns[i].alt);
};
} else {
* (void **) (glu_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GLU Skipped %s\r\n", glu_fns[i].name);
}
}
}
// dlclose(LIBhandle);
// fprintf(stderr, "GLU library is loaded\r\n");
} else {
fprintf(stderr, "Could NOT load OpenGL GLU library: %s\r\n", DLName);
};
return 1;
}
void gl_error() {
// fprintf(stderr, "OpenGL Extension not available \r\n");
throw "undef_extension";
}
/* *******************************************************************************
* GLU Tesselation special
* ******************************************************************************/
static GLUtesselator* tess;
typedef struct {
GLdouble * tess_coords;
int alloc_n;
int alloc_max;
int * tess_index_list;
int index_n;
int index_max;
int error;
} egl_tess_data;
#define NEED_MORE_ALLOC 1
#define NEED_MORE_INDEX 2
static egl_tess_data egl_tess;
void CALLBACK
egl_ogla_vertex(GLdouble* coords)
{
/* fprintf(stderr, "%d\r\n", (int) (coords - tess_coords) / 3); */
if(egl_tess.index_n < egl_tess.index_max) {
egl_tess.tess_index_list[egl_tess.index_n] = (int) (coords - egl_tess.tess_coords) / 3;
egl_tess.index_n++;
}
else
egl_tess.error = NEED_MORE_INDEX;
}
void CALLBACK
egl_ogla_combine(GLdouble coords[3],
void* vertex_data[4],
GLfloat w[4],
void **dataOut)
{
GLdouble* vertex = &egl_tess.tess_coords[egl_tess.alloc_n];
if(egl_tess.alloc_n < egl_tess.alloc_max) {
egl_tess.alloc_n += 3;
vertex[0] = coords[0];
vertex[1] = coords[1];
vertex[2] = coords[2];
*dataOut = vertex;
#if 0
fprintf(stderr, "combine: ");
int i;
for (i = 0; i < 4; i++) {
if (w[i] > 0.0) {
fprintf(stderr, "%d(%g) ", (int) vertex_data[i], w[i]);
}
}
fprintf(stderr, "\r\n");
fprintf(stderr, "%g %g %g\r\n", vertex[0], vertex[1], vertex[2]);
#endif
} else {
egl_tess.error = NEED_MORE_ALLOC;
*dataOut = NULL;
}
}
void CALLBACK
egl_ogla_edge_flag(GLboolean flag)
{
}
void CALLBACK
egl_ogla_error(GLenum errorCode)
{
// const GLubyte *err;
// err = gluErrorString(errorCode);
// fprintf(stderr, "Tesselation error: %d: %s\r\n", (int) errorCode, err);
}
void init_tess()
{
tess = gluNewTess();
gluTessCallback(tess, GLU_TESS_VERTEX, (GLUfuncptr) egl_ogla_vertex);
gluTessCallback(tess, GLU_TESS_EDGE_FLAG, (GLUfuncptr) egl_ogla_edge_flag);
gluTessCallback(tess, GLU_TESS_COMBINE, (GLUfuncptr) egl_ogla_combine);
gluTessCallback(tess, GLU_TESS_ERROR, (GLUfuncptr) egl_ogla_error);
}
void exit_tess()
{
gluDeleteTess(tess);
}
int erl_tess_impl(char* buff, ErlDrvPort port, ErlDrvTermData caller)
{
ErlDrvBinary* bin;
int i;
int num_vertices;
GLdouble *n;
int AP;
int a_max = 2;
int i_max = 6;
num_vertices = * (int *) buff; buff += 8; /* Align */
n = (double *) buff; buff += 8*3;
egl_tess.alloc_max = a_max*num_vertices*3;
bin = driver_alloc_binary(egl_tess.alloc_max*sizeof(GLdouble));
egl_tess.error = 0;
egl_tess.tess_coords = (double *) bin->orig_bytes;
memcpy(egl_tess.tess_coords,buff,num_vertices*3*sizeof(GLdouble));
egl_tess.index_max = i_max*3*num_vertices;
egl_tess.tess_index_list = (int *) driver_alloc(sizeof(int) * egl_tess.index_max);
egl_tess.tess_coords = (double *) bin->orig_bytes;
egl_tess.index_n = 0;
egl_tess.alloc_n = num_vertices*3;
gluTessNormal(tess, n[0], n[1], n[2]);
gluTessBeginPolygon(tess, 0);
gluTessBeginContour(tess);
for (i = 0; i < num_vertices; i++) {
gluTessVertex(tess, egl_tess.tess_coords+3*i, egl_tess.tess_coords+3*i);
}
gluTessEndContour(tess);
gluTessEndPolygon(tess);
AP = 0; ErlDrvTermData *rt;
rt = (ErlDrvTermData *) driver_alloc(sizeof(ErlDrvTermData) * (13+egl_tess.index_n*2));
rt[AP++]=ERL_DRV_ATOM; rt[AP++]=driver_mk_atom((char *) "_egl_result_");
for(i=0; i < egl_tess.index_n; i++) {
rt[AP++] = ERL_DRV_INT; rt[AP++] = (int) egl_tess.tess_index_list[i];
};
rt[AP++] = ERL_DRV_NIL; rt[AP++] = ERL_DRV_LIST; rt[AP++] = egl_tess.index_n+1;
rt[AP++] = ERL_DRV_BINARY; rt[AP++] = (ErlDrvTermData) bin;
rt[AP++] = egl_tess.alloc_n*sizeof(GLdouble); rt[AP++] = 0;
rt[AP++] = ERL_DRV_TUPLE; rt[AP++] = 2; // Return tuple {list, Bin}
rt[AP++] = ERL_DRV_TUPLE; rt[AP++] = 2; // Result tuple
driver_send_term(port,caller,rt,AP);
/* fprintf(stderr, "List %d: %d %d %d \r\n", */
/* res, */
/* n_pos, */
/* (tess_alloc_vertex-new_vertices)*sizeof(GLdouble), */
/* num_vertices*6*sizeof(GLdouble)); */
driver_free_binary(bin);
driver_free(egl_tess.tess_index_list);
driver_free(rt);
return 0;
}
<commit_msg>wx: Fix windows compiler warnings<commit_after>/*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2011-2016. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include "egl_impl.h"
#define WX_DEF_EXTS
#include "gen/gl_fdefs.h"
#include "gen/gl_finit.h"
#include "gen/glu_finit.h"
void init_tess();
void exit_tess();
int load_gl_functions();
/* ****************************************************************************
* OPENGL INITIALIZATION
*****************************************************************************/
int egl_initiated = 0;
#ifdef _WIN32
#define RTLD_LAZY 0
#define OPENGL_LIB L"opengl32.dll"
#define OPENGLU_LIB L"glu32.dll"
typedef HMODULE DL_LIB_P;
typedef WCHAR DL_CHAR;
#define DL_STR_FMT "%S"
void * dlsym(HMODULE Lib, const char *func) {
void * funcp;
if((funcp = (void *) GetProcAddress(Lib, func)))
return funcp;
else
return (void *) wglGetProcAddress(func);
}
HMODULE dlopen(const WCHAR *DLL, int unused) {
return LoadLibrary(DLL);
}
void dlclose(HMODULE Lib) {
FreeLibrary(Lib);
}
#else
typedef void * DL_LIB_P;
typedef char DL_CHAR;
# define DL_STR_FMT "%s"
# ifdef _MACOSX
# define OPENGL_LIB "/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib"
# define OPENGLU_LIB "/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGLU.dylib"
# else
# define OPENGL_LIB "libGL.so.1"
# define OPENGLU_LIB "libGLU.so.1"
# endif
#endif
extern "C" {
DRIVER_INIT(EGL_DRIVER) {
return NULL;
}
}
int egl_init_opengl(void *erlCallbacks)
{
#ifdef _WIN32
driver_init((TWinDynDriverCallbacks *) erlCallbacks);
#endif
if(egl_initiated == 0) {
if(load_gl_functions()) {
init_tess();
egl_initiated = 1;
}
}
return 1;
}
int load_gl_functions() {
DL_CHAR * DLName = (DL_CHAR *) OPENGL_LIB;
DL_LIB_P LIBhandle = dlopen(DLName, RTLD_LAZY);
//fprintf(stderr, "Loading GL: %s\r\n", (const char*)DLName);
void * func = NULL;
int i;
if(LIBhandle) {
for(i=0; gl_fns[i].name != NULL; i++) {
if((func = dlsym(LIBhandle, gl_fns[i].name))) {
* (void **) (gl_fns[i].func) = func;
// fprintf(stderr, "GL LOADED %s \r\n", gl_fns[i].name);
} else {
if(gl_fns[i].alt != NULL) {
if((func = dlsym(LIBhandle, gl_fns[i].alt))) {
* (void **) (gl_fns[i].func) = func;
// fprintf(stderr, "GL LOADED %s \r\n", gl_fns[i].alt);
} else {
* (void **) (gl_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GL Skipped %s and %s \r\n", gl_fns[i].name, gl_fns[i].alt);
};
} else {
* (void **) (gl_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GL Skipped %s \r\n", gl_fns[i].name);
}
}
}
// dlclose(LIBhandle);
// fprintf(stderr, "OPENGL library is loaded\r\n");
} else {
fprintf(stderr, "Could NOT load OpenGL library: " DL_STR_FMT "\r\n", DLName);
};
DLName = (DL_CHAR *) OPENGLU_LIB;
LIBhandle = dlopen(DLName, RTLD_LAZY);
// fprintf(stderr, "Loading GLU: %s\r\n", (const char*)DLName);
func = NULL;
if(LIBhandle) {
for(i=0; glu_fns[i].name != NULL; i++) {
if((func = dlsym(LIBhandle, glu_fns[i].name))) {
* (void **) (glu_fns[i].func) = func;
} else {
if(glu_fns[i].alt != NULL) {
if((func = dlsym(LIBhandle, glu_fns[i].alt))) {
* (void **) (glu_fns[i].func) = func;
} else {
* (void **) (glu_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GLU Skipped %s\r\n", glu_fns[i].alt);
};
} else {
* (void **) (glu_fns[i].func) = (void *) &gl_error;
// fprintf(stderr, "GLU Skipped %s\r\n", glu_fns[i].name);
}
}
}
// dlclose(LIBhandle);
// fprintf(stderr, "GLU library is loaded\r\n");
} else {
fprintf(stderr, "Could NOT load OpenGL GLU library: " DL_STR_FMT "\r\n", DLName);
};
return 1;
}
void gl_error() {
// fprintf(stderr, "OpenGL Extension not available \r\n");
throw "undef_extension";
}
/* *******************************************************************************
* GLU Tesselation special
* ******************************************************************************/
static GLUtesselator* tess;
typedef struct {
GLdouble * tess_coords;
int alloc_n;
int alloc_max;
int * tess_index_list;
int index_n;
int index_max;
int error;
} egl_tess_data;
#define NEED_MORE_ALLOC 1
#define NEED_MORE_INDEX 2
static egl_tess_data egl_tess;
void CALLBACK
egl_ogla_vertex(GLdouble* coords)
{
/* fprintf(stderr, "%d\r\n", (int) (coords - tess_coords) / 3); */
if(egl_tess.index_n < egl_tess.index_max) {
egl_tess.tess_index_list[egl_tess.index_n] = (int) (coords - egl_tess.tess_coords) / 3;
egl_tess.index_n++;
}
else
egl_tess.error = NEED_MORE_INDEX;
}
void CALLBACK
egl_ogla_combine(GLdouble coords[3],
void* vertex_data[4],
GLfloat w[4],
void **dataOut)
{
GLdouble* vertex = &egl_tess.tess_coords[egl_tess.alloc_n];
if(egl_tess.alloc_n < egl_tess.alloc_max) {
egl_tess.alloc_n += 3;
vertex[0] = coords[0];
vertex[1] = coords[1];
vertex[2] = coords[2];
*dataOut = vertex;
#if 0
fprintf(stderr, "combine: ");
int i;
for (i = 0; i < 4; i++) {
if (w[i] > 0.0) {
fprintf(stderr, "%d(%g) ", (int) vertex_data[i], w[i]);
}
}
fprintf(stderr, "\r\n");
fprintf(stderr, "%g %g %g\r\n", vertex[0], vertex[1], vertex[2]);
#endif
} else {
egl_tess.error = NEED_MORE_ALLOC;
*dataOut = NULL;
}
}
void CALLBACK
egl_ogla_edge_flag(GLboolean flag)
{
}
void CALLBACK
egl_ogla_error(GLenum errorCode)
{
// const GLubyte *err;
// err = gluErrorString(errorCode);
// fprintf(stderr, "Tesselation error: %d: %s\r\n", (int) errorCode, err);
}
void init_tess()
{
tess = gluNewTess();
gluTessCallback(tess, GLU_TESS_VERTEX, (GLUfuncptr) egl_ogla_vertex);
gluTessCallback(tess, GLU_TESS_EDGE_FLAG, (GLUfuncptr) egl_ogla_edge_flag);
gluTessCallback(tess, GLU_TESS_COMBINE, (GLUfuncptr) egl_ogla_combine);
gluTessCallback(tess, GLU_TESS_ERROR, (GLUfuncptr) egl_ogla_error);
}
void exit_tess()
{
gluDeleteTess(tess);
}
int erl_tess_impl(char* buff, ErlDrvPort port, ErlDrvTermData caller)
{
ErlDrvBinary* bin;
int i;
int num_vertices;
GLdouble *n;
int AP;
int a_max = 2;
int i_max = 6;
num_vertices = * (int *) buff; buff += 8; /* Align */
n = (double *) buff; buff += 8*3;
egl_tess.alloc_max = a_max*num_vertices*3;
bin = driver_alloc_binary(egl_tess.alloc_max*sizeof(GLdouble));
egl_tess.error = 0;
egl_tess.tess_coords = (double *) bin->orig_bytes;
memcpy(egl_tess.tess_coords,buff,num_vertices*3*sizeof(GLdouble));
egl_tess.index_max = i_max*3*num_vertices;
egl_tess.tess_index_list = (int *) driver_alloc(sizeof(int) * egl_tess.index_max);
egl_tess.tess_coords = (double *) bin->orig_bytes;
egl_tess.index_n = 0;
egl_tess.alloc_n = num_vertices*3;
gluTessNormal(tess, n[0], n[1], n[2]);
gluTessBeginPolygon(tess, 0);
gluTessBeginContour(tess);
for (i = 0; i < num_vertices; i++) {
gluTessVertex(tess, egl_tess.tess_coords+3*i, egl_tess.tess_coords+3*i);
}
gluTessEndContour(tess);
gluTessEndPolygon(tess);
AP = 0; ErlDrvTermData *rt;
rt = (ErlDrvTermData *) driver_alloc(sizeof(ErlDrvTermData) * (13+egl_tess.index_n*2));
rt[AP++]=ERL_DRV_ATOM; rt[AP++]=driver_mk_atom((char *) "_egl_result_");
for(i=0; i < egl_tess.index_n; i++) {
rt[AP++] = ERL_DRV_INT; rt[AP++] = (int) egl_tess.tess_index_list[i];
};
rt[AP++] = ERL_DRV_NIL; rt[AP++] = ERL_DRV_LIST; rt[AP++] = egl_tess.index_n+1;
rt[AP++] = ERL_DRV_BINARY; rt[AP++] = (ErlDrvTermData) bin;
rt[AP++] = egl_tess.alloc_n*sizeof(GLdouble); rt[AP++] = 0;
rt[AP++] = ERL_DRV_TUPLE; rt[AP++] = 2; // Return tuple {list, Bin}
rt[AP++] = ERL_DRV_TUPLE; rt[AP++] = 2; // Result tuple
driver_send_term(port,caller,rt,AP);
/* fprintf(stderr, "List %d: %d %d %d \r\n", */
/* res, */
/* n_pos, */
/* (tess_alloc_vertex-new_vertices)*sizeof(GLdouble), */
/* num_vertices*6*sizeof(GLdouble)); */
driver_free_binary(bin);
driver_free(egl_tess.tess_index_list);
driver_free(rt);
return 0;
}
<|endoftext|>
|
<commit_before>/*
This file is part of libkcal.
Copyright (c) 1998 Preston Brown
Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <kdebug.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "journal.h"
#include "filestorage.h"
#include "calendarlocal.h"
using namespace KCal;
CalendarLocal::CalendarLocal()
: Calendar()
{
init();
}
CalendarLocal::CalendarLocal(const QString &timeZoneId)
: Calendar(timeZoneId)
{
init();
}
void CalendarLocal::init()
{
}
CalendarLocal::~CalendarLocal()
{
close();
}
bool CalendarLocal::load( const QString &fileName )
{
FileStorage storage( this, fileName );
return storage.load();
}
bool CalendarLocal::save( const QString &fileName, CalFormat *format )
{
FileStorage storage( this, fileName, format );
return storage.save();
}
void CalendarLocal::close()
{
deleteAllEvents();
deleteAllTodos();
deleteAllJournals();
setModified( false );
}
bool CalendarLocal::addEvent( Event *event )
{
insertEvent( event );
event->registerObserver( this );
setModified( true );
return true;
}
void CalendarLocal::deleteEvent( Event *event )
{
kdDebug(5800) << "CalendarLocal::deleteEvent" << endl;
if ( mEventList.removeRef( event ) ) {
setModified( true );
} else {
kdWarning() << "CalendarLocal::deleteEvent(): Event not found." << endl;
}
}
void CalendarLocal::deleteAllEvents()
{
// kdDebug(5800) << "CalendarLocal::deleteAllEvents" << endl;
mEventList.setAutoDelete( true );
mEventList.clear();
mEventList.setAutoDelete( false );
}
Event *CalendarLocal::event( const QString &uid )
{
kdDebug(5800) << "CalendarLocal::event(): " << uid << endl;
Event::List::ConstIterator it;
for ( it = mEventList.begin(); it != mEventList.end(); ++it ) {
if ( (*it)->uid() == uid ) {
return *it;
}
}
return 0;
}
bool CalendarLocal::addTodo( Todo *todo )
{
mTodoList.append( todo );
todo->registerObserver( this );
// Set up subtask relations
setupRelations( todo );
setModified( true );
return true;
}
void CalendarLocal::deleteTodo( Todo *todo )
{
// Handle orphaned children
removeRelations( todo );
if ( mTodoList.removeRef( todo ) ) {
setModified( true );
}
}
void CalendarLocal::deleteAllTodos()
{
// kdDebug(5800) << "CalendarLocal::deleteAllTodos()\n";
mTodoList.setAutoDelete( true );
mTodoList.clear();
mTodoList.setAutoDelete( false );
}
Todo::List CalendarLocal::rawTodos()
{
return mTodoList;
}
Todo *CalendarLocal::todo( const QString &uid )
{
Todo::List::ConstIterator it;
for ( it = mTodoList.begin(); it != mTodoList.end(); ++it ) {
if ( (*it)->uid() == uid ) return *it;
}
return 0;
}
Todo::List CalendarLocal::todos( const QDate &date )
{
Todo::List todos;
Todo::List::ConstIterator it;
for ( it = mTodoList.begin(); it != mTodoList.end(); ++it ) {
Todo *todo = *it;
if ( todo->hasDueDate() && todo->dtDue().date() == date ) {
todos.append( todo );
}
}
return todos;
}
Alarm::List CalendarLocal::alarmsTo( const QDateTime &to )
{
return alarms( QDateTime( QDate( 1900, 1, 1 ) ), to );
}
Alarm::List CalendarLocal::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "CalendarLocal::alarms(" << from.toString() << " - "
// << to.toString() << ")" << endl;
Alarm::List alarms;
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *e = *it;
if ( e->doesRecur() ) appendRecurringAlarms( alarms, e, from, to );
else appendAlarms( alarms, e, from, to );
}
Todo::List::ConstIterator it2;
for( it2 = mTodoList.begin(); it2 != mTodoList.end(); ++it2 ) {
appendAlarms( alarms, *it2, from, to );
}
return alarms;
}
void CalendarLocal::appendAlarms( Alarm::List &alarms, Incidence *incidence,
const QDateTime &from, const QDateTime &to )
{
Alarm::List::ConstIterator it;
for( it = incidence->alarms().begin(); it != incidence->alarms().end();
++it ) {
// kdDebug(5800) << "CalendarLocal::appendAlarms() '" << alarm->text()
// << "': " << alarm->time().toString() << " - " << alarm->enabled() << endl;
if ( (*it)->enabled() ) {
if ( (*it)->time() >= from && (*it)->time() <= to ) {
kdDebug(5800) << "CalendarLocal::appendAlarms() '"
<< incidence->summary() << "': "
<< (*it)->time().toString() << endl;
alarms.append( *it );
}
}
}
}
void CalendarLocal::appendRecurringAlarms( Alarm::List &alarms,
Incidence *incidence,
const QDateTime &from,
const QDateTime &to )
{
Alarm::List::ConstIterator it;
QDateTime qdt;
for( it = incidence->alarms().begin(); it != incidence->alarms().end();
++it ) {
if ( incidence->recursOn( from.date() ) ) {
// Find a recurrence which might have an alarm in the
// specified time interval
#warning "This doesn't work for minutely or hourly recurrences"
// TODO: This misses recurrences after 'from' but within the time range.
qdt.setTime( (*it)->time().time() );
qdt.setDate( from.date() );
}
else qdt = (*it)->time();
kdDebug(5800) << "CalendarLocal::appendAlarms() '" << incidence->summary()
<< "': " << qdt.toString() << " - " << (*it)->enabled()
<< endl;
if ( (*it)->enabled() ) {
// kdDebug(5800) << "CalendarLocal::appendAlarms() '" << incidence->summary()
// << "': " << (*it)->time().toString() << endl;
if ( qdt >= from && qdt <= to ) {
alarms.append( *it );
}
}
}
}
/****************************** PROTECTED METHODS ****************************/
// after changes are made to an event, this should be called.
void CalendarLocal::update( IncidenceBase *incidence )
{
incidence->setSyncStatus( Event::SYNCMOD );
incidence->setLastModified( QDateTime::currentDateTime() );
// we should probably update the revision number here,
// or internally in the Event itself when certain things change.
// need to verify with ical documentation.
setModified( true );
}
void CalendarLocal::insertEvent( Event *event )
{
if ( mEventList.find( event ) == mEventList.end() ) {
mEventList.append( event );
}
}
Event::List CalendarLocal::rawEventsForDate( const QDate &qd, bool sorted )
{
Event::List eventList;
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *event = *it;
if ( event->doesRecur() ) {
if ( event->isMultiDay() ) {
int extraDays = event->dtStart().date().daysTo( event->dtEnd().date() );
int i;
for ( i = 0; i <= extraDays; i++ ) {
if ( event->recursOn( qd.addDays( -i ) ) ) {
eventList.append( event );
break;
}
}
} else {
if ( event->recursOn( qd ) )
eventList.append( event );
}
} else {
if ( event->dtStart().date() <= qd && event->dtEnd().date() >= qd ) {
eventList.append( event );
}
}
}
if ( !sorted ) {
return eventList;
}
// kdDebug(5800) << "Sorting events for date\n" << endl;
// now, we have to sort it based on dtStart.time()
Event::List eventListSorted;
Event::List::Iterator sortIt;
for ( it = eventList.begin(); it != eventList.end(); ++it ) {
sortIt = eventListSorted.begin();
while ( sortIt != eventListSorted.end() &&
(*it)->dtStart().time() >= (*sortIt)->dtStart().time() ) {
++sortIt;
}
eventListSorted.insert( sortIt, *it );
}
return eventListSorted;
}
Event::List CalendarLocal::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
Event::List eventList;
// Get non-recurring events
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *event = *it;
if ( event->doesRecur() ) {
QDate rStart = event->dtStart().date();
bool found = false;
if ( inclusive ) {
if ( rStart >= start && rStart <= end ) {
// Start date of event is in range. Now check for end date.
// if duration is negative, event recurs forever, so do not include it.
if ( event->recurrence()->duration() == 0 ) { // End date set
QDate rEnd = event->recurrence()->endDate();
if ( rEnd >= start && rEnd <= end ) { // End date within range
found = true;
}
} else if ( event->recurrence()->duration() > 0 ) { // Duration set
// TODO: Calculate end date from duration. Should be done in Event
// For now exclude all events with a duration.
}
}
} else {
if ( rStart <= end ) { // Start date not after range
if ( rStart >= start ) { // Start date within range
found = true;
} else if ( event->recurrence()->duration() == -1 ) { // Recurs forever
found = true;
} else if ( event->recurrence()->duration() == 0 ) { // End date set
QDate rEnd = event->recurrence()->endDate();
if ( rEnd >= start && rEnd <= end ) { // End date within range
found = true;
}
} else { // Duration set
// TODO: Calculate end date from duration. Should be done in Event
// For now include all events with a duration.
found = true;
}
}
}
if ( found ) eventList.append( event );
} else {
QDate s = event->dtStart().date();
QDate e = event->dtEnd().date();
if ( inclusive ) {
if ( s >= start && e <= end ) {
eventList.append( event );
}
} else {
if ( ( s >= start && s <= end ) || ( e >= start && e <= end ) ) {
eventList.append( event );
}
}
}
}
return eventList;
}
Event::List CalendarLocal::rawEventsForDate( const QDateTime &qdt )
{
return rawEventsForDate( qdt.date() );
}
Event::List CalendarLocal::rawEvents()
{
return mEventList;
}
bool CalendarLocal::addJournal(Journal *journal)
{
if (journal->dtStart().isValid())
kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
else
kdDebug(5800) << "Adding Journal without a DTSTART" << endl;
mJournalList.append(journal);
journal->registerObserver( this );
setModified( true );
return true;
}
void CalendarLocal::deleteJournal( Journal *journal )
{
if ( mJournalList.removeRef(journal) ) {
setModified( true );
}
}
void CalendarLocal::deleteAllJournals()
{
mJournalList.setAutoDelete( true );
mJournalList.clear();
mJournalList.setAutoDelete( false );
}
Journal *CalendarLocal::journal( const QDate &date )
{
// kdDebug(5800) << "CalendarLocal::journal() " << date.toString() << endl;
Journal::List::ConstIterator it;
for ( it = mJournalList.begin(); it != mJournalList.end(); ++it )
if ( (*it)->dtStart().date() == date )
return *it;
return 0;
}
Journal *CalendarLocal::journal( const QString &uid )
{
Journal::List::ConstIterator it;
for ( it = mJournalList.begin(); it != mJournalList.end(); ++it )
if ( (*it)->uid() == uid )
return *it;
return 0;
}
Journal::List CalendarLocal::journals()
{
return mJournalList;
}
<commit_msg>Fix appendRecurringAlarms(): 1) Alarms don't necessarily fall on the same date as the event. 2) Alarm time can vary for hourly/minutely recurrences. 3) Check the full specified time range.<commit_after>/*
This file is part of libkcal.
Copyright (c) 1998 Preston Brown
Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qdatetime.h>
#include <qstring.h>
#include <qptrlist.h>
#include <kdebug.h>
#include "vcaldrag.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "exceptions.h"
#include "incidence.h"
#include "journal.h"
#include "filestorage.h"
#include "calendarlocal.h"
using namespace KCal;
CalendarLocal::CalendarLocal()
: Calendar()
{
init();
}
CalendarLocal::CalendarLocal(const QString &timeZoneId)
: Calendar(timeZoneId)
{
init();
}
void CalendarLocal::init()
{
}
CalendarLocal::~CalendarLocal()
{
close();
}
bool CalendarLocal::load( const QString &fileName )
{
FileStorage storage( this, fileName );
return storage.load();
}
bool CalendarLocal::save( const QString &fileName, CalFormat *format )
{
FileStorage storage( this, fileName, format );
return storage.save();
}
void CalendarLocal::close()
{
deleteAllEvents();
deleteAllTodos();
deleteAllJournals();
setModified( false );
}
bool CalendarLocal::addEvent( Event *event )
{
insertEvent( event );
event->registerObserver( this );
setModified( true );
return true;
}
void CalendarLocal::deleteEvent( Event *event )
{
kdDebug(5800) << "CalendarLocal::deleteEvent" << endl;
if ( mEventList.removeRef( event ) ) {
setModified( true );
} else {
kdWarning() << "CalendarLocal::deleteEvent(): Event not found." << endl;
}
}
void CalendarLocal::deleteAllEvents()
{
// kdDebug(5800) << "CalendarLocal::deleteAllEvents" << endl;
mEventList.setAutoDelete( true );
mEventList.clear();
mEventList.setAutoDelete( false );
}
Event *CalendarLocal::event( const QString &uid )
{
kdDebug(5800) << "CalendarLocal::event(): " << uid << endl;
Event::List::ConstIterator it;
for ( it = mEventList.begin(); it != mEventList.end(); ++it ) {
if ( (*it)->uid() == uid ) {
return *it;
}
}
return 0;
}
bool CalendarLocal::addTodo( Todo *todo )
{
mTodoList.append( todo );
todo->registerObserver( this );
// Set up subtask relations
setupRelations( todo );
setModified( true );
return true;
}
void CalendarLocal::deleteTodo( Todo *todo )
{
// Handle orphaned children
removeRelations( todo );
if ( mTodoList.removeRef( todo ) ) {
setModified( true );
}
}
void CalendarLocal::deleteAllTodos()
{
// kdDebug(5800) << "CalendarLocal::deleteAllTodos()\n";
mTodoList.setAutoDelete( true );
mTodoList.clear();
mTodoList.setAutoDelete( false );
}
Todo::List CalendarLocal::rawTodos()
{
return mTodoList;
}
Todo *CalendarLocal::todo( const QString &uid )
{
Todo::List::ConstIterator it;
for ( it = mTodoList.begin(); it != mTodoList.end(); ++it ) {
if ( (*it)->uid() == uid ) return *it;
}
return 0;
}
Todo::List CalendarLocal::todos( const QDate &date )
{
Todo::List todos;
Todo::List::ConstIterator it;
for ( it = mTodoList.begin(); it != mTodoList.end(); ++it ) {
Todo *todo = *it;
if ( todo->hasDueDate() && todo->dtDue().date() == date ) {
todos.append( todo );
}
}
return todos;
}
Alarm::List CalendarLocal::alarmsTo( const QDateTime &to )
{
return alarms( QDateTime( QDate( 1900, 1, 1 ) ), to );
}
Alarm::List CalendarLocal::alarms( const QDateTime &from, const QDateTime &to )
{
// kdDebug(5800) << "CalendarLocal::alarms(" << from.toString() << " - "
// << to.toString() << ")" << endl;
Alarm::List alarms;
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *e = *it;
if ( e->doesRecur() ) appendRecurringAlarms( alarms, e, from, to );
else appendAlarms( alarms, e, from, to );
}
Todo::List::ConstIterator it2;
for( it2 = mTodoList.begin(); it2 != mTodoList.end(); ++it2 ) {
appendAlarms( alarms, *it2, from, to );
}
return alarms;
}
void CalendarLocal::appendAlarms( Alarm::List &alarms, Incidence *incidence,
const QDateTime &from, const QDateTime &to )
{
Alarm::List::ConstIterator it;
for( it = incidence->alarms().begin(); it != incidence->alarms().end();
++it ) {
// kdDebug(5800) << "CalendarLocal::appendAlarms() '" << alarm->text()
// << "': " << alarm->time().toString() << " - " << alarm->enabled() << endl;
if ( (*it)->enabled() ) {
if ( (*it)->time() >= from && (*it)->time() <= to ) {
kdDebug(5800) << "CalendarLocal::appendAlarms() '"
<< incidence->summary() << "': "
<< (*it)->time().toString() << endl;
alarms.append( *it );
}
}
}
}
void CalendarLocal::appendRecurringAlarms( Alarm::List &alarms,
Incidence *incidence,
const QDateTime &from,
const QDateTime &to )
{
Alarm::List::ConstIterator it;
QDateTime qdt;
int endOffset = 0;
bool endOffsetValid = false;
for( it = incidence->alarms().begin(); it != incidence->alarms().end();
++it ) {
Alarm *alarm = *it;
if ( alarm->hasTime() ) {
// The alarm time is defined as an absolute date/time
qdt = alarm->time();
} else {
// The alarm time is defined by an offset from the event start or end time.
// Find the offset from the event start time, which is also used as the
// offset from the recurrence time.
int offset = 0;
if ( alarm->hasStartOffset() ) {
offset = alarm->startOffset().asSeconds();
} else if ( alarm->hasEndOffset() ) {
if ( !endOffsetValid ) {
endOffset = incidence->dtStart().secsTo( incidence->dtEnd() );
endOffsetValid = true;
}
offset = alarm->endOffset().asSeconds() + endOffset;
}
// Adjust the 'from' date/time and find the next recurrence at or after it
qdt = incidence->recurrence()->getNextDateTime( from.addSecs(-offset - 1) );
if (!qdt.isValid())
continue;
// Remove the adjustment to get the alarm time
qdt = qdt.addSecs( offset );
}
kdDebug(5800) << "CalendarLocal::appendAlarms() '" << incidence->summary()
<< "': " << qdt.toString() << " - " << (*it)->enabled()
<< endl;
if ( (*it)->enabled() ) {
// kdDebug(5800) << "CalendarLocal::appendAlarms() '" << incidence->summary()
// << "': " << (*it)->time().toString() << endl;
if ( qdt >= from && qdt <= to ) {
alarms.append( *it );
}
}
}
}
// after changes are made to an event, this should be called.
void CalendarLocal::update( IncidenceBase *incidence )
{
incidence->setSyncStatus( Event::SYNCMOD );
incidence->setLastModified( QDateTime::currentDateTime() );
// we should probably update the revision number here,
// or internally in the Event itself when certain things change.
// need to verify with ical documentation.
setModified( true );
}
void CalendarLocal::insertEvent( Event *event )
{
if ( mEventList.find( event ) == mEventList.end() ) {
mEventList.append( event );
}
}
Event::List CalendarLocal::rawEventsForDate( const QDate &qd, bool sorted )
{
Event::List eventList;
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *event = *it;
if ( event->doesRecur() ) {
if ( event->isMultiDay() ) {
int extraDays = event->dtStart().date().daysTo( event->dtEnd().date() );
int i;
for ( i = 0; i <= extraDays; i++ ) {
if ( event->recursOn( qd.addDays( -i ) ) ) {
eventList.append( event );
break;
}
}
} else {
if ( event->recursOn( qd ) )
eventList.append( event );
}
} else {
if ( event->dtStart().date() <= qd && event->dtEnd().date() >= qd ) {
eventList.append( event );
}
}
}
if ( !sorted ) {
return eventList;
}
// kdDebug(5800) << "Sorting events for date\n" << endl;
// now, we have to sort it based on dtStart.time()
Event::List eventListSorted;
Event::List::Iterator sortIt;
for ( it = eventList.begin(); it != eventList.end(); ++it ) {
sortIt = eventListSorted.begin();
while ( sortIt != eventListSorted.end() &&
(*it)->dtStart().time() >= (*sortIt)->dtStart().time() ) {
++sortIt;
}
eventListSorted.insert( sortIt, *it );
}
return eventListSorted;
}
Event::List CalendarLocal::rawEvents( const QDate &start, const QDate &end,
bool inclusive )
{
Event::List eventList;
// Get non-recurring events
Event::List::ConstIterator it;
for( it = mEventList.begin(); it != mEventList.end(); ++it ) {
Event *event = *it;
if ( event->doesRecur() ) {
QDate rStart = event->dtStart().date();
bool found = false;
if ( inclusive ) {
if ( rStart >= start && rStart <= end ) {
// Start date of event is in range. Now check for end date.
// if duration is negative, event recurs forever, so do not include it.
if ( event->recurrence()->duration() == 0 ) { // End date set
QDate rEnd = event->recurrence()->endDate();
if ( rEnd >= start && rEnd <= end ) { // End date within range
found = true;
}
} else if ( event->recurrence()->duration() > 0 ) { // Duration set
// TODO: Calculate end date from duration. Should be done in Event
// For now exclude all events with a duration.
}
}
} else {
if ( rStart <= end ) { // Start date not after range
if ( rStart >= start ) { // Start date within range
found = true;
} else if ( event->recurrence()->duration() == -1 ) { // Recurs forever
found = true;
} else if ( event->recurrence()->duration() == 0 ) { // End date set
QDate rEnd = event->recurrence()->endDate();
if ( rEnd >= start && rEnd <= end ) { // End date within range
found = true;
}
} else { // Duration set
// TODO: Calculate end date from duration. Should be done in Event
// For now include all events with a duration.
found = true;
}
}
}
if ( found ) eventList.append( event );
} else {
QDate s = event->dtStart().date();
QDate e = event->dtEnd().date();
if ( inclusive ) {
if ( s >= start && e <= end ) {
eventList.append( event );
}
} else {
if ( ( s >= start && s <= end ) || ( e >= start && e <= end ) ) {
eventList.append( event );
}
}
}
}
return eventList;
}
Event::List CalendarLocal::rawEventsForDate( const QDateTime &qdt )
{
return rawEventsForDate( qdt.date() );
}
Event::List CalendarLocal::rawEvents()
{
return mEventList;
}
bool CalendarLocal::addJournal(Journal *journal)
{
if (journal->dtStart().isValid())
kdDebug(5800) << "Adding Journal on " << journal->dtStart().toString() << endl;
else
kdDebug(5800) << "Adding Journal without a DTSTART" << endl;
mJournalList.append(journal);
journal->registerObserver( this );
setModified( true );
return true;
}
void CalendarLocal::deleteJournal( Journal *journal )
{
if ( mJournalList.removeRef(journal) ) {
setModified( true );
}
}
void CalendarLocal::deleteAllJournals()
{
mJournalList.setAutoDelete( true );
mJournalList.clear();
mJournalList.setAutoDelete( false );
}
Journal *CalendarLocal::journal( const QDate &date )
{
// kdDebug(5800) << "CalendarLocal::journal() " << date.toString() << endl;
Journal::List::ConstIterator it;
for ( it = mJournalList.begin(); it != mJournalList.end(); ++it )
if ( (*it)->dtStart().date() == date )
return *it;
return 0;
}
Journal *CalendarLocal::journal( const QString &uid )
{
Journal::List::ConstIterator it;
for ( it = mJournalList.begin(); it != mJournalList.end(); ++it )
if ( (*it)->uid() == uid )
return *it;
return 0;
}
Journal::List CalendarLocal::journals()
{
return mJournalList;
}
<|endoftext|>
|
<commit_before>#include "less/TokenList.h"
TokenList::~TokenList() {
}
void TokenList::ltrim() {
while (!empty() && front().type == Token::WHITESPACE) {
pop_front();
}
}
void TokenList::rtrim() {
while (!empty() && back().type == Token::WHITESPACE) {
pop_back();
}
}
void TokenList::trim() {
ltrim();
rtrim();
}
std::string TokenList::toString() const {
std::string str;
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
str.append(*it);
}
return str;
}
bool TokenList::contains(const Token &t) const {
return (find(t, begin()) != end());
}
bool TokenList::contains(Token::Type type, const std::string &str) const {
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
if ((*it).type == type && *it == str)
return true;
}
return false;
}
bool TokenList::containsType(Token::Type type) const {
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
if ((*it).type == type)
return true;
}
return false;
}
TokenList::const_iterator TokenList::find(const Token &search,
TokenList::const_iterator offset) const {
for (; offset != end(); offset++) {
if (*offset == search)
return offset;
}
return end();
}
TokenList::const_iterator TokenList::find(const TokenList &search,
TokenList::const_iterator &offset) const {
TokenList::const_iterator it, it2;
while ((it = find(search.front(), offset)) != end()) {
for (it2 = search.begin();
it != end() && it2 != search.end() && *it == *it2;
it++, it2++) {
}
if (it2 == search.end())
return it;
else
offset++;
}
return begin();
}
<commit_msg>Fix find() function, to locate the start of match.<commit_after>#include "less/TokenList.h"
TokenList::~TokenList() {
}
void TokenList::ltrim() {
while (!empty() && front().type == Token::WHITESPACE) {
pop_front();
}
}
void TokenList::rtrim() {
while (!empty() && back().type == Token::WHITESPACE) {
pop_back();
}
}
void TokenList::trim() {
ltrim();
rtrim();
}
std::string TokenList::toString() const {
std::string str;
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
str.append(*it);
}
return str;
}
bool TokenList::contains(const Token &t) const {
return (find(t, begin()) != end());
}
bool TokenList::contains(Token::Type type, const std::string &str) const {
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
if ((*it).type == type && *it == str)
return true;
}
return false;
}
bool TokenList::containsType(Token::Type type) const {
std::list<Token>::const_iterator it;
for (it = begin(); it != end(); it++) {
if ((*it).type == type)
return true;
}
return false;
}
TokenList::const_iterator TokenList::find(const Token &search,
TokenList::const_iterator offset) const {
for (; offset != end(); offset++) {
if (*offset == search)
return offset;
}
return end();
}
TokenList::const_iterator TokenList::find(const TokenList &search,
TokenList::const_iterator &offset) const {
TokenList::const_iterator it, it2;
while ((it = find(search.front(), offset)) != end()) {
offset = it;
for (it2 = search.begin();
it != end() && it2 != search.end() && *it == *it2;
it++, it2++) {
}
if (it2 == search.end())
return it;
else
offset++;
}
return begin();
}
<|endoftext|>
|
<commit_before>
#include "pmx_draw.h"
void mmdpiPmxDraw::draw( void )
{
//for( uint level = 0; level < mmdpiPmxLoad::bone_level_range; level ++ )
//{
// for( uint i = 0; i < mmdpiModel::bone_num; i ++ )
// {
// MMDPI_PMX_BONE_INFO_PTR bonep = &mmdpiPmxLoad::bone[ i ];
// MMDPI_BONE_INFO_PTR bone = &mmdpiBone::bone[ i ];
// if( bonep->level == level )
// {
// // ik
// ik_execute( mmdpiBone::bone, mmdpiPmxLoad::bone, i );
// // 付与
// grant_bone( mmdpiBone::bone, mmdpiPmxLoad::bone, i, bonep->grant_parent_index );
// }
// }
//}
//for( uint level = 0; level < mmdpiPmxLoad::bone_level_range; level ++ )
//{
// for( uint i = 0; i < mmdpiModel::bone_num; i ++ )
// {
// MMDPI_PMX_BONE_INFO_PTR bonep = &mmdpiPmxLoad::bone[ i ];
// MMDPI_BONE_INFO_PTR bone = &mmdpiBone::bone[ i ];
// if( bonep->level == level )
// {
// // ik
// ik_execute( mmdpiBone::bone, mmdpiPmxLoad::bone, i );
// // matrix
// bone->matrix = make_global_matrix( i );
// }
// }
//}
// 物理演算
if( bullet_flag )
this->advance_time_physical( mmdpiModel::get_fps() );
mmdpiModel::draw();
}
// 付与親ボーン処理
int mmdpiPmxDraw::grant_bone( MMDPI_BONE_INFO_PTR bone, MMDPI_PMX_BONE_INFO_PTR pbone, int bone_index, int grant_bone_index )
{
MMDPI_BONE_INFO_PTR grant_bone; // 追従のお手本とするボーン
MMDPI_BONE_INFO_PTR target_bone; // 追従を行うボーン
float rate;
if( !( pbone[ bone_index ].rotation_grant_flag || pbone[ bone_index ].translate_grant_flag ) )
return 0;
target_bone = &bone[ bone_index ];
grant_bone = &bone[ grant_bone_index ];
rate = pbone[ bone_index ].grant_parent_rate;
if( pbone[ bone_index ].rotation_grant_flag )
{
// grant_bone が後の方で出てくるのはMMDでは更新外
if( grant_bone_index < bone_index )
{
mmdpiMatrix rotation1_matrix;
mmdpiVector3d rotate1;
float rate1 = rate;
grant_bone->bone_mat.get_rotation( &rotate1.x, &rotate1.y, &rotate1.z );
rotation1_matrix.rotation( rotate1.x * rate1, rotate1.y * rate1, rotate1.z * rate1 );
target_bone->bone_mat = rotation1_matrix * target_bone->bone_mat;
//mmdpiVector3d rotate2;
//mmdpiMatrix rotation2_matrix;
//float rate2 = rate;
//target_bone->bone_mat.get_rotation( &rotate2.x, &rotate2.y, &rotate2.z );
//rotation2_matrix.rotation( rotate2.x * rate2, rotate2.y * rate2, rotate2.z * rate2 );
//grant_bone->bone_mat = rotation2_matrix * grant_bone->bone_mat;
}
}
if( pbone[ bone_index ].translate_grant_flag )
{
mmdpiVector3d position = grant_bone->bone_mat.get_transform();
position = position * rate;
target_bone->bone_mat.transelation( position.x, position.y, position.z );
}
return 0;
}
int mmdpiPmxDraw::morph_exec( dword index, float rate )
{
MMDPI_PMX_MORPH_INFO_PTR m = &morph[ index ];
if( m->morph_flag == 1 )
{
m->morph_step = rate;
m->morph_flag = 2;
}
if( m->morph_flag )
m->morph_step += -0.02f;
if( m->morph_step < 0.0f )
{
m->morph_step = 0;
m->morph_flag = 0;
morph_exec( index, 0.0f );
//skin_update( m->vertex->vertex_id );
}
switch( m->type )
{
case 0: // グループ
for( uint i = 0; i < m->offset_num; i ++ )
{
morph[ m->group[ i ].group_id ].morph_flag = 1;
morph_exec( m->group[ i ].group_id, m->group[ i ].morph_rate );
}
break;
case 1: // 頂点
for( uint i = 0; i < m->offset_num; i ++ )
{
//for( int j = 0; j < 3; j ++ )
// mmdpiShader::a_vertex_p->skinv[ m->vertex[ i ].vertex_id ][ j ] = m->morph_step * m->vertex[ i ].vertex[ j ];
//skin_update( m->vertex[ i ].vertex_id, 0 );
}
break;
case 2: // ボーン
for( uint i = 0; i < m->offset_num; i ++ )
{
mmdpiMatrix trans_matrix, rotate_matrix;
rotate_matrix.rotation( 1, 0, 0, m->morph_step * m->bone[ i ].rotation[ 0 ] );
rotate_matrix.rotation( 0, 1, 0, m->morph_step * m->bone[ i ].rotation[ 1 ] );
rotate_matrix.rotation( 0, 0, 1, m->morph_step * m->bone[ i ].rotation[ 2 ] );
trans_matrix
.transelation(
m->morph_step * m->bone[ i ].translate[ 0 ],
m->morph_step * m->bone[ i ].translate[ 1 ],
m->morph_step * m->bone[ i ].translate[ 2 ]
);
mmdpiBone::bone[ m->bone->bone_id ].matrix
= rotate_matrix * trans_matrix * mmdpiBone::bone[ m->bone->bone_id ].matrix;
}
break;
case 3: // UV
case 4: // 追加UV
case 5:
case 6:
case 7:
case 8: // 材質
break;
}
return 0;
}
mmdpiPmxDraw::mmdpiPmxDraw()
{
}
mmdpiPmxDraw::~mmdpiPmxDraw()
{
}
<commit_msg>upload debug files.<commit_after>
#include "pmx_draw.h"
void mmdpiPmxDraw::draw( void )
{
for( uint level = 0; level < mmdpiPmxLoad::bone_level_range; level ++ )
{
for( uint i = 0; i < mmdpiModel::bone_num; i ++ )
{
MMDPI_PMX_BONE_INFO_PTR bonep = &mmdpiPmxLoad::bone[ i ];
MMDPI_BONE_INFO_PTR bone = &mmdpiBone::bone[ i ];
if( bonep->level == level )
{
// ik
ik_execute( mmdpiBone::bone, mmdpiPmxLoad::bone, i );
// 付与
grant_bone( mmdpiBone::bone, mmdpiPmxLoad::bone, i, bonep->grant_parent_index );
}
}
}
for( uint level = 0; level < mmdpiPmxLoad::bone_level_range; level ++ )
{
for( uint i = 0; i < mmdpiModel::bone_num; i ++ )
{
MMDPI_PMX_BONE_INFO_PTR bonep = &mmdpiPmxLoad::bone[ i ];
MMDPI_BONE_INFO_PTR bone = &mmdpiBone::bone[ i ];
if( bonep->level == level )
{
// ik
ik_execute( mmdpiBone::bone, mmdpiPmxLoad::bone, i );
// matrix
bone->matrix = make_global_matrix( i );
}
}
}
// 物理演算
if( bullet_flag )
this->advance_time_physical( mmdpiModel::get_fps() );
mmdpiModel::draw();
}
// 付与親ボーン処理
int mmdpiPmxDraw::grant_bone( MMDPI_BONE_INFO_PTR bone, MMDPI_PMX_BONE_INFO_PTR pbone, int bone_index, int grant_bone_index )
{
MMDPI_BONE_INFO_PTR grant_bone; // 追従のお手本とするボーン
MMDPI_BONE_INFO_PTR target_bone; // 追従を行うボーン
float rate;
if( !( pbone[ bone_index ].rotation_grant_flag || pbone[ bone_index ].translate_grant_flag ) )
return 0;
target_bone = &bone[ bone_index ];
grant_bone = &bone[ grant_bone_index ];
rate = pbone[ bone_index ].grant_parent_rate;
if( pbone[ bone_index ].rotation_grant_flag )
{
// grant_bone が後の方で出てくるのはMMDでは更新外
if( grant_bone_index < bone_index )
{
mmdpiMatrix rotation1_matrix;
mmdpiVector3d rotate1;
float rate1 = rate;
grant_bone->bone_mat.get_rotation( &rotate1.x, &rotate1.y, &rotate1.z );
rotation1_matrix.rotation( rotate1.x * rate1, rotate1.y * rate1, rotate1.z * rate1 );
target_bone->bone_mat = rotation1_matrix * target_bone->bone_mat;
//mmdpiVector3d rotate2;
//mmdpiMatrix rotation2_matrix;
//float rate2 = rate;
//target_bone->bone_mat.get_rotation( &rotate2.x, &rotate2.y, &rotate2.z );
//rotation2_matrix.rotation( rotate2.x * rate2, rotate2.y * rate2, rotate2.z * rate2 );
//grant_bone->bone_mat = rotation2_matrix * grant_bone->bone_mat;
}
}
if( pbone[ bone_index ].translate_grant_flag )
{
mmdpiVector3d position = grant_bone->bone_mat.get_transform();
position = position * rate;
target_bone->bone_mat.transelation( position.x, position.y, position.z );
}
return 0;
}
int mmdpiPmxDraw::morph_exec( dword index, float rate )
{
MMDPI_PMX_MORPH_INFO_PTR m = &morph[ index ];
if( m->morph_flag == 1 )
{
m->morph_step = rate;
m->morph_flag = 2;
}
if( m->morph_flag )
m->morph_step += -0.02f;
if( m->morph_step < 0.0f )
{
m->morph_step = 0;
m->morph_flag = 0;
morph_exec( index, 0.0f );
//skin_update( m->vertex->vertex_id );
}
switch( m->type )
{
case 0: // グループ
for( uint i = 0; i < m->offset_num; i ++ )
{
morph[ m->group[ i ].group_id ].morph_flag = 1;
morph_exec( m->group[ i ].group_id, m->group[ i ].morph_rate );
}
break;
case 1: // 頂点
for( uint i = 0; i < m->offset_num; i ++ )
{
//for( int j = 0; j < 3; j ++ )
// mmdpiShader::a_vertex_p->skinv[ m->vertex[ i ].vertex_id ][ j ] = m->morph_step * m->vertex[ i ].vertex[ j ];
//skin_update( m->vertex[ i ].vertex_id, 0 );
}
break;
case 2: // ボーン
for( uint i = 0; i < m->offset_num; i ++ )
{
mmdpiMatrix trans_matrix, rotate_matrix;
rotate_matrix.rotation( 1, 0, 0, m->morph_step * m->bone[ i ].rotation[ 0 ] );
rotate_matrix.rotation( 0, 1, 0, m->morph_step * m->bone[ i ].rotation[ 1 ] );
rotate_matrix.rotation( 0, 0, 1, m->morph_step * m->bone[ i ].rotation[ 2 ] );
trans_matrix
.transelation(
m->morph_step * m->bone[ i ].translate[ 0 ],
m->morph_step * m->bone[ i ].translate[ 1 ],
m->morph_step * m->bone[ i ].translate[ 2 ]
);
mmdpiBone::bone[ m->bone->bone_id ].matrix
= rotate_matrix * trans_matrix * mmdpiBone::bone[ m->bone->bone_id ].matrix;
}
break;
case 3: // UV
case 4: // 追加UV
case 5:
case 6:
case 7:
case 8: // 材質
break;
}
return 0;
}
mmdpiPmxDraw::mmdpiPmxDraw()
{
}
mmdpiPmxDraw::~mmdpiPmxDraw()
{
}
<|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) 2015 Cloudius Systems, Ltd.
*/
#pragma once
/// \file
// File <-> streams adapters
//
// Seastar files are block-based due to the reliance on DMA - you must read
// on sector boundaries. The adapters in this file provide a byte stream
// interface to files, while retaining the zero-copy characteristics of
// seastar files.
#include "file.hh"
#include "iostream.hh"
#include "shared_ptr.hh"
namespace seastar {
class file_input_stream_history {
static constexpr uint64_t window_size = 4 * 1024 * 1024;
struct window {
uint64_t total_read = 0;
uint64_t unused_read = 0;
};
window current_window;
window previous_window;
unsigned read_ahead = 1;
friend class file_data_source_impl;
};
/// Data structure describing options for opening a file input stream
struct file_input_stream_options {
size_t buffer_size = 8192; ///< I/O buffer size
unsigned read_ahead = 0; ///< Maximum number of extra read-ahead operations
::seastar::io_priority_class io_priority_class = default_priority_class();
lw_shared_ptr<file_input_stream_history> dynamic_adjustments = { }; ///< Input stream history, if null dynamic adjustments are disabled
};
/// \brief Creates an input_stream to read a portion of a file.
///
/// \param file File to read; multiple streams for the same file may coexist
/// \param offset Starting offset to read from (no alignment restrictions)
/// \param len Maximum number of bytes to read; the stream will stop at end-of-file
/// even if `offset + len` is beyond end-of-file.
/// \param options A set of options controlling the stream.
///
/// \note Multiple input streams may exist concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, uint64_t offset, uint64_t len, file_input_stream_options options = {});
// Create an input_stream for a given file, with the specified options.
// Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, uint64_t offset, file_input_stream_options = {});
// Create an input_stream for reading starting at a given position of the
// given file. Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, file_input_stream_options = {});
struct file_output_stream_options {
unsigned buffer_size = 8192;
unsigned preallocation_size = 1024*1024; // 1MB
unsigned write_behind = 1; ///< Number of buffers to write in parallel
::seastar::io_priority_class io_priority_class = default_priority_class();
};
// Create an output_stream for writing starting at the position zero of a
// newly created file.
// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
file file,
uint64_t buffer_size = 8192);
/// Create an output_stream for writing starting at the position zero of a
/// newly created file.
/// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
file file,
file_output_stream_options options);
}
<commit_msg>fstream: remove default extent allocation hint<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) 2015 Cloudius Systems, Ltd.
*/
#pragma once
/// \file
// File <-> streams adapters
//
// Seastar files are block-based due to the reliance on DMA - you must read
// on sector boundaries. The adapters in this file provide a byte stream
// interface to files, while retaining the zero-copy characteristics of
// seastar files.
#include "file.hh"
#include "iostream.hh"
#include "shared_ptr.hh"
namespace seastar {
class file_input_stream_history {
static constexpr uint64_t window_size = 4 * 1024 * 1024;
struct window {
uint64_t total_read = 0;
uint64_t unused_read = 0;
};
window current_window;
window previous_window;
unsigned read_ahead = 1;
friend class file_data_source_impl;
};
/// Data structure describing options for opening a file input stream
struct file_input_stream_options {
size_t buffer_size = 8192; ///< I/O buffer size
unsigned read_ahead = 0; ///< Maximum number of extra read-ahead operations
::seastar::io_priority_class io_priority_class = default_priority_class();
lw_shared_ptr<file_input_stream_history> dynamic_adjustments = { }; ///< Input stream history, if null dynamic adjustments are disabled
};
/// \brief Creates an input_stream to read a portion of a file.
///
/// \param file File to read; multiple streams for the same file may coexist
/// \param offset Starting offset to read from (no alignment restrictions)
/// \param len Maximum number of bytes to read; the stream will stop at end-of-file
/// even if `offset + len` is beyond end-of-file.
/// \param options A set of options controlling the stream.
///
/// \note Multiple input streams may exist concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, uint64_t offset, uint64_t len, file_input_stream_options options = {});
// Create an input_stream for a given file, with the specified options.
// Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, uint64_t offset, file_input_stream_options = {});
// Create an input_stream for reading starting at a given position of the
// given file. Multiple fibers of execution (continuations) may safely open
// multiple input streams concurrently for the same file.
input_stream<char> make_file_input_stream(
file file, file_input_stream_options = {});
struct file_output_stream_options {
// For small files, setting preallocation_size can make it impossible for XFS to find
// an aligned extent. On the other hand, without it, XFS will divide the file into
// file_size/buffer_size extents. To avoid fragmentation, we set the default buffer_size
// to 64k (so each extent will be a minimum of 64k) and preallocation_size to 0 (to avoid
// extent allocation problems).
//
// Large files should increase both buffer_size and preallocation_size.
unsigned buffer_size = 65536;
unsigned preallocation_size = 0; ///< Preallocate extents. For large files, set to a large number (a few megabytes) to reduce fragmentation
unsigned write_behind = 1; ///< Number of buffers to write in parallel
::seastar::io_priority_class io_priority_class = default_priority_class();
};
// Create an output_stream for writing starting at the position zero of a
// newly created file.
// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
file file,
uint64_t buffer_size = 8192);
/// Create an output_stream for writing starting at the position zero of a
/// newly created file.
/// NOTE: flush() should be the last thing to be called on a file output stream.
output_stream<char> make_file_output_stream(
file file,
file_output_stream_options options);
}
<|endoftext|>
|
<commit_before>/*
Dynamics/Kinematics modeling and simulation library.
Copyright (C) 1999 by Michael Alexander Ewert
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "csphyzik/phyzent.h"
#include "csphyzik/contact.h"
#include "csphyzik/refframe.h"
#include "csphyzik/mathutil.h"
#include "csphyzik/solver.h"
#include "csphyzik/debug.h"
ctPhysicalEntity::ctPhysicalEntity() : RF( ctReferenceFrame::universe() )
{
RF.add_ref( RF );
solver = NULL;
// use_ODE = true; //!me does this get called by subclasses??
}
ctPhysicalEntity::ctPhysicalEntity( ctReferenceFrame &ref ) : RF( ref )
{
RF.add_ref( RF );
solver = NULL;
// use_ODE = true;
}
ctPhysicalEntity::~ctPhysicalEntity()
{
RF.remove_ref( RF );
if( solver )
delete solver;
}
// pass control to solver
void ctPhysicalEntity::solve( real t )
{
if( solver ){
solver->solve( t );
}
}
void ctPhysicalEntity::apply_given_F( ctForce &frc )
{
// notin
}
void ctPhysicalEntity::rotate_around_line( ctVector3 &paxis, real ptheta )
{
ctMatrix3 new_T;
R_from_vector_and_angle( paxis, -ptheta, new_T );
// RF.set_T(new_T*RF.get_T()); //!me is this right?
RF.set_R(new_T*RF.get_R()); //!me is this right?
}
// add this bodies state to the state vector buffer passed in.
// increment state buffer to point after added state. upload
int ctPhysicalEntity::set_state( real *state_array )
{
ctVector3 o;
ctMatrix3 M;
o = RF.get_offset();
M = RF.get_R();
*state_array++ = o[0];
*state_array++ = o[1];
*state_array++ = o[2];
*state_array++ = M[0][0];
*state_array++ = M[0][1];
*state_array++ = M[0][2];
*state_array++ = M[1][0];
*state_array++ = M[1][1];
*state_array++ = M[1][2];
*state_array++ = M[2][0];
*state_array++ = M[2][1];
*state_array++ = M[2][2];
return ctPhysicalEntity::get_state_size();
}
// add change in state vector over time to state buffer parameter.
int ctPhysicalEntity::set_delta_state( real *state_array )
{
ctMatrix3 M;
M = RF.get_R();
// dx/dt = v change in position over time is velocity
*state_array++ = v[0];
*state_array++ = v[1];
*state_array++ = v[2];
// dR/dt = ~w*R ~w is cross product matrix thing. R is rotation matrix
// ~w = [ 0 -w.z w.y ] pre-mult of ~w with R has the
// [ w.z 0 -w.x ] same effect as x-prod of w with
// [ -w.y w.x 0 ] each row of R
*state_array++ = -w[2]*M[1][0] + w[1]*M[2][0];
*state_array++ = -w[2]*M[1][1] + w[1]*M[2][1];
*state_array++ = -w[2]*M[1][2] + w[1]*M[2][2];
*state_array++ = w[2]*M[0][0] - w[0]*M[2][0];
*state_array++ = w[2]*M[0][1] - w[0]*M[2][1];
*state_array++ = w[2]*M[0][2] - w[0]*M[2][2];
*state_array++ = -w[1]*M[0][0] + w[0]*M[1][0];
*state_array++ = -w[1]*M[0][1] + w[0]*M[1][1];
*state_array++ = -w[1]*M[0][2] + w[0]*M[1][2];
return ctPhysicalEntity::get_state_size();
}
// download state from buffer into this entity
int ctPhysicalEntity::get_state( const real *state_array )
{
ctVector3 o;
ctMatrix3 M;
o[0] = *state_array++;
o[1] = *state_array++;
o[2] = *state_array++;
M[0][0] = *state_array++;
M[0][1] = *state_array++;
M[0][2] = *state_array++;
M[1][0] = *state_array++;
M[1][1] = *state_array++;
M[1][2] = *state_array++;
M[2][0] = *state_array++;
M[2][1] = *state_array++;
M[2][2] = *state_array++;
//!me probably don't need to do it every frame
M.orthonormalize();
RF.set_offset( o );
RF.set_R( M );
return ctPhysicalEntity::get_state_size();
}
void ctPhysicalEntity::set_v( const ctVector3 &pv )
{
v = pv;
}
void ctPhysicalEntity::set_angular_v( const ctVector3 &pw )
{
w = pw;
}
// PONG collision model
// basic collision model for for objects with no mass.
void ctPhysicalEntity::resolve_collision( ctCollidingContact &cont )
{
ctVector3 j;
// this is the dumbest collision model, so the other body may have
// something better, so resolve collision from that bodies "perspective"
if( this == cont.body_a && cont.body_b != NULL ){
cont.body_b->resolve_collision( cont );
}
if( cont.body_a != NULL ){
j = ( cont.n*((cont.body_a->get_v())*cont.n) )*( -1.0 - cont.restitution );
cont.body_a->apply_impulse( cont.contact_p, j );
}
if( cont.body_b != NULL ){
j = ( cont.n*((cont.body_b->get_v())*cont.n) )*( -1.0 - cont.restitution );
cont.body_b->apply_impulse( cont.contact_p, j );
}
}
void ctPhysicalEntity::apply_impulse( ctVector3 jx, ctVector3 jv )
{
set_v( v + jv );
}
//************ ctDynamicEntity
ctDynamicEntity::ctDynamicEntity()
{
m = 10;
solver = new ctSimpleDynamicsSolver( *this );
}
ctDynamicEntity::ctDynamicEntity( ctReferenceFrame &ref ) : ctPhysicalEntity( ref )
{
m = 10;
solver = new ctSimpleDynamicsSolver( *this );
}
ctDynamicEntity::~ctDynamicEntity()
{
}
void ctDynamicEntity::apply_given_F( ctForce &frc )
{
frc.apply_F( *this );
}
void ctDynamicEntity::set_m( real pm ){ m = pm; }
<commit_msg>modified collision response<commit_after>/*
Dynamics/Kinematics modeling and simulation library.
Copyright (C) 1999 by Michael Alexander Ewert
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "csphyzik/phyzent.h"
#include "csphyzik/contact.h"
#include "csphyzik/refframe.h"
#include "csphyzik/mathutil.h"
#include "csphyzik/solver.h"
#include "csphyzik/debug.h"
ctPhysicalEntity::ctPhysicalEntity() : RF( ctReferenceFrame::universe() )
{
RF.add_ref( RF );
solver = NULL;
flags = 0;
// use_ODE = true; //!me does this get called by subclasses??
}
ctPhysicalEntity::ctPhysicalEntity( ctReferenceFrame &ref ) : RF( ref )
{
RF.add_ref( RF );
solver = NULL;
flags = 0;
// use_ODE = true;
}
ctPhysicalEntity::~ctPhysicalEntity()
{
RF.remove_ref( RF );
if( solver )
delete solver;
}
// pass control to solver
void ctPhysicalEntity::solve( real t )
{
if( solver ){
solver->solve( t );
}
}
void ctPhysicalEntity::apply_given_F( ctForce &frc )
{
// notin
}
//!me make sure it's the right direction.. should be counter-clockwise in RHS
void ctPhysicalEntity::rotate_around_line( ctVector3 &paxis, real ptheta )
{
ctMatrix3 new_T;
R_from_vector_and_angle( paxis, -ptheta, new_T );
// RF.set_T(new_T*RF.get_T()); //!me is this right?
RF.set_R(new_T*RF.get_R()); //!me is this right?
}
// add this bodies state to the state vector buffer passed in.
// increment state buffer to point after added state. upload
int ctPhysicalEntity::set_state( real *state_array )
{
ctVector3 o;
ctMatrix3 M;
o = RF.get_offset();
M = RF.get_R();
*state_array++ = o[0];
*state_array++ = o[1];
*state_array++ = o[2];
*state_array++ = M[0][0];
*state_array++ = M[0][1];
*state_array++ = M[0][2];
*state_array++ = M[1][0];
*state_array++ = M[1][1];
*state_array++ = M[1][2];
*state_array++ = M[2][0];
*state_array++ = M[2][1];
*state_array++ = M[2][2];
return ctPhysicalEntity::get_state_size();
}
// add change in state vector over time to state buffer parameter.
int ctPhysicalEntity::set_delta_state( real *state_array )
{
ctMatrix3 M;
M = RF.get_R();
// dx/dt = v change in position over time is velocity
*state_array++ = v[0];
*state_array++ = v[1];
*state_array++ = v[2];
// dR/dt = ~w*R ~w is cross product matrix thing. R is rotation matrix
// ~w = [ 0 -w.z w.y ] pre-mult of ~w with R has the
// [ w.z 0 -w.x ] same effect as x-prod of w with
// [ -w.y w.x 0 ] each row of R
*state_array++ = -w[2]*M[1][0] + w[1]*M[2][0];
*state_array++ = -w[2]*M[1][1] + w[1]*M[2][1];
*state_array++ = -w[2]*M[1][2] + w[1]*M[2][2];
*state_array++ = w[2]*M[0][0] - w[0]*M[2][0];
*state_array++ = w[2]*M[0][1] - w[0]*M[2][1];
*state_array++ = w[2]*M[0][2] - w[0]*M[2][2];
*state_array++ = -w[1]*M[0][0] + w[0]*M[1][0];
*state_array++ = -w[1]*M[0][1] + w[0]*M[1][1];
*state_array++ = -w[1]*M[0][2] + w[0]*M[1][2];
return ctPhysicalEntity::get_state_size();
}
// download state from buffer into this entity
int ctPhysicalEntity::get_state( const real *state_array )
{
ctVector3 o;
ctMatrix3 M;
o[0] = *state_array++;
o[1] = *state_array++;
o[2] = *state_array++;
M[0][0] = *state_array++;
M[0][1] = *state_array++;
M[0][2] = *state_array++;
M[1][0] = *state_array++;
M[1][1] = *state_array++;
M[1][2] = *state_array++;
M[2][0] = *state_array++;
M[2][1] = *state_array++;
M[2][2] = *state_array++;
//!me probably don't need to do it every frame
M.orthonormalize();
RF.set_offset( o );
RF.set_R( M );
return ctPhysicalEntity::get_state_size();
}
void ctPhysicalEntity::set_v( const ctVector3 &pv )
{
v = pv;
}
void ctPhysicalEntity::set_angular_v( const ctVector3 &pw )
{
w = pw;
}
// PONG collision model
// basic collision model for for objects with no mass.
void ctPhysicalEntity::resolve_collision( ctCollidingContact *cont )
{
ctVector3 j;
if( cont == NULL )
return;
j = ( cont->n*((get_v())*cont->n) )*( -1.0 - cont->restitution );
apply_impulse( cont->contact_p, j );
if( cont->body_b != NULL ){
j = ( cont->n*((cont->body_b->get_v())*cont->n) )*( -1.0 - cont->restitution );
cont->body_b->apply_impulse( cont->contact_p, j );
}
}
void ctPhysicalEntity::apply_impulse( ctVector3 jx, ctVector3 jv )
{
set_v( v + jv );
}
//************ ctDynamicEntity
ctDynamicEntity::ctDynamicEntity()
{
m = 10;
solver = new ctSimpleDynamicsSolver( *this );
}
ctDynamicEntity::ctDynamicEntity( ctReferenceFrame &ref ) : ctPhysicalEntity( ref )
{
m = 10;
solver = new ctSimpleDynamicsSolver( *this );
}
ctDynamicEntity::~ctDynamicEntity()
{
}
void ctDynamicEntity::apply_given_F( ctForce &frc )
{
frc.apply_F( *this );
}
void ctDynamicEntity::set_m( real pm ){ m = pm; }
<|endoftext|>
|
<commit_before>/**
* @file Object.hpp
* @brief Object class prototype.
* @author zer0
* @date 2016-06-05
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/id/Id.hpp>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace common {
#define IMPLEMENT_GET_CLASS_NAME(name) \
static constexpr char const * const getClassName() noexcept { \
return #name; \
}
/**
* Object class prototype.
*
* @author zer0
* @date 2016-06-05
*/
class Object
{
public:
IMPLEMENT_GET_CLASS_NAME(Object);
public:
using Id = id::Id;
private:
Id _id;
public:
Object() noexcept
{
_id = reinterpret_cast<Id>(this);
}
Object(Object const & obj) noexcept : Object()
{
// EMPTY.
}
Object(Object && obj) noexcept : Object()
{
// EMPTY.
}
virtual ~Object() noexcept
{
// EMPTY.
}
public:
inline Object & operator =(Object const & obj) noexcept
{
return *this;
}
inline Object & operator =(Object && obj) noexcept
{
return *this;
}
public:
inline bool operator ==(Object const & obj) noexcept
{
return (this == &obj);
}
inline bool operator !=(Object const & obj) noexcept
{
return (this != &obj);
}
public:
inline Id getId() const noexcept
{
return _id;
}
};
} // namespace common
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
<commit_msg>Refactoring libtbag::common::Object class.<commit_after>/**
* @file Object.hpp
* @brief Object class prototype.
* @author zer0
* @date 2016-06-05
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/id/Id.hpp>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace common {
#ifndef IMPLEMENT_GET_CLASS_NAME
#define IMPLEMENT_GET_CLASS_NAME(name, qualify) \
static constexpr char const * const getClassName() noexcept \
{ return #name; } \
virtual char const * const getName() qualify \
{ return getClassName(); }
#endif
#ifndef IMPLEMENT_GET_PARENT_CLASS_NAME
#define IMPLEMENT_GET_PARENT_CLASS_NAME(name) \
IMPLEMENT_GET_CLASS_NAME(name, const noexcept)
#endif
#ifndef IMPLEMENT_GET_CHILD_CLASS_NAME
#define IMPLEMENT_GET_CHILD_CLASS_NAME(name) \
IMPLEMENT_GET_CLASS_NAME(name, const noexcept override)
#endif
/**
* Object class prototype.
*
* @author zer0
* @date 2016-06-05
*/
class Object
{
public:
IMPLEMENT_GET_PARENT_CLASS_NAME(Object);
public:
using Id = id::Id;
private:
Id _id;
public:
Object() noexcept
{
_id = reinterpret_cast<Id>(this);
}
Object(Object const & obj) noexcept : Object()
{ /* EMPTY. */ }
Object(Object && obj) noexcept : Object()
{ /* EMPTY. */ }
virtual ~Object() noexcept
{ /* EMPTY. */ }
public:
inline Object & operator =(Object const & obj) noexcept
{ return *this; }
inline Object & operator =(Object && obj) noexcept
{ return *this; }
public:
inline bool operator ==(Object const & obj) noexcept
{ return (this == &obj); }
inline bool operator !=(Object const & obj) noexcept
{ return (this != &obj); }
public:
inline Id getId() const noexcept
{ return _id; }
};
} // namespace common
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_COMMON_OBJECT_HPP__
<|endoftext|>
|
<commit_before>#include "Building.h"
Building::Building()
{
}
Building::Building(GLuint programme_id)
{
int width = rand() % 60 + 15;
int height = rand() % 80 + 15;
int depth = rand() % 10 + 20;
for (int x = 0; x < width;x++)
{
for (int z = 0; z < depth; z++)
{
for (int y = 0; y < height; y++)
{
points.push_back(x);
points.push_back(y);
points.push_back(z);
}
}
}
glGenBuffers(1, &buildingVBO); //generate 1 VBO for the building vertices
glBindBuffer(GL_ARRAY_BUFFER, buildingVBO);
glBufferData(GL_ARRAY_BUFFER, points.size() * sizeof(GLfloat), &points.front(), GL_STATIC_DRAW);
model_matrix_id = glGetUniformLocation(programme_id, "model_matrix");
position.x = -1*rand() % 200;
position.y = 0.5f;
position.z = -1 * rand() % 200;
}
Building::~Building()
{
}
void Building::draw()
{
glm::mat4 position_matrix = glm::translate(position);
glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, glm::value_ptr(position_matrix));
printf("position is\:(%f,%f,%f)\n", position.x, position.y, position.z);
glBindBuffer(GL_ARRAY_BUFFER, buildingVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(
GL_POINTS,
0,
points.size()
);
}
<commit_msg>Framerate boost withvoxel optimization<commit_after>#include "Building.h"
Building::Building()
{
}
Building::Building(GLuint programme_id)
{
int width = rand() % 60 + 15;
int height = rand() % 80 + 15;
int depth = rand() % 10 + 20;
for (int x = 0; x < width;x++)
{
for (int z = 0; z < depth; z++)
{
for (int y = 0; y < height; y++)
{
if (x == 0 || y == 0 || z == 0 || x == width-1 || y == height-1 || z == depth-1)
{
points.push_back(x);
points.push_back(y);
points.push_back(z);
}
}
}
}
glGenBuffers(1, &buildingVBO); //generate 1 VBO for the building vertices
glBindBuffer(GL_ARRAY_BUFFER, buildingVBO);
glBufferData(GL_ARRAY_BUFFER, points.size() * sizeof(GLfloat), &points.front(), GL_STATIC_DRAW);
model_matrix_id = glGetUniformLocation(programme_id, "model_matrix");
position.x = -1*rand() % 200;
position.y = 0.5f;
position.z = -1 * rand() % 200;
}
Building::~Building()
{
}
void Building::draw()
{
glm::mat4 position_matrix = glm::translate(position);
glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, glm::value_ptr(position_matrix));
printf("position is\:(%f,%f,%f)\n", position.x, position.y, position.z);
glBindBuffer(GL_ARRAY_BUFFER, buildingVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(
GL_POINTS,
0,
points.size()
);
}
<|endoftext|>
|
<commit_before>#include <vector>
#include "compiler.h"
#include "parser.h"
#include "token.h"
using namespace std;
bool next();
void prev();
TokenNode* makeNode();
TokenNode* makeNode(Token);
TokenNode* makeNode(TokenType);
TokenNode* dImports();
TokenNode* dNoContext();
TokenNode* dNoContextItem();
TokenNode* dGenericDecl();
//namespace
TokenNode* dType();
TokenNode* dTypeAllowRef();
TokenNode* dBaseType();
TokenNode* dTypeId();
TokenNode* dTypeMod();
TokenNode* dTypeModRef();
TokenNode* dStructOrFuncDecl();
TokenNode* dStructDecl();
TokenNode* dFuncDecl();
TokenNode* dVarDecl();
/*
Remember that the lexer naively passes:
ANGLE_BRACKET_LEFT - OP_BIN_LESS
ANGLE_BRACKET_RIGHT - OP_BIN_GREATER
OP_BIN_MUL - OP_PTR
OP_BIN_BITWISE_AND - OP_ADDRESS
OP_FUNC_RET - OP_PTR_MEMBER_ACCESS ?
OP_DECLARATION - OP_TERNARY_COLON
DOUBLE_COLON - (OP_FUNC_DECLARATION | OP_STRUCT_DECLARATION)
*/
vector<Token> tokens;
int index;
int length;
Token t;
TokenNode* parseSyntax(vector<Token>& data) {
tokens = data;
index = -1;
length = tokens.size();
TokenNode* root = makeNode(ROOT);
TokenNode* node = dImports();
if (node) root->children.push_back(node);
node = dNoContext();
if (node) root->children.push_back(node);
return root;
}
bool next() {
if (++index < length) {
t = tokens[index];
return true;
}
return false;
}
void prev() {
t = tokens[--index];
}
TokenNode* makeNode() {
return makeNode(t);
}
TokenNode* makeNode(Token token) {
TokenNode* node = new TokenNode;
node->data = token;
return node;
}
TokenNode* makeNode(TokenType type) {
Token t;
t.type = type;
t.lexeme = "";
t.line = -1;
t.col = -1;
return makeNode(t);
}
TokenNode* dImports() {
if (!next()) {
logCompiler(WARN, "empty file");
} else if (t.type == DIR_IMPORT) {
TokenNode* node = makeNode();
if (!next() || t.type != LITERAL_STRING) {
logCompiler(ERROR, "#import expects a string", &node->data);
} else {
node->children.push_back(makeNode());
TokenNode* out = dImports();
if (out) node->children.push_back(out);
return node;
}
}
prev();
return NULL;
}
TokenNode* dNoContext() {
TokenNode* context = makeNode(NO_CONTEXT);
TokenNode* item;
while (true) {
item = dNoContextItem();
if (item) {
context->children.push_back(item);
} else {
break;
}
}
return context;
}
TokenNode* dNoContextItem() {
if (!next()) return NULL;
TokenNode* node;
if (t.type == IDENTIFIER) {
Token name = t;
node = dGenericDecl();
if (node) {
node->children.insert(node->children.begin(), makeNode(name));
return node;
} else {
logCompiler(ERROR, "expected declaration", &name);
}
}
return NULL;
}
TokenNode* dGenericDecl() {
if (!next()) return NULL;
if (t.type == DOUBLE_COLON) {
TokenNode* decl = makeNode();
TokenNode* out = dStructOrFuncDecl();
if (out) {
decl->data.type = out->data.type == KW_STRUCT ? OP_STRUCT_DECLARATION : OP_FUNC_DECLARATION;
decl->children.push_back(out);
return decl;
} else {
delete decl;
prev();
return NULL;
}
} else {
prev();
return dVarDecl();
}
}
TokenNode* dType() {
return NULL;
}
TokenNode* dTypeAllowRef() {
return NULL;
}
TokenNode* dBaseType() {
return NULL;
}
TokenNode* dTypeId() {
return NULL;
}
TokenNode* dTypeMod() {
if (!next()) return NULL;
if (t.type == OP_BIN_MUL) {
t.type = OP_PTR;
return makeNode();
} else if (t.type == SQUARE_BRACKET_LEFT) {
if (!next() || t.type != SQUARE_BRACKET_RIGHT) {
logCompiler(ERROR, "expected ']'", &t);
prev();
return NULL;
}
}
prev();
return NULL;
}
TokenNode* dTypeModRef() {
if (!next()) return NULL;
if (t.type == OP_BIN_BITWISE_AND) {
t.type = OP_ADDRESS;
return makeNode();
}
prev();
return NULL;
}
TokenNode* dStructOrFuncDecl() {
if (!next()) return NULL;
if (t.type == KW_STRUCT) {
TokenNode* node = makeNode();
TokenNode* out = dStructDecl();
if (out) {
node->children.push_back(out);
return node;
} else {
delete node;
prev();
return NULL;
}
} else {
prev();
return dFuncDecl();
}
}
TokenNode* dStructDecl() {
return makeNode(UNKNOWN);
}
TokenNode* dFuncDecl() {
return makeNode(UNKNOWN);
}
TokenNode* dVarDecl() {
return makeNode(UNKNOWN);
}
<commit_msg>Tiny parser bugfix<commit_after>#include <vector>
#include "compiler.h"
#include "parser.h"
#include "token.h"
using namespace std;
bool next();
void prev();
TokenNode* makeNode();
TokenNode* makeNode(Token);
TokenNode* makeNode(TokenType);
TokenNode* dImports();
TokenNode* dNoContext();
TokenNode* dNoContextItem();
TokenNode* dGenericDecl();
//namespace
TokenNode* dType();
TokenNode* dTypeAllowRef();
TokenNode* dBaseType();
TokenNode* dTypeId();
TokenNode* dTypeMod();
TokenNode* dTypeModRef();
TokenNode* dStructOrFuncDecl();
TokenNode* dStructDecl();
TokenNode* dFuncDecl();
TokenNode* dVarDecl();
/*
Remember that the lexer naively passes:
ANGLE_BRACKET_LEFT - OP_BIN_LESS
ANGLE_BRACKET_RIGHT - OP_BIN_GREATER
OP_BIN_MUL - OP_PTR
OP_BIN_BITWISE_AND - OP_ADDRESS
OP_FUNC_RET - OP_PTR_MEMBER_ACCESS ?
OP_DECLARATION - OP_TERNARY_COLON
DOUBLE_COLON - (OP_FUNC_DECLARATION | OP_STRUCT_DECLARATION)
*/
vector<Token> tokens;
int index;
int length;
Token t;
TokenNode* parseSyntax(vector<Token>& data) {
tokens = data;
index = -1;
length = tokens.size();
TokenNode* root = makeNode(ROOT);
TokenNode* node = dImports();
if (node) root->children.push_back(node);
node = dNoContext();
if (node) root->children.push_back(node);
return root;
}
bool next() {
if (++index < length) {
t = tokens[index];
return true;
}
return false;
}
void prev() {
if (--index >= 0) {
t = tokens[index];
}
}
TokenNode* makeNode() {
return makeNode(t);
}
TokenNode* makeNode(Token token) {
TokenNode* node = new TokenNode;
node->data = token;
return node;
}
TokenNode* makeNode(TokenType type) {
Token t;
t.type = type;
t.lexeme = "";
t.line = -1;
t.col = -1;
return makeNode(t);
}
TokenNode* dImports() {
if (!next()) {
logCompiler(WARN, "empty file");
} else if (t.type == DIR_IMPORT) {
TokenNode* node = makeNode();
if (!next() || t.type != LITERAL_STRING) {
logCompiler(ERROR, "#import expects a string", &node->data);
} else {
node->children.push_back(makeNode());
TokenNode* out = dImports();
if (out) node->children.push_back(out);
return node;
}
}
prev();
return NULL;
}
TokenNode* dNoContext() {
TokenNode* context = makeNode(NO_CONTEXT);
TokenNode* item;
while (true) {
item = dNoContextItem();
if (item) {
context->children.push_back(item);
} else {
break;
}
}
return context;
}
TokenNode* dNoContextItem() {
if (!next()) return NULL;
TokenNode* node;
if (t.type == IDENTIFIER) {
Token name = t;
node = dGenericDecl();
if (node) {
node->children.insert(node->children.begin(), makeNode(name));
return node;
} else {
logCompiler(ERROR, "expected declaration", &name);
}
}
return NULL;
}
TokenNode* dGenericDecl() {
if (!next()) return NULL;
if (t.type == DOUBLE_COLON) {
TokenNode* decl = makeNode();
TokenNode* out = dStructOrFuncDecl();
if (out) {
decl->data.type = out->data.type == KW_STRUCT ? OP_STRUCT_DECLARATION : OP_FUNC_DECLARATION;
decl->children.push_back(out);
return decl;
} else {
delete decl;
prev();
return NULL;
}
} else {
prev();
return dVarDecl();
}
}
TokenNode* dType() {
return NULL;
}
TokenNode* dTypeAllowRef() {
return NULL;
}
TokenNode* dBaseType() {
return NULL;
}
TokenNode* dTypeId() {
return NULL;
}
TokenNode* dTypeMod() {
if (!next()) return NULL;
if (t.type == OP_BIN_MUL) {
t.type = OP_PTR;
return makeNode();
} else if (t.type == SQUARE_BRACKET_LEFT) {
if (!next() || t.type != SQUARE_BRACKET_RIGHT) {
logCompiler(ERROR, "expected ']'", &t);
prev();
return NULL;
}
}
prev();
return NULL;
}
TokenNode* dTypeModRef() {
if (!next()) return NULL;
if (t.type == OP_BIN_BITWISE_AND) {
t.type = OP_ADDRESS;
return makeNode();
}
prev();
return NULL;
}
TokenNode* dStructOrFuncDecl() {
if (!next()) return NULL;
if (t.type == KW_STRUCT) {
TokenNode* node = makeNode();
TokenNode* out = dStructDecl();
if (out) {
node->children.push_back(out);
return node;
} else {
delete node;
prev();
return NULL;
}
} else {
prev();
return dFuncDecl();
}
}
TokenNode* dStructDecl() {
return makeNode(UNKNOWN);
}
TokenNode* dFuncDecl() {
return makeNode(UNKNOWN);
}
TokenNode* dVarDecl() {
return makeNode(UNKNOWN);
}
<|endoftext|>
|
<commit_before>/*******************************
Copyright (c) 2016-2019 Grégoire Angerand
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 "MainWindow.h"
#include <csignal>
#include <editor/events/MainEventHandler.h>
#include <editor/context/EditorContext.h>
#include <yave/graphics/swapchain/Swapchain.h>
#include <yave/assets/SQLiteAssetStore.h>
#include <yave/assets/FolderAssetStore.h>
#include <y/core/Chrono.h>
using namespace editor;
static EditorContext* context = nullptr;
#ifdef Y_DEBUG
static bool display_console = true;
static bool debug_instance = true;
#else
static bool display_console = false;
static bool debug_instance = false;
#endif
static void hide_console() {
#ifdef Y_OS_WIN
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
}
[[maybe_unused]]
static void crash_handler(int) {
log_msg("SEGFAULT!");
Y_TODO(we might want to save whatever we can here)
}
static void setup_handlers() {
std::signal(SIGSEGV, crash_handler);
perf::set_output_file("perfdump.json");
}
static void parse_args(int argc, char** argv) {
for(std::string_view arg : core::Span<const char*>(argv, argc)) {
if(arg == "--nodebug") {
debug_instance = false;
}
if(arg == "--debug") {
debug_instance = true;
}
if(arg == "--console") {
display_console = true;
}
}
if(!display_console) {
hide_console();
}
y_debug_assert([] { log_msg("Debug asserts enabled."); return true; }());
}
static void setup_logger() {
set_log_callback([](std::string_view msg, Log type, void*) {
if(context) {
context->log_message(msg, type);
}
return !display_console;
});
}
static Instance create_instance() {
y_profile();
if(!debug_instance) {
log_msg("Vulkan debugging disabled.", Log::Warning);
}
return Instance(debug_instance ? DebugParams::debug() : DebugParams::none());
}
static Device create_device(Instance& instance) {
y_profile();
return Device(instance);
}
static EditorContext create_constext(const Device& device) {
y_profile();
return EditorContext(&device);
}
int main(int argc, char** argv) {
parse_args(argc, argv);
setup_handlers();
setup_logger();
Instance instance = create_instance();
Device device = create_device(instance);
EditorContext ctx = create_constext(device);
context = &ctx;
MainWindow window(&ctx);
window.set_event_handler(std::make_unique<MainEventHandler>());
window.show();
for(;;) {
if(!window.update()) {
if(ctx.ui().confirm("Quit ?")) {
break;
} else {
window.show();
}
}
Swapchain* swapchain = window.swapchain();
if(swapchain && swapchain->is_valid()) {
FrameToken frame = swapchain->next_frame();
CmdBufferRecorder recorder(device.create_disposable_cmd_buffer());
ctx.ui().paint(recorder, frame);
window.present(recorder, frame);
}
ctx.flush_deferred();
}
set_log_callback(nullptr);
context = nullptr;
return 0;
}
<commit_msg>Fix typo<commit_after>/*******************************
Copyright (c) 2016-2019 Grégoire Angerand
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 "MainWindow.h"
#include <csignal>
#include <editor/events/MainEventHandler.h>
#include <editor/context/EditorContext.h>
#include <yave/graphics/swapchain/Swapchain.h>
#include <yave/assets/SQLiteAssetStore.h>
#include <yave/assets/FolderAssetStore.h>
#include <y/core/Chrono.h>
using namespace editor;
static EditorContext* context = nullptr;
#ifdef Y_DEBUG
static bool display_console = true;
static bool debug_instance = true;
#else
static bool display_console = false;
static bool debug_instance = false;
#endif
static void hide_console() {
#ifdef Y_OS_WIN
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
}
[[maybe_unused]]
static void crash_handler(int) {
log_msg("SEGFAULT!");
Y_TODO(we might want to save whatever we can here)
}
static void setup_handlers() {
std::signal(SIGSEGV, crash_handler);
perf::set_output_file("perfdump.json");
}
static void parse_args(int argc, char** argv) {
for(std::string_view arg : core::Span<const char*>(argv, argc)) {
if(arg == "--nodebug") {
debug_instance = false;
}
if(arg == "--debug") {
debug_instance = true;
}
if(arg == "--console") {
display_console = true;
}
}
if(!display_console) {
hide_console();
}
y_debug_assert([] { log_msg("Debug asserts enabled."); return true; }());
}
static void setup_logger() {
set_log_callback([](std::string_view msg, Log type, void*) {
if(context) {
context->log_message(msg, type);
}
return !display_console;
});
}
static Instance create_instance() {
y_profile();
if(!debug_instance) {
log_msg("Vulkan debugging disabled.", Log::Warning);
}
return Instance(debug_instance ? DebugParams::debug() : DebugParams::none());
}
static Device create_device(Instance& instance) {
y_profile();
return Device(instance);
}
static EditorContext create_context(const Device& device) {
y_profile();
return EditorContext(&device);
}
int main(int argc, char** argv) {
parse_args(argc, argv);
setup_handlers();
setup_logger();
Instance instance = create_instance();
Device device = create_device(instance);
EditorContext ctx = create_context(device);
context = &ctx;
MainWindow window(&ctx);
window.set_event_handler(std::make_unique<MainEventHandler>());
window.show();
for(;;) {
if(!window.update()) {
if(ctx.ui().confirm("Quit ?")) {
break;
} else {
window.show();
}
}
Swapchain* swapchain = window.swapchain();
if(swapchain && swapchain->is_valid()) {
FrameToken frame = swapchain->next_frame();
CmdBufferRecorder recorder(device.create_disposable_cmd_buffer());
ctx.ui().paint(recorder, frame);
window.present(recorder, frame);
}
ctx.flush_deferred();
}
set_log_callback(nullptr);
context = nullptr;
return 0;
}
<|endoftext|>
|
<commit_before>#include <unordered_map>
#include "Compression.h"
#include "IMGFile.h"
#include "../Math/Vector2.h"
#include "../Utilities/Bytes.h"
#include "../Utilities/Debug.h"
#include "components/vfs/manager.hpp"
namespace
{
// These IMG files are actually headerless/raw files with hardcoded dimensions.
const std::unordered_map<std::string, Int2> RawImgOverride =
{
{ "ARENARW.IMG", { 16, 16 } },
{ "CITY.IMG", { 16, 11 } },
{ "DITHER.IMG", { 16, 50 } },
{ "DITHER2.IMG", { 16, 50 } },
{ "DUNGEON.IMG", { 14, 8 } },
{ "DZTTAV.IMG", { 32, 34 } },
{ "NOCAMP.IMG", { 25, 19 } },
{ "NOSPELL.IMG", { 25, 19 } },
{ "P1.IMG", { 320, 53 } },
{ "POPTALK.IMG", { 320, 77 } },
{ "S2.IMG", { 320, 36 } },
{ "SLIDER.IMG", { 289, 7 } },
{ "TOWN.IMG", { 9, 10 } },
{ "UPDOWN.IMG", { 8, 16 } },
{ "VILLAGE.IMG", { 8, 8 } }
};
// Some .IMG filenames are misspelled and need a replacement.
const std::unordered_map<std::string, std::string> MisspelledIMGs =
{
{ "SFOUNF1M.IMG", "SFOUNT1M.IMG" },
{ "SFOUNF1T.IMG", "SFOUNT1T.IMG" }
};
}
IMGFile::IMGFile(const std::string &filename, const Palette *palette)
{
// Revise the filename if it is misspelled.
const auto nameIter = MisspelledIMGs.find(filename);
const std::string &correctFilename = (nameIter == MisspelledIMGs.end()) ?
filename : nameIter->second;
VFS::IStreamPtr stream = VFS::Manager::get().open(correctFilename);
DebugAssert(stream != nullptr, "Could not open \"" + correctFilename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
uint16_t xoff, yoff, width, height, flags, len;
// Read header data if not raw. Wall IMGs have no header and are 4096 bytes.
const auto rawOverride = RawImgOverride.find(correctFilename);
const bool isRaw = rawOverride != RawImgOverride.end();
if (isRaw)
{
xoff = 0;
yoff = 0;
width = rawOverride->second.x;
height = rawOverride->second.y;
flags = 0;
len = width * height;
}
else if (srcData.size() == 4096)
{
// Some wall IMGs have rows of black (transparent) pixels near the
// beginning, so the header would just be zeroes. This is a guess to
// try and fix that issue as well as cover all other wall IMGs.
xoff = 0;
yoff = 0;
width = 64;
height = 64;
flags = 0;
len = width * height;
}
else
{
// Read header data.
xoff = Bytes::getLE16(srcData.data());
yoff = Bytes::getLE16(srcData.data() + 2);
width = Bytes::getLE16(srcData.data() + 4);
height = Bytes::getLE16(srcData.data() + 6);
flags = Bytes::getLE16(srcData.data() + 8);
len = Bytes::getLE16(srcData.data() + 10);
}
const int headerSize = 12;
// Try and read the IMG's built-in palette if the given palette is null.
Palette builtInPalette;
const bool useBuiltInPalette = palette == nullptr;
if (useBuiltInPalette)
{
// This code might run even if the IMG doesn't have a palette, because
// some IMGs have no header and are not "raw" (like walls, for instance).
DebugAssert((flags & 0x0100) != 0, "\"" + correctFilename +
"\" does not have a built-in palette.");
// Read the palette data and write it to the destination palette.
IMGFile::readPalette(srcData.data() + headerSize + len, builtInPalette);
}
// Choose which palette to use.
const Palette &paletteRef = useBuiltInPalette ? builtInPalette : (*palette);
// Lambda for setting IMGFile members and constructing the final image.
auto makeImage = [this, &paletteRef](int width, int height, const uint8_t *data)
{
this->width = width;
this->height = height;
this->pixels = std::unique_ptr<uint32_t[]>(new uint32_t[width * height]);
std::transform(data, data + (width * height), this->pixels.get(),
[&paletteRef](uint8_t col) -> uint32_t
{
return paletteRef.get()[col].toARGB();
});
};
// Decide how to use the pixel data.
if (isRaw)
{
// Uncompressed IMG with no header (excluding walls).
makeImage(width, height, srcData.data());
}
else if ((srcData.size() == 4096) && (width == 64) && (height == 64))
{
// Wall texture (the flags variable is garbage).
makeImage(64, 64, srcData.data());
}
else
{
// Decode the pixel data according to the IMG flags.
if ((flags & 0x00FF) == 0)
{
// Uncompressed IMG with header.
makeImage(width, height, srcData.data() + headerSize);
}
else if ((flags & 0x00FF) == 0x0004)
{
// Type 4 compression.
std::vector<uint8_t> decomp(width * height);
Compression::decodeType04(srcData.begin() + headerSize,
srcData.begin() + headerSize + len, decomp);
// Create 32-bit image.
makeImage(width, height, decomp.data());
}
else if ((flags & 0x00FF) == 0x0008)
{
// Type 8 compression. Contains a 2 byte decompressed length after
// the header, so skip that (should be equivalent to width * height).
std::vector<uint8_t> decomp(width * height);
Compression::decodeType08(srcData.begin() + headerSize + 2,
srcData.begin() + headerSize + len, decomp);
// Create 32-bit image.
makeImage(width, height, decomp.data());
}
else
{
DebugCrash("Unrecognized IMG \"" + correctFilename + "\".");
}
}
}
IMGFile::~IMGFile()
{
}
void IMGFile::readPalette(const uint8_t *paletteData, Palette &dstPalette)
{
// The palette data is 768 bytes, starting after the pixel data ends.
// Unlike COL files, embedded palettes are stored with components in
// the range of 0...63 rather than 0...255 (this was because old VGA
// hardware only had 6-bit DACs, giving a maximum intensity value of
// 63, while newer hardware had 8-bit DACs for up to 255.
uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
dstPalette.get()[0] = Color(r, g, b, 0);
// Remaining are solid, so give them 255 alpha.
std::generate(dstPalette.get().begin() + 1, dstPalette.get().end(),
[&paletteData]() -> Color
{
uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
return Color(r, g, b, 255);
});
}
void IMGFile::extractPalette(const std::string &filename, Palette &dstPalette)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename);
DebugAssert(stream != nullptr, "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// Read the flags and IMG file length. Skip the X and Y offsets and dimensions.
// No need to check for raw override. All given filenames should point to IMGs
// with "built-in" palettes, and none of those IMGs are in the raw override.
const uint16_t flags = Bytes::getLE16(srcData.data() + 8);
const uint16_t len = Bytes::getLE16(srcData.data() + 10);
const int headerSize = 12;
// Don't try to read a built-in palette is there isn't one.
DebugAssert((flags & 0x0100) != 0, "\"" + filename +
"\" has no built-in palette to extract.");
// Read the palette data and write it to the destination palette.
IMGFile::readPalette(srcData.data() + headerSize + len, dstPalette);
}
int IMGFile::getWidth() const
{
return this->width;
}
int IMGFile::getHeight() const
{
return this->height;
}
uint32_t *IMGFile::getPixels() const
{
return this->pixels.get();
}
<commit_msg>Revert "Added check for misspelled .IMG filenames."<commit_after>#include <unordered_map>
#include "Compression.h"
#include "IMGFile.h"
#include "../Math/Vector2.h"
#include "../Utilities/Bytes.h"
#include "../Utilities/Debug.h"
#include "components/vfs/manager.hpp"
namespace
{
// These IMG files are actually headerless/raw files with hardcoded dimensions.
const std::unordered_map<std::string, Int2> RawImgOverride =
{
{ "ARENARW.IMG", { 16, 16 } },
{ "CITY.IMG", { 16, 11 } },
{ "DITHER.IMG", { 16, 50 } },
{ "DITHER2.IMG", { 16, 50 } },
{ "DUNGEON.IMG", { 14, 8 } },
{ "DZTTAV.IMG", { 32, 34 } },
{ "NOCAMP.IMG", { 25, 19 } },
{ "NOSPELL.IMG", { 25, 19 } },
{ "P1.IMG", { 320, 53 } },
{ "POPTALK.IMG", { 320, 77 } },
{ "S2.IMG", { 320, 36 } },
{ "SLIDER.IMG", { 289, 7 } },
{ "TOWN.IMG", { 9, 10 } },
{ "UPDOWN.IMG", { 8, 16 } },
{ "VILLAGE.IMG", { 8, 8 } }
};
}
IMGFile::IMGFile(const std::string &filename, const Palette *palette)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename);
DebugAssert(stream != nullptr, "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
uint16_t xoff, yoff, width, height, flags, len;
// Read header data if not raw. Wall IMGs have no header and are 4096 bytes.
const auto rawOverride = RawImgOverride.find(filename);
const bool isRaw = rawOverride != RawImgOverride.end();
if (isRaw)
{
xoff = 0;
yoff = 0;
width = rawOverride->second.x;
height = rawOverride->second.y;
flags = 0;
len = width * height;
}
else if (srcData.size() == 4096)
{
// Some wall IMGs have rows of black (transparent) pixels near the
// beginning, so the header would just be zeroes. This is a guess to
// try and fix that issue as well as cover all other wall IMGs.
xoff = 0;
yoff = 0;
width = 64;
height = 64;
flags = 0;
len = width * height;
}
else
{
// Read header data.
xoff = Bytes::getLE16(srcData.data());
yoff = Bytes::getLE16(srcData.data() + 2);
width = Bytes::getLE16(srcData.data() + 4);
height = Bytes::getLE16(srcData.data() + 6);
flags = Bytes::getLE16(srcData.data() + 8);
len = Bytes::getLE16(srcData.data() + 10);
}
const int headerSize = 12;
// Try and read the IMG's built-in palette if the given palette is null.
Palette builtInPalette;
const bool useBuiltInPalette = palette == nullptr;
if (useBuiltInPalette)
{
// This code might run even if the IMG doesn't have a palette, because
// some IMGs have no header and are not "raw" (like walls, for instance).
DebugAssert((flags & 0x0100) != 0, "\"" + filename +
"\" does not have a built-in palette.");
// Read the palette data and write it to the destination palette.
IMGFile::readPalette(srcData.data() + headerSize + len, builtInPalette);
}
// Choose which palette to use.
const Palette &paletteRef = useBuiltInPalette ? builtInPalette : (*palette);
// Lambda for setting IMGFile members and constructing the final image.
auto makeImage = [this, &paletteRef](int width, int height, const uint8_t *data)
{
this->width = width;
this->height = height;
this->pixels = std::unique_ptr<uint32_t[]>(new uint32_t[width * height]);
std::transform(data, data + (width * height), this->pixels.get(),
[&paletteRef](uint8_t col) -> uint32_t
{
return paletteRef.get()[col].toARGB();
});
};
// Decide how to use the pixel data.
if (isRaw)
{
// Uncompressed IMG with no header (excluding walls).
makeImage(width, height, srcData.data());
}
else if ((srcData.size() == 4096) && (width == 64) && (height == 64))
{
// Wall texture (the flags variable is garbage).
makeImage(64, 64, srcData.data());
}
else
{
// Decode the pixel data according to the IMG flags.
if ((flags & 0x00FF) == 0)
{
// Uncompressed IMG with header.
makeImage(width, height, srcData.data() + headerSize);
}
else if ((flags & 0x00FF) == 0x0004)
{
// Type 4 compression.
std::vector<uint8_t> decomp(width * height);
Compression::decodeType04(srcData.begin() + headerSize,
srcData.begin() + headerSize + len, decomp);
// Create 32-bit image.
makeImage(width, height, decomp.data());
}
else if ((flags & 0x00FF) == 0x0008)
{
// Type 8 compression. Contains a 2 byte decompressed length after
// the header, so skip that (should be equivalent to width * height).
std::vector<uint8_t> decomp(width * height);
Compression::decodeType08(srcData.begin() + headerSize + 2,
srcData.begin() + headerSize + len, decomp);
// Create 32-bit image.
makeImage(width, height, decomp.data());
}
else
{
DebugCrash("Unrecognized IMG \"" + filename + "\".");
}
}
}
IMGFile::~IMGFile()
{
}
void IMGFile::readPalette(const uint8_t *paletteData, Palette &dstPalette)
{
// The palette data is 768 bytes, starting after the pixel data ends.
// Unlike COL files, embedded palettes are stored with components in
// the range of 0...63 rather than 0...255 (this was because old VGA
// hardware only had 6-bit DACs, giving a maximum intensity value of
// 63, while newer hardware had 8-bit DACs for up to 255.
uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
dstPalette.get()[0] = Color(r, g, b, 0);
// Remaining are solid, so give them 255 alpha.
std::generate(dstPalette.get().begin() + 1, dstPalette.get().end(),
[&paletteData]() -> Color
{
uint8_t r = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t g = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
uint8_t b = std::min<uint8_t>(*(paletteData++), 63) * 255 / 63;
return Color(r, g, b, 255);
});
}
void IMGFile::extractPalette(const std::string &filename, Palette &dstPalette)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename);
DebugAssert(stream != nullptr, "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// Read the flags and IMG file length. Skip the X and Y offsets and dimensions.
// No need to check for raw override. All given filenames should point to IMGs
// with "built-in" palettes, and none of those IMGs are in the raw override.
const uint16_t flags = Bytes::getLE16(srcData.data() + 8);
const uint16_t len = Bytes::getLE16(srcData.data() + 10);
const int headerSize = 12;
// Don't try to read a built-in palette is there isn't one.
DebugAssert((flags & 0x0100) != 0, "\"" + filename +
"\" has no built-in palette to extract.");
// Read the palette data and write it to the destination palette.
IMGFile::readPalette(srcData.data() + headerSize + len, dstPalette);
}
int IMGFile::getWidth() const
{
return this->width;
}
int IMGFile::getHeight() const
{
return this->height;
}
uint32_t *IMGFile::getPixels() const
{
return this->pixels.get();
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include "SETFile.h"
#include "../Utilities/Debug.h"
#include "components/vfs/manager.hpp"
const int SETFile::CHUNK_WIDTH = 64;
const int SETFile::CHUNK_HEIGHT = 64;
const int SETFile::CHUNK_SIZE = SETFile::CHUNK_WIDTH * SETFile::CHUNK_HEIGHT;
SETFile::SETFile(const std::string &filename, const Palette &palette)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename);
DebugAssert(stream != nullptr, "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// Number of uncompressed chunks packed in the SET.
const int chunkCount = static_cast<int>(srcData.size()) / SETFile::CHUNK_SIZE;
// Create an image for each uncompressed chunk using the given palette.
for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++)
{
this->chunks.push_back(std::unique_ptr<uint32_t[]>(
new uint32_t[SETFile::CHUNK_SIZE]));
const int byteOffset = SETFile::CHUNK_SIZE * chunkIndex;
const auto chunkStart = srcData.begin() + byteOffset;
const auto chunkEnd = chunkStart + SETFile::CHUNK_SIZE;
std::transform(chunkStart, chunkEnd, this->chunks.at(chunkIndex).get(),
[&palette](uint8_t col) -> uint32_t
{
return palette.get()[col].toARGB();
});
}
}
SETFile::~SETFile()
{
}
int SETFile::getImageCount() const
{
return static_cast<int>(this->chunks.size());
}
uint32_t *SETFile::getPixels(int index) const
{
return this->chunks.at(index).get();
}
<commit_msg>Added special case for TBS2.SET.<commit_after>#include <algorithm>
#include "SETFile.h"
#include "../Utilities/Debug.h"
#include "components/vfs/manager.hpp"
const int SETFile::CHUNK_WIDTH = 64;
const int SETFile::CHUNK_HEIGHT = 64;
const int SETFile::CHUNK_SIZE = SETFile::CHUNK_WIDTH * SETFile::CHUNK_HEIGHT;
SETFile::SETFile(const std::string &filename, const Palette &palette)
{
VFS::IStreamPtr stream = VFS::Manager::get().open(filename);
DebugAssert(stream != nullptr, "Could not open \"" + filename + "\".");
stream->seekg(0, std::ios::end);
std::vector<uint8_t> srcData(stream->tellg());
stream->seekg(0, std::ios::beg);
stream->read(reinterpret_cast<char*>(srcData.data()), srcData.size());
// There is one .SET file with a file size of 0x3FFF, so it is a special case.
const bool isSpecialCase = filename == "TBS2.SET";
if (isSpecialCase)
{
// Add a dummy byte onto the end.
srcData.push_back(0);
}
// Number of uncompressed chunks packed in the SET.
const int chunkCount = static_cast<int>(srcData.size()) / SETFile::CHUNK_SIZE;
// Create an image for each uncompressed chunk using the given palette.
for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++)
{
this->chunks.push_back(std::unique_ptr<uint32_t[]>(
new uint32_t[SETFile::CHUNK_SIZE]));
const int byteOffset = SETFile::CHUNK_SIZE * chunkIndex;
const auto chunkStart = srcData.begin() + byteOffset;
const auto chunkEnd = chunkStart + SETFile::CHUNK_SIZE;
std::transform(chunkStart, chunkEnd, this->chunks.at(chunkIndex).get(),
[&palette](uint8_t col) -> uint32_t
{
return palette.get()[col].toARGB();
});
}
}
SETFile::~SETFile()
{
}
int SETFile::getImageCount() const
{
return static_cast<int>(this->chunks.size());
}
uint32_t *SETFile::getPixels(int index) const
{
return this->chunks.at(index).get();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2015 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "ECDHKeyExchange.h"
#include "../Interface/Server.h"
ECDHKeyExchange::ECDHKeyExchange()
{
CryptoPP::ECDH< CryptoPP::EC2N >::Domain ecdh(CryptoPP::ASN1::sect409k1());
CryptoPP::AutoSeededRandomPool rng;
priv.resize(ecdh.PrivateKeyLength());
pub.resize(ecdh.PublicKeyLength());
ecdh.GenerateKeyPair(rng, priv, pub);
}
std::string ECDHKeyExchange::getPublicKey()
{
return std::string(pub.BytePtr(), pub.BytePtr() + pub.size());
}
std::string ECDHKeyExchange::getSharedKey( const std::string& other_public )
{
CryptoPP::ECDH< CryptoPP::EC2N >::Domain ecdh(CryptoPP::ASN1::sect409k1());
if(other_public.size()!=ecdh.PublicKeyLength())
{
Server->Log("Public key length does not match", LL_ERROR);
return std::string();
}
std::string ret;
ret.resize(ecdh.AgreedValueLength());
if(!ecdh.Agree(reinterpret_cast<byte*>(&ret[0]), priv, reinterpret_cast<const byte*>(other_public.data())))
{
Server->Log("Failed to agree to ECDH shared secret", LL_ERROR);
return std::string();
}
return ret;
}
<commit_msg>Use smaller curve<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2015 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "ECDHKeyExchange.h"
#include "../Interface/Server.h"
ECDHKeyExchange::ECDHKeyExchange()
{
CryptoPP::ECDH< CryptoPP::EC2N >::Domain ecdh(CryptoPP::ASN1::sect233k1());
CryptoPP::AutoSeededRandomPool rng;
priv.resize(ecdh.PrivateKeyLength());
pub.resize(ecdh.PublicKeyLength());
ecdh.GenerateKeyPair(rng, priv, pub);
}
std::string ECDHKeyExchange::getPublicKey()
{
return std::string(pub.BytePtr(), pub.BytePtr() + pub.size());
}
std::string ECDHKeyExchange::getSharedKey( const std::string& other_public )
{
CryptoPP::ECDH< CryptoPP::EC2N >::Domain ecdh(CryptoPP::ASN1::sect233k1());
if(other_public.size()!=ecdh.PublicKeyLength())
{
Server->Log("Public key length does not match", LL_ERROR);
return std::string();
}
std::string ret;
ret.resize(ecdh.AgreedValueLength());
if(!ecdh.Agree(reinterpret_cast<byte*>(&ret[0]), priv, reinterpret_cast<const byte*>(other_public.data())))
{
Server->Log("Failed to agree to ECDH shared secret", LL_ERROR);
return std::string();
}
return ret;
}
<|endoftext|>
|
<commit_before>#include "mayaUtils.h"
#include <maya/MSelectionList.h>
#include <maya/MUuid.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
MayaUtils::MayaUtils()
{
}
MayaUtils::~MayaUtils()
{
}
bool MayaUtils::isValidNodeType(MString& _type)
{
return (_type == MString("transform") ||
_type == MString("mesh") ||
_type == MString("polyTweak") ||
_type == MString("polyExtrudeFace") ||
_type == MString("polyMergeVert") ||
_type == MString("polySplitRing") ||
_type == MString("polyCube"));
}
bool MayaUtils::DoesItRequireConnections(MString& _type)
{
return (_type == MString("polyTweak") ||
_type == MString("polyMergeVert") ||
_type == MString("polySplitRing") ||
_type == MString("polyExtrudeFace"));
}
MStatus MayaUtils::getNodeObjectFromUUID(MString& uuid, MObject& _node)
{
// get node
MSelectionList sList;
MUuid ID(uuid);
sList.add(ID);
return sList.getDependNode(0, _node);
}
bool MayaUtils::doesItExist(std::string& _id)
{
MStatus status;
MSelectionList selList;
MUuid id(_id.c_str());
status = selList.add(id);
return (status == MStatus::kSuccess);
}
MStatus MayaUtils::getIncomingNodeObject(MFnDependencyNode& node, MFnDependencyNode& incomingNode)
{
MStatus status;
MPlug inMeshPlug;
inMeshPlug = MayaUtils::getInPlug(node, status);
if (inMeshPlug.isConnected())
{
MPlugArray tempPlugArray;
inMeshPlug.connectedTo(tempPlugArray, true, false);
// Only one connection should exist on meshNodeShape.inMesh!
MPlug upstreamNodeSrcPlug = tempPlugArray[0];
incomingNode.setObject(upstreamNodeSrcPlug.node());
return MStatus::kSuccess;
}
return status;
}
MStatus MayaUtils::getOutgoingNodeObject(MFnDependencyNode& node, MFnDependencyNode& outgoingNode)
{
MStatus status;
MPlug outMeshPlug;
outMeshPlug = MayaUtils::getOutPlug(node, status);
if (outMeshPlug.isConnected())
{
MPlugArray tempPlugArray;
outMeshPlug.connectedTo(tempPlugArray, false, true);
MPlug downStreamNodeSrcPlug = tempPlugArray[0];
outgoingNode.setObject(downStreamNodeSrcPlug.node());
return MStatus::kSuccess;
}
return status;
}
MPlug MayaUtils::getInPlug(MFnDependencyNode& node, MStatus& status)
{
MPlug in = node.findPlug("inputPolymesh", &status);
// if it doesnt have that plug try this one
if (status != MStatus::kSuccess)
{
in = node.findPlug("inMesh", &status);
}
return in;
}
MPlug MayaUtils::getOutPlug(MFnDependencyNode& node, MStatus &status)
{
return node.findPlug("output", &status);
}<commit_msg>removed vert merge thing<commit_after>#include "mayaUtils.h"
#include <maya/MSelectionList.h>
#include <maya/MUuid.h>
#include <maya/MPlug.h>
#include <maya/MPlugArray.h>
MayaUtils::MayaUtils()
{
}
MayaUtils::~MayaUtils()
{
}
bool MayaUtils::isValidNodeType(MString& _type)
{
return (_type == MString("transform") ||
_type == MString("mesh") ||
_type == MString("polyTweak") ||
_type == MString("polyExtrudeFace") ||
_type == MString("polySplitRing") ||
_type == MString("polyCube"));
}
bool MayaUtils::DoesItRequireConnections(MString& _type)
{
return (_type == MString("polyTweak") ||
_type == MString("polySplitRing") ||
_type == MString("polyExtrudeFace"));
}
MStatus MayaUtils::getNodeObjectFromUUID(MString& uuid, MObject& _node)
{
// get node
MSelectionList sList;
MUuid ID(uuid);
sList.add(ID);
return sList.getDependNode(0, _node);
}
bool MayaUtils::doesItExist(std::string& _id)
{
MStatus status;
MSelectionList selList;
MUuid id(_id.c_str());
status = selList.add(id);
return (status == MStatus::kSuccess);
}
MStatus MayaUtils::getIncomingNodeObject(MFnDependencyNode& node, MFnDependencyNode& incomingNode)
{
MStatus status;
MPlug inMeshPlug;
inMeshPlug = MayaUtils::getInPlug(node, status);
if (inMeshPlug.isConnected())
{
MPlugArray tempPlugArray;
inMeshPlug.connectedTo(tempPlugArray, true, false);
// Only one connection should exist on meshNodeShape.inMesh!
MPlug upstreamNodeSrcPlug = tempPlugArray[0];
incomingNode.setObject(upstreamNodeSrcPlug.node());
return MStatus::kSuccess;
}
return status;
}
MStatus MayaUtils::getOutgoingNodeObject(MFnDependencyNode& node, MFnDependencyNode& outgoingNode)
{
MStatus status;
MPlug outMeshPlug;
outMeshPlug = MayaUtils::getOutPlug(node, status);
if (outMeshPlug.isConnected())
{
MPlugArray tempPlugArray;
outMeshPlug.connectedTo(tempPlugArray, false, true);
MPlug downStreamNodeSrcPlug = tempPlugArray[0];
outgoingNode.setObject(downStreamNodeSrcPlug.node());
return MStatus::kSuccess;
}
return status;
}
MPlug MayaUtils::getInPlug(MFnDependencyNode& node, MStatus& status)
{
MPlug in = node.findPlug("inputPolymesh", &status);
// if it doesnt have that plug try this one
if (status != MStatus::kSuccess)
{
in = node.findPlug("inMesh", &status);
}
return in;
}
MPlug MayaUtils::getOutPlug(MFnDependencyNode& node, MStatus &status)
{
return node.findPlug("output", &status);
}<|endoftext|>
|
<commit_before>#pragma ident "$Id: Rinex3NavFilterOperators.hpp 70 2006-08-01 18:36:21Z ehagen $"
/**
* @file Rinex3NavFilterOperators.hpp
* Operators for FileFilter using Rinex navigation data
*/
#ifndef GPSTK_RINEXNAVFILTEROPERATORS_HPP
#define GPSTK_RINEXNAVFILTEROPERATORS_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "FileFilter.hpp"
#include "Rinex3NavData.hpp"
#include "Rinex3NavHeader.hpp"
#include "GPSWeekSecond.hpp"
#include <set>
namespace gpstk
{
/** @addtogroup Rinex3Nav */
//@{
/// This compares all elements of the Rinex3NavData with less than.
struct Rinex3NavDataOperatorLessThanFull :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
gpstk::GPSWeekSecond lXmitTime(0.L);
lXmitTime.setGPSfullweek(l.weeknum, (double)l.HOWtime);
gpstk::GPSWeekSecond rXmitTime(0.L);
rXmitTime.setGPSfullweek(r.weeknum, (double)r.HOWtime);
if (lXmitTime < rXmitTime)
return true;
else if (lXmitTime == rXmitTime)
{
// compare the times and all data members
if (l.time < r.time)
return true;
else if (l.time == r.time)
{
std::list<double>
llist = l.toList(),
rlist = r.toList();
std::list<double>::iterator
litr = llist.begin(),
ritr = rlist.begin();
while (litr != llist.end())
{
if (*litr < *ritr)
return true;
else if (*litr > *ritr)
return false;
else
{
litr++;
ritr++;
}
}
}
} // if (lXmitTime == rXmitTime)
return false;
}
};
/// This compares all elements of the Rinex3NavData with equals
struct Rinex3NavDataOperatorEqualsFull :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
// compare the times and all data members
if (l.time != r.time)
return false;
else // if (l.time == r.time)
{
std::list<double>
llist = l.toList(),
rlist = r.toList();
std::list<double>::iterator
litr = llist.begin(),
ritr = rlist.begin();
while (litr != llist.end())
{
if (*litr != *ritr)
return false;
litr++;
ritr++;
}
}
return true;
}
};
/// Only compares time. Suitable for sorting a Rinex3Nav file.
struct Rinex3NavDataOperatorLessThanSimple :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
gpstk::GPSWeekSecond lXmitTime(0.L);
lXmitTime.setGPSfullweek(l.weeknum, (double)l.HOWtime);
gpstk::GPSWeekSecond rXmitTime(0.L);
rXmitTime.setGPSfullweek(r.weeknum, (double)r.HOWtime);
if (lXmitTime < rXmitTime)
return true;
return false;
}
};
/// Combines Rinex3NavHeaders into a single header, combining comments
/// This assumes that
/// all the headers come from the same station for setting the other
/// header fields. After running touch() on a list of Rinex3NavHeader,
/// the internal theHeader will be the merged header data for
/// those files.
struct Rinex3NavHeaderTouchHeaderMerge :
public std::unary_function<gpstk::Rinex3NavHeader, bool>
{
public:
Rinex3NavHeaderTouchHeaderMerge()
: firstHeader(true)
{}
bool operator()(const gpstk::Rinex3NavHeader& l)
{
if (firstHeader)
{
theHeader = l;
firstHeader = false;
}
else
{
std::set<std::string> commentSet;
// insert the comments to the set
// and let the set take care of uniqueness
copy(theHeader.commentList.begin(),
theHeader.commentList.end(),
inserter(commentSet, commentSet.begin()));
copy(l.commentList.begin(),
l.commentList.end(),
inserter(commentSet, commentSet.begin()));
// then copy the comments back into theHeader
theHeader.commentList.clear();
copy(commentSet.begin(), commentSet.end(),
inserter(theHeader.commentList,
theHeader.commentList.begin()));
}
return true;
}
bool firstHeader;
gpstk::Rinex3NavHeader theHeader;
};
/// Filter based on PRN ID.
struct Rinex3NavDataFilterPRN :
public std::unary_function<gpstk::Rinex3NavData, bool>
{
public:
Rinex3NavDataFilterPRN(const std::list<long>& lst )
:prnList(lst)
{}
/// This should return true when the data are to be erased
bool operator()(const gpstk::Rinex3NavData& l) const
{
long testValue = (long) l.PRNID;
return find(prnList.begin(), prnList.end(), testValue )
== prnList.end();
}
private:
std::list<long> prnList;
};
//@}
}
#endif
<commit_msg>Simplified constructor call. -DR<commit_after>#pragma ident "$Id: Rinex3NavFilterOperators.hpp 70 2006-08-01 18:36:21Z ehagen $"
/**
* @file Rinex3NavFilterOperators.hpp
* Operators for FileFilter using Rinex navigation data
*/
#ifndef GPSTK_RINEXNAVFILTEROPERATORS_HPP
#define GPSTK_RINEXNAVFILTEROPERATORS_HPP
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "FileFilter.hpp"
#include "Rinex3NavData.hpp"
#include "Rinex3NavHeader.hpp"
#include "GPSWeekSecond.hpp"
#include <set>
namespace gpstk
{
/** @addtogroup Rinex3Nav */
//@{
/// This compares all elements of the Rinex3NavData with less than.
struct Rinex3NavDataOperatorLessThanFull :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
gpstk::GPSWeekSecond lXmitTime(l.weeknum, (double)l.HOWtime);
gpstk::GPSWeekSecond rXmitTime(r.weeknum, (double)r.HOWtime);
if (lXmitTime < rXmitTime)
return true;
else if (lXmitTime == rXmitTime)
{
// compare the times and all data members
if (l.time < r.time)
return true;
else if (l.time == r.time)
{
std::list<double>
llist = l.toList(),
rlist = r.toList();
std::list<double>::iterator
litr = llist.begin(),
ritr = rlist.begin();
while (litr != llist.end())
{
if (*litr < *ritr)
return true;
else if (*litr > *ritr)
return false;
else
{
litr++;
ritr++;
}
}
}
} // if (lXmitTime == rXmitTime)
return false;
}
};
/// This compares all elements of the Rinex3NavData with equals
struct Rinex3NavDataOperatorEqualsFull :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
// compare the times and all data members
if (l.time != r.time)
return false;
else // if (l.time == r.time)
{
std::list<double>
llist = l.toList(),
rlist = r.toList();
std::list<double>::iterator
litr = llist.begin(),
ritr = rlist.begin();
while (litr != llist.end())
{
if (*litr != *ritr)
return false;
litr++;
ritr++;
}
}
return true;
}
};
/// Only compares time. Suitable for sorting a Rinex3Nav file.
struct Rinex3NavDataOperatorLessThanSimple :
public std::binary_function<gpstk::Rinex3NavData,
gpstk::Rinex3NavData, bool>
{
public:
bool operator()(const gpstk::Rinex3NavData& l,
const gpstk::Rinex3NavData& r) const
{
gpstk::GPSWeekSecond lXmitTime(l.weeknum, (double)l.HOWtime);
gpstk::GPSWeekSecond rXmitTime(r.weeknum, (double)r.HOWtime);
if (lXmitTime < rXmitTime)
return true;
return false;
}
};
/// Combines Rinex3NavHeaders into a single header, combining comments
/// This assumes that
/// all the headers come from the same station for setting the other
/// header fields. After running touch() on a list of Rinex3NavHeader,
/// the internal theHeader will be the merged header data for
/// those files.
struct Rinex3NavHeaderTouchHeaderMerge :
public std::unary_function<gpstk::Rinex3NavHeader, bool>
{
public:
Rinex3NavHeaderTouchHeaderMerge()
: firstHeader(true)
{}
bool operator()(const gpstk::Rinex3NavHeader& l)
{
if (firstHeader)
{
theHeader = l;
firstHeader = false;
}
else
{
std::set<std::string> commentSet;
// insert the comments to the set
// and let the set take care of uniqueness
copy(theHeader.commentList.begin(),
theHeader.commentList.end(),
inserter(commentSet, commentSet.begin()));
copy(l.commentList.begin(),
l.commentList.end(),
inserter(commentSet, commentSet.begin()));
// then copy the comments back into theHeader
theHeader.commentList.clear();
copy(commentSet.begin(), commentSet.end(),
inserter(theHeader.commentList,
theHeader.commentList.begin()));
}
return true;
}
bool firstHeader;
gpstk::Rinex3NavHeader theHeader;
};
/// Filter based on PRN ID.
struct Rinex3NavDataFilterPRN :
public std::unary_function<gpstk::Rinex3NavData, bool>
{
public:
Rinex3NavDataFilterPRN(const std::list<long>& lst )
:prnList(lst)
{}
/// This should return true when the data are to be erased
bool operator()(const gpstk::Rinex3NavData& l) const
{
long testValue = (long) l.PRNID;
return find(prnList.begin(), prnList.end(), testValue )
== prnList.end();
}
private:
std::list<long> prnList;
};
//@}
}
#endif
<|endoftext|>
|
<commit_before>//Standard library
#include <iostream>
//External includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
//Local headers
#include "ChunkManager.h"
#include "Types.h"
#include "ShaderCache.h"
#include "Camera.h"
#include "RenderingContext.h"
#include "LightSource.h"
#include "ModelCache.h"
#include "Model.h"
#include "TextureCache.h"
#include "Texture.h"
#include <vector>
#include "FreeCameraController.h"
GLFWwindow* initGLFW();
void update(float32 deltaSeconds);
void render();
// Test cube, will be removed later
#include "Primitives.h"
void initTestCube();
ShaderProgram* cubeShader = nullptr;
Model* cubeModel = nullptr;
Texture* cubeTexture = nullptr;
glm::vec3 playerPosition(0, 160, 2);
ShaderProgram* chunkShader = nullptr;
Texture* chunkTexture = nullptr;
GLFWwindow* gWindow = nullptr;
FreeCameraController* gCameraController;
int main() {
try {
// Initialize GLFW
gWindow = initGLFW();
RenderingContext::init();
chunkShader = RenderingContext::get()->shaderCache.loadShaderProgram("chunk_shader", "chunk_vert.glsl", "chunk_frag.glsl");
chunkTexture = RenderingContext::get()->textureCache.loadTexture2DArray("texture_shader", 7, "tiles.png");
initTestCube();
}
catch (std::runtime_error& ex) {
std::cout << ex.what() << std::endl;
system("pause");
return 1;
}
ChunkManager::instance()->loadChunks(playerPosition);
gCameraController = new FreeCameraController(&RenderingContext::get()->camera);
RenderingContext::get()->camera.transform.translateLocal(0,160,2);
RenderingContext::get()->camera.transform.orient(glm::degrees(-0.0f), 0, 0);
// Load face data for shader
std::vector<glm::vec3> faceData;
faceData.push_back(glm::vec3(1, 0, 2)); // Grass
faceData.push_back(glm::vec3(3, 3, 3)); // Log
faceData.push_back(glm::vec3(4, 4, 4)); // Leaves
faceData.push_back(glm::vec3(2, 2, 2)); // Dirt
faceData.push_back(glm::vec3(5, 5, 5)); // Sand
faceData.push_back(glm::vec3(6, 6, 6)); // Snow
chunkShader->use();
chunkShader->setUniform("faceData", faceData);
glm::vec3 lightDirection(-0.80f, -0.5f, 0.0f);
glm::vec3 lightColor(1.0f, 1.0f, 1.0f);
LightSource sun(lightDirection, lightColor, 0.5f, 0.25f);
chunkShader->use();
chunkShader->setUniform("lightColor", sun.getColor());
chunkShader->setUniform("lightDirection", sun.getDirection());
chunkShader->setUniform("ambientStrength", sun.getAmbStrength());
chunkShader->setUniform("specularStrength", sun.getSpecStrength());
// Start loop
uint32 frames = 0;
float64 counter = 0;
float64 delta = 0;
float64 currentTime = 0;
while (!glfwWindowShouldClose(gWindow)) {
glfwPollEvents();
currentTime = glfwGetTime();
update((float32)delta);
render();
glfwSwapBuffers(gWindow);
delta = glfwGetTime() - currentTime;
counter += delta;
if (counter >= 1) {
counter = 0;
std::cout << "FPS: " << frames << std::endl;
frames = 0;
}
else {
frames++;
}
}
delete gCameraController;
RenderingContext::destroy();
glfwTerminate();
return 0;
}
GLFWwindow* initGLFW() {
if (!glfwInit()) {
throw std::runtime_error("Error: failed to initialize GLFW.");
}
glfwDefaultWindowHints();
// 8x MSAA
glfwWindowHint(GLFW_SAMPLES, 8);
GLFWwindow* window = glfwCreateWindow(640, 480, "Final Project", nullptr, nullptr);
if (!window) {
glfwTerminate();
throw std::runtime_error("Error: failed to initialize window.");
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwSetWindowSizeCallback(window, [](GLFWwindow* window, int32 width, int32 height) -> void { glViewport(0, 0, width, height); });
return window;
}
void update(float32 deltaSeconds) {
// Update logic...
gCameraController->update(deltaSeconds);
const Transform& playerTransform = RenderingContext::get()->camera.transform;
glm::vec3 playerPos(playerTransform.xPos, playerTransform.yPos, playerTransform.zPos);
glm::vec3 currentChunk = ChunkManager::instance()->getCurrentChunk(playerPos);
// Spooky hack lol
static glm::vec3 lastChunk(currentChunk.x + 1.0f, currentChunk.y, currentChunk.z);
if (currentChunk != lastChunk) {
ChunkManager::instance()->loadChunks(currentChunk);
lastChunk = currentChunk;
}
ChunkManager::instance()->uploadQueuedChunk();
chunkShader->use();
chunkShader->setUniform("viewPos", playerPos);
}
void render() {
RenderingContext::get()->prepareFrame();
// Render chunks
chunkShader->use();
chunkShader->setUniform("vpMatrix", RenderingContext::get()->camera.getViewProjectionMatrix());
chunkTexture->bind(Texture::UNIT_0);
const std::unordered_map<int64, Chunk>& chunks = ChunkManager::instance()->getCurrentlyLoadedChunks();
for (const auto& chunk : chunks) {
glBindVertexArray(chunk.second.getVao());
glDrawElementsInstanced(GL_TRIANGLES, cube::numIndices, GL_UNSIGNED_INT, nullptr, chunk.second.getBlockCount());
}
// Render test cube
cubeShader->use();
cubeModel->bind();
cubeShader->setUniform("mvpMatrix", RenderingContext::get()->camera.getViewProjectionMatrix());
cubeShader->setUniform("color", glm::vec3(1, 0, 0));
glDrawElements(GL_TRIANGLES, cubeModel->getCount(), GL_UNSIGNED_INT, nullptr);
}
void initTestCube() {
std::vector<float32> vertices;
std::vector<float32> uvCoords;
std::vector<float32> normals;
std::vector<uint32> indices;
cube::fill(vertices, uvCoords, normals, indices);
cubeModel = RenderingContext::get()->modelCache.loadModel("cube", vertices, indices);
cubeShader = RenderingContext::get()->shaderCache.loadShaderProgram("test_cube", "test_cube_vert.glsl", "test_cube_frag.glsl");
cubeTexture = RenderingContext::get()->textureCache.loadTexture2D("test_cube_texture", "test.png");
}
glm::vec2 getMouseAxis() {
// Poll mouse position
float64 mPosX;
float64 mPosY;
glfwGetCursorPos(gWindow, &mPosX, &mPosY);
static float64 lastMousePosX = mPosX;
static float64 lastMousePosY = mPosY;
glm::vec2 mouseAxis(0, 0);
if (mPosX != lastMousePosX || mPosY != lastMousePosY) {
mouseAxis.x = mPosX - lastMousePosX;
mouseAxis.y = lastMousePosY - mPosY;
}
lastMousePosX = mPosX;
lastMousePosY = mPosY;
return mouseAxis;
}
<commit_msg>ChunkManager fix. First pass was garbage values.<commit_after>//Standard library
#include <iostream>
//External includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
//Local headers
#include "ChunkManager.h"
#include "Types.h"
#include "ShaderCache.h"
#include "Camera.h"
#include "RenderingContext.h"
#include "LightSource.h"
#include "ModelCache.h"
#include "Model.h"
#include "TextureCache.h"
#include "Texture.h"
#include <vector>
#include "FreeCameraController.h"
GLFWwindow* initGLFW();
void update(float32 deltaSeconds);
void render();
// Test cube, will be removed later
#include "Primitives.h"
void initTestCube();
ShaderProgram* cubeShader = nullptr;
Model* cubeModel = nullptr;
Texture* cubeTexture = nullptr;
glm::vec3 playerPosition(0, 160, 2);
ShaderProgram* chunkShader = nullptr;
Texture* chunkTexture = nullptr;
GLFWwindow* gWindow = nullptr;
FreeCameraController* gCameraController;
int main() {
try {
// Initialize GLFW
gWindow = initGLFW();
RenderingContext::init();
chunkShader = RenderingContext::get()->shaderCache.loadShaderProgram("chunk_shader", "chunk_vert.glsl", "chunk_frag.glsl");
chunkTexture = RenderingContext::get()->textureCache.loadTexture2DArray("texture_shader", 7, "tiles.png");
initTestCube();
}
catch (std::runtime_error& ex) {
std::cout << ex.what() << std::endl;
system("pause");
return 1;
}
gCameraController = new FreeCameraController(&RenderingContext::get()->camera);
RenderingContext::get()->camera.transform.translateLocal(0,160,2);
RenderingContext::get()->camera.transform.orient(glm::degrees(-0.0f), 0, 0);
// Load face data for shader
std::vector<glm::vec3> faceData;
faceData.push_back(glm::vec3(1, 0, 2)); // Grass
faceData.push_back(glm::vec3(3, 3, 3)); // Log
faceData.push_back(glm::vec3(4, 4, 4)); // Leaves
faceData.push_back(glm::vec3(2, 2, 2)); // Dirt
faceData.push_back(glm::vec3(5, 5, 5)); // Sand
faceData.push_back(glm::vec3(6, 6, 6)); // Snow
chunkShader->use();
chunkShader->setUniform("faceData", faceData);
glm::vec3 lightDirection(-0.80f, -0.5f, 0.0f);
glm::vec3 lightColor(1.0f, 1.0f, 1.0f);
LightSource sun(lightDirection, lightColor, 0.5f, 0.25f);
chunkShader->use();
chunkShader->setUniform("lightColor", sun.getColor());
chunkShader->setUniform("lightDirection", sun.getDirection());
chunkShader->setUniform("ambientStrength", sun.getAmbStrength());
chunkShader->setUniform("specularStrength", sun.getSpecStrength());
// Start loop
uint32 frames = 0;
float64 counter = 0;
float64 delta = 0;
float64 currentTime = 0;
while (!glfwWindowShouldClose(gWindow)) {
glfwPollEvents();
currentTime = glfwGetTime();
update((float32)delta);
render();
glfwSwapBuffers(gWindow);
delta = glfwGetTime() - currentTime;
counter += delta;
if (counter >= 1) {
counter = 0;
std::cout << "FPS: " << frames << std::endl;
frames = 0;
}
else {
frames++;
}
}
delete gCameraController;
RenderingContext::destroy();
glfwTerminate();
return 0;
}
GLFWwindow* initGLFW() {
if (!glfwInit()) {
throw std::runtime_error("Error: failed to initialize GLFW.");
}
glfwDefaultWindowHints();
// 8x MSAA
glfwWindowHint(GLFW_SAMPLES, 8);
GLFWwindow* window = glfwCreateWindow(640, 480, "Final Project", nullptr, nullptr);
if (!window) {
glfwTerminate();
throw std::runtime_error("Error: failed to initialize window.");
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwSetWindowSizeCallback(window, [](GLFWwindow* window, int32 width, int32 height) -> void { glViewport(0, 0, width, height); });
return window;
}
void update(float32 deltaSeconds) {
// Update logic...
gCameraController->update(deltaSeconds);
const Transform& playerTransform = RenderingContext::get()->camera.transform;
glm::vec3 playerPos(playerTransform.xPos, playerTransform.yPos, playerTransform.zPos);
glm::vec3 currentChunk = ChunkManager::instance()->getCurrentChunk(playerPos);
// Spooky hack lol
static glm::vec3 lastChunk(currentChunk.x + 1.0f, currentChunk.y, currentChunk.z);
if (currentChunk != lastChunk) {
ChunkManager::instance()->loadChunks(currentChunk);
lastChunk = currentChunk;
}
ChunkManager::instance()->uploadQueuedChunk();
chunkShader->use();
chunkShader->setUniform("viewPos", playerPos);
}
void render() {
RenderingContext::get()->prepareFrame();
// Render chunks
chunkShader->use();
chunkShader->setUniform("vpMatrix", RenderingContext::get()->camera.getViewProjectionMatrix());
chunkTexture->bind(Texture::UNIT_0);
const std::unordered_map<int64, Chunk>& chunks = ChunkManager::instance()->getCurrentlyLoadedChunks();
for (const auto& chunk : chunks) {
glBindVertexArray(chunk.second.getVao());
glDrawElementsInstanced(GL_TRIANGLES, cube::numIndices, GL_UNSIGNED_INT, nullptr, chunk.second.getBlockCount());
}
// Render test cube
cubeShader->use();
cubeModel->bind();
cubeShader->setUniform("mvpMatrix", RenderingContext::get()->camera.getViewProjectionMatrix());
cubeShader->setUniform("color", glm::vec3(1, 0, 0));
glDrawElements(GL_TRIANGLES, cubeModel->getCount(), GL_UNSIGNED_INT, nullptr);
}
void initTestCube() {
std::vector<float32> vertices;
std::vector<float32> uvCoords;
std::vector<float32> normals;
std::vector<uint32> indices;
cube::fill(vertices, uvCoords, normals, indices);
cubeModel = RenderingContext::get()->modelCache.loadModel("cube", vertices, indices);
cubeShader = RenderingContext::get()->shaderCache.loadShaderProgram("test_cube", "test_cube_vert.glsl", "test_cube_frag.glsl");
cubeTexture = RenderingContext::get()->textureCache.loadTexture2D("test_cube_texture", "test.png");
}
glm::vec2 getMouseAxis() {
// Poll mouse position
float64 mPosX;
float64 mPosY;
glfwGetCursorPos(gWindow, &mPosX, &mPosY);
static float64 lastMousePosX = mPosX;
static float64 lastMousePosY = mPosY;
glm::vec2 mouseAxis(0, 0);
if (mPosX != lastMousePosX || mPosY != lastMousePosY) {
mouseAxis.x = mPosX - lastMousePosX;
mouseAxis.y = lastMousePosY - mPosY;
}
lastMousePosX = mPosX;
lastMousePosY = mPosY;
return mouseAxis;
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file HanjaDic.cxx
** Korean Hanja Dictionary
** Convert between Korean Hanja and Hangul by COM interface.
**/
// Copyright 2015 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <windows.h>
#include "UniConversion.h"
#include "HanjaDic.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
namespace HanjaDict {
interface IRadical;
interface IHanja;
interface IStrokes;
typedef enum { HANJA_UNKNOWN = 0, HANJA_K0 = 1, HANJA_K1 = 2, HANJA_OTHER = 3 } HANJA_TYPE;
interface IHanjaDic : IUnknown {
STDMETHOD(OpenMainDic)();
STDMETHOD(CloseMainDic)();
STDMETHOD(GetHanjaWords)(BSTR bstrHangul, SAFEARRAY* ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(GetHanjaChars)(unsigned short wchHangul, BSTR* pbstrHanjaChars, VARIANT_BOOL* pfFound);
STDMETHOD(HanjaToHangul)(BSTR bstrHanja, BSTR* pbstrHangul);
STDMETHOD(GetHanjaType)(unsigned short wchHanja, HANJA_TYPE* pHanjaType);
STDMETHOD(GetHanjaSense)(unsigned short wchHanja, BSTR* pbstrSense);
STDMETHOD(GetRadicalID)(short SeqNumOfRadical, short* pRadicalID, unsigned short* pwchRadical);
STDMETHOD(GetRadical)(short nRadicalID, IRadical** ppIRadical);
STDMETHOD(RadicalIDToHanja)(short nRadicalID, unsigned short* pwchRadical);
STDMETHOD(GetHanja)(unsigned short wchHanja, IHanja** ppIHanja);
STDMETHOD(GetStrokes)(short nStrokes, IStrokes** ppIStrokes);
STDMETHOD(OpenDefaultCustomDic)();
STDMETHOD(OpenCustomDic)(BSTR bstrPath, long* plUdr);
STDMETHOD(CloseDefaultCustomDic)();
STDMETHOD(CloseCustomDic)(long lUdr);
STDMETHOD(CloseAllCustomDics)();
STDMETHOD(GetDefaultCustomHanjaWords)(BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(GetCustomHanjaWords)(long lUdr, BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(PutDefaultCustomHanjaWord)(BSTR bstrHangul, BSTR bstrHanja);
STDMETHOD(PutCustomHanjaWord)(long lUdr, BSTR bstrHangul, BSTR bstrHanja);
STDMETHOD(MaxNumOfRadicals)(short* pVal);
STDMETHOD(MaxNumOfStrokes)(short* pVal);
STDMETHOD(DefaultCustomDic)(long* pVal);
STDMETHOD(DefaultCustomDic)(long pVal);
STDMETHOD(MaxHanjaType)(HANJA_TYPE* pHanjaType);
STDMETHOD(MaxHanjaType)(HANJA_TYPE pHanjaType);
};
extern "C" const GUID __declspec(selectany) IID_IHanjaDic =
{ 0xad75f3ac, 0x18cd, 0x48c6, { 0xa2, 0x7d, 0xf1, 0xe9, 0xa7, 0xdc, 0xe4, 0x32 } };
class HanjaDic {
private:
HRESULT hr;
CLSID CLSID_HanjaDic;
public:
IHanjaDic *HJinterface;
HanjaDic() {
hr = CLSIDFromProgID(OLESTR("mshjdic.hanjadic"), &CLSID_HanjaDic);
if (SUCCEEDED(hr)) {
hr = CoCreateInstance(CLSID_HanjaDic, NULL,
CLSCTX_INPROC_SERVER, IID_IHanjaDic,
(LPVOID *)& HJinterface);
if (SUCCEEDED(hr)) {
hr = HJinterface->OpenMainDic();
}
}
}
~HanjaDic() {
if (SUCCEEDED(hr)) {
hr = HJinterface->CloseMainDic();
HJinterface->Release();
}
}
bool HJdictAvailable() {
return SUCCEEDED(hr);
}
bool IsHanja(int hanja) {
HANJA_TYPE hanjaType;
hr = HJinterface->GetHanjaType(static_cast<unsigned short>(hanja), &hanjaType);
if (SUCCEEDED(hr)) {
return (hanjaType > 0);
}
return false;
}
};
int GetHangulOfHanja(int hanjaChar) {
// Convert hanja character to hangul one.
int hangulChar = -1; // If fails, return -1.
HanjaDic dict;
if (!dict.HJdictAvailable() || !dict.IsHanja(hanjaChar)) {
return hangulChar;
}
wchar_t convHnja[UTF8MaxBytes] = {0};
convHnja[0] = static_cast<wchar_t>(hanjaChar);
BSTR bstrHangul = SysAllocString(NULL);
BSTR bstrHanja = SysAllocString(convHnja);
HRESULT hr = dict.HJinterface->HanjaToHangul(bstrHanja, &bstrHangul);
if (SUCCEEDED(hr)) {
wchar_t wHangul = static_cast<wchar_t *>(bstrHangul)[0];
hangulChar = static_cast<int>(wHangul);
}
SysFreeString(bstrHangul);
SysFreeString(bstrHanja);
return hangulChar;
}
}
<commit_msg>Avoid warnings about uninitialised field.<commit_after>// Scintilla source code edit control
/** @file HanjaDic.cxx
** Korean Hanja Dictionary
** Convert between Korean Hanja and Hangul by COM interface.
**/
// Copyright 2015 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <windows.h>
#include "UniConversion.h"
#include "HanjaDic.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
namespace HanjaDict {
interface IRadical;
interface IHanja;
interface IStrokes;
typedef enum { HANJA_UNKNOWN = 0, HANJA_K0 = 1, HANJA_K1 = 2, HANJA_OTHER = 3 } HANJA_TYPE;
interface IHanjaDic : IUnknown {
STDMETHOD(OpenMainDic)();
STDMETHOD(CloseMainDic)();
STDMETHOD(GetHanjaWords)(BSTR bstrHangul, SAFEARRAY* ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(GetHanjaChars)(unsigned short wchHangul, BSTR* pbstrHanjaChars, VARIANT_BOOL* pfFound);
STDMETHOD(HanjaToHangul)(BSTR bstrHanja, BSTR* pbstrHangul);
STDMETHOD(GetHanjaType)(unsigned short wchHanja, HANJA_TYPE* pHanjaType);
STDMETHOD(GetHanjaSense)(unsigned short wchHanja, BSTR* pbstrSense);
STDMETHOD(GetRadicalID)(short SeqNumOfRadical, short* pRadicalID, unsigned short* pwchRadical);
STDMETHOD(GetRadical)(short nRadicalID, IRadical** ppIRadical);
STDMETHOD(RadicalIDToHanja)(short nRadicalID, unsigned short* pwchRadical);
STDMETHOD(GetHanja)(unsigned short wchHanja, IHanja** ppIHanja);
STDMETHOD(GetStrokes)(short nStrokes, IStrokes** ppIStrokes);
STDMETHOD(OpenDefaultCustomDic)();
STDMETHOD(OpenCustomDic)(BSTR bstrPath, long* plUdr);
STDMETHOD(CloseDefaultCustomDic)();
STDMETHOD(CloseCustomDic)(long lUdr);
STDMETHOD(CloseAllCustomDics)();
STDMETHOD(GetDefaultCustomHanjaWords)(BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(GetCustomHanjaWords)(long lUdr, BSTR bstrHangul, SAFEARRAY** ppsaHanja, VARIANT_BOOL* pfFound);
STDMETHOD(PutDefaultCustomHanjaWord)(BSTR bstrHangul, BSTR bstrHanja);
STDMETHOD(PutCustomHanjaWord)(long lUdr, BSTR bstrHangul, BSTR bstrHanja);
STDMETHOD(MaxNumOfRadicals)(short* pVal);
STDMETHOD(MaxNumOfStrokes)(short* pVal);
STDMETHOD(DefaultCustomDic)(long* pVal);
STDMETHOD(DefaultCustomDic)(long pVal);
STDMETHOD(MaxHanjaType)(HANJA_TYPE* pHanjaType);
STDMETHOD(MaxHanjaType)(HANJA_TYPE pHanjaType);
};
extern "C" const GUID __declspec(selectany) IID_IHanjaDic =
{ 0xad75f3ac, 0x18cd, 0x48c6, { 0xa2, 0x7d, 0xf1, 0xe9, 0xa7, 0xdc, 0xe4, 0x32 } };
class HanjaDic {
private:
HRESULT hr;
CLSID CLSID_HanjaDic;
public:
IHanjaDic *HJinterface;
HanjaDic() : HJinterface(NULL) {
hr = CLSIDFromProgID(OLESTR("mshjdic.hanjadic"), &CLSID_HanjaDic);
if (SUCCEEDED(hr)) {
hr = CoCreateInstance(CLSID_HanjaDic, NULL,
CLSCTX_INPROC_SERVER, IID_IHanjaDic,
(LPVOID *)& HJinterface);
if (SUCCEEDED(hr)) {
hr = HJinterface->OpenMainDic();
}
}
}
~HanjaDic() {
if (SUCCEEDED(hr)) {
hr = HJinterface->CloseMainDic();
HJinterface->Release();
}
}
bool HJdictAvailable() {
return SUCCEEDED(hr);
}
bool IsHanja(int hanja) {
HANJA_TYPE hanjaType;
hr = HJinterface->GetHanjaType(static_cast<unsigned short>(hanja), &hanjaType);
if (SUCCEEDED(hr)) {
return (hanjaType > 0);
}
return false;
}
};
int GetHangulOfHanja(int hanjaChar) {
// Convert hanja character to hangul one.
int hangulChar = -1; // If fails, return -1.
HanjaDic dict;
if (!dict.HJdictAvailable() || !dict.IsHanja(hanjaChar)) {
return hangulChar;
}
wchar_t convHnja[UTF8MaxBytes] = {0};
convHnja[0] = static_cast<wchar_t>(hanjaChar);
BSTR bstrHangul = SysAllocString(NULL);
BSTR bstrHanja = SysAllocString(convHnja);
HRESULT hr = dict.HJinterface->HanjaToHangul(bstrHanja, &bstrHangul);
if (SUCCEEDED(hr)) {
wchar_t wHangul = static_cast<wchar_t *>(bstrHangul)[0];
hangulChar = static_cast<int>(wHangul);
}
SysFreeString(bstrHangul);
SysFreeString(bstrHanja);
return hangulChar;
}
}
<|endoftext|>
|
<commit_before>// Copyright 2008 Paul Hodge
#include "common_headers.h"
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_opengl.h>
#include <circa.h>
#include "textures.h"
using namespace circa;
GLenum get_texture_format(SDL_Surface *surface)
{
assert(surface);
int nColors = surface->format->BytesPerPixel;
if (nColors == 4) {
// contains alpha channel
if (surface->format->Rmask == 0x000000ff) {
return GL_RGBA;
} else {
return GL_BGRA;
}
} else if (nColors == 3) {
// no alpha channel
if (surface->format->Rmask == 0x000000ff) {
return GL_RGB;
} else {
return GL_BGR;
}
} else {
std::cout << "warning: get_texture_format failed, nColors = " << nColors << std::endl;
return GL_RGBA;
}
}
GLuint load_image_to_texture(std::string const& filename, Term* errorListener)
{
SDL_Surface* surface = IMG_Load(filename.c_str());
if (surface == NULL) {
error_occurred(errorListener, "Error loading " + filename + ": " + SDL_GetError());
return 0;
}
GLuint texid = load_surface_to_texture(surface);
SDL_FreeSurface(surface);
return texid;
}
GLuint load_surface_to_texture(SDL_Surface *surface)
{
GLuint texid;
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel,
surface->w, surface->h, 0,
get_texture_format(surface), GL_UNSIGNED_BYTE, surface->pixels);
return texid;
}
namespace textures {
void hosted_load_texture(Term* caller)
{
if (as_int(caller) == 0) {
std::string filename = as_string(caller->input(0));
GLuint id = load_image_to_texture(filename, caller);
as_int(caller) = id;
}
}
void hosted_draw_image(Term* caller)
{
int& texid = caller->input(0)->asInt();
std::string filename = caller->input(1)->asString();
float x1 = caller->input(2)->toFloat();
float y1 = caller->input(3)->toFloat();
float x2 = caller->input(4)->toFloat();
float y2 = caller->input(5)->toFloat();
if (texid == 0) {
texid = load_image_to_texture(filename, caller);
if (caller->hasError) return;
}
glBindTexture(GL_TEXTURE_2D, texid);
glColor4f(1,1,1,1);
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex3f(x1, y1, 0);
glTexCoord2d(1.0, 0.0);
glVertex3f(x2, y1,0);
glTexCoord2d(1.0, 1.0);
glVertex3f(x2, y2,0);
glTexCoord2d(0.0, 1.0);
glVertex3f(x1, y2,0);
glEnd();
}
void register_functions(circa::Branch& branch)
{
import_function(branch, hosted_load_texture, "load_texture(string) : int");
import_function(branch, hosted_draw_image,
"draw_image(state int texid, string filename, float,float,float,float)");
}
} // namespace textures
<commit_msg>Cuttlefish: change names to be more declarative, draw_image() -> image()<commit_after>// Copyright 2008 Paul Hodge
#include "common_headers.h"
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_opengl.h>
#include <circa.h>
#include "textures.h"
using namespace circa;
GLenum get_texture_format(SDL_Surface *surface)
{
assert(surface);
int nColors = surface->format->BytesPerPixel;
if (nColors == 4) {
// contains alpha channel
if (surface->format->Rmask == 0x000000ff) {
return GL_RGBA;
} else {
return GL_BGRA;
}
} else if (nColors == 3) {
// no alpha channel
if (surface->format->Rmask == 0x000000ff) {
return GL_RGB;
} else {
return GL_BGR;
}
} else {
std::cout << "warning: get_texture_format failed, nColors = " << nColors << std::endl;
return GL_RGBA;
}
}
GLuint load_image_to_texture(std::string const& filename, Term* errorListener)
{
SDL_Surface* surface = IMG_Load(filename.c_str());
if (surface == NULL) {
error_occurred(errorListener, "Error loading " + filename + ": " + SDL_GetError());
return 0;
}
GLuint texid = load_surface_to_texture(surface);
SDL_FreeSurface(surface);
return texid;
}
GLuint load_surface_to_texture(SDL_Surface *surface)
{
GLuint texid;
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel,
surface->w, surface->h, 0,
get_texture_format(surface), GL_UNSIGNED_BYTE, surface->pixels);
return texid;
}
namespace textures {
void hosted_load_texture(Term* caller)
{
if (as_int(caller) == 0) {
std::string filename = as_string(caller->input(0));
GLuint id = load_image_to_texture(filename, caller);
as_int(caller) = id;
}
}
void hosted_image(Term* caller)
{
int& texid = caller->input(0)->asInt();
std::string filename = caller->input(1)->asString();
float x1 = caller->input(2)->toFloat();
float y1 = caller->input(3)->toFloat();
float x2 = caller->input(4)->toFloat();
float y2 = caller->input(5)->toFloat();
if (texid == 0) {
texid = load_image_to_texture(filename, caller);
if (caller->hasError) return;
}
glBindTexture(GL_TEXTURE_2D, texid);
glColor4f(1,1,1,1);
glBegin(GL_QUADS);
glTexCoord2d(0.0, 0.0);
glVertex3f(x1, y1, 0);
glTexCoord2d(1.0, 0.0);
glVertex3f(x2, y1,0);
glTexCoord2d(1.0, 1.0);
glVertex3f(x2, y2,0);
glTexCoord2d(0.0, 1.0);
glVertex3f(x1, y2,0);
glEnd();
}
void register_functions(circa::Branch& branch)
{
import_function(branch, hosted_load_texture, "load_texture(string) : int");
import_function(branch, hosted_image,
"image(state int texid, string filename, float,float,float,float)");
}
} // namespace textures
<|endoftext|>
|
<commit_before>//===-- StaticBinaryELF.cpp -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Parse a static ELF binary to implement lookupSymbol() address lookup.
//
//===----------------------------------------------------------------------===//
#if defined(__ELF__) && defined(__linux__)
#include "ImageInspection.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "swift/Basic/Lazy.h"
#include <cassert>
#include <string>
#include <vector>
#include <elf.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
using namespace llvm;
#ifdef __LP64__
#define ELFCLASS ELFCLASS64
typedef Elf64_Ehdr Elf_Ehdr;
typedef Elf64_Shdr Elf_Shdr;
typedef Elf64_Phdr Elf_Phdr;
typedef Elf64_Addr Elf_Addr;
typedef Elf64_Word Elf_Word;
typedef Elf64_Sym Elf_Sym;
typedef Elf64_Section Elf_Section;
#define ELF_ST_TYPE(x) ELF64_ST_TYPE(x)
#else
#define ELFCLASS ELFCLASS32
typedef Elf32_Ehdr Elf_Ehdr;
typedef Elf32_Shdr Elf_Shdr;
typedef Elf32_Phdr Elf_Phdr;
typedef Elf32_Addr Elf_Addr;
typedef Elf32_Word Elf_Word;
typedef Elf32_Sym Elf_Sym;
typedef Elf32_Section Elf_Section;
#define ELF_ST_TYPE(x) ELF32_ST_TYPE(x)
#endif
extern const Elf_Ehdr elfHeader asm("__ehdr_start");
class StaticBinaryELF {
private:
// mmap a section of a file that might not be page aligned.
class Mapping {
public:
void *mapping;
size_t mapLength;
off_t diff;
Mapping(int fd, size_t fileSize, off_t offset, size_t length) {
if (fd < 0 || offset + length > fileSize) {
mapping = nullptr;
mapLength = 0;
diff = 0;
return;
}
long pageSize = sysconf(_SC_PAGESIZE);
long pageMask = ~(pageSize - 1);
off_t alignedOffset = offset & pageMask;
diff = (offset - alignedOffset);
mapLength = diff + length;
mapping = mmap(nullptr, mapLength, PROT_READ, MAP_PRIVATE, fd,
alignedOffset);
if (mapping == MAP_FAILED) {
mapping = nullptr;
mapLength = 0;
}
}
template<typename T>
const ArrayRef<T> data() {
size_t elements = (mapLength - diff) / sizeof(T);
const T *data = reinterpret_cast<T *>(reinterpret_cast<char *>(mapping)
+ diff);
return ArrayRef<T>(data, elements);
}
~Mapping() {
if (mapping && mapLength > 0) {
munmap(mapping, mapLength);
}
}
};
string fullPathName;
const Elf_Phdr *programHeaders = nullptr;
const Elf_Shdr *symbolTable = nullptr;
const Elf_Shdr *stringTable = nullptr;
Mapping *sectionHeaders = nullptr;
Mapping *symbolTableData = nullptr;
Mapping *stringTableData = nullptr;
public:
StaticBinaryELF() {
getExecutablePathName();
programHeaders = reinterpret_cast<const Elf_Phdr *>(getauxval(AT_PHDR));
if (programHeaders == nullptr) {
return;
}
// If a interpreter is set in the program headers then this is a
// dynamic executable and therefore not valid.
for (size_t idx = 0; idx < elfHeader.e_phnum; idx++) {
if (programHeaders[idx].p_type == PT_INTERP) {
programHeaders = nullptr;
return;
}
}
if (!fullPathName.empty()) {
mmapExecutable();
}
}
~StaticBinaryELF() {
delete stringTableData;
delete symbolTableData;
delete sectionHeaders;
}
const char *getPathName() {
return fullPathName.empty() ? nullptr : fullPathName.c_str();
}
void *getSectionLoadAddress(const void *addr) {
if (programHeaders) {
auto searchAddr = reinterpret_cast<Elf_Addr>(addr);
for (size_t idx = 0; idx < elfHeader.e_phnum; idx++) {
auto header = &programHeaders[idx];
if (header->p_type == PT_LOAD && searchAddr >= header->p_vaddr
&& searchAddr <= (header->p_vaddr + header->p_memsz)) {
return reinterpret_cast<void *>(header->p_vaddr);
}
}
}
return nullptr;
}
// Lookup a function symbol by address.
const Elf_Sym *findSymbol(const void *addr) {
if (symbolTable) {
auto searchAddr = reinterpret_cast<Elf_Addr>(addr);
const ArrayRef<Elf_Sym> symbols = symbolTableData->data<Elf_Sym>();
for (size_t idx = 0; idx < symbols.size(); idx++) {
auto symbol = &symbols[idx];
if (ELF_ST_TYPE(symbol->st_info) == STT_FUNC
&& searchAddr >= symbol->st_value
&& searchAddr < (symbol->st_value + symbol->st_size)) {
return symbol;
}
}
}
return nullptr;
}
const char *symbolName(const Elf_Sym *symbol) {
if (stringTable && symbol->st_name < stringTable->sh_size) {
const ArrayRef<char> strings = stringTableData->data<char>();
return &strings[symbol->st_name];
}
return nullptr;
}
private:
// This is Linux specific - find the full path of the executable
// by looking in /proc/self/maps for a mapping holding the current
// address space. For a static binary it should only be mapping one
// file anyway. Dont use /proc/self/exe as the symlink will be removed
// if the main thread terminates - see proc(5).
void getExecutablePathName() {
uintptr_t address = (uintptr_t)&elfHeader;
FILE *fp = fopen("/proc/self/maps", "r");
if (!fp) {
perror("Unable to open /proc/self/maps");
} else {
char *line = nullptr;
size_t size = 0;
// Format is: addrLo-addrHi perms offset dev inode pathname.
// If the executable has been deleted the last column will be '(deleted)'.
StringRef deleted = StringRef("(deleted)");
while(getdelim(&line, &size, '\n', fp) != -1) {
StringRef entry = StringRef(line).rsplit('\n').first;
auto addrRange = entry.split(' ').first.split('-');
unsigned long long low = strtoull(addrRange.first.str().c_str(),
nullptr, 16);
if (low == 0 || low > UINTPTR_MAX || address < (uintptr_t)low) {
continue;
}
unsigned long long high = strtoull(addrRange.second.str().c_str(),
nullptr, 16);
if (high == 0 || high > UINTPTR_MAX || address > (uintptr_t)high) {
continue;
}
auto fname = entry.split('/').second;
if (fname.empty() || fname.endswith(deleted)) {
continue;
}
fullPathName = "/" + fname.str();
break;
}
if (line) {
free(line);
}
fclose(fp);
}
}
// Parse the ELF binary using mmap for the section headers, symbol table and
// string table.
void mmapExecutable() {
struct stat buf;
int fd = open(fullPathName.c_str(), O_RDONLY);
if (fd < 0) {
return;
}
if (fstat(fd, &buf) != 0) {
close(fd);
return;
}
// Map in the section headers.
size_t sectionHeadersSize = (elfHeader.e_shentsize * elfHeader.e_shnum);
sectionHeaders = new Mapping(fd, buf.st_size, elfHeader.e_shoff,
sectionHeadersSize);
if (sectionHeaders->mapping) {
auto section = findSectionHeader(SHT_SYMTAB);
if (section) {
assert(section->sh_entsize == sizeof(Elf_Sym));
symbolTableData = new Mapping(fd, buf.st_size, section->sh_offset,
section->sh_size);
if (symbolTableData->mapping) {
symbolTable = section;
}
}
section = findSectionHeader(SHT_STRTAB);
if (section) {
stringTableData = new Mapping(fd, buf.st_size, section->sh_offset,
section->sh_size);
if (stringTableData->mapping) {
stringTable = section;
}
}
}
close(fd);
return;
}
// Find the section header of a specified type in the section headers table.
const Elf_Shdr *findSectionHeader(Elf_Word sectionType) {
if (sectionHeaders && sectionHeaders->mapping) {
const ArrayRef<Elf_Shdr> headers = sectionHeaders->data<Elf_Shdr>();
for (size_t idx = 0; idx < elfHeader.e_shnum; idx++) {
if (idx == elfHeader.e_shstrndx) {
continue;
}
auto header = &headers[idx];
if (header->sh_type == sectionType) {
if (header->sh_entsize > 0 && header->sh_size % header->sh_entsize) {
fprintf(stderr,
"section size is not a multiple of entrysize (%ld/%ld)\n",
header->sh_size, header->sh_entsize);
return nullptr;
}
return header;
}
}
}
return nullptr;
}
};
static swift::Lazy<StaticBinaryELF> TheBinary;
int
swift::lookupSymbol(const void *address, SymbolInfo *info) {
// The pointers returned point into the mmap()'d binary so keep the
// object once instantiated.
auto &binary = TheBinary.get();
info->fileName = binary.getPathName();
info->baseAddress = binary.getSectionLoadAddress(address);
auto symbol = binary.findSymbol(address);
if (symbol != nullptr) {
info->symbolAddress = reinterpret_cast<void *>(symbol->st_value);
info->symbolName = binary.symbolName(symbol);
} else {
info->symbolAddress = nullptr;
info->symbolName = nullptr;
}
return 1;
}
#endif // defined(__ELF__) && defined(__linux__)
<commit_msg>[runtime] StaticBinaryELF review fixes<commit_after>//===-- StaticBinaryELF.cpp -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Parse a static ELF binary to implement lookupSymbol() address lookup.
//
//===----------------------------------------------------------------------===//
#if defined(__ELF__) && defined(__linux__)
#include "ImageInspection.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "swift/Basic/Lazy.h"
#include <cassert>
#include <string>
#include <vector>
#include <elf.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
using namespace llvm;
#ifdef __LP64__
#define ELFCLASS ELFCLASS64
typedef Elf64_Ehdr Elf_Ehdr;
typedef Elf64_Shdr Elf_Shdr;
typedef Elf64_Phdr Elf_Phdr;
typedef Elf64_Addr Elf_Addr;
typedef Elf64_Word Elf_Word;
typedef Elf64_Sym Elf_Sym;
typedef Elf64_Section Elf_Section;
#define ELF_ST_TYPE(x) ELF64_ST_TYPE(x)
#else
#define ELFCLASS ELFCLASS32
typedef Elf32_Ehdr Elf_Ehdr;
typedef Elf32_Shdr Elf_Shdr;
typedef Elf32_Phdr Elf_Phdr;
typedef Elf32_Addr Elf_Addr;
typedef Elf32_Word Elf_Word;
typedef Elf32_Sym Elf_Sym;
typedef Elf32_Section Elf_Section;
#define ELF_ST_TYPE(x) ELF32_ST_TYPE(x)
#endif
extern const Elf_Ehdr elfHeader asm("__ehdr_start");
class StaticBinaryELF {
private:
// mmap a section of a file that might not be page aligned.
class Mapping {
public:
void *mapping;
size_t mapLength;
off_t diff;
Mapping(int fd, size_t fileSize, off_t offset, size_t length) {
if (fd < 0 || offset + length > fileSize) {
mapping = nullptr;
mapLength = 0;
diff = 0;
return;
}
long pageSize = sysconf(_SC_PAGESIZE);
long pageMask = ~(pageSize - 1);
off_t alignedOffset = offset & pageMask;
diff = (offset - alignedOffset);
mapLength = diff + length;
mapping = mmap(nullptr, mapLength, PROT_READ, MAP_PRIVATE, fd,
alignedOffset);
if (mapping == MAP_FAILED) {
mapping = nullptr;
mapLength = 0;
diff = 0;
}
}
template<typename T>
ArrayRef<T> data() {
size_t elements = (mapLength - diff) / sizeof(T);
const T *data = reinterpret_cast<T *>(reinterpret_cast<char *>(mapping)
+ diff);
return ArrayRef<T>(data, elements);
}
~Mapping() {
if (mapping && mapLength > 0) {
munmap(mapping, mapLength);
}
}
};
string fullPathName;
const Elf_Phdr *programHeaders = nullptr;
Optional<Mapping> symbolTable;
Optional<Mapping> stringTable;
public:
StaticBinaryELF() {
getExecutablePathName();
programHeaders = reinterpret_cast<const Elf_Phdr *>(getauxval(AT_PHDR));
if (programHeaders == nullptr) {
return;
}
// If a interpreter is set in the program headers then this is a
// dynamic executable and therefore not valid.
for (size_t idx = 0; idx < elfHeader.e_phnum; idx++) {
if (programHeaders[idx].p_type == PT_INTERP) {
programHeaders = nullptr;
return;
}
}
if (!fullPathName.empty()) {
mmapExecutable();
}
}
const char *getPathName() {
return fullPathName.empty() ? nullptr : fullPathName.c_str();
}
void *getSectionLoadAddress(const void *addr) {
if (programHeaders) {
auto searchAddr = reinterpret_cast<Elf_Addr>(addr);
for (size_t idx = 0; idx < elfHeader.e_phnum; idx++) {
auto header = &programHeaders[idx];
if (header->p_type == PT_LOAD && searchAddr >= header->p_vaddr
&& searchAddr <= (header->p_vaddr + header->p_memsz)) {
return reinterpret_cast<void *>(header->p_vaddr);
}
}
}
return nullptr;
}
// Lookup a function symbol by address.
const Elf_Sym *findSymbol(const void *addr) {
if (symbolTable.hasValue()) {
auto searchAddr = reinterpret_cast<Elf_Addr>(addr);
auto symbols = symbolTable->data<Elf_Sym>();
for (size_t idx = 0; idx < symbols.size(); idx++) {
auto symbol = &symbols[idx];
if (ELF_ST_TYPE(symbol->st_info) == STT_FUNC
&& searchAddr >= symbol->st_value
&& searchAddr < (symbol->st_value + symbol->st_size)) {
return symbol;
}
}
}
return nullptr;
}
const char *symbolName(const Elf_Sym *symbol) {
if (stringTable.hasValue()) {
auto strings = stringTable->data<char>();
if (symbol->st_name < strings.size()) {
return &strings[symbol->st_name];
}
}
return nullptr;
}
private:
// This is Linux specific - find the full path of the executable
// by looking in /proc/self/maps for a mapping holding the current
// address space. For a static binary it should only be mapping one
// file anyway. Dont use /proc/self/exe as the symlink will be removed
// if the main thread terminates - see proc(5).
void getExecutablePathName() {
uintptr_t address = (uintptr_t)&elfHeader;
FILE *fp = fopen("/proc/self/maps", "r");
if (!fp) {
perror("Unable to open /proc/self/maps");
} else {
char *line = nullptr;
size_t size = 0;
// Format is: addrLo-addrHi perms offset dev inode pathname.
// If the executable has been deleted the last column will be '(deleted)'.
StringRef deleted = StringRef("(deleted)");
while(getdelim(&line, &size, '\n', fp) != -1) {
StringRef entry = StringRef(line).rsplit('\n').first;
auto addrRange = entry.split(' ').first.split('-');
unsigned long long low = strtoull(addrRange.first.str().c_str(),
nullptr, 16);
if (low == 0 || low > UINTPTR_MAX || address < (uintptr_t)low) {
continue;
}
unsigned long long high = strtoull(addrRange.second.str().c_str(),
nullptr, 16);
if (high == 0 || high > UINTPTR_MAX || address > (uintptr_t)high) {
continue;
}
auto fname = entry.split('/').second;
if (fname.empty() || fname.endswith(deleted)) {
continue;
}
fullPathName = "/" + fname.str();
break;
}
if (line) {
free(line);
}
fclose(fp);
}
}
// Parse the ELF binary using mmap for the section headers, symbol table and
// string table.
void mmapExecutable() {
struct stat buf;
int fd = open(fullPathName.c_str(), O_RDONLY);
if (fd < 0) {
return;
}
if (fstat(fd, &buf) != 0) {
close(fd);
return;
}
// Map in the section headers.
size_t sectionHeadersSize = (elfHeader.e_shentsize * elfHeader.e_shnum);
Mapping sectionHeaders = Mapping(fd, buf.st_size, elfHeader.e_shoff,
sectionHeadersSize);
if (sectionHeaders.mapping) {
auto headers = sectionHeaders.data<Elf_Shdr>();
auto section = findSectionHeader(headers, SHT_SYMTAB);
if (section) {
assert(section->sh_entsize == sizeof(Elf_Sym));
symbolTable.emplace(fd, buf.st_size, section->sh_offset,
section->sh_size);
if (symbolTable->mapping == nullptr) {
symbolTable.reset();
}
}
section = findSectionHeader(headers, SHT_STRTAB);
if (section) {
stringTable.emplace(fd, buf.st_size, section->sh_offset,
section->sh_size);
if (stringTable->mapping == nullptr) {
stringTable.reset();
}
}
}
close(fd);
return;
}
// Find the section header of a specified type in the section headers table.
const Elf_Shdr *findSectionHeader(ArrayRef<Elf_Shdr> headers,
Elf_Word sectionType) {
assert(elfHeader.e_shnum == headers.size());
for (size_t idx = 0; idx < headers.size(); idx++) {
if (idx == elfHeader.e_shstrndx) {
continue;
}
auto header = &headers[idx];
if (header->sh_type == sectionType) {
if (header->sh_entsize > 0 && header->sh_size % header->sh_entsize) {
fprintf(stderr,
"section size is not a multiple of entrysize (%ld/%ld)\n",
header->sh_size, header->sh_entsize);
return nullptr;
}
return header;
}
}
return nullptr;
}
};
static swift::Lazy<StaticBinaryELF> TheBinary;
int
swift::lookupSymbol(const void *address, SymbolInfo *info) {
// The pointers returned point into the mmap()'d binary so keep the
// object once instantiated.
auto &binary = TheBinary.get();
info->fileName = binary.getPathName();
info->baseAddress = binary.getSectionLoadAddress(address);
auto symbol = binary.findSymbol(address);
if (symbol != nullptr) {
info->symbolAddress = reinterpret_cast<void *>(symbol->st_value);
info->symbolName = binary.symbolName(symbol);
} else {
info->symbolAddress = nullptr;
info->symbolName = nullptr;
}
return 1;
}
#endif // defined(__ELF__) && defined(__linux__)
<|endoftext|>
|
<commit_before>/*
* vending_machine.hpp
*
* Created on: Nov 15, 2016
* Author: zmij
*/
#ifndef AFSM_EXAMPLES_VENDING_MACHINE_HPP_
#define AFSM_EXAMPLES_VENDING_MACHINE_HPP_
#include <afsm/fsm.hpp>
#include <map>
#include <algorithm>
#include <numeric>
namespace vending {
namespace events {
struct power_on {};
struct power_off {};
struct start_maintenance {
int secret;
};
struct end_maintenance {};
struct withdraw_money {};
struct load_goods {
::std::size_t p_no;
int amount;
};
struct load_done {};
struct set_price {
::std::size_t p_no;
float price;
};
struct money {
float amount;
};
struct select_item {
::std::size_t p_no;
};
} /* namespace events */
struct goods_entry {
int amount;
float price;
};
using goods_storage = ::std::map<::std::size_t, goods_entry>;
struct vending_def : ::afsm::def::state_machine<vending_def> {
using vending_fsm = ::afsm::state_machine<vending_def>;
using history = ::afsm::def::tags::has_history;
//@{
/** @name Guards */
struct is_empty {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const&) const
{
return root_machine(fsm).is_empty();
}
};
struct prices_correct {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const&) const
{
return root_machine(fsm).prices_correct();
}
};
struct goods_exist {
template < typename FSM, typename State, typename Event >
bool
operator()(FSM const& fsm, State const&, Event const& evt) const
{
return root_machine(fsm).goods_exist(evt.p_no);
}
};
//@}
struct off : state<off> {};
struct on : state_machine<on, history> {
// A type alias for actual state machine, that will be passed to actions
// and guards, just for demonstration purposes
using on_fsm = ::afsm::inner_state_machine<on, vending_fsm>;
// Forward declaration
struct maintenance;
//@{
/** @name Guards */
struct check_secret {
template < typename State >
bool
operator()(on_fsm const& fsm, State const&, events::start_maintenance const& evt) const
{
return root_machine(fsm).secret == evt.secret;
}
};
//@}
//@{
/** @name Actions */
//@}
//@{
/** @name Substates */
struct maintenance : state_machine<maintenance> {
//@{
/** @name Guards */
struct check_amount {
template < typename FSM, typename State >
bool
operator()(FSM const&, State const&, events::load_goods const& goods) const
{
return goods.amount >= 0;
}
};
struct check_price {
template < typename FSM, typename State >
bool
operator()(FSM const&, State const&, events::set_price const& price) const
{
return price.price >= 0;
}
};
//@}
//@{
struct set_price {
template < typename FSM, typename SourceState, typename TargetState >
void
operator()(events::set_price&& price, FSM& fsm, SourceState&, TargetState&) const
{
root_machine(fsm).set_price(price.p_no, price.price);
}
};
//@}
using internal_transitions = transition_table <
/* Event Action Guard */
in< events::set_price, set_price, and_< goods_exist, check_price > >,
in< events::withdraw_money, none, none >
>;
struct idle : state<idle> {};
struct loading : state<loading> {
template < typename FSM >
void
on_enter(events::load_goods&& goods, FSM& fsm) const
{
root_machine(fsm).add_goods(::std::move(goods));
}
};
using initial_state = idle;
using transitions = transition_table <
/* State Event Next Action Guard */
tr< idle, events::load_goods, loading, none, check_amount >,
tr< loading, events::load_done, idle, none, none >
>;
};
struct serving : state_machine<serving, history> {
//@{
/** @name Guards */
struct enough_money {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const& state, events::select_item const& item) const
{
return root_machine(fsm).get_price(item.p_no) <= state.balance;
}
};
struct dispense {
template < typename FSM, typename SourceState, typename TargetState >
void
operator()(events::select_item&& item, FSM& fsm, SourceState&, TargetState&) const
{
root_machine(fsm).dispense_product(item.p_no);
}
};
//@}
//@{
/** @name Substates */
struct idle : state<idle> {};
struct active : state<active> {
template < typename FSM >
void
on_enter(events::money&& money, FSM&)
{
balance += money.amount;
}
template < typename FSM >
void
on_exit(events::select_item&& item, FSM& fsm)
{
// Subtract balance
auto& root = root_machine(fsm);
balance -= root.get_price(item.p_no);
if (balance > 0) {
// Give change
}
}
float balance{0};
};
//@}
using initial_state = idle;
using transitions = transition_table<
/* Start Event Next Action Guard */
tr< idle, events::money, active, none, none >,
tr< active, events::money, active, none, none >,
tr< active, events::select_item, idle, dispense, and_< goods_exist, enough_money > >
>;
};
struct out_of_service : state<out_of_service> {};
//@}
using initial_state = serving;
using transitions = transition_table<
/* Start Event Next Action Guard */
/* Default transitions */
/*-----------------+---------------------------+---------------+-------+--------------------------------*/
tr< serving, none, out_of_service, none, is_empty >,
tr< out_of_service, none, serving, none, not_<is_empty> >,
/*-----------------+---------------------------+---------------+-------+--------------------------------*/
/* Normal transitions */
tr< serving, events::start_maintenance, maintenance, none, check_secret >,
tr< out_of_service, events::start_maintenance, maintenance, none, check_secret >,
tr< maintenance, events::end_maintenance, serving, none, or_< is_empty, prices_correct > >
>;
};
using initial_state = off;
using transitions = transition_table<
/* Start Event Next */
tr< off, events::power_on, on >,
tr< on, events::power_off, off >
>;
static const int factory_code = 2147483647;
vending_def()
: secret{factory_code}, goods{}, balance{0} {}
vending_def(int code)
: secret{code}, goods{}, balance{0} {}
vending_def(goods_storage&& goods)
: secret{factory_code}, goods{goods}, balance{0} {}
vending_def(int code, goods_storage&& goods)
: secret{code}, goods{::std::move(goods)}, balance{0} {}
bool
is_empty() const
{
return count() == 0;
}
::std::size_t
count() const
{
return ::std::accumulate(
goods.begin(), goods.end(), 0ul,
[](::std::size_t cnt, goods_storage::value_type const& i)
{
return cnt + i.second.amount;
}
);
}
void
add_goods(events::load_goods&& entry)
{
auto f = goods.find(entry.p_no);
if (f == goods.end()) {
goods.emplace(entry.p_no, goods_entry{entry.amount, 0});
} else {
f->second.amount += entry.amount;
}
rebind().process_event(events::load_done{});
}
bool
prices_correct() const
{
auto f = ::std::find_if(goods.begin(), goods.end(),
[](goods_storage::value_type const& i)
{
return i.second.price <= 0;
});
return f == goods.end();
}
bool
goods_exist(::std::size_t p_no) const
{
auto f = goods.find(p_no);
return f != goods.end();
}
void
set_price(::std::size_t p_no, float price)
{
auto f = goods.find(p_no);
if (f != goods.end()) {
f->second.price = price;
}
}
float
get_price(::std::size_t p_no) const
{
auto f = goods.find(p_no);
if (f != goods.end()) {
return f->second.price;
}
return 0;
}
void
dispense_product(::std::size_t p_no)
{
auto f = goods.find(p_no);
if (f != goods.end() && f->second.amount > 0) {
--f->second.amount;
balance += f->second.price;
}
}
void
add_balance(float amount)
{
balance += amount;
}
void
clear_balance()
{ balance = 0; }
vending_fsm&
rebind()
{ return static_cast<vending_fsm&>(*this); }
vending_fsm const&
rebind() const
{ return static_cast<vending_fsm const&>(*this); }
int secret;
goods_storage goods;
float balance;
};
using vending_machine = ::afsm::state_machine<vending_def>;
} /* namespace vending */
#endif /* AFSM_EXAMPLES_VENDING_MACHINE_HPP_ */
<commit_msg>Fix vending machine example documentation issue<commit_after>/*
* vending_machine.hpp
*
* Created on: Nov 15, 2016
* Author: zmij
*/
#ifndef AFSM_EXAMPLES_VENDING_MACHINE_HPP_
#define AFSM_EXAMPLES_VENDING_MACHINE_HPP_
#include <afsm/fsm.hpp>
#include <map>
#include <algorithm>
#include <numeric>
namespace vending {
namespace events {
struct power_on {};
struct power_off {};
struct start_maintenance {
int secret;
};
struct end_maintenance {};
struct withdraw_money {};
struct load_goods {
::std::size_t p_no;
int amount;
};
struct load_done {};
struct set_price {
::std::size_t p_no;
float price;
};
struct money {
float amount;
};
struct select_item {
::std::size_t p_no;
};
} /* namespace events */
struct goods_entry {
int amount;
float price;
};
using goods_storage = ::std::map<::std::size_t, goods_entry>;
struct vending_def : ::afsm::def::state_machine<vending_def> {
using vending_fsm = ::afsm::state_machine<vending_def>;
using history = ::afsm::def::tags::has_history;
//@{
/** @name Guards */
struct is_empty {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const&) const
{
return root_machine(fsm).is_empty();
}
};
struct prices_correct {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const&) const
{
return root_machine(fsm).prices_correct();
}
};
struct goods_exist {
template < typename FSM, typename State, typename Event >
bool
operator()(FSM const& fsm, State const&, Event const& evt) const
{
return root_machine(fsm).goods_exist(evt.p_no);
}
};
//@}
struct off : state<off> {};
struct on : state_machine<on, history> {
// A type alias for actual state machine, that will be passed to actions
// and guards, just for demonstration purposes
using on_fsm = ::afsm::inner_state_machine<on, vending_fsm>;
// Forward declaration
struct maintenance;
//@{
/** @name Guards */
struct check_secret {
template < typename State >
bool
operator()(on_fsm const& fsm, State const&, events::start_maintenance const& evt) const
{
return root_machine(fsm).secret == evt.secret;
}
};
//@}
//@{
/** @name Actions */
//@}
//@{
/** @name Substates */
struct maintenance : state_machine<maintenance> {
//@{
/** @name Guards */
struct check_amount {
template < typename FSM, typename State >
bool
operator()(FSM const&, State const&, events::load_goods const& goods) const
{
return goods.amount >= 0;
}
};
struct check_price {
template < typename FSM, typename State >
bool
operator()(FSM const&, State const&, events::set_price const& price) const
{
return price.price >= 0;
}
};
//@}
//@{
struct set_price {
template < typename FSM, typename SourceState, typename TargetState >
void
operator()(events::set_price&& price, FSM& fsm, SourceState&, TargetState&) const
{
root_machine(fsm).set_price(price.p_no, price.price);
}
};
//@}
using internal_transitions = transition_table <
/* Event Action Guard */
in< events::set_price, set_price, and_< goods_exist, check_price > >,
in< events::withdraw_money, none, none >
>;
struct idle : state<idle> {};
struct loading : state<loading> {
template < typename FSM >
void
on_enter(events::load_goods&& goods, FSM& fsm) const
{
root_machine(fsm).add_goods(::std::move(goods));
}
};
using initial_state = idle;
using transitions = transition_table <
/* State Event Next Action Guard */
tr< idle, events::load_goods, loading, none, check_amount >,
tr< loading, events::load_done, idle, none, none >
>;
};
struct serving : state_machine<serving, history> {
//@{
/** @name Guards */
struct enough_money {
template < typename FSM, typename State >
bool
operator()(FSM const& fsm, State const& state, events::select_item const& item) const
{
return root_machine(fsm).get_price(item.p_no) <= state.balance;
}
};
//@}
//@{
/** @name Actions */
struct dispense {
template < typename FSM, typename SourceState, typename TargetState >
void
operator()(events::select_item&& item, FSM& fsm, SourceState&, TargetState&) const
{
root_machine(fsm).dispense_product(item.p_no);
}
};
//@}
//@{
/** @name Substates */
struct idle : state<idle> {};
struct active : state<active> {
template < typename FSM >
void
on_enter(events::money&& money, FSM&)
{
balance += money.amount;
}
template < typename FSM >
void
on_exit(events::select_item&& item, FSM& fsm)
{
// Subtract balance
auto& root = root_machine(fsm);
balance -= root.get_price(item.p_no);
if (balance > 0) {
// Give change
}
}
float balance{0};
};
//@}
using initial_state = idle;
using transitions = transition_table<
/* Start Event Next Action Guard */
tr< idle, events::money, active, none, none >,
tr< active, events::money, active, none, none >,
tr< active, events::select_item, idle, dispense, and_< goods_exist, enough_money > >
>;
};
struct out_of_service : state<out_of_service> {};
//@}
using initial_state = serving;
using transitions = transition_table<
/* Start Event Next Action Guard */
/* Default transitions */
/*-----------------+---------------------------+---------------+-------+--------------------------------*/
tr< serving, none, out_of_service, none, is_empty >,
tr< out_of_service, none, serving, none, not_<is_empty> >,
/*-----------------+---------------------------+---------------+-------+--------------------------------*/
/* Normal transitions */
tr< serving, events::start_maintenance, maintenance, none, check_secret >,
tr< out_of_service, events::start_maintenance, maintenance, none, check_secret >,
tr< maintenance, events::end_maintenance, serving, none, or_< is_empty, prices_correct > >
>;
};
using initial_state = off;
using transitions = transition_table<
/* Start Event Next */
tr< off, events::power_on, on >,
tr< on, events::power_off, off >
>;
static const int factory_code = 2147483647;
vending_def()
: secret{factory_code}, goods{}, balance{0} {}
vending_def(int code)
: secret{code}, goods{}, balance{0} {}
vending_def(goods_storage&& goods)
: secret{factory_code}, goods{goods}, balance{0} {}
vending_def(int code, goods_storage&& goods)
: secret{code}, goods{::std::move(goods)}, balance{0} {}
bool
is_empty() const
{
return count() == 0;
}
::std::size_t
count() const
{
return ::std::accumulate(
goods.begin(), goods.end(), 0ul,
[](::std::size_t cnt, goods_storage::value_type const& i)
{
return cnt + i.second.amount;
}
);
}
void
add_goods(events::load_goods&& entry)
{
auto f = goods.find(entry.p_no);
if (f == goods.end()) {
goods.emplace(entry.p_no, goods_entry{entry.amount, 0});
} else {
f->second.amount += entry.amount;
}
rebind().process_event(events::load_done{});
}
bool
prices_correct() const
{
auto f = ::std::find_if(goods.begin(), goods.end(),
[](goods_storage::value_type const& i)
{
return i.second.price <= 0;
});
return f == goods.end();
}
bool
goods_exist(::std::size_t p_no) const
{
auto f = goods.find(p_no);
return f != goods.end();
}
void
set_price(::std::size_t p_no, float price)
{
auto f = goods.find(p_no);
if (f != goods.end()) {
f->second.price = price;
}
}
float
get_price(::std::size_t p_no) const
{
auto f = goods.find(p_no);
if (f != goods.end()) {
return f->second.price;
}
return 0;
}
void
dispense_product(::std::size_t p_no)
{
auto f = goods.find(p_no);
if (f != goods.end() && f->second.amount > 0) {
--f->second.amount;
balance += f->second.price;
}
}
void
add_balance(float amount)
{
balance += amount;
}
void
clear_balance()
{ balance = 0; }
vending_fsm&
rebind()
{ return static_cast<vending_fsm&>(*this); }
vending_fsm const&
rebind() const
{ return static_cast<vending_fsm const&>(*this); }
int secret;
goods_storage goods;
float balance;
};
using vending_machine = ::afsm::state_machine<vending_def>;
} /* namespace vending */
#endif /* AFSM_EXAMPLES_VENDING_MACHINE_HPP_ */
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.